var isIE = isInternetExplorer();

function isInternetExplorer() {
	var appVer = navigator.appVersion;
	appVer = appVer.split(';');
	if(String(appVer[1]).indexOf('MSIE') > -1) {
		return true;
	} else {
		return false;
	}
}

function getUrl(url){
	window.location = url;
}

function isBlank(item) {
	item = String(item).toLowerCase();
	if(item == "undefined" || item == "" || item == "null") return true;
	else return false;
}

/**** ITEM DATA TABS FUNCTIONS ****/
function itemDataTabs(){
	var itemDataTabs = document.getElementById("itemDataTabs");
	if(itemDataTabs){
		tabs = itemDataTabs.getElementsByTagName("IMG");
		for(i=0;i<2;i++){
			var s = tabs[i].id;
			var tabName = s.substring(0,6)		
			var imagePos = s.substring(6,12)	
			if(imagePos == "ImgLft" || imagePos == "ImgRgt"){
				document.getElementById(tabName + "Tab").className = "tabs_active";
				document.getElementById(tabName + "Content").style.display = "block";
				var imgSrc = document.getElementById(s).src;
				var newImgSrc = imgSrc.replace("_inactive_","_active_");
				document.getElementById(s).src = newImgSrc;
			}
		}
	}
}


function resetItemDataTabs(){
	var itemDataTabs = document.getElementById("itemDataTabs");
	var tabs = itemDataTabs.getElementsByTagName("IMG");
	for(i=0;i<tabs.length;i++){
		var s = tabs[i].id;
		var tabName = s.substring(0,6)		
		var imagePos = s.substring(6,12)	
		if(imagePos == "ImgLft" || imagePos == "ImgRgt"){
			document.getElementById(tabName + "Tab").className = "tabs_inactive";
			document.getElementById(tabName + "Content").style.display = "none";
			var imgSrc = document.getElementById(s).src;
			var newImgSrc = imgSrc.replace("_active_","_inactive_");
			document.getElementById(s).src = newImgSrc;
		}
	}
}

function displayTab(elem) {
	resetItemDataTabs();
	var imgLft = document.getElementById(elem + "ImgLft");
	var imgSrcLft = imgLft.src;
	var newImgSrcLft = imgSrcLft.replace("_inactive_","_active_");
	if (document.images){imgLft.src = newImgSrcLft;}
	
	var imgRgt = document.getElementById(elem + "ImgRgt");
	var imgSrcRgt = imgRgt.src;
	var newImgSrcRgt = imgSrcRgt.replace("_inactive_","_active_");
	if (document.images){imgRgt.src = newImgSrcRgt;}
	
	document.getElementById(elem + "Tab").className = "tabs_active";
	document.getElementById(elem + "Content").style.display = "block";
}	

function ieHideSelect(state){
	if(isIE == true) {
		var selectTags = document.getElementsByTagName("SELECT");
		for(var i=0; i<selectTags.length; i++){
			if(state){
				selectTags[i].style.display = "none";
			}else{
				selectTags[i].style.display = "block";
			}
		}
	}
}

function displayStaticPopup(state, pageName){
	if(state == 'on'){
		var ajaxUrl = '/staticPopup?pageName=' + pageName;
		new Ajax.Updater('staticPopupWin', ajaxUrl, {
			onComplete: function s(transport){displayStaticPopupAjaxComplete(state);}
		});
	}else{
		displayStaticPopupAjaxComplete(state)
	}
}

function displayStaticPopupAjaxComplete(state){
	var fadeBg = document.getElementById('fadeBg');
	var staticInfo = document.getElementById('staticPopupWin');
	var winHeight = document.body.clientHeight + 10;
	var winWidth = document.body.clientWidth;
	var y = getOffset("y");
	var top = y + 100; 
	
	if(state == 'on'){
		ieHideSelect(true);
		//************ SET DIV WIDTHS *************
		fadeBg.style.height = winHeight + 'px';
		fadeBg.style.width = winWidth + 'px';
		//************ SET DIV POSITION FROM TOP *************
		staticInfo.style.top = top + 'px';
		//************ SET DIV DISPLAY *************
		fadeBg.style.display = "block";
		staticInfo.style.display = "block";
	}else{
		ieHideSelect(false);
		fadeBg.style.display = "none";
		staticInfo.style.display = "none";
	}
}

function emailProduct() {
	$('emailProductFormId').request(
	{
		onSuccess: function(transport)
				   { 
				   		var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
					   		document.getElementById("emailProductDiv").innerHTML = html;
				   		}
				   		else
				   		{
				   			$('emailProductErrors').innerHTML = html;
				   			$('emailProductErrorsSection').show();
				   		}
				   }
	});
	
	return false;
}

function compareItems() {
	var itemString = "";
	var checkboxes = document.getElementsByClassName('item_checkbox', $('itemListing'));
	var numChecked = 0;

	if(checkboxes)
	{
		for(i=0;i<checkboxes.length;i++)
		{
			var item = checkboxes[i];

			if (item.checked) {
				var itemkey = item.id.sub('itemList_', '');
				itemString += itemkey + ';';
				numChecked++;
			}
		}
	}

	if (numChecked == 0) {
		alert("Please select at least one item");
	} else if (numChecked > 4) {
		alert("Please select at most four items");
	} else {
		showBBox('Compare Items', '/productCompare?keys=' + itemString, '');
	}
}

function removeCompareItem(itemKey) {
	var items = $('comparedItems').value.split(";");
	var itemString = "";
	var numCompare = 0;

	for (i=0;i<items.length;i++)
	{
		if (items[i] != itemKey)
		{
			itemString += items[i] + ';';
			if (items[i] != '') {
				numCompare++;
			}
		}
	}

	if (numCompare > 1) {
		showBBox('Compare Items', '/productCompare?keys=' + itemString, '');
	} else {
		alert("At least two items must be compared");
	}
}


function getOffset(which){
	//********************************************************//
	//*********** FIND TOP POSITION OF SCROLLED AREA *********//
	//********************************************************//
	var x,y;
	// all except Explorer
	if (self.pageYOffset){ 
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	// Explorer 6 Strict
	else if (document.documentElement && document.documentElement.scrollTop){
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body){ 
	// all other Explorers
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	if(which == "y"){
		return y;
	}else{
		return x
	}
}

function trimShippingNotes(elem)
{
	var notes = elem.value;
	if(notes != null && notes != undefined && notes.length > 100)
	{
		elem.value = notes.substring(0,100);
	}
}

function fade(el,duration,fadeIn) {
  
  var fadeTime = duration/1000;
  var elem = $(el);
  
  if(fadeIn) {
  	elem.setOpacity(0);
  	elem.show();
  	new Effect.Opacity(elem,
    { 
    	duration: fadeTime, 
      	from: 0.0, 
      	to: 1.0 
    });
  }
  else 
  {
  	new Effect.Opacity(elem,
    { 
    	duration: fadeTime, 
      	from: 1.0, 
      	to: 0.0,
      	afterFinish: hideCart
    });
  }
}

function getUrl(url, method, data) {

	//************************************************************************
	//*** IF METHOD IS "GET" SEND DATA ON URL RATHER THAN IN DATA VARIABLE ***
	//************************************************************************
	if(method == "GET" && !isBlank(data)) {
		url += "?" + data;
		data = "";
	}

	//**********************************************
	//*** MODIFY URL TO PREVENT CACHING ************
	//*** - FIX FOR IE6 DEFAULT CACHING BEHAVIOR ***
	//**********************************************
	var cacheBuster = (new Date()).getTime();
	if(url.indexOf("?") > -1) url += "&cb=" + cacheBuster;
	else url += "?cb=" + cacheBuster;

	//***********************************************
	//*** MODIFY XMLHTTP REQUEST BASED ON BROWSER ***
	//***********************************************
	if(isBlank(method)) method = "GET";
	var xmlhttp = new Object();
	if(isIE) {
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		var xmlhttp = new XMLHttpRequest();
	}
	xmlhttp.open(method, url, false);
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send(data);
	var responseText = String(xmlhttp.responseText);
	xmlhttp = null;
	
	//**************
	//*** RETURN ***
	//**************	
	return responseText;
}

function emptyCart() {
	
	new Ajax.Updater('', '/emptyCart', {
		method: 'post',
		onSuccess: function(transport)
		{
			$('fullPageCartContent').replace(transport.responseText);
			var fcItemsInCart = document.getElementById('cartItemsInCartForFloating').innerHTML;
			var fcTotalFormatted = document.getElementById('cartTotalCartForFloating').innerHTML;
			var fcInfoOnPageHTML = fcItemsInCart + ' <span>Items:</span> ' + fcTotalFormatted;
			document.getElementById("fcInfoOnPage").innerHTML = fcInfoOnPageHTML;
			
			new Ajax.Updater('fc', '/viewFloatingCart',{});
		}
	});
}

function addCart() {

	var styleSelect = document.getElementById("attr_0");
	if(styleSelect) 
	{
		var selIndex = styleSelect.selectedIndex;
		var itemKey = styleSelect.options[selIndex].value;
		$('itemId').writeAttribute({'value':itemKey});
	}
}

function addToWishList()
{
	var styleSelect = document.getElementById("attr_0");
	if(styleSelect) 
	{
		var selIndex = styleSelect.selectedIndex;
		var itemKey = styleSelect.options[selIndex].value;
		$('itemKey').value = itemKey;
		document.getElementById('wishListForm').submit();
	}
	else
	{
		document.getElementById('wishListForm').submit();
	}
}

function wishListToCart(index)
{
		var form = "wishListForm_" + index; 
		eval('document.' + form + '.action= "/addWishToCart"');
		eval('document.' + form + '.submit()'); 
}

function wishListAddAllToCart(group){
	var itemKeyString ="" ;
	for (var i=0;i<document.forms.length;i++) {
		var elementItemKey = "";
		var elementQuantity = "";
		
		for (var z=0;z<document.forms[i].elements.length;z++) {
			var element	= document.forms[i].elements[z];
			if(element.name == "itemKey"){
				elementItemKey = element.value;
			}
			if(element.name == "wishQuantity"){
			
				elementQuantity = element.value;
			}
		}
		itemKeyString += elementItemKey + '-' + elementQuantity + ';';
	}
	
	return itemKeyString;	
}

//**************************************************
//************** BEGIN PCS SCRIPT ******************
//**************************************************
function calculateShippingFromCart()
{
	$('shipCalcCartForm').request(
	{
		onSuccess: function(transport)
				   { 
				   		var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			$('calcShippingErrorsSection').hide();
					   		$('shippingCalcResultText').innerHTML = transport.responseText;
					   		document.getElementById("shippingCalcResult").style.display = "";
				   		}
				   		else
				   		{
				   			$('shippingCalcResult').hide();
				   			$('calcShippingErrors').innerHTML = html;
				   			$('calcShippingErrorsSection').show();
				   		}
				   }
	});
	
	return false;
}

function displayEmailCartPopup()
{
	$('friendName').writeAttribute({'value':''});
	$('friendEmail').writeAttribute({'value':''});
	$('yourName').writeAttribute({'value':''});
	$('yourEmail').writeAttribute({'value':''});
	$('emailCartErrorsSection').hide();
	displayPopup('EmailCart','on');
}

function emailCart()
{
	$('emailCartFormId').request(
	{
		onSuccess: function(transport)
				   { 
				   		var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("emailCartDiv").innerHTML = html;
				   		}
				   		else
				   		{
				   			$('emailCartErrors').innerHTML = html;
				   			$('emailCartErrorsSection').show();
				   		}
				   }
	});
	
	return false;
}

function saveCart()
{
	$('saveCartFormId').request(
	{
		onSuccess: function(transport)
				   { 
				   
				   		var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			hideBBox();
				   			document.getElementById('cartName').value = "";
				   			document.getElementById('savedCartResults').innerHTML = html;
				   		}
				   		else
				   		{
				   			$('saveCartErrors').innerHTML = html;
				   			$('saveCartErrorsSection').show();
						}
				   }
	});
	
	return false;
}

function addDestination(checkoutItemId)
{
	var multiSectionDiv = "multiLineSection_" + checkoutItemId;
	new Ajax.Updater('', '/multiShipAddDestination', 
	{
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	   			
	   			document.getElementById(multiSectionDiv).innerHTML = jsonResult.line;
	   			document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
	   		}
		}
	});
}

function removeDestination(checkoutItemId, checkoutLineId)
{
	var multiSectionDiv = "multiLineSection_" + checkoutItemId;
	new Ajax.Updater('', '/multiShipRemoveDestination', 
	{
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId,
			'checkoutLineId': checkoutLineId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	   			
	   			document.getElementById(multiSectionDiv).innerHTML = jsonResult.line;
	   			document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
	   		}
		}
	});
}

function syncFields(fieldNameSrc, fieldNameDest)
{
	var isSame = document.getElementById('shippingSameAsBilling').checked;

	if(isSame)
	{
		var fieldSrc = document.getElementById(fieldNameSrc);
		var fieldDest = document.getElementById(fieldNameDest);
	
		fieldDest.value = fieldSrc.value;
	}
}

function loadSavedShippingAddress(addressKey, url)
{
	if(addressKey == "")
	{
		return;
	}
	
	new Ajax.Updater('', url, {
		parameters: 
		{ 
			'addressKey': addressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{
			document.getElementById("shippingAddressDiv").innerHTML = transport.responseText;
		}
	});
}

function updateMultiShippingQty(checkoutItemId, checkoutLineId)
{
	var oldValueElem = $('multiQuantityOld_' + checkoutLineId);
	var newValueElem = $('multiQuantity_' + checkoutLineId);
	
	var oldValue = oldValueElem.readAttribute('value');
	var newValue = newValueElem.readAttribute('value');
	
	// only update if the old and new values are different
	if(parseInt(oldValue) != parseInt(newValue))
	{
		new Ajax.Updater('', '/multiShipUpdateQty', {
			parameters: 
			{ 
				'checkoutItemId': checkoutItemId,
			    'checkoutLineId': checkoutLineId,
			    'quantity': newValue
			},
			method: 'post',
			onSuccess: function(transport)
			{
				var html = transport.responseText;
				if(html == "error" || html.indexOf('pcs-error-messages') >= 0)
				{
					// there was an error updating the quantities 
					// so just revert the changed quantity back to its old value
					document.getElementById('multiQuantity_' + checkoutLineId).value = oldValue;
				}
				else
				{
					eval("var jsonResult = " + html);
					
					var quantities = jsonResult.quantities;
					for(var i=0; i<quantities.qtyChanges.length; i++)
					{
						var qtyChange = quantities.qtyChanges[i];
	
						if(qtyChange.isFirst == "true")
						{
							$('multiQuantity_' + qtyChange.oln).innerHTML = qtyChange.qty;
						}
						else
						{
							// change the old value first
							$('multiQuantityOld_' + qtyChange.oln).writeAttribute({'value':qtyChange.qty});
							$('multiQuantity_' + qtyChange.oln).writeAttribute({'value':qtyChange.qty});
						}
					}
					
					document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
				}
			}
		});
	}
}

function updateMultiShippingAddress(checkoutItemId, checkoutLineId, shipAddressKey)
{
	new Ajax.Updater('', '/multiShipUpdateAddress', {
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId,
		    'checkoutLineId': checkoutLineId,
		    'shipAddressKey': shipAddressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
			{
				document.getElementById('checkoutPrices').innerHTML = html;
			}
		}
	});
}

function updateMultiShippingReorder(checkoutItemId, checkoutLineId, reorder)
{
	new Ajax.Updater('', '/multiShipUpdateReorder', {
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId,
		    'checkoutLineId': checkoutLineId,
		    'reorder': reorder
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
			{
				document.getElementById('checkoutPrices').innerHTML = html;
			}
		}
	});
}

function updateMultiShippingMethod(checkoutItemId, checkoutLineId, shippingMethod)
{
	new Ajax.Updater('', '/multiShipUpdateMethod', {
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId,
		    'checkoutLineId': checkoutLineId,
		    'shippingMethod': shippingMethod
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
			{
				document.getElementById('checkoutPrices').innerHTML = html;
			}
		}
	});
}

function updateMultiShippingPrices()
{
	new Ajax.Updater('', '/multiShipPrices', {
			method: 'post',
			onSuccess: function(transport)
			{
				var html = transport.responseText;
				if(html.indexOf('lv-error-messages') < 0)
		   		{
		   			document.getElementById("checkoutPrices").innerHTML = html;
		   		}
			}
		});
}

function updateMultiShipping(checkoutItemId)
{
	$('multiShipForm').request(
	{
		parameters: 
		{ 
			'checkoutItemId':checkoutItemId,
			'skipValidation':true
		},
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
			if(html.indexOf('lv-error-messages') < 0)
	   		{
	   			document.getElementById("checkoutPrices").innerHTML = html;
	   		}
		}
	});
}

function newMultiShipRecipient()
{
	$('MultiShippingNewRecipientForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	
				var recipient = jsonResult.recipient;
		
				// get the information from the json response
				var addressKey = recipient.address.id;
				var addressOption = recipient.address.value;
				var checkoutItemId = recipient.address.checkoutItemId;
				var checkoutLineId = recipient.address.checkoutLineId;

				// add the option to each field
				var addressSelects = document.getElementsByName("updatedShippingAddresses");
				for(var i=0; i<addressSelects.length; i++)
				{
					// create the option to add to all shipping address select fields
					var newAddressOption = new Option(addressOption,addressKey);
					var addressSelect = addressSelects[i];
					var len = addressSelect.length;
					addressSelect.options[len] = newAddressOption;
				}
		
				// set the new address to be the address for the order line we clicked new recipient for
				var currentSelect = document.getElementById("multiLineAddress_" + checkoutLineId);
				currentSelect.selectedIndex = currentSelect.options.length - 1;

				// replace prices
				document.getElementById("checkoutPrices").innerHTML = jsonResult.prices;
	
				hideBBox();
	   		}
	   		else
	   		{
	   			$('newRecipientErrors').innerHTML = html;
	   			$('newRecipientErrorsSection').show();
			}
		}
	});
	
	return false;
}

function removeSelectOptions(elem)
{
	var selectElem = document.getElementById(elem);
	for(var count = selectElem.options.length - 1; count >= 0; count--)
    {
        selectElem.options[count] = null;
    }
}

function editAddress()
{
	$('EditAddressForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				var address = jsonResult.address;
				var addressKey = address.addressKey;
				
				$(addressKey + '_firstName').innerHTML = address.firstName;
				$(addressKey + '_lastName').innerHTML = address.lastName;
				$(addressKey + '_street1').innerHTML = address.street1;
				if(document.getElementById(addressKey + '_street2') != null) {
					$(addressKey + '_street2').innerHTML = address.street2;
				}
				$(addressKey + '_city').innerHTML = address.city;
				$(addressKey + '_state').innerHTML = address.state;
				$(addressKey + '_zip').innerHTML = address.zip;
				$(addressKey + '_country').innerHTML = address.country;
				if(document.getElementById(addressKey + '_phoneAreaCode') != null) {
					$(addressKey + '_phoneAreaCode').innerHTML = address.phoneAreaCode;
					$(addressKey + '_phone3').innerHTML = address.phone3;
					$(addressKey + '_phone4').innerHTML = address.phone4;
				}
				if(document.getElementById(addressKey + '_phoneExt') != null) {
					$(addressKey + '_phoneExt').innerHTML = address.phoneExt;
				}
				$(addressKey + '_email').innerHTML = address.email;
				
				displayPopup('EditAddressBookAddress','off');
			}
			else {
				$('editAddressErrors').innerHTML = html;
	   			$('editAddressErrorsSection').show();
			}
		}
	});
	
	return false;
}

function addAddress(elem)
{
	$('AddAddressForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
				$(elem).innerHTML = transport.responseText;
				displayPopup('AddAddressBookAddress','off');
			}
			else {
				$('AddressErrors').innerHTML = html;
	   			$('AddressErrorsSection').show();
			}
		}
	});
	
	return false;
}

function removeAddress(addressKey)
{
	new Ajax.Updater('', '/removeAddress', {
		parameters: 
		{ 
			'addressKey': addressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			document.getElementById("centerContent").innerHTML = html;
			}
			else {
				// there were errors deleting the address
			}
		}
	});
}

function removePaymentOption(paymentOptionKey)
{
	new Ajax.Updater('', '/removePaymentOption', {
		parameters: 
		{ 
			'paymentOptionKey': paymentOptionKey
		},
		method: 'post',
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			document.getElementById("centerContent").innerHTML = html;
			}
			else {
				// there were errors deleting the payment option
			}
		}
	});
}

function displayAddAccountPaymentDialog()
{
	$('AddAccontPaymentErrorsSection').hide();
	displayPopup('AddAccountPayment','on');
}

function addAccountPayment()
{
	$('AddPaymentForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				$('billAddrPayListBlock').innerHTML = html;
				displayPopup('AddAccountPayment','off');
			}
			else {
				$('AddAccountPaymentErrors').innerHTML = html;
	   			$('AddAccontPaymentErrorsSection').show();
			}
		}
	});
	
	return false;
}

function loadCheckoutAccountPayment(accountPaymentKey)
{
	new Ajax.Updater('', '/checkoutLoadAccountPayment', 
	{
		parameters: 
		{ 
			'accountPaymentKey': accountPaymentKey
		},
		onSuccess: function(transport)
		{
			eval("var jsonResult = " + transport.responseText);
			
			$('creditCardType').writeAttribute({'value':jsonResult.paymentType});
			$('creditCardName').writeAttribute({'value':jsonResult.holderName});
			$('creditCardNumber').writeAttribute({'value':jsonResult.ccNumber});
			$('creditCardExpMonth').writeAttribute({'value':jsonResult.expMnth});
			$('creditCardExpYear').writeAttribute({'value':jsonResult.expYr});
			$('creditCardSecurityId').writeAttribute({'value':''});
		}
	});
}

function removeWishRegimen(group, index)
{
	new Ajax.Updater('', '/removeWish', 
	{
		parameters: 
		{ 
			'wishGroup': group,
			'removeIndex': index
		},
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			$('wishRegimenDiv').replace(html);
		}
	});
}

function displayPopup(elem,state){
	var fadeBg = document.getElementById('fadeBg');
	var wrapper = document.getElementById('popupContent');
	if(elem){
		var content = document.getElementById(elem);
		var header = document.getElementById(elem + "Heading");
		
		var headerHTML = "";
		if(header != null)
		{
			headerHTML = document.getElementById(elem + "Heading").innerHTML;
		}
		
		var contentHTML = content.innerHTML;
		var closePanelHTML = document.getElementById('popup_windowClose').innerHTML;
		var html;
		
		/****** LOGIC TO ADD CLOSE PANEL HTML ***********/
		var closeTags = $(elem).getElementsByClassName('popup_windowClose');
		if(closeTags == null || closeTags.length == 0){
			html = closePanelHTML + headerHTML + contentHTML + "<br>";
		}
		else{
			html = contentHTML;
		}
	}
	var winHeight = document.body.clientHeight + 10;
	var winWidth = document.body.clientWidth;
	var y = getOffset("y");

	if(state == 'on'){
		ieHideSelect(true);
		//************ SET DIV WIDTHS *************
		fadeBg.style.height = winHeight + 'px';
		fadeBg.style.width = winWidth + 'px';
		wrapper.style.width = winWidth + 'px';
		//************ SET DIV POSITION FROM TOP *************
		wrapper.style.top = y + 'px';
		//************ SET DIV DISPLAY *************
		if(elem){content.innerHTML = html;}
		fadeBg.style.display = "block";
		wrapper.style.display = "block";
		content.style.display = "block";
	}else{
		ieHideSelect(false);
		fadeBg.style.display = "none";
		wrapper.style.display = "none";
		hideAllPopup();
	}
	
}
function displayGlobalPopup(elem,state){
	var fadeBg = document.getElementById('fadeBg');
	var wrapper = document.getElementById('globalPopupContent');
	if(elem){
		var content = document.getElementById(elem);
		var header = document.getElementById(elem + "Heading");
		
		var headerHTML = "";
		if(header != null)
		{
			headerHTML = document.getElementById(elem + "Heading").innerHTML;
		}
		
		var contentHTML = content.innerHTML;
		var closePanelHTML = document.getElementById('globalPopup_windowClose').innerHTML;
		var html;
		
		/****** LOGIC TO ADD CLOSE PANEL HTML ***********/
		var closeTags = $(elem).getElementsByClassName('popup_windowClose');
		if(closeTags == null || closeTags.length == 0){
			html = closePanelHTML + headerHTML + contentHTML + "<br>";
		}
		else{
			html = contentHTML;
		}
	}
	var winHeight = document.body.clientHeight + 10;
	var winWidth = document.body.clientWidth;
	var y = getOffset("y");

	if(state == 'on'){
		ieHideSelect(true);
		//************ SET DIV WIDTHS *************
		fadeBg.style.height = winHeight + 'px';
		fadeBg.style.width = winWidth + 'px';
		wrapper.style.width = winWidth + 'px';
		//************ SET DIV POSITION FROM TOP *************
		wrapper.style.top = y + 'px';
		//************ SET DIV DISPLAY *************
		if(elem){content.innerHTML = html;}
		fadeBg.style.display = "block";
		wrapper.style.display = "block";
		content.style.display = "block";
	}else{
		ieHideSelect(false);
		fadeBg.style.display = "none";
		wrapper.style.display = "none";
		hideAllPopup();
	}
	
}
function hideAllPopup(){
	var wrapper = document.getElementById('popupContent');
	var divs = wrapper.getElementsByTagName("DIV");
	for(i=0; i<divs.length; i++){
		if(divs[i].className = "popup_window"){
			divs[i].style.display = "none";
		}
	}

	var wrapper = document.getElementById('globalPopupContent');
	var divs = wrapper.getElementsByTagName("DIV");
	for(i=0; i<divs.length; i++){
		if(divs[i].className = "popup_window"){
			divs[i].style.display = "none";
		}
	}
}

function showOrderHistory(sortColumn, url) {
	var selObj = document.getElementById('showOrderBySelection');
	var selIndex = selObj.selectedIndex;
	var enumName = selObj.options[selIndex].value;
		
	window.location.href = url+'?showOrders='+enumName+'&sortColumn='+sortColumn;		
}

function phoneMover(srcElem, destElem, numberDigits)
{
	if(document.getElementById(srcElem).value.length >= numberDigits)
	{
		document.getElementById(destElem).focus();
	}
}

function emptyAutoFillFields(countryElemName, postalElemName, cityElemName, stateElemName, errorsName, errorsSectionName, sCountryElemName, sPostalElemName, sCityElemName, sStateElemName)
{
	var isSame = false;
	var isSameObj = document.getElementById('shippingSameAsBilling');
	if(isSameObj)
	{
		isSame = isSameObj.checked;
	}
	
	// set the state name
	document.getElementById(stateElemName).value = "";
	
	if(isSame)
	{
		document.getElementById(sStateElemName).value = "";
	}
				
	var citySelect = document.getElementById(cityElemName);
	for(var count = citySelect.options.length - 1; count >= 0; count--)
    {
        citySelect.options[count] = null;
    }
    
    if(isSame)
	{
		var sCitySelect = document.getElementById(sCityElemName);
		for(var count = sCitySelect.options.length - 1; count >= 0; count--)
	    {
	        sCitySelect.options[count] = null;
	    }
	}
}

function autoFillAddress(countryElemName, postalElemName, cityElemName, stateElemName, errorsName, errorsSectionName, sCountryElemName, sPostalElemName, sCityElemName, sStateElemName)
{
	var postal = document.getElementById(postalElemName).value;
	var postalOld = document.getElementById(postalElemName + "Old").value;
	
	if(postal == postalOld)
	{
		return;
	}
	
	document.getElementById(postalElemName + "Old").value = postal;
	
	if(postal.strip() == "")
	{
		//$(errorsSectionName).hide();
		//$(postalElemName + "ErrorIcon").hide();
		Effect.Fade(postalElemName + "ErrorIcon", { duration: 0.3 });
		document.getElementById(postalElemName).style.borderColor = "";
		document.getElementById(postalElemName).style.borderWidth = "";
		document.getElementById(postalElemName).style.borderStyle = "";
		emptyAutoFillFields(countryElemName, postalElemName, cityElemName, stateElemName, errorsName, errorsSectionName, sCountryElemName, sPostalElemName, sCityElemName, sStateElemName);
		return;
	}
	
	var countryKey = document.getElementById(countryElemName).value;
	
	
	new Ajax.Updater('', '/addressAutoFill',
	{
		parameters:
		{
			'postal':postal,
			'countryKey':countryKey
		},
		onSuccess: function(transport)
		{
			//$(errorsSectionName).hide();
			
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				//$(postalElemName + "ErrorIcon").hide();
				Effect.Fade(postalElemName + "ErrorIcon", { duration: 0.3 });
				document.getElementById(postalElemName).style.borderColor = "";
				document.getElementById(postalElemName).style.borderWidth = "";
				document.getElementById(postalElemName).style.borderStyle = "";
				
				var isSame = false;
				var isSameObj = document.getElementById('shippingSameAsBilling');
				if(isSameObj)
				{
					isSame = isSameObj.checked;
				}
				
				// set the state name

				document.getElementById(stateElemName).value = jsonResult.state;

				
				if(isSame)
				{
					document.getElementById(sStateElemName).value = jsonResult.state;

				}
				
				// remove the options already in the city select box
				var citySelect = document.getElementById(cityElemName);
				for(var count = citySelect.options.length - 1; count >= 0; count--)
			    {
			        citySelect.options[count] = null;
			    }
			    
			    if(isSame)
				{
					var sCitySelect = document.getElementById(sCityElemName);
					for(var count = sCitySelect.options.length - 1; count >= 0; count--)
				    {
				        sCitySelect.options[count] = null;
				    }
				}
				
				// add the cities to the city select box with keys as postal keys and values as the city name
				var cities = jsonResult.cities;
				var postalKeys = jsonResult.postalKeys;
				
				for(var i=0; i<cities.length; i++)
				{
					// create the option in the city options
					var newOption = new Option(cities[i],postalKeys[i]);
					citySelect.options[i] = newOption;
				}
				
				// select the default city which is the first one in the list
				citySelect.selectedIndex = 0;
				
				if(isSame)
				{
					var sCitySelect = document.getElementById(sCityElemName);
					for(var i=0; i<cities.length; i++)
					{
						// create the option in the city options
						var newOption = new Option(cities[i],postalKeys[i]);
						sCitySelect.options[i] = newOption;
					}
					
					// select the default city which is the first one in the list
					sCitySelect.selectedIndex = 0;
				}
			}
			else {
			
				var isSame = false;
				var isSameObj = document.getElementById('shippingSameAsBilling');
				if(isSameObj)
				{
					isSame = isSameObj.checked;
				}
				
				Effect.Appear(postalElemName + "ErrorIcon", { duration: 0.3 });
				//$(postalElemName + "ErrorIcon").show();
				document.getElementById(postalElemName).style.borderColor = "#FF0000";
				document.getElementById(postalElemName).style.borderWidth = "1px";
				document.getElementById(postalElemName).style.borderStyle = "solid";	
				
				//$(errorsName).innerHTML = html;
	   			//$(errorsSectionName).show();
	   			
	   			// remove the options already in the city select box
				var citySelect = document.getElementById(cityElemName);
				for(var count = citySelect.options.length - 1; count >= 0; count--)
			    {
			        citySelect.options[count] = null;
			    }
			    
			    // empty the state key
			    document.getElementById(stateElemName).value = "";

			    
			    if(isSame)
			    {
			    	var sCitySelect = document.getElementById(sCityElemName);
					for(var count = sCitySelect.options.length - 1; count >= 0; count--)
				    {
				        sCitySelect.options[count] = null;
				    }
				    
				    // empty the state key
				    document.getElementById(sStateElemName).value = "";

			    }
			}
		}
	});
}

var fadeStartColor = "#bae0a2";
var fadeDuration = 1.0;
var fadeDelay = 0.5;
function bbDoEditBilling()
{
	document.getElementById('bbEditBillingForm').action = "/checkoutEditBillingAddressSave";
	
	$('bbEditBillingForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				document.getElementById("checkoutReviewBillingAddress").innerHTML = html;
				hideBBox();
				
				document.getElementById("checkoutReviewBillingAddress").style.backgroundColor = "#bae0a2";
				new Effect.Highlight('checkoutReviewBillingAddress', 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function bbDoEditPaymentMethod()
{
	$('bbEditPaymentMethodForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				document.getElementById("checkoutReviewPaymentType").innerHTML = jsonResult.type;
				document.getElementById("checkoutReviewPaymentHolder").innerHTML = jsonResult.holder;
				document.getElementById("checkoutReviewPaymentNumber").innerHTML = jsonResult.number;
				document.getElementById("checkoutReviewPaymentExp").innerHTML = jsonResult.exp;
				
				hideBBox();
				
				document.getElementById("checkoutReviewPaymentSection").style.backgroundColor = "#bae0a2";
				new Effect.Highlight('checkoutReviewPaymentSection', 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function bbLoadShippingAddress(addressKey, callback, checkoutItemId, checkoutLineId)
{
	if(addressKey == "")
	{
		return;
	}
	
	if(checkoutItemId == null || checkoutItemId == undefined)
	{
		checkoutItemId = 0;
		checkoutLineId = 0;
	}
	
	new Ajax.Updater('', '/checkoutLoadShippingAddress', {
		parameters: 
		{ 
			'addressKey': addressKey,
			'callback': callback,
			'checkoutItemId': checkoutItemId,
			'checkoutLineId': checkoutLineId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			$('bboxContents').innerHTML = transport.responseText;
		}
	});
}

function bbDoEditShippingAddressSingle()
{
	document.getElementById('bbEditShippingForm').action = "/checkoutEditShippingAddressSave";
	
	$('bbEditShippingForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
	   			
	   			document.getElementById('checkoutReviewShippingAddress').innerHTML = jsonResult.address;
	   			document.getElementById('checkoutPricesId').innerHTML = jsonResult.prices;
				
				//updateReviewPrices();	
				hideBBox();

				document.getElementById("checkoutReviewShippingAddress").style.backgroundColor = "#bae0a2";
				new Effect.Highlight('checkoutReviewShippingAddress', 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function updateReviewPrices()
{
	new Ajax.Updater('', '/reviewPrices', {
			method: 'post',
			onSuccess: function(transport)
			{
				var html = transport.responseText;
				if(html.indexOf('pcs-error-messages') < 0)
		   		{
		   			document.getElementById("orderReviewPrices").innerHTML = html;
		   		}
			}
		});
}

function submitPaymentMethod()
{
	copyMultiShipping();
	return true;
}

function copyMultiShipping()
{
	var multis = document.getElementsByName("multiShipIdsSrc");
	if(multis == null || multis == undefined || multis.length == 0)
	{
		return;
	}
	
	var i;
	var paramValue = "";
	for(i=0;i<multis.length;i++)
	{
		if(multis[i].checked)
		{
			if(paramValue != "")
			{
				paramValue += ",";
			}
			
			paramValue += multis[i].value;
		}
	}
	
	document.getElementById("multiShipIds").value = paramValue;
}

var applyingPromotion = false;
function applyCheckoutDiscount()
{
	if(applyingPromotion)
	{
		return false;
	}
	
	applyingPromotion = true;
	var discountCode = document.getElementById("discountCode").value;
	
	if(!discountCode || discountCode == null || discountCode == undefined || discountCode == '')
	{
		applyingPromotion = false;
		return false;
	}
			
	$('applyCheckoutDiscountForm').request(	
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			// success
	   			eval("var jsonResult = " + html);
				
				if(jsonResult.promoResult)
				{
					// the discount was applied
					document.getElementById("checkoutPricesId").innerHTML = jsonResult.prices;
					document.getElementById("applyDiscountText").innerHTML = jsonResult.promoResultText;
					document.getElementById("applyDiscountText").style.color = "#409529";
					document.getElementById("applyDiscountText").style.display = "";
					Effect.Fade("applyDiscountText", { duration: 0.25, delay: 2.0 });
				}
				else
				{
					// the discount was not applied
					document.getElementById("applyDiscountText").innerHTML = jsonResult.promoResultText;
					document.getElementById("applyDiscountText").style.color = "#FF0000";
					document.getElementById("applyDiscountText").style.display = "";
					Effect.Fade("applyDiscountText", { duration: 0.25, delay: 2.0 });
				}
			}
			else {
				// failure
				document.getElementById("applyDiscountText").innerHTML = "Invalid Code";
				document.getElementById("applyDiscountText").style.color = "#FF0000";
				document.getElementById("applyDiscountText").style.display = "";
				Effect.Fade("applyDiscountText", { duration: 0.25, delay: 2.0 });
			}
		},
		onComplete: function()
		{
			document.getElementById("discountCode").value = "";
			applyingPromotion = false;
		}
	});
	
	return false;
}

var applyingCartPromotion = false;
function applyCartDiscount()
{
	if(applyingCartPromotion)
	{
		return false;
	}
	
	applyingCartPromotion = true;
	var discountCode = document.getElementById("discountCode").value;
	
	if(!discountCode || discountCode == null || discountCode == undefined || discountCode == '')
	{
		applyingCartPromotion = false;
		return false;
	}
			
	$('applyCartDiscountForm').request(	
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			// success
	   			eval("var jsonResult = " + html);
				
				if(jsonResult.promoResult)
				{
					// the discount was applied
					document.getElementById("tilesContent").innerHTML = jsonResult.cart;
					document.getElementById("cartApplyDiscountMsgDiv").innerHTML = jsonResult.promoResultText;
					document.getElementById("cartApplyDiscountMsgDiv").style.color = "#409529";
					document.getElementById("cartApplyDiscountMsgDiv").style.display = "";
					Effect.Fade("cartApplyDiscountMsgDiv", { duration: 0.25, delay: 2.0 });
				}
				else
				{
					// the discount was not applied
					document.getElementById("tilesContent").innerHTML = jsonResult.cart;
					document.getElementById("cartApplyDiscountMsgDiv").innerHTML = jsonResult.promoResultText;
					document.getElementById("cartApplyDiscountMsgDiv").style.color = "#FF0000";
					document.getElementById("cartApplyDiscountMsgDiv").style.display = "";
					Effect.Fade("cartApplyDiscountMsgDiv", { duration: 0.25, delay: 2.0 });
				}
			}
			else {
				// failure
				document.getElementById("cartApplyDiscountMsgDiv").innerHTML = "Invalid Code";
				document.getElementById("cartApplyDiscountMsgDiv").style.color = "#FF0000";
				document.getElementById("cartApplyDiscountMsgDiv").style.display = "";
				Effect.Fade("cartApplyDiscountMsgDiv", { duration: 0.25, delay: 2.0 });
			}
		},
		onComplete: function()
		{
			applyingCartPromotion = false;
			document.getElementById("discountCode").value = "";
		}
	});
	
	return false;
}

function bbDoEditShippingAddressMulti()
{
	document.getElementById('bbEditShippingForm').action = "/checkoutReviewEditShipping";
	var checkoutLineId = document.getElementById('checkoutLineId').value;
	
	$('bbEditShippingForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
				
				document.getElementById("checkoutReviewShippingId_" + checkoutLineId).innerHTML = jsonResult.address;
				
				updateReviewPrices();
				hideBBox();
				
				document.getElementById("checkoutReviewShippingIdTr_" + checkoutLineId).style.backgroundColor = "#bae0a2";
				new Effect.Highlight("checkoutReviewShippingIdTr_" + checkoutLineId, 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}	

function bbDoEditShippingNotesMulti()
{
	document.getElementById('bbEditShippingNotesForm').action = "/checkoutReviewEditShippingMethodNotes";
	
	$('bbEditShippingNotesForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				document.getElementById("checkoutReviewNotesId").innerHTML = jsonResult.notes;
	
				hideBBox();
				
				document.getElementById("checkoutReviewShippingNotesSection").style.backgroundColor = "#bae0a2";
				new Effect.Highlight("checkoutReviewShippingNotesSection", 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function bbDoEditShippingMethodMulti()
{
	document.getElementById('bbEditShippingMethodForm').action = "/checkoutReviewEditShippingMethodNotes";
	var checkoutLineId = document.getElementById('checkoutLineId').value;
	
	$('bbEditShippingMethodForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				document.getElementById("checkoutReviewMethodId_" + checkoutLineId).innerHTML = jsonResult.method;
				
				updateReviewPrices();
				hideBBox();
				
				document.getElementById("checkoutReviewMethodIdTr_" + checkoutLineId).style.backgroundColor = "#bae0a2";
				new Effect.Highlight("checkoutReviewMethodIdTr_" + checkoutLineId, 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function bbDoEditShippingMethodNotes()
{
	document.getElementById('bbEditShippingMethodNotesForm').action = "/checkoutReviewEditShippingMethodNotes";
	
	$('bbEditShippingMethodNotesForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				document.getElementById("checkoutReviewShippingMethod").innerHTML = jsonResult.method;
				document.getElementById("checkoutReviewShippingNotes").innerHTML = jsonResult.notes;
				
				updateReviewPrices();
				hideBBox();
				
				document.getElementById("checkoutReviewShippingNotesSection").style.backgroundColor = "#bae0a2";
				new Effect.Highlight("checkoutReviewShippingNotesSection", 
				{
					startcolor:fadeStartColor,
					endcolor:"#FFFFFF",
					restorecolor:"#FFFFFF",
					duration:fadeDuration,
					delay:fadeDelay
				});
			}
			else {
				$("bbErrors").innerHTML = html;
	   			$("bbErrorsSection").show();
			}
		}
	});
}

function showBBoxText(title, contents, boxWidth)
{
	displayBBox(title, contents, boxWidth);
}
	
function showBBoxStatic(title, contentsDiv, boxWidth)
{
      var contents = document.getElementById(contentsDiv).innerHTML;
      displayBBox(title, contents, boxWidth);
}

function showBBox(title, url, callback, boxWidth)
{
      if(callback == null || callback == undefined)
      {
            callback = '';
      }
      
      new Ajax.Updater('', url,
      {
            parameters:
            {
                  'callback':callback
            },
            onSuccess: function(transport)
            {
                  var html = transport.responseText;
                  displayBBox(title, html, boxWidth);
            }
      });
}

var bboxMinWidth = 400;
function displayBBox(title, contents, boxWidth)
{
	  ieHideSelect(true);
      showBackgroundFade();
      var bbox = document.getElementById('bbox');
      
      document.getElementById('bboxTitle').innerHTML = title;
      document.getElementById('bboxContents').innerHTML = contents;

      bbox.style.left = "-5000px";
      bbox.style.display = "";

      var width = parseInt($('bbox').getStyle('width'));
      var height = parseInt($('bbox').getStyle('height'));

      // set minimum width
      if(boxWidth != null && boxWidth != undefined)
      {
            width = boxWidth;
            bbox.style.width = boxWidth + "px";
            document.getElementById('bboxTable').style.width = boxWidth + "px";
      }

      else if(width < bboxMinWidth)
      {
            width = bboxMinWidth;
            bbox.style.width = bboxMinWidth + "px";
            document.getElementById('bboxTable').style.width = bboxMinWidth + "px";
      }

      var y = parseInt(getOffset("y"));

      setViewportSize();
      var top = parseInt((viewportheight / 2) - (height / 2));
      var left = parseInt((viewportwidth / 2) - (width / 2));

	  if(top < 0)
      	top = 0;
      	
      bbox.style.top = (top + y) + "px";
      bbox.style.left = left + "px"; 
      
      
      
      new Draggable('bbox', 
      {
      	scroll:window,
      	handle: 'bbox_header',
      	revert: false,
      	starteffect: null,
      	endeffect: null
      	
      });
      
      contents.evalScripts();
}

var onPopupCloseHandler = null;
function hideBBoxClose()
{
	if(onPopupCloseHandler)
	{
		onPopupCloseHandler();
	}
	
	hideBBox();
}

function hideBBox()
{
	  onPopupCloseHandler = null;
      
	  document.getElementById('bbox').style.display = "none";
      document.getElementById('fadeBg').style.display = "none";
      document.getElementById('bboxTitle').innerHTML = "";
      document.getElementById('bboxContents').innerHTML = "";
      ieHideSelect(false); 
}

function centerBBox()
{
	  var bbox = document.getElementById('bbox');
      var width = parseInt($('bbox').getStyle('width'));
      var height = parseInt($('bbox').getStyle('height'));
      var y = parseInt(getOffset("y"));

      setViewportSize();
      var top = parseInt((viewportheight / 2) - (height / 2));
      var left = parseInt((viewportwidth / 2) - (width / 2));

	  if(top < 0)
      	top = 0;
      	
      bbox.style.top = (top + y) + "px";
      bbox.style.left = left + "px"; 
}

function onWindowResize()
{
	var elem = document.getElementById("fadeBg");
	if(!elem || elem.style.display == "none")
		return;
	showBackgroundFade();
	centerBBox();
}

function showBackgroundFade()
{
	var height = document.documentElement.scrollHeight + 'px';
	var width = document.documentElement.scrollWidth + 'px';
	$('fadeBg').setStyle({opacity: 0.6, 'width': width, 'height': height});
	$('fadeBg').show();
}

var viewportwidth;
var viewportheight;
function setViewportSize()
{
      if (typeof window.innerWidth != 'undefined')
      {
            // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
            viewportwidth = window.innerWidth;
            viewportheight = window.innerHeight;
      }
      else if (typeof document.documentElement != 'undefined' &&
                   typeof document.documentElement.clientWidth != 'undefined' &&
                   document.documentElement.clientWidth != 0)
      {
            // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
            viewportwidth = document.documentElement.clientWidth;
            viewportheight = document.documentElement.clientHeight;
      }
      else
      {
      // older versions of IE
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
            viewportheight = document.getElementsByTagName('body')[0].clientHeight;
      }
}

function info_popup(url)
{
	var popw = (screen.width - 600) / 2; 
	var poph = (screen.height - 500) / 2; 
	var popft = 'width=640,height=480,top='+poph+',left='+popw+',scrollbars=yes,menubar=no,resizable=no';
	var name=window.open(url, "pop",popft);
	name.focus();
}

function credit_card_popup(url)
{
	var popw = (screen.width - 560) / 2; 
	var poph = (screen.height - 300) / 2; 
	var popft = 'width=400,height=250,top='+poph+',left='+popw+',scrollbars=yes,menubar=no,resizable=no';
	var name=window.open(url, "pop",popft);
	name.focus();
}

function updateKitPrice()
{
	var index = 0;
	var totalPrice = 0;
	var elem = document.getElementById('selectionItemKey_' + index);
	while(elem)
	{
		var configLineKey = elem.value;
		var configLineSelectKey = document.getElementById('configSelectKey' + configLineKey).value;
		totalPrice += kitToPrice[configLineKey][configLineSelectKey];
		elem = document.getElementById('selectionItemKey_' + (++index));
	}
	
	document.getElementById('kitTotalPrice').innerHTML = 'Price&nbsp;$' + totalPrice.toFixed(2);
}

function populateFundCity()
{
	var stateKey = document.getElementById("fundraiserState").value;
	
	new Ajax.Updater('', '/fundraiserPopulateCity',
	{
		parameters:
		{
			'stateKey':stateKey
		},
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			eval("var jsonResult = " + html);
				
			// remove the options already in the city select box
			var citySelect = document.getElementById("fundraiserCity");
			for(var count = citySelect.options.length - 1; count >= 0; count--)
		    {
		        citySelect.options[count] = null;
		    }

			// add the cities to the city select box with keys as postal keys and values as the city name
			var cities = jsonResult.cities;
			var postalKeys = jsonResult.postalKeys;
				
			var defaultOption = new Option("Select","0");
			citySelect.options[0] = defaultOption;

			for(var i=0; i<cities.length; i++)
			{
				// create the option in the city options
				var newOption = new Option(cities[i],postalKeys[i]);
				citySelect.options[i+1] = newOption;
			}
				
			// select the default city which is the first one in the list
			citySelect.selectedIndex = 0;
			
			// reset list of schools
			// remove the options already in the city select box
			var schoolSelect = document.getElementById("fundraiserSchool");
			for(var count = schoolSelect.options.length - 1; count >= 0; count--)
		    {
		        schoolSelect.options[count] = null;
		    }

			var defaultSchoolOption = new Option("Select","0");
			schoolSelect.options[0] = defaultSchoolOption;
			
			var acctField = document.getElementById("fundraiserAcctNumber");
			acctField.value = '';
		}
	});
}

function populateFundSchool()
{
	var stateKey = document.getElementById("fundraiserState").value;
	var postalKey = document.getElementById("fundraiserCity").value;
	
	new Ajax.Updater('', '/fundraiserPopulateSchool',
	{
		parameters:
		{
			'stateKey':stateKey,
			'postalKey':postalKey
		},
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			eval("var jsonResult = " + html);
				
			// remove the options already in the school select box
			var schoolSelect = document.getElementById("fundraiserSchool");
			for(var count = schoolSelect.options.length - 1; count >= 0; count--)
		    {
		        schoolSelect.options[count] = null;
		    }
			    
			// add the cities to the city select box with keys as postal keys and values as the city name
			var schools = jsonResult.schools;
			var accountKeys = jsonResult.accountKeys;
				
			var defaultOption = new Option("Select","0");
			schoolSelect.options[0] = defaultOption;

			for(var i=0; i<schools.length; i++)
			{
				// create the option in the city options
				var newOption = new Option(schools[i],accountKeys[i]);
				schoolSelect.options[i+1] = newOption;
			}
				
			// select the default city which is the first one in the list
			schoolSelect.selectedIndex = 0;

			var acctField = document.getElementById("fundraiserAcctNumber");
			acctField.value = '';
		}
	});
}

function populateFundAcctNum()
{
	var acctKey = document.getElementById("fundraiserSchool").value;
	var acctField = document.getElementById("fundraiserAcctNumber");

	if (acctKey == '0')
	{
		acctKey = '';
	}
	
	acctField.value = acctKey;
}

// The scripts below handle international shipping.
// When the country changes, the address form changes
function onCountryChange(addressDivName,
						 countryFieldName, 
                         oldCountryKeyFieldName,
                         firstNameFieldName,
                         lastNameFieldName,
                         companyFieldName,
                         street1FieldName,
                         street2FieldName,
                         cityFieldName,
                         postalFieldName,
                         stateFieldName,
                         emailFieldName,
                         checkboxFieldName)
{

	var countryKey = document.getElementById(countryFieldName).value;
	var oldCountryKeyField = document.getElementById(oldCountryKeyFieldName);
	var oldCountryKey = parseInt(oldCountryKeyField.value);

	if(oldCountryKey == countryKey)
	{
		return;
	}
	
	if(oldCountryKey <= 3 && countryKey <= 3)
	{
		setAddressLabels(countryKey, postalFieldName, stateFieldName);
	}
	else if(oldCountryKey > 3 && countryKey <= 3)
	{
		swapAddressForms(addressDivName, 
		                 firstNameFieldName,
                         lastNameFieldName,
                         companyFieldName,
                         street1FieldName,
                         street2FieldName,
                         emailFieldName,
                         countryFieldName,
                         checkboxFieldName);
                         
		setAddressLabels(countryKey, postalFieldName, stateFieldName);
	}
	else if(oldCountryKey <= 3 && countryKey > 3)
	{
		swapAddressForms(addressDivName, 
		                 firstNameFieldName,
                         lastNameFieldName,
                         companyFieldName,
                         street1FieldName,
                         street2FieldName,
                         emailFieldName,
                         countryFieldName,
                         checkboxFieldName);
	}
	
	// update the old value with the current value to be used next time the country is changed
	oldCountryKeyField.value = countryKey;
}

function displayPvaPackInfo(itemKey)
{
	new Ajax.Updater('', '/pvaProductInfo', 
	{
		parameters: 
		{ 
			'itemKey': itemKey
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') >= 0)
	   		{
	   			showBBoxText("Personal Vitamin Assessment", html, 300);
	   		}
	   		else
	   		{
	   			showBBoxText("Personal Vitamin Assessment", html, 400);
	   		}
		}
	});
}

//**************************************************
//*************** END PCS SCRIPT *******************
//**************************************************

Event.observe(window, 'resize', onWindowResize);

