var geocoder, location1, location2, gDir, distance, dirtType;

var palAmount = 0;
var TotPicAmount = 0;
var halfPalAmount = 0; 
var origPicAmount = 0;
var footage = 0;
var grass = '';
var totalSubPrice = 0;
var TotalSodPrice = 0;
var picAmount = 0;
var dirtYard = 0;
var dirtPrice = 0;
var dirtTotal = 0;


window.onload = initialize;

function calcQuote()
{
	var shape = document.frmQuote.selShape.value;
	
	var hasInnerText =
(document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

if(!hasInnerText)
{
   document.getElementById('frmerror').textContent = '';
   } 
   else
  {
  document.getElementById('frmerror').innerText = '';
}


	
var emailFilter="/^.+@.+\..{2,3,4,6}$/";
var illegalChars= "/[\(\)\<\>\,\;\:\\\/\"\[\]]/";
var stripped = document.frmQuote.txtNumber.value.replace(/[\(\)\.\-\ ]/g, '');
var strng = document.frmQuote.txtEmail.value



if (document.frmQuote.txtFname.value == '') {
	
	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'First name is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'First name is a required feild.';
	}
return false;
}
else if (document.frmQuote.txtLname.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Last name is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Last name is a required feild.';
	}
		return false;
	}
	
	else if (stripped == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Phone Number is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Phone Number is a required feild.';
	}
		return false;
	}
	
	 else if (isNaN(stripped)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Phone.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Phone.';
	}
 
      return false; 
      } 
	
	else if (!(stripped.length == 10)) {
			 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Phone number must contain 10 digits';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Phone number must contain 10 digits';
	}

		return false;
	}
	
	else if (document.frmQuote.txtEmail.value == '') {
					 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Email Address is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Email Address is a required feild.';
	}
		
		return false;
	}
	else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.frmQuote.txtEmail.value))){
							 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Email Address is not properly formated.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Email Address is not properly formated.';
	}

	return false;
	}

	else if (strng.match(illegalChars)) {
			if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent =  'Email address entered contains invalid charecters.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText =  'Email address entered contains invalid charecters.';
	}
   	
	return false;
	
	}
	else if (document.frmQuote.txtAddress.value == '') {
				if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent =  'Address is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText =  'Address is a required feild.';
	}

		return false;
	}
		else if (document.frmQuote.txtCity.value == '') {
							if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent =  'City is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText =  'City is a required feild.';
	}

		return false;
	}
	
		else if (document.frmQuote.selState.value == '') {
									if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'State is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'State is a required feild.';
	}

		return false;
	}
	
			else if (document.frmQuote.txtZip.value == '') {
											if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Zip Code is a required feild.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Zip Code is a required feild.';
	}
	
		return false;
	}
	
			else if (isNaN(document.frmQuote.txtZip.value)) { 
													if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Zip Code.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Zip Code.';
	}
   
      return false; 
      } 
	
	else if (!(document.frmQuote.txtZip.value.length == 5)) {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Zip Code must contain 5 digits';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Zip Code must contain 5 digits';
	}

		return false;
	}
	else if (document.frmQuote.selGrassType.value == '') {
											if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please select a grass type.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please select a grass type.';
	}
	
		return false;
	}
else if (shape == 'square')
{
	if (document.frmQuote.txtHeight.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Height is a required field.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Height is a required field.';
	}

		return false;
	}
	else if (document.frmQuote.txtWidth.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Width is a required field.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Width is a required field.';
	}

		return false;
	}
	else if (isNaN(document.frmQuote.txtHeight.value)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Height.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Height.';
	}
 
      return false; 
      }  
      	else if (isNaN(document.frmQuote.txtWidth.value)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Width.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Width.';
	}
 
      return false; 
      } 
}

else if (shape == 'circle')
{
	if (document.frmQuote.txtDiameter.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Diameter is a required field.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Diameter is a required field.';
	}

		return false;
	}
	else if (isNaN(document.frmQuote.txtDiameter.value)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Diameter.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Diameter.';
	}
 
      return false; 
      }  

}
else if (shape == 'triangle')
{
	if (document.frmQuote.txtBase.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Base is a required field.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Base is a required field.';
	}

		return false;
	}
	else if (document.frmQuote.txtHeight.value == '') {
		if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Height is a required field.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Height is a required field.';
	}

		return false;
	}
	else if (isNaN(document.frmQuote.txtBase.value)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Base.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Base.';
	}
 
      return false; 
      }  
      	else if (isNaN(document.frmQuote.txtHeight.value)) { 
	 	
	 	if(!hasInnerText)
	{
	  document.getElementById('frmerror').textContent = 'Please enter only numbers for Height.';
	   } 
	   else
	  {
	  document.getElementById('frmerror').innerText = 'Please enter only numbers for Height.';
	}
 
      return false; 
      } 
}
calcArea();
}


function calcArea()
{
document.getElementById('frmerror').innerHTML =	'<img src="images/loading.gif" alt=""/> Processing... please wait';

	
	grass = document.frmQuote.selGrassType.value
	//calculate sq footage
	var shape = document.frmQuote.selShape.value

	if (shape == 'square')
	{
		var hgt = document.frmQuote.txtHeight.value;
		var wid = document.frmQuote.txtWidth.value;
		
		 footage = Math.round(hgt * wid);
		//alert (footage);
	}
	else if (shape == 'circle')
	{
		var rad = document.frmQuote.txtDiameter.value / 2;
		
		footage = Math.round((rad*rad)*Math.PI);
		//alert (footage);
	}
	else if (shape == 'triangle')
	{
		var bse = document.frmQuote.txtBase.value;
		var hgt = document.frmQuote.txtHeight.value;
		
		footage = Math.round((bse * hgt)/2);
		//alert (footage);
	}
	
	//calculate amount of sod needed
	
	//calc number of pieces needed.
	
	
	//total pieces is sq footage divided by 2.6 sq feet per piece
	 TotPicAmount = Math.round(footage / 2.63157895); 
	
//	alert (TotPicAmount);

	//pallet amount is total number of pieces divided by 160 approx pieces per pallet
	

	palAmount = TotPicAmount / 160; 
	

		if (grass == 'palisades')
	{
		palAmount = Math.ceil(TotPicAmount / 160); 
		picAmount = 0;
}
else
	{
	// get the decimal portion of the pallet amount nad subract the whole number amount to get decimal
	var OrigPicAmount = palAmount - Math.floor(palAmount);
	
	//multiply decimal amount by 160 pieces to determine the number of loose pieces.
	origPicAmount = Math.round(OrigPicAmount * 160);
	
	if (origPicAmount <= 80 )
	{
		halfPalAmount = 0;
		
		picAmount = origPicAmount;
	}
	else
		{
			halfPalAmount = 1;
			
			picAmount = origPicAmount - 80;
		}
	

	
	//round palAmount to determine total number of pallets
	palAmount = Math.floor(palAmount);
	
	//round halfPalAmount to determine total number of half pallets
	
	halfPalAmount = Math.round(halfPalAmount);
	

}

//calculate dirt amounts
if (!document.frmQuote.radDil[4].checked)
{
	dirtYard = palAmount + halfPalAmount;
	
	if (picAmount > 0)
	{
		dirtYard = dirtYard + 1;
	}
}

//calculate dirt total
if (document.frmQuote.radDil[0].checked) //dilo mix
{
	dirtType = 'Dillo Compost Mix with Soil';
	dirtPrice = 45;
	dirtTotal = CurrencyFormatted(Math.round(parseFloat(dirtYard * dirtPrice)*100)/100);
}
else if (document.frmQuote.radDil[1].checked) //comp mix
{
	dirtType = 'Compost Mix with Soil';
	dirtPrice = 40;
	dirtTotal = CurrencyFormatted(Math.round(parseFloat(dirtYard * dirtPrice)*100)/100);
}
else if (document.frmQuote.radDil[2].checked) //mulch
{
	dirtType = 'Mulch';
	dirtPrice = 35;
	dirtTotal = CurrencyFormatted(Math.round(parseFloat(dirtYard * dirtPrice)*100)/100);
}
else if (document.frmQuote.radDil[3].checked) //top soil
{
	dirtType = 'Top Soil';
	dirtPrice = 30;
	dirtTotal = CurrencyFormatted(Math.round(parseFloat(dirtYard * dirtPrice)*100)/100);
}





//calculate price
//alert ("Pallets: " + palAmount + " Half Pallet: " + halfPalAmount + " Pieces: " + picAmount)	


	if (grass == 'staugustine' || grass == 'bermuda')
	{
		
		var palPrice = 110; //per pallet
		var halfPalPrice = 70; //half pallet
		var picPrice = 1.50; //per piece
		
	}
	else if (grass == 'palisades')
	{
		var palPrice = 180; //per pallet
	
	}
	else if (grass == 'celebration' || grass == 'palmetto')
	{
		var palPrice = 130; //per pallet
		var halfPalPrice = 70; //half pallet
		var picPrice = 1.50; //per piece
	}
	
	//calculate subtotal
	if (grass != 'palisades')
	{
		
	var SubTotalPalPrice = CurrencyFormatted(Math.round(parseFloat(palAmount * palPrice)*100)/100);
	var SubTotalHalfPalPrice = CurrencyFormatted(Math.round(parseFloat(halfPalAmount * halfPalPrice)*100)/100);
	var SubTotalPicPrice = 	CurrencyFormatted(Math.round(parseFloat(picAmount * picPrice)*100)/100);

	 totalSubPrice = CurrencyFormatted(Math.round(parseFloat(parseFloat(SubTotalPalPrice) + parseFloat(SubTotalHalfPalPrice) + parseFloat(SubTotalPicPrice) + parseFloat(dirtTotal))*100)/100);
	
		//calculate total with tax
	 TotalSodPrice = CurrencyFormatted(Math.round(parseFloat(totalSubPrice * 1.0825)*100)/100);

}
else {
	
	var SubTotalPalPrice = CurrencyFormatted(Math.round(parseFloat(palAmount * palPrice)*100)/100);
	var SubTotalPicPrice = 	CurrencyFormatted(Math.round(parseFloat(picAmount * picPrice)*100)/100);
	
	 totalSubPrice = CurrencyFormatted(Math.round(parseFloat(parseFloat(SubTotalPalPrice) + parseFloat(SubTotalPicPrice) + parseFloat(dirtTotal))*100)/100);
		//calculate total with tax
 TotalSodPrice = CurrencyFormatted(Math.round(parseFloat(totalSubPrice * 1.0825)*100)/100);

}


//delivery charges

if (document.frmQuote.radDel[0].checked || document.frmQuote.radDelSol[0].checked)
{
var addr = document.frmQuote.txtAddress.value + ', ' + document.frmQuote.txtCity.value + ', ' + document.frmQuote.selState.value + document.frmQuote.txtZip.value

showLocation(addr);
int = setInterval("distance = Math.round(distance); contCalc(distance); window.clearInterval(int);",5000)
}
else 
	{
		distance = 0;
		contCalc(distance, addr);
	}
}



function contCalc(distance, addr)
{
if (distance  == 0)
{
	var delCharge = 0;
}	
else if (distance >= 1 && distance <= 5)
{
	var delCharge;
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = 50;
	}
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = delCharge + 50;
	}
	
	totalSubPrice = parseFloat(totalSubPrice) + delCharge

	TotalSodPrice = parseFloat(TotalSodPrice) + delCharge
}
else if (distance >= 6 && distance <= 10)
{
	var delCharge;
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = 75;
	}
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = delCharge + 75;
	}
	
	totalSubPrice = parseFloat(totalSubPrice) + delCharge

	TotalSodPrice = parseFloat(TotalSodPrice) + delCharge
}
else if (distance >= 11 && distance <= 20)
{
	var delCharge;
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = 100;
	}
	if (document.frmQuote.radDel[0].checked)
	{
		delCharge = delCharge + 100;
	}
	
	totalSubPrice = parseFloat(totalSubPrice) + delCharge

	TotalSodPrice = parseFloat(TotalSodPrice) + delCharge
}
else if (distance > 20)
{
	var delCharge = 1;
}



//alert ("Total Pieces: " + TotPicAmount + " PalletAmount: " + palAmount + " Pieces: " + picAmount + " Half Pallet: " + halfPalAmount + " Sq Footage: " + footage + " Grass Type: " + grass + " Subtotal: " + totalSubPrice + " Total: " + TotalSodPrice + " Distance: " + distance);
var	data = "dirtYard=" + dirtYard + "&dirtType=" + dirtType + "&TotPicAmount="+ TotPicAmount + "&delCharge=" + delCharge + "&palAmount=" + palAmount + "&picAmount=" + picAmount + "&halfPalAmount=" + halfPalAmount + "&footage=" + footage + "&grass=" + grass + "&totalSubPrice=" + totalSubPrice + "&TotalSodPrice=" + TotalSodPrice + "&distance="+ distance + "&fname=" + document.frmQuote.txtFname.value + "&lname=" + document.frmQuote.txtLname.value + "&email=" + document.frmQuote.txtEmail.value + "&phone=" + document.frmQuote.txtNumber.value;
	//alert(data)
		 $.ajax({
  type: 'POST',
  url: 'sendquote.php',
  data: data,
  success: function(data, status) { 
  	
  	if (data == 1)
  	{
  		document.getElementById('frmerror').innerHTML =	'';
  		var url = "quote.php?" +  "dirtYard=" + dirtYard + "&dirtType=" + dirtType + "&TotPicAmount="+ TotPicAmount + "&delCharge=" + delCharge + "&palAmount=" + palAmount + "&picAmount=" + picAmount + "&halfPalAmount=" + halfPalAmount + "&footage=" + footage + "&grass=" + grass + "&totalSubPrice=" + totalSubPrice + "&TotalSodPrice=" + TotalSodPrice + "&distance="+ distance;
  		window.location = url;
  	}
  	else
  		{
	//alert(data);
	document.getElementById('frmerror').innerHTML =	data;
	}
  	 } ,
  error:function (xhr, ajaxOptions, thrownError)
		{  
			alert(xhr.status);
			alert(thrownError);
		} 
});
	
	

}
function str_to_num(form) {
num_out = "";
if(form.input.value == "") alert(e);
else {
str_in = escape(form.input.value);
for(i = 0; i < str_in.length; i++) {
num_out += str_in.charCodeAt(i) - 23;
}
form.output.value = num_out;
form.input.value = "";
   }
}

 
function initialize() {
	geocoder = new GClientGeocoder();
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", function() {
		var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
		//var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
	//	document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
	distance = drivingDistanceMiles;
	});
}
 
function showLocation(address2) {

	var address1 = '15000 Ranch Road 620 North Austin, Texas 78717';
	geocoder.getLocations(address1, function (response) {
		if (!response || response.Status.code != 200)
		{
			alert("Sorry, we were unable to geocode the first address");
		}
		else
		{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			geocoder.getLocations(address2, function (response) {
				if (!response || response.Status.code != 200)
				{
					alert("Sorry, we were unable to geocode the second address");
				}
				else
				{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					gDir.load('from: ' + location1.address + ' to: ' + location2.address);
				}
			});
		}
	});
} 

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function changeShape()
{
	
var shape = document.frmQuote.selShape.value

if (shape == 'square')
{
	document.getElementById('area').innerHTML = '<label>Area<span style="font-size:xx-small;"> (in feet)</span>:</label><span style="font-size:xx-small;">Height: </span><input type="text" name="txtHeight" id="txtHeight" value="" size="3"/> <span style="font-size:xx-small;">Width: </span><input type="text" name="txtWidth" id="txtWidth" value="" size="3"/>';
}
else if (shape == 'circle')
{
	document.getElementById('area').innerHTML = '<label>Diameter<span style="font-size:xx-small;"> (in feet)</span>:</label> <input type="text" name="txtDiameter" id="txtDiameter" value="" size="3"/>';
}
else if (shape == 'triangle')
{
	document.getElementById('area').innerHTML = '<label>Area<span style="font-size:xx-small;"> (in feet)</span>:</label> <span style="font-size:xx-small;">Base: </span><input type="text" name="txtBase" id="txtBase" value="" size="3"/> <span style="font-size:xx-small;">Height: </span><input type="text" name="txtHeight" id="txtHeight" value="" size="3"/>';
}
	
}

