
$(document).ready(function() {

    $(".help").live('click', function() {
        url = $(this).attr('href');
        if (url != '#') {
            display_overlay(url, '', '');
        }
        return false;
    });

    /* because these dropdowns are in update panels: re-attach customStyle(); */
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() {
        //$(".customStyleSelectBoxInner").hide();
        $("#productSearchControl ul li span").hide();
        $('#productSearchControl li .select').customStyle();

        $(".findstore-dropdowns ul li span").hide();
        $('.findstore-dropdowns .select').customStyle();
    });

    /* find a store promobox */
    $('.field-neareststore-city').val($('.MaskCity').val());
    $('.field-neareststore-postcode').val($('.MaskPostcode').val());

    $('.field-neareststore-city').focus(function() {
        var inputBoxes = $(this).parents(".box-storeform").children("P").children(".inputtext");
        inputBoxes.each(function() {
            MaskStoreLocatorFields('focus', $(this));
        });
    });
    $('.field-neareststore-city').blur(function() {
        var inputBoxes = $(this).parents(".box-storeform").children("P").children(".inputtext");
        inputBoxes.each(function() {
            MaskStoreLocatorFields('blur', $(this));
        });
    });


    $('.field-neareststore-postcode').focus(function() {
        var inputBoxes = $(this).parents(".box-storeform").children("P").children(".inputtext");
        inputBoxes.each(function() {
            MaskStoreLocatorFields('focus', $(this));
        });
    });
    $('.field-neareststore-postcode').blur(function() {
        var inputBoxes = $(this).parents(".box-storeform").children("P").children(".inputtext");
        inputBoxes.each(function() {
            MaskStoreLocatorFields('blur', $(this));
        });
    });

    function MaskStoreLocatorFields(type, input) {
        var textVal = input.val();
        var originalVal = input.attr('originalVal');

        if (type == 'focus') {
            if (originalVal == undefined || (textVal == originalVal)) {
                input.attr('value', '');
            }

            if (originalVal == undefined) {
                input.attr('originalVal', textVal);
            }

        }
        else {

            if (textVal == '') {
                input.attr('value', originalVal);
            }

            if (textVal != '' && originalVal != undefined && textVal != originalVal) {
                input.attr('storelocator-param', textVal);
            }
        }
    }

    if ($(document).attr('profile') == null) {
        var profile = new ProfileService();
        profile.loadItems();
        $(document).attr('profile', profile);
    }

    $('.help').click(function() {
        url = $(this).attr('href');
        if (url != '#') {
            display_overlay(url, '', '');
        }
    });

    $(window).scroll(function() {
        // fix for the menu bottom because somehow the document height is not calculated by js correctly
        resize_calculate();
    });

    /* // find a store promobox */


    // Modal popups
    if ($('.box-layer-mydulux').length > 0) {
        $('.box-layer-mydulux').hide();
        $('#box-layer-message').hide();
    }


    if (page == 'popup') {
        $('.body-background').css('z-index', '-10');
    }

    if (page != 'popup' && page != 'mydulux') {
        if ($.cookie('bodybackground')) {
            var x = $.cookie('bodybackground');
            var bodybackground = backgrounds[Math.max(x - 1, 0)];
        } else {
            var x = Math.floor(Math.random() * backgrounds.length);
            var bodybackground = backgrounds[x];
            $.cookie('bodybackground', x, {
                path: '/',
                expires: null
            });
        }

        if ($.browser.msie && $.browser.version == 6.0) {
            $('body').addClass('ie6-bg');
        } else {
            $('<div id="body-background-image"><img class="body-background" src="' + bodybackground + '" alt="" /></div>').appendTo('body');
        }
    }

    if (page != 'popup') {
        background_width = $('.body-background').width();
        background_height = $('.body-background').height();
        body_background();
    }

    if (page != 'home') {
        $('.box-search').fadeIn(700);
        $('.box-breadcrumbs').fadeIn(700);
        $('.box-menuswitch').fadeIn(700);
        $('.box-pagefooter').show();
        $('.box-pagecontent').show();
    }
    //$('.box-page').fadeIn(700);
    //$('.box-pagefooter').fadeIn(2000);

    empty_search = 0;
    $('.search-value').focus(function() {
        if (empty_search == 0) {
            $('.search-value').attr('value', '');
        }
        empty_search = 1;
    });
    $('.search-value').blur(function() {
        if ($('.search-value').val() == '') {
            $('.search-value').val('Search...');
            empty_search = 0;
        }
    });

    $('.select').customStyle();

    $('.box-menu ul:first-child ul').hide();
    $('.box-menu ul:first-child li.active ul').show();
    $('.box-menu ul:first-child li.active').addClass('selected');

    $('.box-menu ul, .box-menu ul li').addClass('level1');
    $('.box-menu ul ul, .box-menu ul li ul li').addClass('level2');
    $('.box-menu ul ul, .box-menu ul li ul li').removeClass('level1');
    $('.box-menu ul ul ul, .box-menu ul li ul li ul li').addClass('level3');

    var timer_menu;

    $('.box-menu ul.level1 li.level1 a, .box-menu ul.level1 li.level2 a').mouseover(function() {
        clearTimeout(timer_menu);
        var test = $(this);
        timer_menu = setTimeout(function() {
            expand(test);
        }, 400, this);
        //expand(this);
    });

    $('.searchstore a').click(function() {

        var inputBoxes = $(this).parents(".promobox").find(".inputtext");
        var qs = '';
        var link = $(this).attr('href');

        inputBoxes.each(function() {
            var qsElement = CreateStoreLocatorQueryString($(this));

            if (qsElement != '' && qs == '') {
                if (link.indexOf("?") != -1) {
                    qs += '&';
                }
                else {
                    qs += '?';
                }
            }

            if (qsElement != '' && qs != '') {
                qs += qsElement + '&';
            }

        });

        url = $(this).attr('href') + qs;
        if (url != '#') {
            display_overlay(url, 680, 516);
        }
        return false;
    });

    function CreateStoreLocatorQueryString(input) {
        var qs = '';
        var qsParamName = input.attr('originalVal');
        var qsParamVal = input.attr('storelocator-param');
        if (qsParamVal != undefined && qsParamVal != '') {
            qs = qsParamName + '=' + qsParamVal;
        }
        return qs;
    }

    $('.searchProduct a').live('click', (function(event) {
        url = $(this).attr('href')

        display_overlay(url, 680, 514);
        event.preventDefault();
        return false;
    }));
    $('input[name=search-submit]').click(function() {
        $(this).attr('src', '/_Layouts/Fusion/medias/common/background-search-submit-over.png');
        //  TODO replace url with 'real' one.
        window.location = links['searchResults'] + '?k=' + $('input[name=search-value]').val();
        return false;
    });
    /*$('.search-submit').mouseover(function () {/search/pages/default.aspx?k=
    $(this).attr('src', 'medias/common/background-search-submit-over.png');
    });*/
    $('.search-submit').mouseout(function() {
        $(this).attr('src', '/_Layouts/Fusion/medias/common/background-search-submit.png');
    });

    $('a.socialprint').click(function() {
        window.print();
        return false;
    });

    $('a.JQ_userregistration').click(function() {
        url = $(this).attr('href');
        if (url != '#') {
            display_overlay(url, 652, 406);
        }
        return false;
    });

    $('a.socialemail').click(function() {
        url = $(this).attr('href');
        if (url != '#') {
            display_overlay(url, 668, 514);
        }
        return false;
    });

    $('a.socialfacebook').click(function() {
        url = window.location.href;
        $(this).attr('href', 'http://www.facebook.com/sharer.php?u=' + url);
        $(this).attr('target', '_blank');
    });

    var auto_slide;

    $('.box-menu').mouseleave(function() {
        //auto_slide = setTimeout(slide_menu_auto, 5000);
    });

    // MENU STUFF
    var bShouldBeOpen = 0;
    var bMenuLockedOpen = 0;
    var bIsTransitioning = 0;


    //Handles all menu animations
    function setMenu() {

        var src_temp = '';

        //Is the menu already transitioining?
        if (bIsTransitioning == 0) {

            //Flag as IsTransitioning
            bIsTransitioning = 1;

            //Grab the existing menu image for flip
            src_temp = $('.box-menuswitch h3 a').find('img').attr("src");

            if (src_temp) {
                //Shoukld the menu be open or closed?
                if (bShouldBeOpen == 1) {

                    //Switch menu
                    $('.box-menuswitch h3 a').find('img').attr("src", src_temp.replace('-off', '-on'));

                    //Slide the menu open
                    $('.box-menu').slideDown(750, function() {
                        //Only animate the logo if the mouse is still over
                        if (bShouldBeOpen == 1) {
                            $('.logo-akzonobel').fadeIn(500);
                            bIsTransitioning = 0;
                        } else {
                            //required state has changed to closed
                            bIsTransitioning = 0;
                            setMenu();
                        }
                        resize_calculate();
                        manage_logo('calculate');
                    });

                } else {
                    //Hide the logo
                    $('.logo-akzonobel').hide();
                    //Close the menu
                    $('.box-menu').slideUp(600, function() {
                        //always let the menu close, and change to orange button
                        bShouldBeOpen = 0;
                        bIsTransitioning = 0;
                        $('.box-menuswitch h3 a').find('img').attr("src", src_temp.replace('-on', '-off'));
                    });
                }
            }
        }
    }

    // MOUSE OVER
    $('.box-menuswitch h3 a').mouseover(function() {
        bShouldBeOpen = 1;
        setMenu();
    });

    // MOUSE LEAVE
    $('.box-menusidebar').mouseleave(function() {
        //Load the var from the cookie
        bMenuLockedOpen = $.cookie('bMenuLockedOpen');

        if (bMenuLockedOpen != 1) { 							//if entire menu hasn't already been locked open by a set cookie
            if ($('.box-menusidebar .active-page')[0]) { 	//and if a sub page is marked as active
                bMenuLockedOpen = 1; 					//set the entire menu to stay open
            }
        }

        if (bMenuLockedOpen == 1) {
            bShouldBeOpen = 1;
        } else {
            bShouldBeOpen = 0;
        }

        setMenu();

        // sections within the menu
        //don't close it if it contains an item called active page!
        if (!$('.box-menusidebar .active-page')[0]) { 								// if no sub-pages are marked as active
            $('.box-menu ul.level1 ul.level2').slideUp(500, function() {
                $('.box-menu ul.level1 li.level1').removeClass('active');
            });
        }
    });

    // MOUSE CLICK
    $('.box-menuswitch h3 a').click(function() {

        //Load the var from the cookie
        bMenuLockedOpen = $.cookie('bMenuLockedOpen');

        //Toggle the menu lock
        if (bMenuLockedOpen == 1) {
            bMenuLockedOpen = 0;
            bShouldBeOpen = 0;
            $.cookie('bMenuLockedOpen', 0, {
                path: '/',
                expires: null
            });
        } else {
            bMenuLockedOpen = 1;
            bShouldBeOpen = 1;
            $.cookie('bMenuLockedOpen', 1, {
                path: '/',
                expires: null
            });
        }

        setMenu();
    });

    // --

    //defined in functions.js
    //var duluxLoaded = false;
    // var duluxLoading = false;
    //var basketLoaded = false;
    // var basketLoading = false;	

    // ----- start mybasket

    $('.box-footermy-basket, .box-footermy .footer-mybasket').hover(function(e) {
        if (!basketLoaded) {
            // var x = e.pageX - this.offsetLeft;
            // var y = e.pageY - this.offsetTop;
            // alert(this.offsetLeft + ' ' + this.offsetTop + ', ' + x + ' ' + y);

            basketLoaded = true;
            $('<div class="box-layer-mybasket"></div>').appendTo('.display-footermy');
            url = calls['layer-mybasket'];
            url = url.replace('[profile_id]', $.cookie('profile_id'));
            $.get(url, function(data) {
                $('.box-layer-mybasket').html(data);
                update_basket_data('footer');
                if (page == 'basket-page') {
                    update_basket_data('page');
                }
                //$('.mybasket-popup img').load(function() {
                height_layer = $('.mybasket-popup').height() - 50;
                $('.box-layer-mydulux').animate({ top: 0 }, null, null, function() {
                    $('.box-layer-mydulux').remove();
                    $('.box-footermy-dulux').show();
                    duluxLoaded = false;
                });
                $('.box-footermy-basket').hide();
                $('.box-layer-mybasket').animate({ top: -height_layer });
                //});
            });
        }
        return false;
    });

    $('.mybasket-popup').live('mouseleave', function() {
        $('.box-layer-mybasket').animate({ top: 0 }, null, null, function() {
            $('.box-layer-mybasket').remove();
            $('.box-footermy-basket').show();
            basketLoaded = false;
        });
        return false;
    });

    // ----- end mybasket

    // ----- start mydulux

    $('.box-footermy-dulux, .box-footermy .footer-mydulux').hover(function() {
        myDulux_popup_hover();
    });

    $('#mydulux-popup').live('mouseleave', function() {
        myDulux_popup_leave();
    });

    // ----- end mydulux

    $('.select-more-collections').change(function() {
        if ($('.select-more-collections').val() != '') {
            select_redirect($('.select-more-collections').val());
        }
        return false;
    });

    $('.buttonimage').mouseover(function() {
        src = $(this).find('img').attr("src");
        if (src) {
            $(this).find('img').attr("src", src.replace('-off', '-on'));
        }
    });
    $('.buttonimage').mouseout(function() {
        src = $(this).find('img').attr("src");
        if (src) {
            $(this).find('img').attr("src", src.replace('-on', '-off'));
        }
    });
    $('.buttonimage').click(function() {
        src = $(this).find('img').attr("src");
        if (src) {
            $(this).find('img').attr("src", src.replace('-on', '-click'));
        }
    });
    $('.buttonimage').mouseleave(function() {
        src = $(this).find('img').attr("src");
        if (src) {
            $(this).find('img').attr("src", src.replace('-click', '-off'));
        }
    });

    $('.inputimage').mouseover(function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-off', '-on'));
    });
    $('.inputimage').mouseout(function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-on', '-off'));
    });
    $('.inputimage').click(function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-on', '-click'));
    });
    $('.inputimage').mouseleave(function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-click', '-off'));
    });

    $('.linkimage').mouseover(function() {
        href = $(this).attr("href");
        $(this).attr("href", href.replace('-off', '-on'));
    });
    $('.linkimage').mouseout(function() {
        href = $(this).attr("href");
        $(this).attr("href", href.replace('-on', '-off'));
    });
    $('.linkimage').click(function() {
        href = $(this).attr("href");
        $(this).attr("href", href.replace('-on', '-click'));
    });
    $('.linkimage').mouseleave(function() {
        href = $(this).attr("href");
        $(this).attr("href", href.replace('-click', '-off'));
    });

    //--- 

    $('.box-footermy .inputimage').live('mouseover', function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-off', '-on'));
    });

    $('.box-footermy .inputimage').live('mouseout', function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-on', '-off'));
    });

    $('.box-footermy .inputimage').live('click', function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-on', '-click'));
        setTimeout('window.location.replace("' + $(this).parent().attr("href") + '")', 500);
        return false;
    });

    $('.box-footermy .inputimage').live('mouseleave', function() {
        src = $(this).attr("src");
        $(this).attr("src", src.replace('-click', '-off'));
    });

    //--- 

    // AUTO EXPAND IF COOKIE SET
    //Load the var from the cookie
    bMenuLockedOpen = $.cookie('bMenuLockedOpen');
    if (bMenuLockedOpen == 1) {
        bShouldBeOpen = 1;
    } else {
        bShouldBeOpen = 0;
    }
    setMenu();

    if (page != 'popup') {
        resize_calculate();

        var window_width = $(window).width();
        var window_height = $(window).height();
        $(window).resize(function() {
            body_background();
            manage_logo('calculate');
            resize_calculate();
            window_width = $(window).width();
            window_height = $(window).height();
        });

        $(window).change(function() {
            body_background();
            window_width_new = $(window).width();
            window_height_new = $(window).height();
            if ((window_width != window_width_new && window_width != window_width_new - 16) || window_height != window_height_new) {
                //debug(window_width);
                //debug(window_width_new);
                resize_calculate();
                window_width = $(window).width();
                window_height = $(window).height();
            }
        });
    }

    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        DD_belatedPNG.fix('.box-menuswitch img');
        DD_belatedPNG.fix('.more a, .display-logo a');
        DD_belatedPNG.fix('.footer-mydulux, .footer-mybasket');
        DD_belatedPNG.fix('.box-search .search-value, .display-search p');
        DD_belatedPNG.fix('.box-pageheader');
        DD_belatedPNG.fix('.box-socialmedia a');
        DD_belatedPNG.fix('.box-page');
        DD_belatedPNG.fix('.a_socialButton-cut, a_socialButton-email, a_socialButton-print, a_socialButton-facebook, a_socialButton-sharethis');
        DD_belatedPNG.fix('.box-pagefooter .box-footermy-dulux, .box-pagefooter .box-footermy-basket, .box-pagefooter .mybasket-popup .header, .box-pagefooter .mybasket-popup .content, .box-pagefooter #mydulux-popup .header, .box-pagefooter .mydulux-popup .content');
    }
    if ($('.box-menusidebar .active-page')[0]) { 											//if a page is marked as active
        $('.box-menusidebar .active-page').parent('ul').show(); 							//expand menu section to reveal active page
        $('.box-menusidebar .active-page').parent('ul').parent('li').addClass('active'); 	//set class of active section to apply styling
        bShouldBeOpen = 1;
        setMenu();
    }

    showRecentlySavedItemsMyDulux();
});

function expand(obj) {
    var checkElement = $(obj).next();
    if (checkElement.is('ul') && checkElement.is(':visible')) {
        manage_logo('calculate');
        return false;
    }

    if (checkElement.is('ul') && !checkElement.is(':visible')) {
        //if ((!checkElement.is(':visible'))) {
        if ($.browser.msie) {
            if ($.browser.version == "7.0") {
                $('.box-menu ul.level1 ul.level2').css("maxHeight", $('.box-menu ul.level1 ul.level2').height() + "px");
            }
        }
        //
        hasLevel3 = checkElement.hasClass('level3');
        if (hasLevel3 == false) {
            $('.box-menu ul.level1 ul.level2').slideUp(1000, function() {
                if ($.browser.msie) {
                    if ($.browser.version == "7.0") {
                        // alert($(this).html());
                        $(this).css("maxHeight", "none");
                    }
                }
            });
        } else {
            $('.box-menu ul.level1 ul.level3').slideUp(1000, function() {
                if ($.browser.msie) {
                    if ($.browser.version == "7.0") {
                        // alert($(this).html());
                        $(this).css("maxHeight", "none");
                    }
                }
            });
        }
        //$('.box-menu ul:first-child ul ul').show();
        if (hasLevel3 == false) {
            $('.box-menu ul.level1 li.level1').removeClass('active');
            $(obj).parent().addClass('active');
        }
        checkElement.slideDown(750, function() {
            manage_logo('calculate');
        });
        //$('li.active ul').slideDown(1200);
        return false;
    } else {
        manage_logo('calculate');
    }
    return false;
}

function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}
function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

