// Init global vars
var tmpCount = 0;
var div = null;
var map = null;
var adcontrol = null;
var maplogo = null;
var maphelp = null;
var warningKey = null;
var timestamp = null;
var radarTrans = 0.7;
var currentCond = null;
var aniMode = false;
var animatedLayers = new Array();
var ip = null;
var startServer = Math.floor(4*Math.random());
//var dataServer = new Array("server5.mytiwi.com","server6.mytiwi.com","server6.mytiwi.com","server6.mytiwi.com");
var dataServer = new Array("weatherdata0.mytiwi.com","weatherdata1.mytiwi.com","weatherdata2.mytiwi.com","weatherdata3.mytiwi.com");
var loopPin = null;
var quadImages = new Array();
var weatherIcons = new Array("/images/mapicons/partly_sun.png","/images/mapicons/snow.png","/images/icons/sun.png");

// Default weather layer settings
var layerSettings = new Array();
layerSettings.NumServers = 4;
layerSettings.Bounds = [new VELatLongRectangle(new VELatLong(50,-130),new VELatLong(20,-55))];
layerSettings.MinZoomLevel = 1;
layerSettings.MaxZoomLevel = 14;
layerSettings.Opacity = 0.5;
layerSettings.ZIndex = 100;

// Weather layer preloader
function ImagePreloader(images, callbackfn)
{
	this.callbackfn = callbackfn;
	this.nLoaded = 0;
	this.nProcessed = 0;
	this.aImages = new Array;
	this.nImages = images.length;

	for ( var i = 0; i < images.length; i++ )
		this.preload(images[i]);
}

ImagePreloader.prototype.preload = function(image)
{
	var oImage = new Image();
	this.aImages.push(oImage);

	oImage.onload = ImagePreloader.prototype.onload;
	oImage.onerror = ImagePreloader.prototype.onerror;
	oImage.onabort = ImagePreloader.prototype.onabort;

	oImage.oImagePreloader = this;
	oImage.bLoaded = false;
	oImage.src = image;
}

ImagePreloader.prototype.onComplete = function()
{
	this.nProcessed++;
	if ( this.nProcessed == this.nImages ){
		this.callbackfn(this.aImages, this.nLoaded);
	}
}

ImagePreloader.prototype.onload = function()
{
	this.bLoaded = true;
	this.oImagePreloader.nLoaded++;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onerror = function()
{
	this.bError = true;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onabort = function()
{
	this.bAbort = true;
	this.oImagePreloader.onComplete();
}

// Show hide static layers
function ShowLayer(name, active)
{
	// Detect layer change during animation
	if( aniMode == true )
	{
		StopLoop();
		//LoadLoopLayers();
	}

	if (active == true){
		if(name == "Conditions"){
			currentCond.Show();
		}else if(name == "Warnings"){
			ToggleLayer(name, active);
			AddWarningKey();
		}else{
			ToggleLayer(name, active);
		}
	}else{
		if(name == "Conditions"){
			currentCond.Hide();
		}else if(name == "Warnings"){
			ToggleLayer(name, active);
			RemoveMyControl(warningKey );
			warningKey = null;
		}else{
			ToggleLayer(name, active);
		}
	}

}

// Hide/show animated layers
function ToggleLayer(name, active)
{
	if (active == true){
		map.ShowTileLayer(name);
	}else{
		map.HideTileLayer(name);
	}
}

// Hide/restore visible layers
function HideRestoreLayers(active){
	animatedLayers["fronts"] = $("#fronts").attr('checked');
	animatedLayers["radar"] = $("#radar").attr('checked');
	animatedLayers["cloud"] = $("#cloud").attr('checked');
	animatedLayers["temp"] = $("#temp").attr('checked');
	animatedLayers["warnings"] = $("#warnings").attr('checked');

	if(active == true){
		if(animatedLayers["fronts"] != null){
			ToggleLayer("Fronts", false);
		}		
		if(animatedLayers["cloud"] != null){
			ToggleLayer("Cloud", false);
		}
		if(animatedLayers["radar"] != null){
			ToggleLayer("Radar", false);
		}
		if(animatedLayers["temp"] != null){ 
			ToggleLayer("Temp", false);
		}
		if(animatedLayers["warnings"] != null){ 
			ToggleLayer("Warnings", false);
		}

		RemoveMyControl(timestamp);
		timestamp = null;
	}else{
		if(animatedLayers["fronts"] != null){
			ToggleLayer("Fronts", true);
		}		
		if(animatedLayers["cloud"] != null){
			map.ShowTileLayer("Cloud");
		}
		if(animatedLayers["radar"] != null){
			map.ShowTileLayer("Radar");
		}
		if(animatedLayers["temp"] != null){ 
			ToggleLayer("Temp", true);
		}
		if(animatedLayers["warnings"] != null){ 
			ToggleLayer("Warnings", true);
		}

		AddTimeStamp();
	}
}

// Add a weather layer to the map
function LoadLayer(layerID, opacity, visible)
{
	var tileSourceSpec = new VETileSourceSpecification(layerID, "http://weatherdata%2.mytiwi.com/weathertile.aspx?key=%4&l=" + layerID);
	//var tileSourceSpec = new VETileSourceSpecification(layerID, "http://server6.mytiwi.com/weathertile.aspx?key=%4&l=" + layerID);
	
	tileSourceSpec.Bounds		= layerSettings.Bounds;
	tileSourceSpec.NumServers	= layerSettings.NumServers;
	tileSourceSpec.MinZoomLevel = layerSettings.MinZoomLevel;
	tileSourceSpec.MaxZoomLevel = layerSettings.MaxZoomLevel;
	tileSourceSpec.ZIndex		= layerSettings.ZIndex;
	layerSettings.ZIndex		= layerSettings.ZIndex + 1;
	
	if( opacity == "" ){
		tileSourceSpec.Opacity	= layerSettings.Opacity;
	}else{
		tileSourceSpec.Opacity	= opacity;
	}
	map.AddTileLayer(tileSourceSpec, visible);
}

// Load current map layers
function LoadLayers()
{
		LoadLayer("Temp", radarTrans, false);
		LoadLayer("Cloud", "0.6", false);
		LoadLayer("Cloude", "0.7", false);
		LoadLayer("Radar", radarTrans, true);
		LoadLayer("Warnings", "0.8", false);
		LoadLayer("Fronts", "1.0", false);

		UpdateSliders();
}

//Block Map UI
function BlockMapUI()
{
	$('#Map').block({
		message: '<img src=/System/ContentModule/WeatherMap/images/loading.gif align=absmiddle> &nbsp; <span class=Loading>Loading Weather Data</span>',
		css: { border: '2px solid #4d739d', padding: '10px'}
	});
}

// Load animation layer
function LoadLoopLayers()
{
	if( aniMode == false ){
		aniMode = true;
		var timeSpan = $("#loop").val();
		
		// Find active layer
		var layerType = $("#layerType").val();
				
		var tmpRadarTrans = $('#slider1').slider('value');
		radarTrans = tmpRadarTrans * 0.01

		//var quadImages = new Array;

		var view = map.GetMapView();
		var query = "?lat1=" + view.TopLeftLatLong.Latitude + 
			"&lon1=" + view.TopLeftLatLong.Longitude + 
			"&lat2=" + view.BottomRightLatLong.Latitude + 
			"&lon2=" + view.BottomRightLatLong.Longitude + 
			"&lvl=" + map.GetZoomLevel() +
			"&l=" + layerType +
			"&t=" + timeSpan;

		
		var quadImage = "http://" + dataServer[startServer] + "/weatherloopstamp.aspx" + query;
		quadImages[0] = quadImage;
		
		BlockMapUI();

		//startServer++
		//if( startServer > 4 ) startServer = 0;

		if( quadImages.length > 0 ){
			ip = new ImagePreloader( quadImages, PreloadComplete);
			
		}else{
			aniMode = false;
			$('#Map').unblock(); 
		}
	}
}

// On complete hide the loading screen/play 
function PreloadComplete(a, b)
{
	$('#Map').unblock();
	HideRestoreLayers(true);
	PlayLoop();
}

// Animate the map
function PlayLoop()
{
	var pixel = new VEPixel(13, 13);
	var LL = map.PixelToLatLong(pixel);
	var point1 = new VELatLong( LL.Latitude, LL.Longitude);
							
	loopPin = new VEShape(VEShapeType.Pushpin, point1);
	loopPin.SetCustomIcon("<div id='WeatherLoop'><img src='" + quadImages[0] + "' /></div>");
	map.AddShape(loopPin);
	$('#WeatherLoop').css("opacity", radarTrans);		
}

// Stop animating the map
function StopLoop()
{
	
	if( aniMode == true ){
		aniMode = false;
		HideRestoreLayers(false);
		$('#Map').unblock();	
	}
	if( loopPin != null ){
		map.DeleteShape(loopPin);
	}
}

function PanZoomHandler(e)
{
	if( aniMode == true ){
		StopLoop();
		LoadLoopLayers();
	}
}

function MouseHandler(e)
{
	if (e.eventName == "onclick"){
		if (e.rightMouseButton){
			var x = e.mapX;
			var y = e.mapY;
			
			pixel = new VEPixel(x, y);
			var LL = map.PixelToLatLong(pixel);

			// Start Geoname
			//$.get('/System/WebServices/WwLatlong_zip.aspx?lat=' + LL.Latitude + '&lon=' + LL.Longitude, function(data){
				//var $curCity = $(data).find('placename');
				//var cityName = $curCity.text();

				//var $curState = $(data).find('adminCode1');
				//var stateName = $curState.text();

				//var $curZip = $(data).find('postalcode');
				//var zipName = $curZip.text();

				$.get('/System/WebServices/WwFindIcao.aspx?lat=' + LL.Latitude + '&lon=' + LL.Longitude, function(data){
					var $curStation = $(data).find('Icao');
					var stationID = $curStation.text();

					//if( zipName == "" || zipName == "00" ){

						$curCity = $(data).find('City');
						cityName = $curCity.text();

						$curState = $(data).find('State');
						stateName = $curState.text();

						$curZip = $(data).find('Zip');
						zipName = $curZip.text();

					//}

					var strCond = "";

					if(stationID != ""){
						$.get('/System/WebServices/WwCurrent_obs.aspx?stationID=' + stationID, function(data){
							var $curWeather = $(data).find('weather');
							var skyCondStr = $curWeather.text();

							strCond = "<table border=0 cellpadding=5 cellspacing=0><tr><td valign=top colspan=2>";
							strCond += cityName + ', ' + stateName + " " + zipName + '</td></tr><tr><td valign=top>\n';
							strCond += "<b>Sky Conditon:</b><br>" + $curWeather.text() + '<br><br>\n';

							var $curTemp = $(data).find('temp_f');

							strCond += "<b>Temp:</b> " + $curTemp.text() + '&deg;F<br>\n';
							strCond += "</td><td><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' width='91' height='85' id='weather_icon'><param name='movie' value='/System/ContentModule/WeatherWindow/Flash/weather_icon.swf?skyCond=" + skyCondStr + "' /><embed src='/System/ContentModule/WeatherWindow/Flash/weather_icon.swf?skyCond=" + skyCondStr + "' width='91' height='85' name='weather_icon' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'/></object></td></tr></table>";
							strCond += "<div align='center'><a href='/default.aspx?zip=" + zipName + "'>View Forecast</a> | <a href='#'>Save This Location</a></div>";

							var shape = new VEShape(VEShapeType.Pushpin, LL);
							shape.SetTitle('Weather Conditions For:');
							shape.SetDescription(strCond);
							shape.SetCustomIcon( weatherIcons[0] );
							currentCond.AddShape(shape);
							$('#conditions').attr('checked', 'true');
							currentCond.Show();
							map.ShowInfoBox(shape);
						});
					}
				});
			// End Geoname
			//});
		}
	}
}

// Add an ad map control above the map
function AddAdControl()
{
	if (adcontrol == null)
	{
	   adcontrol = document.createElement("div"); 
	   adcontrol.id = "adControl";
	   adcontrol.style.top ="12px"; 
	   adcontrol.style.left = "640px"; 
	   adcontrol.style.border = "1px solid #4d739d";
	   adcontrol.innerHTML = "<a href='#' target='_blank'><img src='/System/ContentModule/WeatherMap/Images/cc_ad.jpg' border='0'></a>";  

	   map.AddControl(adcontrol);
	}
}

// Add logo to the map
function AddMapLogo()
{
	if (maplogo == null)
	{
	   maplogo = document.createElement("div"); 
	   maplogo.id = "myMaplogo";
	   maplogo.style.top ="330px"; 
	   maplogo.style.left = "110px"; 
	   maplogo.style.border = "none";
	   maplogo.style.color = "#ffffff";
	   maplogo.innerHTML = "<span style=font-family:arial;font-size:9px;>Powered By:</span><br><a href=http://www.mytiwi.com target=_parent><img src=/System/ContentModule/WeatherMap/Images/map_logo.png border=0></a>";  
	   //maplogo.innerHTML = "<img src=/System/ContentModule/WeatherMap/Images/map_logo.png border=0>";  

	   map.AddControl(maplogo);
	}
}

// Add warning key to the map
function AddWarningKey()
{
	if (warningKey == null)
	{
	   warningKey = document.createElement("div"); 
	   warningKey.id = "myWarningKey";
	   warningKey.style.top ="50px"; 
	   warningKey.style.left = "50px"; 
	   warningKey.style.border = "none";
	   warningKey.innerHTML = "<img src=/System/ContentModule/WeatherMap/Images/warnings_key3.png border=0>";  

	   map.AddControl(warningKey);
	}
}

// Add help icon to the map
function AddMapHelp()
{
	if (maphelp == null)
	{
	   maphelp = document.createElement("div"); 
	   maphelp.id = "myMapHelp";
	   maphelp.style.top ="60px"; 
	   maphelp.style.left = "14px"; 
	   maphelp.style.border = "none";
	   maphelp.innerHTML = "<a href=/help.aspx target=_parent><img src=/System/ContentModule/WeatherMap/Images/map_help.gif border=0></a>";  

	   map.AddControl(maphelp);
	}
}

// Add helpo to the map
function AddTimeStamp()
{
	if (timestamp == null)
	{
	   timestamp = document.createElement("div"); 
	   timestamp.id = "myTimeStamp ";
	   timestamp.style.top ="0px"; 
	   timestamp.style.left = "573px"; 
	   timestamp.style.border = "none";
	   timestamp.innerHTML = "<img src=http://weatherdata" + startServer + ".mytiwi.com/currentupdate.aspx?l=radar border=0>";  

	   map.AddControl(timestamp);
	}
}

// Add a shim to a mapcontrol 
function AddShim(el)
{
	tmpCount++
	var shim = document.createElement("iframe");
	shim.id = "myShim" + tmpCount;
	shim.frameBorder = "0";
	shim.style.position = "absolute";
	shim.style.zIndex = "10";
	shim.style.top  = el.offsetTop;
	shim.style.left = el.offsetLeft;
	shim.width  = el.offsetWidth;
	shim.height = el.offsetHeight;
	el.shimElement = shim;
	el.parentNode.insertBefore(shim, el);
}

// Remove a control from the map
function RemoveMyControl( mapControl )
{
	if (mapControl != null)
	{
	   map.DeleteControl(mapControl);
	   mapControl = null;
	}
}

// Handle the layer transparency sliders 
function UpdateSliders()
{
	$('#slider1').slider({
		minValue: 0,
		maxValue: 100,
		startValue: radarTrans * 100,
		slide: function(e,ui) {
			if( ui.value && 4 ){
				var layer = map.GetTileLayerByID("Radar");
				var tmpTransVal = ui.value * 0.01;
				layer.Opacity = tmpTransVal;
				$('#WeatherLoop').css("opacity", tmpTransVal);	
				if( aniMode == false && $("#radar").attr('checked') == true ){
					map.ShowTileLayer("Radar");
				}
			}
		},
		stop: function(e,ui) {
			var layer = map.GetTileLayerByID("Radar");
			var tmpTransVal = ui.value * 0.01;
			layer.Opacity = tmpTransVal;
			$('#WeatherLoop').css("opacity", tmpTransVal);
			if( aniMode == false && $("#radar").attr('checked') == true ){
				map.ShowTileLayer("Radar");
			}
		}
	});

	$('#slider2').slider({
		minValue: 0,
		maxValue: 100,
		startValue: radarTrans * 100,
		slide: function(e,ui) {
			if( ui.value && 4 ){
				var tmpVal = ui.value * 0.01;
				var clayer = map.GetTileLayerByID("Cloud");
				clayer.Opacity = tmpVal;

				var tlayer = map.GetTileLayerByID("Temp");
				tlayer.Opacity = tmpVal;
				
				if( aniMode == false && $("#cloud").attr('checked') == true ){
					map.ShowTileLayer("Cloud");
				}
				if( aniMode == false && $("#temp").attr('checked') == true ){
					map.ShowTileLayer("Temp");
				}
			}
		},
		stop: function(e,ui) {
			var tmpVal = ui.value * 0.01;
			var clayer = map.GetTileLayerByID("Cloud");
			clayer.Opacity = tmpVal;

			var tlayer = map.GetTileLayerByID("Temp");
			tlayer.Opacity = tmpVal;

			if( aniMode == false && $("#cloud").attr('checked') == true ){
				map.ShowTileLayer("Cloud");
			}
			if( aniMode == false && $("#temp").attr('checked') == true ){
				map.ShowTileLayer("Temp");
			}
		}
	});
}

// Load the map, set its location and load weather layers
function LoadMap()
{
	window.onresize = SetLayerPosition;
	
	map = new VEMap('Map');
	map.SetDashboardSize(VEDashboardSize.Tiny);

	// Map types : Road, Shaded, Aerial, Hybrid
	map.LoadMap(new VELatLong(38.44498466889472, -93.69149625000000), 4, VEMapStyle.Hybrid, false, VEMapMode.Mode2D, true);

	LoadLayers();

	map.AttachEvent("onclick",MouseHandler);
	//map.AttachEvent("onendpan", PanZoomHandler);
	//map.AttachEvent("onendzoom", PanZoomHandler);
	map.AttachEvent("onendpan", StopLoop);
	map.AttachEvent("onendzoom", StopLoop);

	currentCond = new VEShapeLayer();
	map.AddShapeLayer(currentCond);

	AddMapLogo();
	AddMapHelp();
	AddTimeStamp();

	if( mapLat != "" && mapLon != "" ){
		addEventIcon( mapLat, mapLon );
	}
}

function addEventIcon( lat, lon ){
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon) );
	shape.SetTitle('Event Location:');
	currentCond.AddShape(shape);
	$('#conditions').attr('checked', 'true');
	currentCond.Show();
	map.SetCenterAndZoom(new VELatLong(lat, lon), "12");
	map.ShowInfoBox(shape);
}

// Get window size
function GetWindowSize()
{
	var myWidth = 0, myHeight = 0;

	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
		//myWidth = window.innerWidth;
		//myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}

	if (myWidth > 0){
		var result = new Array();
		result[0] = myWidth;
		result[1] = myHeight;
		return result;
	}else{
		return null;
	}
}

// set the left position of the map overlays
function SetLayerPosition()
{
	var browserSize = GetWindowSize();
	if (browserSize != null)
	{
		var curWidth = (browserSize[0] - 794)>>1;
		if( curWidth > 0 ){
		if( curWidth && 4 ){
			if( timestamp != null ){
				var timeWidth = curWidth + 583;
				timestamp.style.left = timeWidth + "px"; 
			}
			if( maphelp != null ){
				var helpWidth = curWidth + 24;
				maphelp.style.left = helpWidth + "px"; 
			}
			if( maplogo != null ){
				var logoWidth = curWidth + 120;
				maplogo.style.left = logoWidth + "px"; 
			}
		}
		}
	}
}

// Document ready check
$(document).ready(function()
{
	LoadMap();
});