/// <reference path="jquery-1.3.2.min-vsdoc2.js" />

var systemair = function() {

    var originalSearchButtonClickEvent;

    /** Framework ************************************************************************************/
    /*************************************************************************************************/
    function initFramework() {
        // Handle empty search field

        var $searchbutton = $($(".searchbutton").get(0));

        // Save original click event so that we can trigger it only if a search string has been provided
        originalSearchButtonClickEvent = $searchbutton.attr("onclick");
        $searchbutton.removeAttr("onclick");

        $searchbutton.click(function() {
            if ($('input.searchfield').val() == "") {
                // If we're missing a search string we shouldn't perform search
                return false;
            }
            else {
                // A search string has been provided so perform a search
                originalSearchButtonClickEvent();
                return false;
            }
        });
    }

    /** StartPage_Systemair_Market.aspx **************************************************************/
    /*************************************************************************************************/
    function initStartPage_Systemair_Market() {
        // Distribute childs evenly on entire page width 
        var $children = $("#ProductGroups > li");
        var children = $children.length;

        if (children != 6 && children != 0) {
            var childwidth = 100 / children - 0.05; // -0.05 eliminates rounding errors
            $children.css("width", childwidth + "%");
        }

        // Removes dotted divider from last listitem
        $("#ProductGroups li:last-child").css("background-image", "none");

    }

    /** ProductCatalogProductPrintPDF1.aspx **********************************************************/
    /*************************************************************************************************/
    function initProductCatalogProductPrintPDF1() {

        // Description
        $("#chk1").click(function() {
            // If checkbox is checked after click...
            if ($(this).is(':checked')) {
                // ...show area.
                $("#productnavitem1").show();
            }
            else {
                // Else, hide it.
                $("#productnavitem1").hide();
            }
        });

        // Specifications
        $("#chk2").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem2").show();
            }
            else {
                $("#productnavitem2").hide();
            }
        });

        // Diagram
        $("#chk3").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem3").show();
            }
            else {
                $("#productnavitem3").hide();
            }
        });

        // Acoustics
        $("#chk8").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem8").show();
            }
            else {
                $("#productnavitem8").hide();
            }
        });

        // Dimension
        $("#chk4").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem4").show();
            }
            else {
                $("#productnavitem4").hide();
            }
        });

        // Wiring
        $("#chk5").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem5").show();
            }
            else {
                $("#productnavitem5").hide();
            }
        });

        // Reference photo
        $("#chk10").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem10").show();
            }
            else {
                $("#productnavitem10").hide();
            }
        });

        // Air velocity image
        $("#chk11").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem11").show();
            }
            else {
                $("#productnavitem11").hide();
            }
        });

        // Specification
        $("#chk9").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem9").show();
            }
            else {
                $("#productnavitem9").hide();
            }
        });

        // Documents
        $("#chk6").click(function() {
            if ($(this).is(':checked')) {
                $("#productnavitem6").show();
            }
            else {
                $("#productnavitem6").hide();
            }
        });

        // Accessories
        $("#chk7").click(function() {
            if ($(this).is(':checked')) {
                $("#accessoriesnav").show();
            }
            else {
                $("#accessoriesnav").hide();
            }
        });
    }

    /** FinancialReportList1.aspx ********************************************************************/
    /*************************************************************************************************/
    var FinancialReportListConstants = {
        INDEX_PREFIX: 'index',
        BREAKDATE_DAY: 1, // day
        BREAKDATE_MONTH: 5 // month, zerobased
    };

    var getDate = function(dateString) {
        /// <summary>
        /// Returns a Date object from the specified string (YYYY-MM-DD format).
        /// </summary>
        var date = new Date();
        var year = dateString.toString().substr(0, 4);
        var month = dateString.toString().substr(5, 2);
        var day = dateString.toString().substr(8, 2);
        date.setFullYear(year, month - 1, day);

        return date;
    };

    var getYearTable = function(dateArray) {
        /// <summary>
        /// Returns an array with broken year strings ('2008/2009', '2009/2010', etc.)
        /// </summary>
        var yearTable = new Array();
        var currentYear, currentYearBreakDate;
        var l = dateArray.length;
        var brokenYearString;
        var brokenYearStrings = new Array();

        for (var i = 0; i < l; i++) {
            date = dateArray[i];
            currentYear = date.getFullYear();
            currentYearBreakDate = new Date();
            currentYearBreakDate.setFullYear(currentYear, FinancialReportListConstants.BREAKDATE_MONTH, FinancialReportListConstants.BREAKDATE_DAY);

            if (date >= currentYearBreakDate) {
                // the current date is after the breakdate, add a value consisting of the the current year and the next year.
                brokenYearString = currentYear.toString() + '/' + (currentYear + 1).toString();
            }
            else {
                // the current date is before the breakdate, add a value consisting of the previous year and the current year.
                brokenYearString = (currentYear - 1).toString() + '/' + (currentYear).toString();
            }

            if (-1 == jQuery.inArray(brokenYearString, brokenYearStrings)) {
                brokenYearStrings.push(brokenYearString);
            }
        };

        brokenYearStrings.sort().reverse();

        return brokenYearStrings;
    }

    var addClassToReportItems = function(brokenYearString, index) {
        var beginDate = new Date(), endDate = new Date();
        beginDate.setFullYear(brokenYearString.substr(0, 4), FinancialReportListConstants.BREAKDATE_MONTH, FinancialReportListConstants.BREAKDATE_DAY);
        endDate.setFullYear(brokenYearString.substr(5, 4), FinancialReportListConstants.BREAKDATE_MONTH, FinancialReportListConstants.BREAKDATE_DAY);
        endDate.setHours(0);
        endDate.setMinutes(0);
        endDate.setSeconds(0);

        // loop through all report items and add a class spec
        $("#financialreportlist li[class]").each(function(i) {
            var reportDate = getDate($(this).attr("class"));

            if (reportDate >= beginDate && reportDate < endDate) {
                $(this).addClass(FinancialReportListConstants.INDEX_PREFIX + index);
            }
        });
    };

    var initFinancialReportList1 = function() {
        var dates = new Array(); // array with dates of published reports
        $("#financialreportlist li[class]").each(function(i) {
            var classname = $(this).attr("class");
            if (-1 == jQuery.inArray(classname, dates)) {
                dates.push(getDate(classname));
            }
        });

        dates.sort();
        var yearTable = getYearTable(dates);
        var select = document.createElement('select');
        select.setAttribute('id', "selectyear");

        // Loop through the broken years and create select options.
        for (var i = 0, option, value; value = yearTable[i]; i++) {
            option = document.createElement('option');
            option.setAttribute('value', value);
            option.appendChild(document.createTextNode(value.substr(0, 5) + value.substr(7, 2)));
            select.appendChild(option);
            addClassToReportItems(value, i);
        }

        $("#selectyearcontainer").append(select);
        $("#selectyear").change(selectyearChange).change();
    };

    var selectyearChange = function() {
        var $selectedOption = $("#selectyear option:selected");
        currentyear = $selectedOption.text();
        $("#financialreportlist li").hide();
        $("#financialreportlist li." + FinancialReportListConstants.INDEX_PREFIX + this.selectedIndex).show();
    };

    /** SearchResult1.aspx ***************************************************************************/
    /*************************************************************************************************/
    function initSearchResult1() {
        // Set search field values to search phrase
        q = $(".searchfield");
        query = $("#searchquery");
        $(q).attr("value", $(query).html());

        // Format chosen category
        var resultpanel = ".searchresultareacontainer";
        $("ul#categories a").click(function() {
            $(this).parent().siblings().removeClass();
            $(this).parent().addClass("selected");
            return false;
        });

        // Display all
        $("ul#categories a.viewall").click(function() {
            $(resultpanel).show();
            return false;
        });

        // Display the correct result area depending on which chosen category
        $("ul#categories a.cat").click(function() {
            var catindex = $("ul#categories a.cat").index(this);
            $(resultpanel).hide();
            $(resultpanel + ":eq(" + catindex + ")").show();
            return false;
        });

    };

    /** ProductCatalogGroup1.aspx ********************************************************************/
    /*************************************************************************************************/
    function initProductCatalogGroup1() {
        // Remove background-image from last item on row
        $("#productcataloggroup1 .accessorieslist li:nth-child(5n)").css("background-image", "none");

        //Initiate carousel for "Last viewed products"
        $(function() {

            var displayItems = 5;
            var $childrenSize = $(".lastviewedproducts > ul > li").size();

            if ($childrenSize > displayItems) {
                // Display next and prev buttons
                $("#lastviewedproductscontainer .next, #lastviewedproductscontainer .prev").css("display", "block")

                // Start carousel
                $(".lastviewedproducts").jCarouselLite({
                    btnNext: ".next",
                    btnPrev: ".prev",
                    visible: 5,
                    scroll: 3
                });
            }

            // Hide "Last viewed items" area if none is present
            else if ($childrenSize == 0) {
                $(".lastviewedheader").css("display", "none");
                $(".lastviewedproductscontainer").css("display", "none");
            }
        });
    };

    /** ProductCatalogProduct1.aspx ******************************************************************/
    /*************************************************************************************************/
    function initProductCatalogProduct1(hiddenLastSelectedTabClientId) {
        // Initiate tab nav
        initTabNavigation('#productnav', '.productnavitem', 'productnavitem', 'h2', false);
        initTabNavigation('#accessoriesnav', '.accessoriesnavitem', 'accessoriesnavitem', 'h2', false);

        // Remove background-image from last item on row
        $("#productcatalogproduct1 .accessorieslist li:nth-child(5n)").css("background-image", "none");

        //Initiate carousel for "Last viewed products"
        $(function() {

            var displayItems = 5;
            var $childrenSize = $(".lastviewedproducts > ul > li").size();

            if ($childrenSize > displayItems) {
                // Display next and prev buttons
                $("#lastviewedproductscontainer .next, #lastviewedproductscontainer .prev").css("display", "block")

                // Start carousel
                $(".lastviewedproducts").jCarouselLite({
                    btnNext: ".next",
                    btnPrev: ".prev",
                    visible: 5,
                    scroll: 3
                });
            }

            // Hide "Last viewed items" area if none is present
            else if ($childrenSize == 0) {
                $(".lastviewedheader").css("display", "none");
                $(".lastviewedproductscontainer").css("display", "none");
            }
        });

        // Tab navigation
        function initTabNavigation(containerSelector, contentSelector, contentIdPrefix, headingSelector, showHeadings) {

            var hasSelected = false;
            var $list = $(document.createElement('ul')); // The navigation list.
            var navigationElementId = contentIdPrefix + '-tabnav';

            $list.attr('id', navigationElementId);
            $list.addClass('clearbox tabnav');

            $(contentSelector).each(function(j) {
                var selected = $(this).hasClass('selected');
                var currentContentId = $(this).attr("id");

                $(this).find(headingSelector).each(function(i) {
                    var $item = $(document.createElement('li'));
                    var $link = $(document.createElement('a'));
                    var $span = $(document.createElement('span'));
                    var $span2 = $(document.createElement('span'));

                    var text = $(this).attr('title'); // Get the title attribute from the heading element.

                    // If the title attribute is missing, get the text content.
                    if (text == '') {
                        text = $(this).text();
                    }

                    // Add id attribute to li element
                    if (currentContentId.match(/\d{1,}\.{0,}\d{0,}/)) {
                        $item.attr('id', navigationElementId + currentContentId.match(/\d{1,}\.{0,}\d{0,}/));
                    }
                    if (selected) {
                        $item.addClass('selected');
                    }

                    $span.text(text);
                    $link.attr('href', '#' + currentContentId);

                    // Bind a function to each of the a elements click event.
                    $link.bind('click', { currentContentId: currentContentId }, function(e) {
                        $(contentSelector).hide(); // Hide all content elements.
                        $('#' + e.data.currentContentId).show(); // Show the content element that corresponds to the clicked a element.
                        $('#' + navigationElementId + ' > li').removeClass('selected'); // Remove the 'selected' class from all of the navigation links.
                        $(this).parent(0).addClass('selected'); // And add it to the one that was clicked.

                        // Store the last selected tab in a hidden-field so that we can preselect it after postbacks
                        $('#' + hiddenLastSelectedTabClientId).val($(this).parent(0).attr('id'));

                        if (containerSelector = '#productnav') {
                            // Append selected tab to same-range product links
                            $('#sameRange li a').each(function() {                                
                                var selectedTabID = $('#productnavitem-tabnav li.selected').attr('id');
                                var url = $(this).attr('href');
                                var tabStrIndex = url.indexOf("?tab=");
                                if (tabStrIndex != -1) {
                                    url = url.substring(0, tabStrIndex);
                                }
                                $(this).attr('href', url + '?tab=' + selectedTabID);
                            });
                        }
                        return false;
                    });

                    $span2.append($span);
                    $link.append($span2);
                    $item.append($link);
                    $list.append($item);

                    if (!showHeadings) {
                        $(this).css('display', 'none');
                    }
                });

                // Show or hide the content element.
                if (selected) {
                    hasSelected = true;
                    $(this).show();
                }
                else {
                    $(this).hide();
                }
            });

            $(containerSelector).prepend($list);

            if (!hasSelected) // We found no element with class 'selected', so we show the first tab.
            {
                $list.find('li:first').addClass('selected'); // And add the class selected to that tab.
                $(contentSelector + ':first').show(); // show the matching element                
                hasSelected = true;
            }
        };
    };

    return {
        initProductCatalogProductPrintPDF1: initProductCatalogProductPrintPDF1,
        initFinancialReportList1: initFinancialReportList1,
        initProductCatalogGroup1: initProductCatalogGroup1,
        initProductCatalogProduct1: initProductCatalogProduct1,
        initSearchResult1: initSearchResult1,
        initStartPage_Systemair_Market: initStartPage_Systemair_Market,
        selectyearChange: selectyearChange,
        initFramework: initFramework
    };
} ();