var showCheckoutOnLoad = false;
var showPricePromiseBoxOnLoad = false;
var submitPricePromiseForm = false;
var showTileSamplesBoxOnLoad = false;
var submitTileSamplesForm = false;
var showAccountLoginBoxOnLoad = false;
var showSpecialOfferPopupOnLoad = false;
var currentImage = 0;

menu_position_mod_x = -7;
menu_position_mod_y = 0;
menu_filter = '';
menu_location = 'S';
menu_fadeout = false;
hideTime = 0;

function doClass( id ) {
	document.getElementById( 'nav_item_' + id ).className = 'hover';
}

function undoClass( id ) {
	document.getElementById( 'nav_item_' + id ).className = 'button';
}

/** BEGIN CALCULATOR **/

function showCalculator( elementId, criteriaLength, criteriaDisplayLength, criteriaLengthUnit, criteriaWidth, criteriaDisplayWidth, criteriaWidthUnit, criteriaPackSize, productName ) {
	// get its x and y
	var newXPos = findPosX( elementId ) - 64;
	var newYPos = findPosY( elementId ) + 28;
	// assign the values to the page for use in calculations
	document.getElementById( 'calculate_length' ).value = criteriaLength;
	document.getElementById( 'calculate_width' ).value = criteriaWidth;
	document.getElementById( 'calculate_pack_size' ).value = criteriaPackSize;
	// show the product name
	document.getElementById( 'calculatorProductName' ).innerHTML = productName;
	// tile dimensions (display purpose only)
	document.getElementById( 'tile_width' ).innerHTML = parseFloat( criteriaDisplayWidth );
	document.getElementById( 'calculate_width_unit' ).innerHTML = criteriaWidthUnit;
	document.getElementById( 'tile_length' ).innerHTML = parseFloat( criteriaDisplayLength );
	document.getElementById( 'calculate_length_unit' ).innerHTML = criteriaLengthUnit;
	// and move the calculator into position
	var calculator = document.getElementById('calculator');
	calculator.style.left = newXPos + "px";
	calculator.style.top = newYPos + "px";
	calculator.style.display = '';
}

function convertFromCM( val, units ) {
	switch( units ) {
		case 'mm':
			return val*10;
			break;
		case 'cm':
			return val;
			break;
		case 'in':
			return val / 2.54;
			break;
		case 'ft':
			return val / 30.48;
			break;
		case 'metre':
			return val / 100;
			break;
	}
}

function convertToCM( val, units ) {
	switch( units ) {
		case 'mm':
			return val/10;
			break;
		case 'cm':
			return val;
			break;
		case 'in':
			return val * 2.54;
			break;
		case 'ft':
			return val * 30.48;
			break;
		case 'metre':
			return val * 100;
			break;
	}
}

function calculateArea( w, l ) {
	return w * l;
}

function calculateTilesNeededByDimensions( ) {
	if ( ( document.getElementById( 'areaW').value != '' ) && ( document.getElementById( 'areaL').value != '' ) ) {
		var units = document.getElementById( 'calculatorUnitsDim' ).value;
		var area = calculateArea( convertToCM( document.getElementById( 'areaW').value, units ), convertToCM( document.getElementById( 'areaL').value, units ) );
		var qtyRequired = calculateTilesNeeded( area );
		document.getElementById( 'qtyNeeded' ).innerHTML = qtyRequired;
	} else {
		alert( 'Please enter the dimensions you wish to cover.' );
		return false;
	}
}

function calculateTilesNeededByArea( ) {
	if ( document.getElementById( 'totalArea').value != '' ) {
		var units = document.getElementById( 'calculatorUnitsArea' ).value;
		var dimension = convertToCM( Math.sqrt(document.getElementById( 'totalArea').value), units );
		var area = Math.round( dimension * dimension );
		var qtyRequired = calculateTilesNeeded( area );
		document.getElementById( 'qtyNeeded' ).innerHTML = qtyRequired;
	} else {
		alert( 'Please enter the area you wish to cover.' );
		return false;
	}
}

function calculateTilesNeeded( area ) {
	area = area * 1.1; // add 10% for wastage
	var packSizeCovered = ( document.getElementById( 'calculate_length' ).value * document.getElementById( 'calculate_width' ).value ) * document.getElementById( 'calculate_pack_size' ).value;
	qtyRequired = Math.ceil( area / packSizeCovered );
	return qtyRequired;
}

function updateQuantityRequired() {
	if ( document.getElementById( 'qtyNeeded' ).innerHTML > 1 ) {
		document.getElementById( 'CMSCatalogueBasket_product_quantity' ).value = document.getElementById( 'qtyNeeded' ).innerHTML;
	} else {
		document.getElementById( 'qtyNeeded' ).innerHTML = 1;
	}
	document.getElementById('calculator').style.display = 'none';
}

function numberFormat(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function pricePerSqMetre(price,length,height) {
	//note length and height are in cm
	var pricePerSqMetre = price/((length/100)*(height/100));
	return numberFormat( pricePerSqMetre.toFixed(2) );
}

/** END CALCULATOR **/

function correctPNGBackground( divId, imgURL, method ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	if( method == 'undefined' ) {
		method = 'scale';
	}
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	{
		var div = document.getElementById( divId );
		div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgURL+"', sizingMethod='" + method + "')";
		div.style.background = '';
	}    
}
function correctPNG( imageId, imgURL ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	{
		var img = document.getElementById( imageId );
		var imgID = (img.id) ? "id='" + img.id + "' " : "";
		var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		var imgStyle = "display:inline-block;" + img.style.cssText 
		if (img.align == "left") imgStyle = "float:left;" + imgStyle
		if (img.align == "right") imgStyle = "float:right;" + imgStyle
		if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		var strNewHTML = "<span " + imgID + imgClass + imgTitle
		+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
		+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		+ "(src=\'" + imgURL + "\', sizingMethod='scale');\"></span>";
		img.outerHTML = strNewHTML;
		return false;
	}    
}

function showCheckout() {
	var xpos = $('#minibasket').offset().left;
	$('#checkoutPopup').css('left',xpos+35);
	$('#checkoutPopup').show();
	$('#checkoutPopup').animate({width:"188px"},5000,function() {
		hideCheckout();
	});
}
function hideCheckout() {
	$('#checkoutPopup').hide();
}

function addProductToBasket( productId ) {
	var validate = new validateForm();
	if( productId != '' ) {
		validate.checkNumeric( 'CMSCatalogueBasket_product_quantity_' + productId, 'Quantity' );
	} else {
		validate.checkNumeric( 'CMSCatalogueBasket_product_quantity', 'Quantity' );
	}
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}

	var handleSuccess = function(o){
		document.getElementById( 'checkoutPopup' ).innerHTML = o.responseText;
		showCheckout();
		// update the minibasket
		document.getElementById('minibasketSummaryItemsNumber').innerHTML = document.getElementById('temp_minibasket_total_items').value + ' ';
		document.getElementById('minibasketSummaryItemsValueIncVAT').innerHTML = document.getElementById('temp_minibasket_total_value_inc_vat').value;
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	// argument formId can be the id or name attribute value of the
	// HTML form, or an HTML form object.
	if( productId != ''  ) {
		var formObject = document.getElementById( 'productForm_' + productId );
	} else {
		var formObject = document.getElementById( 'productForm' );
	}

	YAHOO.util.Connect.setForm(formObject);
	// This example facilitates a POST transaction.
	// An HTTP GET can be used as well.
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
	// scroll to top of page
	window.scroll(0,0);
}

function inputBoxFocus( input, defaultText, passwordField ) {
	if( typeof( passwordField ) != 'undefined' ) {
		document.getElementById( passwordField ).style.display = '';
		document.getElementById( passwordField+'_text' ).style.display = 'none';
		document.getElementById( passwordField ).focus();
	} else {
		if( input.value == defaultText ) {
				input.value = '';
		} else {
		}
	}
}

function inputBoxBlur( input, defaultText, passwordField ) {
	if( input.value == '' ) {
		if( typeof( passwordField ) != 'undefined' ) {
			document.getElementById( passwordField ).style.display = 'none';
			document.getElementById( passwordField+'_text' ).style.display = '';
		} else {
			input.value = defaultText;
		}
	}
}

function doSearch( ) {
	if ( ( document.getElementById( 'quickSearchText' ).value != '' ) && ( document.getElementById( 'quickSearchText' ).value != ' - Quick Product Search' ) ) {
		document.location = '/products/%20search::' + document.getElementById( 'quickSearchText' ).value;
	} else {
		alert( "Please enter search text" );
	}
	return false;
}

function doAdvancedSearch() {
	var queryString = '/products';
	var colour = document.getElementById('search_colour').value;
	var size = document.getElementById('search_size').value;
	var area = document.getElementById('search_area').value;
	var txt = document.getElementById( 'quickSearchText' ).value;
	var doSearch = false;
	
	if ( colour != '' ) {
		queryString += '/%20Colour::' + colour;
		doSearch = true;
	}
	if ( size != '' ) {
		queryString += '/%20Size::' + size;
		doSearch = true;
	}
	if ( area != '' ) {
		queryString += '/%20Area of Use::' + area;
		doSearch = true;
	}
	if ( ( txt != '' ) && ( txt != ' - Quick Product Search' ) ) {
		queryString += '/%20search::' + txt;
		doSearch = true;
	}
	if ( doSearch ) {
		document.location = queryString;
	} else {
		alert('Please select some search criteria');
	}
}

/* price promise */

function initPricePromise() {
	correctPNGBackground( 'pricePromisePopupBg', '/custom/images/price-promise-bg.png' );
	document.getElementById('pricePromisePopup').style.display = '';
	pricePromiseBox = 
		new YAHOO.widget.Panel("pricePromisePopup",  
										{ width:"324px", 
										  height:"418px", 
										  fixedcenter:true, 
										  close:false, 
										  draggable:false, 
										  modal:true,
										  visible:false,
										  underlay:"none",
										  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
										} 
									);

	pricePromiseBox.render(document.body);
	if( showPricePromiseBoxOnLoad )
		pricePromiseBox.show();
}

function hidePricePromise() {
	if( typeof pricePromiseBox != "undefined" )
		pricePromiseBox.hide();
	submitPricePromiseForm = false;
}

function showPricePromise() {
	if( typeof pricePromiseBox != "undefined" )
		pricePromiseBox.show();
	else
		showPricePromiseBoxOnLoad = true
}

function initAccountLogin() {
	correctPNGBackground( 'accountLoginPopupBg', '/custom/images/account-login-bg.png' );
	document.getElementById('accountLoginPopup').style.display = '';
	accountLoginBox = 
		new YAHOO.widget.Panel("accountLoginPopup",  
										{ width:"324px", 
										  height:"318px", 
										  fixedcenter:true, 
										  close:false, 
										  draggable:false, 
										  modal:true,
										  visible:false,
										  underlay:"none",
										  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
										} 
									);

	accountLoginBox.render(document.body);
	if( showAccountLoginBoxOnLoad )
		accountLoginBox.show();
}

function hideAccountLogin() {
	if( typeof accountLoginBox != "undefined" )
		accountLoginBox.hide();
}

function showAccountLogin() {
	if( typeof accountLoginBox != "undefined" )
		accountLoginBox.show();
	else
		showAccountLoginBoxOnLoad = true
}

function initOneMoreThing() {
	correctPNGBackground( 'oneMoreThingBg', '/custom/images/one-more-thing.png' );
	document.getElementById('oneMoreThing').style.display = '';
	oneMoreThingBox = 
		new YAHOO.widget.Panel("oneMoreThing",  
										{ width:"324px", 
										  height:"224px", 
										  fixedcenter:true, 
										  close:false, 
										  draggable:false, 
										  modal:true,
										  visible:false,
										  underlay:"none",
										  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
										} 
									);

	oneMoreThingBox.render(document.body);
}

function hideOneMoreThing() {
	if( typeof oneMoreThingBox != "undefined" )
		oneMoreThingBox.hide();
}

function showOneMoreThing() {
	if( typeof oneMoreThingBox != "undefined" )
		oneMoreThingBox.show();
}

function onPricePromisePopupSubmit() {
	// if we are submitting to form
	if( submitPricePromiseForm ){
		// ensure we have all details
		var validate = new validateForm();
		validate.checkText( 'first_name', 'First Name', 'First Name*' );
		validate.checkText( 'last_name', 'Last Name', 'Last Name*' );
		validate.validateEmailAddress( 'email_address', 'Email Address' );
		validate.checkText( 'phone_number', 'Contact Number', 'Contact Number*' );
		validate.checkText( 'product', 'Product Name', 'Product Name*' );
		validate.checkNumeric( 'price_found', 'Price Quoted' );
		validate.checkText( 'where_found', 'Place where product was found', 'Place/Store/URL where product was found*' );
		if( validate.numberOfErrors() > 0 ) {
			validate.displayErrors();
			// we have errors
			submitPricePromiseForm = false;
		}
		
		document.getElementById( 'pricePromiseForm' ).action = '/email/price_promise';
	}
	
	return submitPricePromiseForm;
}

/* tile samples */

function onTileSamplesPopupSubmit() {
	// if we are submitting to form
	if( submitTileSamplesForm ){
		// ensure we have all details
		var validate = new validateForm();
		validate.checkText( 'sample_contact_name', 'Name', 'Name*' );
		validate.validateEmailAddress( 'sample_email_address', 'Email' );
		validate.checkNumeric( 'sample_phone_number', 'Phone' );
		validate.checkText( 'sample_address_1', 'Address 1', 'Address 1*' );
		validate.checkText( 'sample_town', 'Town', 'Town*' );
		validate.checkText( 'sample_county', 'County', 'County*' );
		validate.validatePostCode( 'sample_postcode', 'Postcode' );
		
		if( validate.numberOfErrors() > 0 ) {
			validate.displayErrors();
			// we have errors
			submitTileSamplesForm = false;
		}
		
		document.getElementById( 'tileSamplesForm' ).action = '/email/tile_samples';
	}
	
	return submitTileSamplesForm;
}

function checkPostcode() {
	if( document.getElementById( 'address' ).value == '- Enter your postcode...' ) {
		alert( "Please enter your postcode" );
		return false;
	}
	return true;
}

function showTerms(){
	window.open( '/popup/terms', 'mywindow', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, width=509, height=500');
}

function showPrivacy(){
	window.open( '/popup/privacy', 'mywindow', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, width=509, height=500');
}

function doAskAQuestion() {
	var validate = new validateForm();
	var validate2 = new validateForm();
	if( document.getElementById( 'ask_a_question_name' ).value == ' - Enter Name' ) {
		validate.addCustomError( 'Enter Name' );
	} else {
		validate.checkText( 'ask_a_question_name', 'Enter Name' );
	}
	if( document.getElementById( 'ask_a_question_email_address' ).value == ' - Enter Email Address' ) {
		validate2.addCustomError( 'Enter Email Address' );
	} else {
		validate2.validateEmailAddress( 'ask_a_question_email_address', 'Enter Email Address' );
	}
	if( document.getElementById( 'ask_a_question_telephone' ).value == ' - Your Telephone Number' ) {
		validate2.addCustomError( 'Your Telephone Number' );
	} else {
		validate2.checkText( 'ask_a_question_telephone', 'Your Telephone Number' );
	}
	if( validate2.numberOfErrors() > 1 ) {
		validate.addCustomError( 'Email Address and/or Telephone Number' );
	}
	if( document.getElementById( 'ask_a_question_question' ).value == "Type your question here..." ) {
		validate.addCustomError( "Type your question ..." );
	} else {
		validate.checkText( 'ask_a_question_question', "Type your question ..." );
	}
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}

	var handleSuccess = function(o){
		document.getElementById('askAQuestionContainer').style.display = 'none';
		alert( "Your question was succesfully sent, we will be in touch as soon as possible" );		
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	var formObject = document.getElementById( 'askAQuestionForm' );

	YAHOO.util.Connect.setForm(formObject);
	var cObj = YAHOO.util.Connect.asyncRequest('GET', '/email/askAQuestion', callback);
}
function changeFilter(basePath,filterString,filterName,filterValue) {
	if(filterValue != '') {
		basePath = basePath + filterString + '/ ' + filterName + '::' + filterValue;
	}
	else {
		basePath = basePath + filterString;
	}
	document.location = basePath;
}
function scrollDecrease(scrollName) {
	var currentPosition = $('#'+scrollName).parent().scrollTop();
	var scrollerHeight = $('#'+scrollName).height();
	if(currentPosition > 0) {
		$('#'+scrollName).parent().scrollTop(currentPosition - 333);
	}
}
function scrollIncrease(scrollName) {
	var currentPosition = $('#'+scrollName).parent().scrollTop();
	var scrollerHeight = $('#'+scrollName).height();
	if(scrollerHeight - currentPosition > 333) {
		$('#'+scrollName).parent().scrollTop(currentPosition + 333);
	}
}
function darkenLeft() {
	$('#navLeft').css('background','url(/custom/images/nav-left-dark.gif) no-repeat left');
}
function lightenLeft() {
	$('#navLeft').css('background','url(/custom/images/nav-left.gif) no-repeat left');
}
function increaseQuantity(inputId) {
	var inputvalue = $('#'+inputId).val();
	inputvalue++;
	$('#'+inputId).val(inputvalue);
}
function decreaseQuantity(inputId) {
	var inputvalue = $('#'+inputId).val();
	if(inputvalue > 1) {
		inputvalue--;
		$('#'+inputId).val(inputvalue);
	}
}
function selectPickup() {
	$('#pickupSelectTop').attr('src','/custom/images/store-pickup-select-active.gif');
	$('.pickupSelectRow').attr('src','/custom/images/store-pickup-on.gif');
	$('#pickupSelectBottom').attr('src','/custom/images/store-pickup-select-bottom-active.gif');
		
	$('.storePickupCell').css('border-top','1px solid #00a160');
	$('.storePickupCell').css('border-bottom','1px solid #ccecdf');
	
	$('#checkoutPricing').css('background','#ccecdf');
	$('#checkoutPricing').css('border-top','1px solid #00a160');
	
	$('#standardStage3Text').hide();
	$('#pickupStage3Text').show();
	$('#checkoutAddress').hide();
	$('#reserveSearch').show();
	$('#pickupTotalsText').show();
}
function showTileSamples(element) {
	var xPos = $(element).offset().left;
	var yPos = $(element).offset().top;
	$('#tileSamples').css('left',xPos-82);
	$('#tileSamples').css('top',yPos+30);
	$('#tileSamples').show();
}
function hideTileSamples() {
	$('#tileSamples').hide();
}

function showAskAQuestion(element) {
	var xPos = $(element).offset().left;
	var yPos = $(element).offset().top;
	$('#askAQuestionContainer').css('left',xPos-264);
	$('#askAQuestionContainer').css('top',yPos+128);
	$('#askAQuestionContainer').show();
}

/* Banner Stuff */
var totalBanners = 10;
var currentBanner = 1;
var timeoutId = 0;
var bannerAnimating = 0;
var neverAnimate = 0;

function showNextBanner() {
	clearTimeout(timeoutId);
	if(currentBanner < totalBanners) {
		var nextBanner = currentBanner + 1;
	}
	else {
		var nextBanner = 1;
	}
	$('#banner_image_'+currentBanner).fadeOut(2000);
	$('#banner_image_'+nextBanner).fadeIn(2000);
	currentBanner = nextBanner;
	if(neverAnimate == 0) {
		timeoutId = setTimeout('showNextBanner()',8000);
		bannerAnimating = 1;
	}
}
function showPreviousBanner() {
	clearTimeout(timeoutId);
	if(currentBanner == 1) {
		var nextBanner = totalBanners;
	}
	else {
		var nextBanner = currentBanner - 1;
	}
	$('#banner_image_'+currentBanner).fadeOut(2000);
	$('#banner_image_'+nextBanner).fadeIn(2000);
	currentBanner = nextBanner;
	if(neverAnimate == 0) {
		timeoutId = setTimeout('showPreviousBanner()',8000);
		bannerAnimating = 1;
	}
}
function toggleBanner() {
	if(bannerAnimating == 1) {
		clearTimeout(timeoutId);
		bannerAnimating = 0;
	}
	else {
		if(neverAnimate == 0) {
			timeoutId = setTimeout('showNextBanner()',8000);
			bannerAnimating = 1;
		}
	}
}
/*End of Banner Stuff*/



function initSpecialOfferPopup() {
	if($( '#specialOfferPopup' ).length == 0 )
		return;
	
	document.getElementById('specialOfferPopup').style.display = '';
	offerBox = new YAHOO.widget.Panel( 'specialOfferPopup', {
				width:"330px",
				height:"223px",
				fixedcenter:true,
				close:false,
				draggable:false,
				modal:true,
				visible:false,
				underlay:"none",
				effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
			}
		);

	offerBox.render(document.body);
	if( showSpecialOfferPopupOnLoad )
		offerBox.show();
}

function hideSpecialOfferInfo() {
	if( typeof offerBox != "undefined" )
		offerBox.hide();
}

function showSpecialOfferInfo( description, offerType ) {
	if ( description != '' ) {
		document.getElementById('specialOfferPopupContainer').innerHTML = description;
		if ( offerType == 'bogof' ) {
			var stickerSrc = 'rosette-bogof.png';
		} else {
			var stickerSrc = 'rosette-sale.png';
		}
		document.getElementById('specialOfferPopupSticker').src = '/custom/images/' + stickerSrc;
		if( typeof offerBox != "undefined" )
			offerBox.show();
		else
			showSpecialOfferOnLoad = true
	}
}

function checkLogin() {
	var validate = new validateForm();
	if( document.getElementById( 'clientLogin_username') .value == 'Enter Email Address...' ) {
		validate.addCustomError( 'Enter Email Address...' );
	} else {
		validate.validateEmailAddress( 'clientLogin_username', 'Email Address not valid' );
	}
	validate.checkText( 'clientLogin_password', 'Password' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	return true;
}

function checkForgotten() {
	var validate = new validateForm();
	if( document.getElementById( 'clientLogin_username') .value == 'Enter Email Address...' ) {
		validate.addCustomError( 'Enter Email Address...' );
	} else {
		validate.validateEmailAddress( 'clientLogin_username', 'Email Address not valid' );
	}
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	else {
		document.getElementById('cmsAuthForgottenPasswordPopup_email').value = document.getElementById( 'clientLogin_username').value;
	}
	return true;
}

function showThumb( imageNo ){
	document.getElementById( 'productImage' ).style.backgroundImage = 'url('+imageArray[imageNo]['src_medium']+')';
	document.getElementById( 'productImage' ).title = imageArray[imageNo]['caption'] + ': Click for larger image';
	// update the current image number
	currentImage = imageNo;
}
function showLarge( ) {
	if( imageArray[currentImage]['src'] != '' ) {
		imgWin=window.open('about:blank','','scrollbars=no,width=500,height=500,left=100,top=100');
		with (imgWin.document) {
			writeln('<HTML><HEAD><TITLE></TITLE><scr'+''+'ipt language="javascript">var arrTemp=self.location.href.split("?");var NS = (navigator.appName=="Netscape")?true:false;function FitPic() { iWidth = (NS)?window.innerWidth:document.body.clientWidth; iHeight = (NS)?window.innerHeight:document.body.clientHeight; iWidth = document.images[0].width - iWidth; iHeight = document.images[0].height - iHeight; window.resizeBy(iWidth, iHeight); self.focus(); }; </scr'+''+'ipt> </HEAD> <BODY bgcolor="#ffffff" onload="FitPic();" topmargin="0" marginheight="0" leftmargin="0" marginwidth="0"> <img src="' + imageArray[currentImage]['src'] + '" border="0" /></BODY> </HTML>');
			close();	
		}
	}
}

/** store locator **/

var popup = false;
var mapsLoaded = new Array();
var branchLocations = new Array();
var defaultMapX = 51.703613;
var defaultMapY = -0.507617;
var map;
var currentDisplayedStore = 'branch_list';
var globalBranchId = false;

function branchClick_branch_list( ) {
	if( currentDisplayedStore ) {
		document.getElementById(currentDisplayedStore).style.display = 'none';
	}
	if( marker ) {
		marker.closeInfoWindow();
	}
	document.getElementById('branch_list').style.display = '';
	currentDisplayedStore = 'branch_list';
	
	map.setCenter(new GLatLng(defaultMapX,defaultMapY), 8);
	document.getElementById('directions_div').style.display = 'none';
	directions.clear();
}

function foundAddress(detail) {
	if( detail['Status']['code'] != 200 ) {
		alert( 'Sorry, we could not locate that address' );
		return;
	}
	document.getElementById('address').value = detail['Placemark'][0]['address'];
	var point = new GLatLng( detail['Placemark'][0]['Point']['coordinates'][1], detail['Placemark'][0]['Point']['coordinates'][0] );

	closestDistance = 0;
	closestStore = globalBranchId;
	if( !closestStore ) {
		for( var branchId in branchLocations ) {
			//calc distance
			var a = (branchLocations[branchId][1]-detail['Placemark'][0]['Point']['coordinates'][0]);
			var b = (branchLocations[branchId][0]-detail['Placemark'][0]['Point']['coordinates'][1]);
			var c = Math.sqrt(a*a + b*b);
			if ( !isNaN( c ) && ( ( !closestStore ) || ( closestDistance > c ) ) ) {
				closestDistance = c;
				closestStore = branchId;
			}
		}
	}
	if ( ( closestStore ) && ( closestStore != 'empty' ) ) {
		eval( 'branchClick_'+closestStore+'( false )' );
		getDirections( detail['Placemark'][0]['Point']['coordinates'][1]+', '+detail['Placemark'][0]['Point']['coordinates'][0] );
	}
}

function onDirectionsLoad() {
}

function findClosest( address, branchId ) {
	globalBranchId = branchId;
	geocoder.getLocations( address,  foundAddress );			
}

function onDirectionsError() {
	var error = directions.getStatus();
	alert( error.code );
}

function getNewDirections( address, branchId ) {
	findClosest( address, branchId );
}

function getDirections(address) {  
	//GEvent.addListener(directions, "error", onDirectionsError);
	directions.load( address+' to '+branchLat+', '+branchLong );
	document.getElementById('directions_div').style.display = '';
}

function printCoupon() {
	var printWin = window.open( '/custom/images/coupon-print.jpg', 'couponWindow', 'width=610, height=168' );
	printWin.print();
}

/** end store locator **/


function setCookie( name, value ) {
	document.cookie = name + '=' + value + ';path=/;';
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}

function clearCookie( name ) {
	document.cookie = name + '=;expires=-86400000;path=/;';
}

$(document).ready(function() {
	initSpecialOfferPopup();
	$('.featuredItem').mouseenter(function(){
		$(this).css('background-color','#ffc424');
		$(this).css('border','1px solid #ffc424');
	});
	$('.featuredItem').mouseleave(function(){
		$(this).css('background-color','#ffffff');
		$(this).css('border','1px solid #dfdfdf');
	});
	correctPNGBackground( 'checkoutPopupShadow', '/custom/images/checkout-rpt.png' );
	initPricePromise();
	initAccountLogin();
});