/**
 * Created by IntelliJ IDEA.
 * User: v.sheyko
 * Date: 15/10/2010
 * Time: 13:34:12
 */

var PGMU = {};

PGMU.commons = {
    trim: function (str) {
        str = str.replace(/^\s+/, '');
        for (var i = str.length - 1; i >= 0; i--) {
            if (/\S/.test(str.charAt(i))) {
                str = str.substring(0, i + 1);
                break;
            }
        }
        return str;
    },
    cutTooLongText: function (text, length) {
        return text.length > length ? text.substr(0, length) + '...' : text;
    },
    escapeQuotes : function(text) {
        return new String(text).replace("'", "&apos;").replace('"', '&quot;');
    },
    hidePanel: function(selector) {
        jQuery(selector).hide();
    },
    initPagedTable: function(pagesLabel) {
        jQuery("#pagedTable").pageable({
            limit: 10,
            pager: '<p class="pager">' + pagesLabel + '</p>'
        });
        jQuery("#pagedTable").show();
    },
    initTablesorter: function(tablesorterSelector, notSortableHeader, sortList, sortForce) {
        jQuery(tablesorterSelector).tablesorter({
            sortList: sortList,
            sortForce: sortForce,
            textExtraction: PGMU.commons.innerTagTextExtraction,
            headers: {notSortableHeader: {sorter: false}} // disable the third column sorting
        });
    },
    initTablesorterHeaders: function(tablesorterSelector, headers, sortList, sortForce) {
        jQuery(tablesorterSelector).tablesorter({
            sortList: sortList,
            sortForce: sortForce,
            textExtraction: PGMU.commons.innerTagTextExtraction,
            headers: headers
        });
    },
    initTablesorterWithAlphabetList: function(tablesorterSelector, headers, sortList, sortForce) {
        jQuery(tablesorterSelector).tablesorter({
            sortList: sortList,
            sortForce: sortForce,
            textExtraction: PGMU.commons.innerTagTextExtraction,
            headers: headers
        });
        jQuery(tablesorterSelector).bind("sortEnd", function() {
            jQuery("h2.headers-letters").remove();
            var listName = jQuery("table tr td.column-left-space");
            listName.eq(0).prepend("<h2 class='headers-letters'>" + jQuery.trim(listName.eq(0).text()).substr(0, 1) + "</h2>");
            for (var i = 1; i < listName.length; i++) {
                if (jQuery.trim(listName.eq(i).text().toLowerCase()).substr(0, 1) !=
                        jQuery.trim(listName.eq(i - 1).text().toLowerCase()).substr(0, 1)) {
                    listName.eq(i).prepend("<h2 class='headers-letters'>" +
                            jQuery.trim(listName.eq(i).text()).substr(0, 1) + "</h2>");
                }
            }
        });
    },
    initTabs: function(panelSelector, tabs, selectedTab) {
        var panel = jQuery('.categoriesContainer');
        panel.tabs({
            select: function(event, ui) {
                return false;
            },
            selected: tabs[selectedTab]
        });
        panel.show();
    },
    initializeDatepickerDF: function(datePickerSelector, yearRange, contextPath, dateFormat, tooltip) {
        tooltip = tooltip || '...';
        jQuery(datePickerSelector).datepicker({
            dateFormat:dateFormat,
            altFormat: dateFormat,
            showOn: 'button',
            yearRange: yearRange,
            minDate:null,
            maxDate:null,
            buttonImageOnly: true,
            buttonImage: contextPath + '/images/datepicker.png',
            buttonText: tooltip});
    },
    initializeDatepicker: function(datePickerSelector, yearRange, contextPath) {
        PGMU.commons.initializeDatepickerDF(datePickerSelector, yearRange, contextPath,'dd/mm/yy');
    },
    innerTagTextExtraction: function(node) {
        return jQuery(node).text();
    },
    updateSubmitButtonVisibility: function(checkbox, button) {
        if (jQuery("#" + checkbox).is(':checked')) {
            jQuery("#" + button).show();
            jQuery("#" + button + "Disabled").hide();
        } else {
            jQuery("#" + button).hide();
            jQuery("#" + button + "Disabled").show();
        }
    },
    fillAdoptionKindSubjectsComboboxForRegionalNpa: function(targetComboboxId) {

    },
    fillAdoptionKindSubjectsComboboxForMunicipalNpa: function(targetComboboxId, municipalityComboboxId) {

    },
    initTerritoryCombobox: function(showallTeritoryLabel, allTeritoryLabel, regionId, contextPath, submitFormOnChange, onSelect) {
        var regionCodeCombobox = jQuery("#regionCodeCombobox");
        jQuery.get(contextPath + "/search?q=+id:municipality* -municipality.municipalityParentId_l:*&sortField=municipality.municipalityName_s", {}, function(data) {
            var docs = data.response.docs;
            if (showallTeritoryLabel) {
                regionCodeCombobox.html("<option value='0' title='" + PGMU.commons.escapeQuotes(allTeritoryLabel) + "'>" + allTeritoryLabel + "</option>");
            }
            for (var i = 0; i < docs.length; i++) {
                var doc = docs[i];
                regionCodeCombobox.each(function() {
                    var id = doc['id'].substring(13);
                    var name = doc['municipality.municipalityName_s'];
                    var code = doc['municipality.municipalityCode_l'];
                    var mos = doc['municipality.mos']
                    if (id == regionId) {
                        jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(name)
                                                + "' value='" + id
                                                + "' id='rcode" + code
                                                + "' selected='selected'>"
                                + PGMU.commons.cutTooLongText(name, 28) + "</option>");
                    } else {
                        jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(name)
                                                + "' value='" + id
                                                + "' id='rcode" + code + "'>"
                                + PGMU.commons.cutTooLongText(name, 28) + "</option>");
                    }
                    if (typeof(mos) !== 'undefined') {
                        for (var i = 0; i < mos.length; i++) {
                            var mosObj = mos[i].split("_");
                            var mosId = mosObj[0].substring(13);
                            var mosName = ' ';
                            if (typeof(mosObj[1]) != 'undefined') {
                                 mosName = mosObj[1];
                            }
                            var mosCode = ' ';
                            if (typeof(mosObj[3]) != 'undefined') {
                                 mosCode = mosObj[3];
                            }
                            if (mosId == regionId) {
                                jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(mosName)
                                                        + "' value='" + mosId
                                                        + "' id='rcode" + mosCode
                                                        + "' selected='selected'>&nbsp;&nbsp;&nbsp;"
                                        + PGMU.commons.cutTooLongText(mosName, 25) + "</option>");
                            } else {
                                jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(mosName)
                                                        + "' value='" + mosId
                                                        + "' id='rcode" + mosCode + "'>&nbsp;&nbsp;&nbsp;"
                                        + PGMU.commons.cutTooLongText(mosName, 25) + "</option>");
                            }

                        }
                    }

                });
            }
            if (submitFormOnChange != null && submitFormOnChange != "") {
                /*
                    jQuery 1.3.2 + IE hack, the most simple code must be like this:
                    jQuery(".filter-select select").change(submitForm(submitFormOnChange));
                    The problem hides in dynamically added "onchange" events to <select> options which are
                    buggy in IE + jQuery 1.3.2 combination. In jQuery 1.4 the problem was fixed.
                */
                regionCodeCombobox.get(0).onchange = function() {
                            submitForm(submitFormOnChange);
                        }
            }
        }, "json");
        if (typeof(onSelect) == "function") {
           regionCodeCombobox.change(onSelect);
        }
    },
    initSelectTerritoryDialog: function(selector, title, linkSelector) {
        jQuery(selector).dialog({
            modal: true,
            width:600,
            autoOpen:false,
            title: title
        });
        jQuery(linkSelector).click(function() {
            jQuery(selector).dialog('open');
        });
    },
    updateRegion: function(region, submitFormOnChange) {
        jQuery("#regionCodeCombobox option").removeAttr("selected");
        jQuery("#rcode" + region).attr("selected", "selected");
        if (submitFormOnChange != null && submitFormOnChange != "") {
            submitForm(submitFormOnChange);
        } else {
            jQuery("#select_ynao_teritory_dialog").dialog('close');
        }
    },
    initRegionsStyles: function(areaSelector, mapDivId) {
        var aw = new Array
        aw = jQuery(areaSelector);
        var i = 0;
        while(aw[i]) {
            var myid = aw[i].id
            aw[i].onmouseover = function() {
                jQuery(mapDivId).attr("class",this.id + ' map_common');
            }
            aw[i].onmouseout = function() {
                jQuery(mapDivId).attr('class','mapa map_common');
            }
            i += 1
        }
    },
    initConfirmationDialog: function(selector, title, linkSelector, cancelSelector, sourceType, sourceSelectorId, addMessageCSS) {
        jQuery(selector).dialog({
            modal: true,
            resizable: false,
            autoResize:true,
            minHeight: null,
            width: 400,
            autoOpen:false,
            position: "center",
            title: title
        });
        jQuery(linkSelector).click(function() {
            var find = jQuery().find(".ui-dialog-titlebar");
            find.addClass("confirmation");
            if (addMessageCSS) {
                jQuery(selector).find('.confirmationMessage').addClass(addMessageCSS);
            }
            PGMU.commons.changeDialogMessage(sourceType, sourceSelectorId, selector);
            jQuery(selector).dialog('open');
            return false;
        });
        jQuery(cancelSelector).click(function() {
            jQuery(selector).dialog('close');
            return false;
        });
    },
    initIframeModalDialog:function(dialogSelector, title, openSelector, srcUrl, width, height) {
        jQuery(dialogSelector).dialog({
            modal:true,
            width:width,
            height:height,
            autoOpen:false,
            title: title,
            dialogClass: 'iframe-dialog'
        });
        jQuery(openSelector).click(function() {
            var dialog = jQuery(dialogSelector);
            dialog.html("<iframe src='" + srcUrl + "' frameborder='0' scrolling='auto' width='100%' height='100%'></iframe>");
            dialog.dialog('open');
        });
    },
    initCommonModalDialog: function(selector, title, linkSelector, cancelSelector) {
        jQuery(selector).dialog({
            modal: true,
            width:600,
            autoOpen:false,
            title: title
        });
        jQuery(linkSelector).click(function() {
            jQuery(selector).dialog('open');
        });
        jQuery(cancelSelector).click(function() {
            jQuery(selector).dialog('close');
            return false;
        });
    },
    closeModalDialog: function (selector) {
        jQuery(selector).dialog('close');
    },
    closeModalDialogAndReloadParent: function (parentSelector) {
        jQuery(parentSelector).click();
    },
    setActionAndSubmitForm: function(action, formId) {
        jQuery("#" + formId).attr("action", action);
        jQuery('#' + formId).submit();
    },
    changeDialogMessage: function(sourceType, sourceSelectorId, destSelector) {
        if (!sourceType || !destSelector) {
            return;
        }
        var currentName;
        if (sourceType.indexOf("tree") != -1) {//text locates in tree-elelment which id on selection puts into special 'input' with id == selected_id.
            sourceSelectorId = jQuery("#selected_id").val();
            currentName = jQuery("#" + sourceType + " a[id=" + sourceSelectorId + "]").attr("text");
        }

        //within table text can be located in 'td' or in 'a' ('flow-link')
        if (sourceType.indexOf("table") != -1 || sourceType.indexOf("Table") != -1) {
            currentName = jQuery("#" + sourceType + " td[id=" + sourceSelectorId + "]").html();
            if (!currentName) {
                currentName = jQuery("#" + sourceType + " a[id=" + sourceSelectorId + "]").attr("text");
            }
        }
        if (currentName) {
            var dest = jQuery(destSelector + " .confirmationMessage");
            dest.html('&#171;' + currentName + '&#187;?');
        }
    },
    initSlidableLayout:function(sliderHeaderSelector, sliderContentSelector){
        jQuery(sliderHeaderSelector).click(function () {
            jQuery(sliderContentSelector).toggleClass("collapsed").toggleClass("expanded");
        });
    },

    initAccordion: function(accordionSelector, headerSelector) {
        $(accordionSelector).accordion({
			header: headerSelector
		});
    },
	initPagedTable: function(pagedTableSelector, pagesLabel) {
        jQuery(pagedTableSelector).each(function(){
            jQuery(this).pageable({
                limit: 10,
                pager: '<p class="pager">' + pagesLabel + '</p>'
            });
            jQuery(this).show();
        });
    },
    initValidatorUpdater: function(selector) {
        jQuery(selector).live("change",function() {
            jQuery(this).focus();
            jQuery(this).blur();
            jQuery(this).focus();
        });
    },
    urlEncode: function(c) {
        var o = '';
        var x = 0;
        c = c.toString();
        var r = /(^[a-zA-Z0-9_.]*)/;
        while (x < c.length) {
            var m = r.exec(c.substr(x));
            if (m != null && m.length > 1 && m[1] != '') {
                o += m[1];
                x += m[1].length;
            } else {
                if (c[x] == ' ')o += '+'; else {
                    var d = c.charCodeAt(x);
                    var h = d.toString(16);
                    o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
                }
                x++;
            }
        }
        return o;
    },
    urlDecode:function(s) {
        var o = s;
        var binVal,t;
        var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b);
            o = o.replace(m[1], t);
        }
        return o;
    },
    initSlidableLayout:function(sliderHeaderSelector, sliderContentSelector, hideFilterMessage, showFilterMessage, toggle) {
        jQuery(sliderHeaderSelector).click(function () {
            var content = $(sliderContentSelector);
            content.toggleClass("collapsed").toggleClass("expanded");
            var hederTitle = (content.hasClass(".expanded")) ? hideFilterMessage : showFilterMessage;
            $(this).find(".title").html(hederTitle);
        });
    }

};

PGMU.commons.breadcrumbs = {
    deleteBreadcrumbCookies: function (path) {
        var counter = 0;
        var cookieName;
        while (counter >= 0) {
            cookieName = 'Breadcrumb' + counter;
            if (PGMU.commons.cookies.getCookie(cookieName)) {
                PGMU.commons.cookies.deleteCookie(cookieName, path, null);
                counter++;
            } else {
                return;
            }
        }
    }
};

PGMU.commons.cookies = {
    setCookie: function  (name, value, expires, path, domain, secure) {
        document.cookie = name + "=" + value +
                ((expires) ? "; expires=" + expires : "") +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "");
    },
    deleteCookie: function (name, path, domain) {
        var instance = this;
        if (instance.getCookie(name)) {
            document.cookie = name + "=" +
                    ((path) ? "; path=" + path : "") +
                    ((domain) ? "; domain=" + domain : "") +
                    "; expires=" + new Date().toGMTString();
        }
    },
    getCookie: function(name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var allCookies = document.cookie.split(';');
        var tempCookie = '';
        var cookieName = '';
        var cookieValue = '';
        var cookieFound = false; // set boolean t/f default f

        for (i = 0; i < allCookies.length; i++) {
            // now we'll split apart each name=value pair
            tempCookie = allCookies[i].split('=');

            // and trim left/right whitespace while we're at it
            cookieName = tempCookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookieName == name) {
                cookieFound = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (tempCookie.length > 1) {
                    cookieValue = unescape(tempCookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookieValue;
                break;
            }
            tempCookie = null;
            cookieName = '';
        }
        if (!cookieFound) {
            return null;
        }
    },
    getCookieOld: function (name) {
        var cookie = " " + document.cookie;
        var search = " " + name + "=";
        var setStr = null;
        var offset = 0;
        var end = 0;
        if (cookie.length > 0) {
            offset = cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = cookie.indexOf(";", offset);
                if (end == -1) {
                    end = cookie.length;
                }
                setStr = cookie.substring(offset, end);
            }
        }
        return(setStr);
    }
};

PGMU.contentPortlets = {
    showPrevFavour: function(itemArray, firstItem, lastItem) {
        lastItem += 1;
        if (lastItem >= itemArray.length) {
            lastItem = 0;
            var last = jQuery(".favour-ribbon .ribbon-items-area .ribbon-item:first");
            var clone = last.clone();
            clone.addClass("last-item");
            last.remove();
            jQuery(".favour-ribbon .ribbon-items-area .ribbon-item:last").after(clone);
            clone.show();
        } else {
            itemArray[lastItem].addClass("last-item");
            itemArray[lastItem].show();
        }
        itemArray[firstItem].hide();
        firstItem += 1;
        itemArray[firstItem].addClass("first-item");
    },
    showNextFavour: function(itemArray, firstItem, lastItem) {
        firstItem -= 1;
        if (firstItem < 0) {
            firstItem = itemArray.length - 1;
            var last = jQuery(".favour-ribbon .ribbon-items-area .ribbon-item:last");
            var clone = last.clone();
            clone.addClass("first-item");
            last.remove();
            jQuery(".favour-ribbon .ribbon-items-area .ribbon-item:first").before(clone);
            clone.show();
        } else {
            itemArray[firstItem].addClass("first-item");
            itemArray[firstItem].show();
        }
        itemArray[lastItem].hide();
        lastItem -= 1;
        itemArray[lastItem].addClass("last-item");
        itemArray[lastItem].show();
    },
    initRibbonFavours: function() {
        var instance = this;
        jQuery(".favour-item-button").click(function() {
            var itemArray = new Array();
            var firstItem = 0;
            var lastItem = 0;
            jQuery(".favour-ribbon .ribbon-items-area .ribbon-item").each(function(i) {
                itemArray[i] = jQuery(this);
                if (jQuery(this).hasClass("first-item")) {
                    firstItem = i;
                }
                if (jQuery(this).hasClass("last-item")) {
                    lastItem = i;
                }
            });
            if (itemArray.length == 4) return;
            itemArray[firstItem].removeClass("first-item");
            itemArray[lastItem].removeClass("last-item");
            if ($(this).hasClass("prev-favour-item")) {
                instance.showNextFavour(itemArray, firstItem, lastItem);
            } else {
                instance.showPrevFavour(itemArray, firstItem, lastItem);
            }
        });
    },
    ribbonFavoursSelectUp: function() {
        jQuery("#favourRibbonUpButton").removeClass("rib-up-area-unselected");
        jQuery("#favourRibbonUpButton").addClass("rib-up-area-selected");
    },
    ribbonFavoursUnselectUp: function() {
        jQuery("#favourRibbonUpButton").removeClass("rib-up-area-selected");
        jQuery("#favourRibbonUpButton").addClass("rib-up-area-unselected");
    },
    ribbonFavoursSelectDown: function() {
        jQuery("#favourRibbonDownButton").removeClass("rib-down-area-unselected");
        jQuery("#favourRibbonDownButton").addClass("rib-down-area-selected");
    },
    ribbonFavoursUnselectDown: function() {
        jQuery("#favourRibbonDownButton").removeClass("rib-down-area-selected");
        jQuery("#favourRibbonDownButton").addClass("rib-down-area-unselected");
    },
    showLoading: function(selectedItemId) {
        jQuery("#" + selectedItemId).parent().addClass("ajax-loading");
    },
    hideLoading: function(selectedItemId) {
        jQuery("#" + selectedItemId).parent().removeClass("ajax-loading");
    },
    initCategoryCombobox: function(allLabel, selectedItemId, contextPath, selectId, npaArea) {
        var loadingTimeout = setTimeout("PGMU.contentPortlets.showLoading('" + selectId + "')", 1000);
        var npaFilter = "";
        if(npaArea != null && "" != npaArea) {
            npaFilter = "+%2BstandardAct.area_s:"+npaArea;
        }
        jQuery("#"+selectId).html("<option value='0' title=''></option>");
        jQuery.get(contextPath + "/search?q=%2Bid:standardAct*+%2BstandardAct.project_b:false"+npaFilter+"&sortField=standardAct.category_s&fields=standardAct.category_s", {}, function(data) {
            var docs = data.response.docs;
            jQuery("#"+selectId).html("<option value='0' title='" + PGMU.commons.escapeQuotes(allLabel) + "'>" + allLabel + "</option>");
            var items = new Array();
            for (var i = 0; i < docs.length; i++) {
                var doc = docs[i];
                jQuery("#"+selectId).each(function() {
                    var code = doc['standardAct.category_s'];
                    if(typeof(code) !== 'undefined' && code != null) {
                        for(var i=0;i<code.length;i++) {
                            if(jQuery.inArray(code[i], items)==-1) {
                                items.push(code[i]);
                                if (code == selectedItemId) {
                                    jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' id='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' selected='selected'>"
                                            + PGMU.commons.cutTooLongText(code[i], 28) + "</option>");
                                } else {
                                    jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' id='" + PGMU.commons.escapeQuotes(code[i]) + "'>"
                                            + PGMU.commons.cutTooLongText(code[i], 28) + "</option>");
                                }
                            }
                        }
                    }
                });
            }
            clearTimeout(loadingTimeout);
            PGMU.contentPortlets.hideLoading(selectId);
        }, "json");
    },
    initDepartmentComboboxNoMunicipality: function(allLabel, selectedItemId, contextPath, selectId, npaArea) {
        var loadingTimeout = setTimeout("PGMU.contentPortlets.showLoading('" + selectId + "')", 1000);
        var npaFilter = "";
        if(npaArea != null && "" != npaArea) {
            npaFilter = " +standardAct.area_s:"+npaArea;
        }
        jQuery("#"+selectId).html("<option value='0' title=''></option>");
        jQuery.get(contextPath + "/search?q=+id:standardAct* +standardAct.project_b:false"+npaFilter+"&sortField=standardAct.depName_s&fields=standardAct.depName_s", {}, function(data) {
            var docs = data.response.docs;
            jQuery("#"+selectId).html("<option value='0' title='" + PGMU.commons.escapeQuotes(allLabel) + "'>" + allLabel + "</option>");
            var items = new Array();
            for (var i = 0; i < docs.length; i++) {
                var doc = docs[i];
                jQuery("#"+selectId).each(function() {
                    var code = doc['standardAct.depName_s'];
                    if (typeof(code) !== 'undefined' && code != null && code != "") {
                        for(var i=0;i<code.length;i++) {
                            if(jQuery.inArray(code[i], items) == -1) {
                                items.push(code[i]);
                                if (code == selectedItemId) {
                                    jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' id='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' selected='selected'>"
                                            + PGMU.commons.cutTooLongText(code[i], 58) + "</option>");
                                } else {
                                    jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                            + "' id='" + PGMU.commons.escapeQuotes(code[i]) + "'>"
                                            + PGMU.commons.cutTooLongText(code[i], 58) + "</option>");
                                }
                            }
                        }
                    }
                });
            }
            clearTimeout(loadingTimeout);
            PGMU.contentPortlets.hideLoading(selectId);
        }, "json");
    },
    initDepartmentCombobox: function(allLabel, selectedItemId, contextPath, selectId, npaArea, municipalityId) {
        var loadingTimeout = setTimeout("PGMU.contentPortlets.showLoading('" + selectId + "')", 1000);
        if (municipalityId == null) {
            PGMU.contentPortlets.initDepartmentComboboxNoMunicipality(allLabel, selectedItemId, contextPath, selectId, npaArea);
            return;
        }
        // 1. Get municiaplity VKMO code by it's id
        jQuery.get(contextPath + "/search?q=+id:municipality." + municipalityId + "&fl=municipality.municipalityCodeVKMO_l", {}, function(data) {
            var vkmo = null;
            var municipalityWithVKMO = data.response.docs;
            if (municipalityWithVKMO.length == 0) {
                jQuery.error("The municipality VKMO code wasn't found.");
            } else {
                if (municipalityWithVKMO.length > 1) {
                    jQuery.error("There was too many VKMO codes for municipality. We will use first of them.");
                }
                vkmo = municipalityWithVKMO[0]['municipality.municipalityCodeVKMO_l'];

                // 2. Get all unique adpotionKindSubjects of all NPA's with the retrieved VKMO code
                jQuery("#"+selectId).html("<option value='0' title=''></option>");

                if (vkmo != null && vkmo != "") {
                    var query = contextPath + "/search?q=" +
                            "-standardAct.project_b:true" +
                            "-(NOT standardAct.area_s:MUNICIPAL)"+
                            " +standardAct.areaCode_s:" + vkmo +
                            "&sortField=standardAct.adoptionKindSubject_s" +
                            "&fields=standardAct.adoptionKindSubject_s" +
                            "&fl=standardAct.adoptionKindSubject_s";
                    jQuery.get(query, {}, function(data) {
                        var docs = data.response.docs;
                        jQuery("#"+selectId).html("<option value='0' title='" + PGMU.commons.escapeQuotes(allLabel) + "'>" + allLabel + "</option>");
                        var items = new Array();
                        for (var i = 0; i < docs.length; i++) {
                            var doc = docs[i];
                            jQuery("#"+selectId).each(function() {
                                var code = doc['standardAct.adoptionKindSubject_s'];
                                if (typeof(code) !== 'undefined' && code != null && code != "") {
                                    for(var i=0;i<code.length;i++) {
                                        if(jQuery.inArray(code[i], items) == -1) {
                                            items.push(code[i]);
                                            if (code == selectedItemId) {
                                                jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                                        + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                                        + "' id='" + PGMU.commons.escapeQuotes(code[i])
                                                                        + "' selected='selected'>"
                                                        + PGMU.commons.cutTooLongText(code[i], 58) + "</option>");
                                            } else {
                                                jQuery(this).append("<option title='" + PGMU.commons.escapeQuotes(code[i])
                                                                        + "' value='" + PGMU.commons.escapeQuotes(code[i])
                                                                        + "' id='" + PGMU.commons.escapeQuotes(code[i]) + "'>"
                                                        + PGMU.commons.cutTooLongText(code[i], 58) + "</option>");
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }, "json");
                }
            }
            clearTimeout(loadingTimeout);
            PGMU.contentPortlets.hideLoading(selectId);
        }, "json");
    },
    initAccordion: function(accordionSelector, headerSelector, selectedTabId) {
        $(accordionSelector).accordion({
            active:parseInt(selectedTabId),
            header: headerSelector,
            autoHeight: false
        });
    }
    
};

PGMU.referenceBook = {
    initializeTypicalRegistryDefaultTree: function(containerSelector, dataUrl) {
        jQuery(containerSelector).tree({
            data : {
                async: true,
                type : "json",
                opts : {
                    method: "GET",
                    url : dataUrl
                }
            },
            callback: {
                beforedata: function(n, t) {
                    return jQuery(n).attr("id") === "" ?
                           { id: jQuery(n).find("a:first").attr("id")} :
                           { id: jQuery(n).attr("id") || 0 };
                }
            },
            ui : {
                theme_name : "classic",
                dots       : false
            },
            types: {
                "default" : {
                    max_depth   : 1,
                    deletable   : false,
                    renameable  : false,
                    creatable   : false,
                    draggable   : false,
                    icon : {
                        image    : false,
                        position : false
                    }
                }
            }
        });
    },
    initializeReferenceBookMenu: function(selected) {
        jQuery("#reference-book-menu-tree").show('slow');
        jQuery("#reference-book-menu-tree").tree({
            selected : selected == null || selected == '' ? 'root' : selected,
            plugins : [ "types", "html_data" ],
            ui : {
                theme_name : "references",
                dots       : false
            },
            types : {
                "default" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false
                },
                "integration" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/integration.png",
                        position: "center bottom"
                    }
                },
                "search" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/search.png",
                        position: "center bottom"
                    }
                },
                "groups" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/groups.png",
                        position: "center bottom"
                    }
                },
                "updown" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/updown.png",
                        position: "center bottom"
                    }
                },
                "referencebook" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/list.png",
                        position: "center bottom"
                    }
                },
                "question" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/question.png",
                        position: "center bottom"
                    }
                },
                "organization" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/organization.png",
                        position: "center bottom"
                    }
                },
                "npa" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/npa.png",
                        position: "center bottom"
                    }
                },
                "document" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/document.png",
                        position: "center bottom"
                    }
                },
                "internet" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/internet.png",
                        position: "center bottom"
                    }
                },
                "registry" : {
                    deletable  : false,
                    renameable : false,
                    creatable  : false,
                    draggable  : false,
                    icon : {
                        image : "images/reference-book/menu/integration.png",
                        position: "center bottom"
                    }
                }
            },
            callback: {
                onselect: function(n, t) {
                    // To avoid the infinite selection cycles
                    if (n.id != selected) {
                        var href = jQuery(n).find("a:first").attr("href");
                        if (href != null && window.location != href) {
                            window.location = href;
                        }
                    }
                }
            }
        });
    },
    setFizPosition: function(position) {
        jQuery("#setFavourCategoryFizSortOrderFormPosition").val(position);
        jQuery("#setFavourCategoryFizSortOrderForm").submit();
    },
    showFizPositionDialog: function(favourCategoryId, container) {
        var x = jQuery(container).offset().left + jQuery(container).width() + 5;
        var y = jQuery(container).offset().top - jQuery(window).scrollTop();
        jQuery("#setFavourCategoryFizSortOrderFormFavourCategoryId").val(favourCategoryId);
        jQuery("#fizNumbersPopup").dialog("option", "position", [x, y]);
        jQuery("#fizNumbersPopup").dialog("open");
    },
    setJurPosition: function(position) {
        jQuery("#setFavourCategoryJurSortOrderFormPosition").val(position);
        jQuery("#setFavourCategoryJurSortOrderForm").submit();
    },
    showJurPositionDialog: function(favourCategoryId, container) {
        var x = jQuery(container).offset().left + jQuery(container).width() + 5;
        var y = jQuery(container).offset().top - jQuery(window).scrollTop();
        jQuery("#setFavourCategoryJurSortOrderFormFavourCategoryId").val(favourCategoryId);
        jQuery("#jurNumbersPopup").dialog("option", "position", [x, y]);
        jQuery("#jurNumbersPopup").dialog("open");
    },
    showInstitutionTemplateOrganizationsDialog: function() {
        jQuery("#institutionTemplateOrganizationsDialog").dialog("open");
    },
    setOrganizationNameFromTemplate: function(container) {
        jQuery("#institutionName").val(jQuery(container).text());
        jQuery("#institutionTemplateOrganizationsDialog").dialog("close");
    },
    updateAdministrativeRegulationsFieldsEnablement: function(checkbox) {
        if (jQuery("#" + checkbox).is(':checked')) {
            jQuery("#stop").attr('disabled', 'disabled');
            jQuery("#suspend").attr('disabled', 'disabled');
            jQuery("#suspendEnd").attr('disabled', 'disabled');
            jQuery("#duration").attr('disabled', 'disabled');
            jQuery("#commingIntoEffect").attr('disabled', 'disabled');
            jQuery("#commingIntoEffect").datepicker("disable");
            jQuery("#stop").datepicker("disable");
            jQuery("#suspend").datepicker("disable");
            jQuery("#suspendEnd").datepicker("disable");
        } else {
            jQuery("#stop").removeAttr('disabled');
            jQuery("#suspend").removeAttr('disabled');
            jQuery("#suspendEnd").removeAttr('disabled');
            jQuery("#duration").removeAttr('disabled');
            jQuery("#commingIntoEffect").removeAttr('disabled');
            jQuery("#commingIntoEffect").datepicker("enable");
            jQuery("#stop").datepicker("enable");
            jQuery("#suspend").datepicker("enable");
            jQuery("#suspendEnd").datepicker("enable");
        }
    }
}

PGMU.registration = {
    updateUserType: function (personControls) {
        for (var i = 0; i < personControls.visible.length; i++) {
            jQuery(personControls.visible[i]).show();
        }
        for (var i = 0; i < personControls.invisible.length; i++) {
            jQuery(personControls.invisible[i]).hide();
        }
    },
    updateSeriesVisiblity: function(passportTypeId) {
        if (jQuery("select[name=idCardType]").val() == passportTypeId) {
            jQuery(".idCardSeries").show();
        } else {
            jQuery(".idCardSeries").hide();
        }
    },
    submitRegistrationForm: function(passportTypeID) {
        if (jQuery("select[name=idCardType]").val() == passportTypeID) {
            jQuery("#hiddenSubmitButton > a").click();
        } else {
            jQuery("#dialog-confirm").dialog("open");
        }
    }
};

PGMU.favour = {
    cutTooLongComboboxContent: function (comboboxId) {
        jQuery("#" + comboboxId + " option").each(function(){
            jQuery(this).text(PGMU.commons.cutTooLongText(PGMU.commons.trim(jQuery(this).text()), 30));
        });
    },
    submitFormWhenListValueChanged: function(formSelector, listSelector) {
        if (jQuery(listSelector + " option:selected").val() != "") {
            jQuery(formSelector).submit();
        }
    }
}

PGMU.smevFormPlayer = {
    cutTooLongComboboxContent: function (comboboxId,length) {
        jQuery("#" + comboboxId + " option").each(function(){
            jQuery(this).text(PGMU.commons.cutTooLongText(PGMU.commons.trim(jQuery(this).text()), length));
        });
    }
}

PGMU.favourCatalogue = {
    contextPath:"",
    favourCategoryId:"",
    recipientCategoryId:"",

    initAccordion: function(contextPath, accordionSelector, headerSelector, recipientCategoryTabId, favourCategoryId, recipientCategoryId) {
        PGMU.favourCatalogue.contextPath = contextPath;
        PGMU.favourCatalogue.favourCategoryId = favourCategoryId;
        PGMU.favourCatalogue.recipientCategoryId = recipientCategoryId;
        $(accordionSelector).accordion({
            active:parseInt(recipientCategoryTabId),
            header: headerSelector,
            autoHeight: false
        });
        $(accordionSelector).bind("accordionchange", PGMU.favourCatalogue.recipientCategoryChanged);
    },

    recipientCategoryChanged: function(event, ui) {
        var contentId = ui.newContent[0].id;
        var recipientCategoryId = contentId.split("_")[1];
        var recipientCategoryTab = ui.newHeader[0].id.split("_")[1];
        var municipalityId = jQuery("#municipalityId").attr("value");
        var activityDirectionId = jQuery("#activityDirectionId").attr("value");
        var omsuOrganizationId = jQuery("#omsuOrganizationId").attr("value");
        var iogvOrganizationId = jQuery("#iogvOrganizationId").attr("value");
        var favourOrganizationFilter = jQuery("#favourOrganizationFilter").attr("value");

        var showAllServices = jQuery("#showAllServices").attr("value");
        var showElectronicServices = jQuery("#showElectronicServices").attr("value");
        var showMfcServices = jQuery("#showMfcServices").attr("value");
        var params = {municipalityId:municipalityId,
            activityDirectionId:activityDirectionId,
            omsuOrganizationId:omsuOrganizationId,
            iogvOrganizationId:iogvOrganizationId,
            favourOrganizationFilter:favourOrganizationFilter,
            recipientCategoryId:recipientCategoryId,

            showMfcServices:showMfcServices,
            showElectronicServices:showElectronicServices,
            showAllServices:showAllServices
        };
        jQuery("#recipientCategoryId").attr("value", recipientCategoryId);
        jQuery("#recipientCategoryTab").attr("value", recipientCategoryTab);
        var url = PGMU.favourCatalogue.contextPath + "/indexService";
        jQuery.get(url, params, function(data) {
            //console.log("Loaded");
            var ul = document.createElement("ul");
            jQuery.each(data, function() {
                var li = document.createElement("li");
                var content;
                var favourImage;
                if (this.iconId != null && this.iconId != '') {
                    favourImage = "<img src=\"" + PGMU.favourCatalogue.contextPath + "/file?id=" + this.iconId + "\" alt=\"\"/>";
                } else {
                    favourImage = "<img src=\"" + PGMU.favourCatalogue.contextPath + "/images/blank.gif" + "\" alt=\"\"/>";
                }
                if (municipalityId > 0) {

                    if (this.id == PGMU.favourCatalogue.favourCategoryId && recipientCategoryId == PGMU.favourCatalogue.recipientCategoryId) {
                        content = "<a href=\"#\" class=\"icon\">" + favourImage + "</a>";
                        content += "<div class=\"nav-item-desc selected\"><div class=\"fix-align\"><a href=\"#\">" + this.name + "</a></div></div>";
                    } else {
                        content = "<a href=\"#\" onclick='PGMU.favourCatalogue.filterFavours(" + this.id + ")' class=\"icon\">" + favourImage + "</a>";
                        content += "<div class=\"nav-item-desc\"><div class=\"fix-align\"><a href=\"#\" onclick='PGMU.favourCatalogue.filterFavours(" + this.id + ")'>" + this.name + "</a></div></div>";
                    }
                } else {
                    content = "<a href=\"#\" class=\"icon\">" + favourImage + "</a>";
                    content += "<div class=\"nav-item-desc\"><div class=\"fix-align\">" + this.name + "</div></div>";
                }
                jQuery(li).html(content);
                jQuery(ul).append(li);
            });

            jQuery("#favourCategories_" + recipientCategoryId).html(ul);

        }, "json");

    },

    filterFavours: function(favourCategoryId) {
        jQuery("#favourCategoryId").attr("value", favourCategoryId);
        submitForm("filterFavours");
    },

    setFavourCategoryFormFavourCategoryAndSubmit: function(id) {
        jQuery("#favourCategoryId").val(id);
        jQuery("#goIntoFavourCategoryForm").submit();
    },

    setTabAndSubmitTopFavourCategoriesChangeTabForm: function(tab) {
        jQuery("#setTabAndSubmitTopFavourCategoriesChangeTabFormTab").val(tab);
        jQuery("#topFavourCategoriesChangeTabForm").submit();
    }
};

PGMU.mupassport = {
     changeElectronicAccess: function() {
        if (jQuery("#favourElectronic").is(":checked")) {
            jQuery("#favourElectronicSystemSelect").removeAttr("disabled");
        } else {
            jQuery("#favourElectronicSystemSelect").attr("disabled","disabled");
        }
    },
    belongingChanged: function() {
        if (jQuery('#belonging').val() == "MUNICIPAL") {
            jQuery('#municipal').show();
            hide('iogv');
            hide('federal');
            hide('institution');
        } else if (jQuery('#belonging').val() == "IOGV") {
            jQuery('#iogv').show();
            hide('municipal');
            hide('federal');
            hide('institution');
        } else if (jQuery('#belonging').val() == "FEDERAL") {
            jQuery('#federal').show();
            hide('municipal');
            hide('iogv');
            hide('institution');
        } else if (jQuery('#belonging').val() == "INSTITUTION") {
            jQuery('#institution').show();
            hide('municipal');
            hide('federal');
            hide('iogv');
        } else {
            hide('iogv');
            hide('municipal');
            hide('federal');
            hide('institution');
        }
    },
    submitFavoursFilterFormOnEnter: function(submitButtonId, e) {
        if(e.which == 13) {
            jQuery('#' + submitButtonId).focus().click();
        }
    }
}
