// create the gateway object
oProcess = new Gateway("WeatherProcess.aspx", false);

var mapApplication = null;
var timerId = 0;	
var splitChar = ";";

//*** PAGE
function InitPage(mapdiv)
{
	InitializeMaps(mapdiv);
	InitProcessGateway();
	
	// select first location
	var firstLocation = new GPoint(-77.0361, 38.8910);
	SelectLocation(firstLocation);
}

function MapScript()
{
/* substitute for:
		<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAftNcN9_GTmQYDP7CrvfiMBQM4lSDQSi0Q-I8imoYbw1d5rjh3xSNMJieqzAjtzueA1nksvfV7fMHTA"
			type="text/javascript"></script>
*/			
	//var theKey = "ABQIAAAAftNcN9_GTmQYDP7CrvfiMBQM4lSDQSi0Q-I8imoYbw1d5rjh3xSNMJieqzAjtzueA1nksvfV7fMHTA"; // weather.novospark.com
	var theKey = "ABQIAAAAftNcN9_GTmQYDP7CrvfiMBQhduo_vDNGHQeEMEk6pUkSOxqslxTmcOXeH8XrqiKMrF2f7ENBlkQeKw";
	var scriptTag = '<' + 'script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=' + theKey + '">'+'<'+'/script>';
	document.write(scriptTag);
}

//*** MAPS
function NovoSparkMaps(mapdiv) {
  this.zoom = 4;
  this.longitude = 38.50;
  this.latitude = -98.00;
  this.centerPoint = new GLatLng(this.longitude, this.latitude);
  this.container = document.getElementById(mapdiv);
  this.map = new GMap2(this.container, {draggableCursor:"crosshair"});
  this.map.disableDoubleClickZoom();
	this.map.addControl(new GSmallMapControl());  
  this.map.setCenter(this.centerPoint, this.zoom);
  this.map.setMapType(G_NORMAL_MAP); // G_NORMAL_MAP; G_SATELLITE_MAP; G_HYBRID_MAP; G_PHYSICAL_MAP;  
  
  
  GEvent.bind(this.map, "click", this, this.onMapClick);
  GEvent.bind(this.map, "mousemove", this, this.onMouseMove);
  GEvent.bind(this.map, "zoomend", this, this.onZoomEnd);
  GEvent.bind(this.map, "dragend", this, this.onDragEnd);
}
    
NovoSparkMaps.prototype.onMapClick = function(overlay, point) 
{
	ClearWeatherRecord();
  this.longitude = point.x;
  this.latitude = point.y;   
  this.map.clearOverlays();
	this.map.addOverlay(new GMarker(point));  
  oProcess.sendPacket("MapClickPosition" + splitChar + point.x + splitChar + point.y, false);
}

NovoSparkMaps.prototype.onMouseMove = function(point) 
{
  this.longitude = point.x;
  this.latitude = point.y;  
  
  //SetSpanText("LongitudeLatitude", "Longitude: " + this.longitude.toFixed(6) + ", Latitude: " + this.latitude.toFixed(6));
}

NovoSparkMaps.prototype.onZoomEnd = function (oldLevel, newLevel) 
{
  oProcess.sendPacket("MapZoomEnd" + splitChar + oldLevel + splitChar + newLevel, false);
}

NovoSparkMaps.prototype.onDragEnd = function () 
{
  oProcess.sendPacket("MapDragEnd", false);
}

function SelectLocation(point) 
{
	if(null != mapApplication) 
	{				
		mapApplication.onMouseMove(point);
		mapApplication.onMapClick(null, point);
	}
}

function InitializeMaps(mapdiv) 
{
  if (GBrowserIsCompatible()) 
  {
    mapApplication = new NovoSparkMaps(mapdiv);
  }
}

function UnInitializeMaps() 
{
	GUnload();
}

//*** GATEWAY
function InitProcessGateway() 
{
	// define the function[s] to run when a packet has been received from the server
	oProcess.onReceive = function ()
	{
		var doError = false;
		// no error by default
		ShowError("");
		
		var data = String(this.received).split(splitChar);
		
		if(null == data)
			return;
			
		if(0 == data.length)
			return;
		
		if(data[0] == "WeatherRecord")
		{
			UpdateWeatherRecord(data);
			return;
		}
			
		if(data[0] == "ExplanationRead")
		{
			return;
		}

		if(data[0] == "MapZoomEnd")
		{
			return;
		}

		if(data[0] == "MapDragEnd")
		{
			return;
		}
				
		if("Error" == data[0])
		{
			doError = true;
			if(1 < data.length)
				ShowError(data[1]);
			// do not return: update image				
		}

		//*** start image source
		var img = document.getElementById("ImageScenery");					
		var imageSource = "WeatherImageProvider.aspx?ImgWidth=" + img.width + "&ImgHeight=" + img.height + 
			"&Longitude=" + mapApplication.longitude + "&Latitude=" + mapApplication.latitude +
			"&Cash=" + (new Date()).getTime();
			
		if(true == doError) 
		{
			imageSource = imageSource + "&ImgMessage='Please try again'";
		}			
		img.src = imageSource;
		//*** end image source

		// always update weather record			
		if(false == doError) {
			oProcess.sendPacket("GetWeatherRecord", false);
		} else {
			ClearWeatherRecord();
		}
	};
}

function XBrowserMousePosition(e) {
	this.posx = 0;
	this.posy = 0;
	
	var e = e || window.event;
	
	if (e.pageX || e.pageY) 	{
		this.posx = e.pageX;
		this.posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		this.posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		this.posy = e.clientY + document.body.scrollTop	+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
}

function OnImageClick(e) 
{

	var e = e || window.event;
  if (!e) return;	
		
	var eX = e.offsetX; //  || e.layerX);// - e.clientX;
	var eY = e.offsetY; //  || e.layerY);// - e.clientY;
	if(!eX) 
	{
		var page = new XBrowserMousePosition(e);
		var eTarget = e.target || e.srcElement;

		eX = page.posx;
		eY = page.posy;	
	
		var elm = eTarget;
		while(elm) {
			eX = eX - ((elm.offsetLeft)? elm.offsetLeft : 0);
			eY = eY - ((elm.offsetTop)? elm.offsetTop : 0);	
			elm = elm.offsetParent;
		}
	}
		
	//oProcess.sendPacket("ImageClickPosition" + splitChar + window.event.offsetX + splitChar + window.event.offsetY, false);
	oProcess.sendPacket("ImageClickPosition" + splitChar + eX + splitChar + eY, false);
}

function SendExplanationRead()
{
	oProcess.sendPacket("ExplanationRead", false);
}

function SetSpanText(spanid, text)
{
	var oSpan = document.getElementById(spanid);
	if(null != oSpan)
		oSpan.innerHTML = text;
}

function SetImageSource(imgid, path)
{
	var oImg = document.getElementById(imgid);
	if(null != oImg)
		oImg.src = path;
}

function ShowError(text)
{
	SetSpanText("labelError", text);
	if(0 < text.length)
		ClearWeatherRecord();
}

function ClearWeatherRecord()
{
		SetSpanText("weatherLongitude", "&nbsp;");
		SetSpanText("weatherLatitude", "&nbsp;");
		SetSpanText("weatherCity", "&nbsp;");
		SetSpanText("weatherForecastPeriod", "&nbsp;");
		SetSpanText("weatherDate", "&nbsp;");
		SetSpanText("weatherTemperature", "&nbsp;");
		SetSpanText("weatherDewPointTemperature", "&nbsp;");
		SetSpanText("weatherApparentTemperature", "&nbsp;");
		SetSpanText("weatherWindSpeed", "&nbsp;");
		SetSpanText("weatherCloudCover", "&nbsp;");
		SetSpanText("weatherHumidity", "&nbsp;");
		SetSpanText("weatherPrecipitation", "&nbsp;");
		SetSpanText("weatherSnow", "&nbsp;");
		SetSpanText("weatherWindSpeedGust", "&nbsp;");
		SetImageSource("weatherIcon", "../images/na.gif");
}

function UpdateWeatherRecord(data)
{
		SetSpanText("weatherLongitude", data[1]);
		SetSpanText("weatherLatitude", data[2]);		
		SetSpanText("weatherCity", data[3]);
		SetSpanText("weatherForecastPeriod", data[4]);
		SetSpanText("weatherDate", data[5]);
		SetSpanText("weatherTemperature", data[6]);
		SetSpanText("weatherDewPointTemperature", data[7]);
		SetSpanText("weatherApparentTemperature", data[8]);
		SetSpanText("weatherWindSpeed", data[9]);
		SetSpanText("weatherCloudCover", data[10]);
		SetSpanText("weatherHumidity", data[11]);
		SetSpanText("weatherPrecipitation", ('' == data[12])? 'not available' : data[12]);
		SetSpanText("weatherSnow", ('' == data[13])? 'not available' : data[13]);
		SetSpanText("weatherWindSpeedGust", ('' == data[14])? 'not available' : data[14]);
		SetImageSource("weatherIcon", ('' == data[15])? "../images/na.gif" : data[15]);
}