var pricesToChange = new Array();
var featuredProducts = new Array();
var currentProductOption = '';

function logout() {
	document.getElementById('logoutForm').submit();
}

function hideMiniBasket() {
	document.getElementById('miniBasketDrawerOpen').style.visibility = 'visible';
	document.getElementById('miniBasketProducts').style.display = 'none';
}
function expandMiniBasket() {
	document.getElementById('miniBasketDrawerOpen').style.visibility = 'hidden';
	document.getElementById('miniBasketProducts').style.display = '';
	window.scrollTo(0,0);
}

function doBrandSearch( brand ) {
	if ( brand != '' ) {
		document.location = '/products/ Brand::' + brand;
	}
}

function addToBasket( productId, onProductPage, addingMultiple, multipleProductIds, redirectToCheckout ) {
	if ( typeof addingMultiple == 'undefined' ) {
		var validate = new validateForm();
		if( !onProductPage ) {
			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){
		var first5Chars = o.responseText.substr( 0, 5 );
		if ( first5Chars == 'ERROR' ) {
			alert( o.responseText.substr( 6, o.responseText.length ) );
		} else {
			document.getElementById( 'miniBasketInfo' ).innerHTML = o.responseText;
			if( redirectToCheckout ) {
				// redirect to checkout
				document.location = '/checkout'	;
			} else {
				checkCurrencyCookie();
				expandMiniBasket();
				alert( "This product has now been added to your shopping basket" );
				setTimeout( 'hideMiniBasket()', 4000 );
			}
		}
	};
	var handleFailure = function(o){
		alert( 'An error occured adding this item to your basket.  Please try again.' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	
	if ( typeof addingMultiple == 'undefined' ) {
		if( !onProductPage  ) {
			var formObject = document.getElementById( 'productForm_' + productId );
		} else {
			var formObject = document.getElementById( 'productForm' );
		}
	} else {
		var formObject = document.getElementById( 'multipleAddForm' );
	}
	
	YAHOO.util.Connect.setForm(formObject);
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
}

function doSuccessPopup() {
	window.open("/productAdded","productAdded","width=200,height=100,left=300,top=300");	
}

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 = '';
		}
	}
}

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 subscribeUserInline(){
	var validateform = new validateForm();
	// check we have name, email
	var emailAddress = document.getElementById('cmsContentSubscribe-emailAddressInline');
	if(( emailAddress.value != '- Email Address...' ) && ( emailAddress.value != '' )){
		// check email address is an email address
		validateform.validateEmailAddress( emailAddress.value );
		if(validateform.numberOfErrors() > 0) {
			validateform.displayErrors();
		} else {
			return true;
		}
	} else {
		validateform.addCustomError( 'Please enter your email address.' );
		validateform.displayErrors();
		emailAddress.focus();
	}
	return false;
}

function getCurrentCurrency() {
	var curr = getCookie( 'currencyViewing' );
	if ( !curr ) {
		setCookie( 'currencyViewing', 'Pounds' );
		return 'Pounds'; // show pounds by default
	} else {
		return curr;
	}
}

function showCurrencyDropDown() {
	document.getElementById('currencySelectorDropDown').style.display = '';
}
function hideCurrencyDropDown() {
	document.getElementById('currencySelectorDropDown').style.display = 'none';
}


function addToWishList( itemID, quantity ) {
	var sUrl = "/xmlservice.php?service=addToWishList&itemType=1&itemID=" + itemID + "&quantity=" + quantity;

	var handleSuccess = function( result ){
		document.getElementById( 'wishListAddButton_' + itemID ).style.display = 'none';
		document.getElementById( 'wishListRemoveButton_' + itemID ).style.display = '';
	}
	
	var handleFailure = function(o){
		alert( 'Sorry, there was an error saving this item to your wishlist.  Please try again.' );
	}
	
	var callback =
	{
	  success: handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

function removeFromWishList( itemID, inWishList ) {
	var sUrl = "/xmlservice.php?service=removeFromWishList&itemType=1&itemID=" + itemID + '&wishlistId=null';
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				if ( !inWishList ) {
					document.getElementById( 'wishListAddButton_' + itemID ).style.display = '';
					document.getElementById( 'wishListRemoveButton_' + itemID ).style.display = 'none';
				} else {
					document.getElementById( 'wishListItem_' + itemID ).style.display = 'none';
					numberOfWishListItems--;	// global var on the /wishlist page
					if ( numberOfWishListItems == 0 ) {
						document.getElementById( 'noWishListItemsMessage' ).style.display = '';
						document.getElementById( 'wishlistTable' ).style.display = 'none';
					} else {
						// update the row colours
						var tbody = document.getElementById('wishlistItems');
						var rows = tbody.getElementsByTagName('TR');
						var rowCount = 0;
						for ( var i in rows ) {
							if ( document.getElementById( rows[i].id ) ) {
								idSplit = rows[i].id.split('_');
								if ( rows[i].style.display != 'none' ) {
									rowClass = ( rowCount % 2 == 0 ) ? 'rowDark' : 'rowLight';
									document.getElementById( rows[i].id ).className = rowClass;
									rowCount++;
								}
							}
						}
					}
				}
			} else {
				alert( 'Sorry, an error occured whilst removing this item from your wish list.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst removing this item from your wish list.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}


function doSimpleSearch(){
	if( document.getElementById('quickSearch').value != '' ){
		document.location = '/products/%20namesearch::' + document.getElementById('quickSearch').value;
	} else {
		alert( "Please enter a search term" );
	}
	return false;
}

function initQuickSearch() {
	
	//auto suggest
	// An XHR DataSource   
	var myServer = "/xmlservice.php";
	var mySchema = ["ResultSet.Result", "display", "code", "image", "media", "path", "resultSize" ];
	var productDataSource = new YAHOO.widget.DS_XHR(myServer, mySchema); 
	productDataSource.scriptQueryAppend  = "service=quickSearch&nameSearch=true";
	
	var autoCompleteProduct = new YAHOO.widget.AutoComplete("quickSearch","quickSearchSuggest", productDataSource, { forceSelection : false, useShadow : true, allowBrowserAutocomplete : false, animHoriz : true, allowBrowserAutocomplete : false } );

	
	// This function returns markup that bolds the original query,
	// and also displays to additional pieces of supplemental data.
	autoCompleteProduct.formatResult = function(aResultItem, sQuery) {
		var name = aResultItem[0]; // the entire result key
		var code = aResultItem[1];
		

		var image = aResultItem[2];
		var media = aResultItem[3];
		var path = aResultItem[4];
		var results = aResultItem[5];
		
		if( results ) {
			this.setHeader('Displaying: '+results+' results');
			this.setFooter('<a href="/products/%20namesearch::'+escape(sQuery)+'">Show All Results</a>');
		}

		var thumbUrl = '';

		if( media && media[0] ) {
			thumbUrl = media[0]['preview_url'];
		} else {
			thumbUrl ='/custom/images/noimage.jpg';
		}
		
		var aMarkup = "<table class='searchResult'><tr><td class='searchResultName'>"+name+"</td><td class='searchResultImage'>" + ( ( thumbUrl != '' ) ? "<img class='searchImage' src='"+thumbUrl+"' />" : '' ) + "</td></tr></table>";
		return aMarkup;
	};
	
	autoCompleteProduct.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) {   
		var pos = YAHOO.util.Dom.getXY(oTextbox);   
		pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight;   
		pos[0] -= 400;
		pos[0] += YAHOO.util.Dom.get(oTextbox).offsetWidth;
		YAHOO.util.Dom.setXY(oContainer,pos);   
		return true;   
	};   
	
	autoCompleteProduct.itemSelectEvent.subscribe( function( oSelf , elItem , aResultItem )  {
			var path = elItem[2][4];
			if( path ) {
				document.location = path;
			}
		}
		, autoCompleteProduct );

}


function setTall() {
	if ( document.getElementById ) {
		var divs = new Array( 
			new Array( 
				new Array( document.getElementById('lhs'), document.getElementById('contentArea'), document.getElementById('rhs')),
				new Array( document.getElementById('menu'), document.getElementById('contentArea'), document.getElementById('topProductsContent'))
			)
		);
		for (var i = 0; i < divs.length; i++) {
			var maxHeight = 0;
			for (var j = 0; j < divs[i][0].length; j++) {
				if (divs[i][0][j].offsetHeight > maxHeight) {
					maxHeight = divs[i][0][j].offsetHeight;
				}
			}
			for (var j = 0; j < divs[i][0].length; j++) {
				divs[i][divs[i].length-1][j].style.height = maxHeight + 'px';
				if (divs[i][0][j].offsetHeight > maxHeight) {
					divs[i][divs[i].length-1][j].style.height = ( parseInt(divs[i][divs[i].length-1][j].style.height) - (divs[i][0][j].offsetHeight - maxHeight)) + 'px';
				}
			}
		}
		document.getElementById('lhs').style.height = 'auto';
		document.getElementById('contentArea').style.height = 'auto';
		document.getElementById('rhs').style.height = 'auto';
	}
}

function setTallHomeFeatured() {
	if ( document.getElementById ) {
		var divs = new Array( 
			new Array( 
				new Array( document.getElementById('content_featuredProduct1'), document.getElementById('content_featuredProduct2'), document.getElementById('content_featuredProduct3'))
			)
		);
		for (var i = 0; i < divs.length; i++) {
			var maxHeight = 0;
			for (var j = 0; j < divs[i][0].length; j++) {
				if (divs[i][0][j].offsetHeight > maxHeight) {
					maxHeight = divs[i][0][j].offsetHeight;
				}
			}
			for (var j = 0; j < divs[i][0].length; j++) {
				divs[i][divs[i].length-1][j].style.height = maxHeight + 'px';
				if (divs[i][0][j].offsetHeight > maxHeight) {
					divs[i][divs[i].length-1][j].style.height = ( parseInt(divs[i][divs[i].length-1][j].style.height) - (divs[i][0][j].offsetHeight - maxHeight)) + 'px';
				}
			}
		}
	}
}

function sortNumber( a, b ) {
	return a - b;
}

function optionChanged( e, obj ) {
	var productId = obj.productId;
	var uniqueId = obj.uniqueId;
	currentProduct = obj.productName;
	// loop through all options to see if all required options have been selected
	var sortedIds = new Array();
	var selectedOptions = new Array();
	var isUnselected = false;
	for ( var optionId in obj.optionIds ) {
		var isOptional = obj.optionIds[optionId];
		var select = document.getElementById( obj.selectId + '' + optionId );
		if ( select.selectedIndex > 0 ) {
			selectedOptions.push( select.options[ select.selectedIndex ].text );
		} else {
			isUnselected = true;
		}
		if ( !isOptional ) {
			if ( select.value ) {
				sortedIds.push( select.value );
			}
		}
	}
	sortedIds.sort( sortNumber );
	var optionIdsJoined = sortedIds.join('_');
	currentProductOption = selectedOptions.join(', ');
//	var stockLevel = stock[ productId ][ optionIdsJoined ];
//
//	if ( ( stockLevel == '0' || stockLevel == '' || !stockLevel ) && ( !isUnselected ) ) {
//		// show "out of stock" message
//		document.getElementById('stockDisplayOut_' + uniqueId + '_' + productId).style.display = 'block';
//		if ( document.getElementById('stockDisplayOut2_' + uniqueId + '_' + productId) ) {
//			document.getElementById('stockDisplayOut2_' + uniqueId + '_' + productId).style.display = 'inline';
//		}
//		document.getElementById('stockDisplayIn_' + uniqueId + '_' + productId).style.display = 'none';
//	} else {
		// show "add to basket" button
//		document.getElementById('stockDisplayOut_' + uniqueId + '_' + productId).style.display = 'none';
//		if ( document.getElementById('stockDisplayOut2_' + uniqueId + '_' + productId) ) {
//			document.getElementById('stockDisplayOut2_' + uniqueId + '_' + productId).style.display = 'none';
//		}
//		document.getElementById('stockDisplayIn_' + uniqueId + '_' + productId).style.display = 'inline';
//	}
}

var currentCurrency = 'pounds';

function updateCurrency( currency ) {
	
	var poundsElements = YAHOO.util.Dom.getElementsByClassName( 'price_incVAT_pounds' );
	var eurosElements = YAHOO.util.Dom.getElementsByClassName( 'price_incVAT_euros' );
	var dollarsElements = YAHOO.util.Dom.getElementsByClassName( 'price_incVAT_dollars' );
	
	// hide the correct elements
	if( currentCurrency == 'euros' ) {
		// hide all the ex vat euros elements
		if ( typeof eurosElements != 'undefined' && eurosElements.length > 0 ) {
			for( eurosElement in eurosElements ) {
				YAHOO.util.Dom.setStyle( eurosElements[eurosElement], 'display', 'none' );
			}
		}
	} else if( currentCurrency == 'dollars' ) {
		// hide all the ex vat pounds elements
		if ( typeof dollarsElements != 'undefined' && dollarsElements.length > 0 ) {
			for( dollarsElement in dollarsElements ) {
				YAHOO.util.Dom.setStyle( dollarsElements[dollarsElement], 'display', 'none' );
			}
		}
	} else if( currentCurrency == 'pounds' ) {
		// hide all the ex vat pounds elements
		if ( typeof poundsElements != 'undefined' && poundsElements.length > 0 ) {
			for( poundsElement in poundsElements ) {
				YAHOO.util.Dom.setStyle( poundsElements[poundsElement], 'display', 'none' );
			}
		}
	}
	
	currentCurrency = currency;
	// update flag image
	document.getElementById('currentCurrencyIcon').src = '/custom/images/currencyicon' + currentCurrency + '.gif';

	if( currentCurrency == 'euros' ) {
		// hide all the ex vat euros elements
		if ( typeof eurosElements != 'undefined' && eurosElements.length > 0 ) {
			for( eurosElement in eurosElements ) {
				YAHOO.util.Dom.setStyle( eurosElements[eurosElement], 'display', 'inline' );
			}
		}
	} else if( currentCurrency == 'dollars' ) {
		// hide all the ex vat pounds elements
		if ( typeof dollarsElements != 'undefined' && dollarsElements.length > 0 ) {
			for( dollarsElement in dollarsElements ) {
				YAHOO.util.Dom.setStyle( dollarsElements[dollarsElement], 'display', 'inline' );
			}
		}
	} else if( currentCurrency == 'pounds' ) {
		// hide all the ex vat pounds elements
		if ( typeof poundsElements != 'undefined' && poundsElements.length > 0 ) {
			for( poundsElement in poundsElements ) {
				YAHOO.util.Dom.setStyle( poundsElements[poundsElement], 'display', 'inline' );
			}
		}
	}
	
	setCookie( 'currencyViewing', currency );
}

function getCurrentCurrency() {
	var curr = getCookie( 'currencyViewing' );
	if ( !curr ) {
		setCookie( 'currencyViewing', 'pounds' );
		return 'pounds'; // show pounds by default
	} else {
		return curr;
	}
}

function checkCurrencyCookie() {
	var cookieVal = getCookie( 'currencyViewing' );
	currentCurrency = getCurrentCurrency();
	// if val is true or not previously been set...
	if ( cookieVal != 'false' || cookieVal == 'true' || typeof cookieVal == 'undefined' ) {
		updateCurrency( currentCurrency );
	}
}

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 ) );
}

YAHOO.util.Event.addListener(window, "load", checkCurrencyCookie);
YAHOO.util.Event.addListener(window, "load", initQuickSearch);
YAHOO.util.Event.addListener(window, "load", setTall);
//YAHOO.util.Event.addListener(window, "load", changeAllPrices);