var pageIsLoading = false;
var pageHash = window.location.hash;

// START OF DOCUMENT.READY
// Put all on load events in here
$(document).ready(function () {
    disableControls();
    jQuery.easing.def = "easeInOutExpo";
    shortenBreadcrumb({ maxWidth: 600 });
    setUpCatMenu();
    setUpTopMenu();

    $(':first-child').addClass('first-child');
    $(':last-child').addClass('last-child');

    $("input.datepicker").datepicker({ dateFormat: 'dd/mm/yy' });

    readyAlsoAfterAjax();

    // Moved from default.master start
    disableAutoCompletes();
    LoadPageByHash();
    $('#hidAjaxHash').val(window.location.hash);
    // Moved from default.master end

//    var checkHash = setInterval(function () {
//        if (window.location.hash != pageHash && pageIsLoading == false) {
//            //alert(pageHash);
//            LoadPageByHash();
//            pageHash = window.location.hash;
//            if (window.location.hash == "") {
//                pageLoading();
//                window.location.reload();
//            }
//        }
//    }, 500);

    //alert("Content hidden");
});
// END OF DOCUMENT.READY


function productTabs() {
    // Product tabs highlighting
    $('ul.tabs li:first-child a').addClass('current');
    $('ul.tabs a').click (function (e) {
        e.preventDefault();
        $(this).parent('li').siblings('li').children('a').removeClass('current');
        $(this).addClass('current');
    });
    // End product tabs highlighting
}

function readyAlsoAfterAjax() {
    contentLinks();
    slidersLoaded = false;
    initProductSlider();
    initProductFilterVertical();
    ssiCarousel();
    pageHash = window.location.hash;
    //alert("Pagehash set: " + pageHash);
    //pageLoaded();
    
    //SetProductGridWidth();
}

function fixSliderHeight() {
    var prodSlider = $('#coda-slider-1');
    var startHeight = prodSlider.find('.panel').eq(0).innerHeight();
    prodSlider.css({ 'height': startHeight + 'px' });
}

var slidersLoaded = false;
function initProductSlider() {
    if (slidersLoaded) return false;
    sliderCount = 1;
    slidersLoaded = true;
    $('.coda-slider.productSlider').unbind().codaSlider({
        dynamicArrows: false,
        dynamicTabs: false
    });
    $('.coda-slider.productSlider .panel').show();
}

function UpdateSessionScreenResolution() {
    ajaxPost('/system/services/Session.asmx/UpdateScreenResolution',
    { Width: $(window).width(), Height: $(window).height() },
    function (res) {
        //
    });
}

function LoadPageByHash(lang) {
    hash = window.location.hash;
    if (hash == "") {
        pageLoaded();
        return false;
    } else if (hash.substring(0, 9) == "#product/") {
        DisplayProduct(hash.substring(9), true, lang);
    } else if (hash.substring(0, 8) == "#search/") {
        SetOptions(hash.substring(8), lang);
    } else if (hash.substring(0, 6) == "#page/") {
        DisplayPage(hash.substring(6), lang);
    } else {
        pageLoaded();
        return false;
    }
    return true;
    //alert("Loaded by hash");
}

function DisplayPage(Code, lang) {
    pageLoading();
    if (lang === undefined) lang = _LanguageCode;
    ajaxPost('/system/services/Search.asmx/DisplayPage',
            { Code: Code, LanguageCode: lang },
            function (res) {
                var obj = JSON.parse(res.d);
                if (obj.Redirect) {
                    top.location.href = obj.Redirect;
                } else {
                    if (obj.Content === undefined) return false;
                    window.location.hash = '#page/' + Code;
                    $('#hidAjaxHash').val(window.location.hash);
                    $('#content').html(obj.Content);
                    $('#divTopHeader').html(obj.Header);
                    $('#breadcrumbCell').html(obj.Breadcrumb);
                    document.title = obj.PageTitle;
                    pageLoaded();
                }
            });
}

function DisplayProduct(_ProductCode, ResetSearch, lang) {
    pageLoading();
    if (ResetSearch === undefined) ResetSearch = true;
    if (lang === undefined) lang = _LanguageCode;
    ProductCode = _ProductCode;
    ret = false;
    var data = {
        ProductCode: ProductCode,
        ResetSearch: ResetSearch,
        LanguadeCode: lang
    }
    $.ajax({
        type: "POST",
        async: false, // need to know the return value of this function.
        url: "/system/services/Product.asmx/DisplayProduct",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (res) {
            var obj = JSON.parse(res.d);
            if (obj.Redirect) {
                top.location.href = obj.Redirect;
            } else {
                if (obj.Content === undefined) return false;
                if (obj.ProductsAlreadySeenCookieValue !== undefined) {
                    var exdate = new Date();
                    exdate.setDate(exdate.getDate() + 365);
                    document.cookie = "ProductsAlreadySeen=" + escape(obj.ProductsAlreadySeenCookieValue) + ";path=/;expires=" + exdate.toUTCString();
                }
                window.location.hash = '#product/' + _ProductCode;
                $('#hidAjaxHash').val(window.location.hash);
                $('#content').html(obj.Content);
                $('html, body').animate({ scrollTop: 0 }, 'slow');
                ProductPageReady();
                readyAlsoAfterAjax();
                $('#divTopHeader').html(obj.Header);
                $('#breadcrumbCell').html(obj.Breadcrumb);
                document.title = obj.PageTitle;
                ret = true;
                pageLoaded();
            }
        }
    });
    return ret;
}

function ProductPageReady() {
    //pageLoaded();
    //$('.coda-nav, div.productBox').css({ visibility: 'visible' });
    $('h2#pageTitle').remove();
    productTabs();
}

function form_is_modified(oForm) {
    var el, opt, hasDefault, i = 0, j;
    while (el = oForm.elements[i++]) {
        switch (el.type) {
            case 'text':
            case 'textarea':
            case 'hidden':
                if (!/^\s*$/.test(el.value) && el.value != el.defaultValue) return true;
                break;
            case 'checkbox':
            case 'radio':
                if (el.checked != el.defaultChecked) return true;
                break;
            case 'select-one':
            case 'select-multiple':
                j = 0, hasDefault = false;
                while (opt = el.options[j++])
                    if (opt.defaultSelected) hasDefault = true;
                j = hasDefault ? 0 : 1;
                while (opt = el.options[j++])
                    if (opt.selected != opt.defaultSelected) return true;
                break;
        }
    }
    return false;
}


function setUpCatMenu(){
    // Category Menu stuff
    setActiveCategory();
    $('#catMenu > ul > li > a').click(function (e) {
        if ($(this).next('ul').size() > 0) {
            e.preventDefault();
            $('#catMenu > ul > li > ul').not($(this).next('ul')).slideUp();
            $(this).next('ul').slideToggle();
        }
    });

    $('#catMenu li.level2 a').not('.active').hover(function () {
        $(this).css({ 'color': $(this).closest('li.level1').css('color') });
    }, function () {
        $(this).css({ 'color': '#393939' });
    });

    //Hover Intent stuff
    var CatMenuConfig = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
        interval: 50, // number = milliseconds for onMouseOver polling interval    
        over: function () {
            $(this).siblings('li').not(this).children('ul').hide();
            $(this).children('ul').show(150);
        },
        timeout: 500, // number = milliseconds delay before onMouseOut    
        out: function () {
            $(this).children('ul').hide(150);
        }
    };

    $('#catMenu > ul > li > ul > li > ul').css({'display':'none', 'left':'auto'})
        .closest('li').hoverIntent(CatMenuConfig);
    // End Category Menu stuff
}

function setUpTopMenu() {
    // Create slide effect for top menu

    var topMenuConfig = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
        interval: 50, // number = milliseconds for onMouseOver polling interval    
        over: function () {
            $(this).siblings('li').not(this).children('ul').slideUp(150);
            $(this).children('ul').slideDown(150);
        },
        timeout: 500, // number = milliseconds delay before onMouseOut    
        out: function () {
            $(this).children('ul').slideUp(150);
        }
    };
    $('div#toolbar ul#topLinks > li').hoverIntent(topMenuConfig)
         .children('ul').css({ 'left': 'auto', 'display': 'none' });

    $('div#toolbar ul#topLinks a').click(function (e) {
        $('div#toolbar ul#topLinks ul').slideUp();
    });
}

/*
function SetProductGridWidth() {
    // Product grid tips
    if ($('#prodGridRight > div').size() > 0){
        //$('#prodGridRight').remove();
        $('#prodGridLeft').addClass('prodGridLeft').css();
        $('#prodGridRight').addClass('prodGridRight').css();
    }
}*/

function setActiveCategory(){
    var currentURL = location.href.substring(location.href.indexOf('/products'));
    
    var level1URL = $('#breadcrumb ul li:nth-child(2) a').attr('href');
    if (level1URL == undefined) level1URL = currentURL;
    
    var level2URL = $('#breadcrumb ul li:nth-child(3) a').attr('href');
    if (level2URL == undefined) level2URL = currentURL;
    
    var level3URL = $('#breadcrumb ul li:nth-child(4) a').attr('href');
    if (level3URL == undefined) level3URL = currentURL;
    
    $('#catMenu a[href=' + level1URL + ']').next('ul').show();
    
    var level2lnk=$('#catMenu a[href=' + level2URL + ']');
    level2lnk.addClass('active').css({'color' : level2lnk.closest('li.level1').css('color')});
    
    var level3lnk=$('#catMenu a[href=' + level3URL + ']');
    level3lnk.addClass('active').css({'color' : level3lnk.closest('li.level1').css('color')});
}

function shortenBreadcrumb(options){
    /*  
        Shortens the breadcrumb to a specified width by removing the text from one list item
        at a time and replacing it with "..." - accepts an options object as an optional
        parameter with two options:
            shortenBreadcrumb({
                breadcrumb : $('div#breadcrumb > ul'),
                maxWidth : 725
            });
            
        The first is the selector for the breadcrumb ul, the second is the maximum width you
        want it to be.
    */

    var breadcrumb = $('div#breadcrumb > ul');
    var maxWidth = $('div#breadcrumb').innerWidth();
    
    if (options != undefined){
        if (options.breadcrumb != null) { breadcrumb = options.breadcrumb; }
        if (options.maxWidth != null) { maxWidth = options.maxWidth; }
    }
    
    var levelCount = breadcrumb.find('li').size();
    var shortEnough = false;
    var totalWidth;
    while (shortEnough == false) {
        totalWidth = 0;
        breadcrumb.children('li').each (function(){
            totalWidth += $(this).outerWidth(true);
        });
        if (totalWidth > maxWidth){
            var li = breadcrumb.children('li').not('.short').eq(1);
            li.addClass('short');
            li.children('a').attr('title', li.children('a').html());            
            li.children('a').html('...');
        }
        else {
            shortEnough = true;
        }
    }
}

function ssiCarousel(){
    var prevBtn = $('<a href="#" class="carouselPrev">Previous</a>');
    var nextBtn = $('<a href="#" class="carouselNext">Next</a>');
    
    $('div.carousel').append(prevBtn);
    $('div.carousel').append(nextBtn);
    
    $('div.carousel > div.productGrid').addClass('carouselInner');
    listWidth = $('div.carousel > div.productGrid > div.product').eq(0).outerWidth(true);
    listCount = $('div.carousel > div.productGrid > div.product').size();
    current = 1;
    
    //Set carousel margins for first and last item in view
    var rightProd = $('div.carousel > div.productGrid > div.product').eq(2);
    var firstProd = $('div.carousel > div.productGrid > div.product').eq(0);
    firstProd.css({marginLeft : '35px'});
    rightProd.css({marginRight : '43px'});

    //alert(typeof (carouselTimer));
    if (typeof (carouselTimer) != 'undefined') {
        clearInterval(carouselTimer);
    }

    carouselTimer = setInterval(function() {
        if (current < listCount - 2) {
            current += 1;
        } else {
            current = 1;
        }
        moveCarousel();
    }, 5000);
    $('div.carousel > div.productGrid').addClass('carouselInner').width((listCount * listWidth) + 71);

    nextBtn.click(function(e) {
        clearInterval(carouselTimer);
        e.preventDefault();
        if (current < listCount - 2) {
            current += 1;
        } else {
            current = 1;
        }
        moveCarousel();
    });

    prevBtn.click(function(e) {
        clearInterval(carouselTimer);
        e.preventDefault();
        if (current > 1) {
            current -= 1;
        } else {
            current = listCount - 2;
        }
        moveCarousel();
    });

    var carouselHeader = $('div.carousel > div.productGrid > h3');
    $('div.carousel').prepend(carouselHeader);
}

function moveCarousel() {
    $('div.carousel > div.productGrid').animate({
        left : -((current - 1) * listWidth) + "px"
    }, 500);
    var leftProd = $('div.carousel > div.productGrid > div.product').eq(current-1);
    var rightProd = $('div.carousel > div.productGrid > div.product').eq(current+1);
    var firstProd = '';
    $('div.carousel > div.productGrid > div.product').not(leftProd)
                                                     .not(rightProd)
                                                     .animate({marginRight: '10px', marginLeft: '0px'});
    leftProd.animate({marginLeft: '35px', marginRight: '10px'});
    rightProd.animate({marginLeft: '0px', marginRight: '43px'});
}

//function getSearchNavigateUrl(source, eventArgs) {
//    $('#txtToolbarSearch').val('');
//    Code = eventArgs.get_value();
//    arr = Code.split("_");
//    switch (arr[0]) {
//        case "PRODUCT":
//            DisplayProduct(arr[1]);
//            location.hash = "#product/" + arr[1];
//            break;
//        case "NAVIGATOR":
//            SetOptions('navigator,' + arr[1] + ',' + arr[1]);
//            location.hash = "#search/navigator," + arr[1];
//            break;
//        default:
//            DisplayPage(arr[1]);
//            location.hash = "#page/" + arr[1];
//    }
//}

// Product Filter (Vertical)
function initProductFilterVertical() {
    var visibleItems = 5;
    $('#prodFilterVertical ul.filter').each(function () {
        var filters = $(this).children('li');
        if (filters.size() > visibleItems) {
            filters.slice(visibleItems).hide();
            $(this).append($('<li class="more"><a href="#">'+_filterViewMore+'</a></li>'))
        }
        else {
            $(this).children('li.more').remove();
        }
    }).find('li.more a').unbind().toggle(function (e) {
        e.preventDefault();
        $(this).html(_filterViewLess).parent().prevAll().show(300);
    }, function (e) {
        e.preventDefault();
        $(this).html(_filterViewMore).closest('ul').children('li:not(.more)').slice(visibleItems).hide(300);
    });


}

function contentLinks() {
    $('#content p a').not('p#homeButtons a').each(function () {
        if ($(this).children('img').size() <= 0) {
            $(this).addClass('contentLink');
        }
    });
}

function pageLoading() {
    //alert("Loading...");
    pageIsLoading = true;
    $('#content').css('visibility', 'hidden');
    $('.loading').show();
    $('#imgAjax').show();
}

function pageLoaded() {
    //alert("Loaded");
    pageIsLoading = false;
    $('#content').css('visibility', 'visible');
    $('.loading').hide();
    $('#imgAjax').hide();
    doCufon();
}

function doCufon() {
    //This function is blank unless overridden in a page using Cufon.  Basically it will call cufon again on that page after the content is loaded.
}