var deleteOrder = "Are you sure you want to delete this order?";
var copyOrder = "All specials and coupons will be recalculated.";
var copyOrderTitle = "Continue?"
var copyAutoShipment = "All items, payments, and information will be duplicated.";
var copyAutoShipmentTitle = "Continue?"
var deletePackage = "All order items linked to this package will be unassigned and need to be assigned to another package.";
var deletePackageTitle = "Delete this package?"
var deleteSpecial = "This special will not longer be available to your customers.";
var deleteSpecialTitle = "Delete this special?"
var deleteCoupon = "This coupon will not longer be available to your customers.";
var deleteCouponTitle = "Delete this coupon?"
var deleteList = "Are you sure you want to delete this list?";
var deleteListItems = "Are you sure you want to delete the selected list items?";
var deleteBrand = "All products in this brand will no longer show up on the web site.";
var deleteBrandTitle = "Delete this brand?"
var deleteSupplier = "Order fulfillment e-mails will no longer be sent to this supplier.";
var deleteSupplierTitle = "Delete this supplier?"
var deletePage = "All links to this page will be broken.";
var deletePageTitle = "Delete this page?"
var deletePayment = "Are you sure you want to delete this payment?";
var editProcessedPayment = "This payment has already been processed.";
var editProcessedPaymentTitle = "Edit this payment?"
var deleteProcessedPayment = "This payment has already been processed.";
var deleteProcessedPaymentTitle = "Delete this payment?"
var deleteCategoryTitle = "You are about to delete the category."
var deleteCategory = "Any pages in this category will no longer appear on the site until they are added to another category.";
var deleteDivision = "Are you sure you want to delete this division?";
var deleteProduct = "Are you sure you want to delete this product?";
var deleteOption = "Are you sure you want to delete this option?";
var deleteProductCategory = "Are you sure you want to remove this product from this category?";
var deleteBlogCategory = "All blog entries associated with this category will be unassigned.";
var deleteBlogTopicTitle = "Delete this blog topic?"
var deleteAutoShipment = "Your customer will no longer received automatic orders generated from this auto shipment. <p class='notice'>Delete this auto shipment?</p>";
var deleteAutoShipmentTitle = "Delete this special?"
var deleteBlogComment = "Are you sure you want to delete this comment?";
var deleteBlogEntry = "Any blog comments associated with this entry will be lost.";
var deleteBlogEntryTitle = "Delete this entry?"
var cancelMessage = "All changes since you last saved will be discarded.";
var cancelMessageTitle = "Cancel anyway?"
var discardChanges = "Your changes will be lost since your last save.";
var discardChangesTitle = "Discard all changes?"

var browserType;

if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) 
{
	browserType= "gecko"
}

// Hide Element
function hide(elementid) {
	if (browserType == "gecko" )
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else if (browserType == "ie")
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else
		document.poppedLayer = eval('document.layers["' + elementid + '"]');
	
	document.poppedLayer.style.display = "none";
}

// Show Element
function show(elementid, block) {
	if (browserType == "gecko" )
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else if (browserType == "ie")
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	 else
		document.poppedLayer = eval('document.layers["' + elementid + '"]');
	
	if ( block )
		document.poppedLayer.style.display = "block";
	else
		document.poppedLayer.style.display = "inline";
}

// Hide Element
function hideElement(elementid) {
	if (browserType == "gecko" )
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else if (browserType == "ie")
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else
		document.poppedLayer = eval('document.layers["' + elementid + '"]');
	
	document.poppedLayer.style.visibility = "hidden";
}

// Show Element
function showElement(elementid) {
	if (browserType == "gecko" )
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	else if (browserType == "ie")
		document.poppedLayer = eval('document.getElementById("' + elementid + '")');
	 else
		document.poppedLayer = eval('document.layers["' + elementid + '"]');
	
	document.poppedLayer.style.visibility = "visible";
}

function disableKey( e, code )
{
	var key;     
	
	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     

	return (key != code);
}

function enterKeyPressed( e )
{
	var key;     

	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox
	
	if (key == 13)
		return true;
	else
		return false;
}

function toggleEditableTextBox( checkBoxId, textBoxId )
{
	textbox = document.getElementById( textBoxId );
	checkBox = document.getElementById( checkBoxId );
	
	if ( checkBox.checked )
		textbox.readOnly = false;
	else
		textbox.readOnly = true;
}

function allowKeyStroke( id )
{
	if ( document.getElementById(id).checked )
		return true;
	else
	{
		return false;
	}
}

//function alphaNumericCheck( id ){
//	
//	var regex = /^[0-9]+$/;  //^[0-9a-zA-z]+$/
//	var textBox = document.getElementById( id );
//	
//	if( regex.test(textBox.value.replace("$", "")))
//	{
//		alert("true")
//		return true;
//	}
//	else
//		return false;
//}

function loadQuantityDiscount( txtPrice, txtQuantityPrice )
{
	var price = document.getElementById( txtPrice );
	var quantityPrice = document.getElementById( txtQuantityPrice  );
	
	price.value = quantityPrice.value;
}

function calculateTotal()
{
	var itemTotal = document.getElementById("txtItemTotal").value.replace("$","");
	var shipping = document.getElementById("txtShipping").value.replace("$","");
	var tax = document.getElementById("txtTax").value.replace("$","");
	var discount = document.getElementById("txtDiscount").value.replace("$","");
	var total = document.getElementById("txtFinalTotal");

	if (!isFloat(itemTotal))
		itemTotal = 0.00;
		
	if (!isFloat(shipping))
		shipping = 0.00;
		
	if (!isFloat(tax))
		tax = 0.00;
		
	if (!isFloat(discount))
		discount = 0.00;
	
	total.value = ((parseFloat(itemTotal.replace(",","")) + parseFloat(shipping.replace(",","")) - parseFloat(discount.replace(",",""))) + parseFloat(tax.replace(",",""))).toFixed(2);
	total.value = "$" + total.value
}

function checkForDollarSign( currency, force )
{
	var textbox = document.getElementById(currency);
	
	// Remove any dollar signs in case they are in the wrong place
	textbox.value = textbox.value.replace("$", "");
	
	// Ensure that the value in the text box is a float
	if ( !isFloat(textbox.value) && force)
	{
		textbox.value = "0.00";
		// Add a dollar sign in the correct position
		textbox.value = "$" + parseFloat(textbox.value.replace(",","")).toFixed(2);
	}
	else if ( isFloat(textbox.value) )
	{
		// Add a dollar sign in the correct position
		textbox.value = "$" + parseFloat(textbox.value.replace(",","")).toFixed(2);
	}
	
}

function checkForPercentSign( percent, force )
{
	var textbox = document.getElementById( percent );
	
	// Remove any dollar signs in case they are in the wrong place
	textbox.value = textbox.value.replace("%", "");
	
	// Ensure that the value in the text box is a float
	if ( !isFloat(textbox.value) && force )
	{
		textbox.value = "0.00";
		// Add a percent sign in the correct position
		textbox.value = textbox.value + "%";
	}
	else if (isFloat(textbox.value))
		textbox.value = textbox.value + "%";
}

function validateNumber( id, defaultNumber )
{
	var textbox = document.getElementById( id )

	if ( !isInteger(textbox.value) )
		textbox.value = defaultNumber
}

function isFloat(s) 
{
	return (s.toString().search(/^-?[0-9.]+$/) == 0);
}

function isInteger(s) 
{
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function setCheckPanels( checkBoxId, panelId )
{
	var checkbox = document.getElementById( checkBoxId )
	
	if ( document.getElementById( checkBoxId ).checked )
	{
		document.getElementById( panelId ).style.display="block";
	}
	else
	{
		document.getElementById( panelId ).style.display="none";
	}
}

function setShippingPanels( checkBoxId, panelId )
{
	if (document.getElementById(checkBoxId).checked) 
		hideElementDisplay(panelId);
	else 
		showElementDisplay(panelId, 'block');
}

function setCreditCardPanels( id )
{
	var payment = document.getElementById(id)

	try
	{
		if ( payment.options[payment.selectedIndex].value == 0 )
		{
			show( "pnlNewCard" );
			show( "pnlRemember" );
			show( "pnlCardAddress" );
		}
		else
		{
			hide( "pnlNewCard" );
			hide( "pnlRemember" );
			hide( "pnlCardAddress" );
		}
	}
	catch(err)
	{
		// this is here because the panels do not exists for ie6 when editing a check
	}
	
}

function setDisplay( statusTextBoxId, panelId, block )
{
	if ( document.getElementById(statusTextBoxId).value == "true" )
		show(panelId, block );
	else
		hide(panelId);
}

function toggleDisplay( statusTextBoxId, panelId, block )
{
	if ( document.getElementById(statusTextBoxId).value == "true" )
		document.getElementById(statusTextBoxId).value = "false";
	else
		document.getElementById(statusTextBoxId).value = "true";
		
	setDisplay( statusTextBoxId, panelId, block );
}

function updateDivStatus( panelId, titleId )
{
	var html = document.getElementById( titleId ).innerHTML
	var panel = document.getElementById( panelId ).style.display
	
	if ( panel == "none" )
		html = html.replace("-", "+")
	else
		html = html.replace("+", "-")
		
	document.getElementById( titleId ).innerHTML = html
}

function loadBillingPop()
{
	document.getElementById("txtFirstNameEdit").value = document.getElementById("txtFirstName").value; 
	document.getElementById("txtLastNameEdit").value = document.getElementById("txtLastName").value;
	document.getElementById("txtAddress1Edit").value = document.getElementById("txtAddress1").value;
	document.getElementById("txtAddress2Edit").value = document.getElementById("txtAddress2").value;
	document.getElementById("txtCityEdit").value = document.getElementById("txtCity").value;
	document.getElementById("ddlCountryEdit").value = document.getElementById("ddlCountry").value;
	document.getElementById("txtIntlStateEdit").value = document.getElementById("txtIntlState").value;
	document.getElementById("ddlStateEdit").value = document.getElementById("ddlState").value;
	document.getElementById("txtZipEdit").value = document.getElementById("txtZip").value;
	document.getElementById("ddlCountryEdit").value = document.getElementById("ddlCountry").value;
}

function changeBillingAddress()
{

	document.getElementById("txtFirstName").value = document.getElementById("txtFirstNameEdit").value; 
	document.getElementById("txtLastName").value = document.getElementById("txtLastNameEdit").value;
	document.getElementById("txtAddress1").value = document.getElementById("txtAddress1Edit").value;
	document.getElementById("txtAddress2").value = document.getElementById("txtAddress2Edit").value;
	document.getElementById("txtCity").value = document.getElementById("txtCityEdit").value;
	document.getElementById("ddlCountry").value = document.getElementById("ddlCountryEdit").value;
	document.getElementById("txtIntlState").value = document.getElementById("txtIntlStateEdit").value;
	document.getElementById("ddlState").value = document.getElementById("ddlStateEdit").value;
	document.getElementById("txtZip").value = document.getElementById("txtZipEdit").value;
	document.getElementById("ddlCountry").value = document.getElementById("ddlCountryEdit").value;
	
	var address = "";
	
	address = address + document.getElementById("txtFirstName").value + " ";
	address = address + document.getElementById("txtLastName").value + "<br />";
	address = address + document.getElementById("txtAddress1").value + "<br />";
	
	if ( document.getElementById("txtAddress2").value != "" )
		address = address + document.getElementById("txtAddress2").value + "<br />";
	
	if (document.getElementById("ddlCountry").value == "United States")
	{
		if (document.getElementById("txtCity").value !=  "" && document.getElementById("ddlState").value != "" )
			address = address + document.getElementById("txtCity").value + ", " + document.getElementById("ddlState").value + " ";
		else
		{	
			if (document.getElementById("txtCity").value !=  "" || document.getElementById("ddlState").value != "" )
				address = address + document.getElementById("txtCity").value + document.getElementById("ddlState").value  + " ";
		}
	}
	else
		address = address + document.getElementById("txtCity").value + "<br />" + document.getElementById("txtIntlState").value + " ";
	
	address = address + document.getElementById("txtZip").value + "<br />";
	address = address + document.getElementById("ddlCountry").value;

	document.getElementById("lblAddress").innerHTML = address;
}

function checkForName()
{
	if (( document.getElementById("txtFirstName").value == "" ) || ( document.getElementById("txtLastName").value == "" ))
	{
		displayMessage("", "Customer's full name is required.", "warning");
		return false;
	}
}

function viewReceipt( oid )
{
	window.open("/admin/order/receipt.aspx?oid=" + oid, "receipt_" + oid, "width=1000,height=700,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes");
}

function viewPackingSlip( oid )
{
	window.open("/admin/order/packing-slip.aspx?oid=" + oid, "packingSlips_" + oid, "width=1000,height=700,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes");
}

function viewHelp( hid )
{
	window.open("/admin/help/popup.aspx?hid=" + hid, "help_" + hid, "width=300,height=300,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=yes,resizable=no");
}

var browserType;

if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) 
{
	browserType= "gecko"
}

// Maxamize window size
function maximize() {
  window.moveTo(0, 0);
  window.resizeTo(screen.width, screen.height);
}
	
function selectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function hideQuickSearch(elementid) 
{
	createCookie("hideSearch","true",1)
	hide(elementid,"false");
}

function showQuickSearch(elementid) 
{
	createCookie("hideSearch","false",1)
	show(elementid,"false");

}

function toggleMoreOptions(elementid) 
{
	if (readCookie("moreOptions") == "true") 
	{
		createCookie("moreOptions","false",1)
		hide(elementid,"false");
	}
	else
	{
		createCookie("moreOptions","true",1)
		show(elementid,"false");
	}
}

function showMoreOptions(elementid) 
{
	createCookie("moreOptions","true",1)
	show(elementid,"false");
}

function hideShoppingCart(elementid) 
{
	createCookie("hideCart","true",1)
	hide(elementid,"false");

}

function showShoppingCart(elementid) 
{
	createCookie("hideCart","false",1)
	show(elementid,"false");
	
	return false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


var b_timer = null; // blink timer
var b_on = true; // blink state
var blnkrs = null; // array of spans

function blink() {
	var tmp = document.getElementsByTagName("span");
	
	if (tmp) {
		blnkrs = new Array();
		var b_count = 0;
		
		for (var i = 0; i < tmp.length; ++i) {
			if (tmp[i].className == "blink") {
				blnkrs[b_count] = tmp[i];
				++b_count;
			}
		}

		// time in m.secs between blinks
		// 500 = 1/2 second
		blinkTimer(2500);
	}
}

function blinkTimer(ival) {
	if (b_timer) {
		window.clearTimeout(b_timer);
		b_timer = null;
	}
	
	blinkIt();
	b_timer = window.setTimeout('blinkTimer(' + ival + ')', ival);
}

function blinkIt() {
	for (var i = 0; i < blnkrs.length; ++i) {
		if (b_on == true) {
			if (browserType == "ie")
				blnkrs[i].style.visibility = "hidden";
			else
				opacity(blnkrs[i].id, 99, 30, 2500)
		}
		else {
			if (browserType == "ie")
				blnkrs[i].style.visibility = "visible";
			else
				opacity(blnkrs[i].id, 30, 99, 2500)
		}
	}
	b_on =!b_on;
} 


function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 

function centerDiv(Xwidth,Yheight,divid) 
{ 	
	// First, determine how much the visitor has scrolled 
	var scrolledX, scrolledY; 
	
	if( self.pageYOffset ) { 
		scrolledX = self.pageXOffset; 
		scrolledY = self.pageYOffset; 
	} else if( document.documentElement && document.documentElement.scrollTop ) { 
		scrolledX = document.documentElement.scrollLeft; 
		scrolledY = document.documentElement.scrollTop; 
	} else if( document.body ) { 
		scrolledX = document.body.scrollLeft; 
		scrolledY = document.body.scrollTop; 
	} 

	// Next, determine the coordinates of the center of browser's window 
	var centerX, centerY; 
	if( self.innerHeight ) { 
		centerX = self.innerWidth; 
		centerY = self.innerHeight; 
	} else if( document.documentElement && document.documentElement.clientHeight ) { 
		centerX = document.documentElement.clientWidth; 
		centerY = document.documentElement.clientHeight; 
	} else if( document.body ) { 
		centerX = document.body.clientWidth; 
		centerY = document.body.clientHeight; 
	} 

	// Xwidth is the width of the div, Yheight is the height of the 
	// div passed as arguments to the function: 
	var leftOffset = scrolledX + (centerX - Xwidth) / 2; 
	var topOffset = scrolledY + (centerY - Yheight) / 2; 
	
	// The initial width and height of the div can be set in the 
	// style sheet with display:none; divid is passed as an argument to the function 
	var o=document.getElementById(divid); 
	var r=o.style; 
	
	r.position='absolute'; 
	
	// Ensure the div is never higher than the page and atleast 50px from the top
	if (topOffset < 50 || Yheight == 0)
		r.top = '50px'; 
	else
		r.top = topOffset + 'px'; 
	
	r.left = leftOffset + 'px'; 
	r.display = "block"; 
} 

function checkCardNumber( id, outId )
{
	var cardNumber = document.getElementById( id ).value;

	var re = /^((((4\d{3})|(5[1-5]\d{2})|(6011))[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|(3[47][\d\s-]{13}))$/

	if (re.test(cardNumber))
		document.getElementById( outId ).style.color = "#0daf01";
	else
		document.getElementById( outId ).style.color = "#ff0000";

	return re.test(cardNumber);
}

function testFileType( fileName, fileTypes ) 
{
	if (!fileName) return;

	dots = fileName.split(".")
	
	//get the part AFTER the LAST period.
	fileType = dots[dots.length-1];

	if (fileTypes.join(".").indexOf(fileType) != -1)
		return true;
	else
	{
		alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
		return false;
	}
}

var TimeToFade = 1000.0;

function fade(eid)
{
	var element = document.getElementById(eid);
	
	if(element == null)
		return;
   
	if(element.FadeState == null)
	{
		if(element.style.opacity == null 
			|| element.style.opacity == '' 
			|| element.style.opacity == '1')
		{
			element.FadeState = 2;
		}
		else
		{
			element.FadeState = -2;
		}
	}
    
	if(element.FadeState == 1 || element.FadeState == -1)
	{
		element.FadeState = element.FadeState == 1 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
	}
	else
	{
		element.FadeState = element.FadeState == 2 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade;
		setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
	}  
}

function animateFade(lastTick, eid)
{  
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
  
	var element = document.getElementById(eid);
 
	if(element.FadeTimeLeft <= elapsedTicks)
	{
		element.style.opacity = element.FadeState == 1 ? '1' : '0';
		element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
		element.FadeState = element.FadeState == 1 ? 2 : -2;
		return;
	}
 
	element.FadeTimeLeft -= elapsedTicks;
	
	var newOpVal = element.FadeTimeLeft/TimeToFade;
	
	if(element.FadeState == 1)
		newOpVal = 1 - newOpVal;

	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
  
	setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}

function initializeWaterMark(textboxID, text) 
{
		
	if (document.getElementById(textboxID).value == '')
	{
		document.getElementById(textboxID).value = text;
		document.getElementById(textboxID).className = document.getElementById(textboxID).className + " watermark";
	}
	else if (document.getElementById(textboxID).value != text)
		document.getElementById(textboxID).className = document.getElementById(textboxID).className + " cartRegularTextBox";
	else if (document.getElementById(textboxID).value == text)
		document.getElementById(textboxID).className = document.getElementById(textboxID).className + " watermark";
}

function hideWaterMark(textboxID, text) 
{
	if (document.getElementById(textboxID).value == text)
	{
		document.getElementById(textboxID).value = '';
		document.getElementById(textboxID).className = document.getElementById(textboxID).className.replace("watermark", "cartRegularTextBox");
	}
}

function showWaterMark(textboxID, text) 
{
	if (document.getElementById(textboxID).value == '')
	{
		document.getElementById(textboxID).value = text;
		document.getElementById(textboxID).className = document.getElementById(textboxID).className.replace("cartRegularTextBox", "watermark");
	}
}

function determineCheckout( typeOfCheckout, usernameId, passwordId )
{

	hide('pnlCartAccountEmailLabel', 'true');
	hide('pnlCartAccountEmail', 'true');
	hide('pnlCartAccountPassword', 'true');
	hide('pnlCartAccountButton', 'true');
	hide('pnlCartCheckoutInfoContainer', 'true');
	hide('btnCartCheckout', 'true');
	hide('pnlCartSaveCreditCard', 'true');
	hide('pnlCartAccountPasswordLabel', 'true');
	hide('pnlCartAccountPasswordChooseLabel', 'true');
	hide('pnlCartAccountPasswordNewLabel', 'true');
	hideElement('pnlEmailRequired');

	if ( typeOfCheckout == "rbGuest" )
	{
		show('pnlCartCheckoutInfoContainer', 'true');
		show('pnlCartAccountEmailLabel', 'true');
		show('pnlCartAccountEmail', 'true');
		show('btnCartCheckout', 'true');
		document.getElementById('pnlCartLoginMessage').innerHTML = "";
	}
	else if ( typeOfCheckout == "rbAccount" )
	{
		show('pnlCartAccountPasswordLabel', 'true');
		show('pnlCartAccountPasswordNewLabel', 'true');
		show('pnlCartAccountEmailLabel', 'true');
		show('pnlCartAccountEmail', 'true');
		show('pnlCartAccountPassword', 'true');
		show('pnlCartAccountButton', 'true');
		showElement('pnlEmailRequired');
		
		if (isUserLoggedIn(usernameId, passwordId)=="true")
			displayLoggedInInformation(passwordId);
	}
	else if ( typeOfCheckout == "rbNewAccount" )
	{
		show('pnlCartAccountPasswordLabel', 'true');
		show('pnlCartAccountPasswordChooseLabel', 'true');
		show('pnlCartAccountEmailLabel', 'true');
		show('pnlCartAccountEmail', 'true');
		show('pnlCartAccountPassword', 'true');
		show('pnlCartCheckoutInfoContainer', 'true');
		show('btnCartCheckout', 'true');
		showElement('pnlEmailRequired');
		document.getElementById('pnlCartLoginMessage').innerHTML = "";
	}
	
	document.getElementById('lblCartAccountState').value = typeOfCheckout;
}

function setcheckoutradiobutton( rbID )
{
	document.getElementById(rbID).checked = true;
}

function displayLoggedInInformation(passwordId)
{
	show('pnlCartCheckoutInfoContainer', 'true');
	show('btnCartCheckout', 'true');
	hide('pnlCartCustomerAccount', 'true');
	show('pnlCartSaveCreditCard', 'true');
	
	document.getElementById('pnlCartLoginMessage').innerHTML = "<b>Your account was found and you are logged in.</b> <label class='cartLink' onclick=logout('" + passwordId + "');>Log Out</label>";
	document.getElementById('pnlCartLoginMessage').className="successMessage";
}

function determineShippingMethods( method, cartSubTotalId, onMouseClick, ddlShipCountry, ddlBillCountry )
{


	if (onMouseClick)
	{
		clearShippingMethod();
		calculateCartSubTotal( cartSubTotalId );
	}

	if ( method=='NonUS' )
	{
		hide('pnlCartZipCode');
		document.getElementById('pnlCartShippingOptions').innerHTML="Calculate shipping to view available methods.";
		
		var shipCountries = document.getElementById(ddlShipCountry);
		var billCountries = document.getElementById(ddlBillCountry);
		
		if (shipCountries[shipCountries.selectedIndex].value == "United States")
			for (var x=0; x < shipCountries.options.length; x++)
				if (shipCountries.options[x].value=="")
					shipCountries.options[x].selected=true;
					
	}
	else
	{
		show('pnlCartZipCode');
		document.getElementById('pnlCartShippingOptions').innerHTML="";
		
		var shipCountries = document.getElementById(ddlShipCountry);
		var billCountries = document.getElementById(ddlBillCountry);
		
					
		if (shipCountries[shipCountries.selectedIndex].value == "")
			for (var x=0; x < shipCountries.options.length; x++)
				if (shipCountries.options[x].value=="United States")
					shipCountries.options[x].selected=true;
					
		if (billCountries[billCountries.selectedIndex].value == "")
			for (var x=0; x < billCountries.options.length; x++)
				if (billCountries.options[x].value=="United States")
					billCountries.options[x].selected=true;
						
	}
	
	document.getElementById('lblCartShippingState').value = method;
}

function clearShippingMethod()
{
	document.getElementById('lblCartTaxCharge').innerHTML 		= "$0.00"
	document.getElementById('lblCartShippingCharge').innerHTML	= '$0.00';
	document.getElementById('lblCartShippingChargeHold').value	= '$0.00';
	document.getElementById('lblCartShippingMethodHold').value	= '';
	document.getElementById('lblCartShippingMethodIDHold').value	= '-1';
}

function determinePaymentMethods( typeOfPayment )
{
	if ( typeOfPayment == "rbNewCreditCard" )
	{
		hide('tblExistingCreditCard', 'true');
		show('tblNewCreditCard', 'true');
	}
	else if ( typeOfPayment == "rbExistingCreditCard" )
	{
		hide('tblNewCreditCard', 'true');
		show('tblExistingCreditCard', 'true');
	}
	else if ( typeOfPayment == "rbPhoneCall" )
	{
		hide('tblExistingCreditCard', 'true');
		hide('tblNewCreditCard', 'true');
	}
	else if ( typeOfPayment == "rbMailCheck" )
	{
		hide('tblExistingCreditCard', 'true');
		hide('tblNewCreditCard', 'true');
	} 
	else
	{
		hide('tblExistingCreditCard', 'true');
		hide('tblNewCreditCard', 'true');
	}
	
	document.getElementById('lblCartPaymentMethodState').value = typeOfPayment;
}

function determineExistingPaymentMethods( onFile )
{
	if ( onFile=='true' )
		show('pnlExistingCreditCard');
	else
		hide('pnlExistingCreditCard');
	
	document.getElementById('lblCartPaymentExistingPaymentsState').value = onFile;
}

function copyBillingAddress( sameBilling, shipFirst, shipLast, shipAddress, shipAddress2, shipCountry, shipCity, shipAddressThree, shipState, shipZip, billFirst, billLast, billAddress, billAddress2, billCountry, billCity, billAddressThree, billState, billZip )
{
	if ( sameBilling )
	{
		document.getElementById(billFirst).value = document.getElementById(shipFirst).value.replace('Enter First Name*','');
		document.getElementById(billLast).value = document.getElementById(shipLast).value.replace('Enter Last Name*','');;
		document.getElementById(billAddress).value = document.getElementById(shipAddress).value.replace('Enter Address*','');;
		document.getElementById(billAddress2).value = document.getElementById(shipAddress2).value.replace('Enter Address Line 2','');;
		document.getElementById(billCountry).selectedIndex = document.getElementById(shipCountry).selectedIndex;
		document.getElementById(billCity).value = document.getElementById(shipCity).value.replace('Enter City*','');;
		document.getElementById(billAddressThree).value = document.getElementById(shipAddressThree).value.replace('Enter State or Province','');;
		document.getElementById(billState).selectedIndex = document.getElementById(shipState).selectedIndex;
		document.getElementById(billZip).value = document.getElementById(shipZip).value.replace('Enter Zip*','');;
	}
}

function toggleAddress( country, addressThree, state )
{
	if (document.getElementById(country))
		if ( (document.getElementById(country)[document.getElementById(country).selectedIndex].value=="United States") || (document.getElementById(country)[document.getElementById(country).selectedIndex].value=="") )
		{
			hide(addressThree);
			show(state);
		}
		else
		{
			show(addressThree);
			hide(state);
		}
}


function getShippingAndTaxDataIfEnter( e, cartSubTotalId, rbNonUS, weight, total, zip, user, pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage )
{
	if (enterKeyPressed( e ))
		return getShippingAndTaxData( cartSubTotalId, rbNonUS, weight, total, zip, user, pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage );
}

function getShippingAndTaxData( cartSubTotalId, rbNonUS, weight, total, zip, user, pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage )
{
	getShippingMethods( cartSubTotalId, rbNonUS, weight, total, zip, user, pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage );
	getTaxData( total, zip, cartSubTotalId );
	return false;
}

function calculateCartSubTotal( cartSubTotalId )
{
	var discount = "0.00"
	if (document.getElementById('lblCartOrderDiscount')) 
		discount = document.getElementById('lblCartOrderDiscount').innerHTML
	
	document.getElementById('lblCartOrderTotal').innerHTML = formatCurrency(parseFloat(parseFloat(document.getElementById(cartSubTotalId).innerHTML.replace("$","").replace(",","")) + parseFloat(document.getElementById('lblCartShippingCharge').innerHTML.replace("$","").replace(",","")) + parseFloat(document.getElementById('lblCartTaxCharge').innerHTML.replace("$","").replace(",","")) - parseFloat(discount.replace("$","").replace(",","")) ).toFixed(2) )
	document.getElementById('lblCartOrderTotal2').innerHTML = document.getElementById('lblCartOrderTotal').innerHTML
}

function formatCurrency( amount )
{
        while (amount.match(/\d{4}/))
        {
		amount = amount.replace(/(\d)(\d{3})$/,"$1,$2");
		amount = amount.replace(/(\d)(\d{3})(\.)/,"$1,$2$3");
		amount = amount.replace(/(\d)(\d{3})(,)/,"$1,$2$3");
	}
	return "$" + amount.replace("$", "");
}

function getShippingMethods( cartSubTotalId, rbNonUS, weight, total, zip, user, pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage )
{

	if ( ((document.getElementById(zip).value != 'Enter Zip Code*') || (document.getElementById(rbNonUS).checked))  && document.getElementById(zip).value.length >= 5  && !isNaN(document.getElementById(zip).value))
	{
	
		document.getElementById('pnlCartShippingOptions').innerHTML = "Loading shipping options. Please wait ...";
		sendAjaxRequest('/includes/javascript/ajax-feeds/get-shipping-methods.aspx?cartTotalId=' + escape(cartSubTotalId) + '&nonUS=' + document.getElementById(rbNonUS).checked + '&weight=' + escape(weight) + '&total=' + escape(total) + '&zip=' + document.getElementById(zip).value, null, 
			function( responseData )
			{
				document.getElementById('pnlCartShippingOptions').innerHTML=responseData;

				if (document.getElementById('lblCartShippingMethodIDHold').value > -1)
				{
					var temp = document.getElementById('cartShippingMethods');
					for (var x=0; x < temp.options.length; x++)
						if (document.getElementById('cartShippingMethods').options[x].value==document.getElementById('lblCartShippingMethodIDHold').value)
							document.getElementById('cartShippingMethods').options[x].selected=true;
				}

				loadShippingData( 'cartShippingMethods', cartSubTotalId );
			}
			, false);
	}
	else
		if ( (user) && (!document.getElementById(rbNonUS).checked) )
			showCartError( pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage, '<li>Please enter a valid United States 5 digit zip code.</li>' )

	return false;
}

function getTaxData( total, zip, cartSubTotalId )
{	
	if (document.getElementById(zip).value != 'Enter Zip Code*')
		sendAjaxRequest('/includes/javascript/ajax-feeds/get-tax.aspx?total=' + escape(total) + '&zip=' + escape(document.getElementById(zip).value), null, 
			function( responseData )
			{
				document.getElementById('lblCartTaxCharge').innerHTML = "$" + parseFloat(responseData.replace(",","")).toFixed(2);
				calculateCartSubTotal( cartSubTotalId );
			}
			, false);
	
}

function loadShippingData( listID, cartSubTotalId )
{
	var shippingMethod = new Array(); 
	
	shippingMethod = document.getElementById(listID)[document.getElementById(listID).selectedIndex].text.replace(" ","").split("-");

	if (shippingMethod.length > 1 )
	{
		document.getElementById('lblCartShippingCharge').innerHTML=shippingMethod[0];
		document.getElementById('lblCartShippingChargeHold').value=shippingMethod[0];
		document.getElementById('lblCartShippingMethodHold').value=shippingMethod[1];
		document.getElementById('lblCartShippingMethodIDHold').value=document.getElementById(listID)[document.getElementById(listID).selectedIndex].value;
	}
	else
		clearShippingMethod( cartSubTotalId );
	calculateCartSubTotal( cartSubTotalId );
	
}

function setTextBox( sourceID, destinationID, watermark )
{
	if ( document.getElementById(destinationID).value == watermark && document.getElementById(sourceID).value != "" )
	{
		document.getElementById(destinationID).className = document.getElementById(destinationID).className.replace("watermark", "cartRegularTextBox");
		document.getElementById(destinationID).value = document.getElementById(sourceID).value;
	}
}

function setSelectBox( sourceID, destinationID, countryList, addressThree, state )
{
	if ( document.getElementById(destinationID).selectedIndex == "" )
	{
		document.getElementById(destinationID).selectedIndex = document.getElementById(sourceID).selectedIndex;
		
		if (countryList)
			toggleAddress( destinationID, addressThree, state );
	}
}

function getPaymentsOnFile()
{
	sendAjaxRequest('/includes/javascript/ajax-feeds/get-account-payments.aspx', null,
		function ( responseData )
		{
			var payments = new Array();
			payments = responseData.split("|");
			
			if ( payments[1]=="true" )
			{
				document.getElementById('pnlExistingCreditCard').style.display = "inline";
				document.getElementById('lblCartPaymentExistingPaymentsState').value = 'true';
				document.getElementById('pnlCartCreditCards').innerHTML = payments[2];
				
				var temp = document.getElementById('ddlCartCreditCardsOnFile');
		
				for (var x=0; x < temp.options.length; x++)
					if (document.getElementById('ddlCartCreditCardsOnFile').options[x].value==document.getElementById('lblCartPaymentID').value)
						document.getElementById('ddlCartCreditCardsOnFile').options[x].selected=true;
			}
		}
	, false);
}

function isUserLoggedIn(usernameId, passwordId)
{
	return sendAjaxRequest('/includes/javascript/ajax-feeds/is-logged-in.aspx', 'username=' + document.getElementById(usernameId).value + '&password=' + document.getElementById(passwordId).value, null, false);
}

function logout(passwordId)
{
	hide('pnlCartCheckoutInfoContainer', 'true');
	hide('btnCartCheckout', 'true');
	show('pnlCartCustomerAccount', 'true');
	hide('pnlCartSaveCreditCard', 'true');
	
	hide('tblExistingCreditCard', 'true');
	hide('pnlExistingCreditCard');
	
	document.getElementById('pnlCartLoginMessage').innerHTML = "You have been logged out. Please choose a checkout option.";
	document.getElementById('pnlCartLoginMessage').className="successMessage";
	document.getElementById('lblCartPaymentMethodState').value = "";
	
	document.getElementById('lblCartPaymentExistingPaymentsState').value = 'false';
	document.getElementById(passwordId).value = '';
	return sendAjaxRequest('/includes/javascript/ajax-feeds/cart-logout.aspx', null, null, false);
}

function loginIfEnter( e, username, password, shipFirst, shipLast, shipAddress, shipAddress2, shipCountry, shipCity, shipAddressThree, shipState, shipZip, billFirst, billLast, billAddress, billAddress2, billCountry, billCity, billAddressThree, billState, billZip, phone, extension )
{
	if (enterKeyPressed( e ))
	{
		login( username, password, shipFirst, shipLast, shipAddress, shipAddress2, shipCountry, shipCity, shipAddressThree, shipState, shipZip, billFirst, billLast, billAddress, billAddress2, billCountry, billCity, billAddressThree, billState, billZip, phone, extension );
		return false;
	}
}

function login( username, password, shipFirst, shipLast, shipAddress, shipAddress2, shipCountry, shipCity, shipAddressThree, shipState, shipZip, billFirst, billLast, billAddress, billAddress2, billCountry, billCity, billAddressThree, billState, billZip, phone, extension )
{
	sendAjaxRequest('/includes/javascript/ajax-feeds/cart-login.aspx?username=' + escape(document.getElementById(username).value) + '&password=' + escape(document.getElementById(password).value), null,
		function ( responseData ) 
		{ 
			var account = new Array();
			account = responseData.split("|");
			
			document.getElementById('pnlCartLoginMessage').innerHTML = account[1]; 
		
			if (account[0]=="success")
			{
				if (account[2]!="") 
				{
					document.getElementById(shipFirst).className = document.getElementById(shipFirst).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipFirst).value = account[2];
				}
				
				if (account[3]!="") 
				{
					document.getElementById(shipLast).className = document.getElementById(shipLast).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipLast).value = account[3];
				}
				
				if (account[4]!="") 
				{
					document.getElementById(shipAddress).className = document.getElementById(shipAddress).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipAddress).value= account[4];
				}
				
				if (account[5]!="") 
				{
					document.getElementById(shipAddress2).className = document.getElementById(shipAddress2).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipAddress2).value = account[5];
				}
				
				if (account[6]!="") 
				{
					document.getElementById(shipCity).className = document.getElementById(shipCity).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipCity).value = account[6];
				}
				
				if (account[9] == "United States")
					document.getElementById(shipState).value = account[7];
					
				if (account[7]!="") 
				{
					document.getElementById(shipAddressThree).className = document.getElementById(shipAddressThree).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipAddressThree).value = account[7];
				}
				
				if (account[8]!="") 
				{
					document.getElementById(shipZip).className = document.getElementById(shipZip).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipZip).value = account[8];
				}	
				
				if (account[9]!="")
				{
					document.getElementById(shipCountry).className = document.getElementById(shipCountry).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(shipCountry).value = account[9];
				}
				
				if (account[10]!="") 
				{
					document.getElementById(phone).className = document.getElementById(phone).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(phone).value = account[10];
				}
				if (account[11]!="") 
				{
					document.getElementById(extension).className = document.getElementById(extension).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(extension).value = account[11];
				}
		
				if (account[13]!="") 
				{
					document.getElementById(billFirst).className = document.getElementById(billFirst).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billFirst).value = account[13];
				}
				if (account[14]!="") 
				{
					document.getElementById(billLast).className = document.getElementById(billLast).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billLast).value = account[14];
				}
				if (account[15]!="") 
				{	
					document.getElementById(billAddress).className = document.getElementById(billAddress).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billAddress).value= account[15];
				}
				if (account[16]!="") 
				{
					document.getElementById(billAddress2).className = document.getElementById(billAddress2).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billAddress2).value = account[16];
				}
				if (account[17]!="") 
				{
					document.getElementById(billCity).className = document.getElementById(billCity).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billCity).value = account[17];
				}
				
				if (account[20] == "United States")
					document.getElementById(billState).value = account[18];
					
				if (account[18]!="") 
				{
					document.getElementById(billAddressThree).className = document.getElementById(billAddressThree).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billAddressThree).value = account[18];
				}
				
				if (account[19]!="") 
				{
					document.getElementById(billZip).className = document.getElementById(billZip).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billZip).value = account[19];
				}
				if (account[20]!="") 
				{
					document.getElementById(billCountry).className = document.getElementById(billCountry).className.replace("watermark", "cartRegularTextBox");
					document.getElementById(billCountry).value = account[20];
				}
				if ( account[21]=="true" )
				{
					document.getElementById('pnlExistingCreditCard').style.display = "inline";
					document.getElementById('lblCartPaymentExistingPaymentsState').value = true;
					document.getElementById('pnlCartCreditCards').innerHTML = account[22];
				}
				
				toggleAddress( billCountry, billAddressThree, billState );
				toggleAddress( shipCountry, shipAddressThree, shipState );
				
				displayLoggedInInformation(password);
			}
			else
				document.getElementById('pnlCartLoginMessage').className="errorMessage";
		} 

		, false);
	return false;
}

function loadCreditCardInfo()
{
	document.getElementById('lblCartPaymentID').value = document.getElementById('ddlCartCreditCardsOnFile')[document.getElementById('ddlCartCreditCardsOnFile').selectedIndex].value
}

function validateShoppingCart( username, password, shipFirst, shipLast, shipAddress, shipAddress2, shipCountry, shipCity, shipAddressThree, shipState, shipZip, billFirst, billLast, billAddress, billAddress2, billCountry, billCity, billAddressThree, billState, billZip, phone, extension, rbNewCreditCard, rbExistingCreditCard, rbPhoneCall, rbMail, pnlCartPopup, lblMessageHeader, lblMessage, pnlCartPopupDoneOptions, pnlCartPopupErrorOptions, rbUS, rbNonUS )
{
	var message = '';
	
	if (document.getElementById('pnlItemsInCart').innerHTML=="0")
		message = message + '<li>Your shopping cart is empty. Please add items to your cart before trying to checkout.</li>';
	
	if (document.getElementById('lblCartShippingMethodIDHold').value == "-1")
		message = message + '<li>Please choose a shipping method.</li>';
		
	if (document.getElementById(rbUS).checked && document.getElementById(shipCountry)[document.getElementById(shipCountry).selectedIndex].value != "United States" && document.getElementById('lblCartShippingMethodIDHold').value > -1 )
		message = message + '<li>Your shipping method is based on a US address, but your shipping address is Non-US.</li>';
		
	if (document.getElementById(rbNonUS).checked && document.getElementById(shipCountry)[document.getElementById(shipCountry).selectedIndex].value == "United States" && document.getElementById('lblCartShippingMethodIDHold').value > -1 )
		message = message + '<li>Your shipping method is based on a Non-US address, but your shipping address is in the US.</li>';
		
	if (document.getElementById(shipFirst).value == 'Enter First Name*')
		message = message + '<li>Shipping first name required.</li>';
	else if (document.getElementById(shipFirst).value.length > 100)
		message = message + '<li>Shipping first name must be fewer than 100 characters.</li>';
		
	if (document.getElementById(shipLast).value == 'Enter Last Name*')
		message = message + '<li>Shipping last name required.</li>';
	else if (document.getElementById(shipLast).value.length > 100)
		message = message + '<li>Shipping last name must be fewer than 100 characters.</li>';
		
	if (document.getElementById(shipAddress).value == 'Enter Address*')
		message = message + '<li>Shipping address required.</li>';
	else if (document.getElementById(shipAddress).value.length > 100)
		message = message + '<li>Shipping address must be fewer than 100 characters.</li>';
		
	if (document.getElementById(shipCity).value == 'Enter City*')
		message = message + '<li>Shipping city required.</li>';
	else if (document.getElementById(shipCity).value.length > 100)
		message = message + '<li>Shipping city must be fewer than 100 characters.</li>';
	
	if (document.getElementById(shipCountry)[document.getElementById(shipCountry).selectedIndex].value == "United States" )
	{
		if (document.getElementById(shipState).value == '0')
			message = message + '<li>Shipping state required.</li>';
		if (document.getElementById(shipZip).value == 'Enter Zip*')
			message = message + '<li>Shipping zip code required.</li>';
		else if (document.getElementById(shipZip).value.length > 16)
			message = message + '<li>Shipping zip code must be fewer than 16 characters.</li>';
	}
	else
	{
		if (document.getElementById(shipAddressThree).value.length > 100)
			message = message + '<li>Shipping state or province must be fewer than 100 characters.</li>';
		if (document.getElementById(shipZip).value.length > 16)
		message = message + '<li>Shipping zip code must be fewer than 16 characters.</li>';
	}

	if (document.getElementById(shipCountry)[document.getElementById(shipCountry).selectedIndex].value == "" )
		message = message + '<li>Shipping country required.</li>';
	
	if (document.getElementById(phone).value != "Enter Phone*")
	{
		var re = new RegExp("^[0-9-(). +]+$");
		if (!document.getElementById(phone).value.match(re))
			message = message + '<li>Phone number must only use numbers, dashes, periods, parentheses or spaces.</li>';
	}
	else
		message = message + '<li>A phone number is required.</li>';
	
	if (document.getElementById(extension).value != "Ext.")
	{
		var re = new RegExp("^[0-9]+$");
		if (!document.getElementById(extension).value.match(re))
			message = message + '<li>Phone extensions should be 10 or fewer digits.</li>';
	}
	
	if (!document.getElementById(rbNewCreditCard).checked && !document.getElementById(rbExistingCreditCard).checked && !document.getElementById(rbPhoneCall).checked && !document.getElementById(rbMail).checked )
		message = message + '<li>Please select a payment method.</li>';
	
	
	if (message.length > 0)
	{
		showCartError( pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage, message )
		return false;
	}
	
}

function showCartError( pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage, message )
{
	show(pnlCartPopup, true);
	show('pnlCartIsolate', true);
	show(pnlCartPopupErrorOptions, true);
	hide(pnlCartPopupDoneOptions);
	
	document.getElementById(lblMessageHeader).innerHTML = "Oops!";
	document.getElementById(lblMessage).innerHTML = 'Please correct the following information. <br /><br />' + message;
	
	hideSelects();
	centerDiv(400,400,pnlCartPopup);
}

function showCartOrderMessage( pnlCartPopup, pnlCartPopupErrorOptions, pnlCartPopupDoneOptions, lblMessageHeader, lblMessage, message )
{
	show(pnlCartPopup, true);
	show('pnlCartIsolate', true);
	hide(pnlCartPopupErrorOptions);
	show(pnlCartPopupDoneOptions);
	
	document.getElementById(lblMessageHeader).innerHTML = "Order Complete";
	document.getElementById(lblMessage).innerHTML = message;
	
	hideSelects();
	centerDiv(400,400,pnlCartPopup);
}

function hideCartMessage( pnlCartPopup )
{
	hide(pnlCartPopup);
	hide('pnlCartIsolate');
	
	showSelectsInDiv('pnlShoppingCartPopup');
}

function setAddressFields( ddlCountry, pnlDomestic, pnlInternational )
{
	var countries = document.getElementById(ddlCountry)
	
	if ( countries.options[countries.selectedIndex].text.indexOf("United States") > -1 )
	{
		hide( pnlInternational );
		show( pnlDomestic );
	}
	else
	{
		show( pnlInternational );
		hide( pnlDomestic );
	}
}

// sends a request to the specified url and either returns the results or calls the provided callback function
// Parameters:
//    url: (required) The url of the server resource to be retrieved.
//    postData: (optional) The post data if any to send to the server.  You may prefer to use query string
//      parameters which would be specified as part of the url.
//    callback: (optional) A function that will be called when a response has been received from the server.
//      If this parameter is omitted, the request will be syncrhonous and the response will be returned from
//      the function as a string.  If it is included, it should specify a function that expets a single string
//      parameter which will be the server's response.
//    allowPartialResponses: (optional) A boolean which indicates whether you wish to receive paratial responses
//      from the server (defaults to false).  If set, your callback function will be called with a second paramter
//      (partial=true) when a partial response is received from the server.  Please note that the entire server
//      response will be include with each partial callback and the final callback.
//
// If you wish to use a callback function with no post data, simply pass null for the postData parameter.
function sendAjaxRequest(url, postData, callback, allowPartialResponses)
{
    url = url.replace('&amp;','&');

    var XMLHttpFactories =
    [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ];

    var req = false;
    for (var i = 0; i < XMLHttpFactories.length; i++)
    {
        try
        {
            req = XMLHttpFactories[i]();
        }
        catch (e)
        {
            continue;
        }
        break;
    }

    if (!req)
    {
        return;
    }
    async = callback ? true : false;
    req.open(postData ? "POST" : "GET", url, async);
    // if this is not commented out Chrome does not like the request
    // req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
    if (postData)
    {
        req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        req.setRequestHeader('Content-length', postData.length);
    }
    if (async)
    {
        req.onreadystatechange = function ()
        {
            if (allowPartialResponses && req.readyState == 3)
            {
                callback(req.responseText, true);
            }
            if (req.readyState != 4)
            {
                return;
            }
            if (req.status != 200 && req.status != 304)
            {
                return;
            }
	    callback(req.responseText, false);
        }
        if (req.readyState == 4)
        {
            return false;
        }
    }
    req.send(postData);
    if (!async)
    {
        return req.responseText;
    }
}

function showSelectsInDiv( panelId )
{
	// Show all select elements in the panel
	var x = document.getElementById(panelId).getElementsByTagName("select");

	for (i = 0; i < x.length; i++)
		x[i].style.visibility = '';
}

function hideSelects()
{
	// Hide all select elements on the page
	var x = document.getElementsByTagName("select");
		
	for (i = 0; i < x.length; i++)
		x[i].style.visibility = 'hidden';
}

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function sizeIsolateScreen()
{
	document.getElementById('pnlWholeCartIsolate').style.height = getDocHeight() + "px";
}

function parseUSNumber( e, textBox, ddlCountry )
{
	var key;     

	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     
			
	if (document.getElementById(ddlCountry )[document.getElementById(ddlCountry).selectedIndex].value == "United States" )
	{
		
	
		if (key != 37 && key != 39 && key != 8 )
		{
			var PhoneNumberInitialString = textBox.value.replace("(", "").replace(")", "").replace(" ", "").replace("-", "")
			var FmtStr = "";
			var index = 0;
		
			while (index < PhoneNumberInitialString.length)
			{
				if (!isNaN(parseInt(PhoneNumberInitialString.charAt(index))))
					FmtStr = FmtStr + PhoneNumberInitialString.charAt(index); 
				index = index + 1;
			}
		
			while (FmtStr.length < 10)
				FmtStr = FmtStr + " ";
		
			FmtStr = "(" + FmtStr.substring(0,3) + ")~" + FmtStr.substring(3,6) + "-" + FmtStr.substring(6,10);
			textBox.value = FmtStr.replace("~", " ");
				
			if (FmtStr.indexOf(" ") != -1 )
				setCaretPosition(textBox, FmtStr.indexOf(" "));
		}		
	}
	else
	{
		var PhoneNumberInitialString = textBox.value.replace(String.fromCharCode(key), "")
		if (PhoneNumberInitialString == "(   )    -    ")
			textBox.value = String.fromCharCode(key)
	}
}
	
function setCaretPosition(elem, caretPos) 
{
    if(elem != null) {
	if(elem.createTextRange) {
	    var range = elem.createTextRange();
	    range.move('character', caretPos);
	    range.select();
	}
	else {
	    if(elem.selectionStart) {
		elem.focus();
		elem.setSelectionRange(caretPos, caretPos);
	    }
	    else
		elem.focus();
	}
    }
}

function hideElementLeft( elementId )
{
	document.getElementById(elementId).style.left = "-9999px";
}

function showElementLeft( elementId )
{
	document.getElementById(elementId).style.left = "auto";
}

function hideElementDisplay( elementId )
{
	document.getElementById(elementId).style.display = "none";
}

function showElementDisplay( elementId, type )
{
	if (type.toLowerCase() == "inline")
		document.getElementById(elementId).style.display = "inline";
	else
		document.getElementById(elementId).style.display = "block";
}

function selectTextBox( textbox )
{
	var textbox = document.getElementById(textbox) 

	if (!textbox.readOnly)
	{
		// Remove any dollar signs in case they are in the wrong place
		textbox.value = textbox.value.replace("$", "")
		textbox.value = textbox.value.replace("%", "")
		textbox.select()
	}
}

function hideOverTab( elementId )
{
	if (document.getElementById(elementId).className.indexOf("over") > -1)
		document.getElementById(elementId).className = document.getElementById(elementId).className.replace("over", "unselected");
}

function showOverTab( elementId )
{
	if (document.getElementById(elementId).className.indexOf("unselected") > -1)
		document.getElementById(elementId).className = document.getElementById(elementId).className.replace("unselected", "over");
}

function changeVisiblePanel( page, targetPanelId )
{
	var panels = new Array();

	if (page.toLowerCase()=="customers")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlAdvancedSearch';
		panels[2] = 'pnlUnprocessedOrders';
		panels[3] = 'pnlBackorders';
	}
	else if (page.toLowerCase()=="customer")
	{
		panels[0] = 'pnlCustomer';
		panels[1] = 'pnlShippingAddress';
		panels[2] = 'pnlPayments';
		panels[3] = 'pnlAutoships';
	}
	else if (page.toLowerCase()=="pages")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlProductPages';
		panels[2] = 'pnlInformationPages';
	}
	else if (page.toLowerCase()=="autoshipment")
	{
		panels[0] = 'pnlDetail';
		panels[1] = 'pnlSchedule';
		panels[2] = 'pnlAddress';
		panels[3] = 'pnlPayment';
	}
	else if (page.toLowerCase()=="settings")
	{
		panels[0] = 'pnlBusinessInformation';
		panels[1] = 'pnlPayments';
		panels[2] = 'pnlShippingOptions';
		panels[3] = 'pnlOtherSettings';
		panels[4] = 'pnlTechnicalSettings';
		panels[5] = 'pnlTax';
	}
	else if (page.toLowerCase()=="brands")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlBrands';
	}
	else if (page.toLowerCase()=="suppliers")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlSuppliers';
	}
	else if (page.toLowerCase()=="entries")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlEntries';
	}
	else if (page.toLowerCase()=="entry")
	{
		panels[0] = 'pnlEntry';
		panels[1] = 'pnlComments';
		panels[2] = 'pnlPage';
	}
	else if (page.toLowerCase()=="files")
	{
		panels[0] = 'pnlDocuments';
		panels[1] = 'pnlOtherImages';
		panels[2] = 'pnlProductImages';
	}
	else if (page.toLowerCase()=="products")
	{
		panels[0] = 'pnlQuickSearch';
		panels[1] = 'pnlProducts';
	}
	
	for (i=0; i<panels.length; i++) 
	{ 
		hideElementDisplay(panels[i]);
		document.getElementById(panels[i].replace("pnl", "sub")).className = document.getElementById(panels[i].replace("pnl", "sub")).className.replace(" selected", " unselected");
	}

	showElementDisplay(targetPanelId, 'block');
	document.getElementById(targetPanelId.replace("pnl", "sub")).className = document.getElementById(targetPanelId.replace("pnl", "sub")).className.replace("over", "selected").replace("unselected", "selected");
	document.getElementById('hfTabId').value = targetPanelId;
}


/*********************************************************************
 * No onMouseOut event if the mouse pointer hovers a child element 
 * *** Please do not remove this header. ***
 * This code is working on my IE7, IE6, FireFox, Opera and Safari
 * 
 * Usage: 
 * <div onMouseOut="fixOnMouseOut(this, event, 'JavaScript Code');"> 
 *		So many childs 
 *	</div>
 *
 * @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com		
**/
function is_child_of(parent, child) {
	if( child != null ) {			
		while( child.parentNode ) {
			if( (child = child.parentNode) == parent ) {
				return true;
			}
		}
	}
	return false;
}
function fixOnMouseOut(element, event, JavaScript_code) {
	var current_mouse_target = null;
	if( event.toElement ) {				
		current_mouse_target = event.toElement;
	} else if( event.relatedTarget ) {				
		current_mouse_target = event.relatedTarget;
	}
	if( !is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
		eval(JavaScript_code);
	}
	
}
/****************************************************************/

function toggleMenu( dropdownId )
{
	if (document.getElementById(dropdownId).style.left=="auto")
		hideElementLeft(dropdownId);
	else
		showElementLeft(dropdownId);
}

function viewCustomer( customerId )
{
	window.location = '/admin/customer/default.aspx?cid=' + document.getElementById(customerId).value;
}

function viewPage( pageId )
{
	window.location = "/admin/page.aspx?pid=" + document.getElementById(pageId).value;
}

function viewPost( postId )
{
	window.location = "/admin/blog-entries.aspx?entry_id=" + document.getElementById(postId).value;
}

function viewProduct( productId )
{
	window.location = "/admin/product.aspx?pid=" + document.getElementById(productId).value;
}

function displayMessage( title, message, type, commandId, commandArgument, link, functionCall )
{
	var cancel = document.getElementById('btnClose');

	document.getElementById("lblTitle").innerHTML = title;
	
	document.getElementById("lblMessage").innerHTML = message;
	document.getElementById("lblMessage").className = type;
	cancel.innerHTML = "Ok";
	popMessage.showPopup();
	
	if ( commandId != undefined )
	{
		cancel.innerHTML = "Cancel";
		
		var footer = document.getElementById('phOkButton');
		footer.innerHTML = "";
		
		var newSpan = document.createElement('span');
		newSpan.setAttribute('id','btnOk');
		newSpan.innerHTML = "Ok";
		
		if (commandId.length==0)
			alert('control id missing.');
		
		if ( link != undefined )
			addEventHandler(newSpan, 'click', function () { window.location = link } )
		else if ( functionCall != undefined )
			addEventHandler(newSpan, 'click', functionCall )
		else
			addEventHandler(newSpan, 'click', function () { popMessage.hidePopup(); __doPostBack( commandId.replace('_', '$'), commandArgument ); } )
		
		footer.appendChild(newSpan);
	}
	
	return false;
}

function getActiveObject(e)
{
	var obj;
	
	if (!e)
		obj = window.event.scrElement;
	else if (e.srcElement)
		obj = e.srcElement;
	else
		obj = e.target;
		
	return obj;
}

function addEventHandler(obj, eventName, handler)
{
	if (document.attachEvent)
		obj.attachEvent("on" + eventName, handler);
	else if (document.addEventListener)
		obj.addEventListener(eventName, handler, false);
}

function removeEventHandler(obj, eventName, handler)
{
	if (document.removeEvent)
		obj.removeEvent("on" + eventName, handler);
	else if (document.addEventListener)
		obj.removeEventListener(eventName, handler, false);
}


/*******************************************************************************************
Manage File Functions 
********************************************************************************************/
function loadPreviewFile( sourceId )
{
	document.getElementById("previewPanel").innerHTML = document.getElementById( sourceId ).innerHTML
}

function chooseImage( url )
{
	document.getElementById("hfSelectedFile").value = url;
	
        // insert file into active editor
	if (document.getElementById('hfFileTarget').value == 'product')
		document.getElementById("imgProduct").src = url;
	else if (document.getElementById('hfFileTarget').value == 'textbox')
	{
		if (document.getElementById('rbDocuments'))
			if (document.getElementById('rbDocuments').checked)
				tinyMCE.execCommand('mceInsertContent',false,"<a href='" + url + "'>Download</a>");
		if (document.getElementById('rbOtherImages'))
			if (document.getElementById('rbOtherImages').checked)
				tinyMCE.execCommand('mceInsertContent',false,"<img src='" + url + "' />");
		if (document.getElementById('rbProductImages'))
			if (document.getElementById('rbProductImages').checked)
				tinyMCE.execCommand('mceInsertContent',false,"<img src='" + url + "' />");
	}
	
	popFiles.hidePopup();
}

function deleteFile( deletePath, fileName )
{
	if (document.getElementById('previewPanel'))
		document.getElementById("previewPanel").innerHTML = "No file is selected.";

	sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=deleteUrl&param=' + escape(deletePath + fileName), null,
		function ( responseData ) 
		{
			if (document.getElementById('previewPanel'))
			{
				document.getElementById("previewPanel").innerHTML = "No file is selected.";
				document.getElementById("hfSelectedFile").value = "";
				setFileListing()
			}
			
			if (document.getElementById('popupFile_' + fileName))
				document.getElementById('popupFile_' + fileName).parentNode.removeChild(document.getElementById('popupFile_' + fileName));
				
			if (document.getElementById('mainFile_' + fileName))
				document.getElementById('mainFile_' + fileName).parentNode.removeChild(document.getElementById('mainFile_' + fileName));
		} 
		, false);
}

function updateFileListing()
{
	if (document.getElementById('fileList'))
	{
		document.getElementById("pnlFileListing").innerHTML = "Loading...";
		document.getElementById("pnlOtherImageListing").innerHTML = "Loading...";
		document.getElementById("pnlProductImageListing").innerHTML = "Loading...";
		
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=true&path=' + escape(document.getElementById('hfRelativeFilesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlFileListing").innerHTML = responseData;
			} 
			, false);
			
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=true&path=' + escape(document.getElementById('hfRelativeOtherImagesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlOtherImageListing").innerHTML = responseData;
			} 
			, false);
			
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=true&path=' + escape(document.getElementById('hfRelativeProductImagesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlProductImageListing").innerHTML = responseData;
			} 
			, false);
	}
	
	if (document.getElementById('pnlFileListingMain'))
	{	
		document.getElementById('pnlFileListingMain').innerHTML = "Loading...";
		document.getElementById("pnlOtherImageListingMain").innerHTML = "Loading...";
		document.getElementById("pnlProductImageListingMain").innerHTML = "Loading...";
		
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=false&path=' + escape(document.getElementById('hfRelativeFilesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlFileListingMain").innerHTML = responseData;
			} 
			, false);
			
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=false&path=' + escape(document.getElementById('hfRelativeOtherImagesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlOtherImageListingMain").innerHTML = responseData;
			} 
			, false);
			
		sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFiles&popup=false&path=' + escape(document.getElementById('hfRelativeProductImagesPath').value), null,
			function ( responseData ) 
			{ 
				document.getElementById("pnlProductImageListingMain").innerHTML = responseData;
			} 
			, false);
	}
}

function loadSelectedFile( filePath )
{
	document.getElementById("previewPanel").innerHTML = "Loading..."

	sendAjaxRequest('/includes/javascript/ajax-feeds/file.aspx?action=getFile&path=' + escape(filePath), null,
		function ( responseData ) 
		{ 
			document.getElementById("previewPanel").innerHTML = responseData;
		} 
		, false);
}

function setFileListing()
{
	if ( document.getElementById('rbDocuments') )
		if ( document.getElementById('rbDocuments').checked )
		{
			hideElementDisplay('pnlOtherImageListing'); 
			hideElementDisplay('pnlProductImageListing'); 
			showElementDisplay('pnlFileListing', 'block');
			swfu.removePostParam("path");
			swfu.addPostParam("path", document.getElementById('hfRelativeFilesPath').value);
		}
	
	if ( document.getElementById('rbOtherImages') )
		if ( document.getElementById('rbOtherImages').checked )
		{
			hideElementDisplay('pnlFileListing'); 
			hideElementDisplay('pnlProductImageListing'); 
			showElementDisplay('pnlOtherImageListing', 'block');
			swfu.removePostParam("path");
			swfu.addPostParam("path", document.getElementById('hfRelativeOtherImagesPath').value);
		}
	
	if ( document.getElementById('rbProductImages') )
		if ( document.getElementById('rbProductImages').checked )
		{
			hideElementDisplay('pnlFileListing'); 
			hideElementDisplay('pnlOtherImageListing'); 
			showElementDisplay('pnlProductImageListing', 'block');
			swfu.removePostParam("path");
			swfu.addPostParam("path", document.getElementById('hfRelativeProductImagesPath').value);
		}
}

//function openItemList( newList, listID )
//{
//	popList_open();
//	setItemList( newList );
//}

//function openItemListPopup( newList, listID )
//{
//	popList.showPopup();
//	setItemList( newList );
//}

function setItemList( listState )
{
	if (listState == "addnew")
	{
		hideElementDisplay( "pnlPreviousList" );
		hideElementDisplay( "pnlItemList" );
		hideElementDisplay( "pnlList" );

		hideElementDisplay( "btnSaveList" );
		hideElementDisplay( "btnDeleteList" );
		hideElementDisplay( "btnDeleteItems" );
		showElementDisplay( "btnAddList", "inline" );
		
		document.getElementById("txtListName").value = "";
	}
	else if (listState == "editnew")
	{
		showElementDisplay( "pnlPreviousList", "block" );
		showElementDisplay( "pnlItemList", "block" );
		hideElementDisplay( "pnlList");

		showElementDisplay( "btnSaveList", "inline" );
		showElementDisplay( "btnDeleteList", "inline" );
		showElementDisplay( "btnDeleteItems", "inline" );
		hideElementDisplay( "btnAddList", "inline" );
	}
	else
	{
		showElementDisplay( "pnlPreviousList", "block" );
		showElementDisplay( "pnlItemList", "block" );
		showElementDisplay( "pnlList", "block" );

		showElementDisplay( "btnSaveList", "inline" );
		showElementDisplay( "btnDeleteList", "inline" );
		showElementDisplay( "btnDeleteItems", "inline" );
		hideElementDisplay( "btnAddList", "inline" );
	}

	document.getElementById("hfListState").value = listState;
}

function getCurrentTime()
{
	var a_p = "";
	var d = new Date();
	var curr_hour = d.getHours();
	
	if (curr_hour < 12)
		a_p = "AM";
	else
		a_p = "PM";

	if (curr_hour == 0)
		curr_hour = 12;
	
	if (curr_hour > 12)
		curr_hour = curr_hour - 12;

	var curr_min = d.getMinutes();
	curr_min = curr_min + "";

	if (curr_min.length == 1)
		curr_min = "0" + curr_min;

	return curr_hour + " : " + curr_min + " " + a_p;
}

function fireLinkButtonOnEnter(evt, linkButtonID)
{
    if(evt.which || evt.keyCode)
    {
	if((evt.which == 13) || (evt.keyCode == 13))
	{
	location = document.getElementById(linkButtonID).href;
	return false;   
    }
	return true;
    }
}

function toggleTextBoxStatus(linkId, textBoxId, checkBoxId)
{
	if (document.getElementById(checkBoxId).checked)
	{
		document.getElementById(textBoxId).setAttribute('readonly','readonly');
		// ie does not gray out a disabled textbox
		document.getElementById(textBoxId).style.backgroundColor = "#EBEBE4";
		
		document.getElementById(linkId).innerHTML = "manual";
		document.getElementById(checkBoxId).checked = false;
	}
	else
	{
		document.getElementById(textBoxId).removeAttribute('readonly','');
		// ie does not gray out a disabled textbox
		document.getElementById(textBoxId).style.backgroundColor = "";
		
		document.getElementById(linkId).innerHTML = "auto";
		document.getElementById(checkBoxId).checked = true;
	}
	
}

function setTextBoxStatus(linkId, textBoxId, checkBoxId)
{
	if (document.getElementById(checkBoxId).checked)
	{
		document.getElementById(textBoxId).removeAttribute('readonly','');
		// ie does not gray out a disabled textbox
		document.getElementById(textBoxId).style.backgroundColor = "";
		
		document.getElementById(linkId).innerHTML = "auto";
	}
	else
	{
		document.getElementById(textBoxId).setAttribute('readonly','readonly');
		// ie does not gray out a disabled textbox
		document.getElementById(textBoxId).style.backgroundColor = "#EBEBE4";
		
		document.getElementById(linkId).innerHTML = "manual";
	}
	
}

function saveProductPage()
{

	var postStr = "action=update";
	
	postStr += "&" + tempProduct.save();
	postStr += "&" + tempPricing.save();
	postStr += "&" + tempSections.save();
	postStr += "&" + tempPages.save();
	
	document.getElementById('pnlSimpleMessage').innerHTML = "Saving... Please wait.";
	
	sendAjaxRequest('/includes/javascript/ajax-feeds/product.aspx', postStr, 
		function( responseData )
		{
			var results = new Array()
			results = responseData.split("#@#");
		
			if (results[0] == "success")
			{
				document.getElementById('productName').innerHTML = tempProduct.name.value;
				document.getElementById('hfProductID').value = results[1];
				
				tempProduct = new product(results[1]);
				
				// Assign priceIds to all price rows
				var tempPricingArray = new Array()
				tempPricingArray = results[2].replace('pricing=','').split("@%@");
				
				for (x = 0; x < tempPricingArray.length; x++)
				{
					var tempPriceRowArray = new Array()
					tempPriceRowArray = tempPricingArray[x].split("@#@")
					tempPricing.updatePriceIdByIndex( tempPriceRowArray[0], tempPriceRowArray[1] )
				}
				
				// Assign sectionIds to all rows
				var tempSectionArray = new Array()
				tempSectionArray = results[3].replace('sections=','').split("@%@");
				
				for (x = 0; x < tempSectionArray.length; x++)
				{
					var tempSectionRowArray = new Array()
					tempSectionRowArray = tempSectionArray[x].split("@#@")
					tempSections.updateSectionIdByIndex( tempSectionRowArray[0], tempSectionRowArray[1] )
				}
				
				// Assign pageIds to all rows
				var tempPageArray = new Array()
				tempPageArray = results[4].replace('pages=','').split("@%@");

				for (x = 0; x < tempPageArray.length; x++)
				{
					var tempPageRowArray = new Array()
					tempPageRowArray = tempPageArray[x].split("@#@")
					tempPages.updatePageIdByIndex( tempPageRowArray[0], tempPageRowArray[1] )
				}
				
				if (document.getElementById('pnlDelete'))
					document.getElementById('pnlDelete').style.display = "inline";
				
				if ( document.getElementById('cbCreatePage') )
					if ( document.getElementById('cbCreatePage').checked )
					{
						postStr = "action=update";

						postStr += "&" + tempPage.save();
						postStr += "&" + tempCategories.save();
						
						sendAjaxRequest('/includes/javascript/ajax-feeds/page.aspx', postStr, 
							function( responseData )
							{
								results = responseData.split("#@#");
								
								if (results[0] == "success")
								{
									tempPage = new page(results[1]);
									
									postStr = "action=link";

									postStr += "&pid=" + tempProduct.productId;
									postStr += "&pageid=" + results[1];
									
									// Assign categoryIds to all rows
									var tempCategoryArray = new Array()
									tempCategoryArray = results[2].replace('categories=','').split("@%@");

									for (x = 0; x < tempCategoryArray.length; x++)
									{
										var tempCategoryRowArray = new Array()
										tempCategoryRowArray = tempCategoryArray[x].split("@#@")
										tempCategories.updateCategoryIdByIndex( tempCategoryRowArray[0], tempCategoryRowArray[1] )
									}
									
									sendAjaxRequest('/includes/javascript/ajax-feeds/product.aspx', postStr, 
										function( responseData )
										{
											results = responseData.split("#@#");
											
											if (results[0] == "success")
											{
												if (tempPages.rowCount == 0)
													tempPages.add(results[1], tempPage.pageId, tempPage.pageTitle.value, 'true', false);
												else
													tempPages.add(results[1], tempPage.pageId, tempPage.pageTitle.value, 'false', false);
												
												document.getElementById('pnlExistingPage').style.display = "none";
												document.getElementById('pnlCreatePage').style.display = "none";
												showElementDisplay( 'cpExistingPage', 'block'); 
												
												document.getElementById('cbCreatePage').checked = false;
												document.getElementById('pnlSimpleMessage').innerHTML = "Saved (" + getCurrentTime() + ")";
											}
											else
												alert('Error adding product to newly created product page.' + responseData);
										}
										, false);
								}
								else
								{
									document.getElementById('pnlSimpleMessage').innerHTML = "";
									displayMessage( "Please correct the following...", results[1], "error");
								}
							}
							, false);
					}
					else
					{
						document.getElementById('pnlSimpleMessage').innerHTML = "Saved (" + getCurrentTime() + ")";
					}
				else
					{
						document.getElementById('pnlSimpleMessage').innerHTML = "Saved (" + getCurrentTime() + ")";
					}
			}
			else
			{
				document.getElementById('pnlSimpleMessage').innerHTML = "";
				displayMessage( "Please correct the following...", results[1], "error");
			}
		}
		, false);

}

function replaceNonAlphaNumericCharacters( string, replacement )
{
	string = string.replace(/[^a-zA-Z0-9]+/g,replacement);
	
	while (string.indexOf(replacement + replacement) > -1)
		string = string.replace(replacement + replacement, replacement);
	
	string = string.replace(/-$/g,'');
	string = string.replace(/^-/g,'');
	
	return string;
}

function determinePageName( id, directoryControlId, pageName, targetControlId, type )
{
	postStr = "action=checkpagename";

	if (type == 'page')
		postStr += "&pid=" + id;
	else if (type == 'blog')
		postStr += "&bid=" + id;

	postStr += "&page=" + replaceNonAlphaNumericCharacters( pageName, "-" ).toLowerCase() + '.aspx';
	postStr += "&directory=" + document.getElementById(directoryControlId).value;
	
	if (type == 'page')
		sendAjaxRequest('/includes/javascript/ajax-feeds/page.aspx', postStr, 
			function( responseData )
			{
				if (document.getElementById(targetControlId).value.length == 0)
					document.getElementById(targetControlId).value = responseData
			}
		, false);
	else if (type == 'blog')
		sendAjaxRequest('/includes/javascript/ajax-feeds/blog.aspx', postStr, 
			function( responseData )
			{
				if (document.getElementById(targetControlId).value.length == 0)
					document.getElementById(targetControlId).value = responseData
			}
		, false);
}

function setDirectoryPath( targetId, sourceId )
{
	document.getElementById(targetId).value = "/" + replaceNonAlphaNumericCharacters( document.getElementById(sourceId).value, "-" ).toLowerCase() + "/"
}