var YUD = YAHOO.util.Dom;
var YUE = YAHOO.util.Event;
var YUC = YAHOO.util.Connect;

// prototype style $() function
function $(el){
	return YUD.get(el);
};

var map, directions, start, destination, from, to, distance, price, priceAdjust = [0,0,0], maxDistance = [0,0,0], adjustUp = [0,0,0];
var localSearch = new Array(2);

function mw_getCoOrds(){
	$("helpwindow").style.display = 'none';
	start = $('start').value;
	destination = $('destination').value;
	if(start != '' && destination != ''){
		usePointFromPostcode(start, setFrom, 0);
		usePointFromPostcode(destination, setTo, 1);
		$("infowindow").style.display = 'block';
		var pause = setTimeout(calculateDistance, 1000);
	}else{
		alert('You must enter a Pickup and Destination to get a quote!');
	};
};

function usePointFromPostcode(postcode, callbackFunction, ind) {
	
	// code here intercepts airports, etc. saving localsearch
	var lowerpcode = postcode.toLowerCase();
	
	switch(lowerpcode){
		case 'stansted airport' :
			var point = new GLatLng('51.889913','0.261151');
			priceAdjust[ind] = 50;
			maxDistance[ind] = 39;
			callbackFunction(point);
			break;
		case 'stansted' :
			var point = new GLatLng('51.889913','0.261151');
			priceAdjust[ind] = 50;
			maxDistance[ind] = 35;
			callbackFunction(point);
			break;
		case 'london city airport' :
			var point = new GLatLng('51.503963','0.047118');
			priceAdjust[ind] = 50;
			maxDistance[ind] = 35;
			callbackFunction(point);
			break;
		case 'city airport' :
			var point = new GLatLng('51.503963','0.047118');
			priceAdjust[ind] = 50;
			maxDistance[ind] = 35;
			callbackFunction(point);
			break;
		case 'gatwick airport' :
			var point = new GLatLng('51.156234','-0.162241');
			priceAdjust[ind] = 65;
			maxDistance[ind] = 65;
			callbackFunction(point);
			break;
		case 'gatwick' :
			var point = new GLatLng('51.156234','-0.162241');
			priceAdjust[ind] = 65;
			maxDistance[ind] = 65;
			callbackFunction(point);
			break;
		case 'heathrow airport' :
			var point = new GLatLng('51.471559','-0.452145');
			priceAdjust[ind] = 75;
			maxDistance[ind] = 80;
			callbackFunction(point);
			break;
		case 'heathrow' :
			var point = new GLatLng('51.471559','-0.452145');
			priceAdjust[ind] = 75;
			maxDistance[ind] = 80;
			callbackFunction(point);
			break;
		case 'luton airport' :
			var point = new GLatLng('51.878469','-0.369202');
			priceAdjust[ind] = 75;
			maxDistance[ind] = 80;
			callbackFunction(point);
			break;
		case 'luton' :
			var point = new GLatLng('51.878469','-0.369202');
			priceAdjust[ind] = 75;
			maxDistance[ind] = 80;
			callbackFunction(point);
			break;
		default:
			mw_geoCode(postcode, callbackFunction, ind);
			break;
	};
		
};

function mw_geoCode(sAddress, callbackFunction, ind){
	
	var handleSuccess = function(o){
		try{
			var oGeoCode = YLJ.parse(o.responseText);
		}
		catch(e){
			alert('Invalid JSON data!');
			googleGeoCode(sAddress, callbackFunction, ind);
		};
		if(oGeoCode.status == 'found'){
			priceAdjust[ind] = oGeoCode.priceAdjust;
			maxDistance[ind] = oGeoCode.maxDistance;
			adjustUp[ind] = oGeoCode.adjustUp;
			var point = new GLatLng(oGeoCode.geoLat,oGeoCode.geoLng);
			callbackFunction(point);
		};
		if(oGeoCode.status == 'new'){
			googleGeoCode(sAddress, callbackFunction, ind);
		}
	};
	
	var handleFailure = function(o){
			alert("ERROR");
		};

	var callback = {
		success: handleSuccess,
		failure: handleFailure
	};
	
	YUC.asyncRequest('GET', 'scripts/geocode.asp?act=get&loc=' + escape(sAddress.toLowerCase()), callback, '');

};

function googleGeoCode(sAddress, callbackFunction, ind){
		priceAdjust[ind] = 0;
		maxDistance[ind] = 0;
		adjustUp[ind] = 0;
		localSearch[ind] = new GlocalSearch();
		localSearch[ind].setSearchCompleteCallback(null, 
		function() {
			if (localSearch[ind].results[0]) {		
				var resultLat = localSearch[ind].results[0].lat;
				var resultLng = localSearch[ind].results[0].lng;
				mw_saveGeoCode(sAddress, resultLat, resultLng);
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
			}else{
				mw_logGeoCode(sAddress, ind);
			};
		});	
		localSearch[ind].execute(sAddress + ", UK");
}

function mw_saveGeoCode(sAddress, geoLat, geoLng){
	
	var handleSuccess = function(o){
//		alert(o.responseText);
	};
	
	var handleFailure = function(o){
		alert("ERROR");
	};

	var callback = {
		success: handleSuccess,
		failure: handleFailure
	};
	
	var url = 'scripts/geocode.asp?act=put&loc=' + escape(sAddress.toLowerCase()) + '&lat=' + geoLat + '&lng=' + geoLng
	YUC.asyncRequest('GET', url, callback, '');
};

function mw_logGeoCode(sAddress, ind){
	
	var handleSuccess = function(o){
		var res = o.responseText;
		res = res.replace(/xx/g, '\n');
		alert(res);
	};
	
	var handleFailure = function(o){
		alert("ERROR");
	};

	var callback = {
		success: handleSuccess,
		failure: handleFailure
	};
	
	var url = 'scripts/geocode.asp?act=log&loc=' + escape(sAddress.toLowerCase()) + "&ind=" + ind;
	YUC.asyncRequest('GET', url, callback, '');
};


function setFrom(point){
	from = point.toUrlValue();
}

function setTo(point){
	to = point.toUrlValue();
}

function calculateDistance(){
	
	var textDirections = from + ' to ' + to;
	
	map = new GMap2($("map"));
	map.addControl(new GLargeMapControl());
	
	directions = new GDirections(map);
	directions.load(textDirections);
	
	GEvent.addListener(directions, "load", onGDirectionsLoad);
	
}

function calculatePrice(rawdist){
	
	var dist = parseFloat(rawdist);
	// basic price calculation
	
	switch(true){
		case (dist <= 15): 
			price = dist * 2;
			break;
		case (dist <= 30): 
			price = ((dist - 15) * 1.33) + 30;
			break;
		default: 
			price = (dist - 30) + 49.95;
			break;
	};
	
	// adjustUp[2] is key for which location has upward adustment: 1 = from, 2 = to, 3 = both
	adjustUp[2] = adjustUp[0] + (2 * adjustUp[1]);
		
	switch(adjustUp[2]){
		
		case 0: // No upward adjustment	
		
			// get largest price adjustment if one exists
			priceAdjust[2] = Math.max(priceAdjust[0], priceAdjust[1]);
			maxDistance[2] = Math.max(maxDistance[0], maxDistance[1]);

			if(priceAdjust[2] != 0){
			
				if(price > priceAdjust[2]){
					if(dist <= maxDistance[2]){
						price = priceAdjust[2];
					}else{
						price = (priceAdjust[2] + (dist - maxDistance[2]));
					};
				};
				
			};
			break;
		
		case 1: // from has upward adjustment			
			price = price + priceAdjust[0];
			break;
		
		case 2: // to has upward adjustment
			price = price + priceAdjust[1];
			break;
		
		case 3: // from and to both have upward adjustment
			price = price + priceAdjust[0] + priceAdjust[1];
			break;
		
	};
	
	for(var x = 0; x < 3; x++){
		priceAdjust[x] = 0;
		maxDistance[x] = 0;
	};
	
	return price.toFixed(2).toString();

};

function onGDirectionsLoad(){
	distance = parseFloat(directions.getDistance().html);
	price = calculatePrice(distance);
//	var html = '<p>' + directions.getSummaryHtml() + ' which we quote as &pound;' + price + '<' + '/p><p>(' + from + ') ' + start + '<br />(' + to + ') ' + destination + '<' + '/p>';
	var html = '<p>' + directions.getSummaryHtml() + ' which we quote as &pound;' + price + ' &#8224;<' + '/p>';
	$("priceinfo").innerHTML = html;
	$("frmPickup").value = $("start").value;
	$("frmDestination").value = $("destination").value;
	$("frmDistance").value = distance + ' miles';
	$("frmPrice").value = price;
	$("container").style.left = '15px';
};

function mw_close(choice){
	switch(choice){
		case 'map':
			$("priceinfo").innerHTML = '';
			$("infowindow").style.display = 'none';
			break;
		case 'help':
			$("helpwindow").style.display = 'none';	
			break;
	};
	$("container").style.left = '-3000px';
};

function mw_showHelp(){
	$("helpwindow").style.display = 'block';
	$("container").style.left = '15px';
};

function mw_removeNonNumericChars(string){
	string = string.replace(/[\D]+/g, '');
	return string;
};

var submitSuccess = function(o){
	if(o.responseText == 'OK'){
		$('priceinfo').innerHTML = '<h2>Your details have been received - you will get a call shortly.<' + '/h2>';
		setTimeout(function(){
			$('frmName').value = '';
			$('frmPhone').value = '';
			$('frmPickup').value = '';
			$('frmDestination').value = '';
			$('frmDistance').value = '';
			$('frmPrice').value = '';
//			mw_close('map');
		}, 5000);
		return true;
	}else{
		alert('Oops there\'s been a problem. \nPlease try again - if this persists, you\'ll have to phone us.');
	};
};

var submitFailure = function(o){
	alert('Oops there\'s been a problem. \nPlease try again - if this persists, you\'ll have to phone us.');
};

function mw_submit(){
	var nm = $('frmName').value, pn = $('frmPhone').value, err = '';
	if(nm == '')err += 'You must supply a Name\n';
	if(pn == '')err += 'You must supply a Phone Number\n';
	if(err != ''){
		alert(err);
		return false;
	}else{
		var callback = {
			success: submitSuccess,
			failure: submitFailure,
			cache: false
		};
		var sURL = 'scripts/sendsms.asp';
		YUC.setForm('frmSubmitDetails');
		var request = YUC.asyncRequest('POST', sURL, callback);
		return true;
	};
};

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
	} else {
		window.onunload = function() {
			oldonunload();
			func();
		}
	}
};

addUnLoadEvent(GUnload);