/*	The Recyclimator - Instant E-Waste Project Estimator
*		All Code Copyright 2006-2011 by Assured ITD and Peter T. Graber, MMC.
*
*		Written by Peter T. Graber, MMC, of Grabers.com
*   
*/

window.onload = prepare;

function prepare() {

	//Step 1 - Add behavior to 'Add new component row' link
		if(!document.getElementsByTagName) return false;
		var nRow = document.getElementById("ancr");
		
			nRow.onclick = function() {
					newRow();
					return false;
					}
					
	//Step 2 - Disable necessary input fields 
			textLocker();
	
		
	//Step 3 - Add behavior to component selectors
		var selects = document.getElementsByTagName("select");
			for (var i=0; i < selects.length; i++) {
				var s = selects[i];
				s.onchange = function() {
						return selectChecker(this);
						}
			}
			
	//Step 4 - Add behavior to destruction quantity widget & disable cost per drive / destruction fee 
			var hddCPD = document.getElementById('hddCPD');
					hddCPD.tabIndex = -1;
					hddCPD.readOnly = true;
					
			var hddTC = document.getElementById('hddTC');
					hddTC.tabIndex = -1;
					hddTC.readOnly = true;
			
			var hddQ = document.getElementById('hddQ');
			var hddQ = document.getElementById('hddQ');
			hddQ.onblur = function() {
						return hddCalc(this);
				}
}
		
		
function hddCalc(widget) {
			var org = checkorgType();
			
			if(!org) {
					alert('Please select your organization type before proceeding');
					return false;
					}
			
			//Get weight (for calc)
			var weight = document.getElementById('lbsTotal').value;
			
			var hddPrices = new Array;
			hddPrices[1] = 24.95;
			hddPrices[2] = 14.99;
			hddPrices[3] = 9.99;
			hddPrices[4] = 8.99;
			hddPrices[5] = 6.99;
			var drives = widget.value;
			var hddCPD = 	document.getElementById('hddCPD');	
			var hddTC = document.getElementById('hddTC');
			
			if(drives < 1) {
					hddCPD.value = 0.00;
					hddTC.value = 0.00;
			}
			if(drives == 1) {
				/*	if (org == 3) {
								hddCPD.value = 19.95;
							  hddTC.value = 19.95;
							}
						
					else { */
								hddCPD.value = hddPrices[1];
								hddTC.value = hddPrices[1];
								
				}
				
			if(drives == 2) {
					hddCPD.value = hddPrices[2]/2;
					hddTC.value = hddPrices[2];
					}
					
			if(drives > 2 && drives <= 10) {
				//	drives = drives - 1;
					hddCPD.value = cleanUp((hddPrices[3] * drives) / (drives));
					hddTC.value = hddPrices[3] * drives;
					}
					
			if(drives >= 11 && drives <= 20) {
			//		drives = drives - 1;
					hddCPD.value = cleanUp((hddPrices[4] * drives) / (drives));
					hddTC.value = hddPrices[4] * drives;
					}
			if(drives >= 21) {
			//		drives = drives - 1;
					hddCPD.value = cleanUp((hddPrices[5] * drives) / (drives));
					hddTC.value = hddPrices[5] * drives;
					}
					
		  finalCalc(org, weight);
			
}		




	
function selectChecker(choice) {
		
		var value = choice[choice.selectedIndex].value;
		
		if(choice.selectedIndex == 0) {
				alert('You must first select the type of component to be recycled.');
				return false;
				}
				
		else if (value == '-') {
			choice.selectedIndex = 0;
			return false;
			}
			
	 else {
	 		var org = checkorgType();
			
			if(!org) {
					alert('Please first indicate the type of consumer you represent before indicating the components to be recycled.');
					choice.selectedIndex = 0;
					document.getElementById('orgRadio').focus();
					return false;
					}
	 			
	     
	 			pricingUpdater(choice, 's');
				return true;
				}
				
}


/*	Text Locker:  Does 3 things
*     1) Adds a unique ID# to each widget Row.
*			2) Adds matching ID# to each input widget
*     3) Disables some widgets from outside input
*/

function textLocker() {
	var container = document.getElementById('crc');
 	var rows = 	container.getElementsByTagName("div");
	
	//Disable Avg/Est weight widgets in each component row.
	for(var a=0; a < container.getElementsByTagName("div").length; a++) {
			 var widgetRow = container.getElementsByTagName("div")[a];
			 	widgetRow.id="wr|"+[a];
			 var textWidgets =  widgetRow.getElementsByTagName("input");
						for (var b=0; b < textWidgets.length; b++	) {
						
								if (b < 1) { //quantity widget
												widgetRow.getElementsByTagName("input")[b].id = 'nq|'+[a];
												widgetRow.getElementsByTagName("input")[b].onblur = function() {
																pricingUpdater(this);
												}
										}
							else if (b == 1){  //avg weight widget
							widgetRow.getElementsByTagName("input")[b].readOnly  = true;
							widgetRow.getElementsByTagName("input")[b].tabIndex = -1;
							widgetRow.getElementsByTagName("input")[b].id = 'aw|'+[a];
							}
							
							else {
							widgetRow.getElementsByTagName("input")[b].readOnly  = true;
							widgetRow.getElementsByTagName("input")[b].tabIndex = -1;
							widgetRow.getElementsByTagName("input")[b].id = 'ew|'+[a];
							}
		}
}				
	//Disable Summary values widgets
	for (var c = 0; c < lockedFields.length; c++) {
				var widget = document.getElementById(lockedFields[c]);
				widget.readOnly = true;
				}
}


 //This makes a new component row / Attached to link; 
function newRow() { 
 var container = document.getElementById('crc');
 var rows = 	container.getElementsByTagName('div')
 var lastChild = rows.length - 1;
 var copy = massageCopy(container.getElementsByTagName('div')[lastChild].cloneNode(true), rows.length);
 var lastChildDiv = container.getElementsByTagName('div')[lastChild];	
 var insertedDiv = container.insertBefore(copy, lastChildDiv.nextSibling);
 
  //re-fire onload to initialize new row behavior
 prepare();

}

//Massages Copied Div to prepare it for insertion

function massageCopy(div, id) {
	var nameAppend = id;
	
	//replace select
	var cSelector = div.getElementsByTagName('select');
	
	cSelector[0].name = 'cs_['+nameAppend+']';
	
	//replace text inputs
	var tInputs = div.getElementsByTagName('input');
	for(var a=0; a <= tInputs.length-1; a++) {
		
		var theInput = div.getElementsByTagName('input')[a];
			if(a==0) {
				theInput.name = 'quantity_['+nameAppend+']';
				theInput.value = '';
				}
				
			else if(a==1) {
				theInput.name = 'weight_'+nameAppend;
				theInput.value = '';
				}
			
			else {
				theInput.name = 'cost_'+nameAppend;
				theInput.value = '';
				}
					
	}

	return div;

}

// Confirms that an Organization type is selected and returns value

function checkorgType() { 
		var orgType = document.recyclimator.serviceType;
		
		for(i=0; i <= orgType.length-1; i++) {
				if(orgType[i].checked == true) {
						return orgType[i].value;
						}
				else {
						continue;
						}
	}
		
		return null;
}


//Responds to a change-of-selection to Component Selector Widgets and Quantity Widgets
function pricingUpdater(widget, type) {
		
	  if (type) {
		var parent = widget.parentNode;
		var parentRow = parent.parentNode;
   	var therowID = getLast(parentRow.id);
		var theChoice = widget.options[widget.selectedIndex].value;
		var priceLb = getPrice(theChoice);
				
				//Update the Avg Weight/per field
					var awp = document.getElementById('aw|'+therowID);
					awp.value = priceLb;
					
				//Now give focus to the quantity input widget after clearing quantity & totalWeight;
				document.getElementById('nq|'+therowID).value = '';
				document.getElementById('ew|'+therowID).value = '';
				document.getElementById('nq|'+therowID).focus();
				
				return true;
		}
	 
	 	else {
			var therowID = getLast(widget.id);
			var quantity = widget.value;
			var theLbsMultiplier = document.getElementById('aw|'+therowID).value;
			var totalLbs = quantity * theLbsMultiplier;
			document.getElementById('ew|'+therowID).value = totalLbs;
			}
			
			var total = generateTotal();
			document.getElementById('lbsTotal').value = total+'.00';
			
			var org = checkorgType();
			var selectWidget = 'cs_'+ therowID; 
		
			
			if(!org) {
					alert('Please indicate the type of consumer you represent and select the component type.');
					widget.value = '';
					document.getElementById('orgRadio').focus();
					return false;
					}
		
			
		 // Ensures a valid selection has been chosen in the component selector
		 
		 else if (!selectRowChecker(document.getElementsByTagName('select')[therowID])) {
					widget.value = '';
				  document.getElementsByTagName('select')[therowID].focus();
					return false;
					}   
					
			else {
				finalCalc(org,total);
				return true;
							}
					
}

function selectRowChecker(selector) {
		
		var value = selector[selector.selectedIndex].value;
		
		if( value == 0 || value == '-') {
				alert('You must first select the type of component to be recycled.');
				return false;
				}
		
		else {
			return true;
			}


}

function finalCalc(orgType, weight) {
		
		var fee = document.getElementById('pickupFee');
		var tier = null;
		var pFee = fee.value;
		var wMultiplier = null;
		var gTotal = document.getElementById('estimatedCost');
		
		// Determine weight tier
		if(!weight) {
				weight = 0;
				tier = 0;
				}
		if(weight <= 149) {
				tier = 0;
				}
		if ( (weight >= 150) && (weight <= 699) ) {
				tier = 1;
				}
			
		if ( (weight >= 700) && (weight <= 1299) ) {
				tier = 2;
				}
	if ( (weight >= 1300) && (weight <= 4999) ) {
				tier = 3;
				}
				
	if ( (weight >= 5000) && (weight <= 9999) ) {
				tier = 4;
				}
				
	if ( weight >= 10000) {
				tier = 5;
				}
				
		if (orgType == '1') {
					fee.value = '99.00';
					 }
					
	  if (orgType == '2') {
						if(weight < 1000) {
  					fee.value = '89.00';
						}
					
						else {
						fee.value = '0.00';
							}		
					
			}		
		
		if (orgType =='3') {
					if(weight < 1299) {
					fee.value	= '69.00';
					}
					
					else {
						fee.value = '0.00';
							}					
		}
				
			wMultiplier = weightCalc(orgType,tier);
	 //	alert(wMultiplier);
			var theTotal = weight * wMultiplier;
			theTotal += (fee.value - null);
		
			// Add Hard Drive Destruction
			var hddFee = document.getElementById('hddTC');
			
			theTotal = theTotal + (hddFee.value - null);
			theTotal = cleanUp(theTotal);
			gTotal.value = theTotal;
							
}


function cleanUp(number) {
		
			var total = null;
			total = (number == Math.floor(number) ? number + '.00' : ( (number*10 == Math.floor(number*10)) ? number + '0' : number));
			total = total +'';
			//This deals with Javascript's math errors.
			var decPt = total.indexOf('.', 0) + 3;			
			total = total.substr(0,decPt);
			return total;
}


function weightCalc(type,tier) {
				
		//The mainpriceTiers
		var tiers = new Array();
			tiers[1] =  new Array()
				tiers[1][0] = .85;
				tiers[1][1] = .80;
				tiers[1][2] = .77;
				tiers[1][3] = .75;
				tiers[1][4] = .65;
				tiers[1][5] = .58;
			tiers[2] =  new Array();
				tiers[2][0] = .80;
				tiers[2][1] = .72;
				tiers[2][2] = .65;
				tiers[2][3] = .59;
				tiers[2][4] = .55;
				tiers[2][5] = .50;
			tiers[3] = new Array();
				tiers[3][0] = .75;
				tiers[3][1] = .67;
				tiers[3][2] = .62;
				tiers[3][3] = .55;	
			
			return tiers[type][tier];
				
}


function generateTotal() {
			var container = document.getElementById('crc');
 			var rows = 	container.getElementsByTagName('div').length
			var tmp = 0;
			for (var a=0; a < rows; a++) {
						var ewval = document.getElementById('ew|'+ a).value;
						if((ewval == '') || (ewval == null)) {
						ewval = 0;
						}
								
						tmp += parseInt(ewval);
						}
				
			return tmp;
}


function getLast(data) {   //Simply gets the last character and returns
	 var len = data.length-1;
	 var lastChar =  data.charAt(len);
	 return lastChar;
}
	
function getPrice(choice) {

// The main components array w/weights
var components = new Array();
	components[1]= 28;
	components[2]= 25;
	components[3]= 50;
	components[4]= 12;
	
	components[10]= 26;
	components[11]= 27;
	components[12]= 44;
	components[13]= 70;
	components[14]= 90;
	
	components[20]= 15;
	components[21]=	19;
	components[22]=	24;
	components[23]=	24;
	
	components[30]= 20;
	components[31]= 30;
	components[32]=	80;
	components[33]= 135;
	
	components[40]= 9;
	components[41]= 15;
	components[42]= 35;
	components[43]= 155;
	
	components[50]= 2;
	components[51]= 20;
	components[52]= 20;
	components[53]= 11;
	components[54]= 13;
	components[55] = 20;
	components[56] = 5;
	components[57] = 100;
	
	components[60]= 9;
	components[61]= 14;
	components[62]= 22;
	components[63]= 45;
	
	components[70]= 75;
	components[71]= 160;
	
	components[80]= 20;
	components[81]= 45;
	components[82]= 70;
	components[83]= 100;
	components[84]= 120;
	components[85]= 135;
	components[86]= 170;
	
	components[90]= .25;
	components[91]=	13;
	components[92]= 11;
	components[93]=  9; 
	
	components[95]=  19; 
	components[96]=  45; 
	components[97]=  75; 
	components[98]=  90; 
	
	var price = components[choice];
	
	return price;

}

//Uneditable/Unselectable fields
var lockedFields = new Array (
		'lbsTotal','pickupFee','estimatedCost'
		);
										


