﻿String.prototype.trim = function(value) {
    if (!value) return ''
    return value.replace(/^\s+/, '').replace(/\s+$/, '')
}

if (typeof jQuery == 'undefined') {  
   alert('Error: jQuery v1.4.2 has not been loaded!');  
} else {
    var Page_Validators;

    // gets localized resource name
    function getRes(name) {
        if (typeof (AppResources) == "undefined")
            throw Error("Local resources are not loaded.");
        var res = AppResources[name];
        if (!res) res = name + "_NOT_FOUND_RESOURCE";
        return res;
    }

    (function($) {
        /* Translates Spanish symbols to English */
        $.convertToEnglishLetters = function(str, replaceSpace, replaceSlash) {
            if (!str) return str;
            str = str.trim().toLowerCase()
                    .replace('á', 'a')
                    .replace('à', 'a')
                    .replace('é', 'e')
                    .replace('è', 'e')
                    .replace('í', 'i')
                    .replace('ï', 'i')
                    .replace('ó', 'o')
                    .replace('ú', 'u')
                    .replace('ü', 'u')
                    .replace('ç', 'c')
                    .replace('ñ', 'n')
            //.replace('¿', '/')
            //.replace('¡', '1')
                    .replace("´", "'");
            if (replaceSpace)
                str = str.replace(/\s+/g, '_')
            if (replaceSlash)
                str = str.replace(/\//g, '!')
            return str
        }

        $.showNextPropertyImage = function(imgId) {
            var img = $('#' + imgId);
            if (img.size() == 0) return;

            var propId = img.attr('propId');
            var imgIdx = img.attr('imgIdx');
            if (imgId && propId && imgIdx) {
                jQuery.ajax({
                    url: '/Services.ashx',
                    dataType: "json",
                    data: { action: "GetNextPropertyImage", propertyId: propId, showedImageIdx: imgIdx },
                    success: function(data) {
                        if (data) {
                            img.attr('src', data.fileName);
                            img.attr('imgIdx', data.nextIdx);
                        }
                    }
                });
            }
        }

        /* Select all checkboxes with certain class name */
        $.selectAllCheckboxes = function(className) {
            $('.' + className + ':not(:checked)').attr('checked', 'checked');
        }

        /* Unselect all checkboxes with certain class name */
        $.unSelectAllCheckboxes = function(className) {
            $('.' + className + ':checked').removeAttr('checked');
        }

        /* Check whether there is at least one check box has been checked */
        $.checkSelectedCheckboxes = function(className) {
            return ($('.' + className + ':checked').size() > 0);
        }

        /* Unselect all checkboxes with certain class name */
        $.checkAspSelectedCheckboxes = function(className) {
            return ($(':checked', '.' + className).size() > 0);
        }

        $.lazyLoadProperty = function(str, url, sucessCallback, errorCallback) {
            if (eval('typeof (' + str + ') == "undefined"')) {
                jQuery.ajax({
                    url: url,
                    dataType: "script",
                    success: sucessCallback,
                    error: errorCallback
                });
                return false;
            }
            return true;
        }

        /* Rounds certain boxes */
        $.fn.roundbox = function(settings) {
            return $(this).each(function() {
                var e = $(this);
                if (!e.attr('hasRound')) {
                    var rb = new RoundBox(this, $(this).attr('href'), settings);
                    $.decorateRoundboxes(rb);
                    this._roundbox = rb;
                    e.attr('hasRound', true);
                }
            });
        }

        /* gets the instance of the class RoundBox if exists */
        $.fn.get_roundbox = function() {
            return this[0]._roundbox;
        }

        /* custom rounds certain boxes */
        $.fn.customRoundbox = function(destinationId, settings) {
            return $(this).each(function() {
                var e = $(this);
                e.attr("rel", "roundbox");
                e.attr("href", destinationId);
                e.roundbox(settings);
            });
        }

        /* makes confirm messages */
        $.fn.makeConfirmMessage = function() {
            //alert('makeConfirmMessage');
            return $(this).each(function() {
                var e = $(this);
                if (!e.attr('hasConfirmMessage')) {
                    var message = e.attr('confirmMessage');
                    var onclick;
                    if (e.attr('href')) {
                        var str = e.attr('href');
                        if (str.indexOf('javascript:') == -1) {
                            if (str != '#')
                                onclick = function() { window.location.href = str };
                        }
                        else {
                            var exp = str.replace('javascript:', '');
                            onclick = function() { eval(exp) };
                        }
                        e.attr('href', '#');
                        e.click(function() { return false });
                    }
                    else {
                        onclick = e.attr('onclick');
                        e.unbind('click');
                        e.attr('onclick', 'return false');
                        if (!onclick)
                            onclick = function() {
                                //e.attr('cancelRoundbox', true); 
                                e.trigger('click', false);

                            };
                    }
                    if (message) {
                        e.click(function() {
                            $.confirmMessage(message, onclick);
                        });
                    }
                    e.attr('hasConfirmMessage', true)
                }
            });
        }

        /* Shows confirmation message */
        var _confirmMessage;
        $.confirmMessage = function(message, okHandler) {
            if (!_confirmMessage) {
                var pnl = jQuery('<div id="confirm_panel" >\
                    <table class="pad" style="width: 100%" >\
                        <tr>\
                            <td>\
                                <h4>' + getRes("Common_DeleteQuestion") + '</h4>\
                                <span id="confirm_message" class="small">MESSAGE_HERE</span>\
                                <div class="buttons fl">\
                                <input type="button" id="yesButton" value="' + getRes("BoolTypeYes") + '" />\
                                <input type="button" id="noButton" value="' + getRes("BoolTypeNo") + '" />\
                            </div></td>\
                        </tr>\
                    </table>\
                </div>')
                pnl.appendTo($('form'));
                var a = jQuery('<a href="#confirm_panel" rel="roundbox" />')
                $('#noButton', pnl).click(function() {
                    _confirmMessage.link.get_roundbox().close();
                });
                _confirmMessage = {
                    btnYes: $('#yesButton', pnl),
                    pnlMessage: pnl,
                    link: a
                }
                a.roundbox({
                    body_style: { 'width': '250px' },
                    footer_style: { 'border-style': 'none', 'background-color': 'white' },
                    close_button_style: { 'display': 'none' }
                });
            }
            _confirmMessage.btnYes.unbind('click');
            _confirmMessage.btnYes.click(function(args) {
                //_confirmMessage.link.get_roundbox().close();
                okHandler();
                _confirmMessage.link.get_roundbox().close();
                // add invokation of progres form
            });
            _confirmMessage.link.get_roundbox()._settings.content_style = {
                'display': (message.trim() == '' ? 'none' : '')
            };
            jQuery('#confirm_message', _confirmMessage.pnlMessage).html(message);
            _confirmMessage.link.trigger('click', false);
        }

        /* Makes dynamic text visible when no value */
        $.fn.dynamicEmptyText = function() {
            return $(this).each(function() {
                var item = $(this);
                if (item.attr('dynamicEmptyText') && !item.attr('dynamicEmptyTextInited')) {
                    item.bind('focus', function(isNotEmpty) {
                        var v = item.val();
                        var d = item.attr('dynamicEmptyText');
                        if (v == d || (v != '' && isNotEmpty))
                            item.css('font-style', 'normal')
                                .css('color', '#000000')
                        if (v == d) item.val('');
                    });
                    item.bind('blur', function() {
                        var v = item.val();
                        if (v == '' || v == item.attr('dynamicEmptyText'))
                            item.css('font-style', 'italic')
                                .css('color', '#999999')
                                .val(item.attr('dynamicEmptyText'));
                    });
                    if ((item.val() == '' || item.val() == item.attr('dynamicEmptyText'))
                        && (!document.activeElement || document.activeElement.id != item[0].id))
                        item.css('font-style', 'italic')
                            .css('color', '#999999')
                            .val(item.attr('dynamicEmptyText'));
                    item.attr('dynamicEmptyTextInited', true);
                }
            });
        }


        /* Makes special tooltip */
        $.fn.makeTooltip = function() {
            return $(this).each(function() {
                var item = $(this);
                if (!item.attr('isTitled')) {
                    var title = item.attr('title');
                    if (!title) {
                        title = item.attr('titleContent');
                        if (title) {
                            var titleElem = $(title);
                            if (titleElem) {
                                title = titleElem.html();
                                titleElem.remove();
                            }
                        }
                    }
                    if (title)
                        item.bind('mouseover', function() { tooltip.show(title); })
                            .bind('mouseout', function() { tooltip.hide(); })
                            .attr('isTitled', true)
                            .removeAttr('title');
                }
            });
        }

        /* Determines if there is not empty value */
        $.notEmptyAccepted = function(source, args) {
            args.IsValid = (ValidatorTrim(args.Value).length > 0)
        }

        /* Determines if there is at least one language selected */
        $.languageAccepted = function(source, args) {
            var p = '#' + $('#' + $(source).attr('controltovalidate')).attr('chkParent');
            args.IsValid = ($(':checked', p).size() > 0);
        }

        /* Determines if there is at least one language selected */
        $.locationAccepted = function(source, args) {
            var cb = $('#' + $(source).attr('controltovalidate'))
            args.IsValid = ($(cb).attr("settlementId") > 0);
        }

        /* Determines if the location is selected */
        $.locationSetValid = function(source) {
            var self = $(source);
            if (self.size() > 0) {
                var oldOnChange = self.attr("onchange");
                var onChange = function() {
                    self.attr("settlementId", 1);
                };

                self.removeAttr("onchange")
                    .unbind('change')
                    .change(onChange)
                    .change(function(evt) {
                        oldOnChange(evt);
                    });
            }
        }

        /* show logon content */
        $.showLoginContent = function() {
            if ($.url.param("ReturnUrl") && $.url.param("action") != "logout") {
                var a = $("a[href$=#signin]");
                if (!a)
                    throw Error('Canot find link which opens logon form!');
                else
                    a.trigger("click");
            }
        }

        /* configures cental ajax loader corners */
        $.configureCentralAjaxLoader = function() {
            var settings = {
                tl: { radius: 5 },
                tr: { radius: 5 },
                bl: { radius: 5 },
                br: { radius: 5 },
                antiAlias: true
            };
            $(".central_ajax_loader").each(function(idx, item) {
                curvyCorners(settings, item);
            });
        }

        // makes sortable all th with anchor in the table with class sortable
        $.makeGridSortableSpace = function() {
            $("th:has(a)", ".sortable")
                .live('click', function(event) {
                    window.location = $("a", $(this)).attr('href');
                    event.preventDefault();
                });
        }

        // change style of validator
        $.decorateValidator = function(vldtr, ctrToValidate, isValid) {
            if (!isValid) {
                if (vldtr.attr('error'))
                    vldtr.attr('error')(vldtr, elem);
                if (ctrToValidate) {
                    ctrToValidate.addClass("error");
                    _notValidated[ctrToValidate[0].id] = true;
                }
            }
            else {
                if (vldtr.attr('success'))
                    vldtr.attr('success')(vldtr, elem);
                if (ctrToValidate && ctrToValidate.size() > 0 && !_notValidated[ctrToValidate[0].id])
                    ctrToValidate.removeClass("error");
            }
        }

        var _isJustValidated = false;
        // shows validation error message 
        $.showValidatorsError = function() {
            if (!_isJustValidated) {
                _isJustValidated = true;
                jQuery.pnotify({
                    pnotify_hide: true,
                    pnotify_text: getRes("err_Common_ClientValidationFailed"),
                    pnotify_title: null,
                    pnotify_type: "error",
                    pnotify_after_close: function(pnotify) { _isJustValidated = false }
                });
            }
        }

        $.showMessage = function(message, type, hide) {
            jQuery.pnotify({
                pnotify_hide: hide,
                pnotify_text: message,
                pnotify_title: null,
                pnotify_type: type
            });
        }

        // restore settings of updateprogresses
        $.restoreUpdateProgresses = function() {
            if (_updateProgresses) {
                for (var i = 0; i < _updateProgresses.length; i++)
                    if (_updateProgresses[i].elem)
                    _updateProgresses[i].elem.set_displayAfter(_updateProgresses[i].displayAfter);
                _updateProgresses = null;
            }
        }

        var _updateProgresses = null;

        //set which update progress should be shown
        $.setUpdateProgressesEnabled = function(sender) {
            var panelId = sender._postBackSettings.panelID.replace(/\$/g, '_')
            //var panelId = sender._postBackSettings.panelsToUpdate[0].replace(/\$/g, '_'); // ajaxControltoolkit
            panelId = panelId.substr(0, panelId.indexOf('|', 0));
            var ctrs = Sys.Application.getComponents();

            // check if there was any aborted request (_updateProgresses won't be null)
            $.restoreUpdateProgresses();

            //determines which updateprogress will be shown
            _updateProgresses = new Array();
            var _updateProgress;
            for (att in ctrs)
                if (ctrs[att] instanceof Sys.UI._UpdateProgress) {
                Array.add(_updateProgresses,
                        { elem: ctrs[att], displayAfter: ctrs[att].get_displayAfter() });
                if (ctrs[att].get_associatedUpdatePanelId() == panelId)
                    _updateProgress = ctrs[att];
            }
            if (_updateProgress != null && _updateProgresses.length > 1)
                for (var i = 0; i < _updateProgresses.length; i++)
                if (_updateProgresses[i].elem != _updateProgress) {
                _updateProgresses[i].elem.set_displayAfter(100000);
                if (_updateProgresses[i].elem._timerCookie)
                    clearTimeout(_updateProgresses[i].elem._timerCookie);
            }
        }


















        /* changes style of not validated controls */
        $.ValidatorUpdateDisplay = function(val) {
            var elem = $('#' + val.controltovalidate);
            if (typeof (val.display) == "string") {
                if (val.display == "None") {
                    return;
                }
                if (val.display == "Dynamic") {
                    val.style.display = val.isvalid ? "none" : "inline";
                    return;
                }
            }
            if ((navigator.userAgent.indexOf("Mac") > -1) &&
            (navigator.userAgent.indexOf("MSIE") > -1)) {
                val.style.display = "inline";
            }
            $.decorateValidator($(val), elem, val.isvalid);
            val.style.visibility = val.isvalid ? "hidden" : "visible";
        }

        var _priorValidationGroup, _notValidated;
        $.Page_ClientValidate = function(validationGroup) {
            _notValidated = {};
            _priorValidationGroup = validationGroup;
            Page_InvalidControlToBeFocused = null;
            if (typeof (Page_Validators) == "undefined") {
                return true;
            }
            var i;
            for (i = 0; i < Page_Validators.length; i++) {
                ValidatorValidate(Page_Validators[i], validationGroup, null);
            }
            ValidatorUpdateIsValid();
            ValidationSummaryOnSubmit(validationGroup);
            Page_BlockSubmit = !Page_IsValid;
            if (!Page_IsValid) $.showValidatorsError();
            return Page_IsValid;
        }

        $.ValidatorOnLoad = function() {
            if (typeof (Page_Validators) == "undefined")
                return;
            _notValidated = {};
            Page_InvalidControlToBeFocused = null;
            var i, val;
            for (i = 0; i < Page_Validators.length; i++) {
                val = Page_Validators[i];
                if (typeof (val.evaluationfunction) == "string") {
                    eval("val.evaluationfunction = " + val.evaluationfunction + ";");
                }
                if (typeof (val.isvalid) == "string") {
                    if (val.isvalid == "False") {
                        val.isvalid = false;
                        Page_IsValid = false;
                    }
                    else {
                        val.isvalid = true;
                    }
                } else {
                    val.isvalid = true;
                }
                if (typeof (val.enabled) == "string") {
                    val.enabled = (val.enabled != "False");
                }
                if (typeof (val.controltovalidate) == "string") {
                    ValidatorHookupControlID(val.controltovalidate, val);
                }
                if (typeof (val.controlhookup) == "string") {
                    ValidatorHookupControlID(val.controlhookup, val);
                }
                if (!val.isvalid) {
                    $.decorateValidator($(val), $('#' + val.controltovalidate), val.isvalid);
                    ValidatorSetFocus(val, null);
                }
            }
            Page_ValidationActive = true;
            if (!Page_IsValid) $.showValidatorsError();
        }


        $.ValidatorOnChange = function(event) {
            if (!event) {
                event = window.event;
            }
            _notValidated = {};
            Page_InvalidControlToBeFocused = null;
            var targetedControl;
            if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
                targetedControl = event.srcElement;
            }
            else {
                targetedControl = event.target;
            }
            var vals;
            if (typeof (targetedControl.Validators) != "undefined") {
                vals = targetedControl.Validators;
            }
            else {
                if (targetedControl.tagName.toLowerCase() == "label") {
                    targetedControl = document.getElementById(targetedControl.htmlFor);
                    vals = targetedControl.Validators;
                }
            }
            var i;
            for (i = 0; i < vals.length; i++) {
                ValidatorValidate(vals[i], null, event);
            }
            ValidatorUpdateIsValid();
        }

        $.decorateRoundboxes = function(source) {
            source.onShow = function() {
                var e = jQuery('#central_ajax_loader_wrapper');
                if (e.size() == 0)
                    jQuery('<div id="central_ajax_loader_wrapper" class="central_ajax_loader_wrapper" style="display: none">&nbsp;</div>')
                        .appendTo(jQuery('body'));

                //                alert('window.height: ' + $(window).height() + '\r\ndocument.height: ' + $(document).height() +
                //                '\r\ndocument.documentElement.offset.top ' + $(document.documentElement).offset().top +
                //                '\r\ndocument.documentElement.offset.left ' + $(document.documentElement).offset().left)
                var offset = 0;
                if ($(document.documentElement).offset().top < 0)
                    offset = $(document.documentElement).offset().top * 2
                jQuery('#central_ajax_loader_wrapper')
                    .css({
                        display: '',
                        width: $(window).width(),
                        height: $(document).height() + offset
                    });
            };
            source.onHide = function() {
                jQuery('#central_ajax_loader_wrapper').css(
                {
                    display: 'none',
                    height: '0px'
                });
            };
        }

        $.showUpdateProgress = function(progressElemId) {
            window.setTimeout(function() {
                if (Page_IsValid) {
                    $.correctLoadingWrapper();
                    $(progressElemId).css('display', 'block');
                    $(progressElemId).css('visibility', 'visible');
                } 
            }, 10)
        }

        // corrects loading wrapper
        $.correctLoadingWrapper = function() {
            var seed = $(document).height() - $(window).height();
            if (seed > 4) seed = 0;
            $('.central_ajax_loader_wrapper').height($(document).height() - seed)
            //$('.central_ajax_loader_wrapper').css('z-index', '100')
        }

        // invokes before every ajax request
        $.onBeginAjaxRequest = function(sender, args) {
            $.correctLoadingWrapper();
            // determines which update progress should be shown
            $.setUpdateProgressesEnabled(sender);
        }

        // invokes after every ajax request
        $.onEndAjaxRequest = function(sender, args) {

            jQuery('.central_ajax_loader_wrapper').css('height', '0px');

            // makes tooltips
            $('.tooltip').makeTooltip();

            //initialize dynamic empty textes.
            $('*[dynamicEmptyText]').dynamicEmptyText();

            // makes faceboxes
            $('a[rel*=roundbox]').roundbox();

            // makes confirmation on click
            $('*[confirmMessage]').makeConfirmMessage();

            // restore settings of updateprogresses
            $.restoreUpdateProgresses();

            var error = args.get_error();
            if (error) {
                $.showMessage(error.message, 'error', true);
                args.set_errorHandled(true);
            }
        }

        $(function() {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest($.onEndAjaxRequest);
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest($.onBeginAjaxRequest);

            // pnotify default setings
            $.pnotify.defaults.pnotify_history = false;
            $.pnotify.defaults.pnotify_delay = 3000;

            // makes faceboxes
            $('a[rel*=roundbox]').roundbox();

            // makes tooltips
            $('.tooltip').makeTooltip();

            //initialize dynamic empty textes.
            $('*[dynamicEmptyText]').dynamicEmptyText();

            // shows logon content
            $.showLoginContent();

            // configures cental ajax loader corners
            $.configureCentralAjaxLoader();

            // prepare sortable spaces for clicable
            $.makeGridSortableSpace();

            // makes confirmation on click
            $('*[confirmMessage]').makeConfirmMessage();
        });

    })(jQuery);
}
