/*
Edited: 02 Sept 2011 (MS)
Website: http://www.majestic.co.uk/
Created: 
Author: Snow Valley UX team
=============================
Snow Valley Javascript
=============================
*/

/// <reference path="jquery-1.5.2.min.js" />

jQuery(document).ready(function ($) { // this is for a few files that need to run on dom ready


    /*
    * clearTextfield 
    * Removes value text from the inputfield on focus and puts it back on blur
    * 
    */

    $('.sv-cleartextfield').each(function () {
        var textfield = this;
        var currentValue = $(textfield).val();

        $(textfield).focus(function () {
            if ($(this).val() == currentValue) {
                $(this).val(''); //remove default value on focus
            }
        });

        $(textfield).blur(function () {
            if ($(this).val() == '') {		//put the default value back if nothing has been entered
                $(this).val(currentValue);
            }
        });
    });

    $("#map-search input#getDirectionInput").bind("keydown", function (event) {
        // track enter key
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) { // keycode for enter key
            // force the 'Enter Key' to implicitly click the Update button
            document.getElementById('getDirectionsBtn').focus();
            return false;
        } else {
            return true;
        }
    }); // end of function 
    //Get the carousel HTML ready for the carousel plugin
    if ($("#container #personalisation-left").length) {
        setupCarouselItems();
        jQuery("#browsable").scrollable().navigator();
    }

    // initialize scrollable together with the navigator plugin

    //tabs on the storlacator page
    if ($('.pane', '#pane-container').length && $('ul.tabs').length) {
        $('ul.tabs').idTabs();
    }

    //photo gallery carousel
    /*if ($('.carousel-wrapper').length){
    if ($('li', '.carousel-wrapper').length > 5) {
    var controlDiv = $('<div class="slideControl"/>');
    controlArr = [];
    $('li', '.carousel-wrapper').each( function (i) {
    if (i % 5 == 0) {
    controlBtn = $('<button class="control-'+ i +'">&bull;</button>');
    controlDiv.append(controlBtn);
    }
    controlString = '.slideControl .control-'+ i;
    controlArr.push(controlString);
    });
    console.log(controlArr);
    controlDiv.insertAfter('.carousel-wrapper');
    }
		
    $('.carousel-wrapper').jCarouselLite({
    scroll: 5,
    visible: 5,
    start: 0,
    btnGo: controlArr
    btnNext: ".carousel-wrapper .next",
    btnPrev: ".carousel-wrapper .prev"
    });

    }*/

    //Adding cookie save for gift messages

    jQuery('.gift-checkbox').click(SaveCheckBox);
    jQuery('.gift-textbox').change(SaveText);

    changeButtons();

    if (jQuery('.paging div.paging-options').length) {

        setPanel(jQuery('.paging .show-or-hide-paging-options > a.view-options'), jQuery('.paging p.hide-it a.view-options'), jQuery('.paging div.paging-options'));
        HidePagingOptions();
    }

    function clearTextfield(obj, resetVar) {
        $(obj).each(function () {
            var originalVal = $(this).val();
            if (!resetVar) {
                resetVar = null;
            }
            $(this).focus(function () {
                if (resetVar) {
                    var matchingVals = resetVar == originalVal;
                    if (matchingVals) {
                        $(this).val() == originalVal ? $(this).val('') : null;
                    } else {
                        $(this).val() == resetVar ? $(this).val('') : null;
                    }
                } else {
                    $(this).val() == originalVal ? $(this).val('') : null;
                }
                $(this).val() == originalVal ? $(this).val('') : null;
            }).blur(function () {
                if (resetVar) {
                    $(this).val() == "" ? $(this).val(resetVar) : null;
                } else {
                    $(this).val() == "" ? $(this).val(originalVal) : null;
                }
            });
        }
		);
    }

    $('#checkout #trolley .code-entry .textfield').each(function () {
        clearTextfield('#checkout #trolley .code-entry .textfield', PromoFieldTextObj.defaultText);
    });

    $('#change-store #store-search input.textfield').each(function () {
        clearTextfield('#change-store #store-search input.textfield', SearchFieldTextObj.defaultText);
    });

    // Set up help overlays on Delivery page
    $("#checkout-path").each(function () {
        if ($("#checkout-help").length) { initHelpOverlay(".inner-page-content", "#checkout-help"); }
        if ($("#deliveryCollection-help").length) {
            $('#french-store-select label').each(function () {
                if ($(this).text() == 'Cherbourg') {
                    correctLabel = $(this);
                    return correctLabel;
                }
            });
            correctLabel.append(' <span>' + $('p', '#french-store-select').html() + '</span>');
            $('p', '#french-store-select').remove();
            initHelpOverlay(".inner-page-content", "#deliveryCollection-help");
        }
    });


    //helplink in checkout for security number
    $('.helplink').click(function () {
        $('.securityhelp-overlay').fadeIn('slow');
        return false;
    });

    $('.close').click(function () {
        $('.securityhelp-overlay').fadeOut('fast');
        return false;
    });



    // Functions that are triggered on DOM Ready and after UpdatePanel requests
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () {

        // jQuery UI Tabs for product reviews
        if ($('#reviews').length) {
            $('#reviews #tabs').tabs();
        }

        // jQuery UI buttons
        if ($('#reviews').length) {
            $("a.button", "#reviews").button();
            $("a.button", "#reviews").click(function () { return false; });
        }

        // jQuery UI dialog


        // scrollTo write a review
        $('#reviews p.write-review, .info .review-summary p.write-review').click(function () {
            $('#write-review-form').fadeIn(400);
            $.scrollTo('#write-review-form', 800);
            $('#write-review-form .star-rating').each(function () {
                new StarRating(this, jQuery(this).siblings('select').get(0), $(this).find('.rating'), $(this).attr("id"));
            });
        });

        // Average rating scrollTo reviews section
        $('.info .review-summary p#gotoreviews').click(function () {
            $.scrollTo('#reviews', 800);
        });

        // Cancel write a review
        $('#write-review-form .submit a#cancelreview').click(function () {
            $.scrollTo('#reviews', 400);
            $('#write-review-form').fadeOut(400);
            return false;
        });

        //Hide and show comments
        $('#customer .comments .comments-wrapper, .account #product-list .comments-wrapper, div#reviews div.review div.comments .comments-wrapper, #public-review .comments-wrapper').hide();
        $('#customer .comments a.open, .account #product-list .comments a, div#reviews div.review div.comments a, #public-review div.comments a').click(function () {
            $(this).siblings('.comments-wrapper').slideToggle();
            return false;
        });

        //Hide comments when clicking cancel
        $('.leavecomment .submit a#cancelcomment').click(function () {
            $(this).parents('.comments-wrapper').slideUp();
            return false;
        });

        jQuery('#shopping-trolley')
			.css('cursor', 'pointer')
			.click(function () { window.location = '/checkout'; });

        // fade out basket overlay after set time
        if ($('.add .added-to-basket').length > 0) {
            setTimeout(function () {
                $('.add .added-to-basket').eq(0).fadeOut();
            }, 7000);
        }

        setupTasteFlyouts();
        changeButtons();
        initFlyOuts();

        // Set up help overlays on Trolley page
        $("#trolley").each(function () {
            initHelpOverlay(".inner-page-content", "#deposit-terms1");
            initHelpOverlay(".inner-page-content", "#deposit-terms2");
            initHelpOverlay(".inner-page-content", "#delivery-help-Default");
            initHelpOverlay(".inner-page-content", "#delivery-help-GiftSolutions");
            initHelpOverlay(".inner-page-content", "#delivery-help-EnPrimeur");
            initHelpOverlay(".inner-page-content", "#promo-code-help");

        });

        //		jQuery('.star-rating').each(function () {
        //			new StarRating(this, jQuery(this).siblings('select').get(0), $(this).find('.rating'), '');
        //		});

    });

    $(".basket-header").each(function () {
        stickyPanel(this); // Init the sticky basket header action panel behaviour
    }); // Init the sticky basket header action panel behaviour
    //stickyPanel('.basket-header'); 
    setupTasteFlyouts();



    //jQuery('#promotional-items li.product').normaliseHeight();

    function SaveCheckBox() {
        if ($(this).children()[0].checked) {
            $('.gift-msg').show('fast');
            if ($('.gift-textbox').text() == '')
                saveGiftCookie('-');
            else
                saveGiftCookie($('.gift-textbox').text());
        }
        else {
            $('.gift-msg').hide('fast');
            saveGiftCookie('');
        }
    }

    function SaveText() {
        if ($(this)[0].value == '')
            saveGiftCookie('-');
        else
            saveGiftCookie($(this)[0].value);
    }

    function saveGiftCookie(cookieText) {
        document.cookie = "GiftOptions=" + cookieText + "; path=/";
    }

    function changeButtons() {
        jQuery('.linkbutton').each(function () {
            var button = this;
            var link = jQuery('<a>' + jQuery(button).attr('value') + '</a>')
						.attr('title', jQuery(button).attr('title') || jQuery(button).attr('value'))
			  .click(function () { jQuery(button).click() })
						.keypress(function () { jQuery(button).click() })
			  .mouseover(function () { this.style.color = "#b74b87" })
			  .mouseout(function () { this.style.color = "#96a410" })
			  .css('cursor', 'pointer');

            jQuery(button).removeClass('linkbutton').before(link)
							.hide();
        });
    }

    function initFlyOuts() {

        if (jQuery('#product-list').length > 0) {

            jQuery('#product-list .flyout').hide();
            jQuery('#product-list .flyout-link')
				.click(function (event) {
				    event.preventDefault();
				    var flyout = jQuery(this).parents('.info').find('.flyout');
				    
				    flyout.css({
				        display: "block",
				        position: "absolute",
				        bottom: "5px",
				        right: "auto",
				        top: "auto",
				        left: "80px",
				        zIndex: "9999"
				    });

				    flyout.addClass('cursor').click(function () {
				        jQuery(this).closest('.flyout').hide();
				    });
				    return false;
				});
        };
		
		if (jQuery('#product-grid').length > 0) {

            jQuery('#product-grid .flyout').hide();
            jQuery('#product-grid .flyout-link')
				.click(function (event) {
				    event.preventDefault();
				    var flyout = jQuery(this).parents('.info').find('.flyout');
				    
				    flyout.css({
				        display: "block",
				        position: "absolute",
				        bottom: "5px",
				        right: "0",
				        top: "5px;",
				        left: "5px",
				        zIndex: "9999"
				    });

				    flyout.addClass('cursor').click(function () {
				        jQuery(this).closest('.flyout').hide();
				    });
				    return false;
				});
        };
		
    }

    initFlyOuts();

    // set option panel behaviour
    function setPanel(showLink, hideLink, panel) {
        if ((showLink.length) && (hideLink.length) && (panel.length)) {

            showLink.show();
            hideLink.show();

            showLink.click(function () {
                ShowPagingOptions(false);
                return false;
            });

            hideLink.click(function () {
                ShowPagingOptions(true);
                return false;
            });

        }
    }


    function ShowPagingOptions(makeInvisible) {
        jQuery('.paging div.paging-options').css('visibility', (makeInvisible ? 'hidden' : 'visible')).show();
    }

    function HidePagingOptions() {
        ShowPagingOptions(true);
    }


    function toggleGiftMsgArea() {
        var checkOff = function () {
            if ($('.gift-msg').css('display') == 'none' && $('.gift-msg').slideUp('fast').children('textarea').val() != '') {
                $('.gift-msg').slideUp('fast').children('textarea').val('');
            }
        }
        $('input[type=checkbox]', 'span.checkbox.gift').click(function () {
            $('.gift-msg').slideToggle('fast', checkOff);
        });
    }
    // init toggleGiftMsgArea
    if (jQuery('input[type=checkbox]', 'span.checkbox.gift').length > 0) {
        toggleGiftMsgArea();
    }

    // toggling the Card Issue Date to appear
    function toggleStartDate() {
        var targetSelect = $('select.type[@id*="Card"]');
        var cardType = (targetSelect.length) ? true : false;
        if (cardType == true) {
            targetSelect.change(
				function () {
				    var cardTypeName = $('option:selected', targetSelect).text().trim();
				    var targetCards = (cardTypeName == 'Maestro') ? true : false;
				    var toShow = $('div#card-options');
				    if (targetCards && toShow.css('display') == 'none') {
				        toShow.bGCOrig = toShow.css('background-color');
				        toShow.bGColour = (toShow.css('background-color') == 'transparent') ? "#fff" : toShow.css('background-color');
				        toShow.parentBG = toShow.parent().css('background-color');
				        toShow.slideDown('fast').css('background-color', toShow.parentBG).queue(function () {
				            toShow.animate({ backgroundColor: "#F1F4BF" }, 500, function () {
				                toShow.animate({ backgroundColor: toShow.bGColour }, 500, function () {
				                    toShow.css('background-color', toShow.bGCOrig);
				                });
				            });
				            toShow.dequeue();
				        });

				    }
				    else if (!targetCards) {
				        toShow.slideUp('fast');
				    };
				}
			);
        }
    }
    // init toggleStartDate 
    if (jQuery('select.type', 'div.type').length && jQuery('input, select', 'div#card-options').length) {
        toggleStartDate();
    }

    // show and hide glass and chiller hire items
    function initHireItemsToggle() {

        $("#checkout:not(.complete) #trolley table tr.extras-row div.hire-item").not("").each(function () {

            var container = this;

            // check if any hire items should be shown on load
            var hireItemsInBasket = false;
            $(".qty input.textfield", this).each(function () {
                if ($(this).val() > 0) {
                    hireItemsInBasket = true;
                }
            });

            if ($(container).hasClass('chiller')) {
                $(".qty input.textfield", "div.ice").each(function () {
                    if ($(this).val() > 0) {
                        hireItemsInBasket = true;
                    }
                });
            }

            $("table", this).wrap("<div class='table-wrap hide-for-js'></div>").show();
            if (!hireItemsInBasket) {
                // create a anchor element to associate with table
                $(".toggle strong", this).wrap('<a href="#" class="trigger"></a>');

                // link click behaviour
                $(".toggle", container).click(function () {
                    $(".table-wrap", container).slideDown("fast");
                    $(this).hasClass('chiller') ? $('div.ice').slideDown("fast") : null;
                    slideTrigger = $("a.trigger", this);
                    orginalForm = slideTrigger.html();
                    slideTrigger.remove();
                    $(this).prepend(orginalForm);
                    $(this).unbind('click');
                    return false;
                });
            }
            // if there are hire items in basket, show line items
            if (hireItemsInBasket) {
                $(".table-wrap", container).show();
                $('div.chiller table:visible').length > 0 ? $('div.ice').show() : null;
                //$(".toggle input", container).attr("checked","checked")
            }

        });

    }
    // init show and hide glass and chiller hire items 
    initHireItemsToggle();

    function showThrobber() {
        // to be completed (use existing .loader class?)
    }

    // disable checkout button for when basket is below minimum item threshold
    function disableCheckoutButton(targetButton, title) {

        // create disabled icon
        var disabledIcon = $("<span class='blocked'></span>");
        var newTitle = title || "Disabled";
        disabledIcon.appendTo("#container");

        // add behaviours to checkout button
        $(targetButton)
			.addClass("disabled")
			.attr("title", newTitle)
			.css("cursor", "none")
			.removeAttr('disabled')
			.click(function () {
			    return false;
			})

			.mousemove(function (e) {
			    disabledIcon.css({
			        "display": "block",
			        "left": e.pageX + 2 + "px",
			        "top": e.pageY + 2 + "px"
			    });
			})

			.mouseout(function () {
			    disabledIcon.hide();
			});

    }

    // disable checkout button if trolley alert is shown
    $("#checkout .trolley-alert").each(function () {
        disableCheckoutButton("#checkout .actions li.checkout input", "Proceed to checkout (disabled)");
    });

    // Disabled button on delivery page
    if ($("input.button", "#checkout-path #continue").attr('disabled')) {
        disableCheckoutButton("#checkout-path #continue input.button", "Deliver to this address (disabled)");
    }

    // help overlays
    function initHelpOverlay(container, content) {

        var overlayName = content.substring(1);

        // set up link behaviour - looks for a link to the overlay content and binds the openHelpOverlay function
        $("a[href=" + content + "]").click(function () {
            openHelpOverlay($("." + overlayName));
            return false;
        })

        // set up all the overlay DOM elements
        var modalOverlay = $("<div></div>")
			.addClass("modal")
			.addClass(overlayName);

        var modalOverlayInner = $("<div></div>")
			.addClass("inner")
			.appendTo(modalOverlay);

        var modalOverlayHeading = $("<h2></h2>").html($("h2", content).html()).appendTo(modalOverlayInner);

        var modalOverlayClose = $("<img />")
			.attr({
			    "src": "/assets/majestic/images/btn-close2.png",
			    "title": "Close"
			})
			.addClass("close")
			.click(function () {
			    closeHelpOverlay($(this).parent().parent());
			})
			.appendTo(modalOverlayInner);

        var modalOverlayContent = $("<div></div>")
			.addClass("standard-content")
			.html($(".content", content).html())
			.appendTo(modalOverlayInner);

        modalOverlay
			.appendTo(container)
			.hide();

        // escape keypress closes overlay
        $(document).keyup(function (e) {
            if (e.keyCode == 27) {
                $(".close", modalOverlay).click();
            }
        });

    }

    function openHelpOverlay(overlay) {

        // IE6 doesn't support position:fixed
        if ($.browser.msie && $.browser.version == "6.0") {
            overlay
				.css({
				    "position": "absolute",
				    "left": ($(window).width() - overlay.width()) / 2 + "px",
				    "top": ($(window).height() - overlay.height()) / 2 + $(window).scrollTop() + "px"
				})
			.show();
        } else {
            // A bit nicer for other browsers
            overlay
				.css({
				    "position": "fixed",
				    "left": ($(window).width() - overlay.width()) / 2 + "px",
				    "top": ($(window).height() - overlay.height()) / 2 + "px"
				})
				.show();
        }
    }

    function closeHelpOverlay(overlay) {
        overlay.hide();
    }

    // manage login focus (calls plugin code at the end of this file)
    $('div#sign-in').manageLoginFocus({
        emailTextfield: '.email input.textfield',
        passwordTextfield: 'input[name$=Password]',
        existingCustomerOption: 'input[value=Yes]'
    });

    // slide order detail area in vieworder.aspx page
    $(".web-table", "#checkout").css("display", "none");
    $("#view-more", "#checkout").css("cursor", "pointer");
    $("#view-more", "#checkout").toggle(function () {
        $(".web-table", "#checkout").slideDown('slow');
        $(this).addClass("up").removeClass("down");
    },
		function () {
		    $(".web-table", "#checkout").slideUp('slow');
		    $(this).addClass("down").removeClass("up");
		});

    //setting up the datepicker in the checkout path page delivery
    $("select", "#gift-options").each(function () {
        var dateSelector = $(this);
		Date.format = 'yyyy-mm-dd';
        var DateSet = [];
        $(this).children('option').each(function (e) {
            dateVal = $(this).val();
            if (dateVal != -1) {
                DateSet.push(dateVal);


            }
        });
        dateSelector.datePicker({
			startDate: DateSet[0],
            endDate: DateSet[DateSet.length - 1],
            renderCallback: function ($td, thisDate) {
                var d = thisDate.asString();
                $.inArray(d, DateSet) > -1 ? null : $td.addClass('disabled');

            }
        })
			.bind('dateSelected', function (e, selectedDate, $td) {
			    var dateToSelect = selectedDate.asString();
			    dateSelector.val(dateToSelect);

			}
			);
    }).bind('change', function () {
        $(this).dpSetSelected($(this).val())

    }
		);

    //setting up the datepicker in the checkout path page - collection FRANCE
    $("select", "#collection-date").each(function () {
        var dateSelector = $(this);
        Date.format = 'dd mmm yyyy';
        var DateSet = [];
        $(this).children('option').each(function (e) {
            dateVal = $(this).val();
            if (dateVal != 0) {
                DateSet.push(dateVal);
            }
        });

        dateSelector.datePicker({
            startDate: DateSet[1],
            endDate: DateSet[DateSet.length - 1],
            renderCallback: function ($td, thisDate) {
                var d = thisDate.asString();
                $.inArray(d, DateSet) > -1 ? null : $td.addClass('disabled');
            }
        })
			.bind('dateSelected', function (e, selectedDate, $td) {
			    var dateToSelect = selectedDate.asString();
			    dateSelector.val(dateToSelect);

			}
			);
    }).bind('change', function () {
        $(this).dpSetSelected($(this).val());

    }
		);

    $('#checkout #trolley table td.qty input.textfield').keyup(function () {
        disableCheckoutButton("#checkout .actions li.checkout input", "Please update your trolley before proceeding");
    });

    // My account - store preference

    //show and hide change store options
    $('a#change-store-link').click(function () {
        $('#store-details').slideUp('fast',
				(function () {
				    $('#change-store').slideDown('fast');
				})
			);
        return false;
    });

    $('#cancel-change-store').show();

    $('#button-close-change-store').click(function () {
        $('#change-store').slideUp('fast',
				(function () {
				    $('#store-details').slideDown('fast');
				})
			);
        return false;
    });

    //event handlers for change store         
    $("#store-dropdown").change(function () {
        $("input[name$='ButtonSetStorePreferenceFromSelect']").click();
    });

    $("input[name='radio-store-preference']").click(function () {
        this.blur();
        $("input[name$='ButtonSetStorePreferenceFromRadio']").click();
    });

    $("input[name$='FindAStoreTextBox']").keypress(function (e) {
        if (e.which == 13) {
            $("input[name$='ButtonSearchForStore']").click();
            return false;
        }
    });

    //End my account - store preference

});                                    //end stuff that needs to run on dom ready


function setupTasteFlyouts() {
	jQuery('div.taste-img').hover(function() {
		jQuery('div.popup', this).not(':animated')
			.fadeIn()
			.mouseout(function() {
				jQuery(this).not(':animated')
					.fadeOut();
			});
		}, function() {
			jQuery('div.popup', this).fadeOut();
		})
		.children('div').hide();
}

function StarRating(element, selectElement, ratingElement, productId) { // used for Write a Review

	var elementW		= jQuery(element).width(),						// star-rating element
		offsetLeft		= jQuery(element).offset().left;
		dropdown = selectElement || jQuery(element).siblings().find('select'),
		currentStep = 0,
		selectedStep = 0;

		
	if (dropdown.length == 0) { // don't continue if the select element is not present
		return false;
	};

	var ratingExists = ratingElement.attr('data-ratingexists') === 'True';

	if (ratingExists)
		return true;

	jQuery(element).hover(function() {
	}, function() {
		var ratingExists = ratingElement.attr('data-ratingexists') === 'True';
		if (!ratingExists) 
			jQuery(ratingElement).attr('class', 'rating is-' + selectedStep);
	});

	jQuery(element).mousemove(function (e) {
	    var ratingExists = ratingElement.attr('data-ratingexists') === 'True';

	    if (!ratingExists) {
	        var pos = e.pageX - offsetLeft;

	        currentStep = Math.round(((pos / elementW) * 100) / 20);  // calculate number of stars out of 5
	        
	        jQuery(ratingElement).attr('class', 'rating').addClass('is-' + currentStep); // set the class to show the number of stars
	    }
	});


	jQuery(element).click(function() {
		selectedStep = currentStep; // store the rating the user selects
		jQuery('option', dropdown).eq(currentStep).attr('selected', 'selected'); // set the dropdown so the rating will be posted back to the server
		if (productId) {
			$(element).unbind();
			MajesticReviews.addReviewScore($(this), productId, selectedStep);
			selectedStep = 0;
			currentStep = 0;
		}
		return false;
	}).css('cursor', 'pointer'); 
	return element;
}

/*
	Function: normaliseHeight

	Forces the height of all matched elements to equal the tallest element


*/

var SV = SV || {};

SV.normaliseHeight = function normaliseHeights() { // find the tallest elements and force siblings to the same height
	var elementHeights = [];
	
	this.each(function() {
		elementHeights.push( $(this).height() );
	});
	
	elementHeights.sort(function(a, b) { 
		if (a > b) { return 1 };
		if (a < b) { return -1};
		return 0;
	}).reverse();

	this.css('height', elementHeights[0] + 'px');

	return this;
}

jQuery.fn.extend({
	normaliseHeight: SV.normaliseHeight
});

function stickyPanel(headerPanel) {

	// The floating sticky panel has proven troublesome for IE6 so we're not currently supporting it
	if ($.browser.msie && $.browser.version=="6.0") {
		return;
	}

	function updatePanelOffset(originalPanel, newPanel) {
		$(newPanel)
			.css({
				"width"		: originalPanel.width(),
				"left"		: originalPanel.offset().left - 20		// This number adjusts for the padding
			})
	}

	panel = $(headerPanel).eq(0);		// Find the first panel (only the top one)
	
	// Clone the original action panel, re-insert it and add "sticky" class
	panel
		.clone(true)
			.insertAfter(panel)
			.addClass("sticky")
		;

	// Horizontally position the new panel
	updatePanelOffset(panel, ".sticky");

	// Make the the new panel only appear when the user scrolls down far enough
	$(window).scroll(function(){
		if ($(this).scrollTop() >= panel.offset().top - 20) {
			panel.css("visibility","hidden");
			$(".sticky").fadeIn("fast");
		} else {
		// Otherwise fade out
			$(".sticky").fadeOut("fast");
			panel.css("visibility","visible");
		}
	});

	// This deals with when the browser is resized
	$(window).resize(function(){
		updatePanelOffset(panel, ".sticky");
	});
	
}

function setupCarouselItems(){
		var results =[];
		var x = 0;
		var elements = $("#store-carousel .items").children(".carousel-item");
		$.map(elements, function(i, n){
		$(i).addClass('item' + (x+1));
		
		if((x > 0) && (x%3 === 0)){
			x = x-4;
		}

		if(n%4 === 0){
			results.push(n);
		}
		x++;
		
		});
		$.each(results, function(i,v){
				elements.slice(v, v+4).wrapAll('<div class="row"></div>');
		});
			
		$("#personalisation-left #store-carousel .carousel-item a.pic").hoverIntent({   
			 over: productOver,
			 sensitivity: 7,
			 interval: 200,
			 timeout: 100,   
			 out: productOut  
		});
		
		function productOver() {
			$(".carousel-item").children(".tastings-wrapper").css("display","none");
			$(this).parent(".carousel-item").children(".tastings-wrapper").fadeIn();
		}
		function productOut() {
		return false;
		}
		$("#personalisation-left #store-carousel .carousel-item a.not-available").click(function() {
			return false;
		});
		
		
		$("#personalisation-left #store-carousel a.browse").click(function() { 
		$("#personalisation-left #store-carousel .row .tastings-wrapper").fadeOut(100);
		});
		
		$(".carousel-item .tastings-wrapper").eq(0).show();
		$("#store-carousel").show();
	}

/*
 * manageLoginFocus 
 * Set focus on login fields appropriately for recognised users
 * 
 */

(function($) {
  
  $.fn.manageLoginFocus = function(settings) {  
	var settings = $.extend({}, $.fn.manageLoginFocus.defaultSettings, settings );
	
	return this.each(function() {
	  
	  var emailValue = $.trim( $(settings.emailTextfield).val() );
	  
	  if ( emailValue.length > 0 ) { // if user is recognised
		$.fn.manageLoginFocus.setFocus.apply( $(settings.passwordTextfield).get(0) ); // call set focus with Password field as context
		$.fn.manageLoginFocus.setChecked.apply( $(settings.existingCustomerOption).get(0) ); // call the setChecked method with the option input as the context
	  } else {
		$.fn.manageLoginFocus.setFocus.apply( $(settings.emailTextfield).get(0) );
	  };

	  $(settings.passwordTextfield).focus(function(){
		$.fn.manageLoginFocus.setChecked.apply( $(settings.existingCustomerOption).get(0) ); // call the setChecked method when password field clicked 
	  });
	  
	});
	
  };
  
  $.fn.manageLoginFocus.setFocus = function() {
	$(this).focus();
  };
  
  $.fn.manageLoginFocus.setChecked = function() {
	$(this).attr('checked', 'checked');
  };
  
  $.fn.manageLoginFocus.defaultSettings = {
	emailTextfield          : '.email input.textfield',
	passwordTextfield       : 'input[name=password]',
	existingCustomerOption  : 'input[value=ExistingUser]'
  };

})(jQuery);



jQuery(document).ready(function() {

	/* Function to hide modal address dialogs on checkout pages.  */
	$('input.close[src="/assets/majestic/images/btn-close2.png"]').click(function() {
		$("div.modal").hide();
	});

	// Set handler on the Title drop down list
	$('input.specify-other').each(function() {
		showOrHideOtherTextfield(this);
	});

});

// Show or hide the textfield for the 'Other' option in  dropdown menus
function showOrHideOtherTextfield(textfield) {
	var dropdown = $('select', $(textfield).parent()).get(0);

	if (!dropdown) { // exit if can't find a sibling dropdown to trigger the textfield
		return false;
	};

	function showOrHideTextfield() {
		if ($('option:selected', dropdown).val() == 'Other') {
			$(textfield).show().focus();
		} else {
			$(textfield).hide();
		}
	}

	$(dropdown).change(showOrHideTextfield);

	showOrHideTextfield(); // set correctly for initial page load
}

 ////////////////////////////////////////////////
// add carousel to recently viewed

$(function() {
	
	var i_recently_viewed_children_num, i_visible_products, $recently_viewed, $prev_next_arrows;
	
	$recently_viewed = $(".recently-viewed");
	$prev_next_arrows = $( '.recently-viewed a.prev, .recently-viewed a.next' );
	i_visible_products = 4; // The number of products that should be visible in the carousel
	i_recently_viewed_children_num = $recently_viewed.find( 'li' ).length; // The number of recently viewed products

	// Only activate the carousel if there are more products than can be seen
	if( i_recently_viewed_children_num === 0 ){
	
		$recently_viewed.hide();
		$prev_next_arrows.hide();
	
	}else if( i_visible_products < i_recently_viewed_children_num ){
	
		$recently_viewed.jCarouselLite({
			btnNext: ".recently-viewed .next",
			btnPrev: ".recently-viewed .prev",
			visible: i_visible_products,
			scroll: 1
		});
		
		// Over write the width of .recently-viewed as the default styling applied by the plugin is incorrect
		$recently_viewed.css({'width':'776px'});
		
	}else if( i_visible_products > i_recently_viewed_children_num ){
		
		$prev_next_arrows.hide();
	}
	
});

// tell a friend overlay
$(function() {
	$('a#show-tell-a-friend').click(function(e) {
		e.preventDefault();
		//show loader
		$("a#show-tell-a-friend").after('<img id="ajax-loader-taf" alt="Please wait" title="Please wait" src="/assets/majestic/images/ajax-loader-taf.gif" />');
		//reload the overlay's src
		$('div#tell-a-friend-overlay>iframe').attr('src', $('div#tell-a-friend-overlay>iframe').attr('src'));
		//show as dialog
		$('div#tell-a-friend-overlay').dialog({
			minWidth: 610,
			resizable: false,
			modal: false,
			minHeight: 300
		}).parent('.ui-dialog').attr('id', 'tell-a-friend-overlay-wrapper');
		$("img#ajax-loader-taf").remove();
		return false;
	});

	$("a#more-about-labels-link").click(function(e) {
		e.preventDefault();
		$("div#more-about-labels").dialog({ minWidth: 610, resizable: false, minHeight: 300 }).parent('.ui-dialog').attr('id', 'more-about-labels-wrapper');
	});
});

// tell a friend overlay - iframe dynamic resize

$(function(){
	$('#tell-a-friend-overlay').find('iframe').load(function()
	{
		var selectedFrame = this;
		selectedFrame.style.height = (selectedFrame.contentWindow.document.body.offsetHeight + 20) + 'px';
	});
});

// Setup
function setupGridList() {
	$('.product:not(.recommended):not(.new-arrival):not(.best-seller)').each(function(){
		$(this).find('.offer-price.discounted').insertBefore($(this).find('.was-price'));
		$(this).find('.marketing-flashes').append($(this).find('.product-medal li').addClass('medal'));
		$(this).find('.product-medal').hide();
	});
	$('.medal').parent().addClass('large');
}


// List-Grid View Switching

$(function () {

    // Setting Up Cookie
    if (!$.cookie('chosen-view')) {
        $.cookie('chosen-view', 'list', { path: '/' });
    }
    var chosenView = $.cookie('chosen-view');

    // Grid View
    function gridView() {
        if ($('#product-list').html() != null) {
            changeView('list', 'grid');
            $('#product-grid .product .info').each(function () {
                $(this).find('.marketing-flashes').before($(this).find('.more-links'));
                $('<div class="grid-spacer"></div>').insertBefore($(this).find('h4'));
                $(this).find('.grid-spacer').append($(this).find('h4')).append($(this).find('.more-links'));
            });
            // IE Hacks for < 9 Lacking CSS3
            if ($.browser.msie && $.browser.version < 9) {
                $('#product-grid .product:nth-child(3n), #product-grid .product:last-child').addClass('borderless');
                $('#product-grid .product .add p.offer-price:not(.discounted)').attr('style', 'position:relative; bottom:3px;');
            }
        }
    }

    // List View
    function listView() {
        if ($('#product-grid').html() != null) {
            changeView('grid', 'list');
            $('#product-list .product .info').each(function () {
                $(this).find('.grid-spacer').replaceWith($(this).find('.grid-spacer').html());
                $(this).find('.marketing-flashes').after($(this).find('.more-links'));
            });
        }
    }

    // Shared components
    function changeView(from, to) {
        $.cookie('chosen-view', null);
        $.cookie('chosen-view', to, { path: '/' });
        $('#product-' + from).attr('id', 'product-' + to);
        $('#' + to + '-view-button').attr('class', 'disabled');
        $('#' + from + '-view-button').removeAttr('class');
    }

    // Don't display buttons if: typed search, mixed cases, gift solution
    var pageURL = window.location.pathname.toLowerCase();
    if (pageURL.indexOf('keyword') == -1 && pageURL.indexOf('category-is-mixed+cases') == -1 && pageURL.indexOf('category-is-gift+solutions') == -1 && pageURL.indexOf('account') == -1) {
        $('.list-grid-buttons').append('<img alt="list view" id="list-view-button" src="/assets/Majestic/Images/list-view-btn.gif" /><img alt="grid view" id="grid-view-button" src="/assets/Majestic/Images/grid-view-btn.gif" />');
        $('#' + chosenView + '-view-button').addClass('disabled');
        // If Grid, Setup Grid View
        if (chosenView == 'grid') {
            gridView();
        }
        // Bind Click Events
        $('#grid-view-button').click(function () { gridView(); });
        $('#list-view-button').click(function () { listView(); });
    } else if (pageURL.indexOf('account') != -1) {
        $('.product').each(function () {
            $(this).find('.marketing-flashes').after($(this).find('.more-links'));
        });
    }

    setupGridList();
});

// Functions that need to be re-called when Update Panels refresh the Product List/Grid
function pageLoad(sender, args){
	if (args.get_isPartialLoad()){
		// Setup
		setupGridList();
		$('#product-grid .product .info').each(function(){
			$(this).find('.marketing-flashes').before($(this).find('.more-links'));
			$('<div class="grid-spacer"></div>').insertBefore($(this).find('h4'));
			$(this).find('.grid-spacer').append($(this).find('h4')).append($(this).find('.more-links'));
		});
		// IE Hacks for < 9 Lacking CSS3
		if($.browser.msie && $.browser.version < 9){
			$('#product-grid .product:nth-child(3n), #product-grid .product:last-child').addClass('borderless');
			$('#product-grid .product .add p.offer-price:not(.discounted)').attr('style','position:relative; bottom:3px;');
		}
		$('.flyout').hide();
		$('#single-product-detail.new-design.majestic .add input.button').attr('src','/assets/majestic/images/btn-add-to-basket_large.gif');
		$('#single-product-detail.new-design.france .add input.button').attr('src','/assets/wineandbeerworld/images/btn-add-to-basket_large.gif');
	}
}

// Fix height issue with product bundle page
$(function(){
	var bundle = $('#single-product-detail.bundle');
	bundle.height((bundle.find('.add').height()+70));
});

$(function(){
	$('#single-product-detail.new-design.majestic .add input.button').attr('src','/assets/majestic/images/btn-add-to-basket_large.gif');
	$('#single-product-detail.new-design.france .add input.button').attr('src','/assets/wineandbeerworld/images/btn-add-to-basket_large.gif');
});

(function($){
 $.fn.extend({
  	customStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
		return this.each(function() {
			var currentSelected = $(this).find(':selected');
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));			
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				// selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
			selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
				// Thanks to Juarez Filho & PaddyMurphy
			});
		});
	  }
	}
 });
})(jQuery);

$(document).ready(function(){
	$('.filters .filter-options select').customStyle();
});
