/*
This file is the heart of weather.lancasteronline.com

It is where the AJAX processing is done. It handles all of the requests and communications between the php scripts
in this directory and the index page.

Chances are, if this file gets screwed up, the whole freakin web page craps the sheets.

So if your goal is to freight-train the weather.lancasteronline.com page, changing this file would be a 
great place to start. Just sayin.
*/

var xmlWeather;   //Global AJAX object
var preLoadRadar = new Array(); //This is for the radar array of pictures
var preLoadSatellite = new Array();  //This is for the satellite array of pictures
var j = 0;  //The element of the array of the currently visible image
var t;  //This is the timeout value. We need it stop the timeout when closing the popup
/*
*************************************************United States Weather******************************************
The functions in this area are listed in chronological order in an attempt to demonstrate the flow
of a user request for US weather conditions.
*/

//This function calls compileStates.php to generate a drop-down box of states based on the user specified region.
function grabStates(region) {
  xmlWeather=GetXmlHttpObject()
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 

  var url="ajax/compileStates.php?region=" + region;

  xmlWeather.onreadystatechange=byRegionitemstateChanged;
  xmlWeather.open("GET",url,true);
  xmlWeather.send(null);
}


//This is called by the function directly above and is reponsible for sending the generated state drop-down box
//back to index.php for display.
function byRegionitemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
	document.getElementById("statebox").innerHTML = xmlWeather.responseText;
  }
}

//When the user selects a state, this function calls compileCities.php, which generates a drop-down box
//of cities. It then calls the function directly below.
function grabCities(state) {
  xmlWeather=GetXmlHttpObject()
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 

  var url="ajax/compileCities.php?state=" + state;

  xmlWeather.onreadystatechange=byStateitemstateChanged;
  xmlWeather.open("GET",url,true);
  xmlWeather.send(null);
}

//This is called by the function directly above, and is reponsible for sending the generated cities drop-down box
//back to index.php for display. 
function byStateitemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
	document.getElementById("citybox").innerHTML = xmlWeather.responseText;
  }
}

//This function is called within compileCities.php. When a user selects a city, this function will display the
//Set Location button that will call the function directly below.
function displayUSSearchButton() {
  document.getElementById("USsearchButton").innerHTML =  "<input type=\"button\" style=\"font-size:84%;\"value=\"Set Location\" onclick=\"document.getElementById('cityandstate').innerHTML = 'UPDATING...';getByStateAndCity(document.citysearch.states.value, document.citysearch.cities.value);\"/>";
}

//When we finally have a state and city by which to search with, this function gets called from the Set Location
//button. It calls weatherbystatecity.php to get a zipcode. When it gets that zipcode, it calls the function
//directly below.
function getByStateAndCity(state, city) {
  xmlWeather=GetXmlHttpObject();
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 
  
  //This is what happens when someone attempts to run a search without selecting a city.
  if (city == '') {
    alert('Please enter a city to perform the search.');
  }
  //This is what happens when we have both a city and state (an ideal situation).
  else {
    var url="ajax/weatherbystatecity.php?state=" + state + "&city=" + city;

    xmlWeather.onreadystatechange=byStateCityitemstateChanged;
    xmlWeather.open("GET",url,true);
    xmlWeather.send(null);
  }
}


//This function passes the zipcode information retrieved from the one directly above to the function
//directly below this one when a user searches by city and state.
function byStateCityitemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
    getWeatherByZip(xmlWeather.responseText);
  }
}


//This function passes the zipcode data to getDataByZip.php either from the user on a zipcode search
//or from the function directly above on a city/state search.
function getWeatherByZip(zipcode) {
  xmlWeather=GetXmlHttpObject()
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 
  var url="http://weather.lancasteronline.com/ajax/getDataByZip.php?zipcode=" + zipcode;

  xmlWeather.onreadystatechange=itemstateChanged;
  xmlWeather.open("GET",url,true);
  xmlWeather.send(null);
}

//This function is called by the one directly above once we have a generated XML file created by getDataByZip.php
//It then calls the function directly below this one, to parse that XML file and send it back to the index page 
//for display.
function itemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
  
    var xmlDocument = xmlWeather.responseXML;
	var divlocations = xmlDocument.getElementsByTagName("data");
    getElements(divlocations);
  }
}

//This function is called by the one directly above, and parses the US Weather XML file that was passed to it.
//After parsing, it sends the data back to the index page for display.
function getElements(divlocations) {
  var i = 0;
  var dataElements = new Array();
 
  if (divlocations[0].firstChild.data == '0') {
    alert('No data available for this location.');
	getWeatherByZip(divlocations[1].firstChild.data);
  }
  else {
    dataElements[0]="phrase";
    dataElements[1]="temp";
    dataElements[2]="aptemp";
    dataElements[3]="windchill";
    dataElements[4]="tempunit";
    dataElements[5]="rhumidity";
    dataElements[6]="winddirection";
    dataElements[7]="windspeed";
    dataElements[8]="windunit";
    dataElements[9]="pressure";
    dataElements[10]="pressureunit";
    dataElements[11]="visibilty";
    dataElements[12]="visibilityunit";
    dataElements[13]="icon";
    dataElements[14]="cityandstate";
    dataElements[15]="radar";
    dataElements[16]="satellite";
    dataElements[17]="nameday1";
    dataElements[18]="highday1";
    dataElements[19]="highunitday1";
    dataElements[20]="lowday1";
    dataElements[21]="lowunitday1";
    dataElements[22]="iconday1";
    dataElements[23]="nameday2";
    dataElements[24]="highday2";
    dataElements[25]="highunitday2";
    dataElements[26]="lowday2";
    dataElements[27]="lowunitday2";
    dataElements[28]="iconday2";
    dataElements[29]="nameday3";
    dataElements[30]="highday3";
    dataElements[31]="highunitday3";
    dataElements[32]="lowday3";
    dataElements[33]="lowunitday3";
    dataElements[34]="iconday3";
    dataElements[35]="nameday4";
    dataElements[36]="highday4";
    dataElements[37]="highunitday4";
    dataElements[38]="lowday4";
    dataElements[39]="lowunitday4";
    dataElements[40]="iconday4";
    dataElements[41]="nameday5";
    dataElements[42]="highday5";
    dataElements[43]="highunitday5";
    dataElements[44]="lowday5";
    dataElements[45]="lowunitday5";
    dataElements[46]="iconday5";
    dataElements[47]="nameday6";
    dataElements[48]="highday6";
    dataElements[49]="highunitday6";
    dataElements[50]="lowday6";
    dataElements[51]="lowunitday6";
    dataElements[52]="iconday6";
    dataElements[53]="nameday7";
    dataElements[54]="highday7";
    dataElements[55]="highunitday7";
    dataElements[56]="lowday7";
    dataElements[57]="lowunitday7";
    dataElements[58]="iconday7";
	dataElements[59]="warnings";
	dataElements[60]="detailstoday";
	dataElements[61]="detailstomorrow";
	dataElements[62]="detailsnextday";
    
    for (i=0;i<63;i++) {
	  if (i == 13) {
        document.getElementById(dataElements[i]).innerHTML = 
		  '<img src="graphics/icons/' + divlocations[i].firstChild.data + '.gif" width="95" height="71">';
	  }
	  else if (i == 15) {
		pre0radar = new Image(421, 314);
        pre0radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '1.png';
		
		pre1radar = new Image(421, 314);
        pre1radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '2.png';
		
		pre2radar = new Image(421, 314);
        pre2radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '3.png';
		
		pre3radar = new Image(421, 314);
        pre3radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '4.png';
		
		pre4radar = new Image(421, 314);
        pre4radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '5.png';
		
		pre5radar = new Image(421, 314);
        pre5radar.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '6.png';
		
		preLoadRadar[0] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '1.png';
							  
        preLoadRadar[1] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '2.png';
        preLoadRadar[2] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '3.png';
        preLoadRadar[3] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '4.png';
        preLoadRadar[4] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '5.png';
        preLoadRadar[5] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '6.png';
		
	    document.getElementById(dataElements[i]).innerHTML = '<a onmouseover="this.style.cursor=\'pointer\';" onclick="clearTimeout(t); grabBigMap(\'' + divlocations[i].firstChild.data + '\', \'radarloop\'); runRadar(preLoadRadar);"><img src=\"http://media.lancasteronline.com/weather/' + divlocations[i].firstChild.data + '.png\" width=\"76\" height=\"50\" border=\"1\"></a>';
		
		grabBigMap(divlocations[i].firstChild.data, '');
	  }
	  else if (i == 16) {
		  
		pre0sat = new Image(421, 314);
        pre0sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '1.png';
		
		pre1sat = new Image(421, 314);
        pre1sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '2.png';
		
		pre2sat = new Image(421, 314);
        pre2sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '3.png';
		
		pre3sat = new Image(421, 314);
        pre3sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '4.png';
		
		pre4sat = new Image(421, 314);
        pre4sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                divlocations[i].firstChild.data + '5.png';
		
		pre5sat = new Image(421, 314);
        pre5sat.src = 'http://media.lancasteronline.com/weather/png421/' +
		                 divlocations[i].firstChild.data + '6.png';
		  
	    preLoadSatellite[0] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '1.png';
        preLoadSatellite[1] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '2.png';
        preLoadSatellite[2] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '3.png';
        preLoadSatellite[3] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '4.png';
        preLoadSatellite[4] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '5.png';
        preLoadSatellite[5] = 'http://media.lancasteronline.com/weather/png421/' + divlocations[i].firstChild.data + '6.png';
		
		
	    document.getElementById(dataElements[i]).innerHTML = '<a onmouseover="this.style.cursor=\'pointer\';" onclick="clearTimeout(t); grabBigMap(\'' + divlocations[i].firstChild.data + '\', \'satelliteloop\'); runSatelliteLoop(preLoadSatellite);"><img src=\"http://media.lancasteronline.com/weather/' + divlocations[i].firstChild.data + '.png\" width=\"76\" height=\"50\" border=\"1\"></a>';
	  }
	  else if (i == 1 || i == 2 || i == 3) {
	    document.getElementById(dataElements[i]).innerHTML = divlocations[i].firstChild.data + "&deg;";
	  }
	  else if (i == 22 || i == 28 || i == 34 || i == 40 || i == 46 || i == 52 || i == 58) {
        document.getElementById(dataElements[i]).innerHTML = '<img src="graphics/icons/' + divlocations[i].firstChild.data
	                                                        + '.gif" width ="32" height="20">';
	  }
	 else if (i == 59) {
	    if (divlocations[i].firstChild.data != 0) {
		  var text = '';
		  
		  //Gotta use parent.childNodes here because firstChild.data cuts off string at 4096 characters
		  for (var j=0;j<divlocations[i].childNodes.length;j++) {
		    text += divlocations[i].childNodes[j].data;
		  }
		  text = text.replace(/\[/g, "<");
		  text = text.replace(/\]/g, ">");
		  document.getElementById(dataElements[i]).innerHTML = text;
		}
		else {
		  document.getElementById(dataElements[i]).style.height = '1px';
		  document.getElementById(dataElements[i]).innerHTML = '';
		}
	  }
	  else if (i == 60 || i == 61 || i ==62) {
		var text;
		  
	    text = divlocations[i].firstChild.data;
		text = text.replace(/\[/g, "<");
		text = text.replace(/\]/g, ">");
		document.getElementById(dataElements[i]).innerHTML = text;
	  } 
	  else {
      document.getElementById(dataElements[i]).innerHTML = divlocations[i].firstChild.data;
	  }
    }
  }
}

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


/*
*************************************************International Weather******************************************
The functions in this area are listed in chronological order in an attempt to demonstrate the flow
of a user request for international weather conditions.
*/

//This function retrieves the city for the specified country
function getForeignCity(country) {
  xmlWeather=GetXmlHttpObject();
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 

  var url="ajax/getForeignCity.php?country=" + country;

  xmlWeather.onreadystatechange=foreignCityitemstateChanged;
  xmlWeather.open("GET",url,true);
  xmlWeather.send(null);
}

//This function is called from the one directly above that calls the getForeignCity.php script. 
//It takes that script's results and sends the city drop-down box back to the index page for display.
function foreignCityitemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
	document.getElementById("intcitybox").innerHTML = xmlWeather.responseText;
  }
}

//After a city has been selected, this functions creates and displays the Set Location button.
//This is called from within getForeignCity.php file
function displayForeignSearchButton() {
  document.getElementById("foreignButton").innerHTML =  "<input type=\"button\" style=\"font-size:84%;\" value=\"Set Location\"   onclick=\"getInternationalWeather(document.international.country.value, document.international.foreigncities.value);\"/>";
}

//Once the city and country are finally retrieved from the 3 functions directly above, this function,
//which is called from the Set Location button, calls the getInternationalWeather.php script to create
//the international weather XML file for use by the function directly below this function.
function getInternationalWeather(country, city) {
   xmlWeather=GetXmlHttpObject();
  if (xmlWeather==null)  {
    alert ("Browser does not support HTTP Request")
    return
  } 
  
  //This is what happens when someone attempts to run a search without selecting a city.
  if (city == '') {
    alert('Please enter a city to perform the search.');
  }
  
  //This is what happens when the we have both a city and country (an ideal situation).
  else {
    var url="ajax/getInternationalWeather.php?country=" + country + "&city=" + city;

    xmlWeather.onreadystatechange=foreignWeatheritemstateChanged;
    xmlWeather.open("GET",url,true);
    xmlWeather.send(null);
  }
}

//Now that we have our XML file, which was requested and retrieved from the function directly above,
//we can now acknowledge successfull receipt, and pass it to the function directly below this one for parsing
//and display.
function foreignWeatheritemstateChanged()  { 
  if (xmlWeather.readyState==4 || xmlWeather.readyState=="complete") { 
  
    var xmlForeignDocument = xmlWeather.responseXML;
	var divForeignLocations = xmlForeignDocument.getElementsByTagName("data");
    getForeignElements(divForeignLocations);
  }
}

//Called from the function directly above, this function parses down the international XML file and 
//and sends it back to the index page for display.
function getForeignElements(divForeignlocations) {
  var i = 0;
  var dataElements = new Array();
  
  dataElements[0]="foreignicon";
  dataElements[1]="foreigntemp";
  dataElements[2]="foreigntempunit";
  dataElements[3]="foreignphrase";
  dataElements[4]="citycountry";
  
  for (i=0;i<5;i++) {
	if (i == 0) {
      document.getElementById(dataElements[i]).innerHTML = '<img src="graphics/icons/' + 
	           divForeignlocations[i].firstChild.data + '.gif" width="50" height="31">';
	}
	else if (i == 1) {
	  document.getElementById(dataElements[i]).innerHTML = divForeignlocations[i].firstChild.data + "&deg;";
	}
	else {
      document.getElementById(dataElements[i]).innerHTML = divForeignlocations[i].firstChild.data;
	}
  }
}

//**********************************End of International Weather************************************************

//**********************************Temperature Band Maps*******************************************************
//This function toggles the temperature band map between highs and lows. Highs are loaded when page loads.
function setTempBandMap(map) {
  if (map == 0) {
	pretbandH = new Image(421, 314);
	pretbandH.src = 'http://media.lancasteronline.com/weather/ustmptod.png';
	
	pretbandC = new Image(421, 314);
	pretbandC.src = 'http://media.lancasteronline.com/weather/ustmpton.png';
	
    document.getElementById("tband").innerHTML = '<a onmouseover="this.style.cursor=\'pointer\';" onclick="clearTimeout(t); grabBigMap(\'ustmptod\', \'tband\');"><img src=\"http://media.lancasteronline.com/weather/ustmptod.png\" width=\"76\" height=\"50\" border=\"1\"></a>';
  }
  else {
   document.getElementById("tband").innerHTML = '<a onmouseover="this.style.cursor=\'pointer\';" onclick="clearTimeout(t); grabBigMap(\'ustmpton\', \'tband\');"><img src=\"http://media.lancasteronline.com/weather/ustmpton.png\" width=\"76\" height=\"50\" border=\"1\"></a>';
  }
}
//****************************************************************************************************************    

//******************************************************************************************************************
//The 4 functions below handle the looping radar and satellite
function runRadar(input){

  var speed = 400;
  var p = 6;
  
  document.images['radarloop'].src = input[j];
  j = j + 1;
  
  if (j > (p-1) ) {
    j = 0;
  }
  t = window.setTimeout('runRadar(preLoadRadar)', speed);
}

function runSatellite(input){

  var speed = 400;
  var p = 6;
  
  document.images['satelliteloop'].src = input[j];
  j = j + 1;
  
  if (j > (p-1) ) {
    j = 0;
  }
  t = window.setTimeout('runSatellite(preLoadSatellite)', speed);
}


function runSatelliteLoop() {
  runSatellite(preLoadSatellite);
}

function runRadarLoop() {
  runRadar(preLoadRadar);
}

function grabBigMap(type, name) {
  document.getElementById('bigmap').innerHTML = '<div style="text-align:center;position:relative;top:150px;font-size:12px;color:#727272;font-weight:bold;">Loading...</div>';
  document.getElementById('bigmap').innerHTML = "<img src='http://media.lancasteronline.com/weather/png421/" +
           type + ".png' name='" + name + "' width='421' height='314' border='1'>";	
}
//*****************************************************************************************************************


//**********************************Browser Stuff***************************************************************
//This function detects the browser, so I can figure out which AJAX handler to use.
function GetXmlHttpObject(handler) { 
  var objXMLHttp=null
  
  //Mozilla, Netscape, Safari, etc. You know, the browsers that follow the standards.
  if (window.XMLHttpRequest) {
    objXMLHttp=new XMLHttpRequest()
  }
  
  //IE. What more needs to be said.
  else if (window.ActiveXObject) {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  return objXMLHttp
}
//*************************************************************************************************************