// 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 syncAddressForms()
{
	var isSame = document.getElementById('shippingSameAsBilling').checked;

	if(isSame)
	{
		onCountryChange('shippingAddressDiv', 'shippingCountryKey', 'oldShippingCountryKey', 'shippingFirstName', 'shippingLastName', 'shippingCompany', 'shippingStreet1', 'shippingStreet2','shippingCity','shippingZip','shippingState','shippingEmail','');
	}
}

function setAddressLabels(countryKey, postalFieldName, stateFieldName)
{
	// changing within USA, Canada, and Mexico, we only have to change the labels
	switch(parseInt(countryKey))
	{
	case 1:
	  document.getElementById(postalFieldName + "Label").innerHTML = "<span class='error'>* </span>Zip:";
	  document.getElementById(stateFieldName + "Label").innerHTML = "<span class='error'>* </span>State:";
	  break;    
	case 2:
	  document.getElementById(postalFieldName + "Label").innerHTML = "<span class='error'>* </span>Postal Code:";
	  document.getElementById(stateFieldName + "Label").innerHTML = "<span class='error'>* </span>Province\\Territory:";
	  break;
	case 3:
	  document.getElementById(postalFieldName + "Label").innerHTML = "<span class='error'>* </span>Postal Code:";
	  document.getElementById(stateFieldName + "Label").innerHTML = "<span class='error'>* </span>Province:";
	  break;
	}
}

function swapAddressForms(addressDivName, 
		                  firstNameFieldName,
                          lastNameFieldName,
                          companyFieldName,
                          street1FieldName,
                          street2FieldName,
                          emailFieldName,
                          countryFieldName,
                          checkboxFieldName)
{
	setTextField(firstNameFieldName, "h_" + firstNameFieldName);
	setTextField(lastNameFieldName, "h_" + lastNameFieldName);
	setTextField(companyFieldName, "h_" + companyFieldName);
	setTextField(street1FieldName, "h_" + street1FieldName);
	setTextField(street2FieldName, "h_" + street2FieldName);
	setTextField(emailFieldName, "h_" + emailFieldName);
	setSelect(countryFieldName, "h_" + countryFieldName);
	setCheckbox(checkboxFieldName, "h_" + checkboxFieldName);
	
	var addressHtmlElem = document.getElementById(addressDivName);
	var hiddenAddressHtmlElem = document.getElementById("h_" + addressDivName);
		
	var addressHtml = addressHtmlElem.innerHTML;
	var hiddenAddressHtml = hiddenAddressHtmlElem.innerHTML;
	
	addressHtml = addressHtml.replace(/id=/g, "id=h_");
	addressHtml = addressHtml.replace(/id=h_\"/g, "id=\"h_");
	addressHtml = addressHtml.replace(/name=/g, "name=h_");
	addressHtml = addressHtml.replace(/name=h_\"/g, "name=\"h_");
	hiddenAddressHtml = hiddenAddressHtml.replace(/id=\"h_/g, "id=\"");
	hiddenAddressHtml = hiddenAddressHtml.replace(/id=h_/g, "id=");
	hiddenAddressHtml = hiddenAddressHtml.replace(/name=\"h_/g, "name=\"");
	hiddenAddressHtml = hiddenAddressHtml.replace(/name=h_/g, "name=");
	
	addressHtmlElem.innerHTML = hiddenAddressHtml;
	hiddenAddressHtmlElem.innerHTML = addressHtml;
}

function setTextField(src, dest)
{
	var srcElem = document.getElementById(src);
	var destElem = document.getElementById(dest);
	
	if(!srcElem || !destElem)
	{
		return;
	}
	
	destElem.value = srcElem.value;
}

function setCheckbox(src, dest)
{
	var srcElem = document.getElementById(src);
	var destElem = document.getElementById(dest);
	
	if(!srcElem || !destElem)
	{
		return;
	}
	
	destElem.checked = srcElem.checked;
}

function setSelect(src, dest)
{
	var srcElem = document.getElementById(src);
	var destElem = document.getElementById(dest);
	
	if(!srcElem || !destElem)
	{
		return;
	}
	
	destElem.selectedIndex = srcElem.selectedIndex;
}

function toggleShippingFormFields(elem)
{
	if(elem.checked)
	{
		// change the shipping form to local or foreign address forms based on the updated country key
		document.getElementById('shippingCountryKey').value = document.getElementById('billingCountryKey').value;
		document.getElementById('h_shippingCountryKey').value = document.getElementById('billingCountryKey').value;
		syncAddressForms();
	
		setTextField('billingFirstName', 'shippingFirstName');
		setTextField('h_billingFirstName', 'h_shippingFirstName');
		setTextField('billingLastName', 'shippingLastName');
		setTextField('h_billingLastName', 'h_shippingLastName');
		setTextField('billingEmail', 'shippingEmail');
		setTextField('h_billingEmail', 'h_shippingEmail');
		setTextField('billingStreet1', 'shippingStreet1');
		setTextField('h_billingStreet1', 'h_shippingStreet1');
		setTextField('billingStreet2', 'shippingStreet2');
		setTextField('h_billingStreet2', 'h_shippingStreet2');
		setTextField('billingState', 'shippingState');
		setTextField('h_billingState', 'h_shippingState');
		setTextField('billingZip', 'shippingZip');
		setTextField('h_billingZip', 'h_shippingZip');
		setTextField('billingZipOld', 'shippingZipOld');
		setTextField('h_billingZipOld', 'h_shippingZipOld');
		
		var countryKey = document.getElementById('shippingCountryKey').value;
		var isLocal = true;
		var localPrefix = "";
		var foreignPrefix = "h_";
		if(countryKey > 3)
		{
			isLocal = false;
			localPrefix = "h_";
			foreignPrefix = "";
		}
		
		setTextField(foreignPrefix + 'billingPhone', foreignPrefix + 'shippingPhone');
		setTextField(localPrefix + 'billingPhoneAreaCode', localPrefix + 'shippingPhoneAreaCode');
		setTextField(localPrefix + 'billingPhone3', localPrefix + 'shippingPhone3');
		setTextField(localPrefix + 'billingPhone4', localPrefix + 'shippingPhone4');
		setTextField(localPrefix + 'billingPhoneExt', localPrefix + 'shippingPhoneExt');	
		setTextField(foreignPrefix + 'billingCity', foreignPrefix + 'shippingCity');
		
		// we need to remove all shipping options and copy over the billing options
		var billingCities = document.getElementById(localPrefix + 'billingCity');
		var shippingCities = document.getElementById(localPrefix + 'shippingCity');
		
		// empty the shipping fields
		for(var count = shippingCities.options.length - 1; count >= 0; count--)
	    {
	        shippingCities.options[count] = null;
	    }
		
		// add the cities to the city select box with keys as postal keys and values as the city name
		for(var i=0; i<billingCities.options.length; i++)
		{
			// create the option in the city options
			var newOption = new Option(billingCities.options[i].text, billingCities.options[i].value);
			shippingCities.options[i] = newOption;
		}
		
		shippingCities.selectedIndex = billingCities.selectedIndex;
					
		document.getElementById('shippingFirstName').disabled = true;
		document.getElementById('shippingLastName').disabled = true;
		document.getElementById('shippingEmail').disabled = true;
		document.getElementById('shippingStreet1').disabled = true;
		document.getElementById('shippingStreet2').disabled = true;
		document.getElementById('shippingCountryKey').disabled = true;
		document.getElementById('shippingZip').disabled = true;
		document.getElementById('shippingCity').disabled = true;
		document.getElementById('shippingState').disabled = true;
		document.getElementById('h_shippingFirstName').disabled = true;
		document.getElementById('h_shippingLastName').disabled = true;
		document.getElementById('h_shippingEmail').disabled = true;
		document.getElementById('h_shippingStreet1').disabled = true;
		document.getElementById('h_shippingStreet2').disabled = true;
		document.getElementById('h_shippingCountryKey').disabled = true;
		document.getElementById('h_shippingZip').disabled = true;
		document.getElementById('h_shippingCity').disabled = true;
		document.getElementById('h_shippingState').disabled = true;
		document.getElementById(foreignPrefix + 'shippingPhone').disabled = true;
		document.getElementById(localPrefix + 'shippingPhoneAreaCode').disabled = true;
		document.getElementById(localPrefix + 'shippingPhone3').disabled = true;
		document.getElementById(localPrefix + 'shippingPhone4').disabled = true;
		document.getElementById(localPrefix + 'shippingPhoneExt').disabled = true;
		
		if(document.getElementById(localPrefix + 'savedAddress'))
		{
			document.getElementById(localPrefix + 'savedAddress').selectedIndex = 0;
			document.getElementById(foreignPrefix + 'savedAddress').selectedIndex = 0;
			document.getElementById(localPrefix + 'savedAddress').disabled = true;
			document.getElementById(foreignPrefix + 'savedAddress').disabled = true;
		}
	}
	else
	{
		// change the shipping form to local or foreign address forms based on the updated country key
		document.getElementById('shippingCountryKey').selectedIndex = 0;
		onCountryChange('shippingAddressDiv', 'shippingCountryKey', 'oldShippingCountryKey', 'shippingFirstName', 'shippingLastName', 'shippingCompany', 'shippingStreet1', 'shippingStreet2','shippingCity','shippingZip','shippingState','shippingEmail','');
		
		document.getElementById('shippingFirstName').value = "";
		document.getElementById('shippingLastName').value = "";
		document.getElementById('shippingEmail').value = "";
		document.getElementById('shippingStreet1').value = "";
		document.getElementById('shippingStreet2').value = "";
		document.getElementById('shippingState').value = "";
		document.getElementById('shippingZip').value = "";
		document.getElementById('h_shippingFirstName').value = "";
		document.getElementById('h_shippingLastName').value = "";
		document.getElementById('h_shippingEmail').value = "";
		document.getElementById('h_shippingStreet1').value = "";
		document.getElementById('h_shippingStreet2').value = "";
		document.getElementById('h_shippingState').value = "";
		document.getElementById('h_shippingZip').value = "";
		
		var countryKey = document.getElementById('shippingCountryKey').value;
		var isLocal = true;
		var localPrefix = "";
		var foreignPrefix = "h_";
		if(countryKey > 3)
		{
			isLocal = false;
			localPrefix = "h_";
			foreignPrefix = "";
		}
		
		document.getElementById(foreignPrefix + 'shippingPhone').value = "";
		document.getElementById(localPrefix + 'shippingPhoneAreaCode').value = "";
		document.getElementById(localPrefix + 'shippingPhone3').value = "";
		document.getElementById(localPrefix + 'shippingPhone4').value = "";
		document.getElementById(localPrefix + 'shippingPhoneExt').value = "";
		document.getElementById(foreignPrefix + 'shippingCity').value = "";
		document.getElementById(localPrefix + 'shippingZipOld').value = "";
		
		if(document.getElementById('savedAddress'))
		{
			document.getElementById('savedAddress').selectedIndex = 0;
			document.getElementById('savedAddress').disabled = false;
			document.getElementById('h_savedAddress').selectedIndex = 0;
			document.getElementById('h_savedAddress').disabled = false;
		}
		
		document.getElementById('shippingFirstName').disabled = false;
		document.getElementById('shippingLastName').disabled = false;
		document.getElementById('shippingEmail').disabled = false;
		document.getElementById('shippingStreet1').disabled = false;
		document.getElementById('shippingStreet2').disabled = false;
		document.getElementById('shippingCountryKey').disabled = false;
		document.getElementById('shippingZip').disabled = false;
		document.getElementById('shippingCity').disabled = false;
		document.getElementById('shippingState').disabled = false;
		document.getElementById('h_shippingFirstName').disabled = false;
		document.getElementById('h_shippingLastName').disabled = false;
		document.getElementById('h_shippingEmail').disabled = false;
		document.getElementById('h_shippingStreet1').disabled = false;
		document.getElementById('h_shippingStreet2').disabled = false;
		document.getElementById('h_shippingCountryKey').disabled = false;
		document.getElementById('h_shippingZip').disabled = false;
		document.getElementById('h_shippingCity').disabled = false;
		document.getElementById('h_shippingState').disabled = false;
		document.getElementById(foreignPrefix + 'shippingPhone').disabled = false;
		document.getElementById(localPrefix + 'shippingPhoneAreaCode').disabled = false;
		document.getElementById(localPrefix + 'shippingPhone3').disabled = false;
		document.getElementById(localPrefix + 'shippingPhone4').disabled = false;
		document.getElementById(localPrefix + 'shippingPhoneExt').disabled = false;
		
		var shippingCities = document.getElementById(localPrefix + 'shippingCity');
		
		// empty the shipping fields
		for(var count = shippingCities.options.length - 1; count >= 0; count--)
	    {
	        shippingCities.options[count] = null;
	    }
	}
}

function checkMultiShipSelects()
{
	var elems = document.getElementsByName("multiShipIds");
	for(var i=0; i<elems.length; i++)
	{
		if(elems[i].checked)
		{
			// at least one was selected
			return true;
		}
	}
	
	// nothing was selected so display a message
	showBBoxStatic('Multiple Shipping','multiShipWarning',300);
	return false;
}

function updateShippingPrices()
{
	document.getElementById("loadingShippingPricesImage").style.display = "";
	
	new Ajax.Updater('', '/getShippingPrices', 
	{
		onSuccess: function(transport)
		{
			var jsonStr = transport.responseText;
			if(jsonStr.indexOf('pcs-error-messages') >= 0)
			{
				// there was an error getting the shipping prices 
				document.getElementById("loadingShippingPricesImage").style.display = "none";
				return;
			}
			else
			{
				processShippingPrices(jsonStr);
			}
			
		}
	});
}

function processShippingPrices(jsonStr)
{
	eval("var jsonResult = " + jsonStr);
					
	for(var i=0; i<jsonResult.shippingPrices.length; i++)
	{
		var shippingPrice = jsonResult.shippingPrices[i];
		var carrierKey = shippingPrice.carrierKey;
		var serviceKey = shippingPrice.serviceKey;
		var price = shippingPrice.price;
		
		var priceStr = "";
		if(price != "-1")
			priceStr = "(" + price + ")";
		
		var priceId = carrierKey + "_" + serviceKey + "_price";
		var priceElem = document.getElementById(priceId);
		if(priceElem)
		{
			priceElem.innerHTML = priceStr;
		}
	}
	
	document.getElementById("loadingShippingPricesImage").style.display = "none";
}

function removeCheckoutItem(checkoutItemId, checkoutLineId)
{
	var showMultiShipping = false;
	if(document.getElementById('checkoutShippingId'))
	{
		showMultiShipping = true;
	}

	new Ajax.Updater('', '/checkoutRemoveItem', 
	{
		parameters: 
		{ 
			'checkoutItemId': checkoutItemId,
			'checkoutLineId': checkoutLineId,
			'showMultiShipping': showMultiShipping
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	   			
	   			document.getElementById('checkoutCartId').innerHTML = jsonResult.cart;
	   			document.getElementById('checkoutPricesId').innerHTML = jsonResult.prices;
	   			
	   			var payPalWarningElem = document.getElementById('checkoutPaypalWarning');
	   			var payPalMethodElem = document.getElementById('checkoutPaypalMethod');
	   			if(payPalWarningElem && payPalMethodElem && !jsonResult.hasReorders && !jsonResult.isMultiShipping)
	   			{
	   				payPalMethodElem.style.display = "";
	   				payPalWarningElem.style.display = "none";
	   			}
	   				   			
	   			if(document.getElementById('checkoutShippingId'))
				{
					updateShippingPrices();
				}
	   		}
		}
	});
}

function submitMultiShip()
{
	if(checkMultiShipSelects())
	{
		return copyPaymentShippingFields();
	}
	
	return false;
}

function copyPaymentShippingFields()
{
	copyField("creditCardName", "ccNameCopy");
	copyField("creditCardType", "ccTypeCopy");
	copyField("creditCardNumber", "ccNumberCopy");
	copyField("creditCardExpMonth", "ccExpMonthCopy");
	copyField("creditCardExpYear", "ccExpYearCopy");
	copyField("creditCardSecurityId", "ccSecCodeCopy");
	
	copyRadioField("shippingMethod", "shippingMethodCopy");
	copyRadioField("paymentType", "paymentTypeCopy");

	return true;
}

function copyRadioField(srcName, destId)
{
	var srcElems = document.getElementsByName(srcName);
	if(!srcElems)
		return;
		
	var destElem = document.getElementById(destId);
	if(!destElem)
		return;
	
	for(var i=0; i<srcElems.length; i++)
	{
		if(srcElems[i].checked)
		{
			destElem.value = srcElems[i].value;
			return;
		}
	}
}

function copyField(src, dest)
{
	var srcElem = document.getElementById(src);
	if(!srcElem)
		return;
	
	var destElem = document.getElementById(dest);
	if(!destElem)
		return;
		
	destElem.value = srcElem.value;
}

function updateShippingMethod(carrierServiceId)
{
	new Ajax.Updater('', '/updateShippingMethod', 
	{
		parameters: 
		{ 
			'carrierServiceId': carrierServiceId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			document.getElementById('checkoutPricesId').innerHTML = html;
	   			document.getElementById('oldCarrierServiceId').value = carrierServiceId;
	   		}
	   		else
	   		{
	   			showBBoxText("Error",html,300);
	   			var oldCarrierServiceId = document.getElementById('oldCarrierServiceId').value;
	   			document.getElementById(oldCarrierServiceId).checked = true;
	   		}
		}
	});
}