
/**
 * CLSOE ANY OPEN CALCULATOR WINDOW
 */
function calc_close() {
	$('#calc_bg').hide();
	$('#calc_modal').hide();
}

function calc_show(calc) {
	if (typeof calc != 'undefined') {
		$('#calc_modal #' + calc).show();
	}
	
	var height = $(window).height();
	var scrollTop = $(window).scrollTop();
	scrollTop = (scrollTop = scrollTop+((height - $('#calc_modal').height())/2)-50) < 5 ? 10 : scrollTop;
	
	$('#calc_bg').show();
	$('#calc_modal').css({marginTop:scrollTop, paddingBottom:'71px', background:'#FAA61A url(/calc/calc_bottom_blank.jpg) no-repeat right bottom'}).show();
}

function calc_load(file, callback) {

	$("#calc_modal").html('<div class="margin" style="height:none;">Loading page, please wait...</div>');
	
	calc_show();
	$.ajax({
	  url: "calc/"+file,
	  cache: false,
	  success: function(html){
	    $("#calc_modal").html(html);
	    if (typeof callback === 'function') {
			callback();
		}
	  }
	});
}



// business energy proposal
function calc_business() {
	calc_load('inc_calc_business.html',function() {
		// make all inputs numberic only that have the class ".numeric"
		$(".numbers").numeric();
		pageTracker._trackPageview('/calculator-business-proposal');
		var options = {
	        //target: '#output1',   // target element(s) to be updated with server response 
	        beforeSubmit:function(e) {
	        	// check if mandatory fields are filled-in
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if(this.value === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	    
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#calc_business_form').html(e+'<br><br><input type="button" class="button" value="close" onclick="calc_close();" />');
	        },
	 
	        url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		// 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 	
	    // bind form using 'ajaxForm' 
	    $('#calc_business_form').ajaxForm(options);
		$('#calc_modal').css({width:'800px', height:'500px', paddingBottom:'71px'});
		$('#calc_modal .margin').css({overflow:'auto', height:'430px'});
		calc_show('calc_business');
	});
}


/** RESIDENTION APPLICATION FORM */
function form_apply_residential() {
	calc_load('inc_apply_residential.html',function() {
		pageTracker._trackPageview('/form-apply-residential');
		var options = { 
	        beforeSubmit:function(e) {
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if($(this.name).val() === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	    
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#residential_form').html(e+'<br><br><input type="button" class="button" value="close" onclick="calc_close();" />');
	        },
	        
	 		url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		// 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 
	    // bind form using 'ajaxForm' 
	    $('#residential_form').ajaxForm(options); 
		$('#calc_modal').css({overflow:'none', height:'500px', width:'688px'});
		
		calc_show('calc_residential');
	});
}


/**  business energy enqiery form (not calculator)  **/
function form_apply_commercial() {
	calc_load('inc_apply_commercial.html',function() {
		pageTracker._trackPageview('/form-apply-commercial');
		var options = { 
	        beforeSubmit:function(e) {
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if($(this.name).val() === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	    
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#residential_form').html(e+'<br><br><input type="button" class="button" value="close" onclick="calc_close();" />');
	        },
	        
	 		url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		// 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 
	    // bind form using 'ajaxForm' 
	    $('#residential_form').ajaxForm(options); 
		$('#calc_modal').css({overflow:'none', height:'500px', width:'688px'});
		
		calc_show('apply_commercial');
	});
}


/** OPEN CONTACT FORM **/
function contactForm() {
	calc_load('form_contact.html',function() {
		pageTracker._trackPageview('/form-contact');
		var options = { 
	        beforeSubmit:function(e) {
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if(this.value === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#contact_form').html(e);
	        },
	 		url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		 // 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 
	    // bind form using 'ajaxForm' 
	    $('#contact_form').ajaxForm(options); 
		$('#calc_modal').css({paddingBottom:0, width:'600px',height:'390px', marginLeft:'-305px', fontSize:'12px'});
		$('#calc_modal .margin').css({height:'376px', margin:'20px',width:'530px'});
	});
}


function modal(url) {
	$('#calc_modal').css({paddingBottom:0, width:'850px',height:'540px', marginLeft:'-425px', fontSize:'12px', marginTop:'50px'});
	$('#calc_modal .margin').css({height:'416px', margin:'20px',width:'810px'});
	$("#calc_modal").html('<div class="margin" style="height:none;">Loading...</div>');
	
	//window.scrollTo(0);
	
	calc_show();
	
	$.ajax({
	  url: url,
	  cache: false,
	  success: function(html){
	    $('#calc_modal .margin').html(html);
	    calc_show();
	  }
	});
}

function modal_close() {
	$('#calc_bg').hide();
	$('#calc_modal').hide();
}

function order_lpg() {
	pageTracker._trackPageview('/form-order-lpg');
	$('#calc_modal').css({height:'500px',width:'650px'});
	$('#calc_modal').html(['<div style="padding:10px; height:430px"><div class="bottom">Nova LPG Online Order Form</div>',
		'<iframe width="100%" height="100%" src="/calc/lpg_order_form.php" align="left"',
        ' scrolling="auto" marginheight="0" marginwidth="0" frameborder="0"></frame>',
        '</div>'].join(''));
	calc_show();
}

function apply_lpg() {
	pageTracker._trackPageview('/form-apply-lpg');
	calc_load('inc_apply_lpg.html',function() {
		var options = { 
	        beforeSubmit:function(e) {
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if(this.value === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#lpg_form').html(e);
	        },
	        
	 		url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		// 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 
	    // bind form using 'ajaxForm' 
	    $('#lpg_form').ajaxForm(options); 
		$('#calc_modal').css({overflow:'none', width:'688px', paddingBottom:'71px', background:'#FAA61A url(calc/calc_bottom_blank.jpg) no-repeat right bottom'});
		
		calc_show('apply_lpg');
	});
}

function apply_lpg_c() {
	calc_load('inc_apply_lpg_c.html', function() {
		pageTracker._trackPageview('/form-apply-lpg-commercial');
		var options = { 
	        beforeSubmit:function(e) {
	        	var result = true;
	        	$('#calc_modal .mand').each(function() {
	        		if(this.value === '') {
		        		result = false;
		        		return false;
	        		}
	        	});
	        	
	        	if (!result) {
					alert('Please fill-in every field marked with *');
				}
	        	return result;  
	        },
	        
	        success: function(e) {       			
	        	$('#lpg_form').html(e);
	        },
	        
	 		url:       '/calc/api.php',      // override for form's 'action' attribute 
	        type:      'post'        		// 'get' or 'post', override for form's 'method' attribute 
	    }; 
	 
	    // bind form using 'ajaxForm' 
	    $('#lpg_form').ajaxForm(options); 
		$('#calc_modal').css({overflow:'none', width:'688px', paddingBottom:'71px', background:'#FAA61A url(calc/calc_bottom_blank.jpg) no-repeat right bottom'});
		
		calc_show('apply_lpg_c');
	});
}



/**
 *  Diary Solar Calculator for dairy farms 
 */
function diary_solar() {
	calc_load('inc_calc_solar_diary.html', function() {
		pageTracker._trackPageview('/calculator-solar-dairy');
		$('.input1').val(10000);
		$('.input2').val(17.5);
		
		var calculate = function() {
			var kw = $('.input1').val() / $('.input2').val();
			
			var annual_e_costs = $('.input1').val() / 3;
			$('.c1').html(utils.formatCurrency(annual_e_costs));
			
			var offset_annual = 60 * $('.input2').val();
			var offset_month = offset_annual / 12;
			$('.c2').html(utils.formatCurrency(offset_annual));
			$('.c3').html(utils.formatCurrency(offset_month));
			
			var savings_monthly = 128.33-offset_month;
			$('.c4').html(utils.formatCurrency(savings_monthly));
			$('.c5').html(utils.formatCurrency(savings_monthly * 60));
			$('.c6').html(utils.formatCurrency(7700-(savings_monthly * 60)));
			$('.c7').html(utils.formatCurrency(offset_annual*10));
		};
		
		calculate();
		$('#calc_solar').find('.input1,.input2').bind('keyup', calculate);
	});
}

/** Residential Solar calculator */
var calc_solar = function () {
	var id = '';
	var box = '';
	var input1 = '';
	var input2 = '';
	var c1 = '';
	var c2 = '';
	var c3 = '';
	var c4 = '';
	var c5 = '';
	var c6 = '';
	var c7 = '';
	
	var start_annual = 200;
	var start_number = 2;
	var water = 0.35;
	var solar = 0.70;
	
	this.setAnnual = function(val) { start_annual = val; };
	this.setNumber = function(val) { start_number = val; };
	this.setWaterFactor = function(val) { water = val; };
	this.setSolarFactor = function (val) { solar = val; };
	
	
	this.init = function(id) {
		id = id;
		box = $('#'+id);
		
		$(".input1, .input2").numeric();
		
		input1 = box.find('.input1');
		input2 = box.find('.input2');
		
		input1.val(start_annual);
		input2.val(start_number);
		
		c1 = box.find('.c1');
		c2 = box.find('.c2');
		c3 = box.find('.c3');
		c4 = box.find('.c4');
		c5 = box.find('.c5');
		c6 = box.find('.c6');
		c7 = box.find('.c7');
		
		box.find('.input1,.input2').bind('keyup', this.calculate);
		
		this.calculate();
	};

	this.calculate = function (e) {
		var unitcost = input2.val() > 4 ? 120 : input2.val() > 2 ? 97 : 89;
		var annual = input1.val()*12;
		var spent = Math.round(annual*water);
		var saved = Math.round(spent*solar);
		var monthly = Math.round(saved / 12);
		var ucosts = (unitcost);
		var monthlypay = ucosts - monthly;
		var withgrant = monthlypay - 17;
		
		c1.html(utils.formatCurrency(annual));
		c2.html(utils.formatCurrency(spent));
		c3.html(utils.formatCurrency(saved));
		c4.html(utils.formatCurrency(monthly));
		c5.html(utils.formatCurrency(ucosts));
		c6.html(utils.formatCurrency(monthlypay));
		c7.html(utils.formatCurrency(withgrant));
	};
};


/** basic solar calculator setup **/
function calc1() {
	var calc = new calc_solar();
	calc.setWaterFactor(0.40);
	calc.setSolarFactor(0.75);
	calc.setAnnual(250);
	calc.setNumber(3);
	calc.init('calc_solar');
	$('#calc_modal').css({width:'688px', height:'540px', paddingBottom:'71px'});
	
	calc_load('inc_calc_solar.html',function() {
		pageTracker._trackPageview('/calculator-solar');
		calc.init('calc_solar');
		calc_show('calc_solar');
	});
}


/**
 * Residential Costs compare calculator
 * 
 * Basic workflow is 
 * - load xml
 * - show calc
 * - let user select region, plan etc,
 * - do some math and torture the DOM tree to display the results
 * 
 */
var class_calc_costs = {
	region: false,
	e_only: false,
	daynight: false,
	controlled: false,
	plan: false,
	
	start: function(){
		this.region = false;
		this.e_only = false;
		this.daynight = false;
		this.controlled = false;
		this.plan = false;
		
		calc_load('inc_bill_calculator2.php', function(){
			pageTracker._trackPageview('/calculator-energy-costs');
			$('#calc_modal').css({
				paddingBottom: 0,
				width: '900px',
				height: '540px',
				marginLeft: '-450px',
				fontSize: '12px'
			});
			$('#calc_modal .margin').css({
				height: '416px',
				margin: '20px',
				width: '860px',
				marginBottom: '0'
			});
			
			$('#tabs').click(function(ev){
				costs.showTable($(ev.target).attr('tab'));
			});
		});
	},
	
	
	/** first user selects the regions */
	setRegion: function(r) {
		if (!r) { return; }
		this.region = plans[r];
		$('#t1_tr_next').hide();
		
		// if an electricity only option exists
		if (typeof this.region.e_only_fix != 'undefined') {
			this.e_only = true;
			$('#tr_energy_supply').show();
		}
		// otherwise skip this option and set selection to no
		else {
			$('#tr_energy_supply').hide();
			this.setSupply('n');
		}
	},
	
	
	setSupply: function(v) {
		// if supply set to Electricity only, hide all gas options
		if (v === 'y') {
			this.e_only = true;
			$('.gas,.gastr,#box_gas').addClass('none');
			
		} else {
			$('#box_gas,.gastr,.gas').removeClass('none');
			this.e_only = false;
		}
		
		// if region has a day/night option
		if ((this.e_only && typeof this.region.e_only_day != 'undefined') || (!this.e_only && typeof this.region.e_day != 'undefined')) {
			$('#t1_tr_next').hide();
			$('#tr_daynight').show();
		} else {
			$('#tr_daynight').hide();
			this.setDayNight('n');
		}
	},
	
	
	setDayNight: function(v){
		this.daynight = (v === 'y') ? true : false;
		
		if(this.daynight) {
			$('.trdaynight,.daynight, .twoplans').removeClass('none');
			$('.daynight_h').addClass('hidden');
			$('.t2_col4').html('<strong>Nova Day&Night</strong><br /> ($ pa)');
			
			$('#label_e1_units').html('Units used daytime');
			$('#label_e1_vp').html('Variable Price daytime');
			
			$('#label_e2_units').html('Units used nighttime');
			$('#label_e2_vp').html('Variable Price nighttime');
			
			$('#label_e_1').html('Annual Electricity Estimate');
			$('#label_e_2').html('Annual Electricity Estimate Night');
			
			$('#tr_e2_units').show();
			$('#tr_e2_vp').show();
			
			this.setControlled('n');
			
		} else {
			$('.daynight, .trdaynight, .twoplans').addClass('none');
			$('.daynight_h').removeClass('hidden');
			$('.t2_col4').html('<strong>Nova Anytime</strong><br /> ($ pa)');
			
			$('#tr_e2_units').hide();
			$('#tr_e2_vp').hide();
			
			if((this.e_only && typeof this.region.e_only_controlled != 'undefined') || 
				(!this.e_only && typeof this.region.e_controlled != 'undefined')) {
				$('#tr_controlled').show();
				$('#t1_tr_next').hide();
			} else {
				$('#tr_controlled').hide();
				this.setControlled('n');
			}
		}
	},
	
	
	setControlled: function (v) {
		this.controlled = (v === 'y') ? true : false;
		
		// if a controlled options exists for the selected region
		if(this.controlled) {
			this.controlled = true;
			
			$('.trdaynight, .daynight, .twoplans').removeClass('none');
			$('.daynight_h').addClass('hidden');
			$('.t2_col4').html('<strong>Nova Day&Night</strong><br /> ($ pa)');
			
			$('#label_e1_units').html('Units used during invoice period on controlled rate');
			$('#label_e1_vp').html('Variable Price - Controlled');
			
			$('#label_e2_units').html('Units used during invoice period on uncontrolled (anytime) rate');
			$('#label_e2_vp').html('Variable Price - Uncontrolled (Anytime)');
			
			$('#label_e_2').html('Annual Electricity Estimate Uncontrolled (Anytime)');
			$('#label_e_1').html('Annual Electricity Estimate Controlled');
			
			$('#tr_e2_units').show();
			$('#tr_e2_vp').show();
			
		} else {
			this.controlled = false;
		}
	
		//$('#t1_tr_next').fadeIn();
		this.showTable("2");
	},
	
	
	calculate: function() {
		// CHECK INPUTS 
		var result = true;
		$((this.e_only ? '#calc_costs_t1 .mand' : '#calc_costs_t1 .mand, #calc_costs_t1 .mandg')).each(function(){
			if (this.value === '') {
				result = false;
				return false;
			}
		});
		
		if (!result) {
			alert('Please fill-in all input fields to proceed.');
			return;
		}
		
		//     COLLECTION INPUT PARAMERS 
		var t1_period = $('#t1_period').val() - 1;
		var t1_invoiced_days = Number($('#t1_invoice_days').val());
		var t1_df_discount = Number($('#t1_df_discount').val()); // dual fuel discount
		var t1_pp_discount = Number($('#t1_pp_discount').val());
		var t1_g_used = Number($('#t1_g_used').val());
		var t1_g_vp = Number($('#t1_g_vp').val());
		var t1_g_fp = Number($('#t1_g_fp').val());
		
		var t1_e_vp = Number($('#t1_e_vp').val());
		var t1_e_vp_2 = Number($('#t1_e_vp_2').val());
		var t1_e_fp = Number($('#t1_e_fp').val());
		var t1_e_used = Number($('#t1_e_used').val());
		var t1_e_used_2 = Number($('#t1_e_used_2').val());
		
		
		this.showTable(3);
		
		// CALCULATE ESTIMATES
		// multiplier and days for estimate calculations
		var periods = [[20.87, 30], // jan-feb
			[17.72, 30.5], 			// mar - apr
			[9.19, 30], 			// may - jun
			[7.7, 30.5], 			// jul - aug
			[10.66, 30.5], 			// sep - oct
			[16.7, 30.5] 			// nov - dec
		];
		
		this.t2_g_est = Math.round(((periods[t1_period][0] * periods[t1_period][1]) / t1_invoiced_days) * t1_g_used);
		this.t2_e_est = Math.round(((periods[t1_period][0] * periods[t1_period][1]) / t1_invoiced_days) * t1_e_used);
		this.t2_e_est_2 = Math.round(((periods[t1_period][0] * periods[t1_period][1]) / t1_invoiced_days) * t1_e_used_2);
		
		this.t2_g_var_curr = (this.t2_g_est * t1_g_vp / 100);
		this.t2_g_fix_curr = t1_g_fp * 3.65;
		this.t2_g_annual_curr = this.t2_g_var_curr + this.t2_g_fix_curr;
		
		this.t2_e_var_curr = (this.t2_e_est * t1_e_vp / 100);
		this.t2_e_var_curr_2 = (this.t2_e_est_2 * t1_e_vp_2/100);
		this.t2_e_fix_curr = t1_e_fp * 3.65;
		this.t2_e_annual_curr = this.t2_e_var_curr + this.t2_e_var_curr_2 + this.t2_e_fix_curr;
		
		// if its a electricity split plan add second e-calculation
		if (this.daynight || this.controlled) {
			$('.col2').addClass('none');
		} else {
			$('.col2').removeClass('none');
		}
		
		if(this.e_only) {
			this.t2_g_annual_curr = 0;
		}
		
		this.t2_total_curr = this.t2_g_annual_curr + this.t2_e_annual_curr;
		this.t2_gst_curr = this.t2_total_curr * 0.125;
		this.t2_total_curr += this.t2_gst_curr;
		this.t2_disc_curr = (this.t2_total_curr / 100) * t1_pp_discount;
		this.df_discount_total = t1_df_discount ? (t1_df_discount / 100) * 365 : 0;
		this.t2_discounted_curr = this.t2_total_curr - this.t2_disc_curr - this.df_discount_total;
		
		// current column
		$('#t2_g_annual_vol').html(this.t2_g_est);
		$('#t2_g_annual_curr').html(utils.formatCurrency(this.t2_g_var_curr));
		$('#t2_g_annual_fix_curr').html(utils.formatCurrency(this.t2_g_fix_curr));
	
		$('#t2_e_annual_vol').html(this.t2_e_est);
		$('#t2_e_annual_curr').html(utils.formatCurrency(this.t2_e_var_curr));
		$('#t2_e_annual_curr_2').html(utils.formatCurrency(this.t2_e_var_curr_2));
		$('#t2_e_annual_vol_2').html(this.t2_e_est_2);
		$('#t2_e_annual_fix_curr').html(utils.formatCurrency(this.t2_e_fix_curr));
		
		
		$('#t2_total_curr').html(utils.formatCurrency(this.t2_total_curr));
		$('#t2_gst_curr').html(utils.formatCurrency(this.t2_gst_curr));
		$('#t2_disc_pp_curr').html('-' + (utils.formatCurrency(Math.abs(this.t2_disc_curr))));
		$('#t2_disc_df_curr').html('-' + (utils.formatCurrency(Math.abs(this.df_discount_total))));
		$('#t2_discounted_curr').html(utils.formatCurrency(this.t2_discounted_curr));

		
		this.types = ['Daily Saver', 'Everyday', 'Volume Saver'];
		
		// there is always one plan
		calc1 = new this.calculator(this);
			calc1.e_fix = this.region['e_'+(this.e_only ? 'only_' : '')+'fix'];
			calc1.e_plan = this.region['e_'+(this.e_only ? 'only_' : '')+'anytime'];
		
		
		// scroll to bottom
		$("#calc_modal .margin ").attr({
			scrollTop: $("#calc_modal .margin ").attr("scrollHeight")
		});
		
		// setup calculations - correct
		if (this.controlled) {
			calc1.e_plan = this.region['e_' + (this.e_only ? 'only_' : '') + 'controlled'];
			calc1.e_plan_2 = this.region['e_' + (this.e_only ? 'only_' : '') + 'anytime'];
			calc1.e_fix = this.region['e_' + (this.e_only ? 'only_' : '') + 'fix'];
			calc1.calculate();
			this.displayCol(this, 1, calc1, '<b>Nova Controlled</b> <br>($ pa)');

		// day night plan
		} else if (this.daynight) {
			calc1.e_plan = this.region['e_' + (this.e_only ? 'only_' : '') + 'day'];
			calc1.e_plan_2 = this.region['e_' + (this.e_only ? 'only_' : '') + 'night'];
			calc1.e_fix = this.region['e_' + (this.e_only ? 'only_' : '') + 'fix'];
			calc1.calculate();
			
			this.displayCol(this, 1, calc1, '<b>Nova Day/Night</b> <br>($ pa)');
			$('#label_e_1').html('Annual Electricity Estimate Day');
			$('#label_e_2').html('Annual Electricity Estimate Night');
		
		// anytime
		} else {
			calc1.calculate();
			this.displayCol(this, 1, calc1, '<b>Nova Anytime</b> <br>($ pa)');
			
			$('#label_e_1').html('Annual Electricity Estimate');
			$('#label_e_2').html('');
			
			// EXCEPTION: some plans do not have a composite option
			var plan_e =  this.region['e_'+(this.e_only ? 'only_' : '')+'composite'];
			
			if(plan_e !== undefined && plan_e[0] != 9) {
				var calc2 = new this.calculator(this);
				calc2.e_fix = this.region['e_'+(this.e_only ? 'only_' : '')+'fix'];
				calc2.e_plan = plan_e;
				calc2.calculate();
				
				this.displayCol(this, 2, calc2, '<b>Nova Composite</b><br /> <span class="smalltext">($ pa)</span>');
				$('.col2').removeClass('none');
				
			} else {
				$('.col2').addClass('none');
			}
		}
	},
	
		
	/** 
	 * Calculator function for the costs compare calculator
	 */
	calculator:function(parent) {
		this.e_plan_2 = false;
		this.e_fix = false;
		this.g_plan = parent.region.g_var;
		this.g_fix = parent.region.g_fix;
		
		this.g_total_var = [0,0,0];
		this.g_total_fix = [0,0,0];
		this.g_subtotals = [0,0,0];
		this.g_gst = [0,0,0];
		this.g_totals = [0,0,0];
		this.g_best = 0;
		
		this.e_total_var = [0,0,0];
		this.e_total_var_2 = [0,0,0];
		this.e_total_fix = [0,0,0];
		this.e_subtotals = [0,0,0];
		this.e_subtotals_2 = [0,0,0];
		this.e_gst = [0,0,0];
		this.e_totals = [0,0,0];
		this.e_best = 0;
		
		var _this = this;
		var calc = parent;
		
		this.calculate = function() {
			for(e in _this.g_plan) {
				if (!calc.e_only) {
					_this.g_total_fix[e] = _this.g_fix[e] * 365;
					_this.g_total_var[e] = _this.g_plan[e] * parent.t2_g_est;
					_this.g_subtotals[e] = _this.g_total_var[e] + _this.g_total_fix[e];
					_this.g_gst[e] = _this.g_subtotals[e] * 0.125;
					_this.g_totals[e] = _this.g_subtotals[e] + _this.g_gst[e];
				}
				
				_this.e_total_var[e] = _this.e_plan[e] * parent.t2_e_est;
				_this.e_total_fix[e] = _this.e_fix[e] * 365;
				
				if(_this.e_plan_2) {
					_this.e_total_var_2[e] = _this.e_plan_2[e] * parent.t2_e_est_2;
					_this.e_subtotals[e] = _this.e_total_var_2[e] + _this.e_total_var[e] + _this.e_total_fix[e];
					_this.e_gst[e] = _this.e_subtotals[e] * 0.125;
					_this.e_totals[e] = _this.e_subtotals[e] + _this.e_gst[e];
				}
				
				_this.e_subtotals[e] = _this.e_total_var[e] + _this.e_total_var_2[e] + _this.e_total_fix[e];
				_this.e_gst[e] = _this.e_subtotals[e] * 0.125;
				_this.e_totals[e] = _this.e_subtotals[e] + _this.e_gst[e];
			}
			
			// determine best plan
			this.g_totals_order = this.g_totals.slice();
			this.g_totals_order.sort(numOrdA);
			this.g_best = $.inArray(this.g_totals_order[0],  this.g_totals);
			
			this.e_totals_order = this.e_totals.slice();
			this.e_totals_order.sort(numOrdA);
			this.e_best = $.inArray(this.e_totals_order[0], this.e_totals);
			
			
			this.g_var 		= this.g_total_var[this.g_best];
			this.g_fix 		= this.g_total_fix[this.g_best];
			this.e_1 	= this.e_total_var[this.e_best];
			this.e_2 	= this.e_total_var_2[this.e_best];
			this.e_total = this.e_1 + this.e_2;
			this.e_fix 	= this.e_total_fix[this.e_best];
			this.subtotal = this.e_total + this.g_var + this.g_fix + this.e_fix;
			this.gst 	= this.subtotal * 0.125;
			this.total 	=   this.subtotal + this.gst;
		}
	},
	
	
	displayCol:function(parent, col, calc, title) {
		if(typeof title != 'undefined') $('#label_col'+col).html(title);
		var savings = calc.total - parent.t2_discounted_curr;
		var presign = savings < 0 ? '-' : '+';	
		//var e_annual = calc.e_subtotals[calc.e_best];
		
		$('#t2_g_annual_'+col).html(utils.formatCurrency(calc.g_var));
		$('#t2_g_annual_fix_'+col).html(utils.formatCurrency(calc.g_fix));
		$('#t2_e_annual_'+col).html(utils.formatCurrency(calc.e_1));
		$('#t2_e_annual_'+col+'_2').html(utils.formatCurrency(calc.e_2));
		$('#t2_gst_'+col).html(utils.formatCurrency(calc.gst));
		$('#t2_total_'+col).html(utils.formatCurrency(calc.total));
		$('#savings_'+col).html(presign + utils.formatCurrency(Math.abs(savings)));
		$('#t2_discounted_'+col).html(utils.formatCurrency(calc.total));
		$('#t2_e_annual_fix_'+col).html(utils.formatCurrency(calc.e_fix));
		$('#g_annual_best_'+col).html(parent.types[calc.g_best] + '');
		$('#e_annual_best_'+col).html(parent.types[calc.e_best] + '');
	},
	
	
	showTable: function(n){
		for (var i = 0; i <= 2; i++) {
			if ((n - 1) == i) {
				$('#calc_costs_t' + i).show()
				$('.tab' + (i + 1)).addClass('active');
			}
			else {
				$('#calc_costs_t' + i).hide();
				$('.tab' + (i + 1)).removeClass('active');
			}
		}
	}
}


function calc_costscompare() {
	costs = class_calc_costs;
	costs.start();
}


/* helper to sort numbers in arrays */
function numOrdA(a, b){ return (a-b); }
function numOrdD(a, b){ return (b-a); } 


/* jquery helpers */
$.fn.numeric = function(decimal, callback) {
	decimal = decimal || ".";
	callback = typeof callback == "function" ? callback : function(){};
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
				{
					allow = false;
				}
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function() {
			var val = jQuery(this).val();
			if(val != "") {
				var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
				if(!re.exec(val)) 	{
					callback.apply(this);
				}
			}
		}
	);
	return this;
}



/**
 * bootstrap calculators
 * @author flobo bosselmann@gmail.com
 */
$(document).ready(function () {
	$.ajax({
	  url: "/calc/calculators.html",
	  cache: false,
	  success: function(html){
	    $(document.body).append(html);
	    $('#calc_bg').css('opacity',0.7);
	  }
	});
});


