////////////////////////
//
//Map drawing sections
//
////////////////////////

function makeIcon(currentColour)
{
	var icon = new GIcon();
	icon.image = "images/" + currentColour +".png";
	icon.shadow = "images/shadow.png";
	icon.iconSize = new GSize(13, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	return icon;
}


function getCounties(){

	var request = GXmlHttp.create();
	request.open("Get", "api/getCountiesAPI.php", true);
	request.onreadystatechange = function()
		{
		  	// Clear previous overlays so they don't build up with every map move!
		  	counties = new Array();
		  	if (request.readyState == 4)
		  	{
		  	 	var xmlDoc = request.responseXML;
				var countyResults = xmlDoc.documentElement.getElementsByTagName("county");
				var countyName = null;
				
				for (var i = 0; i < countyResults.length; i++)
				{
					countyName = countyResults[i].getAttribute("Name");
				     	counties[countyName] = new Array();
					counties[countyName]['Point'] = new GLatLng(parseFloat(countyResults[i].getAttribute("Lat")),parseFloat(countyResults[i].getAttribute("Lng")));						
				        counties[countyName]['Lat'] = countyResults[i].getAttribute("Lat");
				        counties[countyName]['Lng'] = countyResults[i].getAttribute("Lng");
				        counties[countyName]['Name'] = countyResults[i].getAttribute("Name");
				        counties[countyName]['ZoomLevel'] = countyResults[i].getAttribute("ZoomLevel");
				 }

 			 	 listCounties();

			}
		}

	request.send(null);
}



function listCounties(){
	
	
	var optionsHTML = "";
	var startSelectHTML = "<select id='county' name='county' onChange='changeCounty(this.form.county.value);'><option SELECTED>Select county</option>";
	var endSelectHTML = "</select>";
	var countyChoiceHTML;
	


	
	for (var countyName in counties)
	{
		countyChoiceHTML = "<option value='" + countyName + "'>" + countyName + "</option>";
		optionsHTML += countyChoiceHTML;
	}

	
	document.getElementById("countyList").innerHTML = startSelectHTML + optionsHTML + endSelectHTML;

}

function changeCounty(countyName){
	currentCountyName=countyName;
	getZones(currentCountyName);
	map.setZoom(17 - counties[currentCountyName]['ZoomLevel']);
	map.panTo(counties[currentCountyName]['Point']);
	setTimeout("getStations()",1000);
}


function getZones(countyName){
	var request = GXmlHttp.create();
	request.open("Get", "api/getZonesAPI.php?county="+countyName, true);
	request.onreadystatechange = function()
		{
		  	// Clear previous overlays so they don't build up with every map move!
		  	zones = null;
		  	zones = new Array();
		  	if (request.readyState == 4)
		  	{

		  	 	var xmlDoc = request.responseXML;
				var zoneResults = xmlDoc.documentElement.getElementsByTagName("zone");
				var zoneName = null;
				
				for (var i = 0; i < zoneResults.length; i++)
				{
					zoneName = zoneResults[i].getAttribute("Name");
				     	zones[zoneName] = new Array();
				        zones[zoneName]['ID'] = zoneResults[i].getAttribute("ID");
						zones[zoneName]['Point']= new GLatLng(parseFloat(zoneResults[i].getAttribute("Lat")),parseFloat(zoneResults[i].getAttribute("Lng")));							
				        zones[zoneName]['Lat'] = zoneResults[i].getAttribute("Lat");
				        zones[zoneName]['Lng'] = zoneResults[i].getAttribute("Lng");
				        zones[zoneName]['Name'] = zoneResults[i].getAttribute("Name");
				        zones[zoneName]['ZoomLevel'] = zoneResults[i].getAttribute("ZoomLevel");
				        zones[zoneName]['County'] = zoneResults[i].getAttribute("County");

				 }

				 listZones();
			}	
		}

	request.send(null);	
	

}

function listZones(){
	var oldSpan = document.getElementById("zoneList").getElementsByTagName("span")[0];
	var optionsHTML = "";
	var startSelectHTML = "<select id='zone' name='zone' onChange='viewZone(this.form.zone.value);'><option SELECTED>Select an area</option>";
	var endSelectHTML = "</select>";
	var zoneChoiceHTML;
	
	pZoneList = document.createElement("span");
	
	for (var zoneName in zones)
	{
	
		zoneChoiceHTML = "<option value='" + zoneName + "'>" + zoneName + "</option>";
		optionsHTML += zoneChoiceHTML;
	}
	pZoneList.innerHTML = startSelectHTML + optionsHTML + endSelectHTML;
	document.getElementById("zoneList").replaceChild(pZoneList,oldSpan);

	//document.getElementById("zoneList").innerHTML = startSelectHTML + optionsHTML + endSelectHTML;


}


function viewZone(zoneName){
	currentZoneName=zoneName;
	map.setZoom(17 - zones[zoneName]['ZoomLevel']);	
	map.panTo(zones[zoneName ]['Point']);
	setTimeout("getStations()",1000);
	
}




function mapStations(){
	// Clear previous overlays so they don't build up with every map move!
	map.clearOverlays();
	
	for (var i = 0; i < station.length ; i++)
	{
		map.addOverlay(station[i]['marker']);
	}

}



//Price Management

function isStale(updatedDate){

	var then = new Date();
	then.setUTCFullYear(parseInt(updatedDate.substring(0,4)));
	then.setUTCMonth(parseInt(updatedDate.substring(5,7)-1,10));
	then.setUTCDate(parseInt(updatedDate.substring(8,10),10));
	

	var now = new Date();
	var diffen = now.getTime() - then.getTime();
	var stale;
	if(diffen >  259200000){
		stale="true";	
	}else{
		stale="false";
	}

	return stale;
}

function setMapView(){

    var mapBounds = new GLatLngBounds(new GLatLng(minLat,maxLng),new GLatLng(maxLat,minLng));
    var mapCenter = mapBounds.getCenter();
    var mapZoom = map.getBoundsZoomLevel(mapBounds);

    map.setCenter(mapCenter, mapZoom);
}

function getColour(price,stale){
  var colour;
  //alert(cheapestPrice + firstBand);

  	
  if(stale == "true"){
  		colour = "stale";
  }else{
  	if(cheapestPrice==0){
  		cheapestPrice=price;
  		updateMapKey(cheapestPrice);
  	}
	if(parseInt(price) <= parseInt(cheapestPrice) + firstBand)
	{
		//If cheapest
		colour = "green";
	}else if(parseInt(price) <= parseInt(cheapestPrice) + secondBand){
		//If within second band of prices
		colour = "amber";  	
	}else{
		//All the rest
		colour = "red";
	}
   }
   return colour
}

function getMiniHTML(i){
	var minihtml = "<iframe width='200' height='350' style='margin: 0px 0px 0px 0px' border='0' frameborder='0'  scrolling='No' src='miniViewStation.php?stationID="+station[i]['ID'] +"'></iframe>"; 
	return minihtml;
}



function updateMapKey(cheapestPrice){

	var cheapestPriceInt = parseInt(cheapestPrice);
	var middlePriceInt = cheapestPriceInt + 2;
	var topPriceInt = cheapestPriceInt + 4;
	document.getElementById("mapKey").innerHTML = "<img src='images/greenmini.png'>"+cheapestPriceInt+".9c-"+middlePriceInt+".9c <img src='images/ambermini.png'>" + middlePriceInt + ".9c-" + topPriceInt + ".9c <img src='images/redmini.png'>" + topPriceInt +".9c and up! <img src='images/stalemini.png'>Old price";

}

// Create a marker for each station 
function createMarker(point,i,markerColour)
{
  var icon;
  if(markerColour=="stale"){
  	icon= staleIcon;
  }else if(markerColour=="amber"){
  	icon= amberIcon;
  }else  if(markerColour=="green"){
  	icon= greenIcon;
  }else  if(markerColour=="red"){
  	icon= redIcon;
  }
  
  var marker = new GMarker(point,icon);
  // Show this markers index in the info window when it is clicked
  GEvent.addListener(marker, "click", function() 
  {
	marker.openInfoWindowHtml(getMiniHTML(i));
  }
       );
      
  return marker;
}

function showWholeCountry(){
        map.setCenter(new GLatLng(53.5,-7.8), 7);
        currentCountyName ='all';
        currentZoneName = 'all';
        getStations();
}

function changeFuel(fuelType){
        fuel=fuelType;
	if(fuelType=="petrol"){
		highlightCell("petrolTab");
		unhighlightCell("dieselTab");	
		unhighlightCell("e85Tab");
		unhighlightCell("biodieselTab");		
	} else if(fuelType=="diesel") {
		unhighlightCell("petrolTab");
		highlightCell("dieselTab");	
		unhighlightCell("e85Tab");
		unhighlightCell("biodieselTab");		
	} else if(fuelType=="e85") {
		unhighlightCell("petrolTab");
		unhighlightCell("dieselTab");	
		highlightCell("e85Tab");
		unhighlightCell("biodieselTab");		
	} else {
		unhighlightCell("petrolTab");
		unhighlightCell("dieselTab");	
		unhighlightCell("e85Tab");
		highlightCell("biodieselTab");		
	}
        getStations();
}

function unhighlightCell(id){
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.background= '#f2f2f2';
	}else {
		if (document.layers) { // Netscape 4	
		document.id.background= '#f2f2f2';
		}
		else { // IE 4
			document.all.id.style.background= '#f2f2f2';
		}
	}	
	
}

function highlightCell(id){
	//safe function to show an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.background= '#FFFFFF';
	}else {
		if (document.layers) { // Netscape 4
		document.id.background= '#FFFFFF';
		}
		else { // IE 4
			document.all.id.style.background= '#FFFFFF';
		}
	}	
}




function updatePrice(form, row){
	var PriceNew = parseFloat(form.Price.value);
	var PriceOld = parseFloat(form.oldPrice.value);
	var FuelType = form.type.value;


	
	var url = "api/updatePriceAPI.php?ID="+form.ID.value+"&Price="+form.Price.value+"&Type="+FuelType;
	var request = GXmlHttp.create();
	request.open("Get", url , true);
	request.onreadystatechange = function()
		{
		  	if (request.readyState == 4)
		  	{
		  	 	var xmlDoc = request.responseXML;
				var results = xmlDoc.documentElement.getElementsByTagName("Result");
				var success = results[0].getAttribute("Success");
				var error = results[0].getAttribute("Error");
				
				if(success != "True"){
				  alert("Price update failed:" + error);				
				}else{
				  changeSpanValue(FuelType + 'PriceSpan'+row, PriceNew + "c");
				  changeSpanValue(FuelType + 'DateSpan'+row, "Just now");				  
				  hideCell(FuelType + 'Form' + row);
				  showCell(FuelType + 'Price' + row);
				  
				}
			}	
		}

	request.send(null);	

}

///////////////////
// Add Station Commands
///////////////////
function addStation(form){

	if(form.lat.value.length==0){
		alert("Please click on map to mark Petrol Station's location!");
	}else if(form.county.value=="Select a county"){
		alert("Please choose a county !");
	}else if(form.zone.value=="Select an area"){
		alert("Please choose an area!");
	}else if(form.name.value.length==0){
		alert("Please enter a station name!");		
	}else if(form.addr1.value.length==0){
		alert("Please enter a station address line 1!");				
	}else if(form.addr2.value.length==0){
		alert("Please enter a station address line 2!");
        }else if(form.petrol.value.length==0){
                alert("Please enter a petrol price!");
        }else if(form.diesel.value.length==0){
                alert("Please enter a diesel price!");
	}else{
		form.submit();
	}
}
	
	
	////
	//Update station commands
	//
function updateStation(form){

	if(form.lat.value.length==0){
		alert("Please click on map to mark Petrol Station's location!");
	}else if(form.name.value.length==0){
		alert("Please enter a station name!");		
	}else if(form.addr1.value.length==0){
		alert("Please enter a station address line 1!");				
	}else if(form.addr2.value.length==0){
		alert("Please enter a station address line 2!");
	}else{
		form.submit();
	}
}

function hideCell(id){
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}else {
		if (document.layers) { // Netscape 4	
		document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}	
	
	}

function showCell(id){
	//safe function to show an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = '';
	}else {
		if (document.layers) { // Netscape 4
		document.id.display = '';
		}
		else { // IE 4
			document.all.id.style.display = '';
		}
	}	
	}

function changeSpanValue(id, value){
	//safe function to show an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).innerHTML = value;
	}else {
		document.all.id.innerHTML = value;
	}	
}
