//global Objects
var geocoder = {};
var gCurrentGeoCode = {}; //eg {lat:'53.68420', lon:-1.50410'}

//global arrays
var geocode_results = new Array();
var locations = new Array();

//global hash for the petrol types - maps the fuel types to the field names returned from mulitmap database
//note: 'modal_price_3' has been left out of the hash as it has no corresponding fuel type
var fuelTypes = {super_unleaded:'modal_price_1', unleaded:'modal_price_2', LRP:'modal_price_4', premium_diesel:'modal_price_5', diesel:'modal_price_6', LPG:'modal_price_7'};

//global strings
var no_postcode_available = "This location doesn't have a postcode recorded\n\nAs a result, it's location cannot be located on the Multimap";
var cheapest_petrol_loaded = "The cheapest fuel station has been automatically loaded within a 10 mile radius of the selected waypoint";
var no_petrol_stations = "Sorry no fuel stations found in the immediate area";
var problem_communicating_with_multimap = "Sorry there has been a problem communicating with the Multimap server so no results can be displayed, please try again later";
var multimap_server_busy = "The Multimap route service encountered an unexpected error whilst servicing your request, please try again. If this problem persists please contact Multimap Customer Services";
var multimap_locations_outside_uk = "The requested locations are outsize of the UK";
var multimap_start_end_the_same = "Route wasn't performed as the start and end locations provided are the same, please change";
var multimap_geocoding_issue = "One or both of the locations could not be found. Check that the information entered is correct and that the locations are inside of the UK";
var multimap_route_not_found = "A route could not be found between the two points check that the information entered is correct and that the locations are inside of the UK";
var arrive_at_your_destination = "Arrive at your destination";

var max_zindex = 1000;
var debug = false;

function init(){
	if(debug){alert("init()");}
	
    //create new geocoder object specifying a callback function
    geocoder = new MMGeocoder(processPetrolResults);
}

function setGlobalGeoCode(lat,lon){
	if(debug){alert("setGlobalGeoCode()");}
	
    gCurrentGeoCode = {lat:lat,lon:lon};
}

function cleanUp(){
	if(debug){alert("cleanUp()");}
	
    geocode_results = new Array();
    locations = new Array();
}

//performs a spacial search based on the global lat and lon stored
//callBack - function to call when the search returns
//dataSource - database to source the search on eg.'mm.clients.vx_petrolprices' [optional]
//maxDistance - max distance for the search to look, [optional] - default bounds of map
//maxCount - max number of results to return, [optional] - default 10

function performSpacialSearch(callBack,dataSource,maxDistance,maxCount ){
	if(debug){alert("performSpacialSearch()");}
	
    var searcher = new MMSearchRequester(callBack);

    search = new MMSearch();

    //if(maxCount){ search.count = maxCount;}
    search.count = maxCount || 10;

    if(maxDistance){
        search.max_distance = maxDistance;
        search.distance_units = 'miles';
    }
    else{
        search.bounding_box = mapviewer.getMapBounds();
    }
	
    search.data_source = dataSource;
    search.point = new MMLatLon(gCurrentGeoCode.lat,gCurrentGeoCode.lon);
    searcher.search(search);
}

//performs a search for fuel stations within 5km of point
//type: type of fuel;
//resultsDiv: reference to the div display the results in;
//displayText [optional] - text to display to the user for the fuel type - default
function searchForFuelStations(type,displayText){
	if(debug){alert("searchForFuelStations()");}
	
    displayText = displayText || type;
	
    var callBack = _displayFuelStations.bind([{fuelType:type, displayText:displayText}]);

    performSpacialSearch(callBack, 'mm.clients.vx_petrolprices', 10, 200);
}

function tidy_fuel_name(fuel){
	if(debug){alert("tidy_fuel_name()");}
	
    switch(fuel){
        case "super_unleaded": return "Super Unleaded"; break;
        case "unleaded": return "Unleaded"; break;
        case "LRP": return "LRP"; break;
        case "premium_diesel": return "Premium Diesel"; break;
        case "diesel": return "Diesel"; break;
        case "LPG": return "LPG"; break;
    }
}

function tidy_brand(brand){
	if(debug){alert("tidy_brand()");}

    switch(brand.toUpperCase()){
        case "SAINSBURYS": return "SAINSBURY\'S"; break;
		default: return(brand.replace(/_/g," ").toUpperCase());
    }
}

function sortByFuelPrice(a,b){	
    var x = parseInt(a.Price);
    var y = parseInt(b.Price);

    return((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function getBrandImage(brand){
	if(debug){alert("getBrandImage()");}

    var brandCounter = 1;

    // Know brands with images
    var fuelBrand = new Array();
	
    //default
    fuelBrand[0] = "petrolpump";
	
    //most common
    fuelBrand[1] = "bp";
    fuelBrand[2] = "shell";
    fuelBrand[3] = "asda";
    fuelBrand[4] = "tesco";
	
    //others
    fuelBrand[5] = "elf";
    fuelBrand[6] = "esso";
    fuelBrand[7] = "gulf";
    fuelBrand[8] = "jet";
    fuelBrand[9] = "morrisons";
    fuelBrand[10] = "murco";
    fuelBrand[11] = "pace";
    fuelBrand[12] = "q8";
    fuelBrand[13] = "sainsburys";
    fuelBrand[14] = "sommerfield";
    fuelBrand[15] = "tesco_express";
    fuelBrand[16] = "tesco_extra";
    fuelBrand[17] = "texaco";
    fuelBrand[18] = "total";
    fuelBrand[19] = "waitrose";

    // loop through array and if a match is found, return it.
    while (fuelBrand[brandCounter] != null) {
        if (brand == fuelBrand[brandCounter]) { return(fuelBrand[brandCounter]); }
        brandCounter++;
    }

    return(fuelBrand[0]);
}

function _displayFuelStations(resultsArray){
	if(debug){alert("_displayFuelStations()");}
		
    var description = '';
    var image;
    var prices = '';
    var totalFound = 0;
    var results = resultsArray[0];
    var cheapestRecords = new Array(results.totalRecordCount);
	if(debug){alert("totalRecordCount=" + results.totalRecordCount);}
    //this[0] comes from the bind() function when the callBack was setup
    var boundVars = this[0];
    var fuelType = boundVars.fuelType;
    var fuelDisplay = boundVars.displayText;

    //alert(results.totalRecordCount);
    if(results && results.totalRecordCount > 0){
        var records = results.records;

        for(var i=0, len=records.length; i<len; i++){
            var currRec = records[i];

            if(currRec.brand.toUpperCase()!= "CLOSED"){
                var fuelField = fuelTypes[fuelType];

                //push the petrol price data onto the array of all locations found
                if(currRec[fuelField] && currRec[fuelField] != '0'){
                    // alert("totalFound: " + totalFound + ", " + fuelField + ", " + currRec[fuelField]);
                    cheapestRecords[totalFound] = {Price:currRec[fuelField], Brand:currRec.brand.replace(/ /, "_"), Description:currRec.site_name, Point:currRec.point, Distance:currRec.distance};
                    totalFound++;
                }
            }
        }
		
		if(cheapestRecords.length > totalFound) cheapestRecords.length = totalFound;

        //sort the prices to get the best 5
        cheapestRecords.sort(sortByFuelPrice);
		
        if(cheapestRecords.length > 5) cheapestRecords.length = 5;

		var obj_wrapper = get_element("fuel_prices");
		var fuel_location_original = obj_wrapper.petrol_tool_location.value;
		var fuel_type = obj_wrapper.petrol_tool_fuel_type;

		fuel_location = fuel_location_original.toLowerCase();
		fuel_location = fuel_location.replace(/ /g,"_");
		
		//create heading
		var obj_heading = document.createElement("H4");
		//obj_heading.innerHTML = "<strong>" + tidy_fuel_name(fuel_type.options[fuel_type.selectedIndex].value) + ", " + fuel_location_original + "</strong>";
		obj_heading.innerHTML = "<strong>" + tidy_fuel_name(fuel_type.options[fuel_type.selectedIndex].value) + ": " + fuel_location_original.toUpperCase() + "</strong>";
		obj_wrapper.innerHTML = "";

		//create pump image
		var obj_image = document.createElement("IMG");
		obj_image.src = (ie6) ? "images/petrol_tool/pump.gif" : "images/petrol_tool/pump.png";
		obj_image.style.position = "absolute";
		obj_image.style.top = "0px";
		obj_image.style.left = "0px";
		obj_wrapper.appendChild(obj_image);

        //add the markers and petrol prices div
        if (cheapestRecords.length > 0){
			//create results list
			var obj_results_list = document.createElement("UL");
			var obj_results_item;
			var obj_results_span;
			var obj_results_link;

			for(var i=0; i<cheapestRecords.length; i++){
	            //get brand icon
	            var displayBrandIcon = getBrandImage(cheapestRecords[i].Brand.toLowerCase());

	            price = new Number(cheapestRecords[i].Price.replace(/(\d*)(\d$)/, '$1.$2'));
	            image = '<img src="images/journey_planner/fuel_stations_icons/' + displayBrandIcon + '.gif" class="fuel_station_icon" style="width: 18px; height: 18px; border:none;";/>';
	            description = cheapestRecords[i].Description + '<br/>';
	            prices = tidy_fuel_name(fuelType) + ': ' + price;
	            priceLinkText = fuelDisplay + ' ' + price;
			
				//create <li>'s
				obj_results_item = document.createElement("LI");
				obj_results_span = document.createElement("SPAN");
			
				//handle first record being bold
				//obj_results_span.innerHTML = (i == 0) ? "<strong>" + price + "</strong>" : price;
				obj_results_span.innerHTML = price;
						
				obj_results_link = document.createElement("A");
			
				//handle first record being bold
				if(ie6){
					obj_results_link.innerHTML = cheapestRecords[i].Description.substr(0,14);
				}
				else{
					obj_results_link.innerHTML = cheapestRecords[i].Description.substr(0,16);
				}
			
				obj_results_link.href = "on_the_road.html?tab=3&fuelType=" + fuelType + "&location=" + fuel_location + "&offset=" + (i);
				obj_results_link.title = "View map of " + cheapestRecords[i].Description;
				obj_results_item.appendChild(obj_results_span);
				obj_results_item.appendChild(obj_results_link);
						
				if(i == (cheapestRecords.length-1))
				{
					obj_results_item.className = "last";
				}
						
				//add list item to parent ul
				obj_results_list.appendChild(obj_results_item);
    	    }
		}
		else
		{
			// Deal with case of no results
			var obj_results_list = document.createElement("SPAN");
			obj_results_list.innerHTML = "Sorry, no results found today for <br />that location &amp; fuel type.<br />&nbsp;";
			obj_results_list.className = "no_results";
		}
		
		//create float clearer (before submit button)
		var obj_float_clear = document.createElement("BR");
		obj_float_clear.className = "clear";
		
		//create "search again" submit button
		var obj_submit = document.createElement("INPUT");
		obj_submit.type = "button";
		obj_submit.id = "submit";
		obj_submit.value = "Search again";
		obj_submit.onclick = function(){top.location.href = 'index.html';}
		
		obj_wrapper.appendChild(obj_heading);
		obj_wrapper.appendChild(obj_results_list);
		obj_wrapper.appendChild(obj_float_clear);
		obj_wrapper.appendChild(obj_submit);
    } else {
		alert('Sorry, no results found today matching that location and fuel type');
	}
}

function processPetrolResults(){
	if(debug){alert("processPetrolResults()");}
	
    geocode_results = geocoder.result_set;

    var geocode_error = geocoder.error_code;

	var petrolTypeSel = get_element("petrol_tool_fuel_type");
	
	var fuelType = petrolTypeSel.options[petrolTypeSel.selectedIndex].value;
	var displayText	= petrolTypeSel.options[petrolTypeSel.selectedIndex].text;
	
	set_cookie("fuelType",fuelType);
    var address = geocode_results[0];
	var geo_code = address.coords;
	var geoLat = geo_code.lat;
	var geoLon = geo_code.lon
	
	setGlobalGeoCode(geoLat,geoLon);
	locations.push(address);
	searchForFuelStations(fuelType, displayText);
}

function get_petrol_prices(){
	if(debug){alert("get_petrol_prices()");}
	
	init();
	
	//setup variables
	var placeToFind = get_element("petrol_tool_location").value;
	
	set_cookie("location",placeToFind);
	var geocode_status, message, results_panel;
	var results = new Array();
	var markers = new Array();
	var max_results = 1;
	
	// Setup address object
	var address = new MMAddress();
	
	address.street = "";
	address.city = "";
	address.state = "";
	address.postal_code = "";
	address.country_code = "UK";
	address.qs = placeToFind;
	
	//lear previous
	cleanUp();
		
	//perform geocode search for town, address or postcode
	geocoder.count = max_results;
	geocoder.geocode(address);
}