var showTipOnLoad = false;
var showLoginOnLoad = false;
var freeDeliveryPrice = 50;

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

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 correctPNG( imageId ) // 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) && (document.body.filters)) 
	{
		var img = document.getElementById( imageId );
		var imgName = img.src.toUpperCase()
		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=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
		img.outerHTML = strNewHTML
	}
}

function correctPNGBackground( divId, 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 div = document.getElementById( divId );
		div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgURL+"', sizingMethod='image')";
		div.style.background = '';
	}
}

function hideElement( id ) {
	document.getElementById( id ).style.display = 'none';
}
function showElement( id ) {
	document.getElementById( id ).style.display = '';
}

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

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 setLastPageCookie() {
	lastPage = getCookie('currentPage');
	setCookie('lastViewedPage',lastPage);
	setCookie('currentPage',document.location);
}
function gotoLastViewed() {
	if(getCookie('lastViewedPage')) {
		document.location = getCookie('lastViewedPage');
	}
}

function addToBasket( modifier, productId, productName, price, image ) {
	var validate = new validateForm();
	validate.checkNumeric( 'CMSCatalogueBasket_product_quantity_' + modifier + '_' + productId, 'Quantity' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}

	var handleSuccess = function(o){
		hideItemAdded();
		// scroll to top of page
		window.scroll(0,0);
		document.getElementById( 'minibasket' ).innerHTML = o.responseText;
		// show the "item added" bubble
		document.getElementById('itemAddedArea').style.display = '';
		// populate the "item added" bubble
		document.getElementById('itemAddedName').innerHTML = unescape( productName );
		document.getElementById('itemAddedQty').innerHTML = document.getElementById( 'CMSCatalogueBasket_product_quantity_' + modifier + '_' + productId ).value;
		document.getElementById('itemAddedPrice').innerHTML = price;
		document.getElementById('itemAddedImage').src = image;
		var amountRequired = freeDeliveryPrice - document.getElementById('basket_to_receive_free_delivery_value').value;
		if( amountRequired < 0 ) {
			document.getElementById('addForFreeDelivery').style.display='none';
			document.getElementById('currentlyForFreeDelivery').style.display='';
		} else {
			document.getElementById('add_to_basket_to_receive_free_delivery').innerHTML = '£' + amountRequired.toFixed(2);
		}
		
		checkVATCookie();
		setTimeout( 'hideItemAdded()', 5000 )
		
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	var formObject = document.getElementById( 'productForm_' + modifier + '_' + productId );
	
	YAHOO.util.Connect.setForm(formObject);
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
}

function hideItemAdded() {
	document.getElementById( 'itemAddedArea' ).style.display = 'none';
}

function initLogin() {
	correctPNGBackground( 'loginPopupBg', '/custom/images/login-bg.png' );
	document.getElementById( 'loginPopup' ).style.display = '';
	loginBox = 
			new YAHOO.widget.Panel("loginPopup",  
											{ width:"379px", 
											  height:"240px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  zIndex:9999,
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	loginBox.render(document.body);
	if( showLoginOnLoad )
		loginBox.show();
}

function hideLogin() {
	if( typeof loginBox != "undefined" )
		loginBox.hide();
}

function showLogin() {
	if( typeof loginBox != "undefined" )
		loginBox.show();
	else
		showLoginOnLoad = 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 checkLoginForm() {
	// ensure we have username and password
	var validate = new validateForm();
	validate.checkText( 'clientLogin_username', 'Email' );	
	validate.checkText( 'clientLogin_password', 'Password' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		// we have errors
		return false;
	}
	
	return true;
}

function doValidateEmailAddress( email ){
	emailAddress = document.getElementById( email ).value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( !filter.test( emailAddress )){
		return false;
	} else {
		return true;
	}
}

var showVat = false;
var currentCurrency = 'pounds';

function updateVAT( vat, currency ) {
	
	var incVATPoundsElements = YAHOO.util.Dom.getElementsByClassName( 'price_incVAT_pounds' );
	var exVATPoundsElements = YAHOO.util.Dom.getElementsByClassName( 'price_exVAT_pounds' );
	var incVATEurosElements = YAHOO.util.Dom.getElementsByClassName( 'price_incVAT_euros' );
	var exVATEurosElements = YAHOO.util.Dom.getElementsByClassName( 'price_exVAT_euros' );
	
	var poundsElements = YAHOO.util.Dom.getElementsByClassName( 'price_pounds' );
	var eurosElements = YAHOO.util.Dom.getElementsByClassName( 'price_euros' );
	
	// hide the correct elements
	if( showVat ) {
		if( currentCurrency == 'euros' ) {
			document.getElementById( 'euro_flag' ).src = '/custom/images/euro_off.gif';
			// hide all the inc vat euros elements
			if ( typeof incVATEurosElements != 'undefined' && incVATEurosElements.length > 0 ) {
				for( incVATEurosElement in incVATEurosElements ) {
					YAHOO.util.Dom.setStyle( incVATEurosElements[incVATEurosElement], 'display', 'none' );
				}
			}
		} else if( currentCurrency == 'pounds' ) {
			document.getElementById( 'gbp_flag' ).src = '/custom/images/gbp_off.gif';
			// show all the inc vat pounds elements
			if ( typeof incVATPoundsElements != 'undefined' && incVATPoundsElements.length > 0 ) {
				for( incVATPoundsElement in incVATPoundsElements ) {
					YAHOO.util.Dom.setStyle( incVATPoundsElements[incVATPoundsElement], 'display', 'none' );
				}
			}
		}
	} else {
		if( currentCurrency == 'euros' ) {
			document.getElementById( 'euro_flag' ).src = '/custom/images/euro_off.gif';
			// hide all the ex vat euros elements
			if ( typeof exVATEurosElements != 'undefined' && exVATEurosElements.length > 0 ) {
				for( exVATEurosElement in exVATEurosElements ) {
					YAHOO.util.Dom.setStyle( exVATEurosElements[exVATEurosElement], 'display', 'none' );
				}
			}
		} else if( currentCurrency == 'pounds' ) {
			document.getElementById( 'gbp_flag' ).src = '/custom/images/gbp_off.gif';
			// hide all the ex vat pounds elements
			if ( typeof exVATPoundsElements != 'undefined' && exVATPoundsElements.length > 0 ) {
				for( exVATPoundElement in exVATPoundsElements ) {
					YAHOO.util.Dom.setStyle( exVATPoundsElements[exVATPoundElement], 'display', 'none' );
				}
			}
		}
	}
	
	// now hide any non vat specific elements
	if( currentCurrency == 'euros' ) {
		// hide all the euro (non vat specific) elements
		if ( typeof eurosElements != 'undefined' && eurosElements.length > 0 ) {
			for( eurosElement in eurosElements ) {
				YAHOO.util.Dom.setStyle( eurosElements[eurosElement], 'display', 'none' );
			}
		}
	} else {
		// hide all the pound (non vat specific) elements
		if ( typeof poundsElements != 'undefined' && poundsElements.length > 0 ) {
			for( poundsElement in poundsElements ) {
				YAHOO.util.Dom.setStyle( poundsElements[poundsElement], 'display', 'none' );
			}
		}
	}
	
	showVat = vat;
	currentCurrency = currency;
	
	// show the correct elements
	if( showVat ) {
		// alter the toggle
		document.getElementById( 'showVATInBasket_yes' ).checked = true;
		
		if( currentCurrency == 'euros' ) {
			document.getElementById( 'euro_flag' ).src = '/custom/images/euro_on.gif';
			// show all the inc vat euros elements
			if ( typeof incVATEurosElements != 'undefined' && incVATEurosElements.length > 0 ) {
				for( incVATEurosElement in incVATEurosElements ) {
					YAHOO.util.Dom.setStyle( incVATEurosElements[incVATEurosElement], 'display', 'inline' );
				}
			}
		} else if( currentCurrency == 'pounds' ) {
			document.getElementById( 'gbp_flag' ).src = '/custom/images/gbp_on.gif';
			// show all the inc vat pounds elements
			if ( typeof incVATPoundsElements != 'undefined' && incVATPoundsElements.length > 0 ) {
				for( incVATPoundsElement in incVATPoundsElements ) {
					YAHOO.util.Dom.setStyle( incVATPoundsElements[incVATPoundsElement], 'display', 'inline' );
				}
			}
		}
	} else {
		// alter the toggle
		document.getElementById( 'showVATInBasket_no' ).checked = true;
		
		if( currentCurrency == 'euros' ) {
			document.getElementById( 'euro_flag' ).src = '/custom/images/euro_on.gif';
			// show all the ex vat euros elements
			if ( typeof exVATEurosElements != 'undefined' && exVATEurosElements.length > 0 ) {
				for( exVATEurosElement in exVATEurosElements ) {
					YAHOO.util.Dom.setStyle( exVATEurosElements[exVATEurosElement], 'display', 'inline' );
				}
			}
		} else if( currentCurrency == 'pounds' ) {
			document.getElementById( 'gbp_flag' ).src = '/custom/images/gbp_on.gif';
			// show all the ex vat pounds elements
			if ( typeof exVATPoundsElements != 'undefined' && exVATPoundsElements.length > 0 ) {
				for( exVATPoundElement in exVATPoundsElements ) {
					YAHOO.util.Dom.setStyle( exVATPoundsElements[exVATPoundElement], 'display', 'inline' );
				}
			}
		}
	}
	
	// now hide any non vat specific elements
	if( currentCurrency == 'euros' ) {
		// show all the euro (non vat specific) elements
		if ( typeof eurosElements != 'undefined' && eurosElements.length > 0 ) {
			for( eurosElement in eurosElements ) {
				YAHOO.util.Dom.setStyle( eurosElements[eurosElement], 'display', 'inline' );
			}
		}
	} else {
		// show all the pound (non vat specific) elements
		if ( typeof poundsElements != 'undefined' && poundsElements.length > 0 ) {
			for( poundsElement in poundsElements ) {
				YAHOO.util.Dom.setStyle( poundsElements[poundsElement], 'display', 'inline' );
			}
		}
	}
	
	setCookie( 'showVATInBasket', showVat );
	setCookie( 'currencyViewing', currency );
}

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

function checkVATCookie() {
	var cookieVal = getCookie( 'showVATInBasket' );
	currentCurrency = getCurrentCurrency();
	// if val is true or not previously been set...
	if ( cookieVal != 'false' || cookieVal == 'true' || typeof cookieVal == 'undefined' ) {
		updateVAT( true, currentCurrency );
	} else {
		updateVAT( showVat, currentCurrency );
	}
}

/* favourites */
function addToFavourites( itemID, quantity, wishlistId ) {
	var sUrl = "/xmlservice.php?service=addToWishList&itemType=1&itemID=" + itemID + "&quantity=" + quantity;
	if ( typeof wishlistId != 'undefined' ) {
		sUrl += "&wishlistId=" + wishlistId
	} else {
		// favourites list
		sUrl += "&wishlistId=null";
	}

	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				document.getElementById( 'wishListAddButton_' + itemID ).style.display = 'none';
				document.getElementById( 'wishListAddSpan_' + itemID ).style.display = 'none';
				document.getElementById( 'wishListRemoveButton_' + itemID ).style.display = '';
				document.getElementById( 'wishListRemoveSpan_' + itemID ).style.display = '';
			} else {
				alert( 'Sorry, an error occured whilst adding this item to your wishlist.' );
			}
		}
	}
	
	var handleFailure = function(o){
		
		alert( 'Sorry, an error occured whilst adding this item to your wishlist.' );
	}
	
	var callback =
	{
	  success: handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

function removeFromFavourites( itemID, wishlistId, 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( 'wishListAddSpan_' + itemID ).style.display = '';
					document.getElementById( 'wishListRemoveButton_' + itemID ).style.display = 'none';
					document.getElementById( 'wishListRemoveSpan_' + 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 = '';
					}
				}
			} else {
				alert( 'Sorry, an error occured whilst removing this item from your wishlist.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst removing this item from your wishlist.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

function initTip() {
	document.getElementById('tipPopup').style.display = '';
	tipBox = 
			new YAHOO.widget.Panel("tipPopup",  
											{ width:"379px", 
											  height:"240px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  zIndex:9999,
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	tipBox.render(document.body);
	if( showTipOnLoad )
		tipBox.show();
}

function hideTip() {
	// Show the Panel
	if( typeof tipBox != "undefined" )
		tipBox.hide();
}

function showTip( description ) {
	// clear the password field
	document.getElementById('tipDetails').innerHTML = description;
	// Show the Panel
	if( typeof tipBox != "undefined" )
		tipBox.show();
	else
		showTipOnLoad = true
}

function changeQuantity(changeinfo) {
	change  = changeinfo.split("_")[0];
	boxid   = changeinfo.split("_")[1];
	quanbox = "CMSCatalogueBasket_basketQuantity_product_" + boxid;
	currentquan = document.getElementById(quanbox).value;
	
	if(change == 'addproduct')
	{
		currentquan = parseInt(currentquan) + 1;
		document.getElementById(quanbox).value = currentquan;
	}
	else
	{
		if(currentquan > 0)
		{
			currentquan = parseInt(currentquan) - 1;
			document.getElementById(quanbox).value = currentquan;
		}
	}
}

YAHOO.util.Event.addListener(window, "load", initTip);
YAHOO.util.Event.addListener(window, "load", checkVATCookie);
YAHOO.util.Event.addListener(window, "load", initLogin);
