var numSizeRows = 0;
var responseText;
var responseText2;
var redirect;
var categoriesLoaded = new Array();

function checkMandatoryFields( element )
{
}

function storeMandatoryFields( element, rowToAppendTo )
{
}

// Get the sizes belonging to selected product type.

function getProductSizes( absolutePath, webRoot, selectElement, productId )
{
	productTypeId = document.getElementById( selectElement ).options[document.getElementById( selectElement ).
		selectedIndex].value;
	
	if( productTypeId != "-----" )
	{
		url = webRoot + '/includes/GetProductSizes.php?productTypeId=' + productTypeId + '&' + 
			'webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 'productId=' + productId;
  	
		callback = 
		{
     		success: function(o) 
			{
				if( o.responseText != "" )
				{
					row = document.getElementById( selectElement ).parentNode.parentNode;
					rowIndex = row.rowIndex + 1;
					table = row.parentNode.parentNode;
			
					row = table.insertRow( rowIndex );
					
					var column1 = row.insertCell( 0 );
					column1.setAttribute( 'colspan', '2' );
					
					var newTable = document.createElement( 'table' );
					newTable.setAttribute( 'width', '849' );
					newTable.setAttribute( 'border', '0' );
					
					var newTableRow = newTable.insertRow(0);
					
					newTableRow = newTable.insertRow(1);
					newTableRow.setAttribute( 'colspan', '2' );
					newTableRow.setAttribute( 'class', 'green' );
					newTableRow.appendChild( document.createTextNode( 'Product Sizes' ) );
	
					rowIndex = 2;
					
					array = o.responseText.split( '</tr>' );
					len = array.length;
					len--;
					
					for( i = 0; i < len; i++ )
					{
						startIdx = array[i].indexOf( 'sizeRow' );
						endIdx = array[i].indexOf( "'", startIdx )
						
						if( endIdx == -1 )
							endIdx = array[i].indexOf( ">", startIdx )
							
						sizeId = array[i].substring( startIdx, endIdx );
						
						array[i] = "<td>" + array[i].substring( array[i].indexOf( '<input', endIdx ), 
							array[i].lastIndexOf( '</td>' ) ) + "</td>";
						
						newTableRow = newTable.insertRow(rowIndex);
						newTableRow.setAttribute( 'id', sizeId );
						newTableRowColumn = newTableRow.insertCell( 0 );
						newTableRowColumn.setAttribute( 'colspan', '2' );
						newTableRowColumn.innerHTML = array[i];
					}
					
					column1.appendChild( newTable );
				}
			}
	   	}
		
		transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
  	}
}


// When a product size checkbox is checked because the explanation text and input elements for adding a new
// size.

function displayProductSizeInformation( productSizeId, currentIndex )
{
	display = "";
	
	if( !document.getElementById( 'checkbox' + currentIndex + '_' + productSizeId ).checked )
		display = "none";
		
	if( document.getElementById( 'weightHeader' + currentIndex + '_' + productSizeId ) != null )
		document.getElementById( 'weightHeader' + currentIndex + '_' + productSizeId ).style.display = display;
		
	document.getElementById( 'stockHeader' + currentIndex + '_' + productSizeId ).style.display = display;
	document.getElementById( 'priceHeader' + currentIndex + '_' + productSizeId ).style.display = display;
	document.getElementById( 'colourHeader' + currentIndex + '_' + productSizeId ).style.display = display;
	document.getElementById( 'addButton' + currentIndex + '_' + productSizeId ).style.display = display;
}

// This function is used by the EditProduct.php script to create a new row for recording an additional size.
// This is because a product may come in many sizes and for each size the product may come in different colours
// and may have stock statuses. Different sizes may mean different prices also.

function addAnotherSizeRow( idName, productSizeId, currentIndex )
{
	var row = document.getElementById( idName );
	innerHTML = document.getElementById( idName ).innerHTML;
	
	var table = row.parentNode.parentNode;
	
	// Create a new row as a copy of the previous row.
	var newRow = table.insertRow( row.rowIndex + 1 );
	newRow.setAttribute( "id", "sizeRow" + numSizeRows + "_" + productSizeId );
	
	var newColumn = newRow.insertCell( 0 );
	newColumn.setAttribute( 'colspan', '2' );
		
	// For the new row change the id/name of the row itself.
	var text = "sizeRow" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "sizeRow" + numSizeRows );
	
	// For the new row change the id/name of checkbox used to select or deselect whether the size
	// should be added or not.
	var text = "sizeCheckbox~" + productSizeId + "~" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "sizeCheckbox~" + productSizeId + "~" + numSizeRows );
	
	// For the new row change id/name of the column that contains text to explain the product weight drop
	// down.
	var text = "weightHeader" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "weightHeader" + numSizeRows );
	
	// For the new row change id/name of the row that contains the product weight dropdown.
	var text = "weight_id~" + productSizeId + "~" + currentIndex
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "weight_id~" + productSizeId + "~" + numSizeRows );
	
	// For the new row change id/name of the column that contains text to explain the product orientation drop
	// down.
	var text = "orientationHeader" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "orientationHeader" + numSizeRows );
	
	// For the new row change id/name of the row that contains the product orientation dropdown.
	var text = "orientation_id~" + productSizeId + "~" + currentIndex
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "orientation_id~" + productSizeId + "~" + numSizeRows );
	
	// For the new row change id/name of the column that contains text to explain the product size price
	// input field.
	var text = "priceHeader" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "priceHeader" + numSizeRows );
	
	// For the new row change id/name of the product weight drop down.
	var text = "price~" + productSizeId + "~" + currentIndex
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "price~" + productSizeId + "~" + numSizeRows );
	
	// Get the price of the previous size row, which we copied.
	var price = document.getElementById( "price~" + productSizeId + "~" + currentIndex ).value;
	
	// For the new row change the id/name of the stock status explanation text.
	var text = "stockHeader" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "stockHeader" + numSizeRows );
	
	// For the new row change the id/name of the stock status drop down.
	var text = "stock_status_id~" + productSizeId + "~" + currentIndex
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "stock_status_id~" + productSizeId + "~" + numSizeRows );
	
	// For the new row change the id/name of the product colour explanation text.
	var text = "colourHeader" + currentIndex;
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "colourHeader" + numSizeRows );
	
	// For the new row change the id/name of the product colour single line input field.
	var text = "colour~" + productSizeId + "~" + currentIndex
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "colour~" + productSizeId + "~" + numSizeRows );
	
	// Update the text box counter.
	var text = "'" + currentIndex + "'";
	var re = new RegExp(text, 'g');
	innerHTML = innerHTML.replace( re, "'" + numSizeRows + "'" );
	
	// Update the HTML of the new row to store the id/name changes.
	if( innerHTML.indexOf( '<td>' ) != -1 )
		innerHTML = innerHTML.substring( innerHTML.indexOf( '<td>' ), innerHTML.lastIndexOf( '</td>' ) );
	else
		innerHTML = innerHTML.substring( innerHTML.indexOf( '<TD>' ), innerHTML.lastIndexOf( '</TD>' ) );
		
	newColumn.innerHTML = innerHTML;
	
	// Check the checkbox of the new row it indicate that the new size is being used.
	//document.getElementById( 'checkbox' + numSizeRows + "_" + productSizeId ).checked = "checked";
	
	// Set the price for the new product size row to be the same as the previous row, as a default.
	//document.getElementById( "price~" + productSizeId + "~" + numSizeRows ).value = price;
	
	// Update a counter variable of the number of size rows.
	numSizeRows++;
}

// This function changes the main promo that is displayed first when the homepage loads (if other settings
// allow). A validation check is in place to prevent the user from selecting an invalid value for the
// main promo.

function setSpecificMainPromo( absolutePath, webRoot )
{
	// Get the promo selected for display on the homepage.
	mainCategoryId = document.getElementById( 'main_category_id' ).options[document.getElementById
		( 'main_category_id' ).selectedIndex].value;

	// Invalid value selected as main promo.
	if( selectedOption == "-----" )
		return;
	
	// Given that a valid main promo has been selected - football, hockey or cricket (currently) -
	// update the promo in use.
	url = webRoot + '/includes/SetSpecificMainPromo.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'mainCategoryId=' + mainCategoryId;
  	
	callback = 
	{
     	success: function(o) {}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// This function enables the user to flick between having a specific main promo, which can be selected in a
// separate function, or having the main promo chosen at random.

function setFirstPromo( absolutePath, webRoot )
{
	// Which option has been chosen - random main promo or specifically selected promo.
	selectedOption = document.getElementById( 'first_main_promo' ).options[document.getElementById
		( 'first_main_promo' ).selectedIndex].value;

	// Prevent invalid value from being selected and used.
	if( selectedOption == "-----" )
		return;
	
	// Invoke PHP to update the database.
	url = webRoot + '/includes/SetMainPromoStatus.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'mainPromoOption=' + selectedOption;
  	
	callback = 
	{
     	success: function(o) 
		{
			if( selectedOption == "Random" )
			{
				// Option chosen is display randomly selected homepage promo. As a result remove the facility
				// for selecting a specific promo if one exists.
				row = document.getElementById( 'first_main_promo' ).parentNode.parentNode;
				table = row.parentNode.parentNode;
				
				// Just need to remove the specific promo selection drop-down box and then return.
				rowIndex = row.rowIndex;
				rowIndex++;
				
				table.deleteRow( rowIndex );
				table.deleteRow( rowIndex );
				
				return;
			}
			
			// Only got here if chosen to have a specific main promo.
			mainCategoryId = o.responseText;
			
			// Create a new row, dynamically, to display information text.
			row = document.getElementById( 'first_main_promo' ).parentNode.parentNode;
			rowIndex = row.rowIndex;
			rowIndex++;
			
			table = row.parentNode.parentNode;
			
			try
			{
			row = table.insertRow( rowIndex );
			
			// New row has one column that explains what the drop down box is for.
			var column1 = row.insertCell( 0 );
			column1.setAttribute( 'colspan', '2' );
			var span = column1.appendChild( document.createElement( 'span' ) );
			span.className = 'white';
			span.appendChild( document.createTextNode( 'Main Promo to display first' ) );
			column1.appendChild( span );
			
			// Create another row which enables the specific main promo to be selected.
			rowIndex++;
			row = table.insertRow( rowIndex );
		
			column1 = row.insertCell( 0 );
			column1.setAttribute( 'colspan', '2' );
			var selectElement = column1.appendChild( document.createElement( 'select' ) );
			selectElement.setAttribute( 'id', 'main_category_id' );
			selectElement.setAttribute( 'name', 'main_category_id' );
			
			// When a main promo is selected invoke a AJAX function to update the database with
			// the name of the specific main promo to display first.
			selectElement.onchange = function() { setSpecificMainPromo( absolutePath, webRoot ) };
			
			// Get a list of the possible main promos.
			url2 = webRoot + '/includes/GetSportsCategories.php?webRoot=' + webRoot + '&' + 
				'absolutePath=' + absolutePath;
			
			callback2 = 
			{
				success: function(o) 
				{
					// Create drop down to enable specific main promo to be selected.
					addOption('main_category_id', "-----", "Please select main promo to display first", "");
					addOption('main_category_id', "-----", "-----", "");
					
					array = o.responseText.split( '|' );
					
					for( i = 0; i < array.length; i++ )
					{
						temp = array[i].split( '~' );
						
						// If main promo has previously been selected then re-select. Otherwise
						// the first option in the drop down will be selected by default.
						if( temp[0] == mainCategoryId )
							addOption('main_category_id', temp[0], temp[1], '1');
						else
							addOption('main_category_id', temp[0], temp[1]);
					}
				}
			}
				
			transaction = YAHOO.util.Connect.asyncRequest('GET', url2, callback2, null);
			
			}
			catch( err )
			{
				alert( err );
			}
		}
	}
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Is used by the CMS welcome page to change the auto rotation status of the main promos - either yes
// to auto rotate and automatically display each main promo after a time delay or no to disable the auto
// rotate feature so that the main promo displayed when the homepage loads is not changed unless the page is
// re-loaded (however this depends on another sitewide setting) or the user manually chosen to display another
// main promo.

function setAutoRotateStatus( absolutePath, webRoot )
{
	autoRotate = 0;
	
	if( document.getElementById( 'auto_rotate' ).checked )
		autoRotate = 1;
	
	url = webRoot + '/includes/SetAutoRotateStatus.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'autoRotateStatus=' + autoRotate;
  	
	callback = 
	{
     	success: function(o) {}
	}
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Changes the current page to a page where the new customer testimonials can be reviewed.

function viewNewTestimonials( absolutePath, webRoot )
{
	window.location.href = webRoot + '/cms/customer/NewTestimonials.php';
}

// Changes the current page to a page where the new product reviews can be reviewed.

function viewNewReviews( absolutePath, webRoot )
{
	window.location.href = webRoot + '/cms/customer/NewReviews.php';
}

// Changes the current page to a page where the new orders can be viewed.

function viewNewOrders( absolutePath, webRoot )
{
	window.location.href = webRoot + '/cms/customer/NewOrders.php';
}

// Changes the current page to a page where the products that are out of stock can be viewed.

function viewOutOfStockProducts( absolutePath, webRoot )
{
	window.location.href = webRoot + '/cms/shop/OutOfStock.php';
}

// Changes the current page to a page where email reminders are listed.

function viewEmailReminders( absolutePath, webRoot )
{
	window.location.href = webRoot + '/cms/customer/EmailReminders.php';
}

// Displays or hides input fields associated with adding a special offers. Certain special offers are either
// in use or not. Other special offers, however, have a value associated with them - a percentage used as a
// discount or a certain amount off.

function showHideSpecialOffer( absolutePath, webRoot, productId )
{
	// Get a list of all special offers.
	var checkboxGrp = document.getElementsByName( 'special_offer_id~special_offer_products[]' );
	
	// Holds the ids of the special offers belonging to the current product.
	specialOfferIds = "";
	
	// For each special offer.
	for( var i = 0; i < checkboxGrp.length; i++ )
	{
		// Check whether the current special offer is to be used by the product.
		if( checkboxGrp[i].checked )
		{
			if( specialOfferIds != "" )
				specialOfferIds += ",";
				
			specialOfferIds += checkboxGrp[i].value;
		}
		else
		{
			// The special offer is no longer in use. Remove an amount input field for the special
			// offer (if one exists - if the number of columns for the current row is two). The first column
			// being occupied by a checkbox (that enables the special offer to be selected/deselected).
			// The second column is used to input an amount (if this is appropriate for the type of special
			// offer to add/added).
			row = checkboxGrp[i].parentNode.parentNode;
			numCols = row.getElementsByTagName( 'td' ).length;
			
			// Delete the amount column.
			if( numCols == 2 )
				row.deleteCell( 1 );
		}
	}
	
	// Invoke a PHP script to get the details of any existing special offers applied to the current product.
	// As far as arguments are concerned, specialOfferIds contains a list of the ids of special offers applied
	// to the current product. productId contains the id of the product.
	url = webRoot + '/includes/ShowHideSpecialOffer.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'specialOfferIds=' + specialOfferIds + '&' + 'productId=' + productId;
  	
	callback = 
	{
     	success: function(o)
		{
			// Get a list of current or to be added special offers.
			array = o.responseText.split( "|" );
			
			// For each special offer.
			for( var i = 0; i < array.length; i++ )
			{
				// Get the details of the special offer.
				temp = array[i].split( "~" );
				
				// For all possible special offers.
				for( var j = 0; j < checkboxGrp.length; j++ )
				{
					// If the special offer is in use.
					if( checkboxGrp[j].value == temp[0] )
					{
						// If the special offer has an amount associated with it.
						if( temp[1] == 1 )
						{
							// Identify the number of columns associated with the current special offer.
							row = checkboxGrp[j].parentNode.parentNode;
							numCols = row.getElementsByTagName( 'td' ).length;
							
							// If the number of columns is one then an amount input field needs to be 
							// created in a new column. If the number of columns is two then an amount 
							// input field already exist.
							if( numCols == 1 )
							{
								// Create a new column containing an HTML input element for the special
								// offer amount figure. Set the value of the input if the special offer
								// already exists.
								var column1 = row.insertCell( 1 );
								var input = document.createElement( 'input' );
								input.setAttribute( 'type', 'text' );
								input.setAttribute( 'id', 'amount~' + temp[0] );
								input.setAttribute( 'name', 'amount~' + temp[0] );
								
								if( temp.length == 3 )
									input.setAttribute( 'value', temp[2] );
									
								column1.appendChild( input );
							}
						}
					}
				}
			}
		}
	}
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Ajax function to update number of products, best selling products and most popular product totals. The
// selectElement argument is a reference to the actual category drop element. categoryId holds the id of 
// the selected category. detailOption is the option selected from no products, best selling products and
// most popular.

function updateProductsStatistics( absolutePath, webRoot, selectElement, categoryId, detailOption )
{
	url = webRoot + '/includes/UpdateProductsStatistics.php?webRoot=' + webRoot + '&' + 
		'absolutePath=' + absolutePath + '&' + 'categoryId=' + categoryId + '&' + 'detailOption=' + 
		detailOption;
  	
	selectElementIdName = selectElement.id;
	
	callback = 
	{
     	success: function(o)
		{
			// Parse the output to set the overall, month and year totals.
			array = o.responseText.split( '|' );
			
			document.getElementById( selectElementIdName + 'Total' ).innerHTML = array[0];
			document.getElementById( selectElementIdName + 'Month' ).innerHTML = array[1];
			document.getElementById( selectElementIdName + 'Year' ).innerHTML = array[2];
			
			// Get the sub categories of the selected category.
			url2 = webRoot + '/includes/GetSubCategories.php?webRoot=' + webRoot + '&' + 
				'absolutePath=' + absolutePath + '&' + 'categoryId=' + categoryId + '&' + 'detailOption=' + 
				detailOption;
  	
			callback2 = 
			{
     			success: function(o)
				{
					// Assign a unique id for the new category drop down filter.
					subSelectIdName = selectElementIdName.replace( /level/, '' );
					num = parseInt( subSelectIdName );
					num++;
					subSelectIdName = 'level' + num;
					
					selectElement = "";
					
					// Remove redundant drop down lists.
					selectList = document.getElementsByTagName( 'select' );
					len = selectList.length;
					
					for( i = 0; i < len; i++ )
					{
						idName = selectList[i].id.replace( /level/, '' );
						levelNo = parseInt( idName );
						 
						if( levelNo > num )
						{
							deleteRow = selectList[i].parentNode.parentNode;
							deleteTable = deleteRow.parentNode.parentNode;
							deleteTable.deleteRow( deleteRow.rowIndex );
						}
					}	
					
					array = new Array();
					
					if( o.responseText.indexOf( '|' ) != -1 )
						array = o.responseText.split( '|' );
					
					countFields = 0;
					
					if( array.length > 0 )
					{
						temp = array[0].split( '~' );
						countFields = temp.length;
					}
					
					// Create if drop down doesn't already exist and there is more than one.
					if( document.getElementById( subSelectIdName ) == null && countFields == 5 || len == 1 )
					{
						// Dynamically create another category filter. If there are sub categories of the
						// selected category.
						
						// Get the position of the current row, increment it to create new row directly 
						// beneath current row.
						row = document.getElementById( selectElementIdName ).parentNode.parentNode;
						rowIndex = row.rowIndex;
						rowIndex++;
						
						table = row.parentNode.parentNode;
						
						row = table.insertRow( rowIndex );
						
						selectElement = document.createElement( 'select' );
						selectElement.setAttribute( 'id', subSelectIdName );
						selectElement.setAttribute( 'name', subSelectIdName );
				
						//Link up select options to statistics function.
						selectElement.onchange = function() { getStatistics( absolutePath, webRoot, 
							this ) };
						
						column = row.insertCell( 0 );
						column.appendChild( selectElement );
						
						// Populate drop down.
						addOption( subSelectIdName, "-----", "Please select a sub category" );
						addOption( subSelectIdName, "-----", "-----" );
					
						// Create columns where totals will be stored when valid option from new drop down
						// selected.
						column1 = row.insertCell( 1 );
						column1.setAttribute( 'id', subSelectIdName + 'Total' );
						column1.setAttribute( 'name', subSelectIdName + 'Total' );
						column1.setAttribute( 'class', 'green' );
						
						column2 = row.insertCell( 2 );
						column2.setAttribute( 'id', subSelectIdName + 'Month' );
						column2.setAttribute( 'name', subSelectIdName + 'Month' );
						column2.setAttribute( 'class', 'green' );
						
						column3 = row.insertCell( 3 );
						column3.setAttribute( 'id', subSelectIdName + 'Year' );
						column3.setAttribute( 'name', subSelectIdName + 'Year' );
						column3.setAttribute( 'class', 'green' );
					}
					else
					{
						if( document.getElementById( subSelectIdName ) == null )
							subSelectIdName = "";
						else
						{
							if( array.length == 0 )
							{
								deleteRow = document.getElementById( subSelectIdName ).parentNode.parentNode;
								deleteTable = deleteRow.parentNode.parentNode;
								deleteTable.deleteRow( deleteRow.rowIndex );
							}
							else
							{
								document.getElementById( subSelectIdName + 'Total' ).innerHTML = "";
								document.getElementById( subSelectIdName + 'Month' ).innerHTML = "";
								document.getElementById( subSelectIdName + 'Year' ).innerHTML = "";
								
								// Drop down already exists. Clear it so it can be re-populated with 
								// different data.
								removeAllOptions( subSelectIdName );
								
								// Populate drop down.
								addOption( subSelectIdName, "-----", "Please select a sub category" );
								addOption( subSelectIdName, "-----", "-----" );
							}
						}
					}
					
					// Current row.
					currentRow = "";
					
					if( document.getElementById( subSelectIdName ) != null )
						currentRow = document.getElementById( subSelectIdName ).parentNode.parentNode;
					else
						currentRow = document.getElementById( selectElementIdName ).parentNode.parentNode;
					
					breakdownRows = table.rows;
					
					rowsToDelete = new Array();
					
					for( k = 0; k < breakdownRows.length; k++ )
					{
						if( breakdownRows[k].className == "breakdownTotals" )
							rowsToDelete.push( breakdownRows[k] );
					}
					
					for( k = 0; k < rowsToDelete.length; k++ )
						table.deleteRow( rowsToDelete[k].rowIndex );
					
					rowIndex = currentRow.rowIndex;
					rowIndex++;
	
					for( i = 0; i < array.length; i++ )
					{
						temp = array[i].split( '~' );
							
						// Add option to select element.
						if( subSelectIdName != "" )
							addOption( subSelectIdName, temp[0], temp[1] );
						
						// Breakdown row. First column is category or product name.
						row = table.insertRow( rowIndex );
						row.setAttribute( 'class', 'breakdownTotals' );
						column = row.insertCell( 0 );
						column.setAttribute( 'width', '550' );
						span = column.appendChild( document.createElement( 'span' ) );
						span.className = 'white';
						span.appendChild( document.createTextNode( temp[1] ) );
						column.appendChild( span );
						
						if( temp.length == 5 )
						{
							// Overall total.
							column1 = row.insertCell( 1 );
							span = column1.appendChild( document.createElement( 'span' ) );
							span.className = 'green';
							span.appendChild( document.createTextNode( temp[2] ) );
							column1.appendChild( span );
						
							// Month total.
							column2 = row.insertCell( 2 );
							span = column2.appendChild( document.createElement( 'span' ) );
							span.className = 'green';
							span.appendChild( document.createTextNode( temp[3] ) );
							column2.appendChild( span );
						
							// Year total.
							column3 = row.insertCell( 3 );
							span = column3.appendChild( document.createElement( 'span' ) );
							span.className = 'green';
							span.appendChild( document.createTextNode( temp[4] ) );
							column3.appendChild( span );
						
							// Spacer.
							column4 = row.insertCell( 4 );
							column4.setAttribute( 'width', '400' );
						}
						
						rowIndex++;
					}
				}
			}
			
			// Get category list totals for selected category.
			transaction = YAHOO.util.Connect.asyncRequest('GET', url2, callback2, null);
		}
	}
	
	// Get totals for selected category.
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Derives statistics based on user selection.

function getStatistics( absolutePath, webRoot, selectElement )
{
	// Which option - no products, best selling, most popular - has been selected.
	radioGroup = document.getElementsByName( 'detailOption' );
	selectedOption = "";
	
	// Id of selected main or sub category.
	categoryId = -1;
	
	// Get selected option.
	for( i = 0; i < radioGroup.length; i++ )
	{
		if( radioGroup[i].checked )
			selectedOption = radioGroup[i].value;
	}
	
	// No option selected.
	if( selectedOption == "" )
	{
		alert( "Please select an option to use as a filter" );
		selectElement.selectedIndex = 0;
		return;
	}
	else
	{
		// Get selected main or sub category.
		categoryId = selectElement.options[selectElement.selectedIndex].value
	}
	
	// No category selected.
	if( categoryId == -1 || categoryId == "-----" )
	{
		alert( "Please select a category" );
		selectElement.selectedIndex = 0;
		return;
	}
		
	updateProductsStatistics( absolutePath, webRoot, selectElement, categoryId, selectedOption );
}

// Called to clear CMS statistics page so that new statistics can be retrieved.

function clearStatisticsPage()
{
	selectElement = document.getElementById( 'level0' );
	
	document.getElementById( 'level0Total' ).innerHTML = "";
	document.getElementById( 'level0Month' ).innerHTML = "";
	document.getElementById( 'level0Year' ).innerHTML = "";
	
	row = selectElement.parentNode.parentNode;
	table = row.parentNode.parentNode;
	
	rows = table.rows;
	
	rowsToDelete = new Array();
					
	for( i = 0; i < rows.length; i++ )
	{
		if( rows[i].className == "breakdownTotals" )
			rowsToDelete.push( rows[i] );
	}
	
	selectElements = document.getElementsByTagName( 'select' );
	
	for( i = 0; i < selectElements.length; i++ )
	{
		if( selectElements[i].id != "level0" )
		{
			row = selectElements[i].parentNode.parentNode;
			rowsToDelete.push( row );
		}
	}
	
	for( i = 0; i < rowsToDelete.length; i++ )
		table.deleteRow( rowsToDelete[i].rowIndex );
	
	selectElement.selectedIndex = 0;
}

// Replaces the shopping basket details.

function updateShoppingBasketDetails( output )
{
	array = output.split( '~' );
	
	// Replace the total number of items.
			
	// Hide text to replace.
			
	$j("#basketTotalItems").fadeOut("slow", function () 
	{
		// Pluralise text if necessary.
				
		if( array[0] == "1" )
			array[0] += " item";
		else
			array[0] += " items";
					
		// Replace amount.
		document.getElementById('basketTotalItems').innerHTML = array[0];
				
		// Make text visible again
		$j("#basketTotalItems").fadeIn("slow");
	});
			
	// Hide text to replace.
			
	$j("#basketTotalCost").fadeOut("slow", function () 
	{
		// Replace amount.
		document.getElementById('basketTotalCost').innerHTML = array[1];
				
		// Make text visible again
		$j("#basketTotalCost").fadeIn("slow");
	});
	
	updateOverallBasketTotal( array[1] );
}

function hideBasketSuccess()
{
	$j("#addToCartConfirmation").slideUp( "slow" );
}

// Adds a specified quantity of a specified product size to the user's shopping basket.

function addToBasket( absolutePath, webRoot )
{
	productPriceIdToQuantity = "";
	
	// Find the product sizes that have a quantity selected.
	divs = $j(".quantity");
	
	// Ignore the first div found because that relates to a table header row.
	for( i = 1; i < divs.length; i++ )
	{
		selectElement = divs[i].getElementsByTagName( 'select' )[0];
		quantity = selectElement.options[selectElement.selectedIndex].value;
		
		if( quantity > 0 )
		{
			array = selectElement.id.split( '~' );
			
			if( productPriceIdToQuantity != "" )
				productPriceIdToQuantity += "|";
			
			productPriceIdToQuantity += array[1] + "~" + quantity;
		}
	}
	
	if( productPriceIdToQuantity == "" )
	{
		alert( "Please select a valid quantity of an item to add to your shopping basket" );
		return;
	}
	else
	{
		url = webRoot + '/includes/AddToBasket.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + 
			'&' + 'productPriceIdToQuantity=' + productPriceIdToQuantity;
		
		callback = 
		{
			success: function(o)
			{
				array = o.responseText.split( '~' );
				message = array[0];
				o.responseText = array[1] + "~" + array[2];
				
				updateShoppingBasketDetails( o.responseText );
				
				document.getElementById( 'addToCartConfirmation' ).innerHTML = message;
				$j("#addToCartConfirmation").slideDown( "slow" );
				setTimeout( hideBasketSuccess, 5000 );
			}
		}
		
		// Get totals for selected category.
		transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	}
}

// Enables an item to be removed from a user's shopping basket.

function removeBasketItem( absolutePath, webRoot, productPriceId )
{
	try
	{
	url = webRoot + '/includes/RemoveBasketItem.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'productPriceId=' + productPriceId;
  	
	callback = 
	{
     	success: function(o)
		{
			$j("#basketItem" + productPriceId).slideUp( "slow", function()
			{
				document.getElementById( "basketItem" + productPriceId ).parentNode.removeChild( document.getElementById( "basketItem" + productPriceId ) );
				
				if( $j(".basketProductRow").length == 1 )
				{
					$j("#shippingRow").fadeOut( "slow", function()
					{
						$j("#emptyBasketRow").fadeIn( "slow", function()
						{
							document.getElementById( 'overallTotal' ).innerHTML = "&pound;0.00";
						});
					});
				}
				
				updateShoppingBasketDetails( o.responseText );
			});
		}
	}
	
	// Get totals for selected category.
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	}
	catch( err )
	{
		alert( err );
	}
}

// Invokes PHP script to add specified product to current user's list of favourities (if user is logged in).

function addToFavourities( absolutePath, webRoot, productId )
{
	url = webRoot + '/includes/AddToFavourities.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'productId=' + productId;
  	
	callback = 
	{
     	success: function(o)
		{
			if( o.responseText == 1 )
			{
				document.getElementById( 'favourities' ).innerHTML = "Added";
			}
		}
	}
	
	// Get totals for selected category.
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// This function adds an image that has been loaded and cached by the browser. Causes AJAX content to be set when
// all images have been loaded.

var loadedImages = new Array();

function addLoadedImage( imageSrc, noImagesToLoad, responseText )
{
	// Another image has been loaded.
	loadedImages.push( imageSrc );
	
	// Check whether all images have been loaded.
	if( loadedImages.length == noImagesToLoad )
	{
		// All image have been loaded. Ok to replace the page content now.
		document.getElementById( "start" ).innerHTML = responseText;
		responseText = "";
	}
}

function addLoadedImage2( imageSrc, noImagesToLoad, responseText )
{
	// Another image has been loaded.
	loadedImages.push( imageSrc );
	
	// Check whether all images have been loaded.
	if( loadedImages.length == noImagesToLoad )
	{
		alert('all done');
		
		// All image have been loaded. Ok to replace the page content now.
		document.getElementById( "start" ).innerHTML = responseText;
	}
}

// Enables product reviews to be iterated over, paginated.

function navigateReviews( absolutePath, webRoot, reviewIdx )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/NavigateReviews.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'reviewIdx=' + reviewIdx;
	
	callback = 
	{
     	success: function(o) 
		{
			document.getElementById( 'reviews' ).innerHTML = o.responseText;
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// This function takes the output from a PHP script containing a list of images to pre-load and page content to
// replace and pre-loads any images before replacing the page content. This causes the page to load smarter because
// the images are already loaded and in place when the page content is changed.

function changePageContentsWithImages()
{
	// The response text comprises a list of images (if any) to preload and the page content to change.
	array = responseText.split('~');
	
	test = responseText2;
	
	images = "";
	mainContent = "";
	
	if( array.length == 4 )
	{
		pageLinks = array[0];
		document.getElementById( 'paginationLinks' ).innerHTML = pageLinks;
		
		images = array[1];
		
		if( array[2] == undefined )
			responseText = test;
		else
			responseText = array[2];
		
		document.getElementById( 'bottomPaginationLinks' ).innerHTML = array[3];
		document.getElementById("bottomPaginationLinks").style.visibility = "visible";
		
		proceedWithImageLoading( images, responseText );
	}
	else
	{
		images = array[0];
		
		if( array[1] == undefined )
		{
			url3 = '/includes/GetResponseText.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
			
			callback3 = 
			{
				success: function(o) 
				{
					url4 = '/includes/GetNextProducts.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath +
						'&' + 'categoryId=' + o.responseText + '&' + 'next=0';
			
					callback4 = 
					{
						success: function(o) 
						{
							responseText = o.responseText;
							array = responseText.split('~');
							
							images = array[0];
							responseText = array[1];
							
							proceedWithImageLoading( images, responseText );
						}
					}
			
					transaction4 = YAHOO.util.Connect.asyncRequest('GET', url4, callback4, null);
				}
			}
			
			transaction3 = YAHOO.util.Connect.asyncRequest('GET', url3, callback3, null);
		}
		else
		{
			responseText = array[1];
			proceedWithImageLoading( images, responseText );
		}
	}
}

function proceedWithImageLoading( images, responseText )
{
	// Get the images to pre-load and work out how many need to be pre-loaded. noImagesToPreload and 
	// loadedImages are global variables.
	imageArray = images.split(',');
	noImagesToLoad = imageArray.length;
	
	loadedImages = new Array();
	
	// If there is at least one valid image to load.
	//if( preloadImages == undefined || preloadImages == 1 && noImagesToLoad > 0 && imageArray[0] !== undefined && imageArray[0].length > 0 )
	//{
		// For each image to load create an image object and then load the image. Once loading is complete
		// call the addLoadedImage function to acknowledge this and check whether all images have been loaded.
		//alert( noImagesToLoad );
		
		for( i = 0; i < noImagesToLoad; i++ )
		{
			// Create new image.
			var _image = new Image();
			
			currentPage = window.location.href;
			currentPage = currentPage.substring( 0, currentPage.indexOf( '/shop' ) );
			
			_image.src = currentPage + '/downloads/product_photos/' + imageArray[i];
			_image.id = 'newImageId' + i;
					
			// Load image so it will appear on the page straight away when the page contents is changed.
			/*$j(_image).load( function() 
			{
				// The image has been loaded by the browser. Add the image to a list of loaded images and
				// check whether all images to load have been loaded. Only once all image have been loaded
				// is the page content replaced.
				addLoadedImage( _image.src, noImagesToLoad, responseText );
			});*/
			
			$j( function()
			{
  				// Create new image.
				var _image = new Image();
				_image.src = currentPage + "/downloads/product_photos/" + imageArray[i];
				_image.id = 'newImageId' + i;
					
  				//$j(_image).load( function()
				//{
  					addLoadedImage( _image.src, noImagesToLoad, responseText );
					//alert('Image Loaded');
    			//})
    
				// if there was an error loading the image, react accordingly
    			/*.error( function() 
				{
      				// notify the user that the image could not be loaded
					alert( "Couldn't load " + _image.src );
    			})*/
			});
		}
	/*}
	else
	{
		// There are no images to preload so we can change the page contents immediately.
		document.getElementById( "start" ).innerHTML = responseText;
	}*/
}

function changePageContentsWithImages2( responseText, preloadImages )
{
	// The response text comprises a list of images (if any) to preload and the page content to change.
	array = responseText.split('~');
	
	images = "";
	mainContent = "";
	
	if( array.length == 4 )
	{
		pageLinks = array[0];
		document.getElementById( 'paginationLinks' ).innerHTML = pageLinks;
		
		images = array[1];
		responseText = array[2];
		
		document.getElementById( 'bottomPaginationLinks' ).innerHTML = array[3];
		document.getElementById("bottomPaginationLinks").style.visibility = "visible";
	}
	else
	{
		images = array[0];
		responseText = array[1];
	}
	
	// Get the images to pre-load and work out how many need to be pre-loaded. noImagesToPreload and 
	// loadedImages are global variables.
	imageArray = images.split(',');
	noImagesToLoad = imageArray.length;
	
	loadedImages = new Array();
	
	// If there is at least one valid image to load.
	/*if( preloadImages == 1 && noImagesToLoad > 0 && imageArray[0] !== undefined && imageArray[0].length > 0 )
	{
		// For each image to load create an image object and then load the image. Once loading is complete
		// call the addLoadedImage function to acknowledge this and check whether all images have been loaded.
		//alert( noImagesToLoad );
		
		for( i = 0; i < noImagesToLoad; i++ )
		{
			// Create new image.
			var _image = new Image();
			
			currentPage = window.location.href;
			currentPage = currentPage.substring( 0, currentPage.indexOf( '/shop' ) );
			
			_image.src = currentPage + '/downloads/product_photos/' + imageArray[i];
			_image.id = 'newImageId' + i;
					
			// Load image so it will appear on the page straight away when the page contents is changed.
			/*$j(_image).load( function() 
			{
				// The image has been loaded by the browser. Add the image to a list of loaded images and
				// check whether all images to load have been loaded. Only once all image have been loaded
				// is the page content replaced.
				addLoadedImage( _image.src, noImagesToLoad, responseText );
			});*/
			
			/*$j( function()
			{
  				// Create new image.
				var _image = new Image();
				_image.src = currentPage + "/downloads/product_photos/" + imageArray[i];
				_image.id = 'newImageId' + i;
					
  				//$j(_image).load( function()
				//{
  					addLoadedImage2( _image.src, noImagesToLoad, responseText );
					//alert('Image Loaded');
    			//})
    
				// if there was an error loading the image, react accordingly
    			/*.error( function() 
				{
      				// notify the user that the image could not be loaded
					alert( "Couldn't load " + _image.src );
    			})
			});
		}
	}
	else
	{*/
		// There are no images to preload so we can change the page contents immediately.
		document.getElementById( "start" ).innerHTML = responseText;
	//}
}

// Pagination function invoking PHP script to get next or previous sub categories.

function getNextCategories( absolutePath, webRoot, categoryId, next, boolPreloadImages )
{
	divs = document.getElementsByTagName( "div" );
	
	hideContentToChange();
	
	if( document.getElementById( "root_" + categoryId ) != null )
	{
		listItem = document.getElementById( "root_" + categoryId );
		
		listItems = listItem.getElementsByTagName( "li" );
		
		for( i = 0; i < listItems.length; i++ )
		{
			listItemLink = listItems[i].getElementsByTagName( 'a' )[0];
			
			if( listItemLink.className == "activeCategory" )
			{
				listItemLink.className = "lowest";
				listItemLink.style.color = "#ffffff";
			}
		}
	}
	else
	{
		divs = $j(".activeCategory");
		
		for( i = 0; i < divs.length; i++ )
		{
			divs[i].className = "lowest";
			divs[i].style.color = "#ffffff";
		}
	}
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/GetNextCategories.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'categoryId=' + categoryId + '&' + 'next=' + next;
	
	brandValue = document.getElementById( 'brand' ).options[document.getElementById( 'brand' ).selectedIndex].value;

	if( brandValue != "-----" )
		url += '&' + 'manufacturer=' + brandValue;
		
	callback = 
	{
     	success: function(o) 
		{
			categoryResponse = o.responseText;
			responseText = categoryResponse;
			responseText2 = categoryResponse;
			
			//if( categoryId == "0048" )
				//alert( responseText );
			
			preloadImages = 1;
			
			if( boolPreloadImages !== undefined )
				preloadImages = boolPreloadImages;
			
			if( preloadImages == 1 )
			{
				url2 = "";
	
				if( webRoot.length != 0 )
					url2 += webRoot;
		
				url2 += '/includes/PreloadImage.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + 
					'&' + 'categoryId=' + categoryId;
	
				callback2 = 
				{
     				success: function(o) 
					{
						preloadImages = o.responseText;
						
						//responseText = categoryResponse;
						
						// Use the following function to change page content because the page content may contain 
						// images that should be pre-loaded.
						//changePageContentsWithImages( categoryResponse, preloadImages );
					}
				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url2, callback2, null);
			}
			else
			{
				responseText = categoryResponse;
				responseText2 = categoryResponse;
				// Use the following function to change page content because the page content may contain images 
				// that should be pre-loaded.
				//changePageContentsWithImages( categoryResponse, preloadImages );
			}
			
			url3 = '/includes/StoreResponseText.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
				'categoryId=' + categoryId;
	
			callback3 = 
			{
			}
			
			transaction3 = YAHOO.util.Connect.asyncRequest('GET', url3, callback3, null);
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Pagination function invoking PHP script to get next or previous products.

function getNextProducts( absolutePath, webRoot, categoryId, next, manufacturerSelect )
{
	if( manufacturerSelect == undefined )
		manufacturerSelect = 0;
		
	url3 = '/includes/StoreResponseText.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'categoryId=' + categoryId;
	
	callback3 = 
	{
		success: function(o) 
		{
			// Call function to hide content to change.
			hideContentToChange();
		
			listItem = document.getElementById( categoryId );
			
			if( listItem != null )
			{
				listItemLink = listItem.getElementsByTagName( 'a' )[0];
				listItemLink.className = "active";
				listItemInnerHTML = listItem.innerHTML;
				
				unorderedList = document.getElementById( categoryId ).parentNode;
				unorderedListClassName = unorderedList.className;
				
				/*listItems = unorderedList.getElementsByTagName( 'li' );
				
				for( i = 0; i < listItems.length; i++ )
				{
					if( listItems[i].id != categoryId && listItems[i].parentNode.className == unorderedListClassName )
					{
						listItemLink = listItems[i].getElementsByTagName( 'a' )[0];
						listItemLink.className = "lowest";
					}
				}*/
			}
			else
			{
				if( manufacturerSelect == 0 )
				{
					listItemsLinks = document.getElementsByTagName( "a" );
				
					for( i = 0; i < listItemsLinks.length; i++ )
					{
						if( listItemsLinks[i].className == "activeCategory" )
						{
							listItemsLinks[i].className = "lowest";
							listItemLink.style.color = "#ffffff";
						}
					}
				}
				
				listItem = "";
				idsToIgnore = new Array();
				
				if( document.getElementById( "root_" + categoryId ) != null )
				{
					listItem = document.getElementById( "root_" + categoryId );
					
					listItems = document.getElementsByTagName( "li" );
					
					for( i = 0; i < listItems.length; i++ )
					{
						if( listItems[i].id.indexOf( "root_" ) != -1 && listItems[i].className == "activeCategory" )
						{
							listItemLink = listItems[i].getElementsByTagName( 'a' )[0];
							listItemLink.className = "lowest";
							listItemLink.style.color = "#ffffff";
						}
					}
				}
				else if( document.getElementById( "level1_" + categoryId ) != null )
					listItem = document.getElementById( "level1_" + categoryId );
				else if( document.getElementById( "level2_" + categoryId ) != null )
				{
					listItem = document.getElementById( "level2_" + categoryId );
					idsToIgnore.push( listItem.parentNode.parentNode.id );
					idsToIgnore.push( listItem.parentNode.parentNode.parentNode.parentNode.id );
				}
				
				divs = $j(".open");
				
				for( i = 0; i < divs.length; i++ )
				{
					idMatch = 0;
					
					for( j = 0; j < idsToIgnore.length; j++ )
					{
						if( idsToIgnore[j] == divs[i].parentNode.id )
							idMatch = 1;
					}
					
					if( !idMatch )
						$j( divs[i] ).removeClass( "open" );
				}
				
				if( listItem != "" )
				{
					listItemLink = listItem.getElementsByTagName( 'a' )[0];
					listItemLink.className = "activeCategory";
					listItemLink.style.color = "#fd6617";
				}
			}
			
			url = "";
			
			if( webRoot.length != 0 )
				url += webRoot;
				
			if( $j(".activeCategory").length > 0 )
			{
				array = $j(".activeCategory").parent().attr('id').split( '_' );
				categoryId = array[1];
			}
			
			url += '/includes/GetNextProducts.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
				'categoryId=' + categoryId + '&' + 'next=' + next;
			
			brandValue = document.getElementById( 'brand' ).options[document.getElementById( 'brand' ).selectedIndex].value;
		
			if( brandValue != "-----" )
				url += '&' + 'manufacturer=' + brandValue;
				
			callback = 
			{
				success: function(o) 
				{
					preloadImages = 1;
					
					categoryResponse = o.responseText;
					responseText = categoryResponse;
					responseText2 = categoryResponse;
					
					//if( categoryId == "0052" )
					//	alert( responseText );
						
					url2 = "";
			
					if( webRoot.length != 0 )
						url2 += webRoot;
				
					url2 += '/includes/PreloadImage.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + 
						'&' + 'categoryId=' + categoryId;
			
					callback2 = 
					{
						success: function(o) 
						{
							preloadImages = o.responseText;
							
							//responseText = categoryResponse;
							//responseText2 = categoryResponse;
							
							// Use the following function to change page content because the page content may contain 
							// images that should be pre-loaded.
							//changePageContentsWithImages( categoryResponse, preloadImages );
						}
					}
				}
			} 
				
			transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
		}
	}
			
	transaction3 = YAHOO.util.Connect.asyncRequest('GET', url3, callback3, null);
}

// Stores the rating selected by the user for the specified product.

function rateProduct( absolutePath, webRoot )
{
	// Get rating selected by user.
	rating = $j(".star-rating-on").length;
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/RateProduct.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'rating=' + rating;
	
	callback = 
	{
     	success: function(o) 
		{
			// Indicate that the product has been rated and remove the link that enables a product to be rated.
			// This is to prevent a product from being re-rated by the same user.
			document.getElementById( 'rateProduct' ).innerHTML = "Rated";
			document.getElementById( 'rateProduct' ).href = "";
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Enables the search form to be submitted by pressing the return key.

function submitSearchForm( e, absolutePath, webRoot )
{
	var unicode=e.keyCode? e.keyCode : e.charCode

	if( unicode == 13 )
		document.getElementById( 'searchForm' ).submit();
}

// Causes the specified team product to be displayed.

function getTeamProduct( absolutePath, webRoot )
{
	// Call function to hide content to change.
	hideContentToChange();
		
	// Construct URL to PHP script for filterin search results.
	url = webRoot + '/includes/GetTeamProduct.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	// Determine which product has been selected.
	activeSearchFilters = $j(".activeSearchFilter");
		
	for( i = 0; i < activeSearchFilters.length; i++ )
	{
		temp = activeSearchFilters[i].id.split( '~' );
		url += "&" + temp[0] + "=" + temp[1];
	}
		
	// Determine what price restriction the user has enforced. Again add to URL so it is available to PHP script.
	price = document.getElementById( 'amount' ).innerHTML;
	url += "&price=" + price.substring( 1, price.length );
		
	callback = 
	{
		success: function(o) 
		{
			// Store new content.
			responseText = o.responseText;
		}
	} 
			
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Causes the team products matching price range to be displayed.

function getTeamProducts( absolutePath, webRoot )
{
	// Call function to hide content to change.
	hideContentToChange();
		
	// Construct URL to PHP script for filterin search results.
	url = webRoot + '/includes/GetTeamProducts.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
			
	// Determine what price restriction the user has enforced. Again to URL so it is available to PHP script.
	price = document.getElementById( 'amount' ).innerHTML;
	url += "&price=" + price.substring( 1, price.length );
		
	callback = 
	{
		success: function(o) 
		{
			// Store new content.
			responseText = o.responseText;
		}
	} 
			
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Displays the details of selected product.

function getProduct( absolutePath, webRoot, id )
{
	// Call function to hide content to change.
	hideContentToChange();
		
	url = webRoot + '/includes/GetProduct.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 'id=' + id;
	
	callback = 
	{
		success: function(o) 
		{
			//alert( o.responseText );
			
			// Store new content.
			responseText = o.responseText;
		}
	} 
			
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Enables the current search results to be filtered to contain more specific search results.

function filterSearchResults( absolutePath, webRoot )
{
	// Call function to hide content to change.
	hideContentToChange();
		
	// Construct URL to PHP script for filterin search results.
	url = webRoot + '/includes/FilterSearchResults.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	// Determine what active filters (if any) have been applied to the page and add the details of these to the URL.
	activeSearchFilters = $j(".activeSearchFilter");
		
	for( i = 0; i < activeSearchFilters.length; i++ )
	{
		temp = activeSearchFilters[i].id.split( '~' );
		url += "&" + temp[0] + "=" + temp[1];
	}
		
	// Determine what price restriction the user has enforced. Again add to URL so it is available to PHP script.
	price = document.getElementById( 'amount' ).innerHTML;
	url += "&price=" + price.substring( 1, price.length );
		
	callback = 
	{
		success: function(o) 
		{
			// Store new content.
			responseText = o.responseText;
		}
	} 
			
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Caused old content to be hidden whilst content is changing. New content will be loaded to replace the old but
// this will be hidden from the user.

function hideContentToChange()
{
	// Set to true when all content to change has successfully been hidden.
	startProgressBar = 0;
	
	if( window.location.href.indexOf( 'Search.php' ) != -1 )
	{
		if( document.getElementById( 'start' ) != null )
		{
			numProductRows = $j(".productsRow").length;
			
			rowCount = 0;
			
			// First hide the pagination links until the new content has been loaded.
			$j(".productsRow").fadeOut("fast", function() 
			{
				rowCount++;
				
				if( rowCount == numProductRows )
				{
					document.getElementById( "paginationLinks" ).style.visibility = "hidden";
					document.getElementById( "bottomPaginationLinks" ).style.visibility = "hidden";
					
					var ScrollTop = document.body.scrollTop;

					if( ScrollTop == 0 )
					{
						if( window.pageYOffset )
							ScrollTop = window.pageYOffset;
						else
							ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
					}
							
					if( ScrollTop != 0 )
						document.getElementById( 'progressBarContainerCentre' ).style.marginTop = ScrollTop + "px";
					else
						document.getElementById( 'progressBarContainerCentre' ).style.marginTop = "350px";
								
					// Ready to display progress bar. All content to change has been hidden, ready for change.
					startProgessBar( "progressbar" );
				}
			});
		}
	}
	else
	{
		if( document.getElementById( 'bottomPageinationHeightSpacer' ) != null )
		{
			// First hide the pagination links until the new content has been loaded.
			document.getElementById("bottomPageinationHeightSpacer").style.display = "none";
			document.getElementById("bottomPaginationLinks").style.display = "none";
			// Ready to display progress bar. All content to change has been hidden, ready for change.
			
			startProgessBar( "progressbar" );
		}
	}
}

// Caused new content to be displayed after clicking a pagination link or performing a search and the content
// changing.

function showChangedContent()
{
	// Check whether new content is available.
	if( responseText != "" )
	{
		// Change content on the page.
		array = responseText.split('~');
		pageLinks = array[0];
		mainContent = array[1];
		
		document.getElementById( 'topEachPageLink' ).innerHTML = pageLinks;
		document.getElementById( 'start' ).innerHTML = mainContent;
		
		// Display the new products.
		$j(".productsRow").fadeIn("slow");
	
		// Re-display the pagination links.
		$j("#paginationLinks").show();
		
		// Re-initialise responseText so content can be changed again when/if necessary.
		responseText = "";
	}
}

// Holds the percentage of the progress bar loaded.
var pct = 0;

// Holds the identifier associated with the updateProgressBar event. The event that causes this function to be
// invoked by a timer after a specific interval.
var handle = 0;

// Is called after time delay to increment progress bar percentage. After progress bar completes calls function
// to display content.

function updateProgressBar( idName )
{
	// Increment the progress bar percentage.
	$j("#progressbar").reportprogress( ++pct );
    
	// Check if the progress bar is complete.
	if( pct == 100 )
	{
		// Progress bar is complete so stop this function from being called to update percentages.
    	clearInterval( handle );
		
		// Reset the percentage figure now that the progress bar is complete.
		pct = 0;
		
		// Hide the progress bar and when this is complete show the new content.
		document.getElementById('progressBarContainerCentre').style.display = "none";
		document.getElementById('progressbar').style.display = "none";
		// Only display the new content when the progress bar has completely vanished from view.
		// Hence the use of the callback function from the hide function.
		
		changePageContentsWithImages( responseText, '1' );
	}
}

// Initialise and display the progress bar.

function startProgessBar( idName )
{
	// Display the progress bar.
	document.getElementById( 'progressBarContainerCentre' ).style.display = "";
	document.getElementById( 'progressbar' ).style.display = "";	
	// Set the percentage to zero.
	$j("#progressbar").reportprogress(0);
	// Set up timer to cause progress bar to be updated by a percentage every 30 milliseconds.
	
	handle = setInterval( "updateProgressBar('progressBar')", 30 );
}

// Get the next or previous page of search results taking into consideration any filter and sorting applied to the
// page.

function getNextSearchResults( absolutePath, webRoot, next )
{
	// Call function to hide content to change.
	hideContentToChange();
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/GetNextSearchResults.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'next=' + next;
	
	// Has the user chosen to order/sort the results.
	order = document.getElementById( 'sortBy' ).options[document.getElementById( 'sortBy' ).selectedIndex].value;

	if( order != "-----" )
		url += '&' + 'order=' + order;
		
	callback = 
	{
     	success: function(o) 
		{
			responseText = o.responseText;
			//changePageContentsWithImages( o.responseText, '1' );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function getNextSearchResults2( absolutePath, webRoot, next )
{
	// Call function to hide content to change.
	hideContentToChange();
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/GetNextSearchResults2.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'next=' + next;
	
	// Has the user chosen to order/sort the results.
	order = document.getElementById( 'sortBy' ).options[document.getElementById( 'sortBy' ).selectedIndex].value;

	if( order != "-----" )
		url += '&' + 'order=' + order;
		
	callback = 
	{
     	success: function(o) 
		{
			responseText = o.responseText;
			//changePageContentsWithImages( o.responseText, '1' );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Gets all the product sizes of a selected product, available in a selected size.

function getProductDetailSizes( absolutePath, webRoot )
{
	colour = document.getElementById( 'colour' ).options[document.getElementById( 'colour' ).selectedIndex].value;
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/GetProductDetailSizes.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'colour=' + colour;
	
	callback = 
	{
     	success: function(o) 
		{
			if( document.getElementById( 'detailsTableHeader' ).style.display == "none" )
			{
				document.getElementById( 'start' ).innerHTML = o.responseText;
				
				$j("#detailsTableHeader").slideDown("slow", function()
				{
					$j("#start").slideDown("slow");
					
					$j(".unAvailable").easyTooltip
					({
						content: '<p>Out of Stock. Click link to receive notification email when it becomes available.</p>'
					});
				});
			}
			else
			{
				$j(".detailsTableRow").slideUp("slow", function()
				{
					document.getElementById( 'start' ).innerHTML = o.responseText;
					$j(".detailsTableRow").slideDown("slow");
					
					$j(".unAvailable").easyTooltip
					({
						content: '<p>Out of Stock. Click link to receive notification email when it becomes available.</p>'
					});
				});
			}
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function executeFunctionsOnShadowboxClose()
{
	url = '/includes/ExecuteFunctionsOnShadowboxClose.php';
	
	callback = 
	{
     	success: function(o) 
		{
			if( o.responseText != "" )
			{
				functions = o.responseText.split( '|' );
				
				for( i = 0; i < functions.length; i++ )
				{
					functions[i] = functions[i].replace( /\\/g, "" );
					eval( functions[i] );
				}
			}
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function displayLoggedInMessage()
{
	url = '/includes/GetLoggedInMessage.php';
	
	callback = 
	{
     	success: function(o) 
		{
			document.getElementById( 'welcome' ).style.display = "";
			document.getElementById( 'loginSuccessMessage' ).innerHTML = o.responseText;
			
			$j("#loginSuccessMessage").slideDown("slow", function()
			{
				document.getElementById( 'myAccountLink' ).href = "/members/MyAccount.php";
			});
		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Adds specified product to logged in user's list of favourites.

function addToFavourites( absolutePath, webRoot, productId )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/IsLoggedIn.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	callback = 
	{
     	success: function(o) 
		{
			if( o.responseText == 1 )
			{
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
				
				url += '/includes/AddToFavourites.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + 
					'&' + 'productId=' + productId;
	
				callback2 = 
				{
     				success: function(o) 
					{
						if( o.responseText == 1 )
							alert( "Product added to your list of favourites" );
			
						if( o.responseText == 0 )
							alert( "Product already in your list of favourites" );
			
						$j("#addToFavourites").slideUp("slow");
					}
  				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback2, null);
			}
			else
			{
				array = new Array();
				array.push( "addToFavourites( '" + absolutePath + "','" + webRoot + "','" + productId + "');" );
				array.push( "displayLoggedInMessage();" );
				
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
		
				url += '/includes/StoreFunctionsToExecute.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
					absolutePath + '&' + 'functionsToExecute=' + array.join( "|" ) + '&' + 'requiresLogin=1';
	
				callback2 = 
				{
     				success: function(o) 
					{
						frontEndLogIn( absolutePath, webRoot );
					}
				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback2, null);
			}
		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Enables the order of the search results products to be changed.

function sortSearchResults( absolutePath, webRoot, next )
{
	hideContentToChange();
	
	// Get the chosen sort order.
	order = document.getElementById( 'sortBy' ).options[document.getElementById( 'sortBy' ).selectedIndex].value;
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	// Sort the products.
	url += '/includes/SortSearchResults.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'order=' + order;
	
	callback = 
	{
     	success: function(o) 
		{
			responseText = o.responseText;
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Changes the main image on a product detail page to the one that the user clicked.

function changeImage( num )
{
	document.getElementById("productLargeImage").style.background = "url(.." + largeImages[num] + ")";
}

function frontEndLogIn( absolutePath, webRoot, teamLogin )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
	
	if( teamLogin != undefined )
		url += "/members/Login.php?teamLogin=1";
	else
		url += "/members/Login.php";
	
	openShadowbox( 'iframe', url, 157, 175 );
}

function submitReview( absolutePath, webRoot )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/IsLoggedIn.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	callback = 
	{
     	success: function(o) 
		{
			if( o.responseText == 1 )
			{
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
	
				url += "/shop/SubmitReview.php";
				openShadowbox( 'iframe', url, 202, 228 );
			}
			else
			{
				array = new Array();
				array.push( "submitReview( '" + absolutePath + "','" + webRoot + "');" );
				array.push( "displayLoggedInMessage();" );
				
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
		
				url += '/includes/StoreFunctionsToExecute.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
					absolutePath + '&' + 'functionsToExecute=' + array.join( "|" ) + '&' + 'requiresLogin=1';
	
				callback2 = 
				{
     				success: function(o) 
					{
						frontEndLogIn( absolutePath, webRoot );
					}
				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback2, null);
			}
		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function emailAFriend( absolutePath, webRoot )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
	
	url += "/shop/EmailAFriend.php";
	
	openShadowbox( 'iframe', url, 136, 340 );
}

function checkLogin( absolutePath, webRoot )
{
	array = new Array();
	array.push( "displayLoggedInMessage();" );
				
	url2 = "";
	
	if( webRoot.length != 0 )
		url2 += webRoot;
		
	url2 += '/includes/StoreFunctionsToExecute.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
		absolutePath + '&' + 'functionsToExecute=' + array.join( "|" ) + '&' + 'requiresLogin=1';
	
	callback2 = 
	{
     	success: function(o) 
		{
			url = "";
	
			if( webRoot.length != 0 )
				url += webRoot;
				
			email = document.getElementById( 'email' ).value;
			password = document.getElementById( 'password' ).value;
			
			url += '/includes/CheckLogin.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath +
				'&' + 'email=' + email + '&' + 'password=' + password;
			
			callback = 
			{
				success: function(o) 
				{
					array = o.responseText.split( "~" );
					
					success = array[0];
					accountType = array[1];
					
					if( success == 0 )
						alert( "Login unsuccessful. Please register or use forgotten password facility" );
					else
					{
						href = parent.window.location.href;
						idxHREF = href.indexOf( 'www' );
						idxFirstSlash = href.indexOf( '/', idxHREF );
						idxLastSlash = parent.window.location.href.lastIndexOf( '/' );
						
						if( idxFirstSlash == idxLastSlash )
						{
							if( accountType == "customer" )
							{
								myAccountLink = webRoot + "/members/MyAccount.php";
								parent.window.location.href = myAccountLink;
							}
							else
							{
								teamPageLink = webRoot + "/shop/Team.php";
								parent.window.location.href = teamPageLink;
							}
						}
						else
							parent.Shadowbox.close();
					}
				}
			} 
				
			transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url2, callback2, null);
}

function forgottenPassword( absolutePath, webRoot )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	email = document.getElementById( 'email' ).value;
	
	if( email.length == 0 )
	{
		alert( "Please provide the email address of your account" );
		return;
	}
	
	url += '/includes/ForgottenPassword.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath +
		'&' + 'email=' + email;
	
	callback = 
	{
     	success: function(o) 
		{
			success = o.responseText;
			
			if( success == 0 )
				alert( "An account could not be found for the email address specified" );
			else
				alert( "Your password has been reset and emailed" );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function addEmailReminder( absolutePath, webRoot, productPriceId )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/IsLoggedIn.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	callback = 
	{
     	success: function(o) 
		{
			if( o.responseText == 1 )
			{
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
				
				url += '/includes/AddEmailReminder.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + 
					'&' + 'productPriceId=' + productPriceId;
	
				callback2 = 
				{
     				success: function(o) 
					{
						alert( "Email reminder added" );
					}
  				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback2, null);
			}
			else
			{
				array = new Array();
				array.push( "addEmailReminder( '" + absolutePath + "','" + webRoot + "','" + productPriceId + "');" );
				array.push( "displayLoggedInMessage();" );
				
				url = "";
	
				if( webRoot.length != 0 )
					url += webRoot;
		
				url += '/includes/StoreFunctionsToExecute.php?webRoot=' + webRoot + '&' + 'absolutePath=' + 
					absolutePath + '&' + 'functionsToExecute=' + array.join( "|" ) + '&' + 'requiresLogin=1';
	
				callback2 = 
				{
     				success: function(o) 
					{
						frontEndLogIn( absolutePath, webRoot );
					}
				}
				
				transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback2, null);
			}
		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function getEmbroideryDetails( absolutePath, webRoot, productPriceId )
{
	selectedIndex = document.getElementById( "embroidery" + productPriceId ).options
		[document.getElementById( "embroidery" + productPriceId ).selectedIndex].value;
		
	if( selectedIndex == "Yes" )
		$j( "#embroideryHeader" + productPriceId ).slideDown( "slow" );
	else
	{
		$j( "#embroideryHeader" + productPriceId ).slideUp( "slow" );
		updateBasketItem( absolutePath, webRoot, productPriceId )
	}
}

function getShirtPrintingDetails( absolutePath, webRoot, productPriceId )
{
	selectedIndex = document.getElementById( "printing" + productPriceId ).options
		[document.getElementById( "printing" + productPriceId ).selectedIndex].value;
		
	if( selectedIndex == "Yes" )
	{
		$j( "#nameHeader" + productPriceId ).slideDown( "slow" );
		$j( "#numberHeader" + productPriceId ).slideDown( "slow" );
	}
	else
	{
		$j( "#nameHeader" + productPriceId ).slideUp( "slow" );
		$j( "#numberHeader" + productPriceId ).slideUp( "slow" );
	}
}

function signOut( absolutePath, webRoot )
{
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/SignOut.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
	
	callback = 
	{
     	success: function(o) 
		{
			$j(".welcome").slideUp("slow", function()
			{
				document.getElementById( 'myAccountLink' ).href = "javascript:frontEndLogIn('" + absolutePath +
					"','" + webRoot + "')";
				
				if( window.location.href.indexOf( 'MyAccount' ) != -1 )
					window.location.href = "/index.php";
			});
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function showHidePrintingOptions( linkIdName, productPriceId )
{
	rootDiv = document.getElementById( linkIdName + productPriceId ).parentNode.parentNode;
	divs = rootDiv.getElementsByTagName( "div" );
	
	for( i = 0; i < divs.length; i++ )
	{
		if( divs[i].id == "printingDetails" )
		{
			$j(divs[i]).slideToggle( "slow" );
		
			if( document.getElementById("cancelShowPrintingStatus" + productPriceId).className == "no" )
				document.getElementById("cancelShowPrintingStatus" + productPriceId).className = "yes";
			else
				document.getElementById("cancelShowPrintingStatus" + productPriceId).className = "no";
		}
	}
}

function showHideEmbroideryOptions( linkIdName, productPriceId )
{
	rootDiv = document.getElementById( linkIdName + productPriceId ).parentNode.parentNode;
	divs = rootDiv.getElementsByTagName( "div" );
	
	for( i = 0; i < divs.length; i++ )
	{
		if( divs[i].id == "embroideryDetails" )
		{
			$j(divs[i]).slideToggle( "slow" );
		
			if( document.getElementById("cancelShowEmbroideryStatus" + productPriceId).className == "no" )
				document.getElementById("cancelShowEmbroideryStatus" + productPriceId).className = "yes";
			else
				document.getElementById("cancelShowEmbroideryStatus" + productPriceId).className = "no";
			
			document.getElementById("embroideryCopy" + productPriceId).value = "";
		}
	}
}

function changeEmailAddress( absolutePath, webRoot )
{
	emailAddress = document.getElementById( 'email' ).value;
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/ChangeEmailAddress.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'email=' + emailAddress;
		
	callback = 
	{
     	success: function(o) 
		{
			alert( "Email address successfully changed" );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function changePassword( absolutePath, webRoot )
{
	newPassword = document.getElementById( 'newPassword' ).value;
	newPassword2 = document.getElementById( 'newPassword2' ).value;
	
	if( newPassword != newPassword2 )
	{
		alert( "Password do not match" );
		return;
	}
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/ChangePassword.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'newPassword=' + newPassword;
		
	callback = 
	{
     	success: function(o) 
		{
			alert( "Logon password successfully changed" );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function submitToPayPal( absolutePath, webRoot )
{
	divs = $j(".basketProductRow");
	
	for( i = 0; i < divs.length; i++ )
	{
		if( divs[i].id != "emptyBasketRow" )
		{
			id = divs[i].id.substring( 10, divs[i].id.length );
			
			itemNo = i;
			itemNo++;
			
			document.getElementById( 'desc' + id ).innerHTML = 
				document.getElementById( 'desc' + id ).innerHTML.replace( /<BR>/g, '. ', document.getElementById( 'desc' + id ).innerHTML );
			
			document.getElementById( 'desc' + id ).innerHTML = 
				document.getElementById( 'desc' + id ).innerHTML.replace( /<br>/g, '. ', document.getElementById( 'desc' + id ).innerHTML );
			
			document.getElementsByName( 'item_name_' + itemNo )[0].value = document.getElementById( 'desc' + id ).innerHTML;
		}
	}
	
	if( document.getElementById( 'postage' ) != null )
	{
		deliveryPriceVal = document.getElementById( 'postage' ).options
			[document.getElementById( 'postage' ).selectedIndex].value;
	
		if( deliveryPriceVal == "-----" )
		{
			alert( "Please select a delivery option" );
			return;
		}
	}
	
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/CreateOrder.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'postage=' + deliveryPriceVal;
		
	callback = 
	{
     	success: function(o) 
		{
			orderId = o.responseText;
			
			if( orderId != -1 )
			{
				document.getElementById( 'handling_cart' ).value = deliveryPriceVal;
				document.getElementById( 'notify_url' ).value += "?orderId=" + orderId;
				document.paymentForm.submit();
			}
			else
				return;
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function updateBasketItem( absolutePath, webRoot, productPriceId )
{
	shirtName = "";
	shirtNumber = "";
	embroideryCopy = "";
		
	url = "";
	
	if( webRoot.length != 0 )
		url += webRoot;
		
	url += '/includes/UpdateBasketItem.php?webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 
		'productPriceId=' + productPriceId;
	
	quantityVal = document.getElementById( "quantity" + productPriceId ).value;
	
	if( quantityVal != null )
		url += '&' + 'quantity=' + quantityVal;
	
	embroidery = 0;
	
	selectElement = document.getElementById( "embroideryCopy" + productPriceId );
	
	if( document.getElementById( "embroideryCopy" + productPriceId ) != null )
	{
		embroideryCopy = document.getElementById( "embroideryCopy" + productPriceId ).value;
	
		if( embroideryCopy.length > 0 )
		{
			url += '&' + 'embroideryCopy=' + embroideryCopy;
			embroidery = 1;
		}
	}
	
	shirt = 0;
	
	if( document.getElementById( "shirtName" + productPriceId ) != null )
	{
		shirtName = document.getElementById( "shirtName" + productPriceId ).value;
		
		if( shirtName.length > 0 )
		{
			url += '&' + 'shirtName=' + shirtName;
			shirt = 1;
	
			if( document.getElementById( "shirtNumber" + productPriceId ) != null )
			{	
				shirtNumber = document.getElementById( "shirtNumber" + productPriceId ).value;
				url += '&' + 'shirtNumber=' + shirtNumber;
				shirt = 1;
			}
		}
	}
	
	callback = 
	{
     	success: function(o) 
		{
			array = o.responseText.split( '~' );
			
			newQuantity = array[0];
			subTotal = array[1];
			
			document.getElementById( 'quantity_' + productPriceId ).value = newQuantity;
			
			$j("#subTotal" + productPriceId).fadeOut( "slow", function()
			{
				document.getElementById( 'subTotal' + productPriceId ).innerHTML = subTotal;
				$j("#subTotal" + productPriceId).fadeIn( "slow" );
			});
			
			o.responseText = array[2] + "~" + array[3];
			
			if( embroidery == 1 )
			{
				$j("#cancelShowEmbroideryStatus" + productPriceId).fadeOut( "slow", function()
				{
					$j("#cancelShowEmbroideryStatus" + productPriceId).removeClass("no").addClass("yes");
						
					$j("#cancelShowEmbroideryStatus" + productPriceId).fadeIn( "slow", function()
					{
						updateShoppingBasketDetails( o.responseText );
						//showHideEmbroideryOptions('showHideEmbroidery',productPriceId);
					});
				});
				
				document.getElementById( "desc" + productPriceId ).innerHTML += "<br />Embroidery: " +
					embroideryCopy;
				
				showHideEmbroideryOptions( 'showHideEmbroidery', productPriceId );
			}
			
			if( shirt == 1 )
			{
				$j("#cancelShowPrintingStatus" + productPriceId).fadeOut( "slow", function()
				{
					$j("#cancelShowPrintingStatus" + productPriceId).removeClass("no").addClass("yes");
						
					$j("#cancelShowPrintingStatus" + productPriceId).fadeIn( "slow", function()
					{
						updateShoppingBasketDetails( o.responseText );
						//showHideEmbroideryOptions('showHideEmbroidery',productPriceId);
					});
				});
				
				document.getElementById( "desc" + productPriceId ).innerHTML += "<br />Shirt Name: " +
					shirtName + " " + "<br />Shirt Number: " + shirtNumber;
				
				showHidePrintingOptions( 'showHidePrinting', productPriceId );
			}
			
			updateShoppingBasketDetails( o.responseText );
		}
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

function updateOverallBasketTotal( basketTotal )
{
	if( basketTotal === undefined )
		basketTotal = document.getElementById( 'basketTotalCost' ).innerHTML.replace( /,/, '' );
	
	totalVal = 0;
	
	if( document.getElementById( 'postage' ) != null )
	{
		deliveryPriceVal = document.getElementById( 'postage' ).options
			[document.getElementById( 'postage' ).selectedIndex].value;
	
		if( deliveryPriceVal == "-----" )
			totalVal = parseFloat( basketTotal );
		else
			totalVal = parseFloat( basketTotal ) + parseFloat( deliveryPriceVal );
		
		document.getElementById( 'handling_cart' ).value = deliveryPriceVal;
	}
	else
		totalVal = parseFloat( basketTotal );
		
	totalVal = totalVal.toFixed( 2 );
	
	$j("#overallTotal").fadeOut( "slow", function()
	{
		document.getElementById( 'overallTotal' ).innerHTML = "&pound;" + totalVal;
		$j("#overallTotal").fadeIn( "slow" );
	});
}

// Function used by the search page when applying filter. Used as an alternative to href="#".

function doNothing() {}