// Special thanks to: Kevin Reed http://www.tnetweather.com
// Special thanks to: Pinto http://www.joske-online.be
// Pinto got me going on this (but doesn't know!)
//
// 10 March 2009 script to process Cumulus realtime data in XML
//    (http://sandaysoft.com)
//
// (c) S.M.Blinkhorn 2009
//
// ****************************************************************
// Version  1.3 - 1 April 2009
// ****************************************************************
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
// USA.
// ****************************************************************
// History
//
// Version 1.0      Initial release
// Version 1.1      Added hidden input fields to expose the values of interval,
//                  realtimeinterval and the various observation units for use
//                  within the document DOM. These are populated during
//                  the first call to loadXMLDoc and are available to the
//                  document.onload event.
// Version 1.2      Checks whether browser is IE x or not and uses 
//                  document.onreadystatechange to wait for the DOM to be
//                  fully loaded before launching the XML reader loop.
//                  This fixes a problem where the page was not fully
//                  populated on the first pass through the loop.
//                  No other browser seems to need this delay.
//                  And no other browser supports document.readystate.
//                  Ho Hum...
//                  It is still not possible to use <body onload="initialize()">
//                  to call initialize because of the twin constraints of
//                  Symbian not handling global vars properly and not being
//                  able to pass parameters to the onreadystatechange function.
//                  Maybe one day...
// Version 1.3      Cleaned up the set_ajax_obs function to eliminate
//                  the very very occasional 'object is null' error and to 
//                  very very slightly improve the inner loop efficiency
// ****************************************************************
//
function initialize(xmlfile,loop) {
// ****************************************************************
// initialize - call this from <body> javascript
// takes 2 optional parameters
//  xmlfile - names the xml file to read
//      defaults to cumulus.xml in the CWD
//  loop    - specifies the loop time in seconds
//      defaults to 15 seconds
//      a multiplier of 10 is applied if the browser is Symbian
//      a value of 0 disables the looping. 
//      The XML file will be parsed once.
//
//  Other stuff you might want to change:
//  FlashTime - the document stores a value of 0 for the flashtime.
//  Try setting it to about 0.75 (seconds) if you really must have 
//  the text changing colour when it is updated. (It has some use
//  in debugging, but cosmetically I hate it.) 
//  FlashColour - specifies the colour used for the annoying flash.
// ****************************************************************
    var FlashTime = 0; // seconds, 0 disables, try 0.75 if you must
    var FlashColour = '#00FF00'; // Green
// ----------------------------------------------------------------
    var x = navigator;
    document.write('<form>');
    document.write('<input type="hidden" id="appCodeName">');//document.write("<br />");
    document.write('<input type="hidden" id="appMinorVersion">');//document.write("<br />");
    document.write('<input type="hidden" id="appName">');//document.write("<br />");
    document.write('<input type="hidden" id="appVersion">');//document.write("<br />");
    document.write('<input type="hidden" id="cookieEnabled">');//document.write("<br />");
    document.write('<input type="hidden" id="cpuClass">');//document.write("<br />");
    document.write('<input type="hidden" id="onLine">');//document.write("<br />");
    document.write('<input type="hidden" id="platform">');//document.write("<br />");
    document.write('<input type="hidden" id="useragent">');//document.write("<br />");
    document.write('<input type="hidden" id="browserLanguage">');//document.write("<br />");
    document.write('<input type="hidden" id="systemLanguage">');//document.write("<br />");
    document.write('<input type="hidden" id="userLanguage">');//document.write("<br />");

    document.write('<input type="hidden" id="xmlfile">');//document.write("<br />");
    document.write('<input type="hidden" id="loop">');//document.write("<br />");
    document.write('<input type="hidden" id="timeout">');//document.write("<br />");
    document.write('<input type="hidden" id="flashtime">');//document.write("<br />");
    document.write('<input type="hidden" id="flashcolour">');//document.write("<br />");
    document.write('<input type="hidden" id="gotstatics">');//document.write("<br />");
    document.write('<input type="hidden" id="interval">');//document.write("<br />");
    document.write('<input type="hidden" id="realtimeinterval">');//document.write("<br />");
    document.write('<input type="hidden" id="tempunit">');//document.write("<br />");
    document.write('<input type="hidden" id="pressunit">');//document.write("<br />");
    document.write('<input type="hidden" id="rainunit">');//document.write("<br />");
    document.write('<input type="hidden" id="windunit">');//document.write("<br />");
    document.write('<input type="hidden" id="windrununit">');//document.write("<br />");
    document.write('</form>');

    document.getElementById("appCodeName").value=x.appCodeName;
    document.getElementById("appMinorVersion").value=x.appMinorVersion;
    document.getElementById("appName").value=x.appName;
    document.getElementById("appVersion").value=x.appVersion;
    document.getElementById("cookieEnabled").value=x.cookieEnabled;
    document.getElementById("cpuClass").value=x.cpuClass;
    document.getElementById("onLine").value=x.onLine;
    document.getElementById("platform").value=x.platform;
    document.getElementById("useragent").value=x.userAgent;
    document.getElementById("browserLanguage").value=x.browserLanguage;
    document.getElementById("systemLanguage").value=x.systemLanguage;
    document.getElementById("userLanguage").value=x.userLanguage;
	
//	document.write('<IMG src="images/Waxing Gibbous.png" <id="moonphasegraphic" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">');
//	document.write("<br />");
//	document.write("<br />");
//	document.write("<br />");
//	document.write("<br />");
//	document.write("<br />");
//	document.write("<br />");
//	document.write("<br />");

    if(xmlfile==undefined) xmlfile='cumulus.xml';
    document.getElementById("xmlfile").value=xmlfile;

    document.getElementById("flashtime").value=FlashTime;
    document.getElementById("flashcolour").value=FlashColour;
    document.getElementById("gotstatics").value=0;

    if(loop==undefined) loop='15';
    document.getElementById("loop").value=loop;

    var symbian = new RegExp("symbian","i");
    if (symbian.test(x.userAgent)) {
        document.getElementById("timeout").value=Math.min(loop*10,900); // seconds, capped @ 15 mins
    } else {
        document.getElementById("timeout").value=loop; // seconds
    }

// uncomment the next line to switch off the loop
// document.getElementById("timeout").value=0;

    var IE = new RegExp("MSIE","i");
    if (IE.test(x.userAgent)) {
        document.onreadystatechange=fnStartInit;
    } else {
        loadXMLDoc(document.getElementById("xmlfile").value+'?'+Math.random());
    }

}
function fnStartInit() {
    if (document.readyState=="complete") {
        loadXMLDoc(document.getElementById("xmlfile").value+'?'+Math.random());
    }
}

function loadXMLDoc(url) {
    xmlDoc=GetXmlHttpObject();
    if (xmlDoc!=null) {
        xmlDoc.onreadystatechange=state_Change;
        xmlDoc.open("GET",url,true);
        xmlDoc.send(null);
        timeout=document.getElementById("timeout").value;
        flashtime=document.getElementById("flashtime").value;
//        alert(flashtime);
        if(timeout!=0) setTimeout("loadXMLDoc(document.getElementById('xmlfile').value+'?'+Math.random())",timeout*1000);
        if(flashtime!=0) setTimeout("reset_ajax_color()",flashtime*1000);
    } else {
        alert("Your browser does not support XMLHTTP.");
        return;
    }
}

function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e) {
    // Internet Explorer
    try {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
    catch (e) {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function state_Change() {
    if (xmlDoc.readyState==4) {// 4 = "loaded"
        if (xmlDoc.status==200) {// 200 = OK
//            alert("loaded OK");
            if(document.getElementById("gotstatics").value==0) {
                getNamedElement("interval");
                getNamedElement("realtimeinterval");
                getNamedElement("tempunit");
                getNamedElement("pressunit");
                getNamedElement("rainunit");
                getNamedElement("windunit");
                getNamedElement("windrununit");
                document.getElementById("gotstatics").value=1;
            }
            set_ajax_obs();
        } else {
            alert("Problem retrieving XML data");
        }
    }
}

function set_ajax_obs() {
//  get a handle to the XML document
    var x=xmlDoc.responseXML.documentElement;
    if(x!=null) {  // xml doc was NOT modified while we were parsing it
//      set up some constants before we go loopy        
        var flashtime=document.getElementById("flashtime").value;
        var flashcolour=document.getElementById("flashcolour").value;
        var pattern=new RegExp("_"); // mask used to ignore the ajax element 'unique-ifier'
//      get a list of all the XML elements
        var items=x.getElementsByTagName("item")
        var numitems=items.length;
//      get a list of all the 'ajax' elements in the document
        elements=getElementsByClass("span","ajax");
        var numelements=elements.length;
//      here we go loop-de-loop...
        for (var i=0;i!=numitems;i++) { // step through each XML element
            var xid=items.item(i).attributes.getNamedItem("name"); // get the name of the XML element
            for (var index=0;index!=numelements;index++) { // and look for it in the 'ajax' elements list
                var ajx=elements[index];
                var aid=ajx.attributes.getNamedItem("id");
                if(xid.value==aid.value.split(pattern)[0]) { // we found a match, let's go strike it!
                    var cls=x.getElementsByTagName("class")[i].childNodes[0];
                    var val=x.getElementsByTagName("value")[i].childNodes[0];

                    if(val) { // if there is a stored value then use it
                        val=val.nodeValue;
                    } else { // insert something (nothing) to display
                        val="";
                    }

                    lastval = ajx.getAttribute("lastval");
                    if(cls.nodeValue=='static' && lastval!=null) break; // it's a static, it won't change - go get another
                    if(val==lastval) break; // it's not changed since last time - go get another
                    ajx.setAttribute("lastval",val);

                    var unt=x.getElementsByTagName("unit")[i].childNodes[0];
                    if(unt) { // if there is a unit defined in the XML then tack it on
                        unt=unt.nodeValue;
                    } else {
                        unt="";
                    }
                    ajx.innerHTML=val + unt; // and write the xml element into the document
					switch(val)
					{
					case "Waxing Gibbous":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';
					break;
					case "Full moon":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "New moon":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "Waning Gibbous":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "Waxing Cresent":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "Waning Cresent":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "First Quarter":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					case "Last Quarter":
						document.getElementById('moonphaseimage').innerHTML='<IMG src="images/' + val + '.png" <id="moonphaseimage" alt="Moon" width="64" height="64" hspace="10" align="left" border="0">';		
					break;
					}
					
					//document.getElementById('currenttime').innerHTML=currentTime.getHours() + ':' + currentTime.getMinutes();

                    if(flashtime!=0) ajx.style.color=flashcolour;
                }
            }
        }
    }
}

function getElementsByClass(tag, targetclass) {
    var arr = new Array();
    var elem = document.getElementsByTagName(tag);
    var numelem = elem.length;
    for(i = 0,iarr = 0; i != numelem; i++) {
        x = elem[i].getAttributeNode('class');
        if(x!=null) {
            att = x.nodeValue;
            if(att == targetclass) {
                arr[iarr] = elem[i];
                iarr++;
            }
        }
    }
    return arr;
}

function reset_ajax_color( ) {
// reset all the <span class="ajax"...> styles to have no colour override
    elements = getElementsByClass("span","ajax");
    numelements = elements.length;

    for (var index=0;index!=numelements;index++) {
        element = elements[index];
        element.style.color='';
    }
}

function getNamedElement(element) {
//  get a list of all the XML elements
    var x=xmlDoc.responseXML.documentElement;
    var items=x.getElementsByTagName("item")
    var numitems=items.length;
//  off we go...
    for (var i=0;i!=numitems;i++) { // step through each XML element
        var xid=items.item(i).attributes.getNamedItem("name"); // get the name of the XML element
        if(xid.value==element) { // we found a match, let's go strike it!
            var val=x.getElementsByTagName("value")[i].childNodes[0];

            if(val) { // if there is a stored value then use it
                val=val.nodeValue;
            } else { // insert something (nothing) to display
                val="";
            }
            document.getElementById(element).value=val;

            break; // and stop looking ('cos we found it already)
        }
    }
}
