var PT 		= 37; // dollars per ton
var QTY		= '1';
var COST	= '';
var DESC	= '';
var ITEM_ID	= '';
	
$(document).ready(function() {
	
	// Total the cart if present
	if ( $('#cart').length > 0 ) total_cart('cart');
	
	
	// Total the summary if present
	if ( $('#order-summary').length > 0 ) total_cart('summary');
	
	
	// Security code toggle
	$('#what-is-secure').click(function(event) {
		event.preventDefault();
		$('#security-code').toggle();
	});

	
	// FAQ toggle
	$('a.question').click(function(event) {
		var id = this.id.substr(1);
		$('#a'+id).toggle();
		
		return false;
	});
	$('p.answer').hide();
	
	
	// Autofill the car make dropdown based on car year selection
	$('#car_year').change(function() {
		$('#car_make').empty();
		$.post('http://www.livecooler.org/handlers/carMakeSOL/'+this.value, function(data) {
			$('#car_make').append(data).selectedIndex = 0;
		});
	});
	
	
	// Autofill the car model dropdown based on car make selection
	$('#car_make').change(function() {
		$('#car_model').empty();
		$.post('http://www.livecooler.org/handlers/carModelSOL/'+$('#car_year').val()+'/'+this.value, function(data) {
			$('#car_model').append(data).selectedIndex = 0;
		});
	});
	
	
	// Add to cart button
	$("a.add_to_cart").click( function(event) {
                               var retv = genCartLink();
                               if (retv == "stop")
                               {
                                   return false;
                                }
		if (COST == '')
			COST = this.id;
		$.post(this.href, {'qty': QTY, 'item_cost': COST }, function(data) {
  		    window.location = 'http://www.livecooler.org/cart/';});
		
		return false;
	});
	
	
	//	Update cart button
	$("button.update_cart").click( function(event) {
		var id	= $(this).attr("name").substr(6);
		var qty	= $("input#qty" + id).attr("value");
		
		$("img#loading" + id).show();
		
		$.post("http://www.livecooler.org/cart/delete/" + id, { 'paypalpro_qty': qty }, function (data) {
			if ( data.substr(0,1) == "!" ) {alert(data.substr(1));} else {
				$("table#cart tr#cart-"+id).remove();
				total_cart('cart');
			}
		});
		
		return false;
	});
	
	
	//
	// CALCULATIONS FOR FLIGHT SECTION
	//
	
	$('#btn-fly').click(function(event) {
		flyCalc();
		return false;
	});
	
		function Set_Cookie( name, value, expires, path, domain, secure ) 
		{
			// set time, it's in milliseconds
			var today = new Date();
			today.setTime( today.getTime() );

			/*
			if the expires variable is set, make the correct 
			expires time, the current script below will set 
			it for x number of days, to make it for hours, 
			delete * 24, for minutes, delete * 60 * 24
			*/
			if ( expires )
			{
				expires = expires * 1000 * 60 * 60;
			}
			var expires_date = new Date( today.getTime() + (expires) );

			document.cookie = name + "=" +escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
			( ( path ) ? ";path=" + path : "" ) + 
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
		}


                 function genCartLink()
                 {
                      if (document.mass_delegates == undefined)
                      {
                           return "cont";
                      }

                      if (document.mass_delegates.delegatelist.value == "unknown")  
                      {
                           alert("Select a delegate");
                           return "stop";
                      }

                      if (document.mass_delegates.loc[0].checked && 
                          document.mass_delegates.loc[1].checked &&
                          document.mass_delegates.loc[2].checked &&
                          document.mass_delegates.loc[3].checked &&
                          document.mass_delegates.loc[4].checked)  
                      {
                           alert("Select a community");
                           return "stop";
                      }

                    if (document.mass_delegates.loc[4].checked && (document.mass_delegates.nonprofit.value == "" || document.mass_delegates.community.value == ""))  
                      {
                           alert("Select a community");
                           return "stop";
                      }
                      var community = "";
                      var np = "";
                      for (var i = 0; i <  document.mass_delegates.loc.length; i++)
                      {
                         if (document.mass_delegates.loc[i].checked)  
                         {
                             community = document.mass_delegates.loc[i].value;
                         }
                      } 

                      if (document.mass_delegates.loc[4].checked)  
                      {
                         community = document.mass_delegates.community.value;
                         np = document.mass_delegates.nonprofit.value;
                      }
                       //alert("MDC="+escape("dname="+document.mass_delegates.delegatelist.value+"&comm="+community+"&np="+np));
                       document.cookie = "MDC="+escape("dname="+document.mass_delegates.delegatelist.value+"&comm="+community+"&np="+np)+";secure";
                      return "cont";
                 }

	function flyCalc() {
		var amt 	= $('#fly_amt').val();
		var total	= ($('#fly_type').val() == 'hours') ? Math.ceil((amt * 570) * 0.45) : Math.ceil(0.45 * amt);
		var f_range	= [6600, 11000, 17600, 66000];
		var num		= 4;
		var text	= '';
		ITEM_ID		= '6';
		
		if (total <= f_range[0]) {
			num		= 1;
			COST	= cost['fly1'];
			ITEM_ID	= '6';
			text 	= desc['fly1'];
		} else if (total > f_range[0] && total <= f_range[1]) {
			num 	= 2;
			COST	= cost['fly2'];
			ITEM_ID = '7';
			text 	= desc['fly2'];
		} else if (total > f_range[1] && total <= f_range[2]) {
			num 	= 3;
			COST	= cost['fly3'];
			ITEM_ID = '8';
			text 	= desc['fly3'];
		} else if (total > f_range[2] && total <= f_range[3]) {
			COST	= cost['fly4'];
			ITEM_ID = '9';
			text 	= desc['fly4'];
		} else {
			COST	= cost['fly4'];
			ITEM_ID = '9';
		   	QTY		= 2;
			text 	= desc['fly4'];// + " x" + QTY;
		}
		
		$('.offset-item img').attr('src','/images/flight' + num + '.gif');
		$('.offset-item img + p').remove();
		$('.offset-item img').after(text);
		
		$('.offset-item p strong').append(' x ' + QTY);
		$('.offset-item p.price span').html('$' + COST*QTY);
		$('.offset-item p.price a').attr('href', 'http://www.livecooler.org/cart/add/' + ITEM_ID + '/');
		
		// $('table.recommend').show();
		$('div.recommended').show();
	}
	
	// END FLIGHT SECTION
	
	//
	// CALCULATIONS FOR CAR SECTION
	//
	
	$('#btn-car').click(function(event) {
		carCalc();
		return false;
	});
	
	
	function carCalc() {
		var year 	= $('#car_year').val();
		var id 		= $('#car_model').val();
		var miles 	= $('#car_mpy').val();
		
		var total	= '';
		var num		= 4;
		var text	= '';
		var range	= 0;
		
		if (year != '' && id != '') {$.getScript('http://www.livecooler.org/handlers/carFootprintSOL/'+year+'/'+id, function() {
				var c_range		= [6600, 8600, 13200, 22000, 44000, 66000, 88000];
				var consumed 	= miles / combined;
				total 			= Math.ceil(coefficient * consumed);
				ITEM_ID			= '5';
				COST			= cost['car4'];
				DESC			= desc['car4'];
				QTY 			= 1;
				
				if (total <= c_range[0]) {
					num		= 1;
					COST	= cost['car1'];
					ITEM_ID	= '2';
					DESC 	= desc['car1'];
				} else if (total > c_range[0] && total <= c_range[1]) {
					num 	= 2;
					COST	= cost['car2'];
					ITEM_ID	= '3';
					DESC 	= desc['car2'];
				} else if (total > c_range[1] && total <= c_range[2]) {
					num 	= 3;
					COST	= cost['car3'];
					ITEM_ID	= '4';
					DESC 	= desc['car3'];
				} else if (total > c_range[3] && total <= c_range[4]) {
					QTY		= 2;
					//DESC 	= DESC + " x" + QTY;
				} else if (total > c_range[4] && total <= c_range[5]) {
					QTY		= 3;
					//DESC 	= DESC + " x" + QTY;
				} else if (total > c_range[5] && total <= c_range[6]) {
					QTY		= 4;
					//DESC 	= DESC + " x" + QTY;
				} else {
					QTY		= 5;
					//DESC 	= DESC + " x" + QTY;
				}
				
				$('.offset-item img').attr('src','/images/car' + num + '.gif');
				$('.offset-item img + p').remove();
				$('.offset-item img').after(DESC);
				
				$('.offset-item p strong').append(' x ' + QTY);							
				$('.offset-item p.price span').html('$' + COST*QTY);
				$('.offset-item p.price a').attr('href', 'http://www.livecooler.org/cart/add/' + ITEM_ID + '/');
				
				// $('table.recommend').show();
				$('div.recommended').show();
			});
		}
	}
	// END CAR SECTION
	
	// 
	// CALCULATIONS FOR HOME SECTION
	//
	$('#btn-home').click(function(event) {
		homeCalc(this);
		return false;
	});
	

	function homeCalc() {
		var home_type 	= $('#home_type').val();
		var num_people	= ( $('#num_people').val() > 10 ) ? 10 : $('#num_people').val();
		var heat_type	= $('#heat_type').val();
		var state 		= $('#fp_state').val();

		if (home_type != '' && heat_type != '' && state != '' && !isblank(num_people) && num_people != '0') {$.getScript('http://www.livecooler.org/handlers/homeFootprintSOL/'+state+'/'+home_type+'/'+heat_type+'/'+num_people, function() {
				var h_range	= [13200, 17600, 24200, 44000, 88000, 132000];
				var step1 	= mWH * weighting;
				var step2 	= lbs * step1;
				var step3 	= emitted + step2;
				var step4 	= Math.ceil(weight * step3);
				var num	  	= 4;
				var text  	= '';
				ITEM_ID		= '13';
				COST		= cost['home4'];
				DESC		= desc['home4'];
				
				if (step4 <= h_range[0]) {
					num 	= 1;
					COST	= cost['home1'];
					ITEM_ID	= '10';
					DESC	= desc['home1'];
				} else if (step4 > h_range[0] && step4 <= h_range[1]) {
					num 	= 2;
					COST	= cost['home2'];
					ITEM_ID	= '11';
					DESC 	= desc['home2'];
				} else if (step4 > h_range[1] && step4 <= h_range[2]) {
					num 	= 3;
					COST	= cost['home3'];
					ITEM_ID	= '12';
					DESC 	= desc['home3'];
				} else if (step4 > h_range[3] && step4 <= h_range[4]) {
					QTY		= 2;
				} else if (step4 > h_range[4] && step4 <= h_range[5]) {
					QTY		= 3;
				} else {
					QTY		= 4;
				}
				
				$('.offset-item img').attr('src', '/images/home' + num + '.gif');
				$('.offset-item img + p').remove();
				$('.offset-item img').after(DESC);
				
				$('.offset-item p strong').append(' x ' + QTY);							
				$('.offset-item p.price span').html('$' + COST*QTY);
				$('.offset-item p.price a').attr('href', 'http://www.livecooler.org/cart/add/' + ITEM_ID + '/');
				
				// $('table.recommend').show();
				$('div.recommended').show();
			});
		} else {
			alert('Please make sure you\'ve filled out the form correctly. Make sure the number of people isn\'t set to 0 or blank.');
		}
	}

	
	
	// 
	// CALCULATIONS FOR CART TOTAL
	//
	function total_cart(kind) {
		var total_offset	= 0;
		var total_cost		= 0;
		var elem			= (kind == 'cart') ? $('table#cart tr') : $('table#order-summary tr');
		
		elem.each( function( i,n ) {
			if ($(this).attr('id')) {
				var id 			= $(this).attr('id').substr(5);
				var qty			= 0;
				var lbs			= 0;
				var cost		= 0;
				var id_cost		= 0;
				var id_lbs		= 0;
				
				if ( $("#qty" + id).attr("value") ) {
					qty = $("#qty" + id).attr("value") * 1;
				}
				
				if ( $("#item_lbs" + id).attr("value") ) {
					lbs = $("#item_lbs" + id).attr("value") * 1;
				}
				
				if ( $("#cost" + id).attr("value") ) {
					cost = $("#item_cost" + id).attr("value") * 1;
				}
				
				id_lbs			= qty * lbs;
				id_cost			= qty * cost;
				total_offset	+= id_lbs;
				total_cost		+= id_cost;
				
				$("#lbs" + id).html(addCommas(id_lbs.toFixed(0)));
				$("#cost" + id).attr("value", id_cost.toFixed(2));
				$("#cost_cell" + id + " strong").html("$" + id_cost.toFixed(2));
			}
		});
		
		$("#total_lbs").html(addCommas(total_offset.toFixed(0)));
		$("#total strong").html("$" + total_cost.toFixed(2));
	}

	
	// Convert number into tons
	function convert(num) {
		return num / 2000;
	}
	
	
	// This function formats numbers by adding commas
	function addCommas(nStr, prefix) {
	    var prefix = prefix || '';
	    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 prefix + x1 + x2;
	}
	
	
	//
	// CHECKOUT
	//
	
	// Disable/enable shipping address
	$('#ship_address_same').bind('click', function(event) {
		if ($(this).attr('checked')) {
			$('#ship_address1').attr({disabled: 'disabled'}).removeClass('required');
			$('#ship_address2').attr({disabled: 'disabled'}).removeClass('required');
			$('#ship_city').attr({disabled: 'disabled'}).removeClass('required');
			$('#ship_state').attr({disabled: 'disabled'}).removeClass('required');
			$('#ship_postal_code').attr({disabled: 'disabled'}).removeClass('required');
		} else {
			$('#ship_address1').attr({disabled: ''}).addClass('required');
			$('#ship_address2').attr({disabled: ''}).addClass('required');
			$('#ship_city').attr({disabled: ''}).addClass('required');
			$('#ship_state').attr({disabled: ''}).addClass('required');
			$('#ship_postal_code').attr({disabled: ''}).addClass('required');
		}
	});
	
	
	// Disable/enable credit card info
	$('input[@name=card_type]').bind('click', function(event) {
		if (this.id == 'card_type5') {
			$('#card_number').attr({disabled: 'disabled'});
			$('#cvv2_number').attr({disabled: 'disabled'});
			$('select[@name=expire_month]').attr({disabled: 'disabled'});
			$('select[@name=expire_year]').attr({disabled: 'disabled'});
		} else {
			$('#card_number').attr({disabled: ''});
			$('#cvv2_number').attr({disabled: ''});
			$('select[@name=expire_month]').attr({disabled: ''});
			$('select[@name=expire_year]').attr({disabled: ''});
		}
	});
	
	
	// Redirect form processing
	$('#purchase').click(function(event) {
		if ($('#card_type5').attr('checked')) {$('#checkout_type').val('Express');} else {$('#checkout_type').val('Direct');}
	});
	
	
	//	Show/hide login reg form
	$("input#loginreg_login").click( function(event) {
		$("input#password_confirm").parents("tr").hide();
		$("input#email").parents("tr").hide();
	});
	
	
	//	Show/hide login reg form
	$("input#loginreg_register").click( function(event) {
		$("input#password_confirm").parents("tr").show();
		$("input#email").parents("tr").show();
	});
	
	
	// Validate an email address
	function checkmail(e) {
		var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/i;
		return emailfilter.test(e);
	}
	
	
	// Check to see if a field is blank. Spaces, newlines and tabs count as blanks
	function isblank(s) {
	    for (var i = 0; i < s.length; i++) {
	        var c = s.charAt(i);
	        if ((c != ' ') && (c != '\n') && (c != '\t'))
	            return false;
	    }
	    return true;
	}
	
	
	// Validate login form
	$('#login-submit').click(function() {
		var fields 	= [];
		
		$('#login-error').hide();
		
		$('td.login input.required').each(function(i) {
			$(this).css({background: "#fff"});
			$('label[@for='+this.id+']').css({color: "#333"});
			
			if ((this.value == null) || (this.value == '') || isblank(this.value)) {fields.push(this);}
		});
		
		if (fields.length == 0) return true;
		
		$(fields).each(function(i) {
			$(this).css({background: "#fdd"});
			$('label[@for='+this.id+']').css({color: "#f00"});
		});
		
		$('#login-error').empty().html('Please fill out the field(s) highlighted below.').show();
		
		return false;
	});
	
	
	// Validate register form
	$('#register-submit').click(function() {
		var fields 	= [];
		var msg		= '';
		
		$('#register-error').hide();
		
		$('td.register input.required').each(function(i) {
			$(this).css({background: "#fff"});
			$('label[@for='+this.id+']').css({color: "#333"});
			
			switch (this.name) {
				case 'email' :
					if ( !checkmail(this.value)) {
						fields.push(this);
						msg = msg + '<p>Your email address is not properly formatted.</p>';
					}
					break;
				default :
					if ((this.value == null) || (this.value == '') || isblank(this.value)) {
						fields.push(this);
						msg = msg + '<p>The '+ this.name +' field was left blank.</p>';
					}
			}
		});
		
		if ($('#password').val() != $('#password_confirm').val()) {
			fields.push($('#password'));
			fields.push($('#password_confirm'));
			msg = msg + '<p>Your passwords don\'t match.</p>';
		}
		
		if (fields.length == 0) return true;
		
		$(fields).each(function(i) {
			$(this).css({background: "#fdd"});
			$('label[@for='+this.id+']').css({color: "#f00"});
		});
		
		$('#register-error').empty().html(msg).show();
		
		return false;
	});
	
	
	// Validate info form
	$('#verify-submit').click(function() {
		var fields	= [];
		
		$('#verify-error').hide();
		
		$('#checkout-table td .required').each(function(i) {
			$(this).css({background: "#fff"});
			$('label[@for='+this.id+']').css({color: "#333"});
			
			if (this.id == 'state' && this.value == 'default') {fields.push(this);}
			
			if ((this.value == null) || (this.value == '') || isblank(this.value)) {fields.push(this);}
		});
		
		if (fields.length == 0) return true;
		
		$(fields).each(function(i) {
			$(this).css({background: "#fdd"});
			//$('label[@for='+this.id+']').css({color: "#f00"});
		});
		
		$('#verify-error').empty().html('Please fill out the field(s) highlighted below.').show();
		
		return false;
	});
	
	
	// Validate payment form
	$('#purchase').click(function() {
		var fields	= [];
		var msg		= '';
		var method	= false;
		
		$('#pay-error').hide();
		
		// PayPal selected?
		if ( $('#card_type5').attr('checked') ) {
			$('input[name=checkout_type]').attr('value', 'Express');

			if ( ! $('#ship_address_same').attr('checked') ) {
				$('#payment-form .required[@name^="ship_"]').each(function(i) {
					if ( (this.value == null) || (this.value == '') || isblank(this.value) || (this.value == 'default') ) {
						fields.push(this);
						msg = msg + '<p>The '+ this.name +' field was left blank.</p>';
					}
				});
			}
		} else { // DirectPayment
			$('input[name=checkout_type]').attr('value', 'Direct');
		
			$('#payment-form .required').each(function(i) {
				$(this).css({background: "#fff"});
				$('label[@for='+this.id+']').css({color: "#333"});
			
				switch (this.name) {
					case 'ship_address_same' :
						if ( ! $(this).attr('checked') && $('#ship_address1').val() == '' ) {
							fields.push(this);
							msg = msg + '<p>Shipping address information wasn\'t given.</p>';
						}
						break;
					case 'cvv2_number' :
						if ( (this.value == null) || (this.value == '') || isblank(this.value) ) {
							fields.push(this);
							msg = msg + '<p>The security code isn\'t formatted properly.</p>';
						}
						break;
					case 'card_number' :
						this.value = this.value.replace(/-/g, '');
						if ( this.value.length < 13 || this.value.length > 16 ) {
							fields.push(this);
							msg = msg + '<p>The credit card number isn\'t formatted properly.</p>';
						}
						break;
					case 'ship_state' :
						if ( ! $('#ship_address_same').attr('checked') && this.value == 'default' ) {
							fields.push(this);
							msg = msg + '<p>No shipping state was specified.</p>';
						}
					default :
						if ( (this.value == null) || (this.value == '') || isblank(this.value) ) {
							fields.push(this);
							msg = msg + '<p>The '+ this.name +' field was left blank.</p>';
						}
				}
			});
			
			$('input[@name=card_type]').each(function(index) {
				if ( this.checked) method = true;
			});

			if ( ! method) {
				msg = msg + '<p>No payment method was selected.</p>';
			}
		}
		
		if ( fields.length == 0 ) return true;
		
		$(fields).each(function(i) {
			$(this).css({background: "#fdd"});
			//$('label[@for='+this.id+']').css({color: "#f00"});
		});
		
		$('#pay-error').empty().html(msg).show();
		
		return false;
	});

});