// JavaScript Document

var measureFormFields = new Array("MeasurementA","MeasurementB","MeasurementC","MeasurementD","MeasurementE","MeasurementF","MeasurementG");
function CalculateIt(thisForm, mode, priceTextId)
{
	var selectedLight = skylights[thisForm.AddOn14.value];

	// Validate that all of the measurements are filled in
	var numRequiredFields = selectedLight.measCount;
	var isValid = validateFormFields(thisForm, numRequiredFields);
	if ( !isValid ) 
	{
		return isValid;
	}

	// Initialize calculation
	var price = 0.0;
	var PriceText = document.getElementById(priceTextId);
	PriceText.innerHTML = '';

	// Calculate the price and size	
	var size = selectedLight.calculateSize(thisForm);

	// Adjust price for size differences		
	if (size < 20)
	{
		price = size * 8.10;
	}
	else if ( size > 20.01 && size < 49.99 )
	{
		price = size * 6.10;
	}
	else if ( size > 50 && size < 199.99 )
	{
		price = size * 4.75;
	}
	else
	{
		price = size * 3.95;
	}

	// Adjust for skylight price factor
	price = price * selectedLight.factor;
	
	// Adjust for block amount
	if (thisForm.AddOn13.value == '90% Block') 
	{
		price = price * 1.10;
	}	

	if ((price > .01) & (size> 1))
	{
		//update div
		PriceText.innerHTML = Round(size, 2) + ' sq. ft. = $' + Round(price,2);

		if (mode=='1')
		{
			//all is well, submit it
			/* OLD CODE
			thisForm.AddOn1.value = 'Measurement A: ' + thisForm.MeasurementA.value;
			thisForm.AddOn2.value = 'Measurement B: ' + thisForm.MeasurementB.value;
			thisForm.AddOn3.value = 'Measurement C: ' + thisForm.MeasurementC.value;
			thisForm.AddOn7.value = 'Measurement D: ' + thisForm.MeasurementD.value;
			thisForm.AddOn8.value = 'Measurement E: ' + thisForm.MeasurementE.value;
			thisForm.AddOn9.value = 'Measurement F: ' + thisForm.MeasurementF.value;
			thisForm.AddOn10.value = 'Measurement G: ' + thisForm.MeasurementG.value;
			thisForm.Size.value = 'Sq. ft: ' + Round(size,2);
			thisForm.Price.value = price;
			thisForm.method = 'post'; 
			thisForm.action='http://www.coolcart.net/cart/coolcart.aspx/fisherselect';
			thisForm.submit();
			*/
			var submitForm = getNewSubmitForm();
			createNewFormElement(submitForm, "ID", "Custom Size HeatBlocker");
			createNewFormElement(submitForm, "Price", price);
			createNewFormElement(submitForm, "Size", 'Sq. ft: ' + Round(size,2));
			var count = 1;
			if ( thisForm.MeasurementA.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "A: " + thisForm.MeasurementA.value);
			}
			if ( thisForm.MeasurementB.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "B: " + thisForm.MeasurementB.value);
			}
			if ( thisForm.MeasurementC.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "C: " + thisForm.MeasurementC.value);
			}
			if ( thisForm.MeasurementD.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "D: " + thisForm.MeasurementD.value);
			}
			if ( thisForm.MeasurementE.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "E: " + thisForm.MeasurementE.value);
			}
			if ( thisForm.MeasurementF.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "F: " + thisForm.MeasurementF.value);
			}
			if ( thisForm.MeasurementG.value != '' ) {			
				createNewFormElement(submitForm, "AddOn" + count++, "G: " + thisForm.MeasurementG.value);
			}
			createNewFormElement(submitForm, "AddOn12", thisForm.AddOn12.value);
			createNewFormElement(submitForm, "AddOn13", thisForm.AddOn13.value);
			createNewFormElement(submitForm, "AddOn14", selectedLight.name);
						
			createNewFormElement(submitForm, "Qty", thisForm.Qty.value);
			submitForm.action= "http://www.coolcart.net/cart/coolcart.aspx/fisherselect";
			pageTracker._linkByPost(submitForm);
			submitForm.submit();
		}
	}
	else
	{
		alert('Invalid Measurement A and/or Measurement B. Please enter positive numeric values.');
	}
}
function validateFormFields(thisForm, numRequiredFields) 
{
	var isValid = true;
	var errorString = "";
	for ( var i = 0; i < numRequiredFields; i++ )
	{
		if ( thisForm[measureFormFields[i]].value == '' )
		{
			if ( !isValid )
			{
				errorString += ", ";
			}
			errorString += measureFormFields[i];
			isValid = false;
		}
	}
	if (!isValid)
	{
		alert('Please enter a positive numeric value for the fields: ' + errorString + '.');
	}
	return isValid;
}
function IsInteger(fld, e)
{
var key = '';
var i = 0;
var strCheck = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -`=~!@#$%^&*()_+[]\{}|;:<>?,/';
var whichCode = (window.Event) ? e.which : e.keyCode;
if ((whichCode == 13) | (whichCode == 34) | (whichCode == 39) | (whichCode == 92)) {
	return false;  // Enter
}
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) > -1) {
	return false;  // Not a valid key
}
for(i = 0; i < fld.value.length; i++) {
	if (strCheck.indexOf(fld.value.charAt(i))>=0) {
		return false;
	}
}
}

function clearValues(thisForm, priceTextId)
{
thisForm.Price.value = ''; 
thisForm.Size.value = '';
thisForm.Qty.value = '';
thisForm.AddOn1.value = '';
thisForm.AddOn2.value = '';
thisForm.AddOn3.value = '';
thisForm.AddOn4.value = '';
thisForm.AddOn5.value = '';
thisForm.AddOn6.value = '';
thisForm.AddOn7.value = '';
thisForm.MeasurementA.value = '';
thisForm.MeasurementB.value = '';
thisForm.MeasurementC.value = '';
thisForm.MeasurementD.value = '';
thisForm.MeasurementE.value = '';
thisForm.MeasurementF.value = '';
thisForm.MeasurementG.value = '';
document.getElementById(priceTextId).innerHTML = '';
}


function Round(original_number, decimals) {
var result1 = original_number * Math.pow(10, decimals)
var result2 = Math.round(result1)
var result3 = result2 / Math.pow(10, decimals)
return Pad(result3, decimals)
}

function Pad(rounded_value, decimal_places) {

// Convert the number to a string
var value_string = rounded_value.toString()

// Locate the decimal point
var decimal_location = value_string.indexOf(".")

// Is there a decimal point?
if (decimal_location == -1) {
	
	// If no, then all decimal places will be padded with 0s
	decimal_part_length = 0
	
	// If decimal_places is greater than zero, tack on a decimal point
	value_string += decimal_places > 0 ? "." : ""
}
else {

	// If yes, then only the extra decimal places will be padded with 0s
	decimal_part_length = value_string.length - decimal_location - 1
}

// Calculate the number of decimal places that need to be padded with 0s
var pad_total = decimal_places - decimal_part_length

if (pad_total > 0) {
	
	// Pad the string with 0s
	for (var counter = 1; counter <= pad_total; counter++) 
		value_string += "0"
	}

return value_string
}

//faq toggle
function toggle(obj) {
	var el = document.getElementById(obj);
	var ar = document.getElementById(obj+'ar');
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
		ar.innerHTML='<img src="images/arw_right.gif" style="width:5px;height:9px;" alt="" title="" />';
	}
	else {
		el.style.display = 'block';
		ar.innerHTML='<img src="images/arw_down.gif" style="width:9px;height:5px;" alt="" title="" />';
	}

}
var skylights;
var optionalMeasureFormFields = new Array('measD','measE','measF','measG');

function initSkylights()
{
	skylights = new Array();
	skylights['Square Dome'] = new Skylight('Square Dome', 3, 1, 'images/sketch260/square-dome-lg.jpg', defaultSize);
	skylights['Rectangular Dome'] = new Skylight('Rectangular Dome', 3, 1, 'images/sketch260/rectangular-dome-lg.jpg', defaultSize);
	skylights['Flat Glass'] = new Skylight('Flat Glass', 3, 1, 'images/sketch260/flat-glass-lg.jpg', defaultSize);
	skylights['Multiple Dome'] = new Skylight('Multiple Dome', 3, 1, 'images/sketch260/multiple-dome-lg.jpg', defaultSize);
	skylights['Cluster Dome'] = new Skylight('Cluster Dome', 3, 1, 'images/sketch260/cluster-dome-lg.jpg', defaultSize);
	skylights['Continuous Ridge'] = new Skylight('Continuous Ridge', 3, 1, 'images/sketch260/continuous-ridge-lg.jpg', defaultSize);
	skylights['Barrel Vault'] = new Skylight('Barrel Vault', 3, 1, 'images/sketch260/barrel-vault-round-lg.jpg', defaultSize);
	skylights['Pyramid'] = new Skylight('Pyramid', 3, 1.25, 'images/sketch260/pyramid-lg.jpg', pyramid);
	skylights['Barrel Vault Flat'] = new Skylight('Barrel Vault Flat', 4, 1.25, 'images/sketch260/barrel-vault-flat-lg.jpg', barrelFlat);
	skylights['Vaulted Trapezoid'] = new Skylight('Vaulted Trapezoid', 6, 1.5, 'images/sketch260/vaulted-trapezoid-lg.jpg', trapezoid);
	skylights['Round Dome'] = new Skylight('Round Dome', 3, 1.5, 'images/sketch260/round-dome-lg.jpg', spherical);

	// Set up the default/selected skylight
	var customSelect = document.getElementById('customTypeSelect');
	if ( customSelect )
	{
		customTypeChange(customSelect);
	}
}
function customTypeChange(thisObj)
{	
	var measImg = document.getElementById('MeasureExampleImage');
	if ( measImg && measImg != null )
	{
		// Initialize skylight definitions if they aren't already
		if ( !skylights )
		{
			initSkylights();
		}
		if ( thisObj == null || thisObj.value == null )
		{
			return;
		}
		var selectedLight = skylights[thisObj.value];
		
		if ( !selectedLight ) 
		{
			return;			
		}
		// Update the measurement image source
		measImg.src = selectedLight.measImg;
		// Hide all optional form fields
		var numFields = optionalMeasureFormFields.length;
		var i;
		for ( i = 0; i < numFields; i++ )
		{
			hideFormField(optionalMeasureFormFields[i]);
		}
		// Show necessary form fields -- offset by 3 since A, B, C are always shown	
		var additionalFieldsToShow = selectedLight.measCount;
		while ( additionalFieldsToShow > 3 ) 
		{
			showFormField(optionalMeasureFormFields[additionalFieldsToShow - 4]);
			additionalFieldsToShow = additionalFieldsToShow - 1;
		}
	}
}
function hideFormField(fieldId)
{
	var aField = document.getElementById(fieldId);
	if ( aField ) 
	{
		aField.className = "optionalMeasurementBlock";
	}
}

function showFormField(fieldId)
{
	var aField = document.getElementById(fieldId);
	if ( aField ) 
	{
		aField.className = "visibleMeasurementBlock ";
	}
}

function defaultSize(thisForm)
{
	var a = thisForm.MeasurementA.value;
	var b = thisForm.MeasurementB.value;

	//convert inches to feet
	a = a / 12;
	b = b / 12;

	// calculate sq ft
	var size = a * b;

	return size;
}
function pyramid(thisForm)
{
	var a = thisForm.MeasurementA.value;
	var b = thisForm.MeasurementB.value;

	//convert inches to feet
	a = a / 12;
	b = b / 12;

	// calculate sq ft
	var size = (a * b) * 2;

	return size;
}
function barrelFlat(thisForm)
{
	var a = thisForm.MeasurementA.value;
	var b = thisForm.MeasurementB.value;
	var c = thisForm.MeasurementC.value;

	//convert inches to feet
	a = a / 12;
	b = b / 12;
	c = c / 12;

	// calculate sq ft
	var size = (a * c) + (0.4 * (b * b));

	return size;
}
function trapezoid(thisForm)
{
	var a = thisForm.MeasurementA.value;
	var b = thisForm.MeasurementB.value;
	var c = thisForm.MeasurementC.value;
	var d = thisForm.MeasurementD.value;
	var e = thisForm.MeasurementE.value;

	//convert inches to feet
	a = a / 12;
	b = b / 12;
	c = c / 12;
	d = d / 12;
	e = e / 12;

	// calculate sq ft
	var size = ( (a + e) * c ) + (b * d);

	return size;
}
function spherical(thisForm)
{
	var a = thisForm.MeasurementA.value;
	var b = thisForm.MeasurementB.value;

	//convert inches to feet
	a = a / 12;
	b = b / 12;

	// calculate sq ft
	// first get the radius of the cap using circumference "b"
	var pi_value=Math.PI;
	var cap_radius = ( b / pi_value ) / 2;
	// now get the radius of the sphere
	var arc2crd=a/(cap_radius*2);
	var centang=4; <!-- radians -->
	var incr=4;
	var ct=0;
	var angratio = 0;
	while (ct<75)
	{
		angratio=(centang)/(2*Math.sin(centang/2));
		if (angratio > arc2crd)
		{
			incr=incr/2;
			centang=centang-incr;
		}
		else
		{
			incr=incr*2;
			centang=centang+incr;
		}
		ct=ct+1;
	}
	var sphere_radius = cap_radius / (Math.sin( centang / 2 ));
	var apo = (sphere_radius * sphere_radius) - (cap_radius * cap_radius);
	apo=Math.sqrt(apo);
	var caphgt=sphere_radius-apo;
	var size = 2*pi_value*sphere_radius*caphgt;

	return size;
}

function Skylight(name, measCount, factor, measImg, sizeFunction)
{
	this.name = name;
	this.measCount = measCount;
	this.measImg = measImg;
	// preload the image
	var tempImg = new Image();
	tempImg.src = measImg;
	this.factor = factor;
	this.calculateSize = sizeFunction;
}
Skylight.prototype.name;
Skylight.prototype.measCount;
Skylight.prototype.measImg;
Skylight.prototype.factor;


//helper function to create the form
function getNewSubmitForm()
{
	var submitForm = document.createElement("FORM");
	document.body.appendChild(submitForm);
	submitForm.method = "POST";
	return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue)
{
	var newElement = document.createElement("input");
	newElement .setAttribute("type", "hidden");
	newElement .setAttribute("name", elementName);
	newElement .setAttribute("value",  elementValue);
	inputForm.appendChild(newElement);
	newElement.value = elementValue;
	return newElement;
}

//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit()
{
	var submitForm = getNewSubmitForm();
	createNewFormElement(submitForm, "field1", "somevalue");
	createNewFormElement(submitForm, "field2", "somevalue");
	submitForm.action= "someURL";
	submitForm.submit();
}



