/*
This little script handles the homepage banners and menu.
Hovering over a link changes what is displayed in the menu
*/
var cycle_counter = 0;
var cycle_interval = 0;
var cycle_duration = 15000;
var cycle_max = 1;
var cycle_current = 0;


$(document).ready(function() {
    /*Re-position menu elements to prevent right-most elements from dis-appearing off the right of the window.
    Also make sure that padding to the left and right of each menu item text is allocated according to how
    much 'spare' space is available (spare space is distributed evenly across all menu items).*/
    var cumulativeWidth = 0;
    var totalWidth = $("#cat-nav").width();
    var categoryPad = 0;

    $("#cat-nav>li").each(function() {
        cumulativeWidth += $(this).width();
    });
    var categoryCount = $("#cat-nav>li").size();

    var spareWidth = totalWidth - cumulativeWidth;
    $("#cat-nav>li").each(function() {
        categoryPad = $("a", this).css("padding-left");
    });

    if (spareWidth > 0) {
        categoryPad = parseInt(categoryPad) + (parseInt(parseInt(spareWidth / categoryCount) / 2).toFixed(0) - 1);
    }
    cumulativeWidth = 0;
    $("#cat-nav>li").each(function() {

        var subWidth = $(".sub", this).width();
        $("a", this)
                .css("padding-left", categoryPad + "px")
                .css("padding-right", categoryPad + "px")
        if (cumulativeWidth + subWidth > totalWidth) {
            $(".sub", this)
                    .css("margin-left", totalWidth - (cumulativeWidth + subWidth) - 62 + "px");
        }
        cumulativeWidth += $(this).width();
    });

    /*Initialising carousel*/
    $('#carousel').jcarousel({});
    $('#promotions').jcarousel({ scroll: 1 });
    $('#highest-rated').jcarousel({ scroll: 1 });
    $('#most-wanted').jcarousel({ scroll: 1 });
    $('#we-recommend').jcarousel({ scroll: 1 });
    $('a[rel=external]').attr('target', '_blank');

    /* navigation append HOME*/
    /*if ($("#cat-nav li a[title='Home']").length==0) {
    $("#cat-nav li").removeClass("first-child");
    $("#cat-nav li:first").before("<li class='first-child'><a href='/en-gb/' title='Home'>Home</a></li>");
    }*/

    /*Page Appends
    */
    /*Modal-background */
    $("#page").before("<div id='modal-background'/>");

    /* close button for the overlays */
    $(".horizontal-accordian-large, #product-overlay h1").before("<span class='close' title='Close'>Close</span>");

    /*Horizontal Accordian */
    maxWidth = 170;
    minWidth = 15;

    //    $("#ctl00_cphBodyContent_placeeordertop").css({ background: "yellow", border: "3px red solid" });

    //    $("#ctl00_cphBodyContent_placeeordertop").click(function() {
    //        $('#datacash-acs-frame').height = '500';
    //        alert('test');
    //    })



    $("ul.horizontal-accordian li").removeClass("selected");
    $("ul.horizontal-accordian li:first-child").addClass('selected');
    $("ul.horizontal-accordian li").hover(function() {
        $(this).parent().children('li.selected').removeClass('selected').animate({ width: minWidth + "px" }, { queue: false, duration: 400 });
        $(this).animate({ width: maxWidth + "px" }, { queue: false, duration: 400 }).addClass('selected');
    });

    /*Horizontal Accordian Large */
    maxWidthLarge = 415;
    minWidthLarge = 15;

    $('ul.horizontal-accordian').each(function(index, item) {
        var overlay = $(item).next('.accordian-overlay');
        if (overlay.size() === 0) return;
        overlay.attr({ overlayindex: index });
        overlay.css({ display: 'none' }).remove();
        overlay.find('ul li').removeClass('selected');
        overlay.find('ul li:first').addClass('selected');

        $('#body').append(overlay);
        $(item).children('li').each(function(n, o) {
            $(o).click(function() {
                var leaf = $('#body .accordian-overlay[overlayindex=' + overlay.attr('overlayindex') + '] li:eq(' + n + ')');
                leaf.hover();
                $('#body .accordian-overlay[overlayindex=' + overlay.attr('overlayindex') + '], #modal-background').fadeIn('fast');
                return false;
            });
        });
    });

    $("#body .accordian-overlay li").hover(function() {
        $(this).parent().children('li.selected').removeClass('selected').animate({ width: minWidthLarge + "px" }, { queue: false, duration: 400 });
        $(this).animate({ width: maxWidthLarge + "px" }, { queue: false, duration: 400 }).addClass('selected');
    });

    /*Close*/
    $(".accordian-overlay span.close, #modal-background").click(function() {
        $('.accordian-overlay, #modal-background').fadeOut("fast");
    });

    /* 
    Input Boxes blur 
    */
    $('#site-search').focus(function() {
        if ($(this).attr('value') == 'Enter Keyword / Code') $(this).attr('value', '');
    });
    $('#site-search').blur(function() {
        if ($(this).attr('value') == '') $(this).attr('value', 'Enter Keyword / Code');
    });


    /*
    This function initialises the home-page banner cycling.
    */
    cycle_max = $('#home-body-banner-menu li').each(function(index, li) {
        $('#banner-link' + index).mouseover(function() {
            clearInterval(cycle_interval);
            show_banner(index);
        })
    }).length;
    cycle_interval = setInterval(cycle_banners, cycle_duration);

    /*Info product-pop*/
    $("#home-body-banner a.info").click(function() {
        $('#product-overlay, #modal-background').fadeIn("slow");
    });

    $("#product-overlay span.close, #modal-background").click(function() {
        $('#product-overlay, #modal-background').fadeOut("fast");
    });

    /* Gift Options */
    $("#GiftOptionSelection").hide("fast");
    $("#rbGiftYes").click(function() { checkRb() });
    $("#rbGiftNo").click(function() { checkRb() });
    /* Fall Back */
    $('#home-body-banner-menu').show();

    /* Address Control on Checkout pages */
    $("#checkoutaddress").hide("fast");

});


/*
This function displays the banner requested in argument (integer from 1 to n)
*/
function show_banner(number) {
    if (number !== cycle_current) {
        $('#banner-link' + cycle_current).removeClass('select');
        $('#banner-' + cycle_current).fadeOut('slow');
        $('#banner-link' + number).addClass('select');
        $('#banner-' + number).fadeIn('slow');
        cycle_current = number;
    }
}
/* This function hides all the banners */
function hide_all_banners() {
    var b = '';
    var l = '';
    for (var i = 0; i < cycle_max; i++) {
        b = b + ((b.length !== 0) ? ', ' : '') + '#banner-' + i;
        l = l + ((b.length !== 0) ? ', ' : '') + '#banner-link' + i;
    }
    $(b).css('display', 'none');
    $(l).removeClass('select');
}
/* This function cycles through the banners */
function cycle_banners() {
    $('#banner-link' + cycle_current).removeClass('select');
    show_banner((++cycle_counter % cycle_max));
}

/* This function is used to hide/show gift option section on delivery page */
function checkRb() {
    if ($("input[name='rbGift']:checked").val() == "yes") {
        //show the hidden div
        $("#GiftOptionSelection").show("fast");
    }
    else {
        //otherwise, hide it
        $("#GiftOptionSelection").hide("fast");
    }
}

/* This function is used to hide/show register option section on registration page */
function showHideRegRb() {
   
    if ($("input[name='rbRegister']:checked").val() == "yes") {
        //show the hidden div
        $("#passwordSection").show();
    }
    else {
        //otherwise, hide it
        $("#passwordSection").hide();
    }
}

/* Internet Explorer 6 <button> fix; stop the submission of all
 * the button elements within the form and only have the element
 * clicked submitted.  This shouldn't interfere with any other
 * click-handlers as it determines which button was clicked when
 * the form is submitted.
 */
if ($.browser.msie && $.browser.version <= 6) {
	$(document).ready(function() {
		$('button').click(function() {
			if (this.form === null) return true;
			$.each(this.form.elements, function(index, item) {
				if (item.tagName.toLowerCase() === "button")
					item.userclick = false;
			});
			// NOTE: Could also set the value properly .. add the assignment
			//       for the value ('value': this.getAttributeNode('value'))
			this.userclick = true;
			return true;
		});

		$('form').submit(function() {
			$.each(this.elements, function(index, item) {
				if (item.tagName.toLowerCase() === "button" && typeof item.userclick !== 'undefined')
					item.disabled = !item.userclick;
				return true;
			});
		});
	});
}


var Omniture = {
    SendEvent: function(eventId, eventName) {
        if (typeof s_account == "undefined") {
            return;
        }

        s = s_gi(s_account);
        if (typeof s == "undefined") {
            return;
        }

        s.linkTrackVars = "events";
        s.linkTrackEvents = eventId;
        s.events = eventId;

        s.tl(this, 'o', eventName);
    },
    SubmitAddToBasketSingle: function(pid, vid, cid, qty, scopen) {
        if (typeof s_account == "undefined") {
            return;
        }

        s = s_gi(s_account);
        if (typeof s == "undefined") {
            return;
        }
        var events = "";
        s.linkTrackVars = "products,events,eVar3,eVar31";
        if (scopen == "True") {
            s.linkTrackEvents = "scAdd,scOpen";
            s.events = "scAdd,scOpen";
            events = "scAdd,scOpen";
        }
        else {
            s.linkTrackEvents = "scAdd";
            s.events = "scAdd";
            events = "scAdd";
        }
        s.eVar31 = vid;
        s.products = cid + ";" + pid + ";;;;eVar3=" + cid + "|eVar31=" + vid + "|events=" + events;
        s.tl(this, 'o', "Add To Basket");
    },
    RemoveFromBasketSingle: function(pid, vid, qty) {
        if (typeof s_account == "undefined") {
            return;
        }
        s = s_gi(s_account);
        if (typeof s == "undefined") {
            return;
        }
        s.products = ";" + pid;
        s.linkTrackVars = "products,events";
        s.linkTrackEvents = "scRemove";
        s.events = "scRemove";
        s.tl(this, 'o', "Remove From Basket");
    }
}
