// JavaScript Document

var calculateTotal = function(isNew)
{
	// set variables
	var previousPackage_PriceField		=	document.getElementById('txtPreviousPackage_Price');
	if(previousPackage_PriceField)
	{
		previousPackage_Price	=	previousPackage_PriceField.value;
		previousPackage_Price	=	parseFloat(previousPackage_Price.replace("$",""));
	}
	else
	{
		previousPackage_Price	=	0;
	}
	
	var previousStorageIncPriceField	=	document.getElementById('txtPreviousStorageIncPrice');
	if(previousStorageIncPriceField)
	{
		previousStorageIncPrice	=	previousStorageIncPriceField.value;
		previousStorageIncPrice	=	parseFloat(previousStorageIncPrice.replace("$",""));
	}
	else
	{
		previousStorageIncPrice	=	0;
	}

	var new_Package_StorageField	=	document.getElementById('txtNew_Package_Storage');
	if(new_Package_StorageField)
	{
		new_Package_Storage			=	parseInt(new_Package_StorageField.value);
	}
	else
	{
		new_Package_Storage			=	0;
	}
	
	var order_Storage_IncrementField	=	document.getElementById('txtOrder_Storage_Increment');
	if(order_Storage_IncrementField)
	{
		order_Storage_Increment	=	parseInt(order_Storage_IncrementField.value);
	}
	else
	{
		order_Storage_Increment	=	0;
	}

	var order_Price_IncrementField		=	document.getElementById('txtOrder_Price_Increment');
	if(order_Price_IncrementField)
	{
		order_Price_Increment	=	order_Price_IncrementField.value;
		order_Price_Increment	=	parseFloat(order_Price_Increment.replace("$",""));
	}
	else
	{
		order_Price_Increment	=	0;
	}
	
	var discountCodeField				=	document.getElementById('txtDiscountCode');
	if(discountCodeField)
	{
		discountCode			=	discountCodeField.value;
	}
	else
	{
		discountCode			=	"";
	}
	
	var newPackage_PriceField				=	document.getElementById('txtNewPackage_Price');
	if(newPackage_PriceField)
	{
		newPackage_Price		=	newPackage_PriceField.value;
		newPackage_Price		=	parseFloat(newPackage_Price.replace("$",""));
	}
	else
	{
		newPackage_Price		=	0;
	}

	var previous_Price_IncrementField	=	document.getElementById('txtPrevious_Price_Increment');
	if(previous_Price_IncrementField)
	{
		previous_Price_Increment	=	previous_Price_IncrementField.value;
		previous_Price_Increment	=	parseFloat(previous_Price_Increment.replace("$",""));
	}
	else
	{
		previous_Price_Increment	=	0;
	}

	var current_Storage_IncrementField	=	document.getElementById('txtCurrent_Storage_Increment');
	if(current_Storage_IncrementField)
	{
		current_Storage_Increment	=	parseInt(current_Storage_IncrementField.value);
	}
	else
	{
		current_Storage_Increment	=	0;
	}

	var dateTimeField	=	document.getElementById('txtDateTime');
	if(dateTimeField)
	{
		if(dateTimeField.value > "")
		{
			order_Date				=	dateTimeField.value;
		}
		else
		{
			order_Date				=	getLocalDateTime();
		}
	}
	else
	{
		order_Date					=	getLocalDateTime();
	}
	
	var previousExpirationField		=	document.getElementById('txtExpiration_Date');
	if(previousExpirationField)
	{
		previousExpiration			=	previousExpirationField.value;
		var currentDate				=	getCurrentDateTime();
		if(previousExpiration < currentDate)
		{
			previousExpiration			=	currentDate;
		}
	}
	else
	{
		previousExpiration			=	"";
	}

	var order_Storage_Price		=	0;
	var prorate					=	0;
	var diskCost				=	0;
	var order_Price_Total		=	0;
	var order_Subtotal			=	0;
	var order_Storage_Total		=	0;
	
	// set up proxy call
	var subscribeFunctions = new subscribeFunctionsProxy();
	
	// calculate prorate
	if(isNew == 0)  // renew subscription
	{
		order_Storage_Price		=	previous_Price_Increment + order_Price_Increment;
		prorate					=	subscribeFunctions.calculateProrate(previousExpiration,order_Date,previousPackage_Price,previousStorageIncPrice);
	}
	else if(isNew == 2)	// upgrade disk space
	{
		diskCost				=	subscribeFunctions.calculateProrateDisk(previousExpiration,order_Date,order_Price_Increment);
		prorate					=	order_Price_Increment - diskCost;
	}

	order_Storage_Price			=	previous_Price_Increment + order_Price_Increment;
	order_Price_Total			=	newPackage_Price + order_Storage_Price;
	order_Storage_Total			=	new_Package_Storage + current_Storage_Increment + order_Storage_Increment;
	
	// set variables
	var jsDiscountCodes		=	[];
	var city_TaxRate		=	0;
	var county_TaxRate		=	0;
	var state_TaxRate		=	0;
	var dollarAmt			=	0;
	var pctAmt				=	0;
	var order_Total			=	0;
	var order_Subtotal		=	0;
	var order_DiscountAmt	=	0;
	var order_TaxAmt		=	0;
	var foundDiscountCode	=	false;
	
	// get discount code info
	jsDiscountCodes	=	subscribeFunctions.setDiscountCodes();
	
	// determine discount amount
	if((discountCode) && (discountCode > ""))
	{
		for(i=0;i<jsDiscountCodes.length;i++)
		{
			if(jsDiscountCodes[i][1].toUpperCase() == discountCode.toUpperCase())
			{
				dollarAmt			=	jsDiscountCodes[i][2];
				pctAmt				=	jsDiscountCodes[i][3];
				foundDiscountCode	=	true;
				break;
			}
		}
	}
	
	// if invalid discount code, call popup error msg and return
	if((discountCode) && (discountCode > "") && (foundDiscountCode == false))
	{
		errDiscountCode(109);
		return false;
	}
	
	// apply prorate
	order_Subtotal = order_Price_Total - parseFloat(prorate).toFixed(2);
	
	// determine discount amount
	if((dollarAmt) && (dollarAmt > 0))
	{
		order_DiscountAmt	=	dollarAmt;
		
		var dollarAmtField	=	document.getElementById('txtDiscountDollar');
		if(dollarAmtField)
		{
			dollarAmtField.value	=	order_DiscountAmt;
		}
	
		var pctAmtField	=	document.getElementById('txtDiscountPctDollar');
		if(pctAmtField)
		{
			pctAmtField.value	=	0;
		}
	
		var discountPercentField = document.getElementById('txtDiscountPercent');
		if(discountPercentField)
		{
			discountPercentField.value	=	0;
		}
	}
	else if((pctAmt) && (pctAmt > 0))
	{
		order_DiscountAmt	=	(order_Subtotal * pctAmt);
		
		var pctAmtField	=	document.getElementById('txtDiscountPctDollar');
		if(pctAmtField)
		{
			pctAmtField.value	=	order_DiscountAmt;
		}
	
		var discountPercentField = document.getElementById('txtDiscountPercent');
		if(discountPercentField)
		{
			discountPercentField.value	=	pctAmt;
		}
		
		var dollarAmtField	=	document.getElementById('txtDiscountDollar');
		if(dollarAmtField)
		{
			dollarAmtField.value	=	0;
		}
	}
	else
	{
		order_DiscountAmt	=	0;
	}
	
	// apply discount
	order_Subtotal = order_Subtotal - parseFloat(order_DiscountAmt).toFixed(2);
	if(order_Subtotal < 0)
	{
		order_Subtotal = 0;
	}
	
	// determine taxes
	
	// apply taxes
	
	// set final cost
	order_Total	=	order_Subtotal + order_TaxAmt;

	// populate display discount field
	var discountField = document.getElementById('txtDiscountAmount');
	if(discountField)
	{
		var formatDiscount		=	formatNumber(order_DiscountAmt,"dollar",0,1);
		discountField.innerHTML	=	formatDiscount;
	}
	
	// populate display prorate field
	var prorateField = document.getElementById('txtProrate');
	if(prorateField)
	{
		var formatProrate		=	formatNumber(prorate,"dollar",0,1);
		prorateField.innerHTML	=	formatProrate;
	}
	
	// populate hidden prorate field
	var discountProrateField = document.getElementById('txtDiscountProrate');
	if(discountProrateField)
	{
		discountProrateField.value	=	prorate;
	}

	// populate display total price
	var order_TotalField	=	document.getElementById('txtFinal_Price');
	if(order_TotalField)
	{
		var formatTotal			=	formatNumber(order_Total,"dollar",1,0);
		order_TotalField.value	=	formatTotal;
	}
	
	// populate hidden order subtotal price
	var order_SubtotalField	=	document.getElementById('txtOrder_SubTotal');
	if(order_SubtotalField)
	{
		order_SubtotalField.value	=	order_Subtotal;
	}
	
	// populate hidden order storage total space
	var order_Storage_TotalField	=	document.getElementById('txtOrder_Storage_Total');
	if(order_Storage_TotalField)
	{
		order_Storage_TotalField.value	=	order_Storage_Total;
	}
	
	// populate hidden order storage total price
	var order_Storage_PriceField	=	document.getElementById('txtOrder_Storage_Price');
	if(order_Storage_PriceField)
	{
		order_Storage_PriceField.value	=	order_Storage_Price;
	}
	
	// populate display city tax rate
	var city_TaxRateField	=	document.getElementById('txtCity_Taxrate');
	if(city_TaxRateField)
	{
		city_TaxRateField.value	=	city_TaxRate;
	}
	
	// populate display county tax rate
	var county_TaxRateField	=	document.getElementById('txtCounty_Taxrate');
	if(county_TaxRateField)
	{
		county_TaxRateField.value	=	county_TaxRate;
	}
	
	// populate display state tax rate
	var state_TaxRateField	=	document.getElementById('txtState_Taxrate');
	if(state_TaxRateField)
	{
		state_TaxRateField.value	=	state_TaxRate;
	}
	
	
	// show or hide fields
	if(parseFloat(prorate).toFixed(2) > 0.00)
	{
		$("#showProrate").show();
	}
	else
	{
		$("#showProrate").hide();
	}
	
	if(order_DiscountAmt > 0)
	{
		$("#showDiscountAmount").show();
	}
	else
	{
		$("#showDiscountAmount").hide();
	}
	
	if(order_TaxAmt > 0)
	{
		$("#showCityTax").show();
		$("#showCountyTax").show();
		$("#showStateTax").show();
		$("#showTaxes").hide();
	}
	else
	{
		$("#showCityTax").hide();
		$("#showCountyTax").hide();
		$("#showStateTax").hide();
		$("#showTaxes").show();
	}
	
	if(order_Total <= 0)
	{
		if(document.getElementById('paymentMethod'))
		{
			document.getElementById('paymentMethod').style.display = "none";
		}
	}
	else
	{
		if(document.getElementById('paymentMethod'))
		{
			document.getElementById('paymentMethod').style.display = "block";
		}
	}
	
	return true;
	
};

/* =========================================================================== */
/* =========================================================================== */
/* =========================================================================== */
/* =========================================================================== */
var updatePackagePrice = function(jsPackageDataArray,jsPackageType)
{
	var jsIndex	=	-1;

	// find index for the selected package type
	for(i=0;i<jsPackageDataArray.length;i++)
	{
		if(jsPackageDataArray[i][0] == jsPackageType)
		{
			jsIndex			=	i;
			break;
		}
	}

	if(jsIndex > -1)
	{
		var newPackage_Price	=	jsPackageDataArray[jsIndex][4];
		var incrementValue		=	0;

		// update order storage total hidden field
		var order_Storage_TotalField = document.getElementById('txtOrder_Storage_Total');
		if(order_Storage_TotalField)
		{
			order_Storage_TotalField.value = jsPackageDataArray[jsIndex][2];
		}

		// update package storage section for standard package data
		// this is for upgrade from economy to standard
		var kbStorage	=	jsPackageDataArray[jsIndex][2] / 1000;
		var num = new NumberFormat(kbStorage);
		num.setInputDecimal('.');
		num.setPlaces('0', false);
		num.setCurrency(false);
		num.setSeparators(true, ',', ',');
		var packageStorageSizeLabel	=	document.getElementById('packageStorageSizeLabel');
		if(packageStorageSizeLabel)
		{
			packageStorageSizeLabel.innerHTML	=	num.toFormatted() + ' KB';
		}

		var new_Package_StorageField				=	document.getElementById('txtNew_Package_Storage');
		if(new_Package_StorageField)
		{
			new_Package_StorageField.value 			= jsPackageDataArray[jsIndex][2];
		}

		// zero out current Increment when going from Standard to Economy package
		var currentIncrementField			=	document.getElementById('currentIncrement');
		var orderStorageIncrementField		=	document.getElementById('txtOrder_Storage_Increment');
		var orderPriceIncrementField		=	document.getElementById('txtOrder_Price_Increment');
		if(jsPackageDataArray[jsIndex][0] == "E")
		{
			if(currentIncrementField)
			{
				currentIncrementField.value			=	incrementValue;
			}
			if(orderStorageIncrementField)
			{
				orderStorageIncrementField.value	=	incrementValue;
			}
			if(orderPriceIncrementField)
			{
				orderPriceIncrementField.value		=	incrementValue;
			}
		}
		else
		{
			if(currentIncrementField)
			{
				incrementValue					=	currentIncrementField.value;
			}
		}

		// update package price and total fields
		var newPackage_PriceField				=	document.getElementById('txtNewPackage_Price');
		if(newPackage_PriceField)
		{
			newPackage_PriceField.value			=	newPackage_Price;
			calculateAdditionalStorage(jsPackageDataArray,incrementValue,jsIsNew);
		}
		
		// update package duration field
		var packageDurationDayField				=	document.getElementById('txtPackageDurationDay');
		if(packageDurationDayField)
		{
			packageDurationDayField.value		=	jsPackageDataArray[jsIndex][8];
		}

		// if moving to standard package, display storage information
		if(jsPackageDataArray[jsIndex][0] == "S")
		{
			// hide divider line after radio buttons
			$("#renewDivider").hide();

			// show storage information section
			$("#storageInformation").show();
		}
		else
		{
			// hide storage information section
			$("#storageInformation").hide();
			
			// show divider line after radio buttons
			$("#renewDivider").show();
		}
	}
};


/* =========================================================================== */
var trim = function(str)
{
	//check from the beginning of the string
	while (str.substring(0,1) == ' ')
	{
		str = str.substring(1,str.length);
	}

	//check from the end of the string
	while (str.substring(str.length-1,str.length) == ' ')
	{
		str = str.substring(0,str.length-1);
	}
	return str;
};


/* =========================================================================== */
var EmailValidation = function(str)
{
	//blah.blah@blahb.com
	var RegExpression = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(str.match(RegExpression)==null)
	{
		return false;
	}

	else
	{
		return true;
	}
};


/* =========================================================================== */
var checkform_click = function()
{
	if (findnocase('Firefox',cgi.HTTP_USER_AGENT))
	{
		fForm = document.fForm;
	}

	if (checkform())
	{
		fForm.submit();
	}
};


/* =========================================================================== */
var checkform = function()
{
	if (findnocase('Firefox',cgi.HTTP_USER_AGENT))
	{
		fForm = document.fForm;
	}

	var sError = '';
	
	// Identification
	if (trim(fForm.txtFirstname.value) == '')
	{
		sError = sError + 'Please enter your First Name\n'
	}

	if (trim(fForm.txtLastname.value) == '')
	{
		sError = sError + 'Please enter your Last Name\n'
	}
	
	// Phone
	if (trim(fForm.txtCust_Phone.value) == '')
	{
		sError = sError + 'Please enter your Phone\n'
	}
	
	// mail address
	if (trim(fForm.txtAddress1.value) == '')
	{
		sError = sError + 'Please enter your Mailing address\n'
	}
	
	if (trim(fForm.txtCity.value) == '')
	{
		sError = sError + 'Please enter your Mailing City\n'
	}
	
	if (trim(fForm.txtPostal_Code.value) == '')
	{
		sError = sError + 'Please enter your Mailing Postal Code\n'
	}
	
	if (fForm.txtState.options[fForm.txtState.selectedIndex].value == '')
	{
		sError = sError + 'Please choose your Mailing State\n'
	}
	
	if (fForm.txtCountry.options[fForm.txtCountry.selectedIndex].value == '')
	{
		sError = sError + 'Please choose your Mailing Country\n'
	}
	
	// e-mail address
	if (trim(fForm.txtEmail_Address.value) == '')
	{
		sError = sError + 'Please enter your Email\n'
	}
	else if (!EmailValidation(fForm.txtEmail_Address.value))
	{
		sError = sError + 'Please enter valid Email\n'
	}
	
	if (trim(fForm.txtEmail_Address.value) != trim(fForm.txtEmail_Address2.value))
	{
		sError = sError + 'Re-Enter Email should match Email\n'
	}

	// password
	if (trim(fForm.txtPassword.value) == '')
	{
		sError = sError + 'Please enter your Password\n'
	}

	if (trim(fForm.txtPassword.value) != trim(fForm.txtPassword_2.value))
	{
		sError = sError + 'Confirm Password should be the same as Password\n'
	}

	if (trim(fForm.txtPassword_Hint.value) == '')
	{
		sError = sError + 'Please enter your Password Hint\n'
	}

	if (trim(sError) != '')
	{
		alert(sError)
		return false;
	}

	return true;
};


/* =========================================================================== */
var loadPackageInfo = function(fileToLoad,divToLoad)
{
	$("#" + divToLoad).load(fileToLoad);
};


/* ============================================================================================*/
/*
This function gets the computer's local time.
*/
/* ============================================================================================*/

var getCurrentDateTime = function()
{
	// get local date and time
	var currentDateTime = new Date();
	
	// format date information
	var currentMonth = currentDateTime.getMonth() + 1;
	var currentDate = currentDateTime.getDate();
	var currentYear = currentDateTime.getFullYear();
	
	var formattedDate = currentYear + '/' + currentMonth + '/' + currentDate;
	
	// format time information
	var currentHour = currentDateTime.getHours();
	var currentMinute = currentDateTime.getMinutes();
	var currentSecond = currentDateTime.getSeconds();
	var currentMillisecond = currentDateTime.getMilliseconds();
	
	var formattedTime = currentHour + ':' + currentMinute + ':' + currentSecond + '.' + currentMillisecond;
	
	var dateTime = formattedDate + ' ' + formattedTime;
	return dateTime;

};


/* =========================================================================== */
/*
var CheckSameAddress = function()
{
	return true;
	<cfif findnocase('Firefox',cgi.HTTP_USER_AGENT)>
		fForm = document.fForm;
	</cfif>
	if(fForm.chkSameAddress.checked)
	{
		SameAddress();
	}
};
*/

/* =========================================================================== */
/*
var SameAddress = function()
{
	<cfif findnocase('Firefox',cgi.HTTP_USER_AGENT)>
		fForm = document.fForm;
	</cfif>
	if(fForm.chkSameAddress.checked)
	{
		fForm.txtBillAddress1.value = fForm.txtAddress1.value;
		fForm.txtBillAddress2.value = fForm.txtAddress2.value;
		fForm.txtBillCity.value = fForm.txtCity.value;
		fForm.txtBillPostal_Code.value = fForm.txtPostal_Code.value;

		fForm.txtBillState.selectedIndex = fForm.txtState.selectedIndex;
		fForm.txtBillCountry.selectedIndex = fForm.txtCountry.selectedIndex;
	}
};
*/
