/*

	This javascript file is used for the PWS Realtime updates

*/

// auto called when fragment is loaded
var GetUpdateCondsURL='';
var GetUpdateCondsTimeout=60000*15; // 15 minutes

document.domain=getWUIDomain();

function getWUIDomain()
{
	var domainStr = document.domain;
	var domainarray=domainStr.split(".");

	var domaincom=domainarray[domainarray.length-1];
	var domainname=domainarray[domainarray.length-2];

//	alert('domain:' +domainname+'.'+domaincom);
	return domainname+'.'+domaincom;

}
	// create an iframe on stationdata that has the function we can call
//document.domain="wunderground.com";
//alert('about to include a new iframe element');

function addIFrame()
{

return;
	with (document.getElementsByTagName("body")[0].appendChild(document.createElement("iframe"))) 
	{
		style.border='0px';
		style.width='0px';
		style.height='0px';
		setAttribute("id", "condscript", 0);
		setAttribute("src", "http://stationdata."+getWUIDomain()+"/xmlrequest.html",0);
	}
}

function CondsLoaded(conds)
{
	var spanElements=$$('span.pwsrt');
	var spanlength=spanElements.length;
	var seconds_now = parseInt(conds["now"]);
	for (var index=0;index<spanlength;index++)
	{
		var element=spanElements[index];
		var className=element.className;
		if (className=="pwsrt")
		{
			var pwsid=element.getAttribute("pwsid");
			var pwsunit=element.getAttribute("pwsunit");
			var pwsvariable=element.getAttribute("pwsvariable");
			var englishunit=element.getAttribute("english");
			var metricunit=element.getAttribute("metric");
			var oldvalue=element.getAttribute("value");
			var pwssetobject=element.getAttribute("pwssetobject");
		
			if (conds[pwsid] && conds[pwsid][pwsvariable])
			{
				var newHTML;
				var english;
				var metric;
				var value;
				//alert('setting:'+conds[pwsid][pwsvariable]);
				//element.innerHTML=conds[pwsid][pwsvariable];

				value = conds[pwsid][pwsvariable];
				newHTML = value;

				// special cases that change the value
				if (pwsvariable=="winddir")
				{
					newHTML = lookupWindStringFormat(value);
					value = lookupWindString(value);
				}
				else if (pwsvariable=="lu")
				{
					if (parseInt(oldvalue) <= parseInt(value)) 
					{
						oldvalue=value;
					}

					newHTML = convertTime(conds[pwsid], oldvalue);
					//newHTML =newHTML+" "+oldvalue+" "+value;

					// AJS HACK
					element.innerHTML = newHTML;
					element.setAttribute("value",value);
				}
				
				
				// these use the normal values
				if (oldvalue!=value)
				{	
					if (pwsvariable=="tempf")
						newHTML = convertTempIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="windspeedmph")
						newHTML = convertWindIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="windgustmph" || pwsvariable=="maxwindgust")
						newHTML = convertWindIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="humidity")
						newHTML = convertHumidity(value);
					else if (pwsvariable=="dewptf")
						newHTML = convertTempIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="maxtemp")
						newHTML = convertTempIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="mintemp")
						newHTML = convertTempIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="baromin")
						newHTML = convertPressureIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="rainin")
						newHTML = convertRainIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="dailyrainin")
						newHTML = convertRainIntoUnits(pwsunit,value,englishunit,metricunit);
					else if (pwsvariable=="RealTime")
						newHTML = convertRealTime(value);

					element.style.color="#00AA00";
					element.innerHTML = newHTML;
					element.setAttribute("value",value);
				}				
				else
				{
					element.style.color="#000000";
				}


			
				//
				// if a pwssetobject is in the span element, eval the code inside by calling the setValue method
				// this allows generic controls. We don't use value because the wind should be the raw number
				//	
				if (pwssetobject)
				{
					var pwsaction=pwssetobject+'.setValue("'+conds[pwsid][pwsvariable]+'");';
					eval(pwsaction);
				}
			}
			//update the update time if there conds doesn't exist, but there is an old value
			else if (pwsvariable=="lu")
			{
				//use old value to determine the update time compared to now
				var seconds_diff;

				seconds_diff = seconds_now - parseInt(oldvalue);
				conds[pwsid] = new Array();
				conds[pwsid]['ages'] = parseInt(seconds_diff % 60);
				conds[pwsid]['agem'] = parseInt(seconds_diff / 60) % 60;
				conds[pwsid]['ageh'] = parseInt(seconds_diff / 3600);

				newHTML = convertTime(conds[pwsid], oldvalue);
				//newHTML =newHTML+" "+oldvalue+" "+value;

				// AJS HACK
				element.innerHTML = newHTML;
			}
		}

	}
	timeout_id = setTimeout("GetUpdateConds()",GetUpdateCondsTimeout);
}

var iframeadded=0;

function getFrameWin(id)
{
    var elm = document.getElementById(id),
        win, doc;
    //set up a reference to the window object of the iframe
    if(window.frames && window.frames[id]) //IE5, Konq, Safari
        win = window.frames[id];
    else if(elm.contentWindow) //IE5.5+, Moz 1.0+, Opera
        win = elm.contentWindow;
    else //Moz < 0.9 (Netscape 6.0)
        win = elm;
    return win
} 

function GetUpdateConds()
{
	//document.domain='wunderground.com';
//alert("GetUpdateConds");
	if (GetUpdateCondsURL.length)
	{
//alert(GetUpdateCondsURL);
		if (iframeadded==0)
		{
			addIFrame();
			iframeadded=1;
		}

		var win=getFrameWin('condscript');
		if (win && win.startAJAX_JavascriptExec)
		{
		//if (document.getElementById('condscript') && document.getElementById('condscript').contentWindow.startAJAX_JavascriptExec)	{
			var d = new Date();
			var ajaxurl=GetUpdateCondsURL+'&s='+d.getTime();
			// moved to end
			//timeout_id = setTimeout("GetUpdateConds()",GetUpdateCondsTimeout);
			try
			{
				document.getElementById('condscript').contentWindow.startAJAX_JavascriptExec(ajaxurl);
			}
			catch(ex)
			{
				//loadAJAXUsingIFRAME(ajaxurl);
				loadAJAXUsingSCRIPT(url);
            	//alert('err: ' + i + ', ' + ex.toString());
			}
		}
		else{
			//timeout_id = setTimeout("GetUpdateConds()",100);
		//	var localTimer = new Timer;
		//	localTimer.setTimeout(GetUpdateConds(),100);
		//	localTimer=null;
		}
	}

//	timeout_id = setTimeout("GetUpdateConds()",GetUpdateCondsTimeout);
}
function SetUpdateURL(url,timeout)
{
	GetUpdateCondsURL=url;
	GetUpdateCondsTimeout=timeout;
}

function loadAJAXUsingIFRAME(url)
{
    var scriptarray=document.getElementsByTagName('iframe');
    var i=0;
    for (i=0;i<scriptarray.length;i++)
    {
        if (scriptarray[i].id=='stationscript')
        {
            //alert('url'+scriptarray[i].src);
            scriptarray[i].parentNode.removeChild(scriptarray[i]);
        }
    }

   with (document.getElementsByTagName("body")[0].appendChild(document.createElement("iframe"))) {
                style.border='0px';
                style.width='0px';
                style.height='0px';
        setAttribute("id", "stationscript", 0);
        setAttribute("src", url, 0);
        }

}
function loadAJAXUsingSCRIPT(url)
{
    var scriptarray=document.getElementsByTagName('script');
    var i=0;
    for (i=0;i<scriptarray.length;i++)
    {
        if (scriptarray[i].id=='stationscript')
        {
            //alert('url'+scriptarray[i].src);
            scriptarray[i].parentNode.removeChild(scriptarray[i]);
        }
    }

   with (document.getElementsByTagName("body")[0].appendChild(document.createElement("script"))) {
                style.border='0px';
                style.width='0px';
                style.height='0px';
        setAttribute("id", "stationscript", 0);
        setAttribute("src", url, 0);
        }

}

function CheckBrowserDisable()
{
	var detect = navigator.userAgent.toLowerCase();
	var place = detect.indexOf('safari') + 1;
	var disablertupdate = 0;
	if (place)
	{
    	// get the version
    	var safariversion=detect.substr(place+6);
    	var firstdot=safariversion.indexOf('.')+1;
    	var versionnum=0;
    	if (firstdot>0)
    	{
        	versionnum=safariversion.substr(0,firstdot-1);
    	}
    	else
    	{
        	versionnum=parseInt(safariversion);
    	}
    	if (versionnum< 130)
    	{
        	disablertupdate=1;
    	}
		//Check for windows safari - ABC
		//if(detect.indexOf('Windows')){
		//	disablertupdate=1;
		//}
	}
	else if (detect.indexOf('netscape')!=-1)
    	disablertupdate=1;

	return disablertupdate;
}
