var submitLoginForm = false;
var showLoginOnLoad = false;
var showWishListOnLoad = false;
var showPurchaseOnLoad = false;
var showWishListCommentOnLoad = false;
var showSearchOnLoad = false;
var showImageURLPopupOnLoad = false;
var showListEditPopupOnLoad = false;
var showRecommendOnLoad = false;
var showUserSearchOnLoad = false;
var showMoreInfo1OnLoad = false;
var showMoreInfo2OnLoad = false;
var showMoreInfo3OnLoad = false;
var showWishlistInfoOnLoad = false;
var showWishlistIntroOnLoad = false;
var showBookmarkOnLoad = false;
var tempItemID = '';
var tempUserID = '';
var tempWishlistId = '';
var tempWishlistListId = '';
var addressArray = new Array();
var addressArrayLength = 0;
var maximumPurchase = 0;

function initLogin() {
	// 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:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

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

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

function showLogin() {
	// clear the password field
	//document.getElementById('clientLogin_password').value = '';
	// Show the Panel
	if( typeof loginBox != "undefined" )
		loginBox.show();
	else
		showLoginOnLoad = true
}

function initProductSearch() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('searchPopup').style.display = '';
	searchBox = 
			new YAHOO.widget.Panel("searchPopup",  
											{ width:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	searchBox.render(document.body);
	if( showSearchOnLoad )
		searchBox.show();
}

function hideProductSearch() {
	if( typeof searchBox != "undefined" )
		searchBox.hide();
}

function showProductSearch() {
	if( typeof searchBox != "undefined" )
		searchBox.show();
	else
		showSearchOnLoad = true
}

function onPopupSubmit() {
	// if we are submitting to form
	if( submitLoginForm ){
		// ensure we have username and password
		var validate = new validateForm();
		if( document.getElementById('clientLogin_username').value == ' - type here -'){
			validate.addCustomError( 'Email' );
		} else {
			validate.checkText( 'clientLogin_username', 'Email' );	
		}
		validate.checkText( 'clientLogin_password', 'Password' );
		if( validate.numberOfErrors() > 0 ) {
			validate.displayErrors();
			// we have errors
			submitLoginForm = false;
		}
	}
	
	return submitLoginForm;
}

function initWishList() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('wishListPopup').style.display = '';
	wishListBox = 
			new YAHOO.widget.Panel("wishListPopup",  
											{ width:"316px", 
											  height:"207px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	wishListBox.render(document.body);
	if( showWishListOnLoad )
		wishListBox.show();
}

function hideWishList() {
	// Show the Panel
	if( typeof wishListBox != "undefined" )
		wishListBox.hide();
	// set it bask to nothing
	document.getElementById('wishlist_id_chosen').selectedIndex = 0;
	// and the quantity back to 1 (one)
	document.getElementById('quantity_chosen').value = 1;
}

function showWishListPanel( itemID, userID ) {
	tempItemID = itemID;
	tempUserID = userID;
	// Show the Panel
	if( typeof wishListBox != "undefined" )
		wishListBox.show();
	else
		showWishListOnLoad = true
}

function addToWishList( ) {

	// validate we have a quantity
	var validate = new validateForm();
	// which list
	validate.checkSelect( 'wishlist_id_chosen', '', 'Which List?' );
	// quantity
	validate.checkNumeric( 'quantity_chosen', 'Quantity' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	var wishlistId = document.getElementById('wishlist_id_chosen').value;
	var quantityChosen = document.getElementById('quantity_chosen').value;
	var sUrl = "/xmlservice.php?service=addToWishList&itemType=1&itemID=" + tempItemID + "&wishlistId=" + wishlistId + "&quantity=" + quantityChosen;
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				// set the wishlistid to a cookie so it can be reused
				document.cookie = 'previousWishlistId=' + wishlistId + ';path=/;';
				document.location = '/wishlist/' + tempUserID + '/' + wishlistId;
			} else {
				hideWishList();
				alert( 'Sorry, an error occured whilst adding this item to your list.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst adding this item to your list.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

function removeFromWishList( itemID, userID ) {
	if( !confirm('Are you sure you want to remove this from your list?') ) {
		return;
	}
	
	var sUrl = "/xmlservice.php?service=removeFromWishList&itemType=1&itemID=" + itemID + "&wishlistId=" + currentWishListId;
	
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				document.location = '/wishlist/' + userID + '/' + currentWishListId;
				// update the total of products in the side nav
//				var currentTotal = parseInt( document.getElementById( 'wishlist_total_' + currentWishListId ).innerHTML );
//				document.getElementById( 'wishlist_total_' + currentWishListId ).innerHTML = currentTotal - 1;
//				// hide the product in the list
//				document.getElementById( 'wishListItem_' + itemID ).style.display = 'none';
//				// and the one in the gallery
//				numberOfItems--;	// global var on the page
//				if ( numberOfItems <= 0 ) {
//					document.getElementById( 'noItemsMessage' ).style.display = '';
//					document.getElementById( 'savedItems' ).style.display = 'none';
//				}
//				alert( 'Item was successfully removed from this list' );
			} else {
				alert( 'Sorry, an error occured whilst removing this item from your list.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst removing this item from your list.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

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 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) && (version < 7) && (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='scale')";
		div.style.background = '';
	}    
}


function doUserSearch( ) {
	if( document.getElementById('CMSAuthUserSearch_userSearch').value == '' || document.getElementById('CMSAuthUserSearch_userSearch').value == ' type member name here' ) {
		alert( 'Please enter a search term' );
		return false;
	}
	// ok, submit the form
	document.location = basePath + '%20search::' + document.getElementById('CMSAuthUserSearch_userSearch').value;
	return false;
}
function doUserSearchPopup( ) {
	if( document.getElementById('CMSAuthUserSearch_userSearchPopup').value == '' ) {
		alert( 'Please enter a search term' );
		return false;
	}
	// ok, submit the form
	document.location = basePath + '%20search::' + document.getElementById('CMSAuthUserSearch_userSearchPopup').value;
	return false;
}
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 ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

/* addresses */
		
function deleteDeliveryAddress( id ) {
	if( !confirm('Are you sure you want to delete this friend?') ) {
		return;
	}
	
	var sUrl = "/xmlservice.php?service=deleteDeliveryAddress";
	sUrl += '&id='+document.getElementById('address_' + id + '_id').value;
	
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				// remove the tr object
				var table = document.getElementById( 'addressBook' );
				table.removeChild( document.getElementById('address_' + id ));
				// set the value to empty string
				addressArray[id] = '';
				// decremement the length of the array, we're removing an item
//				addressArrayLength--;
				var count = 0;
				for ( var k in addressArray ) {
					if( addressArray[k] !== '' ) {
						count++;
						document.getElementById( 'address_number_' + k ).innerHTML = count + '.';
					}
				}
			} else {
				alert( 'Sorry, an error occured whilst removing this friend.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst adding this friend.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
}
		
function newDeliveryAddress( ) {
	
	var count = 0;
	for ( var n in addressArray ) {
		if( addressArray[n] !== '' ) {
			count++;
		}
	}
	// and set a var for this function
	var currentAddress = addressArrayLength;
	
	var table = document.getElementById( 'addressBook' );
	var newTR = document.createElement( 'tr' );
	newTR.setAttribute( 'id', 'address_' + currentAddress );
	// no. td
	var newTD = document.createElement( 'td' );
	newTD.setAttribute( 'id', 'address_number_' + currentAddress );
	// zero based
	newTD.innerHTML = ( count + 1 ) + '.';
	newTR.appendChild( newTD );
	// name td
	var newTD = document.createElement( 'td' );
	var newInput = document.createElement( 'input' );
	newInput.type = "text";
	newInput.className = 'addressBookName';
	newInput.setAttribute( 'name', 'address[' + currentAddress + '][name]' );
	newInput.setAttribute( 'id', 'address_' + currentAddress + '_name' );
	// on keypress, show the save option
	eval( 'var func=function(){ showSaveChanges(' + currentAddress + '); }')
	YAHOO.util.Event.addListener('address_' + currentAddress + '_name', "keyup", func );
	newTD.appendChild( newInput );
	// hidden input with id
	var newInput = document.createElement( 'input' );
	newInput.type = "hidden";
	newInput.setAttribute( 'name', 'address[' + currentAddress + '][id]' );
	newInput.setAttribute( 'id', 'address_' + currentAddress + '_id' );
	newTD.appendChild( newInput );
	newTR.appendChild( newTD );
	// email td
	var newTD = document.createElement( 'td' );
	var newInput = document.createElement( 'input' );
	newInput.className = 'addressBookEmail';
	newInput.type = "text";
	newInput.setAttribute( 'name', 'address[' + currentAddress + '][email]' );
	newInput.setAttribute( 'id', 'address_' + currentAddress + '_email' );
	// on keypress, show the save option
	eval( 'var func=function(){ showSaveChanges(' + currentAddress + '); }')
	YAHOO.util.Event.addListener('address_' + currentAddress + '_email', "keyup", func );
	newTD.appendChild( newInput );
	newTR.appendChild( newTD );
	
	// delete td
	var newTD = document.createElement( 'td' );
	var span = document.createElement( 'span' );
	span.setAttribute( 'id', 'address_' + currentAddress + '_delete' );
	span.style.display = 'none';
	span.innerHTML = '[Delete]';
	newTD.appendChild( span );
	newTR.appendChild( newTD );
	// add the lot to the table body
	table.appendChild( newTR );
	
	// on click, show the delete option
	eval( 'var func=function(){ deleteDeliveryAddress(' + currentAddress + '); }')
	YAHOO.util.Event.addListener('address_' + currentAddress + '_delete', "click", func );
	// on click, show the save option
	eval( 'var func=function(){ updateDeliveryAddress(' + currentAddress + '); }')
	YAHOO.util.Event.addListener('address_' + currentAddress + '_save', "click", func );
	
	// add an element to the array
	addressArray[currentAddress] = currentAddress;
	
	// incremement the length of the array, we're adding a new item
	addressArrayLength++;
	
	// increment address count
	currentAddress++;
}

function showSaveChanges( ) {
	// show the save changes button
	document.getElementById('address_save')	.style.display = '';
}

function updateDeliveryAddresses( ) {
	addressesToSend = 0;
	var validate = new validateForm();
	for ( var i in addressArray ) {
		if( addressArray[i] !== '' ) {
			var validate2 = new validateForm();
			// check if we have content for name and email before testing them
			var nameValue = document.getElementById('address_' + i + '_name').value;
			var emailValue = document.getElementById('address_' + i + '_email').value;
			
			if( nameValue == '' && emailValue == '' ) {
				// skip the row, nothing was entered
			} else {
				validate.checkText( 'address_' + i + '_name', 'Friend ' + ( parseFloat( i ) + 1 ) + ' Name' );
				validate.validateEmailAddress( 'address_' + i + '_email', 'Friend ' + ( parseFloat( i ) + 1 ) + ' Email Address' );
				addressesToSend++;
			}
		}
	}
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	
	// hide the save changes button
	document.getElementById('address_save')	.style.display = 'none';
	
	var addressesSent = 0;
	var showAlert = false;
	for ( var m in addressArray ) {
		if( addressArray[m] !== '' && ( document.getElementById('address_' + m + '_name').value != '' && document.getElementById('address_' + m + '_email').value != '' )) {
			addressesSent++;
			if( addressesToSend == addressesSent ) {
				showAlert = true; 
			}
			processAddress( m, showAlert );
		}
	}
	
}

function processAddress( id, showAlert ) {
	
	var sUrl = "/xmlservice.php?service=updateDeliveryAddress";
			
	sUrl += '&name='+escape( document.getElementById('address_' + id + '_name').value );
	sUrl += '&email='+escape( document.getElementById('address_' + id + '_email').value );
	sUrl += '&id='+document.getElementById('address_' + id + '_id').value;

	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				// set the returned id to the hidden input( incase we were adding a new record)
				document.getElementById('address_' + id  + '_id').value = response.ResultSet.Result[0]['record']['id'];
				// set the [Delete] to visible
				document.getElementById('address_' + id  + '_delete').style.display = '';
			}
			// if showAlert is true (its the last one
			if( showAlert ) {
				alert( "Friend updates saved successfully" );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst adding this friend.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

/* purchase from wishlist */

function initPurchase() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('purchasePopup').style.display = '';
	purchaseBox = 
			new YAHOO.widget.Panel("purchasePopup",  
											{ width:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

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

function hidePurchase() {
	// Show the Panel
	if( typeof purchaseBox != "undefined" )
		purchaseBox.hide();
	submitPurchaseForm = false;
}

function showPurchase( wishlist_id, quantity_requested, product_name, quantity_purchased_by_others ) {
	// set some panel variables
	document.getElementById('quantity_requested').innerHTML = quantity_requested;
	// max amount purchaseable
	maximumPurchase = quantity_requested - quantity_purchased_by_others;
	// get how many bought already by me
	quantity_purchased_by_logged_in_user = document.getElementById( wishlist_id + '_purchased_by_logged_in_user').value;
	document.getElementById('quantity_purchased').value = quantity_purchased_by_logged_in_user;
	
	if( quantity_purchased_by_logged_in_user > 0 ) {
		// logged in user has already bought some
		document.getElementById('purchase_label').innerHTML = 'Currently Purchased:';
	} else {
		// none currently purchased by logged in user
		document.getElementById('purchase_label').innerHTML = 'Quantity Purchased:';
	}
	document.getElementById('quantity_purchased_by_others').innerHTML = quantity_purchased_by_others;
	document.getElementById('product_name').innerHTML = product_name;
	document.getElementById('wishlistId').value = wishlist_id;
	// Show the Panel
	if( typeof purchaseBox != "undefined" )
		purchaseBox.show();
	else
		showPurchaseOnLoad = true
}

function purchaseMade() {
	// ensure we have username and password
	var validate = new validateForm();
	validate.checkNumeric( 'quantity_purchased', 'Quantity Purchase' );	
	// check more than the asked for amount hasn't been purchased
	if( document.getElementById('quantity_purchased').value > maximumPurchase ) {
		validate.addCustomError( 'Only ' + maximumPurchase + ' more need to be purchased' );
	}	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	
	var wishlist_id = document.getElementById('wishlistId').value;
	var quantityPurchased = document.getElementById('quantity_purchased').value;
	var sUrl = "/xmlservice.php?service=setWishListItemPurchased&wishlistId=" + wishlist_id + "&quantity=" + quantityPurchased;
	hidePurchase();
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				document.getElementById( wishlist_id + '_purchased_by_logged_in_user').value = response.ResultSet.Result[0]['quantity'];
				// new page here why dont you buy a list
				showMessage();
			} else {
				alert( 'Sorry, an error occured while saving your information.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured while saving your information.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
	
}

/* message box */

function initMessage() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('messagePopup').style.display = '';
	messageBox = 
			new YAHOO.widget.Panel("messagePopup",  
											{ width:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	messageBox.render(document.body);
}

function hideMessage() {
	// refresh the wishlist page
	document.location = document.location;
	//messageBox.hide();	
}

function showMessage() {
	messageBox.show();
}


/* help boxes */

function initImageHelp() {
	document.getElementById('imageHelpPopup').style.display = '';
	imageHelpBox = 
			new YAHOO.widget.Panel("imageHelpPopup",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);
	imageHelpBox.render(document.body);
}

function hideImageHelp() {
	imageHelpBox.hide();
}

function showImageHelp() {
	imageHelpBox.show();
}

function initUrlHelp() {
	document.getElementById('urlHelpPopup').style.display = '';
	urlHelpBox = 
			new YAHOO.widget.Panel("urlHelpPopup",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);
	urlHelpBox.render(document.body);
}

function hideUrlHelp() {
	urlHelpBox.hide();
}

function showUrlHelp() {
	urlHelpBox.show();
}


/* wishlist comment */
function initWishListComment() {
	document.getElementById('wishListCommentPopup').style.display = '';
	wishListCommentBox = 
			new YAHOO.widget.Panel("wishListCommentPopup",  
											{ width:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	wishListCommentBox.render(document.body);
	if( showWishListCommentOnLoad )
		wishListCommentBox.show();
}

function hideWishListComment() {
	if( typeof wishListCommentBox != "undefined" )
		wishListCommentBox.hide();
}

function showWishListComment( myTempWishlistId, myWishlistListId, userID ) {
	tempWishlistId = myTempWishlistId;
	tempWishlistListId = myWishlistListId;
	tempUserID = userID;
	document.getElementById('comment').value = '';
	// show the current comment for this item
	document.getElementById('comment').value = document.getElementById('wishlist_' + tempWishlistId + '_comment').value;
	if( typeof wishListCommentBox != "undefined" )
		wishListCommentBox.show();
	else
		showWishListCommentOnLoad = true
}

function addWishListComment() {
	// comment could be nothing
	var comment = document.getElementById('comment').value;
	var sUrl = "/xmlservice.php?service=addWishListItemComment&ID=" + tempWishlistId + "&comment=" + comment;
	var handleSuccess = function( result ){
		if ( result.responseText !== undefined ) {
			eval( 'var response = (' + result.responseText + ')' );
			if ( response.ResultSet.Result[0]['result'] == 'success' ) {
				document.location = '/wishlist/' + tempUserID + '/' + tempWishlistListId;
			} else {
				hideWishListComment();
				alert( 'Sorry, an error occured whilst adding your comment.' );
			}
		}
	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert( 'Sorry, an error occured whilst adding your comment.' );
		}
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}


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

function unsetCookie( name ) {
	document.cookie = name + '=; expires=Thu, 2 Aug 2001 20:47:11 UTC; 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 doLists( id, hover ) {
	if( document.getElementById( 'mylists_' + id ) != null ) {
		if( document.getElementById( 'mylists_' + id ).style.display == 'none' ){
			// its hidden, show it
			document.getElementById( 'mylists_' + id ).style.display = '';
			if( hover ) {
				// alter the image
				document.getElementById( 'mylists_background_' + id ).style.backgroundImage = 'url(/custom/images/new-open-on.gif)';
			}
		} else {
			// its shown, hide it
			document.getElementById( 'mylists_' + id ).style.display = 'none';
			if( hover ) {
				// alter the image
				document.getElementById( 'mylists_background_' + id ).style.backgroundImage = 'url(/custom/images/new-closed-on.gif)';
			}
		}
	}
}
function onListType( id, image, object ) {
	// user moused over a list type
	// and the background
	display = document.getElementById( 'mylists_' + id ).style.display;
	if( display == 'none' ) {
		object.style.backgroundImage = 'url(/custom/images/new-closed-on.gif)';
	} else {
		object.style.backgroundImage = 'url(/custom/images/new-open-on.gif)';
	}
	// and the icon
	newImage = image.replace( '.gif', '-on.gif' );
	document.getElementById( 'mylists_icon_' + id ).style.backgroundImage = 'url(' + newImage + ')';
	// change the text to white
	document.getElementById( 'mylists_title_' + id ).style.color = '#fff';
}
function offListType( id, image, object ) {
	// user moused out a list type
	// change the image
	display = document.getElementById( 'mylists_' + id ).style.display;
	if( display == 'none' ) {
		object.style.backgroundImage = 'url(/custom/images/new-closed.gif)';
	} else {
		object.style.backgroundImage = 'url(/custom/images/new-open.gif)';
	}
	// and the icon
	document.getElementById( 'mylists_icon_' + id ).style.backgroundImage = 'url(' + image + ')';
	// change the text to white
	document.getElementById( 'mylists_title_' + id ).style.color = '#8e8e8e';
}
/* create new list mouseovers/outs */
function onNewList( object ) {
	object.className = 'myListsItem myListsItemBothOn';
}
function offNewList( object ) {
	object.className = 'myListsItem myListsItemBoth';
}
/* actual list mouseovers/outs */
function onList( id ) {
	if( document.getElementById( 'myitems_' + id ) ) {
		display = document.getElementById( 'myitems_' + id ).style.display;
		if( display == 'none' ) {
			document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-right-on.gif';
		} else {
			document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-down-on.gif';
		}
	}
	document.getElementById( 'mylists_list_' + id ).className = 'myListsItem myListsItemNoneOn';
}
function offList( id ) {
	if( document.getElementById( 'myitems_' + id ) ) {
		display = document.getElementById( 'myitems_' + id ).style.display;
		if( display == 'none' ) {
			document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-right.gif';
		} else {
			document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-down.gif';
		}
	}
	document.getElementById( 'mylists_list_' + id ).className = 'myListsItem myListsItemNone';
}
function showWishlistItems( id ) {
	if( document.getElementById( 'myitems_' + id ).style.display == 'none' ) {
		// its hidden, show it
		document.getElementById( 'myitems_' + id ).style.display = '';
		// alter the image
		document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-down-on.gif';
	} else {
		// its shown, hide it
		document.getElementById( 'myitems_' + id ).style.display = 'none';
		// alter the image
		document.getElementById( 'mylists_arrow_' + id ).src = '/custom/images/arrow-right-on.gif';
	}
}

function setSelectedList( id ) {
	setCookie( 'selectedList', id );
}

// sets the list last viewed
function setLastViewedList( id ) {
	setCookie( 'lastViewedList', id );
}
// returns the id of the last viewed list
function getLastViewedList( id ) {
	return getCookie( 'lastViewedList' );
}

function checkSelectedList() {
	var selectedListId = getCookie('selectedList');
	if ( selectedListId ) {
		doLists( selectedListId, false );
	}
}

/* image url */

function initImageURL() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('imageURLPopup').style.display = '';
	imageURLBox = 
			new YAHOO.widget.Panel("imageURLPopup",  
											{ width:"316px", 
											  height:"188px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	imageURLBox.render(document.body);
	if( showImageURLPopupOnLoad )
		imageURLBox.show();
}

function hideImageURLPopup() {
	if( typeof imageURLBox != "undefined" )
		imageURLBox.hide();
}

function showImageURLPopup() {
	if( typeof imageURLBox != "undefined" )
		imageURLBox.show();
	else
		showImageURLPopupOnLoad = true
}

function addURL() {
	// set the value to the parent window and close this window
	var imageURLValue = document.getElementById('makeAList_imageURL').value;
	if( imageURLValue != '' && imageURLValue != '- Enter image URL here' ) {
		// set the hidden input
		document.getElementById('makeAListProduct_product_image').value = imageURLValue;
		// and the image itself
		document.getElementById('makeAListProduct_product_imagedisplay').src = imageURLValue;
		// update the button to say "Change"
		document.getElementById('makeAListProduct_product_showimagepopup').innerHTML = 'Change Image';
		// close this window
		hideImageURLPopup();
	} else {
		alert( 'Please enter an image url' );
	}
}

/* list edit */

function initListEdit() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('listEditPopup').style.display = '';
	listEditBox = 
			new YAHOO.widget.Panel("listEditPopup",  
											{ width:"653px", 
											  height:"500px",
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	listEditBox.render(document.body);
	if( showListEditPopupOnLoad )
		listEditBox.show();
}

function hideListEditPopup() {
	if( typeof listEditBox != "undefined" )
		listEditBox.hide();
}
		
function showListEditPopup( wishlistTypeId, wishlistId, wishlistName, wishlistDescription, wishlistDateDMY, wishlistDateYMD, partnerName ) {
	// set up the edit list panel
	// set the type ddl
	document.getElementById( 'modal_cmsCatalogueWishList_wishlist_wishlist_type_id' ).value = wishlistTypeId;
	// the background image
	alterBackgroundImage();
	// set the hidden variable if we have one (editing)
	if( typeof wishlistId != 'undefined' ) {
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_id' ).value = wishlistId;
		// edit title 
		document.getElementById( 'modal_listHeader' ).innerHTML = 'Edit List Details';
		// list title
		document.getElementById( 'modal_listName' ).innerHTML = wishlistName;
		// use it for the text input too
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_name' ).value = wishlistName;
		// form action 
		document.getElementById( 'modal_form' ).action = 'redirect.php?uri=wishlist/' + userId + '/' + wishlistId;
		// list description... blank
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_description' ).innerHTML = wishlistDescription;
		// hidden date
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date' ).value = wishlistDateYMD;
		// display date... blank
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date_display' ).value = wishlistDateDMY;
		// surname
		document.getElementById( 'modal_cmsUserAdmin_user_surname' ).value = partnerName;
	} else {
		// set it to empty/blank/nothing
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_id' ).value = '';
		// add title
		document.getElementById( 'modal_listHeader' ).innerHTML = 'New List Details';
		// list title
		document.getElementById( 'modal_listName' ).innerHTML = 'List name here...';
		// set the text input title to empty
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_name' ).value = '';
		// form action 
		document.getElementById( 'modal_form' ).action = 'redirect.php?uri=wishlist/' + userId;
		// list description... blank
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_description' ).innerHTML = '';
		// if not a christmas list
		if( imageNameArray[wishlistTypeId] != 'Christmas' && imageNameArray[wishlistTypeId] != 'Kids Christmas' ) {
			// hiddendate... blank
			document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date' ).value = '';
			// display date... blank
			document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date_display' ).value = '';
		}
		// surname
		document.getElementById( 'modal_cmsUserAdmin_user_surname' ).value = '';
	}
	
	if( typeof listEditBox != "undefined" )
		listEditBox.show();
	else
		showListEditPopupOnLoad = true
}

function alterBackgroundImage() {
	var currentImage = document.getElementById('modal_cmsCatalogueWishList_wishlist_wishlist_type_id').value;
	
	// set the correct bg image
	document.getElementById( 'modal_background' ).style.backgroundImage = 'url(' + imageArray[currentImage] + ')';
	
	if( imageNameArray[currentImage] == 'Wedding' ) {
		document.getElementById('modal_wedding_partner').style.display = '';	
	} else {
		document.getElementById('modal_wedding_partner').style.display = 'none';
	}
	
	// if baby list, some info text
	if( imageNameArray[currentImage] == 'Kids Christmas' ) {
		document.getElementById( 'modal_typeInfo' ).innerHTML = 'Send your list to Santa';
	} else if( imageNameArray[currentImage] == 'Other' ) {
		// if other list, some info text
		document.getElementById( 'modal_typeInfo' ).innerHTML = 'A List for any occasion';
	} else {
		// no text
		document.getElementById( 'modal_typeInfo' ).innerHTML = '';
	}
	
	if( imageNameArray[currentImage] == 'Christmas' || imageNameArray[currentImage] == 'Kids Christmas' ) {
		// set the date to the coming xmas
		var currentDate = new Date();
		document.getElementById('modal_cmsCatalogueWishList_wishlist_expiry_date_display').value = '25-12-' + currentDate.getFullYear();
		// set the input date to be submitted as US
		document.getElementById('modal_cmsCatalogueWishList_wishlist_expiry_date').value = currentDate.getFullYear() + '-12-25';
	} else {
		// both dates should be blank
		document.getElementById('modal_cmsCatalogueWishList_wishlist_expiry_date_display').value = '';
		document.getElementById('modal_cmsCatalogueWishList_wishlist_expiry_date').value = '';
	}
}
function modal_checkForm() {
	var validate = new validateForm();
	
	// name of list
	validate.checkText( 'modal_cmsCatalogueWishList_wishlist_name', 'Name your list' );
	// type must be entered
	validate.checkSelect( 'modal_cmsCatalogueWishList_wishlist_wishlist_type_id', '', 'Type' );
	// if wedding partner is seeable
	if( document.getElementById('modal_wedding_partner').style.display == '' ) {
		// check its been entered
		validate.checkText( 'modal_cmsUserAdmin_user_surname', 'Partner Name' );	
	}
	// date, simply check it
	validate.checkText( 'modal_cmsCatalogueWishList_wishlist_expiry_date' , 'Date of occasion' );
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	} 

	return true;
}
function modal_dateChanged( calendar ) {
	var y = calendar.date.getFullYear();
	var m = calendar.date.getMonth() + 1;     // integer, 0..11
	if( m < 10 ) {
		m = '0' + m;
	}
	var d = calendar.date.getDate();      // integer, 1..31
	if( d < 10 ) {
		d = '0' + d;
	}
	if (calendar.dateClicked) {
		// set the visible date to UK
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date_display').value = d + '-' + m + '-' + y;
		// set the input date to be submitted as US
		document.getElementById( 'modal_cmsCatalogueWishList_wishlist_expiry_date').value = y + '-' + m + '-' + d;
		// hide calendar
		calendar.hide();
	} 
}
/* recommend panel */
function initRecommend() {
	document.getElementById('recommendPopup').style.display = '';
	recommendBox = 
			new YAHOO.widget.Panel("recommendPopup",  
											{ width:"316px", 
											  height:"258px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);
	recommendBox.render(document.body);
	if( showRecommendOnLoad )
		recommendBox.show();
}

function hideRecommend() {
	if( typeof recommendBox != "undefined" )
		recommendBox.hide();
}

function showRecommend() {
	if( typeof recommendBox != "undefined" )
		recommendBox.show();
	else
		showRecommendOnLoad = true
}

/* deleting a recently viewed list */

function deleteView( wishlist_id ) {
	if( confirm( 'Are you sure you want to delete this list view?' )) {
		var sUrl = "/xmlservice.php?service=removeWishlistView&wishlistId=" + wishlist_id;
		var handleSuccess = function( result ){
			if ( result.responseText !== undefined ) {
				eval( 'var response = (' + result.responseText + ')' );
				if ( response.ResultSet.Result[0]['result'] == 'success' ) {
					// hide the list view
					document.getElementById( 'recently_viewed_list_' + wishlist_id ).style.display = 'none';
				} else {
					alert( 'Sorry, an error occured whilst deleteing the list view.' );
				}
			}
		}
		
		var handleFailure = function(o){
			if(o.responseText !== undefined){
				alert( 'Sorry, an error occured whilst deleteing the list view.' );
			}
		}
		
		var callback =
		{
		  success:handleSuccess,
		  failure: handleFailure
		};
		
		var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
	}
}

function clickBannerLink( area ) {
	if ( !userAuthenticated ) {
		showLogin();
	} else {
		switch ( area ) {
			case 'wedding':
				var listId = 5;
				break;
			case 'christmas':
				var listId = 3;
				break;
			case 'baby':
				var listId = 8;
				break;
			case 'birthday':
				var listId = 1;
				break;
		}
		showListEditPopup(listId);
	}
}

/* home - more info popups */

function initMoreInfo1() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('moreInfoPopup1').style.display = '';
	moreInfoBox1 = 
			new YAHOO.widget.Panel("moreInfoPopup1",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	moreInfoBox1.render(document.body);
	if( showMoreInfo1OnLoad )
		moreInfoBox1.show();
}
function showMoreInfo1() {
	if( typeof moreInfoBox1 != "undefined" )
		moreInfoBox1.show();
	else
		showMoreInfo1OnLoad = true
}
function hideMoreInfo1() {
	moreInfoBox1.hide();	
}

function initMoreInfo2() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('moreInfoPopup2').style.display = '';
	moreInfoBox2 = 
			new YAHOO.widget.Panel("moreInfoPopup2",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	moreInfoBox2.render(document.body);
	if( showMoreInfo2OnLoad )
		moreInfoBox2.show();
}
function showMoreInfo2() {
	if( typeof moreInfoBox2 != "undefined" )
		moreInfoBox2.show();
	else
		showMoreInfo2OnLoad = true
}
function hideMoreInfo2() {
	moreInfoBox2.hide();	
}

function initMoreInfo3() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('moreInfoPopup3').style.display = '';
	moreInfoBox3 = 
			new YAHOO.widget.Panel("moreInfoPopup3",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	moreInfoBox3.render(document.body);
	if( showMoreInfo3OnLoad )
		moreInfoBox3.show();
}
function showMoreInfo3() {
	if( typeof moreInfoBox3 != "undefined" )
		moreInfoBox3.show();
	else
		showMoreInfo3OnLoad = true
}
function hideMoreInfo3() {
	moreInfoBox3.hide();	
}

function initWishlistInfo() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('wishlistInfoPopup').style.display = '';
	wishlistInfoBox = 
			new YAHOO.widget.Panel("wishlistInfoPopup",  
											{ width:"653px", 
											  height:"366px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	wishlistInfoBox.render(document.body);
	if( showWishlistInfoOnLoad )
		wishlistInfoBox.show();
}
function showWishlistInfo() {
	if( typeof wishlistInfoBox != "undefined" )
		wishlistInfoBox.show();
	else
		showWishlistInfoOnLoad = true
}
function hideWishlistInfo() {
	wishlistInfoBox.hide();	
}
/* wishlist intro */
function initWishlistIntro() {
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('wishlistIntroPopup').style.display = '';
	wishlistIntroBox = 
			new YAHOO.widget.Panel("wishlistIntroPopup",  
											{ width:"657px", 
											  height:"500px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	wishlistIntroBox.render(document.body);
	if( showWishlistIntroOnLoad )
		wishlistIntroBox.show();
}
function showWishlistIntro( id ) {
	if( typeof wishlistIntroBox != "undefined" ) {
		// setup the popup with the correct background
		document.getElementById( 'wishlistIntroPopup_name' ).innerHTML = wishlistTypeArray[id]['name'] + ' List';
		document.getElementById( 'wishlistIntroPopupBackground' ).style.backgroundImage = 'url(' + wishlistTypeArray[id]['image'] + ')';
		document.getElementById( 'wishlistIntroText' ).innerHTML = wishlistTypeArray[id]['description'];
		wishlistIntroBox.show();
	} else {
		showWishlistIntroOnLoad = true
	}
}
function hideWishlistIntro() {
	wishlistIntroBox.hide();	
}

/* user search */
function initUserSearch() {
	// correct png
	correctPNGBackground( 'userSearchPopupBg', '/custom/images/user-search-bg.png' );
	// Initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('userSearchPopup').style.display = '';
	userSearchBox = 
			new YAHOO.widget.Panel("userSearchPopup",  
											{ width:"348px", 
											  height:"142px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	userSearchBox.render(document.body);
	if( showUserSearchOnLoad )
		userSearchBox.show();
}
function showUserSearch() {
	if( typeof userSearchBox != "undefined" )
		userSearchBox.show();
	else
		showUserSearchOnLoad = true
}
function hideUserSearch() {
	userSearchBox.hide();	
}

if ( userAuthenticated ) {
	/* bookmark tool */
	function initBookmark() {
		// correct png
		correctPNGBackground( 'bookmarkPopupBg', '/custom/images/bookmark-bg.png' );
		// Initialize the temporary Panel to display while waiting for external content to load
		document.getElementById('bookmarkPopup').style.display = '';
		bookmarkBox = 
				new YAHOO.widget.Panel("bookmarkPopup",  
												{ width:"821px", 
												  height:"578px", 
												  fixedcenter:true, 
												  close:false, 
												  draggable:false, 
												  modal:true,
												  visible:false,
												  underlay:"none",
												  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
												} 
											);
	
		bookmarkBox.render(document.body);
		if( showBookmarkOnLoad )
			bookmarkBox.show();
	}
	function showBookmark() {
		if( typeof bookmarkBox != "undefined" )
			bookmarkBox.show();
		else
			showBookmarkOnLoad = true
	}
	function hideBookmark() {
		bookmarkBox.hide();	
	}
	
	YAHOO.util.Event.addListener(window, "load", initBookmark);
}

