var defaultPrice={};
var countries=[];
var overrides={};

// So we're going to do something like:
//	countries[countryId]=new VonageCountry(countryId, countryName, diallingCode, callRate, hide);
// and:
//	overrides[countryId+callPlan]=new RatePlanOverride(countryId, callPlan, callRate);

function VonageCountry(countryId, countryName, diallingCode, callRate, hide) {
	this.countryId = countryId;
	this.countryName = countryName;
	this.diallingCode = diallingCode;
	this.callRate = callRate;
	this.hide = hide;
}

function RatePlanOverride(countryId, callPlanName, callRate) {
	this.countryId = countryId;
	this.callPlanName = callPlanName;
	this.callRate = callRate;
}

function Call(countryId, duration) {
	this.countryId = countryId;
	this.duration = duration;

	this.calculateCost=function (callPlanName) {
		var rate=0.00;

		if(countries[this.countryId]!==undefined) {
			rate=countries[this.countryId].callRate;
		}
		if(overrides[''+this.countryId+''+callPlanName]!==undefined) {
			rate=overrides[''+this.countryId+''+callPlanName].callRate;
		}
		return rate*this.duration;
	};
}

// So now we can find out the rate for a call, by doing, e.g.:
//	var phoneCall=new Call(1213, 10);
//	var callCost=phoneCall.calculateCost('V-Plan UK');

function CallBasket() {
	this.calls=[];

	this.addCall=function (countryId, duration) {
		this.calls.push(new Call(countryId, duration));
	};

	this.calculateCost=function (callPlan) {
		var basketCost=0;
		var callCost=0.00;
		var i=0;
		for(i=0; i<this.calls.length; i++) {
			callCost=this.calls[i].calculateCost(callPlan.name);
			if(callCost<0) {
				return -1;
			}
			basketCost+=callCost/100;
		}
		return basketCost;
	};
}

// ... and we calculate the rate for a basket of calls by doing, e.g.:
//	var basket=new CallBasket();
//	basket.addCall(1213, 10);
//	basket.addCall(974, 20);
//	basket.addCall(1306, 10);
//	basket.calculateCost('V-Plan UK');

var resultsTableHeader='<div style="width:630px; border-bottom:1px dotted #999; padding-bottom:10px;"><img src="images/recommend_title.gif" alt="Recommended Call Plans"></div>'
						+'<div class="closeButton"><a href="#" onclick="javascript:hideRecPlans();"><img src="images/close_button.gif"></a></div>'
						+'<table cellpadding="0" cellspacing="2" width="630px">'
						+'<tr>'
						+'<th width="140px" align="center">Plan name</th>'
						+'<th width="120px" style="padding-left:2px;" align="center">Set monthly charge</th>'
						+'<th width="120px" style="padding-left:2px;" align="center">Country call charges</th>'
						+'<th width="120px" style="padding-left:2px;" align="center">Total monthly cost</th>'
						+'<th width="120px" style="padding-left:2px;" align="center">Next steps</th>'
						+'</tr>'
						;
var resultsTableFooter='</table>';


function CostedPlan(callPlan, basketCost) {
	this.callPlan=callPlan;
	this.basketCost=basketCost;

	this.render=function () {
		var tableRow='<tr><td align="center">';
		tableRow+='<img src="images/recplan/'+this.callPlan.className+'.gif"></td>'+"\n";
		tableRow+='<td align="center" class="'+this.callPlan.className+'">&pound;'+Number(this.callPlan.monthly_fee).toFixed(2)+'</td>'+"\n";
		tableRow+='<td align="center" class="'+this.callPlan.className+'">&pound;'+Number(this.basketCost).toFixed(2)+'</td>'+"\n";
		tableRow+='<td align="center" class="plantotal">&pound;'+Number(this.callPlan.monthly_fee+this.basketCost).toFixed(2)+'</td>'+"\n";
		tableRow+='<td align="center"><a href="'+infoURL(this.callPlan.name)+'">More info</a><br><a href="https://secure.vonage.co.uk/subscribe/">Sign up now</a></td>'+"\n";
		tableRow+="</tr>\n";
		return tableRow;
callPlan.name+' would cost &pound; '+Number(this.callPlan.monthly_fee).toFixed(2)+' monthly fee plus &pound; '+Number(this.basketCost).toFixed(2)+' for calls';
	};
}

function compareCostedPlans(planA, planB) {
	if((planA.callPlan.monthly_fee+planA.basketCost)<(planB.callPlan.monthly_fee+planB.basketCost)) {
		return -1;
	}
	if((planB.callPlan.monthly_fee+planB.basketCost)<(planA.callPlan.monthly_fee+planA.basketCost)) {
		return 1;
	}
	return 0;
}

// So now, assuming we have a basket as above, we can do:
//	var callPlans=[	{ 'name' : 'V-Plan UK', 'monthly_fee' : 5.99 },
//					{ 'name' : 'V-Plan 2', 'monthly_fee' : 7.99 },
//					{ 'name' : 'V-Plan 3', 'monthly_fee' : 9.99 },
//					{ 'name' : 'V-Plan 4', 'monthly_fee' : 14.99 },
//					{ 'name' : 'V-Plan 5', 'monthly_fee' : 18.99 },
//					{ 'name' : 'V-Plan US', 'monthly_fee' : 6.99 },
//					{ 'name' : 'V-Plan India', 'monthly_fee' : 6.99 },
//					{ 'name' : 'V-Plan Australia', 'monthly_fee' : 6.99 },
//				];
//	var allPlans=[];
//	var i=0;
//	for(i=0; i<callPlans.length; i++) {
//		allPlans.push(new CostedPlan(callPlans[i], basket.calculateCost(callPlans[i])));
//	}
//
//	allPlans.sort(compareCostedPlans);
//	var planCosts=[];
//	for(i=0; i<allPlans.length; i++) {
//		planCosts.push(allPlans[i].toString());
//	}
//	document.getElementByName('bestPlanDiv').innerHTML=planCosts.join('<br/>');


function CountryItem(countryId) {
	this.countryId=countryId;
	this.duration=0;
	this.enabled=true;
}

var countryItemIndex=0;
var countryItemList=[];

var codesTableHeader='<div style="width:630px; border-bottom:1px dotted #999; padding-bottom:10px;"><img src="images/confirm_code_title.gif" alt="Confirm code"></div>'
					+'<div class="closeButton"><a href="#" onclick="javascript:hideMoreRates();"><img src="images/close_button.gif"></a></div>'
					+'<table cellpadding="0" cellspacing="2" width="630px">'
					+'<tr>'
					+'<th width="300px" align="center">Country</th>'
					+'<th width="200px" align="center">Dialling code</th>'
					+'<th width="124px" align="center">&nbsp;</th>'
					+'</tr>'
					;
var codesTableFooter='</table>';


// function to calculate the UK saving
function doUk(){
	var price = parseFloat($('input[@name=uk-price]').val()); // get the uk-price value
	if (price > 0){
		saving = price - 5.99; // work out the saving from £5.99 a month
		var msg = "";
		if (saving <=0){ // no saving or better
			msg = "<div class='bold' style='font-size:13px;color:#565656; padding-top:10px;'>You've got yourself a great deal! But with Vonage you also get:</div><ul id='less-than-list'><li>Six call plans to choose from</li><li>Unlimited* anytime calls to both UK and international destinations</li><li>20 inclusive call features</li><li>Choice of area dialling code for your phone number</li><li>&amp; much more</li><a href='http://www.vonage.co.uk/call-plans/' onClick=\"javascript: pageTracker._trackPageview('/calculator/uk/deal/call-plans/');\">View our call plans &raquo;</a></ul>";
			$("#uk-result").addClass('less-than-zero');
			$("#uk-result").removeClass('more-than-zero');
		} else { // show the savings
			msg = "<div class='monthly-saving'>&pound;"+saving.toFixed(2)+"</div><div class='annual-saving'>&pound;"+ (saving * 12).toFixed(2)+"</div><div class='result-links'><a href='http://www.vonage.co.uk/call-plans/vplanuk' onClick=\"javascript: pageTracker._trackPageview('/calculator/uk/saving/v-planuk/');\">Go to V-Plan UK &raquo;</a><br/><a href='http://www.vonage.co.uk/call-plans/' onClick=\"javascript: pageTracker._trackPageview('/calculator/uk/saving/call-plans/');\">View all call plans &raquo;</a></div><div class='howmuchterms'>This estimate includes VAT and excludes your line rental and broadband costs.Your estimated monthly and yearly savings has been calculated by deducting the monthly cost you entered against the monthly cost of our base call plan, V-Plan UK. V-Plan UK allows you to make unlimited‡ calls to UK landlines for just £5.99 a month.</div>";
			$("#uk-result").addClass('more-than-zero');
			$("#uk-result").removeClass('less-than-zero');
		}
		
		$("#uk-result").html(msg); // output the result
		$("#uk-result").show();
		//
		// google tracking - pass the price entered
		pageTracker._trackPageview("/calculator/uk/"+price+"/");
		
	} else {
		alert("Please enter a valid amount");
	}
	
}

function resetUk(){
	$("#ukform")[0].reset();
	$("#uk-result").hide();
	$("#int-calc").show();
}

function doInt(){
	// loop through the 'active'
	// set error to false
	var error = false;
	
	var c = 0;
// ... and we calculate the rate for a basket of calls by doing, e.g.:
	var basket=new CallBasket();
	// countryArray is the list of countries/dialling codes/prices on the page.
	for (c = 0; c < countryItemIndex; c++) {
//alert("c is "+c+", enabled="+countryItemList[c].enabled);
		if(countryItemList[c].enabled === true) {
			var mins = $("input[@name='int-mins"+c+"']").getValue();
			if (mins <= 0 || mins=="NaN"){
				// error
				error = true;
			} else {
				// get the country name
				//var country = $("input[@name='int-country"+c+"']").getValue();
				// get the plan info
				var rate = $("input[@name='int-rate"+c+"']").getValue();
			}
			basket.addCall(countryItemList[c].countryId, mins);
		}
	}

	var allPlans=[];
	var i=0;
	for(i=0; i<callPlans.length; i++) {
		allPlans.push(new CostedPlan(callPlans[i], basket.calculateCost(callPlans[i])));
	}

	allPlans.sort(compareCostedPlans);
	var planCosts=[];
//	for(i=0; i<allPlans.length; i++) {
	for(i=0; i<3; i++) {
		planCosts.push(allPlans[i].render());
	}

	var resultsEl=document.getElementById("calc_results_popup");
	resultsEl.innerHTML=resultsTableHeader+planCosts.join("\n")+resultsTableFooter;
	document.getElementById('calc_popup').style.display="none";
	resultsEl.style.display="block";
	
	//HIDE INT-FORM DROPDOWN IE6 fix
		$("#int-select").hide()	
		
	//document.getElementByName('bestPlanDiv').innerHTML=planCosts.join('<br/>');
	
	if (error == false){
		
		// google tracking - international calculation hit
		pageTracker._trackPageview("/calculator/international/");
		// google tracking - countries searched for and their mins
		var countryList = new Array();
		for (c = 1; c <= countryArray.length; c++){
			if (countryArray[c] == 1){ // active
				var mins = $("input[@name='int-mins"+c+"']").getValue();
				var country = $("input[@name='int-country"+c+"']").getValue();
				//countryList.push(country);
				var countrydata = stripText(country)+"/"+stripText(mins);
				//
				pageTracker._trackPageview("/calculator/international/country/"+countrydata+"/");
				
			}
		}
		
		
		// hide the UK content

		//
		var costuk = "&pound;"+(totaluk/100).toFixed(2)+"p";
		//
		// work out the lowest cost
		// set up UK as default
		var lowestcost = totaluk;
		var lowestplan = "uk";
		
		
		
		$("input[@name='calculate-int']").addClass("recalculate");
		//<input type="submit" value="CALCULATE" name="int-submit">
		
		// populate the results
		// main header
		var results = '<div class="header"><h3 class="orange" style="margin-top:0px;margin-left:15px;width:220px;height:25px;">Call Plan Results</h3></div>';
		// table header
		results+='<table border="0" width="736" style="position:relative;left:10px;margin-top:20px;"><tr class="head-d" height="31"><td width="97"></td><td width="227" class="no-image-top1"></td><td width="95" class="no-image-top2"></td><td width="85" class="no-image-top3"></td><td width="95" class="no-image-top4"></td><td width="" class="no-image-top5"></td></tr>';
		
		
		
		// UK results
		var ukresults1 ='<tr class="bg-v-plan';
		
		var ukresults2='"><td>&nbsp;</td><td class="no-image shrink">Our best-value, no frills budget package:<ul><li>Unlimited‡ UK landline calls</li><li>Cheap international calls to '+ limited_uk.join(", ");
		
		ukresults2+='</li><li>Unlimited Vonage-to-Vonage calls</li><li>20 inclusive call features</li></ul></td><td class="smc no-image">&pound;5.99</td><td class="smc no-image">&pound;';
		
		ukresults2+=(totaluk / 100).toFixed(2);
		
		ukresults2+='</td><td class="uk-text no-image">&pound;';
		ukresults2+=((totaluk+599)/100).toFixed(2);
		ukresults2+='</td><td class="no-image"><a href="http://www.vonage.co.uk/call-plans/vplanuk" onClick="javascript: pageTracker._trackPageview(\'/calculator/international/v-planuk/call-plans/more\');" class="table-link">Find out more &raquo;</a><br/><a href="https://secure.vonage.co.uk/vonageuk-subscribe/" onClick="javascript: pageTracker._trackPageview(\'/calculator/international/v-planuk/signup\');" value="Sign up now"><img src="images/sign-up-now.jpg"/></a><br /></td></tr>';
		//
		
			noukresult+='</td><td class="no-image"><br /><a href="'+linkArray[lowestp]+'" onClick="javascript: pageTracker._trackPageview(\'/calculator/international/'+stripText(planArray[lowestp])+'/more\');"class="table-link">Find out more &raquo;</a><br/><a href="https://secure.vonage.co.uk/vonageuk-subscribe/" onClick="javascript: pageTracker._trackPageview(\'/calculator/international/'+stripText(planArray[lowestp])+'/signup\');" value="Sign up now"><img src="images/sign-up-now.jpg"/></a></td></tr>';
			
	} else {
		alert ("Please enter your minutes used.");
	}
}

function resetInt(){
	$("#intform")[0].reset();
	$("#uk-calc .calc-content").show();
}

function hideMoreRates() {
	document.getElementById('calc_popup').style.display="none";
	// SHOW INT-FORM SELECT
	$("#int-select").show()	
}

function hideRecPlans() {
	document.getElementById('calc_results_popup').style.display="none";
	// SHOW INT-FORM SELECT
	$("#int-select").show()	
}

function setCountry(rowId, countryId) {
	if(countryItemList[rowId] === undefined) {
		countryItemList[rowId]=new CountryItem(countryId);
	} else {
		countryItemList[rowId].countryId=countryId;
		countryItemList[rowId].enabled=true;
	}
	var rate=countries[countryId].callRate;
	$("#rate"+rowId).html(rate+'p<input type="hidden" id="int-rate'+rowId+'" name="int-rate'+rowId+'" value="'+rate+'">');
}

function showMoreRates(countryName, id) {
	document.getElementById('calc_results_popup').style.display="none";
	//HIDE INT-FORM DROPDOWN IE6 fix
	$("#int-select").hide()		
	var calcPopupEl=document.getElementById('calc_popup');
calcPopupEl.innerHTML='<h2>Loading, '+countryName+', please wait ...</h2>';
	var content=codesTableHeader;
	var foundOne=false;
	var matchLen=countryName.length;
	for(var i=1; i<countries.length; i++) {
		if(countries[i]===undefined) {
			continue;
		}
		if(countries[i].countryName.substr(0, matchLen) === countryName) {
			foundOne=true;
			content+='<tr><td align="center">'+countries[i].countryName+'</td><td align="center">'+countries[i].diallingCode+'</td><td align="center"><a href="#" onclick="javascript:setCountry(\''+id+'\',\''+i+'\');hideMoreRates();" value="" >Select</a></td></tr>';
		} else {
			if(foundOne) {
				break;	// We've come to the end of our country match, so exit.
			}
		}
	}
	content+=codesTableFooter;
	calcPopupEl.innerHTML=content;
	calcPopupEl.style.display="block";
}

// get the rate
function getRate(id){
	var x = document.getElementById("drop"+id);
//alert(x.options[x.selectedIndex].text);
	var countryName = x.options[x.selectedIndex].text;
	if (countryName !== "null"){
		var countryId=defaultId[countryName];
		setCountry(id, countryId);	// set the countryId in this row of the array.
		var rate=countries[countryId].callRate;
		$("#rate"+id).html(rate+'p<input type="hidden" id="int-rate'+id+'" name="int-rate'+id+'" value="'+rate+'">');
		$("#mins"+id).html('<input type="text" name="int-mins'+id+'" id="int-mins'+id+'" class="numb" maxlength="5" size="5"/>');
		$("#more"+id).html('<a href="javascript:showMoreRates(\''+escape(countryName)+'\', '+id+');" ><img src=\'images/confirm-dial-code.jpg\'/></a><input type="hidden" id="int-country'+id+'" name="int-country'+id+'" value="'+countryName+'">');
		// set focus on mins area
		$("#int-mins"+id).focus();
		digitOnly();
		$(".popupwindow").popupwindow(profiles);
	}
}

// dynamic form fields
// adding

function addFormField() {
	$("#int-titles").show();
	$(".show-image").show();
	$("input[@name='int-add-button']").addClass("add-country");
	//var id = $("input[@name='int-id']").getValue();
	var id=countryItemIndex++;
	//var id = document.getElementById("int-id").value;
	//var numb = $("input[@name='int-numb']").getValue();
	//var numb = document.getElementById("int-numb").value;
	// add a country to the list
	$("#int-select").append("<div class=\"row\" id='row" + id + "'></div>");
	$("#row"+id).append("<div class=\"drop-d\"><select name=\"drop"+id+"\" id=\"drop"+id+"\" onChange=\"javascript:getRate("+id+");\"></select></div>");
	// add the more rates
	$("#row"+id).append("<div class=\"more-d\" id='more" + id + "'><img src=\'images/confirm-dial-code-b.jpg\'/></div>");
	// add the rate holder
	$("#row"+id).append("<div class=\"rate-d\" id='rate" + id + "'>0p</div>");
	// add the mins text
	$("#row"+id).append("<div class=\"mins-d\" id='mins" + id + "'><input type=\"text\" maxlength=\"5\" size=\"5\" disabled=\"true\" /></div>");
		// add the remove text
	$("#row"+id).append("<div class=\"remove-d\"><a href='#' onClick='javascript:removeFormField(\"" + id + "\"); return false;'><img src='images/remove.jpg'/></a>");
	// error field
	$("#row"+id).append("<div class=\"error\" id='error" + id + "'></div></div>");
	// load in the dropdown
	var countryName;
	var selectEl=document.getElementById("drop"+id);
	for(countryName in defaultId) {	// All the country names
		var optEl=document.createElement('option');
		optEl.text=countryName;
		try {
			selectEl.add(optEl, null);	// Works with proper browsers.
		} catch(ex) {
			selectEl.add(optEl);		// Pander to IE's non-standard behaviour.
		}
	}
	// add to country array
	countryArray[id] = 1;
	// increment the int-id
	id = (id - 1) + 2;
	
	//document.getElementById("int-id").value = id;
	$("input[@name='int-id']").setValue(id);
	// more than 0 countries so show the submit button
	$("#int-submit-div").show();
	
	document.getElementById('calc_results_popup').style.display="none";
//alert("At end of addFormField()");
}
// removing
function removeFormField(id) {
	document.getElementById('calc_results_popup').style.display="none";
	countryItemList[id].enabled=false;
	$("#row"+id).remove();
	for(var i=0; i<countryItemIndex; i++) {
		if(countryItemList[i].enabled === true) {
			return;
		}
	}
	$("input[@name='calculate-int']").removeClass("recalculate");
	$("input[@name='int-add-button']").removeClass("add-country");
	$("#int-submit-div").hide();
	$("#int-titles").hide();
	$("#int-result").hide();
	$(".show-image").hide();
}

function digitOnly(){
	// digits only!!
	$(".numb").keypress(function (e) {
		//if the letter is not digit then display error and do not type anything
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
			return false;
		}
	});
}

// array for the country drop downs
var countryArray = [];

$(document).ready(function() {
	// hide stuff
	$("#uk-result").hide();
	$("#int-submit-div").hide();
	//
	// is there a value passed from a banner?
	if ($.getURLParam("price")){
		price = $.getURLParam("price");
		$('input[@name=uk-price]').val(price); // put the price into the input area
		doUk(); // calculate the UK saving
	}
	//
	// input focus clearing
	$('input[type="text"]').focus(function() {
		this.value = '';
	});
	$('input[type="text"]').blur(function() {
		if (this.value == '') this.value = (this.defaultValue ? this.defaultValue : '');
	});
	//
	// uk text entry
	$("#uk-price").keypress(function (e) {
		//if the letter is not digit then display error and do not type anything
		if (e.which == 13){ // enter button
			doUk();
			this.blur();
			return false;
		} else if( e.which!=8 && e.which!=0 && e.which!=46 && (e.which<48 || e.which>57)) {
			return false;
		}
	});
	
	
	// the toggle functionality of the headers
	$("#uk-area").click( function() {
		if ($("#uk-calc .calc-content").is(":hidden")) {
			$("#uk-area").removeClass("arr-right");
			$("#uk-area").addClass("arr-down");
		} else {
			$("#uk-area").removeClass("arr-down");
			$("#uk-area").addClass("arr-right");
		}
		$("#uk-calc .calc-content").toggle();
	});
	
	$("#int-area").click( function() {
		if ($("#int-calc .calc-content").is(":hidden")) {
			$("#int-area").removeClass("arr-right");
			$("#int-area").addClass("arr-down");
			$(".show-image").show();
		} else {
			$("#int-area").removeClass("arr-down");
			$("#int-area").addClass("arr-right");
			$(".show-image").hide();
		}
		if ($("#int-titles").is(':hidden')) {
			$(".calc-image").hide();
			$(".white-top").hide();
			$(".white-bottom").hide();
		}
		else {
			
		}
		$("#int-calc .calc-content").toggle();
		
	});
	
	$("#int-titles").hide();
	$(".show-image").hide();
});

// temp
function temp(){
	alert("This button will link");
	return false;
}

// pop-up window
var profiles =
	{
		windowRate:
		{
			height:400,
			width:600,
			status:1,
			center:1,
			location:0,
			menubar:0,
			toolbar:0,
			scrollbars:1
		}
	};

function infoURL(name) {
	name=(""+name).toLowerCase();
	name=name.replace(/[ -]/g, '');
	return "http://www.vonage.co.uk/call-plans/"+name;
}

function planURL(name) {
	name=(""+name).toLowerCase();
	name=name.replace(/[ -]/g, '');
	return "http://www.vonage.co.uk/call-plans/"+name;
}
										
						
// strip the text
function stripText(strText){
	// set to lowercase
	strText = strText.toLowerCase();
	// replace spaces with -
	strText = strText.replace(/ /g, "-");
	// remove all non-alphanumeric (but keep -)
	strText = strText.replace(/[^a-zA-Z0-9-]/g, "");
	return strText;
}

