// JavaScript Document
//var path_to_root = "";
var windowWidth;
var jsReady = false;
var carouselInstance = 1;
var domready=false;
var carlength=0;
var flashfileCount=0;
var fla_loader = '<div id="loader" class="loader2"><div class="loading"></div></div>';

document.observe("dom:loaded",function(){

	//
	// flash detection
	// Major version of Flash required
	var requiredMajorVersion = 10;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	if(BrowserDetect.browser == 'Firefox'){
	var requiredMajorVersion = 10;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	}

	// Minor version of Flash required
	var requiredRevision = 0;
	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

	if(hasRequestedVersion === false){ //callErrorForm(3);
		var aclinks = $$('.account_links');
		var flashWarn='<br /><p class="flashReq">A later version of flash is required, you can <a href="http://get.adobe.com/flashplayer/">download it here</a></p>';
		if(aclinks[0]) $('header').insert({bottom:flashWarn});
		if($('module_dynamic_homefooter')) $('module_dynamic_homefooter').insert({bottom:flashWarn});
	}

	if(BrowserDetect.browser == 'Safari'){
		if(BrowserDetect.version < 530){
			if($('content_carousel'))
				$('content_carousel').down('ul').setStyle({top:'auto',marginTop:'7.15%'});
		}
	}
	//
	// Support mouse wheel on cars
	if($('horizontal_carousel1') || $('content_carousel')){
		document.observe('DOMMouseScroll', wheel);
		document.observe('mousewheel', wheel);
	}
	if($('content_carousel')){

		//
		// show loader to minimise visual jump
		var flashChk = $$('.module_dyn_ecom_flash');
		if(flashChk[0]) flashfileCount=flashChk.length;

		if(!$('load_wrapper') && !$('loader') && !flashChk[0]){
			$('content_carousel').insert({bottom:'<div id="loader" class="loader2"><div class="loading"></div></div>'});
			$('loader').down('.loading').setStyle({right:'48%'});
		}

		$('previous_button').observe("mousedown",function(){
			panTimer = setTimeout(function(){
				panLeft(25);
			},120)
		})
		$('previous_button').observe("mouseup",function(){
			if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        //return;
	      }
		})

		$('previous_button').observe("mouseout",function(){
		      if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        return;
		      }
		})
		$('next_button').observe("mousedown",function(){
			panTimer = setTimeout(function(){
				panRight(25);
			},120)
		})
		$('next_button').observe("mouseup",function(){
			if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        //return;
	      }
		})

		$('next_button').observe("mouseout",function(){
		      if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        return;
		      }
		})

		Event.observe($('content_carousel'), "scroll",function(){ CheckScroll() });
		Event.observe(window,"resize",function(){ setTimeout(function(){CheckScroll()},500); });



	}

	domready=true;
	windowWidth =$('webpage').up().getWidth();

	if($('filter_controls')){
		var wid = 0;
		$$('#filter_controls ul').each(function(f){
			wid += f.down().getWidth();
		})
		$('filter_controls').setStyle({width:(wid+150)+'px'});
	}

	/** MENU LINKS - SCROLLING **/
	var menus = $$('#main-menu ul');
	menus.each(function(menu){
		if(!$('proceed_checkout')){
		var position = menu.down().positionedOffset();
		menu.setStyle({left:position[0]+"px", position:'absolute', visibility:'hidden'});
		}
	})
	linkjumpto = function(obj){
		var cWidth = obj.up(2).getWidth();
		var scrollPos = (cWidth / 2) - (obj.getWidth() / 2);
		var position = obj.positionedOffset();
		var newPoss = position[0] - scrollPos;
		var containerPos = obj.up().positionedOffset();

		obj.up().setStyle({left:-newPoss+"px",visibility:'visible'});
	}
	linkscroll = function(obj){
		var cWidth = obj.up(2).getWidth();
		//
		// scroll to
		setTimeout(function(){

			var scrollPos = (cWidth / 2) - (obj.getWidth() / 2);
			var position = obj.positionedOffset();
			var newPoss = position[0] - scrollPos;
			var containerPos = obj.up().positionedOffset();

			new Effect.Morph(obj.up(),{style:{left:-newPoss+"px"}, duration:0.6});

		},10);

	}

	var navLinks = $$('.link_container .nav a');
	navLinks.each(function(link){

		setTimeout(function(){link.up(1).setStyle({visibility:'visible'})},800);

		if(link.className == 'on')
			setTimeout(function(){linkscroll(link.up());},700);

		link.observe("click",function(e){
			linkscroll(link.up());
			setTimeout(function(){
				//
				// kill carousel and show waiting
				if($('module_dynamic_placeholder4') && !$('template_5_col_1')) $('module_dynamic_placeholder4').remove();
				if($('content_carousel')) $('content_carousel').remove();
				if($('campaign_shots')) $('campaign_shots').remove();

				if(!$('load_wrapper') && !$('loader')){
				$('webpage').insert({bottom:loadgif});
				$('load_wrapper').down().setStyle({right:'49%'});
				}
				//
				// Navigate away
				window.location = link.href;
			},500)
			Event.stop(e);
			navLinks.each(function(l){
				l.className = "";
			})
			link.className = "on";
		})
	})

	var subNavLinks = $$('.link_container .subnav a');
	jsReady = true;

	subNavLinks.each(function(link){

		setTimeout(function(){link.up(1).setStyle({visibility:'visible'})},1200);

		if(link.className == 'on')
			setTimeout(function(){linkscroll(link.up());},1000);
		link.observe("click",function(e){
			linkscroll(link.up());
			setTimeout(function(){
				//
				// kill carousel and show waiting
				if($('module_dynamic_placeholder4') && !$('template_5_col_1')) $('module_dynamic_placeholder4').remove();
				if($('content_carousel')) $('content_carousel').remove();
				if($('campaign_shots')) $('campaign_shots').remove();

				$('webpage').insert({bottom:loadgif});
				$('load_wrapper').down().setStyle({right:'49%'});
				//
				// Navigate away
				window.location = link.href;
			},500)
			Event.stop(e);
			subNavLinks.each(function(l){
				l.className = "";
			})
			link.className = "on";
		})
	})

	//
	// enable my rail links
	//fn_myrail_link();
	fn_locate_frms();
	//
	// shop the look rail call
	fn_stl_carousel = function(mid) {

			//callErrorForm(2);
			$('carPark').innerHTML='';
			var existingCar = $$('.collectionContainer');
			carouselInstance = carouselInstance+1;
			var currentCar = carouselInstance - 1;
			var heldWidth = existingCar[0].down('ul').getWidth();

			//$('debug').insert({top:'<p>Hide Car:'+existingCar[0].id+' width:'+existingCar[0].down('ul').getWidth()+'</p>'});
			if(existingCar[0])
				existingCar[0].hide();

//			$('carousel_nav_'+currentCar).hide(); // hide current carousel nav
			$('carousel_nav1_1').hide();
			$('carousel_nav_1').hide();

			$('main-menu').hide();
			$('carPark').show();

			new Ajax.Updater('carPark', path_to_root + 'scripts/php/pDockService2.php', {
			  	parameters: "func=newCar&controller_type=shop_the_look&carouselID="+carouselInstance+"&pids="+$('product_id_ar'+mid).value,
			  	onComplete: function(){
			  		setTimeout(function(){
			  			setup('carousel'+carouselInstance,'carouselDock'+carouselInstance,carouselInstance,basketID,'shop_the_look');
			  			$('shopthelookbtn').observe('click',function(){
			  				  $('carPark').hide();
			  				  $('collectionContainer1').show();
			  				  //$('debug').insert({top:'<p>SET WIDTH:'+heldWidth+'</p>'});
			  				  $('collectionContainer1').down('ul').setStyle({width:heldWidth+'px'})
			  				  $('carousel_nav_1').show();
			  				  $('carousel_nav1_1').show();

			  				  $('main-menu').show();
			  			})
			  		},500)
			  	}
			});
	}



});


Event.observe(window,"resize",function(){

	var menus = $$('#main-menu ul');
	menus.each(function(menu){

		var cWidth = $('webpage').up().getWidth();
		var scrollPos = (cWidth / 2) - (menu.getWidth() / 2);
		menu.setStyle({left:scrollPos+"px"});


		var navLinks = $$('.link_container .nav a');
		navLinks.each(function(link){
			if(link.className == 'on')
				linkjumpto(link.up());
		})

		var subNavLinks = $$('.link_container .subnav a');

		subNavLinks.each(function(link){
			if(link.className == 'on')
				linkjumpto(link.up());
		})

	})

})

fn_locate_frms = function(){

	var sendlinks = $$('.stylist_links a');
	sendlinks.each(function(lnk){
		lnk.observe("click",function(e){
			Event.stop(e);
			new Ajax.Request(path_to_root+'scripts/php/pDockService2.php',{
				parameters: lnk.href,
				onComplete: function(transport){
					//
					// create form
					var lightbox = "<div id=\"lightBox\" class=\"lightBox\" style=\"opacity:0\"></div>";
					$('webpage').insert({bottom:lightbox});
					$('lightBox').morph("opacity:0.3");
					$('webpage').insert({bottom:transport.responseText});
					$('sendForm').addClassName('popup');
					fn_input_placeholders();
				},
			evalScripts:true
			})
		})
	})
}

fn_myrail_link = function(){
		var railLink = $$('.account_links a');
		railLink.each(function(link){
			link.observe('click',function(e){

				if(link.className == 'rail') Event.stop(e);

				$('webpage').insert({bottom:loadgif});
				$('load_wrapper').down().setStyle({right:'49%'});

				if(link.className == 'rail'){
				carouselInstance = carouselInstance+1;
				var existingCar = $$('.collectionContainer');
				var currentCar = carouselInstance - 1;

				if(existingCar[0]){
					existingCar[0].hide();
				}else{
					window.location = link.href;
				}
				if($('carousel_nav_'+currentCar)) $('carousel_nav_'+currentCar).hide(); // hide current carousel nav
				$('main-menu').hide();
				$('carPark').show();

				new Ajax.Updater('carPark', path_to_root + 'scripts/php/pDockService2.php', {
				  	parameters: link.href+"&func=newCar&carouselID="+carouselInstance,
				  	onComplete: function(){
				  		$('load_wrapper').remove();
				  		setTimeout(function(){
				  			setup('carousel'+carouselInstance,'carouselDock'+carouselInstance,carouselInstance,basketID,'myrail');
				  		},300)
				  		//
				  		// send to links
				  		fn_locate_frms();
				  	}
				});
				}
			})
		})
}

fn_submitSendToForm = function(theForm){


	if($('name') && $('name').value == ''){
		alert('Please enter your name');
		return false;
	}
	if($('email') && !validEmail($('email'),'email',true)){
		//alert('Please enter a valid email')
		return false;
	}
	/*
	if($('email') && !validEmail($('email'),'cust_email',true)){

		return false;
	}*/

	var num_elements = theForm.elements.length;
	for(i=0; i<num_elements; i++){
		if(theForm.elements[i].id!= 'cust_email' || theForm.elements[i].id!= 'email')
			theForm.elements[i].value = encodeURIComponent(theForm.elements[i].value);
	}
	var func = 'sendWishList';
	if($('func'))
		func = $('func').value;


	//
	// GOOGLE TRACKER
	if(func=='sendWishList')
		pageTracker._trackPageview('/submissions/' + func + '/' + $('sendto_type').value);
	else
		pageTracker._trackPageview('/submissions/' + func);

	new Ajax.Request
	(
		path_to_root + 'scripts/php/pDockService2.php',
		{
			onComplete:function(request)
			{
				theForm.hide();
				theForm.up().insert('<h1>Thank you!</h1>');
				setTimeout("cancel_sendTo();",2000);
			},
			asynchronous:true,
			parameters:Form.serialize(theForm)+ '&func='+func
		}
	);
}

fn_submitForm = function(theForm){

	var num_elements = theForm.elements.length;
	for(i=0; i<num_elements; i++){
		if(theForm.elements[i].type != 'button')
			theForm.elements[i].value = encodeURIComponent(theForm.elements[i].value);
	}


	if($('func')) pageTracker._trackPageview('/submissions/' + $('func').value);

	//return;
	new Ajax.Request
	(
		path_to_root + 'scripts/php/pDockService2.php',
		{
			onComplete:function(request)
			{
				if($('func').value=='add_to_notify'){
					theForm.cust_email.hide(); // hide ability to re add to notify
					theForm.notifyBtn.up('span').hide();
					var msg = "<p>Thank you, you have registered your interest</p>";
					theForm.insert({bottom:msg});
//					alert('Thank you, your interest has been acknowledged');
				}
			},
			asynchronous:true,
			parameters:Form.serialize(theForm)
		}
	);
}

function fn_Notify_Form(theForm,domid){


		//
		// check variations are set detail_wrapper6795
		var varChk = 0;
		var variationSel = $$('#detail_wrapper'+domid+' form input');
		variationSel.each(function(sel){
			if(sel.type == 'hidden' && sel.value == '') varChk = 1;
		})

		if(varChk == 1){
			alert('To give you accurate notification, please select the size /colour');
			return false;
		}

		 var str = theForm.cust_email.value;
		 var at="@"
		 var dot="."
		 var lat=str.indexOf(at)
		 var lstr=str.length
		 var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		  alert("Please enter a valid email address in the correct format")
		  return false;
		}
		else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		  alert("Please enter a valid email address in the correct format")
		  return false;
		}
		else if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
			alert("Please enter a valid email address in the correct format")
			return false;
		}
		else if (str.indexOf(at,(lat+1))!=-1){
			alert("Please enter a valid email address in the correct format")
			return false;
		}
		else if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		 alert("Please enter a valid email address in the correct format")
		 return false;
		}
		else if (str.indexOf(dot,(lat+2))==-1){
		 alert("Please enter a valid email address in the correct format")
		 return false;
		}
		else if (str.indexOf(" ")!=-1){
		 alert("Please enter a valid email address in the correct format")
		 return false;
		}
		fn_submitForm(theForm);
}

function fn_add_toRail(pid,domid){
		//
		// check variations are set detail_wrapper6795
		var varChk = 0;
		var variationSel = $$('#detail_wrapper'+domid+' form input');
		variationSel.each(function(sel){
			if(sel.type == 'hidden' && sel.value == '') varChk = 1;
		})
		
		if(varChk == 1){
			alert('You must select a colour and size.');
			return false;
		}

		new Ajax.Request( path_to_root + 'scripts/php/pDockService2.php', {
		parameters: "func=addToWishList&pid="+pid,
		onComplete: function(){
			// change button
			$('addToRail_'+pid).value = 'BUY';
			window.location = virtual_path + "/myaccount/my-basket";
			// item added notification
			var itemName = $$('#detail_wrapper'+domid+' form h1')[0].innerHTML;			
	  		$('instruct_added').setStyle({marginLeft: - (parseInt($('instruct_added').getWidth()) / 2) + 'px'});
	  		$('instruct_added').down(1).innerHTML = 'The ' + itemName + ' has been added to your basket';
	  		new Effect.Appear('instruct_added');
	  		setTimeout(function(){
	  			new Effect.Fade('instruct_added');  			
	  		},3000)
			
			//analytics - Record event
			var hash = document.location.hash;
			var prod = hash.substr(1,hash.length-1);
			//alert(prod)
			pageTracker._trackPageview('/addedtobasket/' + prod);				
			fn_update_railcount();
		}
		})


}
function fn_adding_item_chk(pid,domid){
	var varChk = 0;
	var variationSel = $$('#detail_wrapper'+domid+' form input');
	variationSel.each(function(sel){
		if(sel.type == 'hidden' && sel.value == '') varChk = 1;
	})
	
	if(varChk == 1){
		alert('You must select a colour and size.');		
		return false;		
	}	
}

function fn_remove_wl_item(wl_is,item_id){
		new Ajax.Request( path_to_root + 'scripts/php/pDockService2.php', {
		parameters: "func=removeFromWishlist&pid="+item_id,
		onComplete: function(transport){
			$('p'+item_id).remove();
		}
		})
}

function fn_remove_myRail_item(wl_is,item_id,domID){

		new Ajax.Request( path_to_root + 'scripts/php/pDockService2.php', {
			parameters: "func=removeFromMyRail&pid="+item_id,
			onComplete: function(transport){
				$(domID).remove();
				fn_update_railcount();

			}
		})
}
/*function fn_select_variation(theForm){
		var replacementArea = theForm.replacementArea.value;
		$(replacementArea).down().remove();
		new Ajax.Updater(replacementArea, path_to_root + 'scripts/php/pDockService2.php', {
			parameters: Form.serialize(theForm)+"&func=detailReq",
			onComplete: function(transport){
		  		// text tips
		  		$(replacementArea).down(1).setStyle({width:'450px'})

		  		fn_input_placeholders();
			},
			insertion: Insertion.Top,
			evalScripts:true
		})
}*/

function cancel_sendTo(){
		//
		// remove form and lightbox effect
		if($('sendForm').up().down())
			$('sendForm').up().down().show();

		$('sendForm').remove();
		if($('lightBox')){
		new Effect.Morph('lightBox', {
		style: 'opacity:0;', // CSS class name
		duration: 0.5,
		afterFinish : function(){
			$('lightBox').remove();
			}
		});
		}

}

function fn_load_carousel_detail_flash_so_1_5(htmlWrapperId, leadMediaType, itemID, carouselType){
		/*
		This is for SWF Object 1.5 - out of date
		----------------------------------------------------
		htmlWrapperId		the id of the wrapper DIV
		leadMediaType		shop, runway, detail, redcarpet, video (relates to XML)
		itemID				will either be prouct ID or media ID
		carouselType		product, collection
		*/
		setTimeout(function(){
			var width = "100%";
			var height = "380px";
			var bgcol = null;
			var so = new SWFObject(path_to_root+"media/swf/CarouselItem.swf", "f_carousel_item_"+itemID, width, height, "8", bgcol, "high");
			so.addParam("wmode", "transparent");
			so.addParam("align", "right");
			so.addParam("menu", "false");
			so.addParam("swfLiveConnect", "true");
			so.addParam("allowScriptAccess","always");
			so.addParam("allowFullScreen","true");
			so.addVariable("myid",itemID);
			so.addVariable("mymediatype",leadMediaType);
			so.addVariable("myrootpath",path_to_root);
			so.addVariable("mycarouseltype",carouselType);
			so.addVariable("mywrapperid",htmlWrapperId);
			var flash = so.write(htmlWrapperId);
			//$('debug').insert({top:'<p>create flash: </p>'});
		},800);

}

function fn_load_carousel_detail_flash(htmlContainerId, htmlWrapperId, leadMediaType, itemID, carouselType, bridal){
		/*
		This is for SWF Object 2.2
		----------------------------------------------------
		htmlContainerId		the id of the container DIV - NB: this DOM element is REPLACED by the flash object
		leadMediaType		shop, runway, detail, redcarpet, video (relates to XML)
		itemID				will either be prouct ID or media ID
		carouselType		product, collection

		swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callback_fn)
		*/
		var htmlContainerId = htmlContainerId;
		var bridalFlag = false;
		if(bridal=='yes')bridalFlag = true;

		setTimeout(function(){
			var swfURL = path_to_root+"media/swf/CarouselItem.swf";
			var id = htmlContainerId;
			var w = "100%";
			var h = "380px";
			if(BrowserDetect.browser == 'Firefox'){
				var version = "10.0.0";
				var expressInstallURL = null;
			} else
			{
				var version = "9.0.246";
				var expressInstallURL = path_to_root+"media/swf/expressInstall.swf";
			}
			var flashvars = {
					myid:itemID,
					mymediatype:leadMediaType,
					myrootpath:path_to_root,
					mycarouseltype:carouselType,
					mywrapperid:htmlWrapperId,
					myheight:375,
					bridal:bridalFlag
				};
			var params = {
					wmode:"transparent",
					menu:"false",
					align:"right",
					swfLiveConnect:"true",
					allowScriptAccess:"always",
					allowFullScreen:"true",
					bgcolor:null,
					quality:"high"
				};
			var attributes = {
					id:"f_carousel_item_"+itemID
				};

			swfobject.embedSWF(swfURL, id, w, h, version, expressInstallURL, flashvars, params, attributes);
			//$('debug').insert({top:'<p>create flash: </p>'});
		},800);

		setTimeout(function(){
			if($('SWFObjectExprInst'))
			{
				fn_flash_loaded(htmlWrapperId);
			}
			},1800);

}

function fn_flash_loaded(htmlWrapperId){
//	$(htmlWrapperId).setStyle({marginTop:'-1000px',height:'100%',width:'100%',float:'left'});
//	$(htmlWrapperId).setStyle({marginTop:'-1000px'});
//	if($(htmlWrapperId)){
	setTimeout(function(){
		//$(htmlWrapperId).className = 'main_image_wrapper';
		//$('debug').insert({top:'<p>position flash - loaded: </p>'});
		$(htmlWrapperId).setStyle({width:'100%',height:'380px',marginTop:'0px'});
		//setTimeout(function(){
//			$(htmlWrapperId).up().down().innerHTML = ''; // kill the static image
			if($(htmlWrapperId).up().down('img')){
//				$(htmlWrapperId).up().down().remove();
				$(htmlWrapperId).up().down().setStyle({display:'none'});
			}

			//$(htmlWrapperId).up().down().setStyle({display:'none'});
//			if($(htmlWrapperId).up().down()) $(htmlWrapperId).up().down().setStyle({display:'none'});
//			$(htmlWrapperId).setStyle({marginTop:'0px'});
		//},1000);
	},0);
//	}

	//$(htmlWrapperId).up().innerHTML = $(htmlWrapperId).innerHTML;

}

function fn_rail_flash_callbacl(e)
{
	if(!e.success)
	{
		alert(e.id+":"+e.success+":"+e.ref);
		//fn_flash_loaded($(e.id).up().id);
		if($(e.id).up(1).down('img')){
//				$(htmlWrapperId).up().down().remove();
			$(e.id).up(1).down().setStyle({display:'none'});
		}
	} else
	{
		//alert(e.id+":"+e.success+":"+e.ref);
		$(e.id).up().setStyle({width:'1px',height:'1px'});
	}
}

function fn_swfobject_callback(e)
{
	if(e.success)
	{
		if($('content_carousel')){
			$(e.id).up().setStyle({width:'1px',height:'1px'});
			if(!$('loader')){
				$('content_carousel').insert({bottom:fla_loader});
				$('loader').down().setStyle({left:'49%'});
			}
		}
	}
}

function isReady(){
	return jsReady;
}

function changeFocus( )
{
	this.window.focus()
}

function debug(msg)
{
	alert("From flash: "+msg);
}

function fn_go_to_product(url)
{
	window.location.href = url;
}

function fn_openForm(theLink,placementID){

	//$(placementID).down().hide();
	new Ajax.Request(path_to_root+'scripts/php/pDockService2.php',{
		parameters: theLink.href,
		onComplete: function(transport){
			//
			// create form
			var lightbox = "<div id=\"lightBox\" class=\"lightBox\" style=\"opacity:0\"></div>";
			$('webpage').insert({bottom:lightbox});
			$('lightBox').morph("opacity:0.3");
			$('webpage').insert({bottom:transport.responseText});
			$('sendForm').addClassName('popup');
			$('sendForm').setStyle({marginLeft: - (parseInt($('sendForm').getWidth()) / 2) + 'px'});
			//$(placementID).insert({bottom:transport.responseText});

			//
			// GRAB IMAGE AND INSERT
			$('dropZone').insert({bottom:'<div class="image">'+$(placementID).up().down('.image').innerHTML+'</div>'})

			fn_input_placeholders();
		},
			evalScripts:true
	})

}
function fn_openSizeChart(lnk){

	pageTracker._trackPageview('/popup/');
	new Ajax.Request(path_to_root+'scripts/php/pDockService2.php',{
  				parameters: lnk.href,
  				onComplete: function(transport){
  					//
  					// create form
  					var lightbox = "<div id=\"lightBox\" class=\"lightBox\" style=\"opacity:0\"></div>";
  					$('webpage').insert({bottom:lightbox});
  					$('lightBox').morph("opacity:0.3");
  					$('webpage').insert({bottom:transport.responseText});
  					fn_input_placeholders();
  					$('sendForm').addClassName('popup');
  				}
  			})
}
function fn_update_railcount(){
		new Ajax.Updater('basket_options',path_to_root+'scripts/php/basket_options.inc.php',{
		onComplete: function(transport){
			new Effect.Pulsate('basket_options');
			//fn_myrail_link();
		}
	})
}
//
// Add title tips into text areas to aid user on forms
function fn_input_placeholders(){
	var t_fields = $$('.hint');
	t_fields.each(function(field){
		if(field.value == '') field.value=field.title;
		field.observe("blur",function(){
			if(field.value == '') field.value=field.title;

		}).observe("focus",function(){
			if(field.value == field.title) field.value = '';

		}).up('form').observe("submit",function () {
			if (field.value == field.title) {
			field.value = '';
			}
		})
	})
}

var previousSize = null;
function fn_watch_flash_resize(wrapperID, imgWidth){

	//imgWidth = imgWidth - 20;

	setTimeout(function(){
	if(wrapperID){
		//previousSize = imgWidth;
		// change the master wrapper size
		var addWidth = (imgWidth - $(wrapperID).up().getWidth());


		//addWidth = Math.round(addWidth);
//		var wrapperNewSize = $(wrapperID).up(2).getWidth() + addWidth;
		var wrapperNewSize = $(wrapperID).up().next().getWidth() + $(wrapperID).up().next(1).getWidth() + imgWidth; // item wrapper


		//$('debug').insert({top:'<p>WrapperID: ' +wrapperID + ' FLASH CAR RESIZE:'+ parseInt($(wrapperID).up(3).getWidth()+(addWidth+0))+'</p>'});
		//$('debug').insert({top:'<p>flash width: ' +imgWidth+' Imgwrap:'+$(wrapperID).up().getWidth()+'</p>'});
		//$('debug').insert({top:'<p>carousel width: ' + parseInt($(wrapperID).up(3).getWidth()+(addWidth+0))+'</p>'});

		if(wrapperNewSize > $(wrapperID).up(2).getWidth()){
		$(wrapperID).up(3).setStyle({width:parseInt($(wrapperID).up(3).getWidth()+(addWidth+0))+'px'}); // CAROUSEL WIDTH
//		$(wrapperID).up(3).setStyle({width:parseInt($(wrapperID).up(3).getWidth())+'px'}); // CAROUSEL WIDTH
		}
		//alert(wrapperNewSize + ' ' + $(wrapperID).up(2).getWidth())

		new Effect.Parallel(
		[
		new Effect.Morph($(wrapperID).up(), { style: 'width:'+(imgWidth)+'px', sync: true}),
		new Effect.Morph($(wrapperID).up(2), {  style: 'width:'+ wrapperNewSize +'px', sync: true})
		],
		{ duration: 0.7, queue:{ position:'end',scope:'openFX'} }
		);

		if((BrowserDetect.browser == 'Safari' && BrowserDetect.version < 530) || (BrowserDetect.browser == 'Chrome' && BrowserDetect.version == 1)){
			$(wrapperID).up(3).setStyle({marginLeft:'inherit',left:'inherit'});
		}

		//
		// show shop the look button
		setTimeout(function(){
		var stlb =$$('.detail_wrapper .stlb');
		stlb.each(function(b){b.show()})

		moveTo($(wrapperID).up(4),$(wrapperID).up(2))

		/*Position.prepare();
		var container_x = Position.cumulativeOffset($(wrapperID).up(4))[0]
		var container_y = Position.cumulativeOffset($(wrapperID).up(4))[1]
		var element_y = Position.cumulativeOffset($(wrapperID).up(2))[1]
		var element_x = Position.cumulativeOffset($(wrapperID).up(2))[0]
		new Effect.Scroll($(wrapperID).up(4), {x:(element_x-container_x-(parseInt($(wrapperID).up(2).getWidth())/2)), y:(container_y)})*/
		},700)

		//$(wrapperID).up(2).setStyle({width:$(wrapperID).up(2).getWidth()+addWidth+'px'});

	}
	},400)
}
function callErrorForm(errorID){
		new Ajax.Request(path_to_root + 'scripts/php/custom/forms/error_message_frm.php', {
				parameters:"errorID="+errorID,
			 	onComplete: function(transport){
				var lightbox = "<div id=\"lightBox\" class=\"lightBox\" style=\"opacity:0\"></div>";
				$('webpage').insert({bottom:lightbox});
				$('lightBox').morph("opacity:0.3",{duration:0.3});
				$('webpage').insert({bottom:transport.responseText});
				$('sendForm').setStyle({marginLeft: - (parseInt($('sendForm').getWidth()) / 2) + 'px'});
			 	}
		});
}
function debugMessage(msg){
	$('debug').insert({top:'<p>debug: ' +msg+'</p>'});
}
function fn_flash_rdy(fid,w,h){
	//debugMessage('flash'+fid+' ready '+flashfileCount);

	$(fid).up().setStyle({width:w+'px',height:h+'px'});
	if(w > 700) $(fid).up(3).setStyle({marginLeft:'0px'});

	flashfileCount = flashfileCount-1;
	if(flashfileCount == 0){
		//debugMessage('remove loader '+flashfileCount);
		if($('loader')) $('loader').remove();
		fn_resize_content_car();
	}
	//debugMessage('flash pass '+fid);

}
function fn_resize_content_car(){

	var pad = 50;
	var flashFiles = $$('.flash_wrapper');
	//
	// remove the left margins on flash only when they have been initialised
	if(flashFiles[0]){
		flashFiles.each(function(ff){
		if(ff.getWidth() > 700){
			 pad = 0;
			 ff.up(2).setStyle({width:ff.getWidth()+'px'})
		}
		})
	}

	var li_length =0;
	var validcount=0;
	$$('#content_carousel ul li').each(function(li){
		li_length += parseInt(li.getWidth());
		if(parseInt(li.getWidth()) > 20){
			validcount++;
		}
		if(li.getWidth()==0 && li.down().innerHTML == '') li.remove();
	})
	lngh = li_length;
	carlength = lngh;
	if(pad==50)
	lngh = li_length + (validcount * 20 ) + pad
	$('content_carousel').down().setStyle({ width:+lngh+'px' });

	if(flashfileCount == 0){
		if($('loader'))	$('loader').remove();
		if($('load_wrapper')) $('load_wrapper').remove();
	}

	CheckScroll();
}

/* NORMAL CAROUSEL SCROLL METHODS */

function panLeft(amnt){
		var panTimer;
		var positionLeft = $('content_carousel').scrollLeft;
		var newPoss = positionLeft - amnt;
		var amnt = amnt;

		if(newPoss > 0 || positionLeft > 0){

			$('content_carousel').scrollLeft=newPoss;

			panTimer = setTimeout(function(){
				panLeft(amnt);
			},1)

			$('previous_button').observe("mouseup",function(){
				if(panTimer) {
			        clearTimeout(panTimer);
			        panTimer = null;
			        return;
		      }
			})
		}

		$('previous_button').observe("mouseout",function(){

		      if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        return;
		      }
		})
}
function panRight(amnt){

		var panTimer;
		var positionLeft = $('content_carousel').scrollLeft;
		var newPoss = positionLeft + amnt;
		var amnt = amnt;

		var negativeWidth = 0 - carlength+600;

		if(newPoss > negativeWidth){

			$('content_carousel').scrollLeft=newPoss;

			panTimer = setTimeout(function(){
				panRight(amnt);
			},1)

			$('next_button').observe("mouseup",function(){
				if(panTimer) {
			        clearTimeout(panTimer);
			        panTimer = null;
			        return;
		      }
			})

		}

		$('next_button').observe("mouseout",function(){

		      if(panTimer) {
		        clearTimeout(panTimer);
		        panTimer = null;
		        return;
		      }
		})
}
function CheckScroll(){
	//
	// Hide buttons if size
	var dimensions = screenDimensions();

	if(dimensions[0]>carlength){
		//
		// attempt to center carousel
		if($('content_carousel')){
			if((BrowserDetect.browser == 'Safari' && BrowserDetect.version < 530) || (BrowserDetect.browser == 'Chrome' && BrowserDetect.version == 1))
			$('content_carousel').setStyle({marginLeft:-(parseInt($('content_carousel').getWidth()) / 2) +'px',marginRight:'auto',left:'50%'});
			else
			$('content_carousel').setStyle({marginLeft:'auto',marginRight:'auto'});

		}
		//
		// hide buttons
		$('previous_button').hide();
		$('next_button').hide();
	}else{
		$('previous_button').show();
		$('next_button').show();
	}

	//debugMessage('offset:'+$('content_carousel').scrollWidth+" "+$('content_carousel').scrollLeft);
	if($('content_carousel').scrollLeft == 0){
		$('previous_button').hide();
	}else{
		$('previous_button').show();
	}
/*	if($('content_carousel').scrollWidth <= $('content_carousel').offsetWidth)
		$('next_button').hide();
	else
		$('next_button').show();*/
}

function wheel(event){

	if($('content_carousel'))
		var scroll = $('content_carousel').scrollLeft;
	else
			var scroll = $('horizontal_carousel1').scrollLeft;

	/* Mousewheel UP */
	if (event.wheelDelta) // IE & Opera
	realDelta = event.wheelDelta / 120;
	else if (event.detail) // W3C
	realDelta = -event.detail / 3;

	if (realDelta > 0) {

		if($('content_carousel'))
			$('content_carousel').scrollLeft=scroll - 50
		else
			$('horizontal_carousel1').scrollLeft=scroll - 50
	}
	/* Mousewheel DOWN*/
	else if ((realDelta < 0) && (scroll >= 0)) {
		if($('content_carousel'))
			$('content_carousel').scrollLeft=scroll + 50
		else
			$('horizontal_carousel1').scrollLeft=scroll + 50
	}


}

/**
*	FLASH DETECTION
*/
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function RecordFlashAnalytics(flashfile,event,eventsubject){
	
	if(event=='')event='notset';
	if(eventsubject=='')eventsubject='notset';
	
	var buildpath = "/flash/"+flashfile+"/"+event+"/"+eventsubject;
	pageTracker._trackPageview(buildpath);	
}

// ]]>
