Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// Hover Intent
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:5,interval:100,timeout:100};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

// Metadata
(function($){$.extend({metadata:{defaults:{type:'class',name:'metadata',cre:/({.*})/,single:'metadata'},setType:function(type,name){this.defaults.type=type;this.defaults.name=name},get:function(elem,opts){var settings=$.extend({},this.defaults,opts);if(!settings.single.length)settings.single='metadata';var data=$.data(elem,settings.single);if(data)return data;data="{}";if(settings.type=="class"){var m=settings.cre.exec(elem.className);if(m)data=m[1]}else if(settings.type=="elem"){if(!elem.getElementsByTagName)return undefined;var e=elem.getElementsByTagName(settings.name);if(e.length)data=$.trim(e[0].innerHTML)}else if(elem.getAttribute!=undefined){var attr=elem.getAttribute(settings.name);if(attr)data=attr}if(data.indexOf('{')<0)data="{"+data+"}";data=eval("("+data+")");$.data(elem,settings.single,data);return data}}});$.fn.metadata=function(opts){return $.metadata.get(this[0],opts)}})(jQuery);

//Cookie Plugin
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.preloadImages = function() {
	for(var i = 0; i < arguments.length; i++) {
		$("<img>").attr("src", arguments[i]);	
	}
};

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        var copy_from = $(this).clone(true);
        $(to).replaceWith(copy_from);
        $(this).replaceWith(copy_to);
    });
};

/*
 *Global namespace for Dig Deep
 */
var DIGDEEP = {};
DIGDEEP.personalise = {};
DIGDEEP.feeds = {};
DIGDEEP.cookie = {};
DIGDEEP.locker = {};
DIGDEEP.ui = {};

DIGDEEP.feeds.parseXml = function (xml) {  	/* Convenience function for parsing xml in Internet Explorer */
	if (jQuery.browser.msie) {  
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(xml);  
		xml = xmlDoc;  
	}  
	return xml;  
} 

DIGDEEP.feeds.getNews = function(callback) {

	//This will update the sports news section. Currently the box is hidden in css. The box needs updating and then made visible.
	//On error just show the box with it's backup content.
	
	var news = [];
	
	$.ajax({
		url: '/pws/client/feeds/news.xml',
		//url: '/pws/client/feeds/news_articles.xml',
		cache: false,
		dateType: 'xml',
		success: function(data, textStatus, XMLHttpRequest) {
			
			//Populate the news array with each article as a raw js object
			$.each($(data).find('article'), function(i, article) {
				
				var article = {
					date: $(article).find('date').text(),
				 	title: $(article).find('title').text(),
					image: $(article).find('image').text(),
					content: $(article).find('content').text(),
					articleLink: $(article).find('link').text(),
					category: $(article).find('category').text()
				};
				
				news.push(article);
			});
			
			if(typeof callback === 'function') {
				callback(news);
			}
		}
	});
	
	return news;		//Return feeds, empty array if the was an error
};

DIGDEEP.cookie.deleteEntry = function(entry, cookie) {
	var cookie = cookie;
	if(cookie !== null && cookie !== 'undefined' && cookie !== '') {
		cookie = cookie.split(',');
		for(var i = 0; i < cookie.length; i++) {
			if(entry == cookie[i]) {
				cookie.remove(i);
				break;
			}
		}
	}
	return cookie.join(',');
};


(function($) {
	
	$.fn.pngfix = function() {

		if(!($.browser.msie && $.browser.version === "6.0")){
			return $(this);
		}
		
		return this.each(function(i, n) {
			var imageSrc = $(n).attr("src");
			var imageHeight = $(n).attr("height");
			var imageWidth = $(n).attr("width");
			var imageFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + imageSrc + ", sizingMethod='crop')";
			$(n).wrap('<span></span>');
			$(n).wrap('<span></span>');
			$(n).parent().parent().css({
				'filter': imageFilter,
				'height': imageHeight,
				'width': imageWidth,
				'display': 'block',
				'margin': '0 0 3px 0'
			});
			
			$(n).parent().css('display','none');
		});
	};
	
	//This is to fix the hidden product images
	$.fn.pngfixWithCSS = function() {

		if(!($.browser.msie && $.browser.version === "6.0")){
			return $(this);
		}
		
		return this.each(function(i, n) {
			var imageSrc = $(n).attr("src");
			var imageHeight = parseInt($(n).css("height"), 10);
			var imageWidth = parseInt($(n).css("width"), 10);
			var imageFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + imageSrc + ", sizingMethod='crop')";
			$(n).wrap('<span></span>');
			$(n).wrap('<span></span>');
			$(n).parent().parent().css({
				'filter': imageFilter,
				'height': imageHeight,
				'width': imageWidth,
				'display': 'block',
				'margin': '0 0 3px 0'
			});
			
			$(n).parent().css('display','none');
		});
	};
	
})(jQuery);

// ---------- Mini Basket ----------
// Gets minibasket counter and product information. Also handles minibasket actions

function loadMiniBasket(){
	
	$.ajax({
		url: "/pws/ssnMiniBasketCount.jsp",
		cache: false,
		success: function(html){
			$("div#mini_basket span.mini_basket_qty").html(html);
		}
	});
	
	var minibasket = $('div#mini_basket');
	var minibasketDetails = $('div#mini_basket_details');
	minibasketDetails.empty();
	
	var minibasketMiddle = $('<div id="mini_basket_details_middle"></div>');
	var minibasketContent = $('<div id="mini_basket_details_content"><img src="/pws/images/loading.gif" alt="Loading basket" height="31" width="31" class="loading_image" /></div>');
	minibasketDetails.append('<div id="mini_basket_details_top"></div>');
	minibasketMiddle.append(minibasketContent);
	minibasketDetails.append(minibasketMiddle);
	minibasketDetails.append('<div id="mini_basket_details_bottom"></div>');
	
	minibasketDetails.append('<div id="minibasket_overlay"></div>');
	minibasketDetails.append('<img id="minbasket_overlay_progress" src="/pws/images/loading.gif" alt="Removing product" height="31" width="31" class="loading_image" />');
	
	minibasket.append(minibasketDetails);
	
	var miniBasketButton = $("div#mini_basket a.view_basket span");
	var miniBasketButtonBg = $("div#mini_basket a.view_basket");

	minibasket.hoverIntent(
		function(){
			
			miniBasketButton.addClass("hover");
			miniBasketButtonBg.addClass("hover");
			minibasketDetails.slideDown("fast", function() {
				minibasketContent.basketWidget('evaluateScroll');
			});
		},
		function(){
			miniBasketButton.removeClass("hover");
			miniBasketButtonBg.removeClass("hover");
			minibasketContent.basketWidget('stop');
			minibasketDetails.slideUp("fast");
		}
	);
	
	$.ajax({
		url: "/pws/ssnMiniBasketProducts.jsp",
		cache: false,
		success: function(html){
			minibasketContent.html(html);
			minibasketContent.find('img.pngfix').pngfixWithCSS();
			//alert(minibasketContent.find('img.pngfix').length);
			minibasketContent.basketWidget();
		}
	});
}

// ---------- IE6 Fixes ------------

function ieNavigationFix(){
	if($.browser.msie) {
		var dropdownMenuItems = $("li#main_navigation_store_home, li#main_navigation_icons_all");
		var menuItems = $("li.level_1");
		$.each(dropdownMenuItems, function(i, n) {
			$(this).hover(function(){
				$(this).addClass('ie6bg');
				$(this).children("div").css('display', 'block');
			}, function(){
				$(this).removeClass('ie6bg');
				$(this).children("div").css('display', 'none');
			});
		});
		
		menuItems.hover(function(){
			$(this).addClass('hover');
		}, function(){
			$(this).removeClass('hover');
		});
	}
}

// Inputs with the class clearValue have their value cleared when focussed
function clearInputValue(){
	$("input.clear_value").focus(function() {
		if(this.value == this.defaultValue) {
			this.value = "";
		}
	}).blur(function() {
		if(!this.value.length) {
			this.value = this.defaultValue;
		}
	});
}

function address_elements_change(){

var id = $("select#country_list").val();

$("select#country_list").change(function(){
	  var field_status = $("<div class='field_status'>&nbsp;</div>");																			 
		$("select#country_list").parents("form").removeClass().addClass($(this).val()+" validate");
		
		if($("body.ly_paymentdetails").length >0) {
			$("select#country_list").parents("form").addClass("payment_details");
		}
					    
	  switch($(this).val()){
				case 'GB':
					$("div#state_element_US").hide();	
				 	$("div#state_element_JP").hide();	
				 	$("div#county_element_GB").show();	
					$("div#state_element_JP input").removeClass("validate").addClass("ignore").removeAttr("name");
					$("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");
					$("div#postcode_lookup_wrapper").css("display","block");
					break;
				case 'IE':
					$("div#county_element_GB").show();
					$("div#state_element_US").hide();
					$("div#state_element_JP").hide();		
					$("div#state_element_JP input").removeClass("validate").addClass("ignore").removeAttr("name");
					$("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");
					$("div#postcode_lookup_wrapper").css("display","none");
					break;
				case 'USA':
				 	$("div#county_element_GB").hide();
				 	$("div#state_element_JP").hide();	
				 	$("div#state_element_JP input").removeClass("validate").addClass("ignore").removeClass("name");
					$("div#state_element_US select").removeClass("ignore").addClass("validate");
					$("div#state_element_US").show();	
					$("div#state_element_US select").after(field_status).attr("name","state");
					$("div#postcode_lookup_wrapper").css("display","none");
					break;	
				case 'JP':
				 	$("div#county_element_GB").hide();
				 	$("div#state_element_US").hide();	
					$("div#state_element_JP input").removeClass("ignore").addClass("validate");
				 	$("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");
				 	$("div#state_element_JP").show();
					$("div#state_element_JP input").after(field_status).attr("name","state");
					break;	
				default:
					$("div#state_element_US").hide();	
				 	$("div#state_element_JP").hide();
				 	$("div#county_element_GB").show();	
					$("div#state_element_JP input").removeClass("validate").addClass("ignore").removeAttr("name");;
					$("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");;
					$("input[name=country]").val($(this).val());
					$("div#postcode_lookup_wrapper").css("display","none");
					break;
			}
				$("input[name=country]").val($(this).val());
	});
}

// --- Updates Slide Down Effect ---

(function($){
	$.fn.updatesDropDown = function(e, n, i){
		
		var that = $(this);
		
		return this.each(function(){
			
			var $updateSection = $(this);
			var $siblingSections = $updateSection.siblings(".update_section");
			var $container = $updateSection.find("div.update_section_cont");
			var $trigger = $updateSection.find(".trigger");
			var $close = $updateSection.find("p.close_btn");
			
			$container.data("hidden",true);
			
			function openSection(){
				/* This branch was added as a quick fix for ie7. It wouldn't show the text in the paragraph tags */
				if($(document.documentElement).hasClass('ie7')) {
					$container.slideDown("slow", function() {
						$(this).find('p').css('display', 'block');
					}).data("hidden",false);
				} else {
					$container.slideDown("slow").data("hidden",false);
				}
				
				$siblingSections.slideUp("slow");				
			}
			
			function closeSection(){
				$container.slideUp("slow").data("hidden",true);	
				$siblingSections.slideDown("slow");
			}			
			
			$trigger.click(function(){
				if($container.data("hidden")){
					openSection();
				} else {
					closeSection();
				}	
			});		
			
			$close.click(function(){
				closeSection();
			});	
		});
	};
	
	$.fn.newsDropDown = function(container) {
		
		return this.each(function() {
			
			var that = $(this);
			var title = $(this).find('div.article_heading');
			var slideUp = $(this).find('span.slideup');
			var article = $(this).find('div.article');
			var animating = false;
			
			$(this).addClass('dropdown');
			
			title.click(function() {
				if(!animating) {
					animating = true;
					if(that.hasClass('dropdown')){
						that.removeClass('dropdown');
						article.slideDown('slow', function(){
							container.jScrollPane();
							animating = false;
						});
						
					} else {
						that.addClass('dropdown');
						article.slideUp('slow', function(){
							container.jScrollPane();
							animating = false;
						});	
					}
				}
			});
			
			slideUp.click(function(){
				if(!animating) {
					animating = true;
					that.addClass('dropdown');
					article.slideUp("slow", function(){
						container.jScrollPane();
						animating = false;
					});
				}
			});	
		});
		
		return false;
		var container = $(this);
		var heading = container.find('.article_heading');//.find('p.title');
		
		heading.addClass("dropdown");
		
		$("span.slideup").click(function(){
			$(this).parent().parent().find(".article_heading").addClass("dropdown");
			$(this).parent().slideUp("slow", function(){
				container.jScrollPane();
			});
		});			
		
		heading.find('p.title').click(function () {

			var articleHeader = $(this).parent('.article_heading');
			var article = $(this).parent().find("div.article");
			
			if(articleHeader.is(".dropdown")){
				articleHeader.removeClass("dropdown");
				article.slideDown("slow", function(){
					container.jScrollPane();
				});
				
			} else {
				articleHeader.addClass("dropdown");
				article.slideUp("slow", function(){
					container.jScrollPane();				
				});	
			}
		});
	};
	
	$.widget('ui.sliderWidget', {
		
		_init: function() {
			//Get the ul and store a reference to it
			var ul = this.element.find('ul.product_scroll_list');
			this._setData('ul', ul);
			
			//Hide the standard scrollbar
			//this.element.css('overflowX', 'hidden');
			
			this._calculateUlWidth();
			
			//Set the ul width and the floating rules to remove extra (inline) margin to make it easy to apply the FrescaFilter display none/block
			ul.css({float: 'left', width: this._getData('ulWidth') + 'px'}).find('li.product').each(function() {
				$(this).css({display: 'block', float: 'left'});
			});
			
			//Kill the widget if we dont need to scroll
			//if(this._getData('ulWidth') <= this.element.width()) {
			if(this._getData('ulWidth') <= parseInt( this.element.css('width'), 10 )) {	
				ul.parent('div').addClass('no_scroll');
				this.destroy();
				return false;
			}
			
			//Past this point so give FrescaFilter a way to know the slider is active.
			this._setData('active', true);
			
			this._buildSlider();
			
			this._setHandleWidth();
			
			this._calculateRatio();
			
			var self = this;
			
			this._getData('handle').draggable({
				axis: 'x',
				containment: 'parent',
				drag: function(event, ui) {
					var val =  "-" + ( ui.position.left * self._getData('ratio') ) + "px";
					ul.css('marginLeft', val);
				}
			});
			
			var self = this;
			
			this._getData('slider').click(function(e) {
				var handle = self._getData('handle');
				var slider = self._getData('slider');
				var newX = (e.pageX - this.offsetLeft) - (handle.outerWidth(true) / 2);
				self._doScroll(newX);
			});
			
			this._getData('handle').hover(function() {
				$(this).css('opacity', .8);
			}, function() {
				$(this).css('opacity', 1);
			});
		},
		
		_calculateUlWidth: function() {
			//Calculate what the ul width should be based on the visible list items and store a reference in the widget
			var ulWidth = 0;
			this._getData('ul').find('li.product').each(function(i) {
				var liWidth = parseInt( $(this).css('width'), 10 ) + parseInt( $(this).css('marginRight'), 10 );
				ulWidth += liWidth;
			});
			
			this._setData('ulWidth', ulWidth);
		},
		
		_calculateVisibleUlWidth: function() {
			//Calculate what the ul width should be based on the visible list items and store a reference in the widget
			var ulWidth = 0;
			this._getData('ul').find('li.product:visible').each(function(i) {
				var liWidth = parseInt( $(this).css('width'), 10 ) + parseInt( $(this).css('marginRight'), 10 );
				ulWidth += liWidth;
			});
			
			this._setData('ulWidth', ulWidth);
		},
		
		_setHandleWidth: function() {
			//var ratio = this.element.width() / this._getData('ulWidth');
			var ratio = parseInt( this.element.css('width'), 10 ) / this._getData('ulWidth');
			//var width = (this.element.width() * ratio);
			var width = parseInt( this.element.css('width'), 10 ) * ratio;
			
			this._getData('handle').width(width - parseInt( this._getData('handle').css('paddingRight'), 10 ));
			this._getData('handle').css("left","0px");
		},
		
		_calculateRatio: function() {
				
			var remainderViewportWidth = this._getData('ulWidth') - parseInt( this.element.css('width'), 10 );
			var handleWidth = parseInt( this._getData('handle').css('width'), 10 ) + parseInt( this._getData('handle').css('paddingRight'), 10 );
			var ratio = remainderViewportWidth / ( parseInt( this._getData('slider').css('width'), 10 ) - handleWidth );
			
			//var ratio = (this._getData('ulWidth') - this.element.width()) / ( this._getData('slider').width() - this._getData('handle').innerWidth(true) );
			
			this._setData('ratio', ratio);
		},
		
		_doScroll: function(newX) {//96px
			
			var self = this;
			var handle = self._getData('handle');
			var slider = self._getData('slider');
			
			//Keep the handle withing the draggable zone
			if(newX < 0) {
				newX = 0;
			}
			
			if (newX > (slider.width() - handle.outerWidth(true))){
				newX = slider.width() - handle.outerWidth(true);
			}
			
			// Center the handle to the to the click
			handle.css('left', newX + 'px');
			
			//Move the product list
			var val =  "-" + ( newX * self._getData('ratio') ) + "px";
			self._getData('ul').css('marginLeft', val);
		},
		
		_buildSlider: function() {
			
			var self = this;
			var SCROLL_AMOUNT = 20;
			var SCROLL_TIMER = 50;
			
			var handle = $('<div class="widget-slider-handle"></div>');//widget-slider-handle
			handle.append('<span></span>');
			var slider = $('<div class="widget-slider"></div>');//widget-slider
			slider.append(handle);
			
			this.element.after(slider);
			this._setData('slider', slider);
			this._setData('handle', handle);
			
			//Adding left/right buttons to product scroll
			//left scroll button
			var leftBtn = $('<img src="/pws/images/btn_scroll-left.gif" class="product_scroll_btn" id="product_scroll_left" />');
			var rightBtn = $('<img src="/pws/images/btn_scroll-right.gif" class="product_scroll_btn" id="product_scroll_right" />');
			
			this.element.before(leftBtn);
			this.element.after(rightBtn);
			
			var scrollInterval;
			
			leftBtn.hover(function() {
				$(this).css('opacity', .6);
			}, function() {
				$(this).css('opacity', 1);
			});
			
			rightBtn.hover(function() {
				$(this).css('opacity', .6);
			}, function() {
				$(this).css('opacity', 1);
			});
			
			function startScrollLeft() {
				scrollInterval = setInterval(scrollLeft, SCROLL_TIMER);
			}
			
			function startScrollRight() {
				scrollInterval = setInterval(scrollRight, SCROLL_TIMER);
			}
			
			function stopScroll() {
				clearInterval(scrollInterval);
			}
			
			function scrollLeft() {
				var handle = self._getData('handle');
				//console.log(parseInt(handle.css('left'), 10) + "  " +  (handle.outerWidth(true) / 2) + "  " +  SCROLL_SPEED);
				var newX = parseInt(handle.css('left'), 10) - SCROLL_AMOUNT;
				//var newX = parseInt(handle.css('left'), 10) + (handle.outerWidth(true) / 2) - SCROLL_SPEED;
				self._doScroll(newX);
			}
			
			function scrollRight() {
				var handle = self._getData('handle');
				var newX = parseInt(handle.css('left'), 10) + SCROLL_AMOUNT;
				//var newX = parseInt(handle.css('left'), 10) + (handle.outerWidth(true) / 2) + SCROLL_SPEED;
				self._doScroll(newX);
			}
			
			leftBtn.mousedown(function() {
				startScrollLeft();
			});
			
			leftBtn.mouseup(function() {
				stopScroll();
			});
			
			leftBtn.click(function() {
				scrollLeft();
			});
			
			rightBtn.mousedown(function() {
				startScrollRight();
			});
			
			rightBtn.mouseup(function() {
				stopScroll();
			});
			
			rightBtn.click(function() {
				scrollRight();
			});
		},
		
		refresh: function() {
			//First calculate and set the new ul width
			//this._calculateUlWidth();
			this._calculateVisibleUlWidth();
			this._getData('ul').css({ 'marginLeft': '0', width: this._getData('ulWidth') + 'px' })
		
			//Maximise scroll if we don't want to scroll
			if(this._getData('ulWidth') <= this.element.width()) {
				var newWidth = this._getData('slider').width() - parseInt( this._getData('handle').css('paddingRight'), 10 );
				alert (newWidth);
				this._getData('handle').css( { left: '0', width: newWidth + 'px' } );
				this._getData('slider').css('visibility', 'hidden');
				$('img.product_scroll_btn').css('visibility', 'hidden');
			} else {
				this._getData('slider').css('opacity', 1);
				this._setHandleWidth();
				this._calculateRatio();
				this._getData('handle').css('left', '0');
				this._getData('slider').css('visibility', 'visible');
				$('img.product_scroll_btn').css('visibility', 'visible');
			}
		},
		
		getActive: function() {
			return this._getData('active');
		}
	});
	
	
	$.widget('ui.basketWidget', {
		
		_init: function() {
			
			var self = this;
			
			//Get a local reference to the elements of interest
			var detailsContent = this.element;
			var scroller = this.element.find('#scrollable_basket_products');
			var ul = this.element.find('ul.basket_products');
			var liArr = scroller.find('li.basket_product');
			
			this._setData('animating', false);
			this._setData('scroller', scroller);
			this._setData('ul', ul);
			this._setData('liArr', liArr);
			
			if(liArr.length === 0) {
				this.destroy();
				return false;
			}
			
			//Only fire off the scrolling functions if applicable
			if(liArr.length > this.options.numberOpenProductsInView) {
				scrollable = true;
				var scrollButtons = [];
				scrollButtons[0] = $('<div id="minibasket_scroll_button_0" class="minibasket_scroll_button inactive"><p>scroll up</p></div>');
				scrollButtons[1] = $('<div id="minibasket_scroll_button_1" class="minibasket_scroll_button inactive"><p>scroll down</p></div>');
				scroller.before(scrollButtons[0]);
				scroller.after(scrollButtons[1]);
				this._setData('scrollButtons', scrollButtons);
				this._setScrollActions();
			}
			
			//Attach the event handlers
			liArr.each(function() {
			
				var button = $(this).find('div.basket_product_title');
				var content = $(this).find('div.basket_product_content');
				var remove = $(this).find('a.basket_product_content_info_remove');
				
				var closed = true;
				
				$(this).hover(function() {
					$(this).addClass('hover');
				}, function() {
					$(this).removeClass('hover');
				});
				
				button.click(function() {
					
					var parent = $(this).parent();
					
					if(!self._getData('animating')) {
						self._setData('animating', true);
						
						if(closed) {
							parent.addClass('open');
							content.animate({height: self.options.contentHeight + 'px'}, self.options.slideDownSpeed, function() {
								self._setData('animating', false);
								closed = false;
								self._checkBounds(0);
								self._checkViewportScrollUp($(this).parent());
								self._evaluateScroll();
							});
						} else {
							self._checkBounds(content.height());
							content.animate({height: 0}, 500, function() {
								parent.removeClass('open');
								self._setData('animating', false);
								closed = true;
								self._checkViewport();
								self._evaluateScroll();
							});
						}
					}
				});
				
				remove.click(function(e) {
					e.preventDefault();
					var anc = $(this);
					
					var href = $(this).attr('href');
					
					var overlay = $('div#minibasket_overlay');
					var loading = $('img#minbasket_overlay_progress');
					
					var height = self.element.height();
					
					overlay.css({
						display: 'block',
						height: height + 'px',
						opacity: 0
					});
					
					loading.css({
						left:		'50%', 
						top:		'50%'
					}).css({
						marginLeft:	'-' + ( loading.outerWidth() / 2 ) + 'px', 
						marginTop:	'-' + ( loading.outerHeight() / 2 ) + 'px'
					});
					
					$.ajax({
						url: href,
						beforeSend: function() {
							loading.css('display', 'block');
							overlay.animate({opacity: .6}, 500);
						},
						success: function(data, textStatus) {
							//If the request was successful then reload the minibasket
							var product = anc.parent('div').parent('div').parent('li');
							loading.css('display', 'none');
							product.animate({height: 0}, 500, function() {
								loadMiniBasket();
							});
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							anc.after('<p class="minibasket_error>Sorry, something went wrong. Please try again.</p>');
							loading.css('display', 'none');
							overlay.stop().animate({opacity: 0}, 500);
						}
					});
				});
			});
		},
		
		_setScrollActions: function() {
			
			var self = this;
			
			function scrollUp() {
				//Work out which li to scroll then animate to that point
				
				var scroller = self._getData('scroller');
				var ul = self._getData('ul');
				var elementToScrollTo;
				
				if(ul.height() <= scroller.height() || self._getData('animating')) {		//Scroller viewport is not max height or currently animating so don't scroll
					return false;
				}
				
				var marginTop = parseInt( ul.css('marginTop'), 10 );
				var liArr = ul.find('li.basket_product');
				
				for(var i = liArr.length - 1; i >= 0; i--) {
					
					var li = $(liArr[i]);
					
					var topInViewport = li.position().top + marginTop;
					
					if(topInViewport < 0) {
						elementToScrollTo = li;
						break;
					}
				}
				
				if(elementToScrollTo) {		//Only scroll if an element is overhanging
				
					var distance = elementToScrollTo.position().top;
					var newMarginTop = marginTop + distance;
					
					self._getData('animating', true);
					
					ul.animate({marginTop: -elementToScrollTo.position().top + 'px'}, 500, function() {
						self._getData('animating', false);
						self._evaluateScroll();
					});
				}
				
			}
			
			function scrollDown() {
				
				//Work out which li to scroll then animate to that point
				
				var scroller = self._getData('scroller');
				var ul = self._getData('ul');
				var elementToScrollTo;
				
				if(ul.height() <= scroller.height() || self._getData('animating')) {		//Scroller viewport is not max height or currently animating so don't scroll
					return false;
				}
				
				var marginTop = parseInt( ul.css('marginTop'), 10 );
				var liArr = ul.find('li.basket_product');
				
				for(var i = 0; i < liArr.length; i++) {
					
					var li = $(liArr[i]);
					
					//This is the bottom of the li relative to the 'scroller' viewport
					var bottomInViewport = li.position().top + li.height() + marginTop;

					if(bottomInViewport > scroller.height()) {			//This is the first li which is all/part outside the bottom of the scroll viewport
						elementToScrollTo = li;
						break;
					}
				}
				
				if(elementToScrollTo) {		//Only scroll if an element is overhanging
					var distance = ( elementToScrollTo.position().top + elementToScrollTo.height() ) - ( scroller.height() - marginTop );
					var newMarginTop = marginTop + -distance;
					
					self._getData('animating', true);
					
					ul.animate({marginTop: newMarginTop + 'px'}, 500, function() {
						self._getData('animating', false);
						self._evaluateScroll();
					});
				}
			}
			
			this._getData('scrollButtons')[0].click(function() {
				scrollUp();
			});
			
			this._getData('scrollButtons')[1].click(function() {
				scrollDown();
			});
		},
		
		_checkBounds: function(height) {
			
			if(typeof document.body.style.maxHeight === 'undefined') {
				return false;
			}
			
			var ul = this._getData('ul');
			var scroller = this._getData('scroller');
			var testHeight = ul.height() - height;
			
			if( testHeight >= parseInt( scroller.css('maxHeight'), 10 ) ) {
			//if( ul.height() >= parseInt( scroller.css('maxHeight'), 10 ) ) {
				scroller.css('height', parseInt( scroller.css('maxHeight'), 10 ) + 'px');
			} else {
				scroller.css('height', 'auto');
			}
		},
		
		_checkViewport: function(element) {
			
			var self = this;
			var ul = this._getData('ul');
			var scroller = this._getData('scroller');
			
			//If there is a gap left animate to fill it up
			var scrollerHeightInViewport = ul.height() + parseInt( ul.css('marginTop'), 10 );
			
			if( scroller.height() > scrollerHeightInViewport ) {
				var difference = scroller.height() - scrollerHeightInViewport;
				var newMarginTop = parseInt( ul.css('marginTop'), 10 ) + difference;
				this._setData('animating', true);
				
				ul.animate({'marginTop': newMarginTop + 'px'}, this.options.slideDownSpeed, function() {
					self._setData('animating', false);
				});
			}
		},
		
		_checkViewportScrollUp: function(element) {
			
			var self = this;
			var ul = this._getData('ul');
			var scroller = this._getData('scroller');
			var newY = 0;
			
			element.prevAll().each(function() {
				newY += $(this).height();
			});
			
			newY += element.height();
			newY = newY;
			
			var x = parseInt( scroller.css('maxHeight'), 10 );
			var z = parseInt( ul.css('marginTop'), 10 );
			
			if(newY > x) {
				z = z - ( ( newY + z ) - x );
				
				this._setData('animating', true);
				
				ul.animate({'marginTop': z + 'px'}, this.options.slideDownSpeed, function() {
					self._setData('animating', false);
				});
			}
		},
		
		_evaluateScroll: function() {

			if(this._getData('liArr').length <= this.options.numberOpenProductsInView) {
				return false;		//Not using scroll buttons
			}
			
			var self = this;
			var ul = this._getData('ul');
			var scroller = this._getData('scroller');
			var scrollButtons = this._getData('scrollButtons');
			
			var marginTop = parseInt( ul.css('marginTop'), 10 );
				
			if(marginTop >= 0) {
				scrollButtons[0].addClass('inactive');
			} else {
				scrollButtons[0].removeClass('inactive');
			}
			
			if(marginTop <= scroller.height() - ul.height()) {
				scrollButtons[1].addClass('inactive');
			} else {
				scrollButtons[1].removeClass('inactive');
			}
		},
		
		//Pulic interface to _evaluateScroll
		evaluateScroll: function() {
			this._evaluateScroll();
		},
		
		getActive: function() {
			return this._getData('active');
		}
	});
	
	$.extend($.ui.basketWidget, {
		getter: "value length",
		defaults: {
			contentHeight: 104,
			numberOpenProductsInView: 3,
			slideDownSpeed: 500,
			scrollInterval: 50,
			scrollAmount: 10,
			interval: 10,
			scrollAmount: 10
		}
	});
	
})(jQuery);

function headerSelect() {
	if ($("body").is(".news")) {
  	$("#main_navigation_level_1 li#main_navigation_news").addClass("highlight")
  }
	if ($("body").is(".dd-moments")) {
  	$("#main_navigation_level_1 li#main_navigation_dd_moments").addClass("highlight")
  }
	if ($("body").is(".my-dd")) {
  	$("#main_navigation_level_1 li#main_navigation_locker").addClass("highlight")
  }
		
}
	

/* Document Ready */

$(document).ready(function(){
													 
	ieNavigationFix();
	loadMiniBasket();
	//newsDropDown();
	$('.pngfix').pngfix();
	$(".update_section").updatesDropDown();
	clearInputValue();
	headerSelect();
	address_elements_change();
	
		if($("form.GB").length>0) {
			 $("div#state_element_US").hide();	
			 $("div#state_element_JP").hide();	
			 $("div#state_element_US select").removeClass("validate").addClass("ignore");
			 $("div#state_element_JP input").removeClass("validate").addClass("ignore");

		}
		else if($("form.US").length>0 || $("form.USA").length>0 ) {
			 $("div#county_element_GB").hide();
			 $("div#state_element_JP").hide();	
			 $("div#state_element_US input").attr("name","state");
			 $("div#state_element_JP input").removeClass("validate").addClass("ignore");
			 $("div#state_element_JP input").removeAttr("name");
			 $("div#state_element_US").show();	
			 $("div#postcode_lookup_wrapper").css("display","none");
			 var addressPostcode = $("form.postcode_GB")
			 if(addressPostcode.length>0) {
				 $("div#postcode_lookup_wrapper").css("display","block");
				 $("div#state_element_US").hide();	
				 $("div#state_element_JP").hide();	
				 $("div#state_element_US select").removeClass("validate").addClass("ignore");
				 $("div#state_element_JP input").removeClass("validate").addClass("ignore");
				 $("#country_list").val("GB");
			 }
		}
		else if($("form.IE").length>0) {
			 $("div#state_element_US").hide();
			 $("div#state_element_JP").hide();	
			 $("div#state_element_JP input").removeClass("validate").addClass("ignore").removeAttr("name");
			 $("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");
			 	$("div#postcode_lookup_wrapper").css("display","none");
				$("div#state_element_JP input").removeAttr("name");
		}
		else if($("form.JP").length>0) {
			 $("div#county_element_GB").hide();
			 $("div#state_element_US").hide();	
			 $("div#state_element_JP input").attr("name","state");
			 $("div#state_element_US select").removeClass("validate").addClass("ignore").removeAttr("name");
			 $("div#state_element_JP").show();
			 $("div#postcode_lookup_wrapper").css("display","none");
			 var addressPostcode = $("form.postcode_GB")
			 if(addressPostcode.length>0) {
				 $("div#postcode_lookup_wrapper").css("display","block");
				 $("div#state_element_US").hide();	
				 $("div#state_element_JP").hide();	
				 $("div#state_element_US select").removeClass("validate").addClass("ignore");
				 $("div#state_element_JP input").removeClass("validate").addClass("ignore");
				 $("#country_list").val("GB");
			 }
		}
		else {
			 $("div#state_element_US").hide();	
			 $("div#state_element_JP").hide();	
			 $("div#postcode_lookup_wrapper").css("display","none");

		}

});


