﻿LabelHandler.initialize("JQueryResource");

var ie6 = false;

if (!window.console) {
    window.console = {
        log: function() { }
    };
}

function closeredframe() {
    try {
        $("#redBox").remove();
        $("#bodyBGBox").remove();
    } catch (e) { return false; }

    return true;
}

function openEdit(url) {
    $("body").append('<div id="bodyBGBox"></div><div id="redBox"><div id="inner_redBox"><div class="CS_close"><span>' + LabelHandler.JQueryResource["Functions_Close"] + '</span></div><iframe id="redFrame" src="' + url + '"></iframe></div></div>');

    $("#inner_redBox").css({
	    width: "980px",
	    height: ($(window).height() - 80) + "px"
	});

    $("#redBox").css({
	    width: $(window).width() + "px",
	    height: $(window).height() + "px"
	});

    $("#bodyBGBox").css({
	    width: $(window).width() + "px",
	    height: $(window).height() + "px"
	});

    if (ie6)
        $("#redBox").css({ height: ($(document).height() - 80) + "px" });

    $("#redFrame").css({
        width: ($("#inner_redBox").width() - 10) + "px",
        height: ($("#inner_redBox").height() - 25) + "px"
    });

    $("#redBox .CS_close span").click(function() {
        closeredframe();
    });
}

String.prototype.format = function () {
    var txt = this,
        i = arguments.length;

    while (i--) {
        txt = txt.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }

    return txt;
};

function createNonEditableListInfo() {
    var editable = $($(".CS_flippingContainer").children().get(0));
    editable.hide();

    var listName = $("input[name$='ListName']").val();
    var listDesc = $("textarea[name$='ListDescription']").val();

    var html = $('<div><h2>{0}</h2><p>{1}</p></div>'.format(listName, listDesc));

    LabelHandler.initialize('MyLists');
    var editLinkText = LabelHandler.MyLists.ListEditButton_Button_Text;
    var editLink = $("<a href='#' class='CS_edit-list-info' style='float:right;'>" + editLinkText + "</a>");

    editLink.toggle(function () {
        $(this).text(LabelHandler.JQueryResource["Functions_Cancel"]);
        editable.show("fast");
    }, function () {
        $(this).text(LabelHandler.JQueryResource["Functions_Edit"]);
        editable.hide("fast");
    });

    $(".CS_flippingContainer").prepend(html);
    $(".CS_flippingContainer").prepend(editLink);
}

$(document).ready(function () {
    console.log("document.ready fired.");

    $('.CS_toggleable').addClass('CS_toggle-area').next().toggle();

    $('.CS_toggleable').click(function () {
        $(this).next().toggle("fast");
    });

    if ($(".CS_flippingContainer").length > 0)
        createNonEditableListInfo();


    $('.CS_catalog-control select').change(function () {
        console.log("$('.CS_catalog-control select').change fired.");

        var catalogId = $('option:selected', this).val();
        beginSetSelectedCatalog(catalogId);
    });

    $('.CS_library-control select').change(function () {
        console.log("$('.CS_library-control select').change fired.");

        var libraryId = $('option:selected', this).val();
        beginSetSelectedLibrary(libraryId);
    });


    function beginSetSelectedCatalog(catalogId, onSuccess) {
        console.log("beginSetSelectedCatalog(catalogId: '" + catalogId + "', onSuccess: " + onSuccess + ")");

        // Select catalog in all lists.
        $('.CS_catalog-control select').val(catalogId);

        var libraryList = $('.CS_library-control select');

        if (catalogId == 0)
            catalogId = "";

        // Clear all library lists (they will be populated in the ajax-success call)
        libraryList.find('option').remove();

        $.ajax({
            type: "POST",
            url: "Admin/Moduler/OLA/Services/AjaxService.asmx/GetLibraries",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ 'catalogId': '" + catalogId + "' }",
            success: function (data) {
                libraryList.append($('<option />').val('').text(LabelHandler.JQueryResource["Functions_All"]));
                $.each(data.d, function (idx, item) {
                    libraryList.append($('<option />').val(item.Id).text(item.Name));
                });

                if (onSuccess) onSuccess();
            }
        });
    };


    function beginSetSelectedLibrary(libraryId, onSuccess) {
        console.log("beginSetSelectedLibrary(libraryId: '" + libraryId + "', onSuccess: " + onSuccess + ")");

        // Select library in all lists.
        $('.CS_library-control select').val(libraryId);

        var departmentList = $('.CS_department-control select');

        if (libraryId == 0)
            libraryId = "";

        // Clear all department lists (they will be populated in the ajax-success call)
        departmentList.find('option').remove();

        $.ajax({
            type: "POST",
            url: "Admin/Moduler/OLA/Services/AjaxService.asmx/GetDepartments",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ 'libraryId': '" + libraryId + "' }",
            success: function (data) {
                departmentList.append($('<option />').val('').text(LabelHandler.JQueryResource["Functions_All"]));
                $.each(data.d, function (idx, item) {
                    departmentList.append($('<option />').val(item.Id).text(item.Name));
                });

                if (onSuccess) onSuccess();
            }
        });
    }


    jQuery.each(jQuery.browser, function (i, val) {
        if (i == "msie" && jQuery.browser.version.substr(0, 3) == "6.0")
            ie6 = true;
    });

    $(".CS_Editlinks a").click(function () {
        var url = $(this).attr("href");
        openEdit(url);
        return false;
    });


    {
        // Check if a catalog dropdown list has a non-zero selected index.
        // This means that the user has gone back in history, and the browser
        // may have preserved the actual selectedIndexes of the library- and 
        // department dropdown lists, but will now point at faulty items.
        var catalogLists = $('.CS_catalog-control select');
        var libraryLists = $('.CS_library-control select');
        var departmentLists = $('.CS_department-control select');

        var selectedCatalogIndex = (catalogLists.length > 0) ? catalogLists.get(0).selectedIndex : -1;
        var selectedLibraryIndex = (libraryLists.length > 0) ? libraryLists.get(0).selectedIndex : -1;
        var selectedDepartmentIndex = (departmentLists.length > 0) ? departmentLists.get(0).selectedIndex : -1;

        if (selectedCatalogIndex > 0) {
            console.log("selectedCatalogIndex > 0, repairing...");

            beginSetSelectedCatalog(catalogLists.val(), function () {
                libraryLists.attr('selectedIndex', selectedLibraryIndex);
                beginSetSelectedLibrary(libraryLists.val(), function () {
                    departmentLists.attr('selectedIndex', selectedDepartmentIndex);
                });
            });
        } else if (selectedDepartmentIndex > 0) {
            console.log("selectedCatalogIndex > 0, repairing...");
            beginSetSelectedLibrary(libraryLists.val(), function () {
                departmentLists.attr('selectedIndex', selectedDepartmentIndex);
            });
        }
    }
});
