////////////////////////
//
//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 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 = 'block';
	}else {
		if (document.layers) { // Netscape 4
		document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}	
	}


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

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 updateMapKey(cheapestPrice){

	var cheapestPriceInt = parseInt(cheapestPrice);
	var middlePriceInt = cheapestPriceInt + 2;
	var topPriceInt = cheapestPriceInt + 4;
	document.getElementById("mapKey").innerHTML = "Key:<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;
}


////////////////////////
//
//Get and List stations
//
////////////////////////
function getStations(){
        var maxLat = map.getBounds().getNorthEast().lat();
        var maxLng = map.getBounds().getNorthEast().lng();
        var minLat = map.getBounds().getSouthWest().lat();
        var minLng = map.getBounds().getSouthWest().lng();

        var request = GXmlHttp.create();
        var random_nocache = Math.random()*4;
	var url="api/getStationsByPriceAPI.php?county=" + currentCountyName + "&minLat=" + minLat + "&maxLat=" + maxLat + "&minLng=" + minLng + "&maxLng=" + maxLng + "&fuel=" + fuel + "&noCache="+random_nocache;
        request.open("Get", url, true);
        request.onreadystatechange = function()
                {

                        station = null;
                        station = new Array();

                        if (request.readyState == 4 && request.status == 200)
                        {

                                var xmlDoc = request.responseXML;
                                var markers = xmlDoc.documentElement.getElementsByTagName("station");
                                if(markers.length >0){
                                        cheapestPrice = 0;
                                        for (var i = 0; i < markers.length; i++)
                                        {
                                                station[i] = new Array();
                                                station[i]['point']=new GLatLng(parseFloat(markers[i].getAttribute("Lat")),parseFloat(markers[i].getAttribute("Lng")));
                                                station[i]['ID'] = markers[i].getAttribute("ID");
                                                //station[i]['Updater'] = markers[i].getAttribute("Updater");
                                                station[i]['brand'] = markers[i].getAttribute("brand");
                                                station[i]['price'] = markers[i].getAttribute("price");
                                                station[i]['fuel'] = markers[i].getAttribute("fuel");
                                                station[i]['trend'] = markers[i].getAttribute("trend");
                                                station[i]['addr1'] = markers[i].getAttribute("addr1");
                                                station[i]['addr2'] = markers[i].getAttribute("addr2");
                                                station[i]['dateupdated'] = markers[i].getAttribute("dateupdated");
                                                station[i]['stale'] = isStale(station[i]['dateupdated']);
                                                station[i]['dateupdatedshort'] = markers[i].getAttribute("dateupdatedshort");
                                                station[i]['Updater'] = markers[i].getAttribute("Updater");
                                                var markerColour = getColour(markers[i].getAttribute("price"),station[i]['stale']);
                                                station[i]['markerColour'] = markerColour;
                                                station[i]['marker'] = createMarker(station[i]['point'],i,markerColour);
                                                station[i]['Zone'] = markers[i].getAttribute("Zone");
                                                station[i]['County'] = markers[i].getAttribute("County");
                                         }
                                }

                                 tabulateStations();
                                 mapStations();
                        }
                }

        request.send(null);



}


function debugWriter(debugText){
	document.getElementById("debugText").innerHTML+=debugText;
}

function tabulateStations(){
	//This method writes 15 top valid stations to the stations table
	
	var oldtbody = document.getElementById("stationsTable").getElementsByTagName("tbody")[0];
	var tbody = document.createElement("tBody");


	var headerRow = document.createElement("tr");
	headerRow.setAttribute("class","stationListHeader");
	
	var pValue = document.createElement("td");
	pValue.innerHTML = "";
	headerRow.appendChild(pValue);

	var pStation = document.createElement("td");
	pStation.innerHTML = "<b>Station</b>";
	headerRow.appendChild(pStation);
	
	var pRoad = document.createElement("td");
	pRoad.innerHTML = "<b>Road</b>";
	headerRow.appendChild(pRoad);

	var pArea = document.createElement("td");
	pArea.innerHTML = "<b>Area</b>";
	headerRow.appendChild(pArea);	

	var pPrice = document.createElement("td");
	pPrice.innerHTML = "<b>Price</b>";
	headerRow.appendChild(pPrice);	

	var pUpdated = document.createElement("td");
	pUpdated.innerHTML = "<b>Updated</b>";
	headerRow.appendChild(pUpdated);	

	var pDetails = document.createElement("td");
	pDetails.innerHTML = "<b>Details</b>";
	headerRow.appendChild(pDetails);	

	tbody.appendChild(headerRow);

	
	
	var maxRows = station.length;
	
	var rowsWritten=0;
	
	//create outside loop to avoid memory leaks.
	var pmarkerColour;
	var pBrand;
	var pAddr1;
	var pAddr2;
	var pDateupdated;
	var fancyHTML;
	
	if(maxRows>0){
		for (var i = 0; i < station.length && rowsWritten < maxRows; i++)
		{
		//alert("RowsWritten"+rowsWritten+" station.length"+station.length);
			if(station[i]['stale']!="true")	
			{
				row = document.createElement("tr");
				pmarkerColour = document.createElement("td");
				pmarkerColour.setAttribute("width","12");
				pmarkerColour.setAttribute("valign","top");
				pmarkerColour.innerHTML = "<img src=\"images/" + station[i]['markerColour'] +"mini.png\" border=0/>";
				row.appendChild(pmarkerColour);		

				pBrand = document.createElement("td");
				pBrand.setAttribute("width","80");
				pBrand.setAttribute("valign","top");
				fancyHTML = "<a href=javascript:map.setZoom(14);map.setCenter(station['" + i + "']['point']);station['" + i + "']['marker'].openInfoWindowHtml(getMiniHTML('"+i+"'));>" + station[i]['brand'] + "</a>";
				pBrand.innerHTML = fancyHTML;
				row.appendChild(pBrand);

				pAddr1 = document.createElement("td");
				pAddr1.setAttribute("width","135");
				pAddr1.setAttribute("valign","top");	
				pAddr1.innerHTML = station[i]['addr1'];
				row.appendChild(pAddr1);		

				pAddr2 = document.createElement("td");
				pAddr2.setAttribute("width","85");
				pAddr2.setAttribute("valign","top");	
				pAddr2.innerHTML = station[i]['addr2'];
				row.appendChild(pAddr2);				

				pPrice = document.createElement("td");
				pPrice.setAttribute("width","30");
				pPrice.setAttribute("valign","top");
				pPrice.innerHTML = station[i]['price'];
				row.appendChild(pPrice);

				pUpdated = document.createElement("td");
				pUpdated.setAttribute("width","40");
				pUpdated.setAttribute("valign","top");				
				pUpdated.innerHTML = station[i]['dateupdatedshort'];
				row.appendChild(pUpdated);		

				pDetails = document.createElement("td");
				pDetails.setAttribute("width","30");
				pDetails.setAttribute("valign","top");
				fancyHTML = "<a href='viewStation.php?stationID="+station[i]['ID']+"'>Details</a>";
				pDetails.innerHTML = fancyHTML;
				row.appendChild(pDetails);

				tbody.appendChild(row);	
				rowsWritten++;
			}

		}
	
	}else{
		//nothing to display
		row = document.createElement("tr");
		var pNoStations = document.createElement("td");
		pNoStations.setAttribute("colspan","6");
		pNoStations.innerHTML = "There are no stations to display for this area";
		row.appendChild(pNoStations);		
		tbody.appendChild(row);	
	
	}	
	document.getElementById("stationsTable").replaceChild(tbody,oldtbody);
}

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 >  604800000){
		stale="true";	
	}else{
		stale="false";
	}

	return stale;
}

function updatePrices(form){
	var PriceNew = parseInt(form.Price.value);
	var PriceOld = parseInt(form.PriceOld.value);
	var FuelType = form.Type.value;
	var Trend;
	if(PriceNew>PriceOld){
		Trend="up";
	}else if(PriceNew<PriceOld){
		Trend="down";
	}else{
		Trend="stable";
	}
	
	var request = GXmlHttp.create();
	request.open("Get", "api/updatePriceAPI.php?ID="+form.ID.value+"&Price="+form.Price.value+"&Trend="+Trend+"&Type="+FuelType, true);
	request.onreadystatechange = function()
		{
		  	if (request.readyState == 4)
		  	{
		  	 	var xmlDoc = request.responseXML;
				var results = xmlDoc.documentElement.getElementsByTagName("Result");
				var result1 = results[0].getAttribute("result1");
				var result2 = results[0].getAttribute("result2");
				var errorReason = results[0].getAttribute("errorReason");
				var i = parseInt(form.StationIndex.value);
				
				if(result1 != "ok" || result2 != "ok"){
				
					var miniResult = "<fieldset>";
					miniResult += "<legend>Update Error</legend>"; 
					miniResult += "Error: " + errorReason; 
					miniResult += "</fieldset>";
					
					//open this new window				
					station[i]['marker'].openInfoWindowHtml(miniResult);				
				}else{
                                        //all ok so just screen!
                                        if(currentCountyName=="view"){
						map.clearOverlays();
						viewStationDetails(form.ID.value);	 
					}else if(currentCountyName=="mymap"){
                                                map.clearOverlays();
                                                getMyStations();
					}else{
                                                getStations("all", "all");
                                        }
					
				}
			}	
		}

	request.send(null);	
}



//Comments
function submitComment(form){

	var request = GXmlHttp.create();
	//Don't really care what the response is!
	request.open("Get", "api/addCommentAPI.php?StationID="+form.StationID.value+"&Comment="+form.Comment.value, true);
	request.send(null);	
	document.getElementById("commentCell").innerHTML = "Comment Submitted. Thank you!";
}
