function hideLoader(){ setTimeout(function(){Ext.get('calcLoader').fadeOut({ useDisplay:true, duration: 1 }) }, 500); }

function switchMenu(type){
	var dom=Ext.get('domDiv'), air=Ext.get('airDiv'), hom=Ext.get('homeDiv'), quick=Ext.get('quickDiv');
	var trx=Ext.get('trxLogo');
	var infDiv=Ext.get('homeInfoDiv');
	
	var oldType; var anch=document.location.hash.substr(1), from='t', empty=false;
	var easeOff='easeOut', easeOn='easeOut', dur=.5;
	
	if (!type){	
		oldType=0; dom.setDisplayed(false); air.setDisplayed(false); hom.setDisplayed(false); quick.setDisplayed(false); // if first opened or refreshed
		trx.setDisplayed(false);
		infDiv.setDisplayed(false);
		switch(anch){
			case 'domestic':type=1; break;
			case 'air':type=2; break;
			case 'home':type=3; break;
			case 'quick':type=4; break;
			default: type=999; break;
		}
	}
	else { // if icon was clicked
		if (dom.isVisible()){ oldType=1;
			if (type>oldType) dom.slideOut('l', { useDisplay:true, duration: dur, easing: easeOff  }); 
			if (type<oldType) dom.slideOut('r', { useDisplay:true, duration: dur, easing: easeOff  }); 
		}
		if (air.isVisible()){ oldType=2;
			if (type>oldType) air.slideOut('l', { useDisplay:true, duration: dur, easing: easeOff  });
			if (type<oldType) air.slideOut('r', { useDisplay:true, duration: dur, easing: easeOff  });
			if (type!=oldType) trx.fadeOut({ useDisplay:true, duration: dur*2, easing: easeOff  });
		}
		if (hom.isVisible()){ oldType=3;
			if (type>oldType) hom.slideOut('l', { useDisplay:true, duration: dur, easing: easeOff  }); 
			if (type<oldType) hom.slideOut('r', { useDisplay:true, duration: dur, easing: easeOff  }); 
			if (type!=oldType) infDiv.fadeOut({ useDisplay:true, duration: dur, easing: easeOff  });
		}
		if (quick.isVisible()){ oldType=4;
			if (type>oldType) quick.slideOut('l', { useDisplay:true, duration: dur, easing: easeOff  }); 
			if (type<oldType) quick.slideOut('r', { useDisplay:true, duration: dur, easing: easeOff  }); 
		}
		if (type>oldType) from='r';
		if (type<oldType) from='l';
	}
	if (oldType==type) return false; // if the same icon was clicked
	switch (type) {
		case 1: dom.slideIn(from, { useDisplay:true, duration: dur, easing: easeOn }); break;
		case 2: air.slideIn(from, { useDisplay:true, duration: dur, easing: easeOn }); trx.fadeIn({ useDisplay:true, duration: dur*3, easing: easeOff  }); break;
		case 3: hom.slideIn(from, { useDisplay:true, duration: dur, easing: easeOn }); infDiv.fadeIn({ useDisplay:true, duration: dur*2, easing: easeOff  }); break;
		case 4: quick.slideIn(from, { useDisplay:true, duration: dur, easing: easeOn }); break;
		default:dom.slideIn(from, { useDisplay:true, duration: dur, easing: easeOn }); break;
	}
}

function tabsMark(){
	var tabs=Ext.getBody().query("#calculator .tabs a");
	Ext.get(tabs[0]).removeClass('done'); Ext.get(tabs[1]).removeClass('done'); Ext.get(tabs[2]).removeClass('done'); Ext.get(tabs[3]).removeClass('done');	
	for (var i=0, cartel; cartel=cart[i]; i++){
		if (cartel[1]=='Car' || cartel[1]=='Motorbike' || cartel[1]=='Train' || cartel[1]=='Bus' || cartel[1]=='Taxi') Ext.get(tabs[0]).addClass('done');
		if (cartel[1]=='Air Travel') Ext.get(tabs[1]).addClass('done');
		if (cartel[1]=='Home Energy') Ext.get(tabs[2]).addClass('done');
		if (cartel[1]=='Quick Offset') Ext.get(tabs[3]).addClass('done');
	}
}

function bnShow(show){	 }
function buyOffset(){
	var parcart='';
	for (var i=0, cartel; cartel=cart[i]; i++) parcart+='|'+cartel.join(';');
	Ext.Ajax.request({ url: 'requests/cart.php', params:{ cart:parcart.substr(1), action:'saveCart' },
		success: function(resp){ location.href="https://www.emissionzero.ie/index.php?p=cart"; }
		//success: function(resp){ location.href="index.php?p=cart"; }
	});
}

function saveCart(){
	var parcart='';
	for (var i=0, cartel; cartel=cart[i]; i++) parcart+='|'+cartel.join(';');
	Ext.Ajax.request({ url: 'requests/cart.php', params:{ cart:parcart.substr(1), action:'saveCart' }	});
}

function readCart(){
	Ext.Ajax.request({ url: 'requests/cart.php', params:{ action:'readCart' },
		success: function(resp){ 
			if (resp.responseText.length>0){
				Ext.get('emptySum').hide(); // hide info
				var cArr=resp.responseText.split('|');
				var newCart=Array();
				for (var i=0; i<cArr.length; i++) {
					cartel=cArr[i].split(';');
					totalco2+=parseFloat(cartel[3]);
					newCart.push(cartel);
					// showing panels
					var newBox=new Ext.SumBox({ title:cartel[1], name:cartel[0], html:cartel[2]+'<br>Tonnes of CO<sub>2</sub>: '+cartel[3]+'</p>' });
					Ext.getCmp('calcSumPanel').insert(0,newBox);
					Ext.getCmp('calcSumPanel').doLayout();
					newBox.slide();
				}
				cart=newCart;
				updateCounters();
			}
		}
	});
}


function removeElement(id){
	var newCart=Array();
	for (var i=0, cartel; cartel=cart[i]; i++) if (cartel[0]==id) totalco2-=cartel[3]; else newCart.push(cartel);
	cart=newCart;	
	updateCounters();
	saveCart();
}

function addElement(type,description,co2){ // cart array of selected elements
	if (checkLimit(co2)){
		var cost=co2*carbonCost;
		var id='el_'+new Date().getTime();	
		var ta=[id, type,description,co2.toFixed(2),cost.toFixed(2)];
		cart.push(ta)
		updateCounters();
		saveCart();
		return id;
	}
	else Ext.Msg.show({ title:'Warning', msg: 'You cannot offset more than 100 tonnes of CO<sub>2</sub>.', buttons: Ext.Msg.OK, icon: Ext.MessageBox.WARNING });
}


function updateCounters(){
	var co2=0, cash=0;
	for (var i=0; cart[i]; i++){ co2+=parseFloat(cart[i][3]); cash+=parseFloat(cart[i][4]); }
	totalco2=co2; 
	Ext.getCmp('totalco2').setValue(numberFormat(co2,2));
	Ext.getCmp('totalCash').setValue('€'+numberFormat(cash,2));
	tabsMark()
	bnShow(cart.length>0);
}


function checkLimit(co2){ // checks the 100 tonnes limit: total+clicked
	var total=0;
	for (var i=0; cart[i]; i++) total+=parseFloat(cart[i][3]); 
	total+=co2;
	return total<100;
}



//*** DOMESTIC TRAVEL **********************************************************************************************************************
function calculate(type,km,cog){ 
	try {	km=km.replace(/€/g,''); km=km.replace(/,/g,''); km=parseFloat(km); } catch(e){}
	if (isNaN(km)|| km==0 || cog==0) Ext.MessageBox.alert('Warning','Please select a type and enter kilometers value first.');
	else {
		Ext.get('emptySum').hide(); // hide info
		var co2=Math.round(km*cog)/1000000; // grammes to tonnes
		var name=addElement(type,km+' km per annum',co2);
		if (name){
			totalco2+=co2;
			var newBox=new Ext.SumBox({ title:type, name:name, html:'<p>Km per annum: '+numberFormat(km,0)+'<br>Tonnes of CO<sub>2</sub>: '+numberFormat(co2,2)+'</p>' });
			Ext.getCmp('calcSumPanel').insert(0,newBox);
			Ext.getCmp('calcSumPanel').doLayout();
			newBox.slide();
		}
	}
}

function otherTypeSelect(c,r,i){ Ext.getCmp('otherWeeklyKm').enable(); otherCog=c.getValue(); }
function motTypeSelect(c,r,i){ motCog=c.getValue(); Ext.getCmp('motAnnualKm').enable(); }
function carSubtypeSelect(c,r,i){ Ext.getCmp('carAnnualKm').enable(); carCog=c.getValue(); }
function carTypeSelect(c,r,i){
	var newStore;
	if (i==0) newStore=[ ['Petrol','≤1.2','140'], ['Diesel','≤1.5','140'], ['Hybrid','','160'] ];
	if (i==1) newStore=[ ['Petrol','≤1.7','170'], ['Diesel','≤1.9','155'], ['Hybrid','≤2','126'] ];
	if (i==2) newStore=[ ['Petrol','›1.7','225'], ['Diesel','›1.9','190'], ['Hybrid','›2','224'] ];
	if (i==3) newStore=[ ['Petrol','›3','260'] ];
	var carSubTypes=Ext.getCmp('carSubType');
	carSubTypes.reset();
	carSubTypes.store.removeAll();
	carSubTypes.store.loadData(newStore);
	carSubTypes.enable();
}
//******************************************************************************************************************************************






//*** AIR TRAVEL ***************************************************************************************************************************
function progress(show){ Ext.getCmp('loadingDiv').setVisible(show); }

function aircalc(fromto,km,co2,carrier){ 
	if (isNaN(km)|| km==0 || co2==0) { Ext.MessageBox.alert('Warning','Please check the form again.'); return false; }
	else {
		Ext.get('emptySum').hide(); // hide info
		co2=co2/1000; // kg to tonnes
		totalco2+=co2;
		var airlines=(carrier.length>0?'Carrier: '+carrier+'<br>':'');
		var fromto='(from '+Ext.getCmp('airFrom').getValue()+' to '+Ext.getCmp('airTo').getValue()+')';
		var name=addElement('Air Travel',km+' km '+fromto,co2);
		if (name){
			var newBox=new Ext.SumBox({ title:'Air Travel', name:name, html:'<p>'+airlines+'Distance: '+numberFormat(km,0)+' km '+fromto+'<br>Tonnes of CO<sub>2</sub>: '+numberFormat(co2,2)+'</p>' });
			Ext.getCmp('calcSumPanel').insert(0,newBox);
			Ext.getCmp('calcSumPanel').doLayout();
			newBox.slide();
			return true;
		} else return false;
	}
}

function getCO2(){
	progress(true);
	Ext.Ajax.request({ url: 'requests/calculate.php', params:{ getCO2:true, airlines:Ext.getCmp('airlines').getValue(), airClass:Ext.getCmp('airclass').getValue() },
		success: function(resp){
			progress(false);
			var res=resp.responseText.split('#');
			airCog=parseFloat(res[0]);	airDist=parseInt(res[1]);
		}
	});
}


function getAirClass(){
	progress(true);
	Ext.getCmp('airclass').store.removeAll(); Ext.getCmp('airclass').reset();
	Ext.getCmp('airclass').store.load({ params:{ getClass:true, airlines:Ext.getCmp('airlines').getValue() },
		callback: function(r,o,s){ progress(false);	if (s) Ext.getCmp('airclass').enable(); else alert('Server error!'); 	}
	});
}

function getAirlines(){
	progress(true);
	Ext.getCmp('airlines').store.removeAll(); Ext.getCmp('airlines').reset();
	Ext.getCmp('airclass').store.removeAll(); Ext.getCmp('airclass').reset();
	Ext.getCmp('airlines').store.load({ params:{ calc:true, from:Ext.getCmp('airFrom').getValue(), to:Ext.getCmp('airTo').getValue() },
		callback: function(r,o,s){ 
			progress(false);
			Ext.getCmp('optionFieldset').show();
			if (s) Ext.getCmp('airButton').enable(); else alert('error'); 
			if (r.length>0) {
				Ext.getCmp('airlineFieldset').show();
				Ext.getCmp('directflightNO').setValue(false);Ext.getCmp('directflightYES').setValue(true);
			}
			else { 
				Ext.getCmp('airlineFieldset').hide();
				Ext.getCmp('directflightNO').setValue(true);Ext.getCmp('directflightYES').setValue(false);

				var a1=Ext.getCmp('airFrom').store.getById(Ext.getCmp('airFrom').getValue()).data; 
				var a2=Ext.getCmp('airTo').store.getById(Ext.getCmp('airTo').getValue()).data;
				//alert(a1.lat+', '+a1.lon+"\n"+a2.lat+', '+a2.lon+"\n"+'distance: '+distance(a1.lat, a1.lon,  a2.lat, a2.lon));
				airDist=Math.round(distance(a1.lat, a1.lon,  a2.lat, a2.lon)*10000)/10000;
				airCog=airDist/10;	
			}
		}
	});
}

function airButtonCheck(type){
	var from=Ext.getCmp('airFrom'), to=Ext.getCmp('airTo'), button=Ext.getCmp('airButton');
	if (from.isValid()&&from.getRawValue().length>0 && to.isValid()&&to.getRawValue().length>0){
		if (type=='select') getAirlines();	//else button.enable();
	}
	else button.disable();
}
//******************************************************************************************************************************************






//*** HOME *********************************************************************************************************************************
function homeCalc(type,idx,val,cog){ 
	try {	val=val.replace(/€/g,''); val=val.replace(/,/g,''); val=parseFloat(val); } catch(e){}
	if (isNaN(val)|| val==0 || cog==0) { Ext.Msg.show({title:'Warning', msg:'Please select a type and enter a value first.', buttons: Ext.Msg.OK, icon: Ext.MessageBox.ERROR }); return false; }
	
	if (idx==6 && val<75){ Ext.Msg.show({title:'Warning', msg:'Sorry, the minimum value for this is €75.', buttons: Ext.Msg.OK, icon: Ext.MessageBox.ERROR }); return false; }
	if (idx==11 && val<120){ Ext.Msg.show({title:'Warning', msg:'Sorry, the minimum value for this is €120.', buttons: Ext.Msg.OK, icon: Ext.MessageBox.ERROR }); return false; }


	var valArray=['Annual fills', 'Kilograms per annum', 'Kilograms per annum', 'Litres per annum', 'Bales per annum', 'Annual kWh', 'Annual Cost','','','','Annual kWh', 'Annual Cost'];
	var description=['fills', 'kg', 'kg', 'litres', 'bales', 'kWh', 'Euro','','','','kWh', 'Euro'];
	Ext.get('emptySum').hide(); // hide info
	var value=val;
	if (idx==0)	value*=1000;
	if (idx==4)	value*=12.5;
	if (idx==6) value=(value-56.75)*100/5.118; // monetary value to kWh
	
	if (idx==11) value=(value-104.39)*100/9.58; // monetary value to kWh
	
	var co2=Math.round(value*cog)/1000; // kg to tonnes
	
	if (hqPeople>1) { co2=co2/hqPeople; val=val/hqPeople; }
	
	var name=addElement('Home Energy',val+' '+description[idx]+' of '+type,co2);
	if (name){
		totalco2+=co2;
		var newBox=new Ext.SumBox({ title:type, name:name, html:'<p>'+valArray[idx]+': '+numberFormat(val,2)+'<br>Tonnes of CO<sub>2</sub>: '+numberFormat(co2,2)+'</p>' });
		Ext.getCmp('calcSumPanel').insert(0,newBox);
		Ext.getCmp('calcSumPanel').doLayout();
		newBox.slide();
		return true;
	} else return false;
}

function setLabel(text){ 
	if (text) Ext.get('homeValue').up('div.x-form-item').dom.firstChild.firstChild.nodeValue = text; 
	else { Ext.get('homeValue').up('div.x-form-item').dom.firstChild.firstChild.nodeValue='Amount';	Ext.getCmp('homeValue').disable();	}
}

function homeTypeSelect(c,r,i){
	var newStore, valField=Ext.getCmp('homeValue');
	var valArray=['Annual fills', 'Kilograms per annum', 'Kilograms per annum', 'Litres per annum', 'Bales per annum', 'Annual kWh', 'Annual Cost'];
	setLabel(valArray[i]);
	if (i==0) newStore=[ 1,2,3,4,5,6,7,8,9,10 ];
	if (i==1) newStore=[ '100','200','300','400','500','600','700','800','900','1,000' ]; 
	if (i==2) newStore=[ '100','200','300','400','500','600','700','800','900','1,000' ]; 
	if (i==3) newStore=[ '100','200','300','400','500','600','700','800','900','1,000' ]; 
	if (i==4) newStore=[ 1,2,3,4,5,6,7,8,9,10 ];
	if (i==5) newStore=[ '100','200','300','400','500','600','700','800','900','1,000' ]; 
	if (i==6) newStore=[ '€100','€200','€300','€400','€500','€600','€700','€800','€900','€1,000' ]; 
	valField.store.removeAll();
	valField.store.loadData(newStore);
	valField.reset();
	valField.enable();
	homeCog=c.getValue();
}


function energyToggle(chb,ch){
	if (chb.getValue()) { Ext.getCmp('energyValue1').enable(); Ext.getCmp('energyValue2').reset(); Ext.getCmp('energyValue2').disable();  }
	else  { Ext.getCmp('energyValue2').enable(); Ext.getCmp('energyValue1').reset(); Ext.getCmp('energyValue1').disable();  }
}
//******************************************************************************************************************************************







//*** QUICK OFFSET *************************************************************************************************************************
function quickOffsetCalc(title,idx,val,cog){
	try {	val=val.replace(/€/g,''); val=val.replace(/,/g,''); val=parseFloat(val); } catch(e){}
	
	if (isNaN(val)|| val==0 || cog==0) Ext.MessageBox.alert('Warning','Please select a value first.');
	else {
		Ext.get('emptySum').hide(); // hide info
//		var co2=Math.round(val*cog)/1000;
		var co2=val*cog/1000;
		var html='';
		if (idx==1) html='Money: €'+numberFormat(val,2);
		if (idx==2) html='Money: €'+numberFormat((co2*carbonCost),2);
		if (idx==3) html='Citizen (annual)';
	// quick travel
		if (idx==4) html='Short flight';
		if (idx==5) html='Average car';
		if (idx==6) html='Long flight';
		if (idx==7) html='Average House';
	// quick events
		if (idx==8) html='New baby';
		if (idx==9) html='Graduationt';
		if (idx==10) html='Small wedding';
		if (idx==11) html='Small party';
		
		if (idx==12) html='Large wedding';
		if (idx==13) html='Large party';
		html2='<br>Tonnes of CO<sub>2</sub>: '+numberFormat(co2,2);
		
		totalco2+=co2;
		var name=addElement('Quick Offset',html,co2);
		if (name){
			var newBox=new Ext.SumBox({ title:title, name:name, html:'<p>'+html+html2+'</p>' });
			Ext.getCmp('calcSumPanel').insert(0,newBox);
			Ext.getCmp('calcSumPanel').doLayout();
			newBox.slide();
		}		
	}
}


function quickOffsetToggle(chb,ch){
	var v1=Ext.getCmp('quickOffsetValue1'), v2=Ext.getCmp('quickOffsetValue2'), but=Ext.getCmp('quickOffsetButton');
	if (ch){
		if (chb.id=='quickOffset11') v1.enable();
		if (chb.id=='quickOffset12') v2.enable();
		if (chb.id=='quickOffset13') but.enable();
	}
	else{
		if (chb.id=='quickOffset11'){ v1.reset(); v1.disable(); }
		if (chb.id=='quickOffset12'){ v2.reset(); v2.disable(); }
		but.disable();
	}
}

//******************************************************************************************************************************************







function infoPopup(){
	if (!Ext.getCmp('infoPopup')){		
		var infoPopup = new Ext.Window({ id:'infoPopup', width: 390, height:340, layout: 'fit', modal:true, resizable:false, plain:true, buttonAlign:'center',
			title: 'Info', closeAction:'hide', animateTarget:'homeInfoDiv', 
			html:'<ul>'+
				'<li>The weight of a bale of briquettes is 12.5 kg, based on 20-24 bricks. Taken from <a href="http://www.irishturf.com/faq.htm">www.irishturf.com/faq.htm</a></li>'+
				'<li>For gas monetary value:<br>Fixed Standing Charge = €56.75 p/a. <br>Tariff = 5.118c p/kWh.<br>E.g.<br>Annual Cost = €1000<br>€1000 - €56.75 (Standing Charge) = €943.25<br>€943.25 * 100 (to get the amount in cents) = 94,325c<br>94,325c / 5.118c (p/kWh) = 18,430.05 kWh</li>'+
				'<li>For electricity monetary value:<br>Fixed Standing Charge = €104.39 p/a<br>Tariff = 9.58c p/kWh.<br>E.g.<br>Annual Cost = €1,000<br>€1,000 - €104.39 (Standing Charge) = €895.61<br>€895.61 * 100 (to get the amount in cents) = 89,561c<br>89,561c / 9.58 (c p/KWh) = 9,348.75 kWh</li>'+
				'</ul>',
			buttons: [ { text: 'Close', minWidth:80, handler: function(){ infoPopup.hide() } }]
		});
	}
	Ext.getCmp('infoPopup').show();	
}
