var G_skymarketNo = '01276693500';
var G_numberLookup = false;

function prefilClasses() {
	var postdata = new Array();
	postdata['picked_id'] = 0;
	
	apilite_post(G_locationLink+'/callout/lookup.php', postdata, 'prefilClassesOK', '', 'prefilClassesFailed', '');
}

function prefilClassesOK(response, args) {
	var classLines = response.split("\n");
	var classId, classNum;
	var classSelect = document.getElementById('numclass');
	
	classLines.pop();
	
	// classSelect.options[classSelect.length] = new Option('Class', '');
	
	for(var i = 0; i < classLines.length; i++) {
		classId = classLines[i].split('|')[0];
		classNum = classLines[i].split('|')[1];
		
		classSelect.options[classSelect.length] = new Option(classNum, classId+'|'+classNum);
	}
}

function prefilClassesFailed(response, args) {
	alert('Can\'t prefil class numbers');
}

function updateRange(classValue) {
	if(classValue != '') {
		var postdata = new Array();
		postdata['class'] = document.getElementById('numclass').value.split('|')[0];
		
		apilite_post( G_locationLink+'/extra_utils/cost_calc/includes/ajax/_ingress.php', postdata, 'updateRangeOK', '', 'updateRangeFailed', '');
	}
}

function updateRangeOK(response, args) {
	var rangeLines = response.split("\n");
	var rangeId, rangeNum, pkPPM, rangePkPPM;
	var rangeSelect = document.getElementById('numrange');
	var classSelect = document.getElementById('numclass');
	
	rangeLines.pop();
	
	rangeSelect.length = 0;
	
	rangeSelect.options[rangeSelect.length] = new Option('Range', '');
	
	for(var i = 0; i < rangeLines.length; i++) {
		rangeId = rangeLines[i].split('|')[0];
		rangeNum = rangeLines[i].split('|')[1].substr(classSelect.options[classSelect.selectedIndex].text.length);
		pkPPM = rangeLines[i].split('|')[2];
		rangePkPPM = (pkPPM > 0) ? (pkPPM/1000)+'ppm' : 'Free';
	
		rangeSelect.options[rangeSelect.length] = new Option(rangeNum+' - ('+rangePkPPM+')', rangeId+'|'+rangeNum);
	}
}

function updateRangeFailed(response, args) {
	alert('Updating range failed. Please refresh and try again.');
}

function displayCostToCaller(rangeValue) {
	var classValue = document.getElementById('numclass').value;
	if(rangeValue != '' && classValue != '') {
		calculateIngress('displayCostToCallerOK', true);
	}
}

function displayCostToCallerOK(response, args) {
	setCTCPrice(response.split('|')[4], response.split('|')[5], response.split('|')[6]);
	recalculateCost();
}

function viewOtherSelect() {
	var to = document.getElementById('to').value;
	var networkSelect = document.getElementById('network');
	var countrySelect = document.getElementById('country');
	
	countrySelect.selectedIndex = 0;
	networkSelect.selectedIndex = 0;
	
	if(to == 'landline') {
		networkSelect.style.display = 'none';
		countrySelect.style.display = 'none';
		
		if(validate()) {
			G_numberLookup = false;
			calculateIngress('calculateLandlineOK')
		}
	} else if(to == 'mobile') {
		countrySelect.style.display = 'none';
		networkSelect.style.display = 'inline';
	} else if(to == 'international') {
		networkSelect.style.display = 'none';
		countrySelect.style.display = 'inline';
	} else {
		networkSelect.style.display = 'none';
		countrySelect.style.display = 'none';
	}
}

function calculatePriceNumber() {
	var telno = stripSpaces(document.getElementById('toNumber').value);
	
	G_numberLookup = true;
	
	if(!validate(true)) {
		return;
	} else {	
		var toSelect = document.getElementById('to');
		var networkSelect = document.getElementById('network');
		var countrySelect = document.getElementById('country');
		
		toSelect.selectedIndex = 0;
		countrySelect.selectedIndex = 0;
		networkSelect.selectedIndex = 0;
		
		countrySelect.style.display = 'none';
		networkSelect.style.display = 'none';
		
		// alert(telno);
		
		// if(telno.match(/^\+440?1|01/) || telno.match(/^\+440?2|02/)) {
		
		if(telno.match(/^(\+440?|0)(1|2)/)) {
			// alert('Landline');
			calculateIngress('calculateLandlineOK');
		} else {
			// alert('Mobile or international');
			calculateIngressOther();
		}
	}
}

function calculatePriceDest(location_id) {
	if(location_id && validate()) {
		G_numberLookup = false;
		showHideLoading(true);	
		calculateIngressOther();
	}
}

function recalculateCost() {
	if(G_numberLookup) {
		// Re calculate phone number
		if(document.getElementById('toNumber').value != '') {
			calculatePriceNumber();
		} else { 
			return; 
		}
	} else {
		// Re calculate destination
		var to = document.getElementById('to').value;
		var network = document.getElementById('network').value;
		var country = document.getElementById('country').value;
		
		if(to == 'landline') {
			if(validate()) {
				calculateIngress('calculateLandlineOK');
			}
		} else if(to == 'mobile' && network != '') {
			calculatePriceDest(network);
		} else if(to == 'international' && country != '') {
			calculatePriceDest(country);
		} else { return; }
	}
}

function calculateIngress(runFunction, noLoading) {
	var postdata = new Array();
	
	if(!noLoading) {showHideLoading(true);}
		
	postdata['number'] = document.getElementById('numclass').value.split('|')[1]+document.getElementById('numrange').value.split('|')[1];
	postdata['limit'] = 1;
	postdata['startat'] = 1;
	
	// alert("'"+postdata['number']+"'");
	
	// alert(runFunction);
	
	apilite_post(G_locationLink+'/callout/fullinfo.php', postdata, runFunction, '', 'displayAPIError', '');
}

function calculateLandlineOK(response, args) {
	setCostRevPrice(response.split('|')[13], response.split('|')[14], response.split('|')[15]);
}

function calculateIngressOther() {
	// First get ingress values
	// Then get egress value of landline
	// Take away the landline egress valye from ingress value
	// Then add cost of call to international or mobile
	
	calculateIngress('calculateEgressLandlineDef');
}

function calculateEgressLandlineDef(response) {
	var ingressCosts = new Array();
	var postdata = new Array();
	var args = new Array();
		
	ingressCosts['peak'] = response.split('|')[13];
	ingressCosts['offpeak'] = response.split('|')[14];
	ingressCosts['weekend'] = response.split('|')[15];
	
	postdata['number'] = G_skymarketNo;	// Skymarkets number to find cost per minute to a UK landline
	
	args['ingressCosts'] = ingressCosts;
	
	apilite_post(G_locationLink+'/extra_utils/cost_calc/includes/ajax/_egress.php', postdata, 'calculateEgressMobInt', args, 'displayAPIError', '');
}

function calculateEgressMobInt(response, args) {
	var newIngressCosts = new Array();
	var postdata = new Array();
	
	newIngressCosts = args['ingressCosts'];
	
	newIngressCosts['peak'] = (args['ingressCosts']['peak'] - response.split('|')[0]);
	newIngressCosts['offpeak'] = (args['ingressCosts']['offpeak'] - response.split('|')[1]);
	newIngressCosts['weekend'] = (args['ingressCosts']['weekend'] - response.split('|')[2]);
		
	// alert(newIngressCosts['peak']+'|'+newIngressCosts['offpeak']+'|'+newIngressCosts['weekend']);
	
	if(G_numberLookup) {
		postdata['number'] = stripSpaces(document.getElementById('toNumber').value);
		
	} else {
		var to = document.getElementById('to').value;
		
		if(to == 'mobile') {
			postdata['location_id'] = document.getElementById('network').value;
		} else { 
			postdata['location_id'] = document.getElementById('country').value;
		}
	}
		
	apilite_post(G_locationLink+'/extra_utils/cost_calc/includes/ajax/_egress.php', postdata, 'calculateEgressMobIntOK', newIngressCosts, 'calculateEgressMobIntError', '');
}

function calculateEgressMobIntOK(response, ingressCosts) {	
	var peakCost = parseFloat(ingressCosts['peak']) + parseFloat(response.split('|')[0]);
	var offpeakCost = parseFloat(ingressCosts['offpeak']) + parseFloat(response.split('|')[1]);
	var weekendCost = parseFloat(ingressCosts['weekend']) + parseFloat(response.split('|')[2]);
		
	setCostRevPrice(peakCost, offpeakCost, weekendCost);
}

function calculateEgressMobIntError(response, args) {
	if(response == 'destnumber non-valid') {
		alert('The destination number is invalid');
	} else {
		alert(response);
	}
	
	showHideLoading(false);
}

function setCTCPrice(ctc_peakCost, ctc_offpeakCost, ctc_weekendCost) {
	var ctc_peakCostDiv = document.getElementById('ctc_peakCostDiv');
	var ctc_offpeakCostDiv = document.getElementById('ctc_offpeakCostDiv');
	var ctc_weekendCostDiv = document.getElementById('ctc_weekendCostDiv');

	ctc_peakCostDiv.innerHTML = (ctc_peakCost > 0) ? (ctc_peakCost/1000)+'p' : 'Free';
	ctc_offpeakCostDiv.innerHTML = (ctc_offpeakCost > 0) ? (ctc_offpeakCost/1000)+'p' : 'Free';
	ctc_weekendCostDiv.innerHTML = (ctc_weekendCost > 0) ? (ctc_weekendCost/1000)+'p' : 'Free';
	
	showHideLoading(false);
}

function setCostRevPrice(peakCost, offpeakCost, weekendCost) {
	var peakCostCellTitle = document.getElementById('costRev_peakCostTitle');
	var offpeakCostCellTitle = document.getElementById('costRev_offpeakCostTitle');
	var weekendCostCellTitle = document.getElementById('costRev_weekendCostTitle');
	
	var peakCostCell = document.getElementById('costRev_peakCostCell');
	var offpeakCostCell = document.getElementById('costRev_offpeakCostCell');
	var weekendCostCell = document.getElementById('costRev_weekendCostCell');
	
	var costTextDiv = document.getElementById('costText');
	var costRevText = (String(peakCost).match(/^-/)) ? 'Revenue' : 'Cost';
	var ngn = document.getElementById('numclass').value.split('|')[1]+document.getElementById('numrange').value.split('|')[1];
	var toSelectValue = document.getElementById('to').value;
	var destination = '';
	
	var classSelect = document.getElementById('numclass');
	var classValue = classSelect.options[classSelect.selectedIndex].text;
	var disclaimerDiv = document.getElementById('disclaimer');
	var ngnDisclaimer = '';
	var to = document.getElementById('to').value;
	
	
	if(((classValue == '0800' || classValue == '0808') && to == 'landline') || classValue == '0870' || classValue == '0871' || classValue == '070') {
		ngnDisclaimer = '*';
	}
	
	if(G_numberLookup) {
		destination = document.getElementById('toNumber').value;
	} else {
		if(toSelectValue == 'landline') {
			destination = 'landline';
		} else if(toSelectValue == 'mobile') {
			var networkSelect = document.getElementById('network');
			destination = (networkSelect.options[networkSelect.selectedIndex].text)+' mobile';
		} else if(toSelectValue == 'international') {
			var countrySelect = document.getElementById('country');
			destination = countrySelect.options[countrySelect.selectedIndex].text;
		}	
	}
	
	if(document.getElementById('numclass').value.match(/070$/)) {
		if(peakCost<0) {peakCost=0;}
		if(offpeakCost<0) {offpeakCost=0;}
		if(weekendCost<0) {weekendCost=0;}
	}

	costTextDiv.innerHTML = costRevText+' to route numbers starting <span id="costTextNGN">'+ngn+ngnDisclaimer+'</span> to <span id="costTextDest">'+destination+'</span>';
		
	peakCostCellTitle.innerHTML = (String(peakCost).match(/^-/)) ? 'Peak revenue' : 'Peak cost';
	offpeakCostCellTitle.innerHTML = (String(offpeakCost).match(/^-/)) ? 'Off peak revenue' : 'Off peak cost';
	weekendCostCellTitle.innerHTML = (String(weekendCost).match(/^-/)) ? 'Weekend revenue' : 'Weekend cost';

	peakCostCell.className = (String(peakCost).match(/^-/)) ? 'costCellRev' : 'costCellCost';
	offpeakCostCell.className = (String(offpeakCost).match(/^-/)) ? 'costCellRev' : 'costCellCost';
	weekendCostCell.className = (String(weekendCost).match(/^-/)) ? 'costCellRev' : 'costCellCost';
	
	peakCostCell.innerHTML = String(peakCost/1000).replace('-', '')+'p';
	offpeakCostCell.innerHTML = String(offpeakCost/1000).replace('-', '')+'p';
	weekendCostCell.innerHTML = String(weekendCost/1000).replace('-', '')+'p';

	if((classValue == '0800' || classValue == '0808') && to == 'landline') {
		disclaimerDiv.style.display = 'block';
		disclaimerDiv.innerHTML = '* Call costs are indicative and may vary between 2ppm and 3.9ppm depending on the tariff you select.'
	} else if(classValue == '0870' || classValue == '0871') {
		disclaimerDiv.style.display = 'block';
		disclaimerDiv.innerHTML = '* '+classValue+' costs or revenue may vary depending on the number type and call volumes.';
	} else if(classValue == '070') {
// 		disclaimerDiv.style.display = 'block';
// 		disclaimerDiv.innerHTML = '* Values shown assume reseller status and therefore entitled to revenue.';
	} else {
		hideDisclaimer();
	}

	showHideLoading(false);
	
}

function displayAPIError(response, args) {
	alert(response);
	
	showHideLoading(false);
}

function validate(number) {
	var fields = {'numclass':	'Class,mandatory',
		      'numrange':	'Range,mandatory'};
	
	if(number) {
		fields['toNumber'] = 'Destination number,mandatory,phonenumber';
	}
		      
	var errorMsg = 'The following error(s) occurred:'+"\n\n";
	var error, errors = '';
			       
	for(fid in fields) {
		foptions = fields[fid].split(',');
		fn = foptions.shift();
		fv = document.getElementById(fid).value;
		validation = foptions;
		
		for(var i = 0; i < validation.length; i++) {
			switch(validation[i]) {
				case 'mandatory':
					error = v_mandatory(fn, fv);
					break;
				case 'phonenumber':
					error = v_phonenum(fn, fv);
					break;
			}
			
			if(error) {
				errors += ' - '+error+"\n";
				error = '';
				break;
			}
		}
	}
	
	if(errors) {
		alert(errorMsg+errors);
		return false;
	}
	
	return true;
}

function v_mandatory(fn, fv) {
	if(fv == '') {
		return fn+' is required';
	}
	
	return
}

function v_phonenum(fn, fv) {
	fv = fv.replace(' ', '');
	
	if(!fv.match(/^\+?[0-9]+$/)) {
		return fn+' can only contain numbers';
	} else if(fv.length < 10) {
		return fn+' is too short';
	}
	
	return;
}

function showHideLoading(show) {
	var loadingDiv = document.getElementById('loadingDiv');
	var costRevTable = document.getElementById('costRevTable');
	var findPriceButt = document.getElementById('loadingDiv');

	if(show) {
		// findPriceButt.src = 'images/loading.gif';
		// findPriceButt.blur();
		findPriceButt.disabled = true;
		costRevTable.style.display = 'none';
		loadingDiv.style.display = 'block';
	} else {
		// findPriceButt.src = 'images/butt_go.gif';
		findPriceButt.disabled = false;
		costRevTable.style.display = 'block';
		loadingDiv.style.display = 'none';
	}
}

function hideDisclaimer() {
	var disclaimerDiv = document.getElementById('disclaimer');
	
	disclaimerDiv.style.display = 'none';
}

function stripSpaces(str) {
	return str.replace(' ', '');
}
