var calculator = Class.create();

calculator.prototype = {

    
    	initialize: function() {
    	
	/** 
	 *  Initialize Class
	 *  	- Finds quick calc submit link, or:
	 *	- Looks for quick calc comparison link
	 */ 

		this.findCalcSubmitLinks();
	},

	findCalcSubmitLinks: function() {
	
	/** 
	 *  Looks for Calculator links on page
	 */ 


		if ($$('#vm-donation-quick-calc input.submit')[0] || $$('#vm-donationcalc input.submit')[0] || $$('#vm-donation-compare-calc input.submit')[0]) {

			if($$('#vm-donation-quick-calc input.submit')[0]) {

				calcId = '#vm-donation-quick-calc';

			}


			if($$('#vm-donationcalc input.submit')[0]) {

				calcId = '#vm-donationcalc';

			}

			if($$('#vm-donation-compare-calc input.submit')[0]) {

				calcId = '#vm-donation-compare-calc';

			}

			calcLink = $$(calcId+' .submit')[0];
			this.activateCalcSubmitButton(calcLink, calcId)

			if(this.readCookieValueFromName('quick-calc')) {
				this.startCalculation('',calcId,this.getCookieValueFromName('quick-calc'));
			} else {
				this.startCalculation('',calcId,'10.00');
			}

			
		}		

	},

	activateCalcSubmitButton: function(element,calcId) {	

	/** 
	 *  Adds event to calculator 'calculate' button
	 */  


	 	element.writeAttribute("onclick", "return false");
		Event.observe(element,'click', this.startCalculation.bindAsEventListener(this,calcId));

	},
	
	startCalculation: function(e,element,donation) {
	
	/** 
	 *  Performs Calculation
	 */ 

	 	
	 	var amount;
		
		if(donation) {
		
			amount = donation;
		
		} else {
		
			amount = $$(calcId+' input.amount')[0].getValue();
		
		}
		
		amount = this.removeSpaces(amount);

		if (amount.length == 0) {

			$$(calcId+' .donate-error')[0].update('Please type in an amount.').setStyle({'display':'block'});
			$$(calcId+' .receive .amount')[0].update("");
			$$(calcId+' .receive .amount')[0].update('&pound;0.00');
			return false;
				
		}
			
		if (isNaN(amount)) {

			$$(calcId+' .donate-error')[0].update('Please donâ€™t use anything other than numbers. ').setStyle({'display':'block'});
			$$(calcId+' .receive .amount')[0].update("");
			$$(calcId+' .receive .amount')[0].update('&pound;0.00');
			return false;

		} 
		
		$$(calcId+' .donate-error')[0].hide();

		this.deleteCookie('quick-calc');
		this.setCookie('quick-calc',amount);
		
		amount = parseFloat(amount);
		amount = amount.toFixed(2);
		
		// Update the value with the trimmed amount
		$$(calcId+' input.amount')[0].value = amount;
		
		this.startCompetitorCalculation('',amount);
		finalDonation = this.vmgCalculationFormula(amount);
	
		$$(calcId+' .receive .amount')[0].update('&pound;' + (finalDonation));
		$$(calcId+' .donate-error')[0].update('');
			
	
	},
	
	
	startCompetitorCalculation: function(e,donation) {
	
	/** 
	 *  Performs Calculation
	 */ 
	 	
	 	if($('vm-donation-other-calc')) {
	 	
	 	var amount;
			
		amount = donation;
		finalDonation = this.competitorCalculationFormula(amount);

		$$('#vm-donation-other-calc .receive .amount')[0].update('&pound;' + finalDonation);
		
		}			
	
	},
	
	vmgCalculationFormula: function(amount) {

		
		// Convert amount to a valid number
		amount = parseFloat(amount);

		// Perform calulation based on 20% Gift Aid allowance
		var giftaid = this.giftAidFormula(amount);

		// Perform calulation based on 2% tranaction fee
		var transactionFee = this.roundUpNumber((amount/100)*2,2);

		// Perform calulation based on 2% virgin money fee
		var vatFee = 0;

		// Debit Card Fee of 16 pence.
		var debitCardFee = 0.16;
		


		//Total Fees
		var totalFees = parseFloat(transactionFee) + parseFloat(vatFee) + parseFloat(debitCardFee);

		// Final Calculation
		
		var donation = this.roundNumber(parseFloat(amount) + parseFloat(giftaid) - parseFloat(totalFees),2);
		
		donation = this.toPence(donation);

		
		if (donation <= 0) {
		
		donation = "0.00";
		
		}
		
		donation = this.commify(donation);

		//alert("Giftaid: "+ giftaid
		//	+"\nTransaction Fee: "+ transactionFee
		//	+"\nDebit Card Fee: "+ debitCardFee
		//	+"\nTotal Fees: "+ totalFees		
		//	+"\nDonation: "+ donation
		//	);
		
		return donation;
	
	},
	
	competitorCalculationFormula: function(amount) {
	
		// Convert amount to a valid number
		amount = parseFloat(amount);

		// Perform calulation based on 20% Gift Aid allowance
		var giftaid = this.giftAidFormula(amount);

		// Perform calulation based on 2% tranaction fee
		var transactionFee = this.roundNumber((amount+giftaid)*0.05,2);

		// Perform calulation based on 15% VAT
		var vatFee = this.roundNumber(transactionFee*0.15,2);

		// Debit Card Fee of 23 pence.
		var debitCardFee = 0.23;

		//Total Fees
		var totalFees = parseFloat(transactionFee) + parseFloat(vatFee) + parseFloat(debitCardFee);

		//alert("Transaction Fee: "+transactionFee +"\n VAT: "+vatFee +"\n Total Fees : "+totalFees)

		// Final Calculation
		var donation = this.roundNumber(parseFloat(amount) + parseFloat(giftaid) - parseFloat(totalFees),2);

		donation = this.toPence(donation);

		if (donation <= 0) {
		
		donation = "0.00";
		
		}
		
		donation = this.commify(donation);	
		return donation;
	
	},
	
	
	giftAidFormula: function(value) {
	
		giftaid = this.roundNumber(value*0.25,2);
		tr = this.roundNumber(giftaid*0.1282051,2);
		
		//alert("Giftaid: "+ giftaid
		//	+"\nTransitional Relief: "+ tr);
		
		return parseFloat(giftaid + tr);
	
	},
	
	roundNumber: function(rnum, rlength) { // Arguments: number to round, number of decimal places
	  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	  return newnumber; // Output the result to the form field (change for your purposes)
	},
	

	roundUpNumber: function(num, dec) {
		var result = Math.ceil( Math.ceil( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
		return result;
	},
	
	toPence: function (amount) {

	/** 
	 *  Returns any amount converted to pence (to 2 decimal places)
	 */

	    return amount.toFixed(2)

	},
	
	
	setCookie: function(name,value) {

	/** 
	 *  Sets session cookie of (name,value)
	 */ 

		document.cookie = name +"="+ value +";path=/;"

	},

	deleteCookie: function(name) {

	/** 
	 *  Deletes session cookie of (name)
	 */ 

		document.cookie = name + '=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT;';

	},
	
	getCookieValueFromName: function(name) {

	/** 
	 *  Returns cookie value from cookie name
	 */ 
		var cookies = document.cookie.split(';');
		for(var i = 0; i < cookies.length; i++) {	
			var cookie = cookies[i].split("=");
			if(cookie[0].replace(" ", "") == name) {
				return cookie[1];    
			}
		}
	},

	readCookieValueFromName: function(name) {

	/** 
	 *  Returns true if cookie found
	 */ 
		var cookies = document.cookie.split(';');
		for(var i = 0; i < cookies.length; i++) {	
			var cookie = cookies[i].split("=");
			if(cookie[0].replace(" ", "") == name) {
				return true    
			}
		}
	},
	
	commify: function(amount) {
		amount +="";
		amountArr = amount.split(".");
		poundAmount = amountArr[0];
		    var newNum = "";
		    var newNum2 = "";
		    var count = 0;


		for (var k = poundAmount.length-1; k >= 0; k--){
		      var oneChar = poundAmount.charAt(k);
		      if (count == 3){
			newNum += ",";
			newNum += oneChar;
			count = 1;
			continue;
		      }
		      else {
			newNum += oneChar;
			count ++;
		      }
		   }  //but now the string is reversed!

		  //re-reverse the string
		  for (var k = newNum.length-1; k >= 0; k--){
		      var oneChar = newNum.charAt(k);
		      newNum2 += oneChar;
		  }

		  if (amountArr.length > 1) {

		   newNum2+="."+ amountArr[1];

		  }
		  return newNum2;


	},
	
	removeSpaces: function(string) {
	 return string.split(' ').join('');
	}
	
}

document.observe('dom:loaded', function () { new calculator() });