// used by: p1.htm

//initAll
window.onload = initAll;
var xhr = false;
var isIE = false;
var unitPrice = 0;
var args;
var strTagName="";
var data=null;


//getHTTPObject
function getHTTPObject() {
	var xhr = false;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	return xhr;
}

//initAll
function initAll() {		
		//determine which xmlhttprequest object will be instanciated, IE or non-IE xmlhttprequest object
		xhr =getHTTPObject();
		 
		 //is xmlhttprequest created?
     if (xhr) {
        xhr.onreadystatechange = getPrice;
        //xhr.open("GET", "json.js", true);
				xhr.open("GET", "js/dataPrice.js", true);
				
				//set header so as to prevent caching of content because price_feet.xml might change its value
				xhr.setRequestHeader ("If-Modified-Since", "Wed, 15 Jan 1995 01:00:00 GMT");
		    xhr.setRequestHeader ("Cache-Control","no-cache");
			  xhr.setRequestHeader ("Cache-Control", "must-revalidate");
			  xhr.setRequestHeader ("Cache-Control","no-store");
			  xhr.setRequestHeader ("Pragma","no-cache");
			  xhr.setRequestHeader ("Expires","0");
	
        xhr.send(null);
     }
     else {
        alert("Sorry, can't retrieve unit price as of this moment...");
     }
}

//getPrice: - retrieve unit price
function getPrice() {
     if (xhr.readyState == 4) {
        if (xhr.status == 200) {
						//get Json object	
						data = eval('('+xhr.responseText+')');
						
						for (var i=0; i<data.panelPrices.length; i++)
						{
							document.getElementById("panelType"+(i+1)).innerHTML = data.panelPrices[i].panel;
							document.getElementById("sqFtPrice"+(i+1)).innerHTML = "$" + data.panelPrices[i].perFoot.toString();
							document.getElementById("sqMtrPrice"+(i+1)).innerHTML = "$" + data.panelPrices[i].perMeter.toString();
							document.getElementById("optPanel"+(i+1)).innerHTML = data.panelPrices[i].panel;
						}				
					 return;
          }
          else {
             alert("There was a problem with the request: " + xhr.statusText);
          }
      }
}

//getArgs
function getArgs( ) {
    var args = new Object( );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}

//showPricePerFoot
function showPricePerFoot(price)
{
	var i;
	for (i=1;i<=10;i++)
	{
		//document.getElementById("priceSquareFoot_"+i).innerHTML = price;
		document.getElementById("priceSquareFoot_"+i).innerHTML = unitPrice;
	}
}

//computeRow
function computeRow(objID,rowID)
{
	//get element suffix to determine which element has lost focus (user has input value)
	var indexNo = getElementSuffix(objID);
	
	computeWallSquareFeet(indexNo);
	computeWindowSquareFeet(indexNo);
	computeDoorSquareFeet(indexNo);

	//display price per foot
	//var price1 = parseFloat(document.getElementById("price1").innerHTML).toFixed(2);
	var price1 = parseFloat(unitPrice).toFixed(2);
	
	//alert(price1);
	document.getElementById("priceSquareFoot_"+indexNo).innerHTML = price1;
	
	var totalSqrFt = computeTotalSqrFt(indexNo);
		
	//compute total price
	if (totalSqrFt !=0  && !isNaN(price1))
	{
		//round total price by using custom number rounding
		var totalPrice = formatNumber((totalSqrFt * price1),2);
		//if totalPrice is negative, display blank else display totalPrice formatted with comma separator
		document.getElementById("totalPrice_"+indexNo).innerHTML = totalPrice < 0 ? "" : formatCommas(totalPrice.toString());	
	} 
	else {
		document.getElementById("totalPrice_"+indexNo).innerHTML = "";		
	}
	
		
	getOverallTotal();	
}

//formatNumber, .toFixed(2) does not round properly, use this only in rounding prices
//but not for getting the total of all prices
function formatNumber (num, decplaces) {
    // convert in case it arrives as a string value
    num = parseFloat(num);
    // make sure it passes conversion
    if (!isNaN(num)) {
        // multiply value by 10 to the decplaces power;
        // round the result to the nearest integer;
        // convert the result to a string
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        // exponent means value is too big or small for this routine
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        // if needed for small values, pad zeros
        // to the left of the number
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        // calculate decimal point position
        var decpoint = str.length - decplaces;
        // assemble final result from: (a) the string up to the position of
        // the decimal point; (b) the decimal point; and (c) the balance
        // of the string. Return finished product.
        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}

//computeTotalSqrFt
function computeTotalSqrFt(indexNo)
{
  var wallSqrFt = parseFloat(stripCommas(document.getElementById("wallSquareFeet_"+indexNo).innerHTML));
	var windowSqrFt = parseFloat(stripCommas(document.getElementById("windowSquareFeet_"+indexNo).innerHTML));
	var doorSqrFt = parseFloat(stripCommas(document.getElementById("doorSquareFeet_"+indexNo).innerHTML));
	
	wallSqrFt = isNaN(wallSqrFt) ? 0 : wallSqrFt;
	windowSqrFt = isNaN(windowSqrFt) ? 0 : windowSqrFt;
	doorSqrFt = isNaN(doorSqrFt) ? 0 : doorSqrFt;

	totalSqrFt = wallSqrFt - (windowSqrFt +doorSqrFt);
	
	totalSqrFt = parseFloat(totalSqrFt).toFixed(2);
	
	if (totalSqrFt != 0)	{
			document.getElementById("totalSquareFeet_"+indexNo).innerHTML = formatCommas(totalSqrFt.toString());
	}
	else {
		document.getElementById("totalSquareFeet_"+indexNo).innerHTML = "";		
	}
	//make totalSquareFeet be in red if computation results to negative value
	document.getElementById("totalSquareFeet_"+indexNo).style.color = totalSqrFt < 0 ? "red" : "black";
		
	return totalSqrFt;	
}

//numeralsOnly
function numeralsOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
    //if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)  {
        //alert("Enter numerals only in this field.");
        return false;
    }
    return true;
}

//recalculate
function recalculate()
{
   var i;
	 for (i=1; i<=10;i++)	 {
	   computeRow(document.getElementById("wallLength_" + i));
	}	
	getOverallTotal();
}

//getOverallTotal
function getOverallTotal()
{
	var i;
  var total=0;
  var rowTotal = 0;	
	
 	for (i=1; i<=10;i++)	 {
		 rowTotal = parseFloat(stripCommas(document.getElementById("totalPrice_" + i).innerHTML)); 
		 if (!isNaN(rowTotal)) {
	   total = total + rowTotal;				 
		}
	}	
	total = formatCommas(total.toFixed(2));
	document.getElementById("total").innerHTML = total;
}

//stripCommas
function stripCommas(numString) {
    var re = /,/g;
    return numString.replace(re,"");
}

//formatCommas
function formatCommas(numString) {
    var re = /(-?\d+)(\d{3})/;
    while (re.test(numString)) {
        numString = numString.replace(re, "$1,$2");
    }
    return numString;
}

//computeDoorSquareFeet
function computeDoorSquareFeet(indexNo)
{
	var doorLength = document.getElementById("doorLength_"+indexNo);
	var doorHeight = document.getElementById("doorHeight_"+indexNo);
	var doorSquareFeet = 0;
	
	if (isValidDimension(doorLength)  && isValidDimension(doorHeight))
	{
	doorSquareFeet = (parseFloat(doorLength.value).toFixed(2) * parseFloat(doorHeight.value).toFixed(2)).toFixed(2);
	document.getElementById("doorSquareFeet_"+indexNo).innerHTML = formatCommas(doorSquareFeet.toString());
	}
	else {
	//document.getElementById("doorSquareFeet_"+indexNo).innerHTML = "0.00";
	document.getElementById("doorSquareFeet_"+indexNo).innerHTML = "";
	}
}

//computeWindowSquareFeet
function computeWindowSquareFeet(indexNo)
{
	var windowLength = document.getElementById("windowLength_"+indexNo);
	var windowHeight = document.getElementById("windowHeight_"+indexNo);
	var windowSquareFeet = 0;
	
	if (isValidDimension(windowLength)  && isValidDimension(windowHeight))
	{
	windowSquareFeet = (parseFloat(windowLength.value).toFixed(2) * parseFloat(windowHeight.value).toFixed(2)).toFixed(2);
	document.getElementById("windowSquareFeet_"+indexNo).innerHTML = formatCommas(windowSquareFeet.toString()); //windowSquareFeet;
	}
	else {
	//document.getElementById("windowSquareFeet_"+indexNo).innerHTML = "0.00";
	document.getElementById("windowSquareFeet_"+indexNo).innerHTML = "";
	}
}

///computeWallSquareFeet
function computeWallSquareFeet(indexNo)
{
	var wallLength = document.getElementById("wallLength_"+indexNo);
	var wallHeight = document.getElementById("wallHeight_"+indexNo);
	var wallSquareFeet = 0;
	
	if (isValidDimension(wallLength)  && isValidDimension(wallHeight))
	{
	wallSquareFeet = (parseFloat(wallLength.value).toFixed(2) * parseFloat(wallHeight.value).toFixed(2)).toFixed(2);
	document.getElementById("wallSquareFeet_"+indexNo).innerHTML = formatCommas(wallSquareFeet.toString());//wallSquareFeet;
	}
	else {
	//document.getElementById("wallSquareFeet_"+indexNo).innerHTML = "0.00";
	document.getElementById("wallSquareFeet_"+indexNo).innerHTML = "";
	}
}

//isValidDimension
function isValidDimension(objId)
{
	//TODO: negative value should be included in the invalid input
	return (!objId.value || isNaN(parseFloat(objId.value))) ? false : true;
}

//getElementSuffix
function getElementSuffix(objID)
{
	//get string position of _
	var index_ = objID.id.lastIndexOf("_");
	
	//get the element suffix number
	var indexNo = objID.id.substr(index_ + 1,objID.id.length - index_ )
	return indexNo;
}

//clearEntries
function clearEntries()
{
	var i;
	for (i=1;i<=10;i++)
	{
		document.getElementById("wallSquareFeet_" + i).innerHTML = "";
		document.getElementById("windowSquareFeet_" + i).innerHTML = "";
		document.getElementById("doorSquareFeet_" + i).innerHTML = "";
		document.getElementById("totalSquareFeet_" + i).innerHTML = "";		
		document.getElementById("totalPrice_" + i).innerHTML = "";		
	}
	document.getElementById("total").innerHTML = "";		
	document.formPanel.reset();
}

function getIndex()
				{
				var i,m =null ;
				i= document.forms.formCalculator.selectPanel.selectedIndex;
				m = document.forms.formCalculator.selectUnit.selectedIndex;
				//alert(document.forms.formCalculator.selectPanel.selectedIndex);
				openCenteredWindow("calculator.htm?i=" + i + "&m=" + m);
				}

