/*
 * jScrollPane - v2.0.0beta11 - 2011-07-04
 * http://jscrollpane.kelvinluck.com/
 *
 * Copyright (c) 2010 Kelvin Luck
 * Dual licensed under the MIT and GPL licenses.
 last change 22/02/2012 08:30
 */
(function(b,a,c){b.fn.jScrollPane=function(e){function d(D,O){var az,Q=this,Y,ak,v,am,T,Z,y,q,aA,aF,av,i,I,h,j,aa,U,aq,X,t,A,ar,af,an,G,l,au,ay,x,aw,aI,f,L,aj=true,P=true,aH=false,k=false,ap=D.clone(false,false).empty(),ac=b.fn.mwheelIntent?"mwheelIntent.jsp":"mousewheel.jsp";aI=D.css("paddingTop")+" "+D.css("paddingRight")+" "+D.css("paddingBottom")+" "+D.css("paddingLeft");f=(parseInt(D.css("paddingLeft"),10)||0)+(parseInt(D.css("paddingRight"),10)||0);function at(aR){var aM,aO,aN,aK,aJ,aQ,aP=false,aL=false;az=aR;if(Y===c){aJ=D.scrollTop();aQ=D.scrollLeft();D.css({overflow:"hidden",padding:0});ak=D.innerWidth()+f;v=D.innerHeight();D.width(ak);Y=b('<div class="jspPane" />').css("padding",aI).append(D.children());am=b('<div class="jspContainer" />').css({width:ak+"px",height:v+"px"}).append(Y).appendTo(D)}else{D.css("width","");aP=az.stickToBottom&&K();aL=az.stickToRight&&B();aK=D.innerWidth()+f!=ak||D.outerHeight()!=v;if(aK){ak=D.innerWidth()+f;v=D.innerHeight();am.css({width:ak+"px",height:v+"px"})}if(!aK&&L==T&&Y.outerHeight()==Z){D.width(ak);return}L=T;Y.css("width","");D.width(ak);am.find(">.jspVerticalBar,>.jspHorizontalBar").remove().end()}Y.css("overflow","auto");if(aR.contentWidth){T=aR.contentWidth}else{T=Y[0].scrollWidth}Z=Y[0].scrollHeight;Y.css("overflow","");y=T/ak;q=Z/v;aA=q>1;aF=y>1;if(!(aF||aA)){D.removeClass("jspScrollable");Y.css({top:0,width:am.width()-f});n();E();R();w();ai()}else{D.addClass("jspScrollable");aM=az.maintainPosition&&(I||aa);if(aM){aO=aD();aN=aB()}aG();z();F();if(aM){N(aL?(T-ak):aO,false);M(aP?(Z-v):aN,false)}J();ag();ao();if(az.enableKeyboardNavigation){S()}if(az.clickOnTrack){p()}C();if(az.hijackInternalLinks){m()}}if(az.autoReinitialise&&!aw){aw=setInterval(function(){at(az)},az.autoReinitialiseDelay)}else{if(!az.autoReinitialise&&aw){clearInterval(aw)}}aJ&&D.scrollTop(0)&&M(aJ,false);aQ&&D.scrollLeft(0)&&N(aQ,false);D.trigger("jsp-initialised",[aF||aA])}function aG(){if(aA){am.append(b('<div class="jspVerticalBar" />').append(b('<div class="jspCap jspCapTop" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragTop" />'),b('<div class="jspDragBottom" />'))),b('<div class="jspCap jspCapBottom" />')));U=am.find(">.jspVerticalBar");aq=U.find(">.jspTrack");av=aq.find(">.jspDrag");if(az.showArrows){ar=b('<a class="jspArrow jspArrowUp" />').bind("mousedown.jsp",aE(0,-1)).bind("click.jsp",aC);af=b('<a class="jspArrow jspArrowDown" />').bind("mousedown.jsp",aE(0,1)).bind("click.jsp",aC);if(az.arrowScrollOnHover){ar.bind("mouseover.jsp",aE(0,-1,ar));af.bind("mouseover.jsp",aE(0,1,af))}al(aq,az.verticalArrowPositions,ar,af)}t=v;am.find(">.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow").each(function(){t-=b(this).outerHeight()});av.hover(function(){av.addClass("jspHover")},function(){av.removeClass("jspHover")}).bind("mousedown.jsp",function(aJ){b("html").bind("dragstart.jsp selectstart.jsp",aC);av.addClass("jspActive");var s=aJ.pageY-av.position().top;b("html").bind("mousemove.jsp",function(aK){V(aK.pageY-s,false)}).bind("mouseup.jsp mouseleave.jsp",ax);return false});o()}}function o(){aq.height(t+"px");I=0;X=az.verticalGutter+aq.outerWidth();Y.width(ak-X-f);try{if(U.position().left===0){Y.css("margin-left",X+"px")}}catch(s){}}function z(){if(aF){am.append(b('<div class="jspHorizontalBar" />').append(b('<div class="jspCap jspCapLeft" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragLeft" />'),b('<div class="jspDragRight" />'))),b('<div class="jspCap jspCapRight" />')));an=am.find(">.jspHorizontalBar");G=an.find(">.jspTrack");h=G.find(">.jspDrag");if(az.showArrows){ay=b('<a class="jspArrow jspArrowLeft" />').bind("mousedown.jsp",aE(-1,0)).bind("click.jsp",aC);x=b('<a class="jspArrow jspArrowRight" />').bind("mousedown.jsp",aE(1,0)).bind("click.jsp",aC);
if(az.arrowScrollOnHover){ay.bind("mouseover.jsp",aE(-1,0,ay));x.bind("mouseover.jsp",aE(1,0,x))}al(G,az.horizontalArrowPositions,ay,x)}h.hover(function(){h.addClass("jspHover")},function(){h.removeClass("jspHover")}).bind("mousedown.jsp",function(aJ){b("html").bind("dragstart.jsp selectstart.jsp",aC);h.addClass("jspActive");var s=aJ.pageX-h.position().left;b("html").bind("mousemove.jsp",function(aK){W(aK.pageX-s,false)}).bind("mouseup.jsp mouseleave.jsp",ax);return false});l=am.innerWidth();ah()}}function ah(){am.find(">.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow").each(function(){l-=b(this).outerWidth()});G.width(l+"px");aa=0}function F(){if(aF&&aA){var aJ=G.outerHeight(),s=aq.outerWidth();t-=aJ;b(an).find(">.jspCap:visible,>.jspArrow").each(function(){l+=b(this).outerWidth()});l-=s;v-=s;ak-=aJ;G.parent().append(b('<div class="jspCorner" />').css("width",aJ+"px"));o();ah()}if(aF){Y.width((am.outerWidth()-f)+"px")}Z=Y.outerHeight();q=Z/v;if(aF){au=Math.ceil(1/y*l);if(au>az.horizontalDragMaxWidth){au=az.horizontalDragMaxWidth}else{if(au<az.horizontalDragMinWidth){au=az.horizontalDragMinWidth}}h.width(au+"px");j=l-au;ae(aa)}if(aA){A=Math.ceil(1/q*t);if(A>az.verticalDragMaxHeight){A=az.verticalDragMaxHeight}else{if(A<az.verticalDragMinHeight){A=az.verticalDragMinHeight}}av.height(A+"px");i=t-A;ad(I)}}function al(aK,aM,aJ,s){var aO="before",aL="after",aN;if(aM=="os"){aM=/Mac/.test(navigator.platform)?"after":"split"}if(aM==aO){aL=aM}else{if(aM==aL){aO=aM;aN=aJ;aJ=s;s=aN}}aK[aO](aJ)[aL](s)}function aE(aJ,s,aK){return function(){H(aJ,s,this,aK);this.blur();return false}}function H(aM,aL,aP,aO){aP=b(aP).addClass("jspActive");var aN,aK,aJ=true,s=function(){if(aM!==0){Q.scrollByX(aM*az.arrowButtonSpeed)}if(aL!==0){Q.scrollByY(aL*az.arrowButtonSpeed)}aK=setTimeout(s,aJ?az.initialDelay:az.arrowRepeatFreq);aJ=false};s();aN=aO?"mouseout.jsp":"mouseup.jsp";aO=aO||b("html");aO.bind(aN,function(){aP.removeClass("jspActive");aK&&clearTimeout(aK);aK=null;aO.unbind(aN)})}function p(){w();if(aA){aq.bind("mousedown.jsp",function(aO){if(aO.originalTarget===c||aO.originalTarget==aO.currentTarget){var aM=b(this),aP=aM.offset(),aN=aO.pageY-aP.top-I,aK,aJ=true,s=function(){var aS=aM.offset(),aT=aO.pageY-aS.top-A/2,aQ=v*az.scrollPagePercent,aR=i*aQ/(Z-v);if(aN<0){if(I-aR>aT){Q.scrollByY(-aQ)}else{V(aT)}}else{if(aN>0){if(I+aR<aT){Q.scrollByY(aQ)}else{V(aT)}}else{aL();return}}aK=setTimeout(s,aJ?az.initialDelay:az.trackClickRepeatFreq);aJ=false},aL=function(){aK&&clearTimeout(aK);aK=null;b(document).unbind("mouseup.jsp",aL)};s();b(document).bind("mouseup.jsp",aL);return false}})}if(aF){G.bind("mousedown.jsp",function(aO){if(aO.originalTarget===c||aO.originalTarget==aO.currentTarget){var aM=b(this),aP=aM.offset(),aN=aO.pageX-aP.left-aa,aK,aJ=true,s=function(){var aS=aM.offset(),aT=aO.pageX-aS.left-au/2,aQ=ak*az.scrollPagePercent,aR=j*aQ/(T-ak);if(aN<0){if(aa-aR>aT){Q.scrollByX(-aQ)}else{W(aT)}}else{if(aN>0){if(aa+aR<aT){Q.scrollByX(aQ)}else{W(aT)}}else{aL();return}}aK=setTimeout(s,aJ?az.initialDelay:az.trackClickRepeatFreq);aJ=false},aL=function(){aK&&clearTimeout(aK);aK=null;b(document).unbind("mouseup.jsp",aL)};s();b(document).bind("mouseup.jsp",aL);return false}})}}function w(){if(G){G.unbind("mousedown.jsp")}if(aq){aq.unbind("mousedown.jsp")}}function ax(){b("html").unbind("dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp");if(av){av.removeClass("jspActive")}if(h){h.removeClass("jspActive")}}function V(s,aJ){if(!aA){return}if(s<0){s=0}else{if(s>i){s=i}}if(aJ===c){aJ=az.animateScroll}if(aJ){Q.animate(av,"top",s,ad)}else{av.css("top",s);ad(s)}}function ad(aJ){if(aJ===c){aJ=av.position().top}am.scrollTop(0);I=aJ;var aM=I===0,aK=I==i,aL=aJ/i,s=-aL*(Z-v);if(aj!=aM||aH!=aK){aj=aM;aH=aK;D.trigger("jsp-arrow-change",[aj,aH,P,k])}u(aM,aK);Y.css("top",s);D.trigger("jsp-scroll-y",[-s,aM,aK]).trigger("scroll")}function W(aJ,s){if(!aF){return}if(aJ<0){aJ=0}else{if(aJ>j){aJ=j}}if(s===c){s=az.animateScroll}if(s){Q.animate(h,"left",aJ,ae)
}else{h.css("left",aJ);ae(aJ)}}function ae(aJ){if(aJ===c){aJ=h.position().left}am.scrollTop(0);aa=aJ;var aM=aa===0,aL=aa==j,aK=aJ/j,s=-aK*(T-ak);if(P!=aM||k!=aL){P=aM;k=aL;D.trigger("jsp-arrow-change",[aj,aH,P,k])}r(aM,aL);Y.css("left",s);D.trigger("jsp-scroll-x",[-s,aM,aL]).trigger("scroll")}function u(aJ,s){if(az.showArrows){ar[aJ?"addClass":"removeClass"]("jspDisabled");af[s?"addClass":"removeClass"]("jspDisabled")}}function r(aJ,s){if(az.showArrows){ay[aJ?"addClass":"removeClass"]("jspDisabled");x[s?"addClass":"removeClass"]("jspDisabled")}}function M(s,aJ){var aK=s/(Z-v);V(aK*i,aJ)}function N(aJ,s){var aK=aJ/(T-ak);W(aK*j,s)}function ab(aW,aR,aK){var aO,aL,aM,s=0,aV=0,aJ,aQ,aP,aT,aS,aU;try{aO=b(aW)}catch(aN){return}aL=aO.outerHeight();aM=aO.outerWidth();am.scrollTop(0);am.scrollLeft(0);while(!aO.is(".jspPane")){s+=aO.position().top;aV+=aO.position().left;aO=aO.offsetParent();if(/^body|html$/i.test(aO[0].nodeName)){return}}aJ=aB();aP=aJ+v;if(s<aJ||aR){aS=s-az.verticalGutter}else{if(s+aL>aP){aS=s-v+aL+az.verticalGutter}}if(aS){M(aS,aK)}aQ=aD();aT=aQ+ak;if(aV<aQ||aR){aU=aV-az.horizontalGutter}else{if(aV+aM>aT){aU=aV-ak+aM+az.horizontalGutter}}if(aU){N(aU,aK)}}function aD(){return -Y.position().left}function aB(){return -Y.position().top}function K(){var s=Z-v;return(s>20)&&(s-aB()<10)}function B(){var s=T-ak;return(s>20)&&(s-aD()<10)}function ag(){am.unbind(ac).bind(ac,function(aM,aN,aL,aJ){var aK=aa,s=I;Q.scrollBy(aL*az.mouseWheelSpeed,-aJ*az.mouseWheelSpeed,false);return aK==aa&&s==I})}function n(){am.unbind(ac)}function aC(){return false}function J(){Y.find(":input,a").unbind("focus.jsp").bind("focus.jsp",function(s){ab(s.target,false)})}function E(){Y.find(":input,a").unbind("focus.jsp")}function S(){var s,aJ,aL=[];aF&&aL.push(an[0]);aA&&aL.push(U[0]);Y.focus(function(){D.focus()});D.attr("tabindex",0).unbind("keydown.jsp keypress.jsp").bind("keydown.jsp",function(aO){if(aO.target!==this&&!(aL.length&&b(aO.target).closest(aL).length)){return}var aN=aa,aM=I;switch(aO.keyCode){case 40:case 38:case 34:case 32:case 33:case 39:case 37:s=aO.keyCode;aK();break;case 35:M(Z-v);s=null;break;case 36:M(0);s=null;break}aJ=aO.keyCode==s&&aN!=aa||aM!=I;return !aJ}).bind("keypress.jsp",function(aM){if(aM.keyCode==s){aK()}return !aJ});if(az.hideFocus){D.css("outline","none");if("hideFocus" in am[0]){D.attr("hideFocus",true)}}else{D.css("outline","");if("hideFocus" in am[0]){D.attr("hideFocus",false)}}function aK(){var aN=aa,aM=I;switch(s){case 40:Q.scrollByY(az.keyboardSpeed,false);break;case 38:Q.scrollByY(-az.keyboardSpeed,false);break;case 34:case 32:Q.scrollByY(v*az.scrollPagePercent,false);break;case 33:Q.scrollByY(-v*az.scrollPagePercent,false);break;case 39:Q.scrollByX(az.keyboardSpeed,false);break;case 37:Q.scrollByX(-az.keyboardSpeed,false);break}aJ=aN!=aa||aM!=I;return aJ}}function R(){D.attr("tabindex","-1").removeAttr("tabindex").unbind("keydown.jsp keypress.jsp")}function C(){if(location.hash&&location.hash.length>1){var aL,aJ,aK=escape(location.hash);try{aL=b(aK)}catch(s){return}if(aL.length&&Y.find(aK)){if(am.scrollTop()===0){aJ=setInterval(function(){if(am.scrollTop()>0){ab(aK,true);b(document).scrollTop(am.position().top);clearInterval(aJ)}},50)}else{ab(aK,true);b(document).scrollTop(am.position().top)}}}}function ai(){b("a.jspHijack").unbind("click.jsp-hijack").removeClass("jspHijack")}function m(){ai();b("a[href^=#]").addClass("jspHijack").bind("click.jsp-hijack",function(){var s=this.href.split("#"),aJ;if(s.length>1){aJ=s[1];if(aJ.length>0&&Y.find("#"+aJ).length>0){ab("#"+aJ,true);return false}}})}function ao(){var aK,aJ,aM,aL,aN,s=false;am.unbind("touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick").bind("touchstart.jsp",function(aO){var aP=aO.originalEvent.touches[0];aK=aD();aJ=aB();aM=aP.pageX;aL=aP.pageY;aN=false;s=true}).bind("touchmove.jsp",function(aR){if(!s){return}var aQ=aR.originalEvent.touches[0],aP=aa,aO=I;Q.scrollTo(aK+aM-aQ.pageX,aJ+aL-aQ.pageY);aN=aN||Math.abs(aM-aQ.pageX)>5||Math.abs(aL-aQ.pageY)>5;
return aP==aa&&aO==I}).bind("touchend.jsp",function(aO){s=false}).bind("click.jsp-touchclick",function(aO){if(aN){aN=false;return false}})}function g(){var s=aB(),aJ=aD();D.removeClass("jspScrollable").unbind(".jsp");D.replaceWith(ap.append(Y.children()));ap.scrollTop(s);ap.scrollLeft(aJ)}b.extend(Q,{reinitialise:function(aJ){aJ=b.extend({},az,aJ);at(aJ)},scrollToElement:function(aK,aJ,s){ab(aK,aJ,s)},scrollTo:function(aK,s,aJ){N(aK,aJ);M(s,aJ)},scrollToX:function(aJ,s){N(aJ,s)},scrollToY:function(s,aJ){M(s,aJ)},scrollToPercentX:function(aJ,s){N(aJ*(T-ak),s)},scrollToPercentY:function(aJ,s){M(aJ*(Z-v),s)},scrollBy:function(aJ,s,aK){Q.scrollByX(aJ,aK);Q.scrollByY(s,aK)},scrollByX:function(s,aK){var aJ=aD()+Math[s<0?"floor":"ceil"](s),aL=aJ/(T-ak);W(aL*j,aK)},scrollByY:function(s,aK){var aJ=aB()+Math[s<0?"floor":"ceil"](s),aL=aJ/(Z-v);V(aL*i,aK)},positionDragX:function(s,aJ){W(s,aJ)},positionDragY:function(aJ,s){V(aJ,s)},animate:function(aJ,aM,s,aL){var aK={};aK[aM]=s;aJ.animate(aK,{duration:az.animateDuration,easing:az.animateEase,queue:false,step:aL})},getContentPositionX:function(){return aD()},getContentPositionY:function(){return aB()},getContentWidth:function(){return T},getContentHeight:function(){return Z},getPercentScrolledX:function(){return aD()/(T-ak)},getPercentScrolledY:function(){return aB()/(Z-v)},getIsScrollableH:function(){return aF},getIsScrollableV:function(){return aA},getContentPane:function(){return Y},scrollToBottom:function(s){V(i,s)},hijackInternalLinks:function(){m()},destroy:function(){g()}});at(O)}e=b.extend({},b.fn.jScrollPane.defaults,e);b.each(["mouseWheelSpeed","arrowButtonSpeed","trackClickSpeed","keyboardSpeed"],function(){e[this]=e[this]||e.speed});return this.each(function(){var f=b(this),g=f.data("jsp");if(g){g.reinitialise(e)}else{g=new d(f,e);f.data("jsp",g)}})};b.fn.jScrollPane.defaults={showArrows:false,maintainPosition:true,stickToBottom:false,stickToRight:false,clickOnTrack:true,autoReinitialise:false,autoReinitialiseDelay:500,verticalDragMinHeight:0,verticalDragMaxHeight:99999,horizontalDragMinWidth:0,horizontalDragMaxWidth:99999,contentWidth:c,animateScroll:false,animateDuration:300,animateEase:"linear",hijackInternalLinks:false,verticalGutter:4,horizontalGutter:4,mouseWheelSpeed:0,arrowButtonSpeed:0,arrowRepeatFreq:50,arrowScrollOnHover:false,trackClickSpeed:0,trackClickRepeatFreq:70,verticalArrowPositions:"split",horizontalArrowPositions:"split",enableKeyboardNavigation:true,hideFocus:false,keyboardSpeed:0,initialDelay:300,speed:30,scrollPagePercent:0.8}})(jQuery,this);
/*
   Magnify functionality removed from separate file
 */ 
	var TopDivName;
	var faderDirection = 0;
	var fadeValue = 0;
	var faderDirections = new Array();
	var fadeValues = new Array();
	var fadeIntervalIDs ={};
	
	function fnInitZoomVariables(_photo_w, _photo_h, _photo2_w, _photo2_h, _zoom_w, _zoom_h, _border, _smallPhotoDivName, _smallPhotoShadowDivName, _bigPhotoDivName, _flyBoxDivName, _flyBoxPhotoDivName, _zoomBoxDivName, _popupDivName, _objName) {
		var SettingsObject = new Object; 
		SettingsObject.photo_w = _photo_w;
		SettingsObject.photo_h = _photo_h;
		SettingsObject.photo2_w = _photo2_w;
		SettingsObject.photo2_h = _photo2_h;
		SettingsObject.zoom_w = _zoom_w;
		SettingsObject.zoom_h = _zoom_h;
		SettingsObject.border = _border;
		SettingsObject.ratio_x = _photo2_w / _photo_w;
		SettingsObject.ratio_y = _photo2_h / _photo_h;
		SettingsObject.fly_w = _zoom_w / SettingsObject.ratio_x - 1;
		SettingsObject.fly_h = _zoom_h / SettingsObject.ratio_y - 1;
		SettingsObject.smallPhotoDivName = _smallPhotoDivName;
		SettingsObject.smallPhotoShadowDivName = _smallPhotoShadowDivName;
		SettingsObject.bigPhotoDivName = _bigPhotoDivName;
		SettingsObject.flyBoxDivName = _flyBoxDivName;
		SettingsObject.flyBoxPhotoDivName = _flyBoxPhotoDivName;
		SettingsObject.zoomBoxDivName = _zoomBoxDivName;
		SettingsObject.popupDivName = _popupDivName;
		SettingsObject.objName = _objName;
		SettingsObject.smallPhotoOffset = {x:0, y:0};
		SettingsObject.bigPhotoOffset = {x:0, y:0};
		SettingsObject.popupOffset = {x:0, y:0};
		if (_popupDivName != '') {
			var popupDiv = document.getElementById(_popupDivName);
			if (popupDiv != null) {
				offsetPair = findPosMagnify(document.getElementById(_popupDivName));
				SettingsObject.popupOffset.x = offsetPair[0];
				SettingsObject.popupOffset.y = offsetPair[1];
			}
		}
		return SettingsObject;
	}          
	function fnAttachHandlers(iOrigWidth, iZoomWidth, ProdDetZoomSettings) {
		var zoomOn=true;	
		// These three handlers that use the 'event' object must be added differently in firefox
		if (navigator.appName.indexOf("Microsoft") != -1) { 
			document.getElementById(ProdDetZoomSettings.smallPhotoShadowDivName).onmousemove = function() { 
				fnTrackMouse(ProdDetZoomSettings, event); 
			} 
		}else {
			document.getElementById(ProdDetZoomSettings.smallPhotoShadowDivName).setAttribute("onmousemove", "fnTrackMouse(" + ProdDetZoomSettings.objName + ", event);"); 
		}
		if(navigator.appName.indexOf("Microsoft") != -1) { 
			document.getElementById(ProdDetZoomSettings.smallPhotoDivName).onmouseover = function() {
				 if(true){
					 fnCalculateZoomPos(ProdDetZoomSettings);
					 fnStepOnOff(ProdDetZoomSettings, true);
					 fnTrackMouse(ProdDetZoomSettings, event);
					}
				} 
		}else{ 
			document.getElementById(ProdDetZoomSettings.smallPhotoDivName).setAttribute("onmouseover", "if(true){fnCalculateZoomPos(" + ProdDetZoomSettings.objName + "); fnStepOnOff(" + ProdDetZoomSettings.objName + ", true); fnTrackMouse(" + ProdDetZoomSettings.objName + ", event);}"); 
		} 
		if (navigator.appName.indexOf("Microsoft") != -1) { 
			document.getElementById(ProdDetZoomSettings.flyBoxDivName).onmousemove = function() { 
			fnTrackMouse(ProdDetZoomSettings, event); 
		} 
		}else{ 
			document.getElementById(ProdDetZoomSettings.flyBoxDivName).setAttribute("onmousemove", "fnTrackMouse(" + ProdDetZoomSettings.objName + ", event);"); 
		}

		// When no 'event' object is passed to a handler, all browsers can add event handlers like so:
		document.getElementById(ProdDetZoomSettings.flyBoxDivName).onmouseout = function() { fnStepOnOff(ProdDetZoomSettings, false); }
		document.getElementById(ProdDetZoomSettings.flyBoxPhotoDivName).onmouseout = function() { fnStepOnOff(ProdDetZoomSettings, false); }
		document.getElementById(ProdDetZoomSettings.flyBoxPhotoDivName).style.width = iOrigWidth + "px";		
		document.getElementById(ProdDetZoomSettings.smallPhotoShadowDivName).style.width = iOrigWidth + "px";	
		document.getElementById(ProdDetZoomSettings.bigPhotoDivName).style.width = iZoomWidth + "px";
		
		if(ProdDetZoomSettings.flyBoxDivName.indexOf('popup')==-1){
			document.getElementById(ProdDetZoomSettings.flyBoxPhotoDivName).style.height = oImage.height + "px";
			document.getElementById(ProdDetZoomSettings.smallPhotoShadowDivName).style.height = oImage.height + "px";
			document.getElementById(ProdDetZoomSettings.bigPhotoDivName).style.height = oImage_Magnify.height + "px";
		}else{
			document.getElementById(ProdDetZoomSettings.flyBoxPhotoDivName).style.height = oImage_popup.height + "px";
			document.getElementById(ProdDetZoomSettings.smallPhotoShadowDivName).style.height = oImage_popup.height + "px";
			document.getElementById(ProdDetZoomSettings.bigPhotoDivName).style.height = oImage_Magnify_popup.height + "px";
		}
		fnCalculateZoomPos(ProdDetZoomSettings);
	}
	
	function fnTrackMouse(setObj, evt) {	
		if(setObj == null){return;}
		max_x = setObj.photo_w + setObj.border - setObj.fly_w - setObj.border*2;
		max_y = setObj.photo_h + setObj.border - setObj.fly_h - setObj.border*2;
		min_x = setObj.border;
		min_y = setObj.border;
		max_x2 = setObj.zoom_w/1 - setObj.photo2_w;
		max_y2 = setObj.zoom_h/1 - setObj.photo2_h;
		min_x2 = 0;
		min_y2 = 0;
		var bigPhoto = document.getElementById(setObj.bigPhotoDivName);
		var flyDiv = document.getElementById(setObj.flyBoxDivName);
		var flyPhotoDiv = document.getElementById(setObj.flyBoxPhotoDivName);
		if (flyPhotoDiv != null) {			
			var o = fPosition(evt);			
			var smallPhoto = document.getElementById(setObj.smallPhotoDivName);			
			real_x = o.x - setObj.smallPhotoOffset.x - setObj.popupOffset.x;
			real_y = o.y - setObj.smallPhotoOffset.y - setObj.popupOffset.y;			
			x = real_x - setObj.fly_w/2;
			y = real_y - setObj.fly_h/2;
			if (x > max_x) {x = max_x;}
			if (y > max_y) {y = max_y;}
			if (x < min_x) {x = min_x;}
			if (y < min_y) {y = min_y;}			
			x2 = 0 - (real_x) * setObj.ratio_x + (setObj.zoom_w)/2;
			y2 = 0 - (real_y) * setObj.ratio_y + (setObj.zoom_h)/2;			
			if (x2 > min_x2) {x2 = min_x2;}
			if (y2 > min_y2) {y2 = min_y2;}
			if (x2 < max_x2) {x2 = max_x2;}
			if (y2 < max_y2) {y2 = max_y2;}
      bigPhoto.style.left = x2 + 'px';
			bigPhoto.style.top = y2 + 'px';	
			flyDiv.style.left = setObj.smallPhotoOffset.x - setObj.border + x + 'px';
			flyDiv.style.top = setObj.smallPhotoOffset.y - setObj.border + y + 'px';			
			flyPhotoDiv.style.left = 0 - x + 'px';
			flyPhotoDiv.style.top = 0 - y + 'px';
		}
	}

	function fnStepOnOff(setObj, onoff) {
		if (setObj == null){return;}
		var intObj = $('.ui-widget-overlay, .main_container')[0];
	  var fd = faderDirections[setObj.zoomBoxDivName];	
		if(onoff == true){			
			document.getElementById(setObj.smallPhotoShadowDivName).style.display = '';
			document.getElementById(setObj.flyBoxDivName).style.display = '';			
			if(!fd || fd==0 || (fd == -1 && fadeValues[setObj.zoomBoxDivName] == 0)){
				faderDirections[setObj.zoomBoxDivName] = 1;
				fSmoothShow(setObj.zoomBoxDivName, 25, 0, 1, 0, 0.1);				
				if (intObj && setObj.objName != '') {
						if (navigator.appName.indexOf("Microsoft") != -1) {
								intObj.onmousemove = function() {return fDblCheckZoom(setObj, event);}
						} else { // Firefox, Opera, Safari etc.
								intObj.setAttribute("onmousemove", "fDblCheckZoom(" + setObj.objName + ", event);");
						}
				} 
			}else{ 
				faderDirections[setObj.zoomBoxDivName] = 1;
			}
		} else {
			document.getElementById(setObj.smallPhotoShadowDivName).style.display = 'none';			
			document.getElementById(setObj.flyBoxDivName).style.display = 'none';
			if(!fd || fd == 0 ){
				faderDirections[setObj.zoomBoxDivName] = -1;
				fSmoothShow(setObj.zoomBoxDivName, 25, 1, 0, 1, -0.1);						
				if (intObj && setObj.objName != '') {
					if (navigator.appName.indexOf("Microsoft") != -1) {
						intObj.onmousemove = "";
					}else { // Firefox, Opera, Safari etc.
						intObj.setAttribute("onmousemove", "");
					}
			  }
			}else{
				faderDirections[setObj.zoomBoxDivName] = -1;
			}
    }
	}

	function fSetFlySize(setObj) {
		if (setObj == null) {return;}
		var targetDiv = document.getElementById(setObj.flyBoxDivName);
		if (targetDiv != null) {
		    if (setObj.fly_w != NaN) {
    			targetDiv.style.width = Math.floor(setObj.fly_w) + 'px';
			} 
		    if (setObj.fly_h != NaN) {
    			targetDiv.style.height = Math.floor(setObj.fly_h) + 'px';
		    }
		}
	}
	
	function fDblCheckZoom(setObj, evt) {
		if (setObj == null) {return;}
		var flyDiv = document.getElementById(setObj.flyBoxDivName);
		var o = fPosition(evt);
		if ((flyDiv.style.display == '') && ((o.x < (setObj.smallPhotoOffset.x + setObj.popupOffset.x)) || (o.x > ((setObj.smallPhotoOffset.x + setObj.popupOffset.x) + setObj.photo_w)) || (o.y < (setObj.smallPhotoOffset.y + setObj.popupOffset.y)) || (o.y > ((setObj.smallPhotoOffset.y + setObj.popupOffset.y) + setObj.photo_h )))) {
			fnStepOnOff(setObj, false);
		}
	}


	function fnCalculateZoomPos(setObj) {	
		if (setObj.popupDivName != '') {
			var popupDiv = document.getElementById(setObj.popupDivName);
			if (popupDiv != null) {
				offsetPair = findPosMagnify(document.getElementById(setObj.popupDivName));
				setObj.popupOffset.x = offsetPair[0];
				setObj.popupOffset.y = offsetPair[1];
			}
		}
		
		if (setObj == null) {return;}
		var imgplace = 	document.getElementById(setObj.smallPhotoDivName);
		var imgpos = findPosMagnify(imgplace);
		var detpos = findPosMagnify(imgplace);

		dx = parseInt(imgplace.style.width);
		dx = imgplace.offsetWidth
		detpos[0] = imgpos[0] + dx;

		var photoplace = document.getElementById(setObj.smallPhotoDivName);
		var photoplaceshadow = document.getElementById(setObj.smallPhotoShadowDivName);
		var zoombox = document.getElementById(setObj.zoomBoxDivName);

		photoplace.style.left = imgpos[0] - setObj.popupOffset.x + 'px';
		photoplace.style.top = imgpos[1] - setObj.popupOffset.y + 'px';
		photoplace.style.display = '';

		photoplaceshadow.style.left = imgpos[0] - setObj.popupOffset.x + 'px';
		photoplaceshadow.style.top = imgpos[1] - setObj.popupOffset.y + 'px';
		
	  zoombox.style.left = detpos[0] - setObj.popupOffset.x + 'px';
		zoombox.style.top = detpos[1] - setObj.popupOffset.y + 'px';
		
		zoombox.style.width = setObj.zoom_w + 'px';
		zoombox.style.height = setObj.zoom_h + 'px';

		setObj.smallPhotoOffset.x = imgpos[0] - setObj.popupOffset.x;
		setObj.smallPhotoOffset.y = imgpos[1] - setObj.popupOffset.y;

		fSetFlySize(setObj);
	}

	function fnShowLargeColour(sender, colourImgSrc, rgbCode, colourCaption) {
		var colourDiv = document.getElementById("LgeColour");
		if (colourDiv != null) {
			var imgObj = document.getElementById("LgeImage");
			var clrBoxObj = document.getElementById("LgeColourBox");
			var captionObj = document.getElementById("LgeCaption");
			if ((imgObj != null) && (captionObj != null) && (clrBoxObj != null)) {
				clrBoxObj.style.display = 'none';
				imgObj.style.display = 'none';
				clrBoxObj.style.backgroundColor = colourDiv.style.backgroundColor;
				if (colourImgSrc != '') {
					if (imgObj.nodeName == 'IMG') {
						imgObj.src = colourImgSrc;
						imgObj.style.display = '';
					}
				} else if (rgbCode != '') {
					if (clrBoxObj.nodeName == 'DIV') {
						clrBoxObj.style.display = '';
						clrBoxObj.style.backgroundColor = rgbCode;
					}
				}
				if (captionObj.nodeName == 'SPAN') {
					captionObj.innerHTML = colourCaption;
				}
				var imgpos = findPosMagnify(sender);
				colourDiv.style.left = imgpos[0] - 2 + 'px';
				colourDiv.style.top = imgpos[1] - 5 - parseInt(colourDiv.style.height) + 'px';
				colourDiv.style.display = '';
			}
		}
	}
	
	function fnHideLargeColour() {
		var colourDiv = document.getElementById("LgeColour");
		if (colourDiv != null) {
			colourDiv.style.display = 'none';
		}
		else {
		}
	}

	function findPosMagnify(obj) {
		if (obj != null) {
			var curleft = curtop = 0;
			if (obj.offsetParent) {
				curleft = obj.offsetLeft
				curtop = obj.offsetTop
				while (obj = obj.offsetParent) {
					curleft += obj.offsetLeft
					curtop += obj.offsetTop
				}
			}

			//during popup mode these two lines help a bit....
			//curleft = curleft - 224;
			//curtop = curtop - 55;
			
			
			return [curleft, curtop];
		}
		else {
			return [0, 0];
		}
	}
	
	function fnSetOpacity(obj, value) {
		if (obj != null) {
			if (value < 0.001 ) {value = 0;}
			if (value > 0.999 ) {value = 1;}
			obj.style.filter = 'alpha(opacity=' + 100*value + ')';
			obj.style.MozOpacity = value;
			obj.style.opacity = value;
			if(value == 1)
			{
				obj.style.filter = null;
			}
		}
	}

	function fSmoothShow(divName, delay, min, max, cur, dx) {
	//	console.log('divName: '+divName+', delay: '+delay+', min: '+min+', max: '+max+', cur: '+cur+', dx: '+dx+', faderDirections[divName]:'+faderDirections[divName])
		if(fadeIntervalIDs[divName] && fadeIntervalIDs[divName]!=null){
			clearInterval(fadeIntervalIDs[divName]);
			fadeIntervalIDs[divName]=null;
		}
		if (faderDirections[divName] * dx <= 0) {
		 //return;
		}
		var diff=faderDirections[divName] * dx;		
		var obj = document.getElementById(divName);
		
		
		if (obj != null) {
/*
			if (cur > 0) {
				if ((obj.style.display == 'none') || (obj.style.visibility == 'hidden')) {
					obj.style.display = '';
					obj.style.visibility = 'visible';
				}
			}
			else if ((dx <= 0) && (cur <= 0 - dx)) {
				obj.style.display = 'none';
				fadeValues[divName] = 1;
				fnSetOpacity(obj, cur);
	//			fadeValues[divName] = fadeValues[divName];
				return;
			}
		*/
			//if (((dx > 0) && (cur < max)) || ((dx < 0) && (cur > max))) {
				cur += diff;
				
				if(cur < min){
					cur = min;
					faderDirections[divName]=0;
				}
				if(cur > max){
					cur = max;
					faderDirections[divName]=0;
				}
				fnSetOpacity(obj, cur);
				fadeValues[divName] = cur;
				//if (faderDirections[divName] * dx > 0) {
				if(cur==0){
					obj.style.display = 'none';
				}else{
					if ((obj.style.display == 'none') || (obj.style.visibility == 'hidden')) {
						obj.style.display = '';
						obj.style.visibility = 'visible';
					}
				}
				if(cur > 0 && cur < 1){
					fadeIntervalIDs[divName]=setInterval("fSmoothShow('" + divName + "', " + delay + ', ' + min +', ' + max + ', ' + cur + ', ' + dx + ')', delay);
					//setTimeout("fSmoothShow('" + divName + "', " + delay + ', ' + min +', ' + max + ', ' + cur + ', ' + dx + ')', delay);
				}
			//}
		}
	}



	function fGetDivAbsPos(obj, curs) {
		var cursor = {x:0, y:0};
		if (obj != null) {
			if (curs == null) {
				curs = {x:0, y:0};
			}
			if (curs.x == NaN) {curs.x = 0;}
			if (curs.y == NaN) {curs.y = 0;}
			x1 = parseInt(obj.style.left);
			y1 = parseInt(obj.style.top);
			if (x1 == NaN) {x1 = 0;}
			if (y1 == NaN) {y1 = 0;}
			cursor.x = curs.x + x1;
			cursor.y = curs.y + y1;
			var parent = obj.parentNode;
			
			if ((parent != null) && (parent.id != '') && (parent.id != TopDivName)) {
			
				var parCurs = fGetDivAbsPos(parent, cursor);
				if (parCurs != null) {
					cursor = parCurs;
				}
			}
		}
		return cursor;

	}
	
	function fPosition(e) {
		e = e || window.event;
		var cursor = { x:0, y: 0 };
		if (e.pageX || e.pageY) {
			cursor.x = e.pageX;
			cursor.y = e.pageY;
		} else {
			var de = document.documentElement;
			var b = document.body;

			//alert("x clientX " + e.clientX + " descrollleft " + de.scrollLeft + " b.scrollleft " + b.scrollLeft + " de.clientLeft " + de.clientLeft);
			//alert("y clientY " + e.clientY + " descrollTop " + de.scrollTop + " b.scrollTop " + b.scrollTop + " de.clientTop " + de.clientTop);
			cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
			cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);   
		}
		return cursor;
	}



/*!
 * jQuery UI 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
(function(c){c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.2",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==
"hidden")return false;b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,
NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect",
"none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",
1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)?
!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);
;
/*!
 * jQuery UI Widget 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend({},c.options);b[e][a].prototype=
b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==undefined){h=i;return false}}):this.each(function(){var g=
b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();
this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*
 * jQuery UI Position 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Position
 */
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);
;
/*
/*
 * jQuery UI Dialog 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *  jquery.ui.button.js
 *	jquery.ui.draggable.js
 *	jquery.ui.mouse.js
 *	jquery.ui.position.js
 *	jquery.ui.resizable.js
 */
(function(c){c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"Close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");var a=this,b=a.options,d=b.title||a.originalTitle||"&#160;",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+
b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),
h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id",
e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");
a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!==
b.uiDialog[0])d=Math.max(d,c(this).css("z-index"))});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+=1;d.uiDialog.css("z-index",
c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;d.next().length&&d.appendTo("body");a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false}else if(e.target===
f[0]&&e.shiftKey){g.focus(1);return false}}});c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();a._trigger("open");a._isOpen=true;return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,function(){return!(d=true)});if(d){c.each(a,
function(g,f){g=c('<button type="button"></button>').text(g).click(function(){f.apply(b.element[0],arguments)}).appendTo(e);c.fn.button&&g.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging");
b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size}}a=a===undefined?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position");
a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop",
f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0];a=a||c.ui.dialog.prototype.options.position;if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(e,g){if(+b[e]===b[e]){d[e]=b[e];b[e]=
g}})}else if(typeof a==="object"){if("left"in a){b[0]="left";d[0]=a.left}else if("right"in a){b[0]="right";d[0]=-a.right}if("top"in a){b[1]="top";d[1]=a.top}else if("bottom"in a){b[1]="bottom";d[1]=-a.bottom}}(a=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position({my:b.join(" "),at:b.join(" "),offset:d.join(" "),of:window,collision:"fit",using:function(e){var g=c(this).css(e).offset().top;g<0&&c(this).css("top",e.top-g)}});a||this.uiDialog.hide()},_setOption:function(a,
b){var d=this,e=d.uiDialog,g=e.is(":data(resizable)"),f=false;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case "draggable":b?d._makeDraggable():e.draggable("destroy");break;
case "height":f=true;break;case "maxHeight":g&&e.resizable("option","maxHeight",b);f=true;break;case "maxWidth":g&&e.resizable("option","maxWidth",b);f=true;break;case "minHeight":g&&e.resizable("option","minHeight",b);f=true;break;case "minWidth":g&&e.resizable("option","minWidth",b);f=true;break;case "position":d._position(b);break;case "resizable":g&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "title":c(".ui-dialog-title",
d.uiDialogTitlebar).html(""+(b||"&#160;"));break;case "width":f=true;break}c.Widget.prototype._setOption.apply(d,arguments);f&&d._size()},_size:function(){var a=this.options,b;this.element.css({width:"auto",minHeight:0,height:0});b=this.uiDialog.css({height:"auto",width:a.width}).height();this.element.css(a.height==="auto"?{minHeight:Math.max(a.minHeight-b,0),height:"auto"}:{minHeight:0,height:Math.max(a.height-b,0)}).show();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",
this._minHeight())}});c.extend(c.ui.dialog,{version:"1.8.2",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=c.ui.dialog.overlay.create(a)}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&&
c(document).bind(c.ui.dialog.overlay.events,function(d){return c(d.target).zIndex()>=c.ui.dialog.overlay.maxZ})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});c.fn.bgiframe&&
b.bgiframe();this.instances.push(b);return b},destroy:function(a){this.oldInstances.push(this.instances.splice(c.inArray(a,this.instances),1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var b=0;c.each(this.instances,function(){b=Math.max(b,this.css("z-index"))});this.maxZ=b},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.documentElement.offsetHeight,
document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(this)});a.css({width:0,
height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
;
/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};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);


/*****************************************************************************************************************************************/

// Extend the jQuery UI dialog box to allow content from within page or an ajax call
$.extend($.ui.dialog.prototype, {
		///<summary>
		/// Function to retrieve an html snippet to display in the popup
		///</summary>
		///<param name="src">
		/// string that refers to the href of the data, strings starting with # source the data from within the page, others are treated as ajax calls
		///</param>
		///<param name="dat">
		/// (optional) string that is the result of jQuery.serialise() called on any form to be posted
		///</param>		
    'loadContent': function(src, dat) {	
				// clear the popup and set its title to loading
        var me = this.element;
        me.dialog('option', 'title', '<h2>Loading</h2>');  				
        var c = $('.content:first', me)	
				c.empty();
				// is the src a reference to part of the current page?
        if (src.length > 1 && src.substring(0, 1) == '#') {
					// Make a reference to the holding element
					var s=$(src)
					// Store the holding element reference to be used when closing the popup (data is returned to the original holder)
					 me.data('return_to',src);
					 // add the contents of the holding element to the display area of the popup
           c.append(s.contents());
					 // ensure the holding element is empty and add a class so that we can identify it as opened in the dialogeue box 
					 s.empty().addClass('popped');
					 // use the UI function 'open' to display the popup
			 		 me.dialog('open');
					 // call the refreshDisplay function to set up any behaviours in the popup
           me.dialog('refreshDisplay');
        } else {
					// the data source is an ajax call so the loading message will be the initial content
					c.html('<p class="loading_message">Loading, please wait...</p>');					
					// ensure dat is not undefined 
					if (!dat) { dat = ''; }
					me.data('alreadyLoaded',false);
					var splitSrc=src.split('#')
					if(splitSrc.length>1){
						window.location.hash=splitSrc[1];
					}
					// make the ajax call						
				  $.ajax({ type: "GET", url: src, data: dat, 
						success: function(xhr) {
						// if, for some reason, a complete page is returned we only want the contents of the body tag, so strip the rest out.
						if(xhr.indexOf('<html')>-1){
							var idx = xhr.indexOf('<body');
							if(idx>-1){
									xhr=xhr.substr(idx);
									xhr=xhr.substr(xhr.indexOf('>')+1).replace('</body>','').replace('</html>','')
							}else{
								xhr='page load error'
							};									
						}
						// populate the contents section of the popup
						c.html(xhr);
						// call the refreshDisplay function to set up any behaviours in the popup
						me.dialog('refreshDisplay') 
						} 
					});
					// use the UI function 'open' to display the popup
		  	 	me.dialog('open');		   
        }		
    },
		///<summary>
		/// Function to set up any behavious that need to be applied after the popup has rendered			
		///</summary>
    'refreshDisplay': function() {		
    	var me = this.element;
			// nextSettings is an optional string that is set when calling the popup
			// string is a comma separated list of name:value pairs
			if(me.dialog('option','nextSettings').length>0){
				var arr=me.dialog('option','nextSettings').split(',');
				// iterate through the nema value pairs and apply them using the UI dialog option function
				for(var i=0;i<arr.length;i++){
					var s=arr[i].split(':');
					if(s.length==2){
						if(!isNaN(parseInt(s[1]))){
							me.dialog('option',s[0],parseInt(s[1]));
						}else{
							me.dialog('option',s[0],s[1]);
						}
					}
				}
				//clear the nextSettings string
				me.dialog('option','nextSettings','')
			}
			// if the contents has an element with the class of heading, or an h1 tag use its contents as the popup title
			var txt = '';
			var $txt=$('.c .content .heading,.c .content .personalised_header, .c .content h1', me);
			if($txt.length>0){
				txt = $($txt[0]).hide().html(); 
			}
			me.dialog('option', 'title', '<h2>' + txt + '</h2>');
			// runOnLoad is a placeholder for functions that need to be executed on the popup
			// the popup should override the base function with its own specific version if required
			if(typeof(runOnLoad)=='function'){
				runOnLoad(me);
			}
			$('.product_details',me).each(function(){setUpProduct(this)});
			// click any default size button
			$('.content:first .add_to_cart .colour input:radio:checked',me).trigger('click'); 
			// the close link is present in popups that are common to standared and advanced product detail and needs to be hidden when using the layered popup
			$('.content:first .close_link',me).css('display','none');
			// tidy up the email bag response 
			$('.form_EmailShoppingBag a:first',me).addClass('keep').parent().addClass('link');
			$('.form_EmailShoppingBag div:last > *:not(.keep)',me).remove();
			var cont=$('.content',me).css({'overflow':'','height':''});
			var myH=me.closest('.ui-dialog').outerHeight(true);
			var contH=cont.height();
			var scrolling=false;
			if(myH>$(window).height()){		
				var maxH = $(window).height()-(myH-contH);
				if(contH > maxH){
					cont.css({'overflow':'auto','height':maxH+'px'});		
					 scrolling=true;	
				}else{
					cont.css({'height':maxH+'px'});
				}
			}
			var mat=$('table.matrix',me)
			if(mat.length>0){
				var contW=cont.width();
			  var tabW=mat.width();
				if(tabW > contW){
					var diffW = me.width() - contW;
					if(scrolling){diffW+=20;}
					var newW = $(window).width()-80;
					if(tabW + diffW < newW){
						newW = tabW + diffW;
					}
					me.dialog('option', 'width', newW+'px');		
				}
			}
			
			$('.additional_info_popup a',me).attr({'href':'#'+me.attr('id'),'target':''})		
			// centre the popup in the page
			me.dialog('option', 'position', 'center');
		}
});


/*
* Popup functionality 
* Initial popup is a modal dialog (creates an overlay that obscures page content) and is referenced in the global variable modal_window
* Subsequent popups are layered over the modal one
* closing the modal dialog closes all other popups. 
*/

///<summary>
/// Creates a new popup layer with the given id and settings using the jQuery UI dialog box
///</summary>
///<param name="id">
/// string a unique id that will be used to reference the pop up layer
///</param>
///<param name="settings">
/// javascript object available settings are defined in the jQuery UI documentation
///</param>
///<returns>
/// jQuery UI dialog box
///</returns>
function makePopup(id, settings){
	if(!id){id='popup_layer';}
	if(!settings){
		// default settings	
		settings={
			modal:false,
			dialogClass:'estar_modal',
			width:640,
			minHeight:178,
			maxHeight:600,
			autoOpen:false,
			resizable:false,
			position:'center',
			beforeClose: function() {
			// if the contents of the popup are taken from within the page they must be returned when the popup closes.
				var me = $(this);
				var returnMeTo=me.data('return_to');
				if(returnMeTo && returnMeTo.length>0){
					$(returnMeTo).removeClass('popped').append($('.content:first', me).contents())
					if(returnMeTo.indexOf('#fakeform_')==0){
						returnMeTo=returnMeTo.replace('fakeform_','')
						$(returnMeTo).removeClass('popped_up_form');
					}
					me.data('return_to','')
				}
				if(me.dialog( "option", "modal" )==true){
					closePopups();
				}
			}
			
		};
	}
	if(id == "modal_popup"){
		settings.modal=true;
		// this is a custom setting which is called before the beforeClose function, used to close all child popups when closing the first one
		//settings.beforeclose =function(){closePopups()};
	}
	// create the object to be displayed and add it to the page
	// the classes n, ne, nw, w, e, s, sw and se are for display purposes, giving the option to use styling that was familiar to our designers from previous popup implementations, the popup will also inherit the styling classes from the jQuery UI, so themes can be used if preferred.
	var popup=$('<div id="'+id+'"><div class="w"><div class="e"><div class="c"><div class="content">Loading, please wait...</div></div></div></div><div><div class="sw"><div class="se"><div class="s"></div></div></div></div></div>');	
	$('body').append(popup);
	// apply the jQuery UI dialog box 
	popup.dialog(settings);
	return popup;
}


///<summary>
/// Displays an html snippet in an overlayed layer
///</summary>
///<param name="type">
/// Integer - reperesents the kinds of data to be displayed
///</param>
///<param name="pageUrl">
/// string href of the data to be displayed, can be an in-page element referenced by "#id" or a server call "/pagename.aspx?something=whatever"
///</param>

function popup(type, pageUrl, formpart){
	/// The id of the popup layer will be determned and put into this string
	var selector='';
	/// settings contains a comma separated string (no spaces) which can be used to set the dimensions of the popup
  /// integer values for width, height, minHeight, minWidth,  maxHeight and maxWidth are accepted
  /// min and max values need the other values set to force a resize	
	/// i.e. minWidth will not necessarily resize the popup without a corresponding width setting 
	var settings='width:600';
	switch(type){
		case 1: // Basic information page
			settings='width:600,position:center;height:auto;maxHeight:'+$(window).height();
			break;
		case 2: // Zoomify / Large image
			settings='width:600,position:center';
			break;
		case 3: //Pop up forms: Email a friend, Reviews etc
			settings='width:600,position:center';
			break;
		case 4: //
			break;
		case 5: // Product detail
			settings='width:840,position:center';
			break;
		case 6:	// Online Book
			settings='width:840,minHeight:605,position:center';
			break;	
		case 7:	// personalisation form
			settings='width:550,position:center,modal:true';
			break;	
		default:
			break;
	}
	// ensure that the first popup is a modal one
	if($('.ui-widget-overlay').length == 0){
		// there are currently no popups open, so give this one the modal id
		selector='modal_popup';
	}else{
		// there is already a popup open so this id should match the data type 
		if(type==7){
		 selector = 'modal_layer_'+type;
		}else{
			selector = 'popup_layer_'+type;
		}
	}	
	// has this popup already been created? if not create it
	var p = $('#'+selector);
	if(p.length == 0){
		p = makePopup(selector,false);
	}
	// the settings passed are applied to the popup once it has been populated, so we set a variable within the dialogue box object
	if(settings.length >0){
		p.dialog("option","nextSettings",settings);
	}else{
		p.dialog("option","nextSettings","");
	}
	
	if(pageUrl.substring(0,1)=="#"){
		// the data to be displayed is an in-page element, referenced by an id
		if(formpart){
			var dummyform=$('<form class="dummyform" />');
			$(pageUrl).contents().wrapAll(dummyform);
		}
		p.dialog('loadContent',pageUrl);
	}else{
		// the data is a server call so we need to add a parameter serveas=ajax to the querystring, so the server knows to only serve an html snippet, not an entire page
			var parts=pageUrl.split('?');
				var d="";
			if(parts.length>1){
				d=parts[1] + '&serveas=ajax';
			}else{
				d='&serveas=ajax';
			}
			p.dialog('loadContent',parts[0],d);
	}
	//put the popup into the centre of the screen
	p.dialog('position','center');	
	if(shopping_cart_popup){
		shopping_cart_popup.setActivePopup(null);
	}
	return p;
}
///<summary>
/// Closes the main popup
/// Function is to be called from outside of the popup layer, since the popup layers have their own close button and functionality
///</summary>
function closePopup(){
 if($('#modal_popup').dialog('isOpen')){
	$('#modal_popup').dialog('close');
	// the dialog object's close function has been changed so that if it is the first popup opened it closes the child elements first
 }
}
///<summary>
/// Closes all child popups (the main popup has been modified to call this function before it closes)
///</summary>
function closePopups(){	
	var p = $('div[id^=popup_layer]');
	if(p.length > 0){
		p.dialog('close');
	}
}

///<summary>
/// Posts a form element formObj and displays the results in a specified UI dialog window popup
///</summary>
///<param name="formObj">
/// HTML form element
///</param>
///<param name="popup">
/// jQuery UI dialog object
///</param>
function popup_formpost(formObj,popup){
	var f=$(formObj);
	$(popup).dialog('loadContent',f.attr('action'),f.serialize()+'&serveas=ajax');
}
 
/// <summary>
/// Simulates a table type display on a series of 'cell' elements within a container, called as a jQuery function on the container element (usually a div block containing product items).
/// Requires a width attribute set in the css for the 'cell' element, which is used to calculate the number of columns the display will have in each row.
/// Height of the cells in each row is set to match the tallest of that row's cells
/// Optionally elements within the cells can have their heights matched across a row to give the impression of sub-rows.
/// </summary>
/// <param name="settings" type="object">
///	Optional settings object contains css selector for the cell elements within the container
/// Also contains optional css selectors for sub-row elements within each cell
/// </param>
/// <returns>
/// jQuery object representing the container div(s), 'cell' elements within the div will have had additional classes added to identify their position within the grid e.g. row_3 col_0, sub-row elements will also have additional classes subrow_0, subrow_1, subrow_2 etc
/// </returns>
/// <example>
/// $('.products').tabulate({cell_selector:'.item', sub_rows:'.item_name, .rating, .pricing, .links, .more_colours'});
/// Finds each element with a class of 'products' and arranges the elements within it that have a class of 'item' into rows and columns, matching the heights of each 'item' element across a row.
/// For each row the elements with 'item_name' are height matched, as are the 'rating', 'pricing', 'links' and 'more_colour' element
/// </example>
(function($){   
 $.fn.tabulate = function(settings) {   		
    var defaults = {  
			cell_selector:'.item',
			sub_rows:'.item_name, .pricing, .links',
			single_row:false
    };
		// Each container that matches the cell_selector identifier MUST contain an element that matches EACH of the sub_rows selectors   
    var o = $.extend(defaults, settings);  
    return this.each(function() {
			// make a jQuery reference to the container object.
			var selfref=$(this);
			// find the items within the container
      var cells = $(o.cell_selector,selfref).css({'float':'left'});
			// cols is the number of cells that will fit across the main container (i.e. the number of columns)
			var cols
			if(!o.single_row){
				cols = Math.floor(selfref.innerWidth()/cells.outerWidth(true));
			}else{
				cols=cells.length;
			}
			if(cells.length > 0){
				var row=0;
				// iterate through the items, set row and column identifier classes, add dividers
				cells.each(function(i){
					var cell=$(this).addClass('row_'+row).addClass('col_'+(i%cols+1));
					// if we have reached the end of the row add a divider and increment the row identifier
					if(!o.single_row && (i%cols == cols-1 || i == cells.length-1)){
						cell.after($('<div class="divider" style="clear:left"></div>'));
						row ++;
					}
				});
				// within each row we need to find the largest height for each of the 'sub_rows' elements and
				// set the others within that row to match it 
				// we will be using arrays to store the maximum heights of each row and subrow as we iterate through the cells	
				// childHeights is a two dimensional array, storing an array for each row to containthe sub-row heights			
				var heights=[];
				var childHeights=[];
				var childSelectors=[]
				if(o.sub_rows&&o.sub_rows.length>0){
					childSelectors=o.sub_rows.split(',');
				}
				for(var i=0; i<childSelectors.length; i++){
					childHeights[i]=[];
				}
				
				// this function is called once the object has been defined, and once again when the window has loaded (images loading in will affect the heights and need to be accounted for)
				function setHeights(e){
					// iterate through the cells 
					cells.each(function(idx){
						// idx is the index of the cell, we can use this along with the number of colums to calculate the row number
						var myRow=Math.floor(idx/cols);
						// iterate through the sub-row elements within this cell 
						for(var i=0; i<childSelectors.length; i++){
							// find the current sub-row element, and clear any inlne height style
							var child=$(childSelectors[i],this).css("height",'');
							// measure the rendered height of the sub-row element
							var childH=child.height();		
							// if the measured height is the highest one so far for this row store it in the two dimensional array				
							if(childHeights[i][myRow]==undefined || childHeights[i][myRow]==null || childHeights[i][myRow] < childH){
								childHeights[i][myRow] = childH;
							}
						}					
					});	
					// using the two dimensional array we have just populated set the height for each element to be matched in each row and add a subrow identifier class
					cells.each(function(idx){
						var myRow=Math.floor(idx/cols);	
						for(var i=0; i<childSelectors.length; i++){
							$(childSelectors[i],this).css("height", childHeights[i][myRow]+"px").addClass('subrow_'+i);
						}
					});	
					// now that the sub-row heights have been set we can set the main row heights
					// iterate through the cell elements
					cells.each(function(idx){
						// calculate the row number isung the cell index and the coloumn count
						var myRow=Math.floor(idx/cols);
						// clear any inline height styling
						$(this).css('height','');
						// measure the rendered height of the current cell
						var myH = $(this).height();	
						// if this is the greatest height for this row store the value in the heights array				
						if(heights[myRow]==undefined || heights[myRow]==null || heights[myRow] < myH){
							heights[myRow]=myH;
						}					
					});	
					//set the height of each cell to match the highest in its row
					cells.each(function(idx){
						var myRow=Math.floor(idx/cols);
						 $(this).css("height",heights[myRow]+"px");		
					});	
					
				}
				
				// now we have set up the basic object call the setHeights function()
				setHeights();
				// Images that load into the cells will affect the heights and need tio n=be accounted for so we neet to run the setheights() function again when the page has fully loaded (using the image onload event is unreliable in webkit browsers so we need to use the window onload event
				$(window).bind('load',function(e){setHeights(e);});	
			}
    });   
 };   
})(jQuery);

///<summary>
///  runs after the tabulate function, for tabulated containers displayed side by side.
///  matches the heights of the subrow elements within all cells with the same row_ number.
///  matches the cell heights across all cells with the same row_ number 
///</summary>
(function($){   
 $.fn.uberTabulate = function(opts) {
	 // the tabulate function will have set classes to identify rows and subrows: row_0, row_1, row_2, subrow_0, subrow_1, subrow_2 etc. we can use these to match heights between different 'tabulated' objects within the container.
    return this.each(function() {															
		var selfref=$(this);
		var row_idx=0;
		// iterate through the main row elements using the 'row_XX' class
		var current_row=$('.row_'+(row_idx),selfref);		
		while(current_row.length>0){
				// create a variable to store the greatest height value
				var maxH=0;
				// iterate through the sub-row elements using the 'subrow_XX' class
			  var sub_row_idx=0;
				var current_sub_row=$('.subrow_'+(sub_row_idx),current_row);				
				while(current_sub_row.length>0){	
					// reset the height variable
					maxH=0;
					//iterate through each item in the sub-row and find the highest height value
					current_sub_row.each(function(){
						var myH=$(this).height();
						if(myH>maxH){
							maxH=myH;
						}
					});
					// set the height of each sub-row element to match the highest found
					current_sub_row.css('height',maxH+'px');
					//increment the sub-row counter
					sub_row_idx++;
					//find the next sub-row
					current_sub_row=$('.subrow_'+(sub_row_idx),current_row);		
				}
				// reset the height variable		
				maxH=0;
				//iterate through the cells in this row and find the greatest height value
				current_row.each(function(){
					var myH=$(this).height();
					if(myH>maxH){
						maxH=myH
					}
				});
				// set the height value of the row to match the tallest cell
				current_row.css('height',maxH+'px');
				// increment the row counter
				row_idx++;
				// find the next row
				current_row=$('.row_'+(row_idx),selfref);
			}
    });   
 };   
})(jQuery);

/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.0  (04/11/2007)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/assets/spacer.gif';
	};	
	$.ifixpng.setSize = function(loadedImg,targetImg) {
		var $l=$(loadedImg);
		var $t=$(targetImg);
		var h=$t.css('height')=='auto'?$l.height():$t.css('height');
		var w=$t.css('width')=='auto'?$l.width():$t.css('width');
		t.css('height',h).css('width',w).positionFix();
		$l.remove();
	};	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src='"+src+"')";
		}
	};
	var holder=null;
	$.fn.ifixpng = hack.ltie7 ? function() {
		if(holder==null){
			holder=$('<div style="positon:absolute;left:-9999px;top:-9999px"/>');
			$('body').append(holder);
		}
    	return this.each(function() {
			var $$ = $(this);
			var base = $('base').attr('href'); 
			if ($$.is('img') || $$.is('input')) { 
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { 
						// use source tag value if set 
						var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						// alert($$.attr('alt')+': '+$$.attr('width')+': '+$$.attr('height'))
						var w=$$.attr('width')||$$.css('width') ;
						if(w=='auto'){w=$$.width();}
						var h=$$.attr('height')||$$.css('height');
						if(h=='auto'){h=$$.height();}
						$$.css({filter:hack.filter(source), width:w, height:h})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix()
						  .attr('onmouseover','')
						  .attr('onmouseout','')
						  .addClass('.pngfixed');
						if(w == 0||h==0){
						holder.append($('<img src="'+source+'"  />').bind('load',function(){$.ifixpng.setSize(this,$$)}));
						}						
					}
				}
			}
		});
	} : function() { return this; };	
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { 
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };	
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};
})(jQuery);



///<summary>
/// Handles the show/hide of the swatch images in the listings
///</summary>
function setMoreColoursHover(){
	//use jQuery.hover(mouseOverFunction,mouseOutFunction)
	$('.more_colours .colour_swatches').parent().hover(
		function(){$('.colour_swatches',this).slideDown(300);},
		function(){$('.colour_swatches',this).slideUp(300);}
	);
}

///<summary>
/// Where there are multiple reviews in a product detail page hide all but the first and add show/hide functionality
///</summary>
(function($){   
 $.fn.truncateReviews = function(opts) { 
    return this.each(function() {
		var selfref=$(this);
		if(selfref.hasClass('truncated')){
			return;
		}
		selfref.addClass('truncated');
		function showRatings(){
			$('.hide_link',selfref).css('display','')
			$('.show_link',selfref).css('display','none')
			$('.review',selfref).css('display','')
			$('.ratings',selfref).css('display','')
		}
		function hideRatings(){
			$('.ratings',selfref).css('display','none')
			$('.hide_link',selfref).css('display','none')
			$('.show_link',selfref).css('display','')
			$('.review',selfref).css('display','none')
			$('.review:first',selfref).css('display','')
		}
		var reviews=$('.reviews',selfref)
		var count=$('.review',reviews).length;
		if(count>1){
			var hideLinkTxt='<a href="#" class="hide_link">Hide Reviews</a>';
			var showLinkTxt='<a href="#" class="show_link">Read a further '+(count-1)+' reviews</a>';
			reviews.prepend($(hideLinkTxt));
			reviews.append($(hideLinkTxt));
			$('.review:first',reviews).after($(showLinkTxt));
			$('.hide_link',reviews).bind('click',function(evt){evt.preventDefault();hideRatings()});
			$('.show_link',reviews).bind('click',function(evt){evt.preventDefault();showRatings()})
		}
		hideRatings();
    });   
 };   
})(jQuery);


///<summary>
/// Limits the number of list items displayed to a given number and adds a More/Less link to show the remainder
///</summary>
(function($){   
 $.fn.limitLinkDisplay = function(opts) {  
    var defaults = {  
		link_count:10,
		more_text:'More Links',
		less_text:'Hide Links'
    };   
    var o = $.extend(defaults, opts);  
    return this.each(function() {
		var selfref=$(this);
		if(selfref.hasClass('link_limited')){
			return;
		}
    $('>li',this).each(function(idx){
			if(idx>=o.link_count){
				$(this).addClass('toggle_me').css('display','none');
			}
		});
		var links=$('.toggle_me',selfref)
		if(links.length>0){
			var lnk=$('<a href="#">'+o.more_text+'</a>');
			lnk
			selfref.append(lnk);
			lnk.wrap('<li class="more_link"/>')
			lnk.bind('click',function(ev){ev.preventDefault();toggleMe();this.blur();})
			var is_open=false;
			function toggleMe(){
				if(is_open){
					$('.toggle_me',selfref).css('display','none')
					$('.more_link a',selfref).html(o.more_text).removeClass('less');
					is_open=false;
				}else{
					$('.toggle_me',selfref).css('display','')
					$('.more_link a',selfref).html(o.less_text).addClass('less');
					is_open=true;				
				}
			}			
		}
    });   
 };   
})(jQuery);


///<summary>
/// Hides the contents of an element and replaces with a link that reveals the content on mouseover
///</summary>
(function($){   
 $.fn.tooltip = function(opts) {  
    var defaults = {  
		linkText:'<span>(<span class="q">?</span>)</span>',
		popupClass:'tooltip_message',
		vPosition:'above',
		hAlign:'center'
    };   
    var o = $.extend(defaults, opts);  
    return this.each(function() {
		var selfref=$(this);
		var tip=[];	
		if(selfref.data('tooltip')){
			return;
		}
		function showTip(){
			if(tip.length==0){
				tip=$('<div style="position:absolute;display:none;" class="'+o.popupClass+'"><div class="message_wrapper"><div class="message_body"></div></div></div>');
				$('.message_body',tip).html(selfref.data('tooltip'));
				selfref.append(tip);
			}
			tip.css('display','block');
			positionTip();
		}
		function positionTip(){
			var new_x=0;
			var new_y=0;
			switch(o.vPosition){
				case "above":
					new_y=tip.outerHeight(true)*-1
					break;
				case "below":
					new_y=selfref.outerHeight(true);
					break;
				case "middle":
					new_y=((tip.outerHeight(true)*-1) + selfref.outerHeight(true))/2;
					break;
				default:
					break;
			}
			switch(o.hAlign){
				case "left":
					new_x=0;
					break;
				case "right":
					new_x=(tip.outerWidth(true)*-1) + selfref.outerWidth(true);
					break;
				case "center":
					new_x=((tip.outerWidth(true)*-1) + selfref.outerWidth(true))/2;
					break;
				default:
					break;
			}
			tip.css({'top':new_y+'px','left':new_x+'px'});
		}
		function hideTip(){
			tip.css('display','none');
		}
    selfref.data('tooltip',selfref.html());
		selfref.empty();
		if(selfref.css('position')=='static'){selfref.css('position','relative')}
		var lnk=$(o.linkText);
		selfref.append(lnk);
		selfref.hover(showTip,hideTip);
		selfref.addClass('tooltip_initialised');
    });   
 };   
})(jQuery);

$.fn.make_tabs = function(opts) { 
    var defaults = {  
		item_selector:'.info_item',
		link_selector:'.info_heading',
		content_selector:'.info_content',
		showing:''
    };  
	
    var o = $.extend(defaults, opts); 
	
    return this.each(function() {
							  
		var selfref=$(this);
		if(selfref.hasClass('current_tab')){return;}
		selfref.addClass('current_tab')
		var tabend=$('<span class="tab_end"><img alt="" src="/assets/spacer.gif"/></span>')
		var links=	$(o.link_selector +' h3',selfref).each(function(){
			var t=$(this);
			if(!(t.children('span:last-child').hasClass('tab_end'))){
				t.append(tabend);
			}
		});
		if(links.length>1){
			links.css('cursor','pointer');
		}
		selfref.displayHolder = $('<div class="tab_display"></div>');
		selfref.append(selfref.displayHolder)
		$(o.item_selector+':first',selfref).addClass("first");
		if($(o.item_selector).length>1){
			$(o.item_selector+':last',selfref).addClass("last");
		}
		selfref.showItem = function(toShow){	
		if($(this).hasClass('current_tab')){
			$(o.item_selector,this).removeClass("tab_open").addClass("tab_closed");
			$(o.content_selector,this).css('display','none');
			$(toShow).addClass("tab_open").removeClass("tab_closed");
			if(o.showing.length>0){
				o.showing.append($(o.content_selector,this.displayHolder));
			}
			var disp=$(o.content_selector,toShow).css('display','');
			this.displayHolder.html('').append(disp);
			o.showing=toShow;
		}
		} 
		$(o.item_selector,selfref).each(function(i){
			var me	= $(this);
			$(o.link_selector, this).click(function(){selfref.showItem(me);return false;});
		;});
		
		selfref.showItem($($(o.item_selector,selfref)[0]));
    }); 
 };

(function($){  
	//define an object with public methods and variables for each thumbnail image
	$.mouseOverPreview = function(el,indx,settings){	
	 if(this === window) { return new $.mouseOverPreview(el,indx,settings)}		
		this.item=$(el);
		if(this.item.data('mouseOverPreview')){return};
		this.item.data('mouseOverPreview',this);
		this.idx=indx;
		this.opts=settings;
		this.image=$('img:not(.overlay img)',el);
		this.popupImage=$('a img',el);
		this.popupImage.wrap('<div class="item_image_crop" />');
		this.imgSrc= this.image.attr('src');
		if(! this.imgSrc || this.imgSrc.length==0){
			return;
		}
		this.imgSrc=this.imgSrc.toLowerCase().replace('/medium/','/large/'); //preview site
		this.imgSrc=this.imgSrc.toLowerCase().replace('/thumb/','/medium/'); //live site ??
		this.imgTitle=this.image.attr('alt');
		this.preview=$('<div />');
		this.preview.addClass(this.opts.previewClass);
		this.item.append(this.preview);
		this.previewContent=$('<div class="preview_content"/>').css('visibility','hidden');
		
		this.previewContent.append($('<div class="name">'+this.imgTitle+'</div><div class="preview_image"><div class="preview_crop"><input id="img_source" type="hidden" value="'+this.imgSrc+'"><img title="'+this.imgTitle+'" /></div><div class="prices">'+$('.pricing', this.item.closest('.item')).html()+'</div></div>'));
		//src="'+this.imgSrc+'"
		this.previewMask=$('<div class="mask"  />');
		this.preview.append(this.previewContent);
		this.preview.append(this.previewMask);
		this.preview.css('display','none');
	}
	
	$.mouseOverPreview.prototype= {
		openPreview:function(){
				var me=this;
				me.item.css('z-index','10');
				var large_img_src = $("#img_source",me.item).val();
				$(".preview_crop img",me.item).attr("src",large_img_src);
				//me.item.find(".preview_crop img").attr("src",large_img_src);
				
				//me.item.css('overflow','visible');
				me.preview.css('display','block');
				me.showContents()
				//me.previewMask.animate({'height':me.preview.height(),'top':0},300,function(){me.showContents()});
		},
		showContents:function(){
			var me=this;
			me.preview.addClass('open');
			if(parseFloat($.browser.version) < 9 && $.browser.msie){
				me.previewContent.css({'visibility':'visible'});
			}else{
				me.previewContent.css({'visibility':'visible','opacity':'0'});
				me.previewContent.stop(false,false).animate({'opacity':1},400);
			}
			
		},
		closePreview:function(){
		
			var me=this;
			me.previewContent.css({'visibility':'hidden','opacity':''});
			me.preview.removeClass('open');
			me.previewContent.stop(true,true).animate({'opacity':0},100,function(){me.finishClose()});
			//me.previewMask.stop(true,true).animate({'height':2,'top':90},100,function(){me.finishClose()});
		},
		finishClose:function(){
			var me=this;
			me.previewContent.stop().css({'visibility':'hidden','opacity':''});
			me.previewMask.stop().css({'height':'2px','top':'90px'})
			me.preview.css('display','none').removeClass('open');
			me.item.css('z-index','');
			//me.item.css('overflow','hidden');			
			if(typeof(me.opts.closedCallback)=='function'){
				me.opts.closedCallback(me.idx);
			}	
		}		
	}	
	//jquery function returns array of mouseOverPreview objects
 	$.fn.mouseOverPreviews = function(opts) {  
    var defaults = {  
			previewClass:'preview',
			closedCallback:function(idx){}
    };   
    var o = $.extend(defaults, opts);
    return this.each(function(idx) {
   		new $.mouseOverPreview(this,idx,o);
    });   
 };   
})(jQuery);

function setMouseOverPreviews(){	
		var pending=null;
		var active=null;
		var currentlyOver=null;
		function hasClosed(idx){
			active=null;
			if(pending != null && pending==currentlyOver){
				mousedOver(pending);
			}
		}
		function mousedOver(idx,delay){
			// a delay is required to stop browser getting confused when mousing from one to another
			// without the delay the openPreview animation never completes
			if(delay){
				setTimeout(function(){mousedOver(idx)},50);
				return;
			}
			currentlyOver=idx;
			if(active==null){
				$(previews[idx]).data('mouseOverPreview').openPreview();
				
				active=idx;
				
			}else{
				pending=idx;
			}
			return false;
		}
		function mousedOut(idx){
			currentlyOver=null;
			pending=null;
			$(previews[idx]).data('mouseOverPreview').closePreview();
		}
		var previews=$('.products .item_image');
		/// make the structural changes to the HTML as required by the new mouseover functionality
		if(previews.length > 0 && $('.magnify_area',previews).length==0){
			// add in the magnify_area and colorswatch_overlay divs
			previews.prepend($('<div class="magnify_area"></div>'));
			previews.append($('<div class="colorswatch_overlay"><div class="more_colours" style="display: block;"><div class="colour_swatches"><div class="magnify_png"></div><div style="margin-bottom: 1px;">&nbsp;</div></div></div></div>'));  
			// make changes to the more colours area
			var more_colours=$('.item .more_colours').css('display','block').each(function(){
				// make a reference to the current div
				var more_colours_div=$(this);
				// how many swatches do we display
				var swatches_to_show=5;
				// cross sell listings may need different behaviour (such as showing fewer swatches) so test to see if we are in one
				var isCrossSell=(more_colours_div.closest('.cross_sell').length>0); 
				//remove any swatches that are not to be shown, and add a more link if necessary
				var swatch_lis=$('li',more_colours_div).each(function(idx){
					if(idx > swatches_to_show){
						$(this).remove();
					}else if(idx==swatches_to_show){
						$(this).html('<a href="#" onclick="moreColoursClick(this);return false;">more...</a>');
					}
				});
				if(swatch_lis.length>0){
					//find the overlay div which we are going to populate (it will be contained within the same item div)
					var overlay_div=$('.colorswatch_overlay',more_colours_div.closest('.item'));
					// add in the text 
					$(overlay_div).html("");
					$('.colour_swatches',more_colours_div).prepend($('<div class="magnify_png"></div><div class="colorswatch_text">'+$('p.heading',more_colours_div).html()+'</div>'));
					$('p.heading',more_colours_div).remove();
					// make the container for the images
					$('ul',more_colours_div).wrap($('<div class="colorswatch_imgs" style="display:none" />'));
					//move the colours div into its new holder
					overlay_div.append(more_colours_div);
				}
			})
			$('.colorswatch_imgs ul').append('&nbsp;');
			$(".spotlight .magnify_area, .spotlight .magnify_png").remove();
		}
		
		previews.mouseOverPreviews({closedCallback:hasClosed}).each(function(idx){var myID=idx; $(this).find('.magnify_area').hoverIntent(function(){mousedOver(myID,true)},function(){mousedOut(myID)})} );
		
		var color_swatch_hovers=$('.colour_swatches');
		
		function colorSwatchOver(hoverSpace){
		
		/* 
		// opacity animations removed for IE8 text rendering issues.
			hoverSpace.find('.colorswatch_text').css('display','none'); 
			hoverSpace.find('.colorswatch_imgs').css('display','block'); 
			hoverSpace.find('.colorswatch_imgs').animate({opacity:1},200)
			hoverSpace.find('.colorswatch_text').css('opacity','0'); 
			*/
			hoverSpace.find('.colorswatch_text').hide(); 
			hoverSpace.find('.colorswatch_imgs').show();
		}
		function colorSwatchOut(hoverSpace){/*
			hoverSpace.find('.colorswatch_text').css('display','block'); 
			hoverSpace.find('.colorswatch_imgs').css('display','none'); 
			hoverSpace.find('.colorswatch_text').animate({opacity:1},400);
			hoverSpace.find('.colorswatch_imgs').css('opacity','0'); 
			*/
			hoverSpace.find('.colorswatch_text').show(); 
			hoverSpace.find('.colorswatch_imgs').hide(); 
		}

		color_swatch_hovers.hoverIntent(function(){colorSwatchOver($(this))},function(){colorSwatchOut($(this))});
		
		return false;
	}
function moreColoursClick(lnk){
		// click the buy now link for the product (item)
		$('.buy_now a',$(lnk).closest('.item')).trigger('click');
		
	}
function mimicPlaceholderBlur(){
	var me=$(this);
	if(!me.val()||me.val().length==0){
		me.val(me.attr('placeholder'));
		me.addClass('placeholder');
	}
}
function mimicPlaceholderFocus(){
	var me=$(this);
	if(me.val()==me.attr('placeholder')){
		me.val('');		
	}
	me.removeClass('placeholder');
}
(function(){if(window.FUNCTIONALITY){return}
	FUNCTIONALITY={};
	
	var inp=document.createElement('input')
	FUNCTIONALITY.input={}
	var attrs='autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ');
	for (var i = 0; i<attrs.length; i++) {
    	FUNCTIONALITY.input[attrs[i]] = !!(attrs[i] in inp);
    }
		delete inp;
		FUNCTIONALITY.css=function(tagName,testStyle){
			var dv=document.createElement(tagName)
			var styleParts=testStyle.split(':');
			if(styleParts.length!=2){
				return null;
			}
			styleParts[1]=styleParts[1].replace(';','')
			dv.setAttribute('style',testStyle);			
			document.body.appendChild(dv)
			var r=($(dv).css(styleParts[0])==styleParts[1]);
			document.body.removeChild(dv);
			return r;
		}
		
})()

var shopping_cart_popup=null;

function hidexcartdata(){
	shopping_cart_popup.hide();
}
function popupCartSummary(){
	var dataUri = $('#BagViewLink').data('ajax_src');	
	if(dataUri.length>0){
		shopping_cart_popup.show(dataUri,true);
		//renderCartSummary()
		//$.ajax({ type: "POST", url: dataUri, data: {}, success: renderCartSummary });
	}
}

function getCartSummary(){
	var dataUri = $('#BagViewLink').data('ajax_src');	
	if(dataUri.length>0){
		shopping_cart_popup.show(dataUri,true);
        //renderCartSummary()
        closePopup();
		//$.ajax({ type: "POST", url: dataUri, data: {}, success: closePopup });
	}
}

function renderCartSummary(content){
	shopping_cart_popup.renderContent(content);
	window.scrollTo(0,0);
	$('.ui-dialog-content').dialog('close');
	/*
	var closeOnTimer=true;
	if(!content || content.length==0){
	content='<div id="BagSummary"><div class="element_wrapper"><div class="element_body"><img src="/assets/preloader.gif" /></div></div></div>';
	closeOnTimer=false;
	}
	$('#CartSummaryPopUp').html(content).css('display','block');
	$('input[placeholder]',$('#CartSummaryPopUp')).trigger('blur');
	closePopup();
	if(closeOnTimer){
		setTimeout(closeCartSummary,10000);
	}
	*/
}

function closeCartSummary(){
	shopping_cart_popup.setActivePopup(null);
	//$('#CartSummaryPopUp').empty().css('display','none');
}

function ie6TrackScroll(){
	
}

function popupCartPrint(){
	var dataUri = $('#BagPrintLink').attr('href');
	window.open(dataUri, 'print_win', "width=700,height=645,toolbar=no,header=no,location=no,resizable=1,scrollbars=1")
}

function popupCartMail(){
	var dataUri = $('#BagMailLink, .form_EmailShoppingBag a:first').data('ajax_src');
	if(dataUri && dataUri.length>0){
		popup(1,dataUri);
	}
}

function popupCartSave(){
	var dataUri = $('#BagSaveLink').data('ajax_src');
	popup(1,dataUri);
}

function popupProduct(lnk){
		popup(5,$(lnk).data('ajax_src'));
}

/*
* Mouseover swatch display functions
*/
function showSwatch(lbl){
	var popDiv=$('<div class="swatch_pop_up" style="position:absolute;left:0;top:-9999px;z-index:1000"><img /><p class="colour_name"></p></div>');
	var lb=$(lbl);
	var t= lb.attr('title').replace(' - click to select','')
	$('p',popDiv).html(t);
	lb.parent().append(popDiv);
	$('img',popDiv).bind('load',function(){positionSwatch(this);}).attr('src',$('img',lbl).attr('src'));
	lb.attr('title',t+' - click to select')
}
function hideSwatch(lbl){
	$('.swatch_pop_up',$(lbl).parent()).remove();
}
function positionSwatch(im){
	var d=$(im).parent();
	d.css({'top':(d.outerHeight()*-1)+'px'})
}

/**** Flash fullscreen simulation  ****/
// 
// Works by resizing the div that holds the swf to match the screen size and positioning it top left, the swf is set to 100% height and width so it will resize with its parent
// CSS changes that may affect the dimensions of the parent (display,position,overflow,height,width) will trigger a reload in Firefox, so this needs to be handled separately
// Note, in order to avoid the above, SWF immediate parent MUST be position:absolute; overflow:visible in the css
/**************/

///<summary>
/// Sets or unsets full screen mode
///</summary>
///<param name="yes">
/// Boolean, if true set fullscreen, else reset in page
///</param>
function flashFullScreen(yes){
	//console.log('FFS '+yes);
	if(yes){
		if(!(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))){
			$('html').addClass('flashfullscreen');
		}
		registerWindowResize();
		// Monitior the window and react if it changes size
		$(window).bind('resize',registerWindowResize);
		$('.online_books .preview .flash_wrapper').data('returnPosition',$(window).scrollTop());
		$(window).bind('scroll',unScroll);		
	}else{
		// Remove all the values that we have applied
		$('html').removeClass('flashfullscreen');
		$('.online_books .preview .flash_holder').css({
			'width':'',
			'height':'',
			'top':'',
			'left':'',
			'z-index':'',
			'overflow':''
		});
		if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			// reset the embedded swf dimension attributes
			$('#flash_catalogue_swf').attr({'width':'100%', 'height':'100%'})
		}
		// Stop monitoring the window
		$(window).unbind('resize',registerWindowResize);
		$(window).unbind('scroll',unScroll);
	}
}

///<summary>
/// Resizes the div holding the swf match the screen size and positioning it top left
///</summary>
function registerWindowResize(evt){
	// Test for Firefox as this is the only browser that has the embedding bug
	var isFF=(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent));
	// make a reference to the div that holds the embedded swf
	var h=$('.online_books .preview .flash_holder');
	// remove any positioning on the holder and note its default position
	var offsetObj=h.css({'top':'','left':''}).offset();
	// reposition the holder to the top-left corner of the window
	h.css({'top':((offsetObj.top*-1)+$(window).scrollTop())+'px','left':(offsetObj.left*-1)+'px','z-index':'99'});	 	
	if(isFF){
		// in Firefox we need to manually set the embedded swf dimension attributes
		$('#flash_catalogue_swf').attr({'width':Math.floor($(window).width()), 'height':Math.floor($(window).height())})
	}else{
		// modify the holder dimensions to fit the window - setting overflow:hidden stops the appearandce of scrollbars in IE
		h.css({
			'overflow':'hidden',
			'width':Math.floor($(window).width())+'px', 
			'height':Math.floor($(window).height())+'px'})
	}
 
 return false;
}	
function unScroll(evt){	
$(window).scrollTop($('.online_books .flash_wrapper').data('returnPosition'));
 
	evt.preventDefault();
 evt.stopPropagation();
}

function analyticsTrack(urlToTrack){
	if(pageTracker){
		pageTracker._trackPageview('/pageTracker/IntegrateGoogleAnalytics/flash'+urlToTrack)
	}
}

(function(a){function d(a){return a[0].offsetHeight+b(a,"marginTop")+b(a,"marginBottom")}function c(a){return a[0].offsetWidth+b(a,"marginLeft")+b(a,"marginRight")}function b(b,c){return parseInt(a.css(b[0],c))||0}a.fn.jCarouselLite=function(b){b=a.extend({selector:null,selectorItem:null,btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},b||{});return this.each(function(){function u(c){if(!e){if(b.beforeStart)b.beforeStart.call(this,t());if(b.circular){if(c<=b.start-i-1){j.css(f,-((n-i*2)*q)+"px");p=c==b.start-i-1?n-i*2-1:n-i*2-b.scroll}else if(c>=n-i+1){j.css(f,-(i*q)+"px");p=c==n-i+1?i+1:i+b.scroll}else p=c}else{if(c<0||c>n-i)return;else p=c}e=true;j.animate(f=="left"?{left:-(p*q)}:{top:-(p*q)},b.speed,b.easing,function(){if(b.afterEnd)b.afterEnd.call(this,t());e=false});if(!b.circular){a(b.btnPrev+","+b.btnNext).removeClass("disabled");a(p-b.scroll<0&&b.btnPrev||p+b.scroll>n-i&&b.btnNext||[]).addClass("disabled")}}return false}function t(){return m.slice(p).slice(0,i)}var e=false,f=b.vertical?"top":"left",g=b.vertical?"height":"width";var h=a(this),i=b.visible;if(b.selector){var j=a(b.selector,h),k=a(b.selectorItem,j),l=k.size()}else{var j=a("ul",h),k=a("li",j),l=k.size()}if(b.circular){j.prepend(k.slice(l-i-1+1).clone()).append(k.slice(0,i).clone());b.start+=i}if(b.selectorItem){var m=a(b.selectorItem,j),n=m.size()}else{var m=a("li",j),n=m.size()}var p=b.start;h.css("visibility","visible");m.css({overflow:"hidden","float":b.vertical?"none":"left"});j.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});h.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var q=b.vertical?d(m):c(m);var r=q*n;var s=q*i;m.css({width:m.width(),height:m.height()});j.css(g,r+"px").css(f,-(p*q));h.css(g,s+"px");if(b.btnPrev)a(b.btnPrev).click(function(){return u(p-b.scroll)});if(b.btnNext)a(b.btnNext).click(function(){return u(p+b.scroll)});if(b.btnGo)a.each(b.btnGo,function(c,d){a(d).click(function(){return u(b.circular?b.visible+c:c)})});if(b.mouseWheel&&h.mousewheel)h.mousewheel(function(a,c){return c>0?u(p-b.scroll):u(p+b.scroll)});if(b.auto)setInterval(function(){u(p+b.scroll)},b.auto+b.speed);})};})(jQuery);


 var ezibuy = function()
			{
				//  Creates a managed popup panel.
				//  Opening a panel will close any panels that are already open.
				function _popupPanel(trigger, element, mouseEvents)
				{
					if(mouseEvents)
						this.mouseEvents = mouseEvents;
						
					this.trigger = trigger;
					this.el = element;
					this.isLoaded=true;
					this.init();
				}
				
				// Protected and static
				_popupPanel.activePopup = null;
				
				_popupPanel.prototype.init = function()
				{
					if(this.mouseEvents == true){
						var mouseoverPanel = false;
						var mouseoverNav = false;
						this.trigger = $(this.trigger).parent("li");
						
						$(this.trigger).bind('mouseenter', {that: this}, this.triggerClickHandler);
						
						$(this.trigger).bind('mouseleave', {that: this}, this.handlemouseleavePanel)
						$(this.el).parent("div.popup-anchor").bind('mouseleave', {that: this}, this.handlemouseleavePanel)
						$(this.el).parent("div.popup-anchor").bind('mouseenter', {that: this}, this.handlemouseenterPanel)
					}else{
						// Bind the open trigger element
						$(this.trigger).bind('click', {that: this}, this.triggerClickHandler);

						// Bind the close button (if present)
						$(this.el).children('.close-btn').bind('click', {that: this}, this.closeClickHandler)
					}
				}
				
				_popupPanel.prototype.handlemouseleavePanel = function(evt)
				{
					mouseoverNav = false;
					if(mouseoverNav == false){
						scope = evt.data.that;
						scope.setActivePopup(null);
					}
				}
				
				_popupPanel.prototype.handlemouseleaveNav = function(evt)
				{
					mouseoverNav = false;
					if(mouseoverPanel == false){
						scope = evt.data.that;
						scope.setActivePopup(null);
					}
				}
				
				_popupPanel.prototype.handlemouseenterPanel = function()
				{
					mouseoverPanel = true;
				}
				
				//  Gets the active popup
				_popupPanel.prototype.getActivePopup = function()
				{
					return _popupPanel.activePopup;
				}
				
				//  Sets the active popup
				_popupPanel.prototype.setActivePopup = function(popupPanel)
				{
					if(_popupPanel.activePopup != null)
					{
						_popupPanel.activePopup.hide();
					}
					
					_popupPanel.activePopup = popupPanel;
				}
				
				// click handler for the trigger element
				_popupPanel.prototype.triggerClickHandler = function(evt)
				{
					evt.preventDefault();					
					scope = evt.data.that;
					if(scope.getActivePopup() != scope)
					{
						scope.show()
					}
				}
				
				// close click handler
				_popupPanel.prototype.closeClickHandler = function(evt)
				{
					evt.preventDefault();
					scope = evt.data.that;
					scope.setActivePopup(null);
				}
				// register end of opening animation
				_popupPanel.prototype.opened=function(){
					//console.log('_popupPanel.opened()')
					$(this.el).removeClass('opening');					
				}
				// Show the popup
				_popupPanel.prototype.show = function()
				{
					var me=this;
					this.setActivePopup(this);
					//$(this.el).addClass('opening').slideDown(600,function(){me.opened()});
					$(this.el).addClass('opening').show(1,function(){me.opened()});
					$(this.trigger).addClass('active');
				}
				
				// Hide the popup
				_popupPanel.prototype.hide = function()
				{
					$(this.el).hide();
					$(this.trigger).removeClass('active');
				}
				
				// Extend PopupPanel to create the Shopping bag popup
				_cart.prototype = new _popupPanel();
				// override the constructor to accept additional parameters
				_cart.prototype.constructor = _cart;
				// Constructor for Shopping Bag
				function _cart(trigger, element, totalRenderer, quantityRenderer, itemList, loader)
				{
					this.trigger = trigger;
					this.el = element;	
					this.autoClose = true;
					var me=this;
					if(this.el.addEventListener){
						this.el.addEventListener('mouseover',function(){me.autoClose=false;},false)
					}else{
						this.el.attachEvent('onmouseover',function(){me.autoClose=false;},false)
					}
								
					_popupPanel.prototype.init.call(this);
				}
				
				_cart.prototype.hide = function()
				{
					$(this.el).html('<div class="active_content"></div><div class="loader" style="display:none"><img alt="loading" class="loading" src="/assets/loading.gif" /></div>');
					_popupPanel.prototype.hide.call(this);					
				}
				_cart.prototype.renderMe=function(){
					var me=this;
					$('.loader',this.el).delay(400).fadeOut(200);
					$('.non_scrolling',this.el).delay(600).slideDown(200);
					$('input[placeholder]',this.el).trigger('blur');
					$('tr.item',this.el).each(function(i, el)
					{
						if(i<2){
							$(el).css('display','').delay(800+(i+1 * 400)).fadeIn(400);
						}else{
							$(el).delay(1600).show(0,function(){$('#BagSummary .scroll_me').jScrollPane();});
						}
					});										
					setTimeout(function(){if(me.autoClose){closeCartSummary();}},12000);
					
				}
				
				_cart.prototype.opened = function(){
					_popupPanel.prototype.opened.call(this);
					if($('.active_content div',this.el).length>0){						
						_cart.prototype.renderMe.call(this);
					}
				}
				_cart.prototype.show = function(dataUrl)
				{
					this.autoClose = true;
					$(this.el).html('<div class="active_content"></div><div class="loader"><img alt="loading" class="loading" src="/assets/loading.gif" /></div>');
					//this.loader.fadeIn();					
					_popupPanel.prototype.show.call(this);					
					// Pass a unique value in the query string to prevent IE
					// from caching the results.
					// cacheBuster = new Date().getTime();
					$.ajax({
						url: dataUrl,
						cache:false,
						context: this,
						success: this.resultHandler
						}
					)
					
				}
				
				_cart.prototype.renderContent = function(content){					
					if($('.active_content',this.el).length==0){
						$(this.el).html('<div class="active_content"></div><div class="loader"><img alt="loading" class="loading" src="/assets/loading.gif" /></div>');
					}else{
						$('.loader',this.el).css('display','');
					}
					if(content){
						$('.active_content',this.el).html(content);
					}
					_popupPanel.prototype.show.call(this);	
					
				}
				
				_cart.prototype.resultHandler = function(data, status, xhr)
				{
					var total = 0;
					var numberOfItems = 0;
					var me = this.el;
					$('.active_content',this.el).append(data);
					$('.non_scrolling',this.el).css('display','none');	
					if($('.summary_listing .item',this.el).css('display', 'none').length>2){
						$('.scroll_area',this.el).addClass('scroll_me');
					}
					if(!($(this.el)).is('.opening')){
						_cart.prototype.renderMe.call(this);
					}					
				}
				
				
				
				function _eqHeight(elements)
				{
					var max = 0;
					elements.each(function(i, el)
					{
						var h = $(el).height();
						if(h > max)
						{
							max = h;
						}
					});
					
					elements.height(max);
				}
				
				
				function _autoClear(element)
				{
					this.element    = $(element);
					this.promptText = this.element.val();
					this.element
						.bind('focus', {that: this}, this.focusHandler)
						.bind('blur', {that: this}, this.blurHandler)
				}
				
				_autoClear.prototype.focusHandler = function(evt)
				{
					scope = evt.data.that;
					if(scope.element.val() == scope.promptText)
					{
						scope.element.val('');
					}
				}
				
				_autoClear.prototype.blurHandler = function(evt)
				{
					scope = evt.data.that;
					if(scope.element.val() == '')
					{
						scope.element.val(scope.promptText)
					}
				}
				
				
				//  Return the namespace
				return {
					PopupPanel: _popupPanel,
					ShoppingBag: _cart,
					equalHeight: _eqHeight,
					AutoClear: _autoClear
				}
			}();
		 



$('.additional_info_links a').live('click',function(evt){		
	var urlparts=this.href.split('#');
	if(urlparts.length==2 && (urlparts[0]=='' || urlparts[0]==window.location.href.split('#')[0])){
		evt.preventDefault();
		$(this).closest('li').addClass('on').siblings().removeClass('on');		
		var holder = $(this).closest('.product_details');
		$('.additional_info_block',holder).css('display','none')
		$('#'+urlparts[1],holder).css('display','')
	}else if(this.href.indexOf('/')==0 || this.href.indexOf(window.location.protocol+'//'+window.location.hostname)==0){
		evt.preventDefault();
		popup(1,this.href); 
	}else{
		return true;
	}
	return false;
})
function altViewClick(evt){
	evt.preventDefault();
	var magImage=this.href.toLowerCase();
	var mainImage=magImage.replace('magnify','large');
	if($(this).is('.alt_view_selectors_popup a')){
		 mainImage=mainImage.replace('large','medium');
	}
	var magnifier=$(this).closest('.image').data('restoreTo',mainImage);
	$('img[id*="flyboximage"], img.photo',magnifier).attr('src',mainImage);
	$('img[id*="magnifyimg"]',magnifier).attr('src',magImage);
	
}
function altViewMouseOver(evt){
	var mainImage=this.href.toLowerCase().replace('magnify','large');
	if($(this).is('.alt_view_selectors_popup a')){
		 mainImage=mainImage.replace('large','medium');
	}
	var magnifier=$(this).closest('.image');
	if(!magnifier.data('restoreTo')){
		magnifier.data('restoreTo', $('img.photo',magnifier).attr('src'));
	}
	if(magnifier.data('restoreTo')!= mainImage){
		$('img.photo',magnifier).attr('src',mainImage);
	}
}
function altViewMouseOut(evt){
	var magnifier=$(this).closest('.image');
	$('img.photo',magnifier).attr('src',magnifier.data('restoreTo'));
	
}
function setUpProduct(scope){
	$('.pricing_matrix',scope).each(function(){
		var p=$(this).parent().css({'display':'block','position':'absolute','left':'-9999px'});
		$('.matrix tr',this).each(function(idx){
			var h=0;
			$('td',this).each(function(){							
				$(this).contents().wrapAll('<div class="bg" />');
				var myH=$('.bg',this).height();				
				if(myH>h){
					h = myH;
				}				
			});
			$('.bg',this).css('height',h+'px');			
		});
		p.css({'display':'','position':'','left':''});
	});	
	$('.Personalisation_link',scope).closest('.product_details').addClass('complex').find('div.disabled_control').append('<span class="disabled_message">This item must be personalised before you can add it to your bag</span>');
	$('.alt_view_selectors a, .alt_view_selectors_popup a',scope).bind('click', altViewClick).hover(altViewMouseOver, altViewMouseOut);
	$('.quantity input', scope).bind('focus',function(){this.value='';}).bind('blur',function(){var v=1;try{v=parseInt(this.value);}catch(err){};if(isNaN(v) || v<1){v=1;}this.value=v.toString();});
	$('.add_to_cart .availability_key li', scope).append('<span class="status_message"/>');
	var hiddenOptions =$('input[type="hidden"][name="clID"], input[type="hidden"][name="szID"]', scope);
	if(hiddenOptions.length==2){
		var selector_prefix='.estar_modal ';
		if($(scope).closest(selector_prefix).length==0){
			selector_prefix='';
		}
		updateSelectionMessages(selector_prefix);
	}
	$('.additional_info_links a:first',scope).trigger('click');
}
function initialiseWishlist(scope){
	var allhtmldivs = $(".wishlist_details .wishlist_how_to, .wishlist_anchor, .wishlist_details .gift_ideas",scope);
	var htmldivs = new Array();
	htmldivs[0] = $(".wishlist_details .wishlist_how_to",scope);
	htmldivs[1] = $(".wishlist_anchor",scope);
	htmldivs[2] = $(".wishlist_details .gift_ideas",scope);	
	allhtmldivs.hide().prepend('<a class="close-btn" href="#">close</a>');
	$(".info_popups .open",scope).each(function(idx){
		$(this).click(function(){
			if($(htmldivs[idx]).is(":visible") == false){
				allhtmldivs.hide();
				$(htmldivs[idx]).slideDown();
			}
		})
	})               
	//bind close buttons
	$(".wishlist_container .close-btn",scope).bind("click",function(){
		$(this).parent().slideUp("fast");
	});
}

function fn_SetFreightCountry(){
	//placeholder function, gets overwritten when in the cart process
}
$('#BagSummary a:not(a[onclick], .summary_checkout a)').live('click',closeCartSummary);

jQuery().ready(function(){
	jQuery('body').addClass('js_enabled');
	var itemsOnView=4;
	if($('.content_section.section_1').length>0){
		itemsOnView=3;
	}
	$('.product_details').each(function(){setUpProduct(this)});
		//insert spotlight nav controls, slider wrapper.
		
	$(".spotlight_row .products").each(function(){if($('.item',this).length>itemsOnView){$(this).wrap('<div class="spotlight_slider"></div>')}});
	$(".cross_sell .products").each(function(){if($('.item',this).length>itemsOnView){$(this).wrap('<div class="spotlight_slider"></div>')}});	
	$('<div class="navbuttons next"><img src="/assets/slider_nav_next.jpg"></div>').insertAfter(".spotlight_slider");
	$('<div class="navbuttons prev"><img src="/assets/slider_nav_prev.jpg"></div>').insertBefore(".spotlight_slider");
	
	// NOTE 22/02/2012 - the following binding was on UAT but not live
	//update button 
	$(".wishlist_anchor input,.wishlist_anchor textarea").live("change keyup", function(){
	$("#wishlist_update_hidden").show();
	$("#wishlist_update_imageonly").hide();
})

	if($(".spotlight").length > 1){
	
		$(".spotlight_slider").each(function(idx){
			$(this).addClass(""+idx);
		})
		$(".navbuttons.next").each(function(idx){
			$(this).addClass(""+idx);
		})
		$(".navbuttons.prev").each(function(idx){
			$(this).addClass(""+idx);
		})
		
		$(".spotlight_slider").each(function(idx){
		$(this).jCarouselLite({
			selector: ".products",
			selectorItem: ".item",
			btnNext: ".navbuttons.next."+idx+" img",
			btnPrev: ".navbuttons.prev."+idx+" img",
			mouseWheel:true,
			circular:true,
			speed:500,
			scroll:1,
			visible: itemsOnView
			});
		})
	}else{
		$(".spotlight_slider").jCarouselLite({
		selector: ".products",
		selectorItem: ".item",
		btnNext: ".navbuttons.next img",
		btnPrev: ".navbuttons.prev img",
		mouseWheel:true,
		circular:true,
		speed:500,
		scroll:1,
		visible: itemsOnView
	});
	}
	
	//bind spotlight slider to custom jCarouselLite.
	
	
	
	$(".header_navigation .element_body > ul > li > ul").wrapInner('<div class="popup-anchor"><div class="panel" /></div>');
	//$(".popup-anchor .panel").prepend('<a class="close-btn" href="#">close</a>');
	//$(".header_navigation .panel").wrap('<div class="popup-anchor">');
	//$('<div style="clear: left;" class="divider"></div>').insertAfter('.header_navigation .panel .category_name');
	$(".header_navigation .panel > li > ul > li a").prepend('<span class="arrow">&gt;</span>')
	//$(".header_navigation .main-nav").prepend('<a class="btn blue no-transform" href="#">Make a quick order</a>')
	$('.carousel-content').jCarouselLite({ btnNext: ".mini-carousel .next", btnPrev: ".mini-carousel .prev", visible:1});					
	$(".header_navigation .element_body > ul > li > a").each(function(i,el){
		if($('div.popup-anchor',this.parentNode).length>0){
			new ezibuy.PopupPanel( el, $($(el).parent()[0]).children("ul").children('div.popup-anchor').children('.panel'), true);
			var thispanel = $($(el).parent()[0]).children("ul").children('div.popup-anchor').children('.panel');
			var headerNavOffset = $(".header_navigation").offset().left;
			var newMarginLeft = ($(el).parent("li").offset().left-headerNavOffset);
			
			//calculate if margin-left and panel width overlaps.
			var panel_ul_count = $(".panel > li > ul", $(el).parent("li")).length;
			var allocated_padding = 30*$(".panel > li", $(el).parent("li")).length;
			var panel_width = ((145 + 20) *panel_ul_count)+allocated_padding;
			
			if(newMarginLeft > 50){
				if(panel_width+newMarginLeft > $(".header_navigation .popup-anchor").width()){
				thispanel.css({float:"right"});
				}else{
			thispanel.css({marginLeft:($(el).parent("li").offset().left-headerNavOffset)});
			}
		}
		}
	});
	$(".header_navigation .element_body > ul > li .panel").css('display', 'none');
	
	$('.promotions .brand_logos li img').each(function(){
		$(this).css({marginTop:(($('.promotions .brand_logos li').height())-$(this).height())/2})
	});
	
	shopping_cart_popup = new ezibuy.ShoppingBag(
		document.getElementById('BagViewLink'),
		document.getElementById('CartSummaryPopUp'),
		$('.cart-total'),
		$('.items-in-cart'),
		$('.cart-items'),
		$('#cart-panel .loading')
	);
	var loginform=document.getElementById('HeaderLoginForm'); 
	$($('.header_greeting')[0]).append('<div class="me_clickarea" style="height:45px;cursor:pointer;">');
	if(loginform){		
		new ezibuy.PopupPanel( $('.header_greeting .login_link')[0], loginform );
		
		new ezibuy.PopupPanel( $('.me_clickarea')[0], loginform);
		$($('.me_clickarea')[0]).attr("title","Sign in to access your EziBuy account here");
		
		if($('#login_email').length==0){
			var returnURL =$('input[name="current_location"]').val();
			if(returnURL && returnURL.length>0){
				
			$('input[name="referrer"]',loginform).each(function(){this.value='external'});
			$('input[name="productcode"]',loginform).each(function(){this.value=returnURL;});
			}
		}
		$('.reminder a', loginform).bind('click',function(evt){evt.preventDefault(); if($('#header_email').trigger('focus').val().length==0){alert('Please enter your email address and click the reminder link again'); }else{ $('input[name="action"]',loginform).val('sendpassword'); $('form',loginform)[0].submit();}});
	}else{
		new ezibuy.PopupPanel( $('.header_greeting .account_link')[0], $('.header_menu .element_wrapper').addClass('panel').css('display','none').prepend(' <a class="close-btn" href="#">close</a>')[0] );	
		new ezibuy.PopupPanel( $('.me_clickarea')[0], $('.header_menu .element_wrapper'));
		$($('.me_clickarea')[0]).attr("title","View & edit your EziBuy account here");
	}
				
	$('.products').tabulate({single_row:true});
	
	$('.additional_info_links li:first a').trigger('click');
	//$(window).bind('load',function(e){$('.cross_sell_container').uberTabulate();});
	if(!FUNCTIONALITY.input.placeholder){
		$('input[placeholder]').live('focus',mimicPlaceholderFocus).live('blur',mimicPlaceholderBlur).trigger('blur');
	}
	$('.online_books .book_list ul').tabulate({cell_selector:'li',sub_rows:'.book_name'});
	$('#flash_catalogue_swf, #flash_catalogue').wrap('<div class="flash_wrapper"><div class="flash_holder"></div></div>');
	if($('.request_catalogues select[name="country"]').bind('change',function(){countryChange('bill');}).length>0){
		$('#mailingplaceholder').after($('.edit_addresss_span'))
	}
	$('h3:contains(Brands)+ul',$('.navigation_categories .navigation_section')).limitLinkDisplay({link_count:7,more_text:'More Brands',less_text:'Less Brands'});
	$('.navigation .filters ul, .most_popular_nav ul').limitLinkDisplay({link_count:7,more_text:'More',less_text:'Less'})
	//setMoreColoursHover();	
	$('.cart .tooltip').tooltip({vPosition:'above',hAlign:'center'});
	$('.cart_details .tooltip').tooltip({vPosition:'below',hAlign:'center'});
	//$('.reviews_and_ratings').truncateReviews();
	// preselect single colours, runonload function will pick up on selected radio buttons
	var colourInputs=$('.product_details .add_to_cart input[type=radio][name=clID]');
	if(colourInputs.length==1){
		colourInputs[0].checked='checked';
	}
	//Add a styleable wrapper to single size values and populate the title attribute of the input (title attroibute is used for selection message)
	var sizeInputs=$('.product_details .add_to_cart input[type=radio][name=szID]');
	if(sizeInputs.length==0){
		var szContent=$('.product_details .add_to_cart .size fieldset');
		var szText=szContent.contents().filter(function(){return this.nodeType==3}).wrap('<li class="on"><span class="single"/></li>').text();
		//console.log('szText: '+szText);
		$('input',szContent).attr('title',szText);	
	}
	if(typeof(runOnLoad)=='function'){
		runOnLoad(this);
		runOnLoad=false;
	}
	$('.tab_holder').make_tabs({item_selector:'.tab_block', link_selector:'.tab',content_selector:'.tabcontent'});
	setMouseOverPreviews();
	
	if($.browser.msie && $.browser.version<8){
		$('legend').contents().wrap($('<span class="ie7fix" />'));
		
		if($.browser.version<7){
			$('img, input[type="image"]').ifixpng()	 
		}
		
		//bind link to div as a href tag around div does not work in IE7
		$("a .item_image_crop").bind("click",function(){
			document.location = $(this).closest("a").attr("href");
		})
		
		//homepage email sign up ie7 fix
		$(".email_sign_up ol").prepend("<li>"+$(".email_sign_up legend").text()+"</li>");
$(".email_sign_up legend").text("");
	}
	//$('.product_details .product_description .element_body').append($('.product_details .pricing .price_break'))
	//it seems we have to force the standard label behaviour for labels added in to the DOM
	$('.estar_modal .add_to_cart label[for]').live('click',function(){	
		var i=$('input#'+($(this).attr('for')));
		if(i.length>0){
			var t=i.attr('type');
			if(t=='radio' || t=='checkbox'){
				if(t=='radio'){
					$('input[name='+i.attr('name')+']',i.closest('form')).attr('checked','');
				}
				i.attr('checked','checked');
			}
			i.trigger('click').focus();
		}
	})	
	// the links in the matrix popup are making it jump to the top of the page
	$('.matrix a').live('click',function(evt){evt.preventDefault();})
	var promotion_home = $(".promotion_home");
	if(promotion_home.length>3){
		$(promotion_home[0]).css("marginLeft","0");
		$(promotion_home[3]).css("marginLeft","0");
	}

		// add a close button to the print window
		$('body.popup .header').append('<a href="#" class="close_button" onclick="window.close()">close</a>'); 
		// auto pop-up delivery method form if needed
       if ($("#perform_delivery_outopopup_tag").val() == "true") {
              popup(1, '#delivery_form_container');
    }

		
})

window.fbAsyncInit = function() {
	FB.init({
		status: true,
		cookie: true,
		xfbml: true,
		oauth : true //enables OAuth 2.0
	});
}

//load event added due to chromes handling of .ready event. specifically for images
$(window).load(function() {
	//wait til logos load then align center vertically
	$('.promotions .brand_logos li img').each(function(){
		$(this).css({marginTop:(($('.promotions .brand_logos li').height())-$(this).height())/2})
	});
	
	// Create the btns for the masthead carousel
	if($('#masthead').length>0){
    var btns = [];
	var navul= $('#masthead .carousel-nav ul');
    $('#masthead .carousel img').each(function(i, el)
    {
        var active = i == 0 ? ' active' : '';
        var rel = $(el).attr('src');
        navul.append('<li><a href="#" class="btn' + i +  active + '" rel="' + rel + '">' + (i+1) + '</a></li>');
        btns.push('#masthead .carousel-nav .btn' + i)
    });
    navul.prepend('<li class="prev"><a href="#">&lt;</a></li>');
    navul.append('<li class="next"><a href="#">&gt;</a></li>');
    
    // Create the masthead carousel
    $('#masthead > .carousel-wrapper > .carousel').jCarouselLite({
        visible: 1,
		auto: 7000,
        speed: 400,
        btnPrev: '#masthead li.prev a',
        btnNext: '#masthead li.next a',
        btnGo: btns,
        // Set the selected buttons
        afterEnd: function(selectedItem)
        {
            var count = $('#masthead  .carousel-nav ul li').length;
            var selectedSrc = selectedItem.children('a').children('img').attr('src');
            
            $('#masthead .carousel-nav li a[rel!="' + selectedSrc +'"]').removeClass('active');
            $('#masthead .carousel-nav li a[rel="' + selectedSrc +'"]').addClass('active');
        }
    });
	}
	var fbr = $('<div id="fb-root"/>');
	$('body').append(fbr);
	if (fbr.length>0) {
		var e = document.createElement('script');
		e.async = true;
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		fbr[0].appendChild(e);
	}
})

$('.ui-widget-overlay').live("click", function(){
  closePopup();
});
 $('.details .rating').live("click", function(){
	 var tablink=$('.additional_info_links a[href="#reviews"]', $(this).closest('.product_details')).trigger('click');;
	 if(tablink.length>0){	  
		window.scrollTo(0,tablink.parent().offset().top);
	 }
});
// iphone/ipad treats the first click as a mouseover and only fires the click if nothing on the page has changed
// so we need to force the click for some elements that already have a mouseover effect
$('.add_to_cart label:not(.estar_modal label)').live('touchend', function(e) {
    var i=$('input#'+($(this).attr('for')));
		if(i.length>0){
			var t=i.attr('type');
			if(t=='radio' || t=='checkbox'){
				if(t=='radio'){
					$('input[name='+i.attr('name')+']',i.closest('form')).attr('checked','');
				}
				i.attr('checked','checked');
			}
			i.trigger('click').focus();
		}
});
 
