var map;
var point;
var marker;
var latlong;
var spanArr;
var spanText = new Array();
var gdir;
var geocoder = null;
var addressMarker;
var req;

//window.onload = init; Loading init script from analytics block due to IE 7 not displaying map thumbs
window.onunload = GUnload;

function init(){

	loadXMLDoc('/proxy.php?proxy_url=http://www.weather.gov/xml/current_obs/KACT.xml');
	// old url http://www.nws.noaa.gov/data/current_obs/KACT.xml
	maps();

}

function maps() {
	
	if(document.getElementById("map")){
	
		document.getElementById("directions").style.display="block";
	
		if (GBrowserIsCompatible()) { 
		
			latlong=document.getElementById("latlong").lastChild.nodeValue;
			
			displayMap("", latlong, 14)
				
			marker = new GMarker(point);
							
			map.addControl(new GSmallMapControl());
			
			map.addControl(new GMapTypeControl());
			
			map.addOverlay(marker);
			
			gdir = new GDirections(map, document.getElementById("driving"));
		
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
		
			GEvent.addListener(gdir, "error", handleErrors);		
			
		}	
		
	} else {
		
		if(document.getElementById('rides') || document.getElementById('events')){
	
			spanArr = document.getElementById('content').getElementsByTagName('span');
	
			if (GBrowserIsCompatible()) { 
			
				//ID the paragraphs first, when maps data loads additional spans will be added to container
	
				for(var i = 0; i < spanArr.length; i++){
			
					spanText.push(spanArr[i].firstChild.nodeValue);
					
					spanArr[i].parentNode.id = 'map' + i;

				}
			
				for(var i = 0; i < spanText.length; i++){
			
					displayMap(i, spanText[i], 14)
			
				}
			
			}	
	
		}
	
	}

}

function displayMap(paraMap, latlong, scale){

		longlat=(latlong.split(','));
			
		point = new GPoint(longlat[1], longlat[0]);
						
		map = new GMap2(document.getElementById('map' + paraMap));
	
		map.setCenter(new GLatLng(longlat[0], longlat[1]), scale);

}

function setDirections(fromAddress, toAddress, locale) {
			

		gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });	

		document.getElementById("todaysRides").style.display="none";
		
		document.getElementById("upcoming").style.display="none";	
		
		map.removeOverlay(marker);


}

function handleErrors(){
	
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

	else alert("An unknown error occurred.");

}

function onGDirectionsLoad(){ 
// Use this function to access information about the latest load()
// results.

// e.g.
// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
// and yada yada yada...
}

//end of maps functions, start weather widget

function loadXMLDoc(url)
{
    if (window.XMLHttpRequest) {
    
        req = new XMLHttpRequest();
        
        req.onreadystatechange = processReqChange;
        
        req.open("GET", url, true);
        
        req.send(null);
            
    } else if (window.ActiveXObject) {
    
        req = new ActiveXObject("Microsoft.XMLHTTP");
        
        if (req) {
        
            req.onreadystatechange = processReqChange;
            
            req.open("POST", url, true);
            
            req.send();
            
        }
        
    }
    
}


function processReqChange() 
{
    
    if (req.readyState == 4) {

        if (req.status == 200) {
        
        	var temp = req.responseXML.getElementsByTagName("temp_f")[0].lastChild.nodeValue;
        	
        	var direction = req.responseXML.getElementsByTagName("wind_degrees")[0].lastChild.nodeValue;      	
        	
			var speed = req.responseXML.getElementsByTagName("wind_mph")[0].lastChild.nodeValue;
			
			//var listSource = document.getElementById('todaysRides').getElementsByTagName('ul')[0].innerHTML;
			
			var listSource = document.getElementById('todaysRides').getElementsByTagName('h4')[0].innerHTML;
			
			 
        	
        	if(speed == 0 || isNaN(speed)){
        	
        			//appendList(listSource + '<li>' + temp + '\u00b0</li><li>Calm</li>');
        			
        			appendList(listSource + ' ' + temp + '\u00b0 Calm');
        	
        		} else {
        		
        			//appendList(listSource + '<li>' + temp + '\u00b0</li><li>' + parseDir(direction) + ' ' + parseSpeed(speed) + '</li>');
        			
        			appendList(listSource + ' ' + temp + '\u00b0 ' + parseDir(direction) + ' ' + parseSpeed(speed));
        		
        		}

        	}
        
        }
  
}


function appendList(listItem){

	document.getElementById('todaysRides').getElementsByTagName('h4')[0].innerHTML = listItem;

}

function appendXML(xmlItem)
{

	var ulNode = document.getElementById('todaysRides').getElementsByTagName('ul')[0];
	
	var liNode = document.createElement('li');
	
	var liNode = liNode.appendChild(document.createTextNode(xmlItem));
	
	ulNode.appendChild(liNode);

}



function parseSpeed(speed)
{

	speed = parseFloat(speed);
	
	speed = Math.round(speed);
	
	return (speed + " mph");

}

function parseDir(direction)
{
	if(isNaN(direction)){
	
		return "Var"
	}
	
	if(direction < 23 && direction >= 0 || direction >= 338){
	
		return "N"
	}
	
	if(direction >= 23 && direction < 68){
	
		return "NE"
	}

	if(direction >= 68 && direction < 113){
	
		return "E"
	}

	if(direction >= 113 && direction < 158){
	
		return "SE"
	}

	if(direction >= 158 && direction < 203){
	
		return "S"
	}

	if(direction >= 203 && direction < 248){
	
		return "SW"
	}

	if(direction >= 248 && direction < 293){
	
		return "W"
	}

	if(direction >= 293 && direction < 338){
	
		return "NW"
	}
	
}

