"use strict";
/*global $, jQuery, document*/ //define here all the globals you might have or want

$(document).ready(function () {
    if (!Array.prototype.push || !document.getElementById) {

    }
    else {
        var KR = {};
        $(function () {
            KR.ui = {
                tabStrips: function () {
                    /* We need to "force" the first tabstrip item to be selected for the graphics to work. */
                    $(".section .endero-wptabs li:first-child").addClass("endero-webpartzone-tab-selected");
                    $(".section .endero-wptabs li:first-child a").addClass("first");
                    $(".section .endero-wptabs li:last-child a").addClass("last");
                },
                openCloseForm: function () {
                    var toggled = false;
                    var curUrl = location.href;
                    if (curUrl.indexOf("search=advanced") != -1) {
                        /* If we come from the front page, close the search terms */
                        $(".AJSFormContent").toggle();
                        toggled = true;
                        $(".openClose").toggleClass("closed");
                        $(".searchHeader .openClose").text(translations['UIText_WP_AJS_EditSearch']);
                    }
                    $(".openClose").click(function () {
                        if (toggled == false) {
                            $(this).text(translations['UIText_WP_AJS_EditSearch']);
                            toggled = true;
                        } else {
                            $(this).text(translations['UIText_WP_AJS_CloseSearch']);
                            toggled = false;
                        }
                        $(this).parent().next(".AJSFormContent").slideToggle(300);
                        $(this).toggleClass("closed");
                        return false;
                    });
                },
                initTogglables: function () {
                    $(".openJobAlertBtn").click(function () {
                        $(".openJobAlert").slideToggle(300);
                    });
                    $(".openAdvancedSearch").click(function () {
                        $(".advancedSearch").slideToggle(300);
                        $(this).toggleClass("opened");
                        var temp = $(this).hasClass("opened");
                        if (temp) {
                            $(this).html("<span></span>" + translations['UIText_WP_AJS_CloseAdvancedSearch']);
                        } else {
                            $(this).html("<span></span>" + translations['UIText_WP_AJS_OpenAdvancedSearch']);
                        }
                    });
                },
                initBack: function () {
                    $(".back").click(function () {
                        history.go(-1);
                    });
                },
                initLocationSearch: function () {
                    var selectedCities = [], selectedCitiesString = $(".jobLocation input[type=hidden]").val();
                    $(".jobLocation input[type=text]").autocomplete(translations['servicePathPrefix'] + "/_layouts/Endero.KN2.Kuntarekry/WebServices/JobSearchAutoComplete.asmx/GetCitiesWithQ", {
                        minChars: 2,
                        matchContains: true
                    }).result(function () {
                        var cityKey = $(".jobLocation input[type=text]").attr("autocompletekey");
                        var cityValue = $(".jobLocation input[type=text]").val();
                        if (selectedCitiesString.indexOf(cityKey) == -1) {
                            $("#selectedCities").append("<li>" + cityValue + "<a href='javascript:void(0)' class='remove' value='" + cityKey + "'></a></li>");
                            selectedCities.push(cityKey);
                            if (selectedCitiesString == "") {
                                $(".jobLocation input[type=hidden]").val(selectedCitiesString + cityKey);
                            } else {
                                $(".jobLocation input[type=hidden]").val(selectedCitiesString + "," + cityKey);

                            }
                        }
                        selectedCitiesString = selectedCities.join(",")

                        $(".jobLocation input[type=text]").attr("value", "")
                        $("#selectedCities").show();
                        RequiredFieldCityValidator();

                    });
                    $("#selectedCities .remove").live("click", function () {
                        var cityToBeDeleted = $(this).attr("value");
                        $(this).closest("li").remove();
                        /*
                        Here we handle the hidden field's value
                        */
                        selectedCities = selectedCitiesString.split(",");
                        /*var cityToBeDeleted = $(this).parent().text();*/

                        for (var i = 0; i < selectedCities.length; i++) {
                            if (selectedCities[i] == cityToBeDeleted) {
                                selectedCities.splice(i, 1);
                            }
                        }
                        selectedCitiesString = selectedCities.join(",");
                        $(".jobLocation input[type=hidden]").val(selectedCitiesString); // assign the hidden the new string value

                        if (selectedCitiesString == "") {
                            RequiredFieldCityValidator();
                        }
                    });
                },
                initClearingJobAreas: function () {
                    $(".clearButton a").live("click", function () {
                        if ($(".jobTypes").length != 0) {
                            $(".jobTypes").find(".jCheckboxWrapper span")
                            .removeClass("jNiceChecked")
                            .end()
                            .find(".jCheckboxWrapper input[type=checkbox]")
                            .attr("checked", "");
                            $("#selectedJobTypes").empty();
                            $(".selectedTaskAreasHidden input[type=hidden]").val("");
                            RequiredFieldAreaValidator();
                        }
                        return false;
                    });
                },
                initEqualHeights: function () {
                    $(".teaser, .section .webPartTitle, .resultContainer table th").equalHeights({ isHeader: true });
                },
                extendResetButton: function () {
                    $(".buttonRow .resetBtn").click(function () {
                        $(':input')
                        .not(':button, :submit, :reset, :hidden')
                        .val('')
                        .removeAttr('checked')
                        .removeAttr('selected');
                        $("option").removeAttr('selected');
                        $("#selectedJobTypes").empty();
                        $("#selectedCities").empty();
                       /* $('.jNiceHidden')
                        .removeAttr('checked')
                        .removeAttr('selected');
                        $('.jNiceChecked').removeClass('jNiceChecked'); */
                        $(".jobDuration select").dropdownchecklist("refresh");
                        $(".jobType select").dropdownchecklist("refresh");
                        $(".jobDurationNewInsert select").dropdownchecklist("refresh");
                        $(".jobTypeNewInsert select").dropdownchecklist("refresh");
                        $(".jobLanguageNewInsert select").dropdownchecklist("refresh");
                        $(".jobLocation select").dropdownchecklist("refresh");
                        $(".jobLanguage select").dropdownchecklist("refresh");
                        $(".selectedTaskAreasHidden input[type=hidden]").val("");
                        $(".jobLocation input[type=hidden]").val("");
                        $(".ui-dropdownchecklist").not(".jobTypeListingAnchor .ui-dropdownchecklist").children(".ui-dropdownchecklist-text").removeAttr("title").html(translations['UIText_WP_AJS_All']);
                    });
                },
                initNewWindowLinks: function () {
                    $(".employerInfo a").click(function () {
                        window.open($(this).attr('href'));
                        return false;
                    });
                },
                initMisc: function () {
                    //Small fixes to UI, small and not requiring own functions.
                    $("#gridFrontpage").prev(".customLeftNavHolder").remove();
                },
                initjobAreaLimitation: function () {
                    if ($(".openJobAlert").length > 0) {
                        $(".openJobAlert .button a").click(function () {
                            return limitJobAreas();
                        });
                    }
                },
                initMaskedInputs: function () {
                    //dd.dd.yyyy hh:mm
                    $(".maskedInput input[type=text]").mask("99.99.9999 99:99")
                },
                init: function () {
                    KR.ui.tabStrips();
                    KR.ui.openCloseForm();
                    KR.ui.initTogglables();
                    KR.ui.initBack();
                    KR.ui.initLocationSearch();
                    KR.ui.initClearingJobAreas();
                    KR.ui.initEqualHeights();
                    KR.ui.extendResetButton();
                    KR.ui.initNewWindowLinks();
                    KR.ui.initMisc();
                    KR.ui.initjobAreaLimitation();
                    KR.ui.initMaskedInputs();
                    initDropdownChecklists();
                    manageSelectedJobs();
                    placeRibbon();
                }
            }

            KR.ui.init();
        });
    }
});

(function ($) {
    $.fn.equalHeights = function (customSettings) {
        var config = { 'isHeader': 'false' }
        if (customSettings) $.extend(config, customSettings);

        var maxHeight = 0;
        this.each(function () {
            if (this.offsetHeight > maxHeight) { maxHeight = this.offsetHeight; }
        });

        this.each(function () {
            if (customSettings) {
                if (this.offsetHeight < maxHeight) {
                    var padding = maxHeight - this.offsetHeight;
                    $(this).css("padding-top", padding);
                }
            } else {
                if (this.offsetHeight > maxHeight) { maxHeight = this.offsetHeight; }
                $(this).height(maxHeight + "px");
                if (this.offsetHeight > maxHeight) {
                    $(this).height((maxHeight - (this.offsetHeight - maxHeight)) + "px");
                }
            }
        });

        return this;
    };

})(jQuery);


function manageSelectedJobs() {

    var selectedAreas = [], selectedAreasString = "";
    if ($(".selectedTaskAreasHidden input[type=hidden]").length > 0) selectedAreasString = $(".selectedTaskAreasHidden input[type=hidden]").val();
    selectedAreas = selectedAreasString.split(",");
    /*
    ADDING AN ITEM
        
    For each selected item in the layer, we append that item's label value to an array and the <ul> as a new <li>
    */

    var thisLabel = "";
    var thisValue = "";
    $(".jobTypes input[type=checkbox]:checked").each(function () {
        thisLabel = $(this).closest("td").find("label").text();
        thisValue = $(this).closest("td").find("input").attr("value");
        if (selectedAreasString.indexOf(thisValue) == -1) {
            $("#selectedJobTypes").append("<li><div><a href='javascript:void(0)' value='" + thisValue + "' class='remove'></a>" + thisLabel + "</div></li>")
            selectedAreas.push(thisValue);
        }
        selectedAreasString = selectedAreas.join(",")
        $(".selectedTaskAreasHidden input[type=hidden]").val(selectedAreasString);
        RequiredFieldAreaValidator();
    });

    if (selectedAreasString != "") {
        $(".jobTypes input[type=checkbox]:not(:checked)").each(function () {
            thisValue = $(this).closest("td").find("input").attr("value");
            if (selectedAreasString.indexOf(thisValue) != -1) {
                var areaListItem = $("#selectedJobTypes ").find("li:has(a[value=" + thisValue + "])");
                areaListItem.remove();
                selectedAreas = jQuery.grep(selectedAreas, function (value) { return value != thisValue; });
                selectedAreasString = selectedAreas.join(",")
                $(".selectedTaskAreasHidden input[type=hidden]").val(selectedAreasString);
                RequiredFieldAreaValidator();
            }
        });
    }
    /*
    DELETING AN ITEM
    
    We splice the removed item from the hidden's string that has been converted into an array and recreate a new string from that edited array and finally assing that string to the hidden
    */

    $("#selectedJobTypes .remove").live("click", function () {
        var textToBeDeleted = $(this).parent().text();
        var valueToBeDeleted = $(this).attr("value");
        for (var i = 0; i < selectedAreas.length; i++) {
            if (selectedAreas[i] == valueToBeDeleted) {
                selectedAreas.splice(i, 1);
            }
        }
        selectedAreasString = selectedAreas.join(",");
        $(".selectedTaskAreasHidden input[type=hidden]").val(selectedAreasString); //Assign the edited value back to the hidden field
        $(this).closest("li").remove(); // Remove the visual element (li)
        // Remove it also from the layer
        $(".jobTypes").find("label:contains('" + textToBeDeleted + "')")
        .closest("td")
        .find(".jCheckboxWrapper span")
        .removeClass("jNiceChecked")
        .end()
        .find(".jCheckboxWrapper input[type=checkbox]")
        .attr("checked", "");
        $(".selectedTaskAreasHidden input[type=hidden]").val(selectedAreasString);
        RequiredFieldAreaValidator();
    });
}

function initDropdownChecklists() {
    $(".jobDuration select").dropdownchecklist({
        firstItemChecksAll: true,
        maxDropHeight: 100,
        width: 198,
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 0: return translations['UIText_WP_AJS_Select'];
                case 1: return selectedOptions.text();
                case size: return translations['UIText_WP_AJS_All'];
                default: return countOfSelected + " " + translations['UIText_WP_AJS_Selected'];
            }
        }
    });
    $(".jobDurationNewInsert select").dropdownchecklist({
        maxDropHeight: 100,
        width: 198,
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 0: return translations['UIText_WP_AJS_Select'];
                case 1: return selectedOptions.text();
                case size: return translations['UIText_WP_AJS_All'];
                default: return countOfSelected + " " + translations['UIText_WP_AJS_Selected'];
            }
        }

    });
    $(".jobType select").dropdownchecklist({
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 0: return translations['UIText_WP_AJS_Select'];
                case 1: return selectedOptions.text();
                case size: return translations['UIText_WP_AJS_All'];
                default: return countOfSelected + " " + translations['UIText_WP_AJS_Selected'];
            }
        },
        firstItemChecksAll: true,
        maxDropHeight: 100,
        width: 198
    });
    $(".jobTypeNewInsert select").dropdownchecklist({
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 0: return translations['UIText_WP_AJS_Select'];
                case 1: return selectedOptions.text();
                case size: return translations['UIText_WP_AJS_All'];
                default: return countOfSelected + " " + translations['UIText_WP_AJS_Selected'];
            }
        },
        maxDropHeight: 100,
        width: 198
    });
    $(".jobLocation select").dropdownchecklist({
        firstItemChecksAll: true,
        maxDropHeight: 100,
        width: 198,
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 0: return translations['UIText_WP_AJS_Select'];
                case 1: return selectedOptions.text();
                case size: return translations['UIText_WP_AJS_All'];
                default: return countOfSelected + " " + translations['UIText_WP_AJS_Selected'];
            }
        }
    });
    $(".jobLanguage select").dropdownchecklist({
        maxDropHeight: 100,
        width: 198
    });
    $(".jobLanguageNewInsert select").dropdownchecklist({
        maxDropHeight: 100,
        width: 198,
        textFormatFunction: function (options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch (countOfSelected) {
                case 1: return selectedOptions.text();
                default: return translations['UIText_WP_AJS_Select'];
            }
        }
    });
}

function placeRibbon() {
    var windowTop = $(window).scrollTop()
    if (windowTop > 0) {
        $('#s4-ribbonrow').css("position", "absolute").css("z-index", "10000").css("top", windowTop);
    } else {
        $('#s4-ribbonrow').css("position", "static");
    }
    $('#s4-ribbonrow').click(function () {
        var ribbonSubItem = $(".ms-cui-menu");
        if (ribbonSubItem) {
            var currentEl = $(this).offset(), currentElHeight = $(this).height(), currentElPos = currentEl.top, newPos = 0;
            newPos = currentElPos + currentElHeight;
            $(".ms-cui-menu").css("top", newPos).css("z-index", "10001");
        }
    });
}
function ShareInFacebook() {
    title = document.title;
    url = location.href;
    encodedUrl = encodeURIComponent(url);
    encodedTitle = encodeURIComponent(title);
    fbSharerUrl = "http://www.facebook.com/sharer.php?u=" + encodedUrl + "&t=" + encodedTitle;
    newWindow = open(fbSharerUrl, "FBShareWindow");
}

function limitJobAreas() {
    var selectedJobAreas = $(".jobTypes input[type=checkbox]:checked").length, isAllowableAmount = true;
    if (selectedJobAreas > 10) {
        $("#openJobAlertMessage").next('div').text(translations['UIText_WP_SearchWatch_Error']).show();
        isAllowableAmount = false;
    } else {
        $("#openJobAlertMessage").next('div').text("").hide();
        isAllowableAmount = true;
    }
    return isAllowableAmount;
}


/* Jnice Fix */
function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        $(".listControls").jNice();
        $(".updatePanelWrapper").jNice();
    }
}

function RequiredFieldAreaValidator() {
    var areaHiddenField = $(".selectedTaskAreasHidden input[type=hidden]");
    var areaRequired = $("#taskAreaRequired");

    if (areaHiddenField != null && areaRequired != null) {
        var areaHiddenFieldVal = areaHiddenField.val();
        if (areaHiddenFieldVal == "") {
            areaRequired.css({ visibility: "visible" });
        }
        else {
            areaRequired.css({ visibility: "hidden" });
        }
    }
}

function RequiredFieldCityValidator() {
    var cityHiddenField = $(".jobLocation input[type=hidden]");
    var cityRequired = $("#cityRequired");

    if (cityHiddenField != null && cityRequired != null) {
        var cityHiddenFieldVal = cityHiddenField.val();
        if (cityHiddenFieldVal == "") {
            cityRequired.css({ visibility: "visible" });
        }
        else {
            cityRequired.css({ visibility: "hidden" });
        }
    }
}

window.onscroll = placeRibbon

