/* dynamic menu */
var creditCheckCount = 0;
var isProductPage = false;
var currentMenuItem = '';
var currentPopupId = '';
var sectionMenu = new Array();
var displayWhenReadyParent = null;
var displayWhenReadyChildId = null;
var displayWhenReadyLevel = null;
var showMessagePopupOnLoad = false;
var saveBasketErrors = 0;
var wishlistTypeId = 9;	// hard coded reference to cms_content_wishlist_type table

function setTall() {
	var theMiddle = document.getElementById( 'middle' );
	var theLeft = document.getElementById( 'left' );
	// get the height of middle
	var middleHeight = theMiddle.offsetHeight;
	// and the height of left
	var leftHeight = theLeft.offsetHeight;
	if( middleHeight < leftHeight ) {
		var difference = leftHeight - middleHeight;
		theMiddle.style.height = leftHeight + 'px';
		// expand all productHeightNeedsFixing's
		productBoxes = YAHOO.util.Dom.getElementsByClassName( 'productHeightNeedsFixing' );
		if ( typeof productBoxes != 'undefined' && productBoxes.length > 0 ) {
			for( productBox in productBoxes ) {
				productBoxes[productBox].style.height = ( difference + 160 ) + 'px';
			}
		}
	}
}

function doNavigation( sectionId ){
	// hide the current popup, check if its loaded
	if( document.getElementById( 'subNavigation_' + currentPopupId ) ){
		// it has
		document.getElementById( 'subNavigation_' + currentPopupId ).style.display = 'none';
	}
	
	// ok, if we are showing a current section hide it
	if( currentMenuItem != '' ){
		// try and hide the children
		document.getElementById( 'children_' + currentMenuItem ).style.display = 'none';
		// set the old area to the off color
		document.getElementById('main_nav_'+ currentMenuItem ).style.backgroundImage = '';
	}
	
	// check if it's the current navigation being altered
	if( sectionId != currentMenuItem ){
		// show the children
		document.getElementById( 'children_' + sectionId ).style.display = '';
		// set the new area to selected background
		document.getElementById('main_nav_'+ sectionId ).style.backgroundImage = "url('/custom/images/drop-down-on.gif')";
		// set the current item
		currentMenuItem = sectionId;
	} else {
		// it is, reset the current item so it can be turned back on if the user so requires
		currentMenuItem = '';
	}
}

var menusLoaded = new Array()

function loadMenu1( sectionId ) {
	if( typeof( menusLoaded[sectionId] ) == 'undefined' ) {
		menusLoaded[sectionId] = true;
		fetchChildMenus( 'parent[]='+sectionId, 1 );
	}
}

function loadMenu2( sectionIds ) {
	if( typeof( menusLoaded[sectionIds] ) == 'undefined' ) {
		menusLoaded[sectionIds] = true;
		fetchChildMenus( sectionIds, 2 );
	}
}

function addMenu( parentId, level ) {
	
	//check there is data and we havent already added the html
	if( typeof sectionMenu[parentId] == 'undefined' || document.getElementById('subNavigation_'+parentId) != null )
		return;
	var menu = '';
	var sectionIds = '';
	
	for( sectionId in sectionMenu[parentId] ) {
		menu += '<a href="'+sectionMenu[parentId][sectionId]['path']+'" class="productDropDownItem" title="'+sectionMenu[parentId][sectionId]['title']+'" id="navigation_'+sectionId+'">';
		menu += '<span class="menuItemHyphen">-&nbsp;&nbsp;&nbsp;</span>';
		menu += '<span class="menuItemStuff">' +sectionMenu[parentId][sectionId]['title']+ '</span>';
		menu += '</a>';
		sectionIds += (sectionIds?'&':'')+'parent[]='+sectionId;
	}
	
	var div = document.createElement('div');
	div.className = 'productDropDownContainer';
	div.id = 'subNavigation_'+parentId;
	div.setAttribute( 'id', 'subNavigation_'+parentId );
	div.innerHTML = menu;
	
	eval( 'var func=function(){ mouseOverChildLevel('+level+'); }')
	YAHOO.util.Event.addListener(div, "mouseover", func ); 
	eval( 'var func=function(){ mouseOutLevel('+level+'); }')
	YAHOO.util.Event.addListener(div, "mouseout", func );
	// attach it to the body (doesn't matter where, its absolute positioned)
	document.body.appendChild( div );
	
	// attach the mouseout event to the parent div also
	var parentDiv = document.getElementById( 'navigation_' + parentId );
	eval( 'var func=function(){ mouseOutLevel('+level+'); }')
	YAHOO.util.Event.addListener(parentDiv, "mouseout", func );
	
	//finished with the data so trash it
	delete sectionMenu[parentId];
	
	if( displayWhenReadyChildId == div.id ) {
		//we want to display this one !
		mouseOver(displayWhenReadyParent,document.getElementById(displayWhenReadyChildId));
	}
}

function menuOut() {
	displayWhenReadyParent = null;
	displayWhenReadyChildId = null;
	displayWhenReadyLevel = null;
}

function menuShow( link, parentId, level ) {
	// set the current popup
	var childObj = document.getElementById( 'subNavigation_'+parentId );
	if( typeof childObj != "undefined" && childObj != null) {
		mouseOver(link,document.getElementById('subNavigation_'+parentId));
		displayWhenReadyParent = null;
		displayWhenReadyChildId = null;
		displayWhenReadyLevel = null;
	} else {
		//not loaded yet ? display it when ready
		displayWhenReadyParent = link;
		displayWhenReadyChildId = 'subNavigation_'+parentId;
		displayWhenReadyLevel = 1;
	}
	return false;
}

function fetchChildMenus( parents, menuLevel ) {
	var callback =
	{
	  success:function(result){
	/* Please see the Success Case section for more
	 * details on the response object's properties.
	 * o.tId
	 * o.status
	 * o.statusText
	 * o.getResponseHeader[ ]
	 * o.getAllResponseHeaders
	 * o.responseText
	 * o.responseXML
	 * o.argument
	 */
		if(result.responseText !== undefined){
			eval( 'var responce = (' + result.responseText + ')' );
			if( responce.ResultSet.Result.length == 1 ) {
				for( var parentId in responce.ResultSet.Result[0] ) {
					switch( result.argument.level ) {
						case 1:
							collectionDiv = document.getElementById( 'children_'+parentId );
							
							if( typeof(collectionDiv) != 'undefined' ) {
								collectionDiv.innerHTML = '';
								var children = '';
								for( var childId in responce.ResultSet.Result[0][parentId] ) {
									children += (children?'&':'')+'parent[]='+childId;
								}
								for( var childId in responce.ResultSet.Result[0][parentId] ) {
									var menu = '';
									menu += '<a href="'+responce.ResultSet.Result[0][parentId][childId]['path']+'">';
									menu += '<span class="menuItemHyphen">-&nbsp;&nbsp;&nbsp;</span>';
									menu += '<span class="menuItemStuff">' +responce.ResultSet.Result[0][parentId][childId]['title']+ '</span>';
									menu += '</a>';
									
									var div = document.createElement('div');
									
									div.appendChild( document.createTextNode('test') );
									div.id = 'subNavigation_'+parentId;
									div.setAttribute( 'id', 'navigation_'+childId );
									div.innerHTML = menu;
									
									eval( 'var func=function(){ loadMenu2( "'+children+'" ); menuShow( this, '+childId+', '+menuLevel+' ) }')
									YAHOO.util.Event.addListener(div, "mouseover", func );
									eval( 'var func=function(){ mouseOutLevel('+result.argument.level+'); menuOut(); }')
									YAHOO.util.Event.addListener(div, "mouseout", func );

									collectionDiv.appendChild( div );

								}
							}
							break;
						case 2:
							sectionMenu[parentId] = responce.ResultSet.Result[0][parentId]
							addMenu( parentId, 2 );
							break;
					}
				}
			}
		}
		if( menuLevel && isProductPage ) {
			setTall();
		}
	},
	  failure:function(o){
	// Access the response object's properties in the
	// same manner as listed in responseSuccess( ).
	// Please see the Failure Case section and
	// Communication Error sub-section for more details on the
	// response object's properties.
	},
	  argument:{level:menuLevel}
	};
	
	YAHOO.util.Connect.asyncRequest('GET', '/xmlservice.php?service=fetchMenus&'+parents, callback );
	
};


//YAHOO.util.Event.addListener(window, "load", fetchLevel2Menus);
/* end dynamic menu */

var submitLoginForm = false;
var showLoginOnLoad = false;

function doSearch( ) {
	var searchModifier = '';
	// check if we have a modifier
	if( document.getElementById( 'searchModifier' ).selectedIndex == 1 ) {
		if( document.getElementById( 'searchText' ).value != ' - Product Search -' && document.getElementById( 'searchText' ).value != '' ){
			document.location = '/products/%20Manufacturer%20Code::' + encodeURIComponent( document.getElementById( 'searchText' ).value );
		} else {
			alert( "Please enter search text" );
		}
	} else {
		if( document.getElementById( 'searchText' ).value != ' - Product Search -' && document.getElementById( 'searchText' ).value != '' ){
			document.location = '/products/%20search::' + encodeURIComponent( document.getElementById( 'searchText' ).value );
		} else {
			alert( "Please enter search text" );
		}
	}
	return false;
}

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 correctPNGBackground( divId, imgURL, method ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	if( !method ) {
		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 initLogin() {
	correctPNGBackground( 'loginPopupBg', '/custom/images/login-panel.png' );
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('loginPopup').style.display = '';
	loginBox = 
			new YAHOO.widget.Panel("loginPopup",  
											{ width:"251px", 
											  height:"147px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.2} 
											} 
										);

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

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

function showLogin() {
	// clear the username and password
	document.getElementById( 'clientLogin_username' ).value = ' - Enter your email address...';
	document.getElementById( 'clientLogin_password' ).style.display = 'none';
	document.getElementById( 'clientLogin_password_text' ).style.display = '';
	document.getElementById( 'clientLogin_password_text' ).value = ' - Enter your password...';
	// Show the Panel
	if( typeof loginBox != "undefined" )
		loginBox.show();
	else
		showLoginOnLoad = true
}

function onPopupSubmit() {
	submitLoginForm = true;
	// ensure we have username and password
	var validate = new validateForm();
	if( document.getElementById('clientLogin_username').value == ' - Enter your email address...'){
		validate.addCustomError( 'Username' );
	} else {
		validate.checkText( 'clientLogin_username', 'Username' );	
	}
	validate.checkText( 'clientLogin_password', 'Password' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		// we have errors
		submitLoginForm = false;
	}
	
	if( submitLoginForm ) {
		// ok, submitting, fire a request to check if the username requires secondary authentication
		usernameRequiresAuthentication();
	} else {
		// do nothing, password was invalid, hopefully we alerted some errors
	}
	
	// always return false
	return false;
}

function usernameRequiresAuthentication() {
	
	// fire an ajax request to see if this account needs secondary authentication
	var sUrl = "/xmlservice.php?service=userLookup&username=" + document.getElementById( 'clientLogin_username' ).value;
	// KEV NOTE...
	// if this request fails, we'll simply try and log them in normally, so return false in cases or error...
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' && response.ResultSet.Result[0]['username_requires_authentication'] == '1' ) {
				// hide the login
				hideLogin();
				// and show the authenticate panel
				showAuthenticate();
			} else {
				// no authentication required, proceed with login
				document.getElementById( 'loginForm' ).submit();
			}
		}
	}
	
	var handleFailure = function(o){
	}
	
	var callback =
	{
	  success: handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
	
}

/* authenticate panel */
function initAuthenticate() {
	correctPNGBackground( 'authenticatePopupBg', '/custom/images/authentication-panel.png' );
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('authenticatePopup').style.display = '';
	authenticateBox = 
			new YAHOO.widget.Panel("authenticatePopup",  
											{ width:"251px", 
											  height:"147px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.2} 
											} 
										);

	authenticateBox.render(document.body);
}

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

function showAuthenticate() {
	// clear down the password
	document.getElementById( 'clientLogin_trade_password' ).style.display = 'none';
	document.getElementById( 'clientLogin_trade_password_text' ).style.display = '';
	document.getElementById( 'clientLogin_trade_password_text' ).value = ' - Enter your trade password...';
	// Show the Panel
	if( typeof authenticateBox != "undefined" ) {
		authenticateBox.show();
	}
}

function submitTradeLogin() {
	var validate = new validateForm();
	validate.checkText( 'clientLogin_trade_password', 'Trade Password' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
	} else {
		// assign the trade password to the initial login panel
		document.getElementById( 'clientLogin_second_password' ).value = document.getElementById( 'clientLogin_trade_password' ).value;
		// submit the form
		document.getElementById( 'loginForm' ).submit();
	}
	return false;
}

/* mmm, cookies */
function checkVATCookie() {
	var cookieVal = getCookie( 'showVATInBasket' );
	// if val is true or not previously been set...
	if ( cookieVal != 'false' || cookieVal == 'true' || typeof cookieVal == 'undefined' ) {
		updateVAT( );
	} else {
		updateVAT( true );
	}
}
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 ) );
}
/* vat toggle */
function updateVAT( incVAT ) {
	
	var incVATElements = YAHOO.util.Dom.getElementsByClassName( 'itemIncVAT' );  
	var exVATElements = YAHOO.util.Dom.getElementsByClassName( 'itemExVAT' );  
	
	if( incVAT ) {
		// alter the toggle
		document.getElementById( 'miniBasket_showVATInBasket').checked = true;
		if( document.getElementById( 'miniBasket_showVATInProduct') ) {
			document.getElementById( 'miniBasket_showVATInProduct').checked = true;
		}
		// update all the elements
		if ( typeof incVATElements != 'undefined' && incVATElements.length > 0 ) {
			for( incVATElement in incVATElements ) {
				incVATElements[incVATElement].style.display = '';
			}
		}
		if ( typeof exVATElements != 'undefined' && exVATElements.length > 0 ) {
			for( exVATElement in exVATElements ) {
				exVATElements[exVATElement].style.display = 'none';
			}
		}
	} else {
		// alter the toggle
		document.getElementById( 'miniBasket_showVATInBasket').checked = false;
		if( document.getElementById( 'miniBasket_showVATInProduct') ) {
			document.getElementById( 'miniBasket_showVATInProduct').checked = false;
		}
		// update all the elements
		if ( typeof incVATElements != 'undefined' && incVATElements.length > 0 ) {
			for( incVATElement in incVATElements ) {
				incVATElements[incVATElement].style.display = 'none';
			}
		}
		if ( typeof exVATElements != 'undefined' && exVATElements.length > 0 ) {
			for( exVATElement in exVATElements ) {
				exVATElements[exVATElement].style.display = '';
			}
		}
	}
	setCookie( 'showVATInBasket', incVAT );
}

/* 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( 'wishListRemoveButton_' + itemID ).style.display = '';
			} else {
				alert( 'Sorry, an error occured whilst adding this item to your favourites list.' );
			}
		}
	}
	
	var handleFailure = function(o){
		
		alert( 'Sorry, an error occured whilst adding this item to your favourites list.' );
	}
	
	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( '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 = '';
					}
				}
			} else {
				alert( 'Sorry, an error occured whilst removing this item from your favourites list.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst removing this item from your favourites list.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

/* add to basket */
function dump(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;
		
		//The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j<level+1;j++) level_padding += "    ";
		
		if(typeof(arr) == 'object') { //Array/Hashes/Objects
		 for(var item in arr) {
		  var value = arr[item];
		 
		  if(typeof(value) == 'object') { //If it is an array,
		   dumped_text += level_padding + "'" + item + "' ...\n";
		   dumped_text += dump(value,level+1);
		  } else {
		   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
		  }
		 }
		} else { //Stings/Chars/Numbers etc.
		 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
		} 
		
function addToBasket( productId ) {
	var handleSuccess = function(o){
		// fiddle with the script
		addedItemsText = o.responseText.substr( 0, o.responseText.indexOf( '###END_JSON###' ));
		eval( 'var addedItems = ' + addedItemsText );
		//alert( dump( addedItems ));
		image = '/custom/images/no-image-small.jpg';
		priceIncVAT = 0;
		price = 0;
		name = '';
		if( typeof addedItems == 'object') {
			for( i in addedItems ) {
				// attempt to overwrite the price
				priceIncVAT = addedItems[i]['priceIncVAT'];
				price = addedItems[i]['price'];
				name = addedItems[i]['name'];
				if( typeof addedItems[i]['image'] != 'undefined' && addedItems[i]['image'] != '' && addedItems[i]['image'] != null ) {
					image = addedItems[i]['image'];
				}
			}
		}
		// get the remaining html and add it to the template
		document.getElementById( 'topExtrasBasket' ).innerHTML = o.responseText.substr( o.responseText.indexOf( '###END_JSON###' ) + 14 );
		// show the "item added" bubble
		document.getElementById('itemAdded').style.display = '';
		// populate the "item added" bubble
		document.getElementById('itemAddedQty').innerHTML = document.getElementById( 'qty_' + productId ).value + ' ';
		document.getElementById('itemAddedName').innerHTML = name;
		document.getElementById('itemAddedPriceIncVAT').innerHTML = '&pound;' + priceIncVAT;
		document.getElementById('itemAddedPrice').innerHTML = '&pound;' + price;
		document.getElementById('itemAddedImage').src = image;
		checkVATCookie();
		setTimeout( 'hideItemAdded()', 5000 )
		
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	var formObject = document.getElementById( 'productForm_' + productId );
	YAHOO.util.Connect.setForm(formObject);
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
	// scroll to top of page
	window.scroll(0,0);
}

function round(number,X) {
	// rounds number to X decimal places, defaults to 2
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

function addMultipleToBasket( totalItems ) {
	var handleSuccess = function(o){
		addedItemsText = o.responseText.substr( 0, o.responseText.indexOf( '###END_JSON###' ));
		eval( 'var addedItems = ' + addedItemsText );
		totalIncVAT = 0;
		total = 0;
		// add the total cosst of the items together
		if( typeof addedItems == 'object') {
			for( i in addedItems ) {
				// attempt to overwrite the price
				totalIncVAT += ( addedItems[i]['priceIncVAT'] * addedItems[i]['quantity'] );
				total += ( addedItems[i]['price'] * addedItems[i]['quantity'] );
			}
		}
		// get the remaining html and add it to the template
		document.getElementById( 'topExtrasBasket' ).innerHTML = o.responseText.substr( o.responseText.indexOf( '###END_JSON###' ) + 14 );
		// show the "item added" bubble
		document.getElementById('itemAdded').style.display = '';
		// populate the "item added" bubble
		document.getElementById('itemAddedQty').innerHTML = totalItems + ' ';
		document.getElementById('itemAddedName').innerHTML = 'Multiple Items';
		document.getElementById('itemAddedPriceIncVAT').innerHTML = '&pound;' + round( totalIncVAT );
		document.getElementById('itemAddedPrice').innerHTML = '&pound;' + round( total );
		document.getElementById('itemAddedImage').src = '/custom/images/no-image-small.jpg';
		checkVATCookie();
		setTimeout( 'hideItemAdded()', 5000 )
		
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	var formObject = document.getElementById( 'multipleAddForm' );
	YAHOO.util.Connect.setForm(formObject);
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
	// scroll to top of page
	window.scroll(0,0);
}

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

/* save basket */

function submitSaveBasketForm() {
	// don't do anything when pressing the enter key on the save basket form
	return false;
}

function showBasketNamePopup() {
	if ( userAuthenticated ) {
		var savedWishlistListId = getCookie( 'myBasketListId' );
		if ( savedWishlistListId != '' && savedWishlistListId ) {
			// we have previously saved this basket so no need to get a new name
			addProductsToList( savedWishlistListId );
		} else {
			// no previously saved wishlist so prompt user to enter a name for it
			// get default name (current date)
			var dateAdded = new Date();
			var dateAddedString = 'My Basket from ' + dateAdded.getDate() + '/' + ( dateAdded.getMonth() + 1 ) + '/' + dateAdded.getFullYear();
			// add it to the window
			document.getElementById( 'cmsCatalogueWishList_wishlist_name' ).value = dateAddedString;
			// show the actions bit, cant submit this time
			document.getElementById( 'innerMessageSubmit' ).style.display = '';
			document.getElementById( 'innerMessageOk' ).style.display = 'none';
			showMessagePopup( '<div class="innerMessagePopup">Please name this basket so you can find it later on the \'Saved Baskets\' page of your account page...</div>', '/custom/images/message-title-save-basket.gif', false );
		}
	} else {
		// hide the actions bit, cant submit this time
		document.getElementById( 'innerMessageSubmit' ).style.display = 'none';
		document.getElementById( 'innerMessageOk' ).style.display = '';
		var href = ( window.opener ) ? 'javascript:window.opener.location=\'/register\';window.close();' : 'register';
		showMessagePopup( '<div class="innerMessagePopup">You must be logged in to save your basket. <a href="' + href + '">Click here to sign up</a>, if you are already registered, <a href="javascript:hideMessagePopup();showLogin();">click here</a> to log in.</div>', '/custom/images/message-title-not-logged.gif', true );
	}
}

function initMessagePopup() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('messagePopup').style.display = '';
	correctPNGBackground('messagePopupBackground', '/custom/images/message-popup.png' );
	messageBox = 
			new YAHOO.widget.Panel("messagePopup",  
											{ width:"251px", 
											  height:"138px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.2} 
											} 
										);

	messageBox.render(document.body);
	if( showMessagePopupOnLoad )
		messageBox.show();
}

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

function showMessagePopup( message, titleImageSrc ) {
	document.getElementById( 'messagePopupMessage' ).innerHTML = message;
	document.getElementById( 'topMessageTitle' ).src = titleImageSrc;
	if( typeof messageBox != "undefined" ) {
		messageBox.show();
	} else {
		showMessagePopupOnLoad = true
	}
}
function addProductsToList( wishlistListId ) {
	// loop round every item in our basket and add it to the wishlist
	for ( var product in saveProductIDs ) {
		productId = saveProductIDs[product];
		qty = document.getElementById( 'save_qty_' + productId ).innerHTML;
		var sUrl = '/xmlservice.php?service=addToWishList&itemType=1&overwrite_quantity=1&wishlistId=' + wishlistListId + '&itemID=' + productId + '&quantity=' + qty;
		var handleSuccess = function( result ){
			if ( typeof result !== 'undefined' ) {
				eval( 'var response = (' + result.responseText + ')' );
				if ( response.ResultSet.Result[0]['result'] == 'success' ) {
					// item successfully added to wishlist
				} else {
					// error
					saveBasketErrors++;
				}
			}
		}
		
		var handleFailure = function(o){
			alert('An error occured while saving your basket, please try again.');
		}
		
		var callback =
		{
		  success: handleSuccess,
		  failure: handleFailure
		};
		
		var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	}
	if ( saveBasketErrors == 0 ) {
		// hide the action areas
		document.getElementById( 'innerMessageSubmit' ).style.display = 'none';
		document.getElementById( 'innerMessageOk' ).style.display = 'none';
		// show the enlarge 
		showMessagePopup( '<div class="outerMessagePopup">Please note that if you add any further products to your basket you will need to click the "Save for later" button again to store your changes. To view your saved baskets, please click the "Go to My Account" link in the top right of the site.</div>', '/custom/images/message-title-basket-saved.gif' );
	} else {
		alert( 'An error occured whilst saving your basket' );
	}
}

function getMonthName( monthNumber ) {
	var months = new Array( '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' );
	return months[ monthNumber ];
}

function addMyBasketList() {
	if ( document.getElementById('cmsCatalogueWishList_wishlist_name').value == '' ) {
		alert( 'Please enter a name for this saved basket so you can refer to it later.' );
	} else {
		
		var dateAdded = new Date();
		var dateAddedString = dateAdded.getDate() + ' ' + getMonthName( dateAdded.getMonth() + 1 ) + ' ' + dateAdded.getFullYear();

		var sUrl = '/xmlservice.php?service=saveWishlistList&wishlist_type_id=' + wishlistTypeId + '&name=' + document.getElementById('cmsCatalogueWishList_wishlist_name').value + '&description=' + dateAddedString;
	
		var handleSuccess = function( result ){
			if ( typeof ( result ) !== 'undefined' ) {
				eval( 'var response = (' + result.responseText + ')' );
				if ( !isNaN( response.ResultSet.Result[0]['result'] ) ) {
					// a wishlist list id has been returned
					// save wishlist id in a cookie so we don't have to enter a name every time
					setCookie( 'myBasketListId', response.ResultSet.Result[0]['result'] );
					addProductsToList( response.ResultSet.Result[0]['result'] );
				} else {
					handleFailure();
				}
			} else {
				handleFailure();
			}
		}
		
		var handleFailure = function(o){
			alert('An error occured while saving your basket, please try again.');
		}
		
		var callback =
		{
		  success: handleSuccess,
		  failure: handleFailure
		};
		
		var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	}
}

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

var creditAvailable = false;
function checkAvailableCredit() {
	var sUrl = "/xmlservice.php?service=getIntactAvailableCredit";
	
	var handleSuccess = function(o) {
		if(o.responseText !== undefined){
			var maxCompanyOrderValueIncVAT = parseFloat( o.responseText );
			var maxCompanyOrderValue = maxCompanyOrderValueIncVAT / 1.15; // 15% VAT
			
			setCookie( 'maxCompanyOrderValueIncVAT', maxCompanyOrderValueIncVAT );
			setCookie( 'maxCompanyOrderValue', maxCompanyOrderValue );
			
			if( maxCompanyOrderValue < customerMaxOrderValue ) {
				var maxOrderValue = maxCompanyOrderValue;
				var maxOrderValueIncVAT = maxCompanyOrderValueIncVAT;
			} else {
				var maxOrderValue = customerMaxOrderValue;
				var maxOrderValueIncVAT = customerMaxOrderValueIncVAT;
			}
			
			var availableBalance = maxOrderValue - basketTotal;
			var availableBalanceIncVAT = maxOrderValueIncVAT - basketTotalIncVAT;

			document.getElementById( 'maxOrderValue' ).innerHTML = '&pound;'+numberFormat(availableBalance.toFixed(2));
			document.getElementById( 'maxOrderValueIncVAT' ).innerHTML = '&pound;'+numberFormat(availableBalanceIncVAT.toFixed(2));
			
			if( availableBalance < 0 ) {
				var balanceWarning = getCookie( 'balanceWarning' );
				if( balanceWarning != 1 ) {
					setTimeout( function() { alert( "Warning: Your basket value has exceeded your account limit.\nYou will need to review your basket before checking out to correct this." ) }, 100 );
					setCookie( 'balanceWarning', 1 );
				}
				document.getElementById( 'checkingCredit' ).innerHTML = 'Insufficient credit available.<br/> Please update your basket.';
			} else {
				setCookie( 'balanceWarning', 0 );
				document.getElementById( 'checkoutButton' ).style.display = '';
				document.getElementById( 'checkingCredit' ).style.display = 'none';
			}
			
		} else {
			alert( 'There was an error while checking your credit balance' );
		}
	}
	
	var handleFailure = function(o){
		var msg = 'There was an error while checking your credit balance';
		if ( o.status == -1 ) {
			// transaction aborted, try again
			creditCheckCount++;
			if ( creditCheckCount <= 5 ) {
				checkAvailableCredit();
			} else {
				creditCheckCount = 0;
				document.getElementById( 'checkingCredit' ).innerHTML = msg + '. <span onclick="document.getElementById(\'checkingCredit\').innerHTML=\'Checking credit status...\';checkAvailableCredit();" class="underline">Click here to retry</a>';
			}
		} else {
			alert( msg );
		}
	}
	var callback = {
	  success:handleSuccess,
	  failure: handleFailure,
	  timeout : 4000
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
}

function updateBreak( productId, breakId ){
	// get the current value
	currentValue = eval( 'currentProductPriceBreak_' + productId );
	// hide both
	document.getElementById( 'productPricePerIncVAT_' + productId + '_' + currentValue ).style.display = 'none';
	document.getElementById( 'productPricePer_' + productId + '_' + currentValue ).style.display = 'none';
	// and show the new ones
	document.getElementById( 'productPricePerIncVAT_' + productId + '_' + breakId ).style.display = '';
	document.getElementById( 'productPricePer_' + productId + '_' + breakId ).style.display = '';
	// reassign the newly selected value
	eval( 'currentProductPriceBreak_' + productId + ' = ' + breakId + ';' );
}

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