/*************************

Virtual Earth map of Hurricane Rita
by Poly9 - http://www.poly9.com
v. 1.2

Contact: msnbc-rita@poly9.com

*************************/

var hurricaneData;
var hurricaneNews;
var newsPanel;

var trafficCams;

var realPoints = [];
var realLine;
var forecastPoints = [];
var forecastLine;

var todayFullDate = new Date();
var milliTimezoneOffset = todayFullDate.getTimezoneOffset() * 60 * 1000;

var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

function dateSort(a,b) {
	return a[0] - b[0];
}

function newsDateSort(a,b) {
	return b[2] - a[2];
}

function loadTrafficCams() {
	var request = GetXmlHttp();
	request.open("GET", 'trafficCams.js');
	
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			trafficCams = eval(request.responseText);
			trafficCams.pop();
			
			showTrafficCams();
		}
	};		
	request.send(null);
}

function loadHurricaneData() {
	var request = GetXmlHttp();
	request.open("GET", 'data.js');
	
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			hurricaneData = eval(request.responseText);
			hurricaneData.pop();
			
			hurricaneData.sort(dateSort);

			for(var i = 0; i < hurricaneData.length; i++)
			{
				if(hurricaneData[i][2])
					realPoints.push(hurricaneData[i][1][1], hurricaneData[i][1][0]);
				else
					forecastPoints.push(hurricaneData[i][1][1], hurricaneData[i][1][0]);
			}
			
			if(forecastPoints && forecastPoints.length > 1 && realPoints && realPoints.length > 1)
			{
				forecastPoints.reverse();
				forecastPoints.push(realPoints[realPoints.length - 1], realPoints[realPoints.length - 2]);
				forecastPoints.reverse();
			}


			showHurricaneData();
		}
	};		
	request.send(null);
}

function loadHurricaneNews() {
	var request = GetXmlHttp();
	request.open("GET", 'dataNews.js');
	
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			hurricaneNews = eval(request.responseText);
			hurricaneNews.pop();
			hurricaneNews.sort(newsDateSort);
			
			var newsDate = new Date();
			newsDate.setTime(hurricaneNews[0][2].getTime() - milliTimezoneOffset);
			var newsDateString = days[newsDate.getDay()].substr(0,3) + " " + newsDate.getDate() + ' ' + months[newsDate.getMonth()].substr(0,3);
			var newsHourString = ((''+newsDate.getHours()).length < 2? '0':'') + newsDate.getHours() + ':';
			newsHourString += ((''+newsDate.getMinutes()).length < 2? '0':'') + newsDate.getMinutes();

			newsPanel.SetToolbar("Updated: "+newsDateString +' '+ newsHourString);
			showHurricaneNews();
		}
	};		
	request.send(null);
}

function showTrafficCams()
{
	if(map.GetZoomLevel() < 9)
	{
		for(var i = 0; i < trafficCams.length; i++)
		{
			//map.RemovePushpin('traffic_'+i);
			if (document.getElementById('traffic_'+i))
				document.getElementById('traffic_'+i).style.display = 'none';
		}
		if (!document.getElementById('traffic_cam')) {
			//map.AddPushpin('traffic_cam', 29.762589, -95.368881, 30, 21, 'camPinMini', '<img src="biggercam.png" onclick="zoomInHouston()" onMouseOver="showNewsHint(-1)" onMouseOut="delayedHintClose()" onload="correctPNG(this);"/>', 5);
			var pt = new VELatLong(29.762589, -95.368881);
			var pin = new VEPushpin('traffic_cam', pt, 'biggercam.png', '', '');
			map.AddPushpin(pin);
		}
		document.getElementById('traffic_cam').style.display = 'block';
	}
	else
	{
		try {
		 document.getElementById('traffic_cam').style.display = 'none';
		} catch(e) {
		}
		//map.RemovePushpin('traffic_cam');

		for(var i = 0; i < trafficCams.length; i++)
		{
			if (!document.getElementById('traffic_'+i)) {
			//	map.AddPushpin('traffic_'+i, trafficCams[i][0][0], trafficCams[i][0][1], 42, 30, 'camPin', '<img src="cam.png" onclick="showTrafficCam(\''+trafficCams[i][1]+'\')" onload="correctPNG(this);"/>', 5);
				var pt = new VELatLong(trafficCams[i][0][0], trafficCams[i][0][1]);
				var pin = new VEPushpin('traffic_' + i, pt, 'cam.png', '', '');
				map.AddPushpin(pin);
			}
			document.getElementById('traffic_'+i).style.display = 'block';
		}
	}
}

function showTrafficCam(url)
{
	var myTrafficCamWin = window.open(url, 'trafficCam', 'width=340,height=280,toolbar=no,status=no,resizable=no');
	myTrafficCamWin.focus();
}

function zoomInHouston()
{
	map.SetCenter( 29.762589, -95.168881);
	map.SetZoom(9);
	
	showTrafficCams();
}

function showHurricaneNews()
{
	var newsPanelData = "<br>";
	
	for(var i = 0; i < hurricaneNews.length; i++)
	{
		newsPanelData += "<a href='http://msnbc.msn.com/id/"+hurricaneNews[i][0]+"/' target=_blank>"+hurricaneNews[i][1]+"</a><br><br>";
	}
	
	document.getElementById('newsPanelItems').innerHTML = newsPanelData;
}

function ShowNewsPanel()
{
	var introFrame=document.getElementById('newsPanelDiv');
	//introFrame.style.display = 'block';
	var height = GetWindowHeight() - 15;
	var p=new VE_Panel_o("newsp",5,10,180,height,"blue",72,"Hurricane Rita news",introFrame,"","",false);
	
//	p.SetFooter("<center><b><a style='font-size:12px' href='http://poly9.viavirtualearth.com/Poly9/MSNBC/' target=_blank>See all MSNBC news</a></b></center>");
	p.SetFooter("<center><a href='http://virtualearth.msn.com' target=_blank>Powered by MSN Virtual Earth</a></center>");
	
	p.body.className="VE_Panel_o_body_help";

	p.onTitleClick=function(e)
	{
		e.srcPanel.Toggle();
	};
	

	newsPanel = p;
}


function showHurricaneData()
{
/*	if(!(navigator.userAgent.toLowerCase().indexOf('safari') != -1 || navigator.userAgent.toLowerCase().indexOf('gecko') != -1))
	{
		if(realPoints && realPoints.length > 2)
		{
			realLine = new MPolyline(realPoints, 'red'); 
			
			if(realLine)
				map.addPolyline(realLine);
		}
		
		if(forecastPoints && forecastPoints.length > 2)
		{
			forecastLine = new MPolyline(forecastPoints, '#888'); 
	
			if(forecastLine)
				map.addPolyline(forecastLine);
		}		
	}*/

	for(var i = 0; i < hurricaneData.length; i++)
	{
		var imgSrc;
		var pinC;
		
		if(hurricaneData[i][2])
		{
			// real point
			
			switch(hurricaneData[i][5])
			{
				case 'tD':
					imgSrc = "hImg/tD.png";
					pinC = 'tDPin';
					pinW = 14;
					pinH = 26;
				break;
				case 'tS':
					imgSrc = "hImg/tS.png";
					pinC = 'tSPin';
					pinW = 18;
					pinH = 34;
				break;
				case 'h0':
				case 'h1':
					imgSrc = "hImg/h1.png";
					pinC = 'hPin';
					pinW = 24;
					pinH = 45;
				break;
				case 'h2':
					imgSrc = "hImg/h2.png";
					pinC = 'hPin';
					pinW = 24;
					pinH = 45;
				break;
				case 'h3':
					imgSrc = "hImg/h3.png";
					pinC = 'hPin';
					pinW = 24;
					pinH = 45;
				break;
				case 'h4':
					imgSrc = "hImg/h4.png";
					pinC = 'hPin';
					pinW = 24;
					pinH = 45;
				break;
				case 'h5':
					imgSrc = "hImg/h5.png";
					pinC = 'hPin';
					pinW = 24;
					pinH = 45;
				break;
			}
		}
		else	// forecast
			imgSrc = "hImg/hFuture.png";
		
		//map.AddPushpin('hurricane_'+i, hurricaneData[i][1][0], hurricaneData[i][1][1], pinW, pinH, pinC, '<img src="'+imgSrc+'" onMouseOver="showNewsHint(\''+i+'\')" onMouseOut="delayedHintClose()" onload="correctPNG(this);"/>', 5);
		var pt = new VELatLong(parseFloat(hurricaneData[i][1][0]), parseFloat(hurricaneData[i][1][1]));
		var p = new VEPushpin('hurricane_' + i, pt, imgSrc, '', '');
		p.i = i;
		p.__type = 'hurricane';
		map.AddPushpin(p);	
		
	}	
}

function makePin() {
    var pinId=this.ID+"_"+this.m_vemap.GUID;
    var content = '';
    switch(this.__type) {
     case 'hurricane':
      content="<div style='z-index: 1000; cursor:hand; text-decoration:none;' id='"+this.ID+"' onmouseover='showNewsHint(\""+this.i+"\");' onmouseout='delayedHintClose();'><img class='"+this.IconStyle+"' src='"+this.Iconurl+"' id='"+pinId+"' onload='correctPNG(this);' /></div>";
	break;
	case 'camera':
	break;
    }
    return content;
}

VEPushpin.prototype.GetContent=makePin;


var currentHintId = null;
var currentHintTimeout = null;

function showNewsHint(id)
{
	if(currentHintTimeout)
		clearTimeout(currentHintTimeout);
	
	if(currentHintId == id) return;

	closeNewsHint();
	var hint = document.getElementById('pushPinHint');
	if(hint.style.display == 'block')
		return;

	hint.onmouseover = function () { 
		if(currentHintTimeout)
			clearTimeout(currentHintTimeout);
		};
	hint.onmouseout = function () { delayedHintClose(); };
	

	if(id == -1)
	{
		hint.style.background = '#ffba9c';
		hint.onclick = function () { zoomInHouston() };
		
		moveHintToBorder(hint, parseInt(document.getElementById('traffic_cam').style.top), parseInt(document.getElementById('traffic_cam').style.left) + 14);
	
		hintData = "<span style='font-size: 14px;'><b>Click here to see live traffic cameras</b></span>";
	}
	else
	{
		hint.style.background = '#fffadc';
		hint.onclick = function () { };

		//moveHintToBorder(hint, parseInt(document.getElementById('hurricane_'+id).style.top), parseInt(document.getElementById('hurricane_'+id).style.left) + 14);
		moveHintToBorder(hint, $('hurricane_' + id));
		var hurricaneDate = new Date();
		hurricaneDate.setTime(hurricaneData[id][0].getTime() - milliTimezoneOffset);
		var hurricaneDateString = days[hurricaneDate.getDay()].substr(0,3) + " " + hurricaneDate.getDate() + ' ' + months[hurricaneDate.getMonth()].substr(0,3);
		var hurricaneHourString = ((''+hurricaneDate.getHours()).length < 2? '0':'') + hurricaneDate.getHours() + ':';
		hurricaneHourString += ((''+hurricaneDate.getMinutes()).length < 2? '0':'') + hurricaneDate.getMinutes();
	
		var hintData = '<span style="font-size: 14px">';
		
		if(hurricaneData[id][2])
		{
			switch(hurricaneData[id][5])
			{
				case 'tD':
					hintData += "<b>Tropical depression</b> center";
				break;
				case 'tS':
					hintData += "<b>Tropical storm</b> center";
				break;
				case 'h1':
					hintData += "<b>Category 1 hurricane</b> center";
				break;
				case 'h2':
					hintData += "<b>Category 2 hurricane</b> center";
				break;
				case 'h3':
					hintData += "<b>Category 3 hurricane</b> center";
				break;
				case 'h4':
					hintData += "<b>Category 4 hurricane</b> center";
				break;
				case 'h5':
					hintData += "<b>Category 5 hurricane</b> center";
				break;
				case 'h0':
					hintData += "Hurricane center";
				break;
			}
		}
		else
			hintData += "<b>Rita forecast</b>";
		
		hintData += "<br>";
		
		hintData += ' <b>'+hurricaneDateString+'</b> at '+hurricaneHourString;
		hintData += '</span><br><span style="font-size: 12px">';
		hintData += 'Maximum sustained wind: <b>'+parseInt(hurricaneData[id][3])+' mph</b>';
		
		if(hurricaneData[id][2])
		hintData += '<br>Hurricane speed: <b>'+parseInt(hurricaneData[id][4])+' mph</b>';
		
		hintData += '</span>';
	}

	hint.innerHTML = hintData;
//	document.getElementById('pushPinHint').innerHTML = 'article '+id;

	hint.style.padding = 3;
//	document.getElementById('pushPinHint').style.height = 30;
//	hint.style.width = 250;
	hint.style.display = 'block';
	currentHintId = id;
}

/*function moveHintToBorder(hint, y, x)
{
	var agt=navigator.userAgent.toLowerCase();
	var is_gecko = (agt.indexOf('gecko') != -1);
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

	var divX = parseInt(x);
	var divY = parseInt(y);
	var divW = parseInt(hint.style.width);
	var divH = parseInt(hint.style.height);
	
	if(is_ie)
	{
		var screenW = document.body.clientWidth;
		var screenH = document.body.clientHeight;
	}
	else if(is_gecko)
	{
		var screenW = window.innerWidth;
		var screenH = window.innerHeight - 20;
	}

	if(divW + divX > screenW + map.offsetX)
		divX = map.offsetX + screenW - divW - 5;
	
	if(divH + divY + 50 > screenH + map.offsetY)
		divY = map.offsetY + screenH - divH - 50;

	hint.style.top = divY + 'px';
	hint.style.left = divX + 'px';
}*/

function moveHintToBorder(hint, pin) {
 Position.clone(pin, hint);
 hint.style.left = parseInt(hint.style.left) + 14;
 hint.style.width = '250px';
 hint.style.height = '60px';
}

function closeNewsHint()
{
	document.getElementById('pushPinHint').style.display = 'none';
	currentHintId = null;
}


function delayedHintClose()
{
	currentHintTimeout = setTimeout('closeNewsHint()', 500);
}

function initHints() {
	var d = document.createElement('div');
	d.style.display = 'none';
	d.style.position = 'absolute';
	d.style.zIndex = 100;
	//d.fontcolor = '#000';
	d.style.background = '#fffadc';
	d.style.border = '1px solid black';
	d.id = 'pushPinHint';
	d.style.width = '270px';
/*	d.style.width = 20;
	d.style.height = 30;*/
	document.body.appendChild(d);
}

function resizeMap(width, height) {
	var m = $("map");
	width=typeof width != 'undefined'?width:Utils.GetWindowWidthHeight().width;

	height=typeof height != 'undefined'?height:Utils.GetWindowWidthHeight().height ;
	m.style.width = width + "px";
	m.style.height = height+ "px";
	map.Resize(width, height);
	return this;
}

function loadPage()
{

	ShowNewsPanel();

	map = new VEMap('map');
	map.LoadMap(new VELatLong(25.0, -90.0), 5, 'h');	
	map.HideDashboard();
	resizeMap();
	map.AttachEvent('onstartzoom', function(e) {
		closeNewsHint();
	});
	map.AttachEvent('onendzoom', function(e) {
		showTrafficCams();
		showHurricaneData();
	});
	//map.SetCenterAndZoom(new VELatLong(25, -90));
/*	map=new VE_MapControl(25,-90,5,'h',"absolute",0,0,GetWindowWidth(),GetWindowHeight());

	map.onStartZoom = function() {
		closeNewsHint();
		map.clearPolylines();
	};

	map.onEndZoom = function()
	{
		VE_ZoomControl.SetZoomLevel(map.GetZoomLevel());
		//showHurricaneData();
		showTrafficCams();
		
		map.drawPolylines();
	}
	
	document.body.appendChild(map.element);*/

//	CreateZoomWidget(5, GetWindowWidth() - 190, 10);
	
	initHints();

	loadHurricaneData();
	loadHurricaneNews();
	loadTrafficCams();
}

function patchCopyright()
{
	return;
	VE_MapControl.prototype.__UpdateCopyright = VE_MapControl.prototype._UpdateCopyright;
	
	VE_MapControl.prototype._UpdateCopyright = function(){ 
		this.__UpdateCopyright();
		
		this.copyrightFg.innerHTML += '<br>Hurricane data by <a href="http://www.noaa.gov/" target=_blank class=copyLinkFg>NOAA</a><br>News by <a href="http://www.msnbc.com" target=_blank class=copyLinkFg>MSNBC</a><br>Application by <a href="http://www.poly9.com" target=_blank class=copyLinkFg>Poly9</a>';
		this.copyrightBg.innerHTML += '<br>Hurricane data by <a href="http://www.noaa.gov/" target=_blank class=copyLinkBg>NOAA</a><br>News by <a href="http://www.msnbc.com" target=_blank class=copyLinkBg>MSNBC</a><br>Application by <a href="http://www.poly9.com" target=_blank class=copyLinkBg>Poly9</a>';
		this._RepositionCopyright();
	}

	var patchedFunc = new String(VE_MapControl.prototype._RepositionCopyright);
	patchedFunc = patchedFunc.replace('28','58');
	patchedFunc = patchedFunc.replace('29','59');
	patchedFunc = patchedFunc.replace('function ()', '');
	VE_MapControl.prototype._RepositionCopyright = function () { eval(patchedFunc) };
}

function GetXmlHttp() {
	var xmlhttp=false;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		// JScript gives us Conditional compilation, we can cope with old IE versions.
		// and security blocked creation of the objects.
		 try {
		  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch (e) {
		  try {
		   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		  } catch (E) {
		   xmlhttp = false;
		  }
		 }
		@end @*/
		if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		  xmlhttp = new XMLHttpRequest();
		}
	return xmlhttp;
}

function dbg(out,dontbreak,clear)
{
	if(typeof dontbreak == 'undefined')
		dontbreak = false;
	if(typeof clear == 'undefined')
		clear = false;
	
	
	if(document.getElementById('dbg'))
	{
		document.getElementById('dbg').style.display='block';
		document.getElementById('dbg').innerHTML = out + (dontbreak?'':'<br>') + (clear? '' : document.getElementById('dbg').innerHTML);
	}
}

function dbgObj(obj)
{
	var out = '';

	for(var i in obj)
		out += '['+i+']'+': '+obj[i];
	
	dbg(out);
}
