var skipform = false;

var CarbonCalc = function () {
	var ERRS = [];
	
	function add_commas (nStr) {
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
	function listErrors () {
		var eList = '';
		ERRS.each(function(e) { eList += '<li>' + e + '</li>'; });
		ERRS = [];
		return '<ol class="warning">' + eList + '</ol>';
	}
	
	function showResults (params) {
		var printIt = '';
		var calcEL = $(params.type + 'CarbonSavings');
		var resultsEL = calcEL.down('div.results');
		var printEL = calcEL.down('div.printIt');
		
		


		//all form names begin with LT_ for Listrack
		printIt = '<div class="form" style="display:none;">\
		<h2>Please fill-out the following information for a print-ready version of your results:</h2>\
		<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="post" onsubmit="return false" id="' + params.type + 'Print_form">\
		<fieldset>\
			<div class="cols">\
				<div class="col">\
				<label for="' + params.type + 'Print_first_name">First Name</label><input id="' + params.type + 'Print_first_name" maxlength="40" name="first_name" type="text" class="text" tabindex="1" />\
				<label for="' + params.type + 'Print_title">Title</label><input id="' + params.type + 'Print_title" maxlength="40" name="title" type="text" class="text" tabindex="3" />\
				<label for="' + params.type + 'Print_company">Company</label><input id="' + params.type + 'Print_company" maxlength="40" name="company" type="text" class="text" tabindex="5" value="' + params.company + '" />\
				<label for="' + params.type + 'Print_num_beds">Number of beds:</label><input  id="' + params.type + 'Print_num_beds" name="00N40000002EBUO" type="text" class="text" tabindex="7" value="' + params.numBeds + '" />\
				</div>\
				<div class="col">\
				<label for="' + params.type + 'Print_last_name">Last Name</label><input id="' + params.type + 'Print_last_name" maxlength="40" name="last_name" type="text" class="text" tabindex="2" />\
				<label for="' + params.type + 'Print_email">Email</label><input id="' + params.type + 'Print_email" maxlength="80" name="email" type="text" class="text" tabindex="4" />\
				<label for="' + params.type + 'Print_city">City</label><input id="' + params.type + 'Print_zip" maxlength="20" name="city" type="text" class="text" tabindex="6" value="" />\
				<label for="' + params.type + 'Print_state">State</label><input id="' + params.type + 'Print_zip" maxlength="20" name="state" type="text" class="text" tabindex="6" value="" />\
				<label for="' + params.type + 'Print_zip">5-Digit Zip Code</label><input id="' + params.type + 'Print_zip" maxlength="20" name="zip" type="text" class="text" tabindex="6" value="' + params.zip + '" />';
				if (params.type == 'customer') {
					printIt += '<label for="' + params.type + 'Print_customer_number">Stericycle Customer # (if applicable):</label><input id="' + params.type + 'Print_customer_number" maxlength="8" name="00N30000000lgD1" type="text" class="text" tabindex="8" value="' + params.custNum + '" />';
				}
				printIt += '</div>\
			</div>\
		</fieldset>\
		<fieldset class="optin">\
			<input id="' + params.type + 'Print_optin" name="00N40000001V49r" type="checkbox" class="checkbox" value="1" /><label for="' + params.type + 'Print_optin">Yes, I would like to receive email communication from Stericycle:</label>\
		</fieldset>\
		<input type="submit" name="submit" style="display:none;" />\
		<input type="hidden" name="oid" value="00D300000000aLj" />\
		<input type="hidden" name="retURL" value="http://www.stericycle.com" />\
		<input type="hidden" name="00N30000000m5Tv" value="WebLeadCarbonFoot" />\
		<input type="hidden" name="recordType" value="012400000000k7b" />\
		<input type="hidden" name="00N30000001D2ZI" value="WebLead" />\
		</form>\
		<a href="javascript:CarbonCalc.sendInfo(\'' + params.type + '\');" class="action submit">Submit</a>\
		</div>';
		
		if(skipform) {
			printIt += '<a href="javascript:CarbonCalc.sendInfo(\'' + params.type + '\');" class="action print">Save/Print Your Results</a>';
		} else {
		
			printIt += '<a href="javascript:CarbonCalc.showPrintForm(\'' + params.type + '\');" class="action print">Save/Print Your Results</a>';
			
		}
		
		resultsEL.update(params.results);
		printEL.update(printIt);
		
	}
	
	var pub = {
		calcBeds : function () {
			var beds = parseInt($('NumBeds').value);
			var fName = $('FacilityName').value;
			var fZip = $('PCZip').value;
			var results = '';
			
			if (fName == '' || fName == 'Enter your name here') { ERRS.push('Please enter your facility\'s name.'); }
			if (fZip == '' || fZip == '5-Digit Zip Code') { ERRS.push('Please enter your facility\'s zip code.'); }
			if (isNaN(beds)) { ERRS.push('Please enter number of beds.'); }
			
			if (ERRS.length > 0) {
				$('prospectCarbonSavings').down('div.results').update(listErrors());
			} else {
				var aloc=beds*1.65;
				var gal2=aloc*0.1;
				var gal3=aloc*0.1;
				var gal4=aloc*0.6;
				var gal8=aloc*0.15;
				var gal17=aloc*0.05;
				var gal2w=gal2*0.65;
				var gal3w=gal3*0.4;
				var gal4w=gal4*0.4;
				var gal8w=gal8*0.78;
				var gal17w=gal17*1.02;
				var gal2l=(gal2w*52)*1.2;
				var gal3l=(gal3w*52)*1.8;
				var gal4l=(gal4w*52)*2;
				var gal8l=(gal8w*52)*3.5;
				var gal17l=(gal17w*52)*5;
				var lbsplastic=gal2l+gal3l+gal4l+gal8l+gal17l;
				var lbscardboard=(((gal2w*52)+(gal3w*52)+(gal4w*52))/10*1.6)+(((gal8w*52)/6)*1.6)+(((gal17w*52)/6)*1.6);
				var lbsCO2=((lbscardboard/2000)*604.5)+(lbsplastic*0.57);
				var galsgas=lbsCO2/19.4202454;
				var propanecyl=lbsCO2/52.868476;
				
				results = '<div class="savings">\
				<h2>By using Stericycle\'s Sharps Management Service featuring Bio Systems reusable sharps containers, your facility\'s annual carbon savings would be:</h2>\
				<dl class="first"><dt>Pounds of CO<sub>2</sub> emissions prevented</dt><dd>' + add_commas(Math.round(lbsCO2)) + '</dd></dl>\
				<dl><dt>Pounds of plastic kept out of landfills</dt><dd>' + add_commas(Math.round(lbsplastic)) + '</dd></dl>\
				<dl><dt>Pounds of cardboard kept out of landfills</dt><dd>' + add_commas(Math.round(lbscardboard)) + '</dd></dl>\
				<dl><dt>CO<sub>2</sub> emissions prevented equal to this many gallons of gasoline</dt><dd>' + add_commas(Math.round(galsgas)) + '</dd></dl>\
				<dl><dt>CO<sub>2</sub> emissions prevented equal to not using this many tanks propane gas for home barbecues</dt><dd>' + add_commas(Math.round(propanecyl)) + '</dd></dl>\
				</div>';
				
				showResults({'type':'prospect','results':results,'zip':fZip,'custNum':'','company':fName,'numBeds':beds});
			}
			
			return false;
		},
		
		doCarbonCalc : function () {
			var c = document.getElementById('CCNumber').value;
			var z = document.getElementById('CCZip').value;
			var y = document.getElementById('CCYear').value;
			
			if (isNaN(c)) { ERRS.push('Please enter your Customer Number.'); }
			if (z == '' || z == '5-Digit Zip Code') { ERRS.push('Please enter your Zip Code.'); }
			if (y == '') { ERRS.push('Please choose a year.'); }
			
			if (ERRS.length > 0) {
				$('customerCarbonSavings').down('div.results').update(listErrors());
			} else {
				var ajaxScript = 'ajax/carbonCalc.php';
				var ajax_params = {'CustomerNum':c,'Zip':z,'Year':y};
				var ajax_opts = {method:'get',
					parameters:ajax_params,
					onSuccess: function(ajax_resp) {
						var r = ajax_resp.responseText.strip().evalJSON();
						if(!r.errors) {
							showResults({'type':'customer','results':r.results,'zip':z,'custNum':r.custNum,'company':r.company,'numBeds':''});
						} else {	
							$('customerCarbonSavings').down('div.results').update(r.errors);
						}
					}
				}
				new Ajax.Request(ajaxScript,ajax_opts);
			}
			return false;
		},
		
		fieldSwap : function (el,val,typ) {
			switch (typ) {
			case 'foc' :
				if (el.value == val) { el.value = ''; }
				break;
			case 'blr' :
				if (el.value == '') { el.value = val; }
				break;
			}
		},
		
		showPrintForm : function (cType) {
			var printItEL = $(cType + 'CarbonSavings').down('div.printIt');
			printItEL.down('a.print').hide();
			printItEL.down('div.form').show();
			
		},
		
		pdfIt : function (cType) {
			alert('under construction');
		},
		
		printIt : function (cType) {
			var params = [];
			var cZip = '',cName = '',vals = '';
			var EL = $(cType + 'CarbonSavings');
			EL.down('div.results').down('div.savings').select('dd').each(function (v) { vals += '|' + v.innerHTML; } );
			params.push('vals=' + vals.substr(1));
			
			switch (cType) {
			case 'prospect' :
				cZip = $('PCZip').value;
				cName = $('FacilityName').value;
				break;
			case 'customer' :
				cZip = EL.down('div.company').down('span.zip').innerHTML;
				cName = EL.down('div.company').down('span.title').innerHTML;
				params.push('Year=' + $('CCYear').value);
				break;
			}
			
			params.push('cType=' + cType);
			params.push('cName=' + escape(cName));
			
			params.push('pdf=no');
			var winURL = 'carbonFootprintPrintout/index.php?' + params.join('&');
			
			window.open(winURL,'printfriendly','width=600px,height=800px,scrollbars,resizable');
		},
		
		sendInfo : function (cType) {
			var printAllowed = true;
			var params = [];
			var errors = [];
			var reqFields = [
				{'display':'First Name','id':'first_name','req':true},
				{'display':'Last Name','id':'last_name','req':true},
				{'display':'Company','id':'company','req':true},
				{'display':'Title','id':'title','req':true},
				{'display':'Zip Code','id':'zip','req':true},
				{'display':'Email Address','id':'email','req':true},
				{'display':'Number of Beds','id':'num_beds','req':true}
			];
			if (cType == 'customer') {
				reqFields.push({'display':'Customer Number','id':'customer_number'});
			}
			
			// check form
			if(!skipform) {
				var formEL = $(cType + 'Print_form');
				if (formEL) {
					reqFields.each(function(field,i) {
						if (field.req) {
							var fieldEL = $(cType + 'Print_' + field.id).removeClassName('error');
							var empty = (/^\w+/i.test(fieldEL.value)) ? false : true;
							if (empty) {
								errors.push('Please enter ' + field.display);
								fieldEL.addClassName('error');
								
							}
						}
					});
					if (errors.length > 0) {
						printAllowed = false;					
					} else {
						params = formEL.serialize().split('&');
						
						var ajaxScript = 'ajax/carbonCalc.php?'+formEL.serialize();
						var ajax_params = {'task':'submitResults'};
						var ajax_opts = {method:'get',
							parameters:ajax_params,
							onSuccess: function(ajax_resp) {}
						}
						new Ajax.Request(ajaxScript,ajax_opts);
					
					}
				}
			}
			
			if (printAllowed) {
				var EL = $(cType + 'CarbonSavings');
				EL.down('div.printIt').hide();
				
				var thanks = '<h2>Thanks!</h2><p>Please click on the link below to print or save your results.</p>';
				thanks += '<ul>';
				thanks += '<li><a href="javascript:CarbonCalc.printIt(\'' + cType + '\');" class="action print">Save/Print Your Results</a></li>';
				thanks += '</ul>';
				
				EL.down('div.thanks').update(thanks).show();
			} else {
				var errList = '';
				errors.each(function(err,i) { errList += (i + 1) + ': ' + err + "\n"; });
				alert('The folowing errors were detected:' + "\n\n" + errList);
			}
		}

	}
	return pub;
}();
