<?php
  $deducedcountry = "Australia";
  $cityopts = "";
  $one = 1;
  $selstuff = "";
  $selstuff2 = "";
  $focusis = "CountryName";
  $thefile = "countries.xml";
  $bytagname = "country";
  $byintagname = "name";
  $onchange = "";
  
  //http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry?CountryName=Australia
  if (isset($_GET['CitiesViaCountry'])) {
    $onchange = " onfocus=' location.href = \"./get_weather_auto_completion.php\"; ' ";
    $focusis = "CityName";
    $deducedcountry = $_GET['CitiesViaCountry'];
    $thefile = str_replace(" ", "_", $_GET['CitiesViaCountry']) . "-cities.xml";
    $bytagname = "Table";
    $byintagname = "City";
    if (file_exists(dirname(__FILE__) . "/" . $thefile)) {
    $selstuff = file_get_contents(dirname(__FILE__) . "/" . $thefile);
    $selarray = explode("<City>", str_replace("/City", "City", $selstuff));
    } else {
    $selstuff = file_get_contents("http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry?CountryName=" . $_GET['CitiesViaCountry']);
    file_put_contents(dirname(__FILE__) . "/" . $thefile, str_replace("&lt;","<",str_replace("&gt;",">",$selstuff)));
    $selarray = explode("&lt;City&gt;", str_replace("/City", "City", $selstuff));
    }
    $one = 1; 
    $cities = array();
    for ($i=1; $i<sizeof($selarray); $i+=2) {
      if ($one < 12) $one++;
      $cities[sizeof($cities)] = substr($selarray[$i],0,(strlen($selarray[$i])-0));
    }
    sort($cities);
    for ($i=1; $i<=sizeof($cities); $i++) {
      $cityopts .= "<option value='" . $cities[$i - 1] . "'>" . $cities[$i - 1] . "</option>";
      if (($i % 10) == 0) $cityopts .= "<option value='CityName:'>CityName:</option>";
    }
  } else {
  $ans = "";
  $place = "";
  $country = "";
  $sqs = "";
  $cr = "";
  if (isset($_GET['CityName']) && isset($_GET['CountryName'])) {
    $place = $_GET['CityName'];
    $country = $_GET['CountryName'];
    $sqs = $_SERVER['QUERY_STRING'];
  } else if (isset($_GET['place']) && isset($_GET['country'])) {
    $cr = "\n";
    $place = $_GET['place'];
    $country = $_GET['country'];
    $sqs = "CityName=" . $place . "&CountryName=" . $country;
  }
  if ($sqs != "") {
    //exec("curl " . "http://www.webservicex.net/globalweather.asmx/GetWeather?" . $_SERVER['QUERY_STRING'] . " > " . dirname(__FILE__) . "/weather.xml");
    //$ans = file_get_contents(dirname(__FILE__) . "/weather.xml");
    //echo $ans;
    $ans = file_get_contents("http://www.webservicex.net/globalweather.asmx/GetWeather?" . $sqs);
    $ans2 = str_replace('<' . '/string>','',str_replace('<string xmlns="http://www.webserviceX.NET"><' . '?xml version="1.0" encoding="utf-16"?>','',str_replace("&lt;","<",str_replace("&gt;",">",$ans))));
    $ans = str_replace('<' . '?xml version="1.0" encoding="utf-8"?>','',str_replace('<' . 'Status>Success</Status>','',$ans2));
    $ans2 = str_replace('<' . 'CurrentWeather>','',str_replace('</' . 'CurrentWeather>','',$ans));
    $ans = str_replace('<' . 'CurrentWeather>','',str_replace('</' . 'CurrentWeather>','',$ans2));
    $ans2 = str_replace('</Time>','',str_replace('</Wind>','',str_replace('</SkyConditions>','',str_replace('</Visibility>','',str_replace('</DewPoint>','',str_replace('</RelativeHumidity>','',str_replace('</Temperature>','',str_replace('</Pressure>','',str_replace('</Location>','',$ans)))))))));
        for ($jj=0; $jj<15; $jj++) {
          $ans = str_replace(">",": ",str_replace("<",$cr,$ans2));
          $ans2 = $ans;
        }
    echo str_replace("\n","<br>",$ans);
    exit(0);
  }
  }
?>
<html>
<head>
<?php
echo '<title>Get the Weather via Global Weather with Country/City Auto-Completion ... http://www.webservicex.net/ ... thanks</title>';
?>

<style>
body, #<?php echo $focusis; ?> {
  font: 1.2em verdana, arial, helvetica, sans-serif;
}

.mysuggestions {
  background-color: #ffffff;
  padding: 2px 6px;
  border: 1px solid #000000;
}

.mysuggestions:hover {
  background-color: #69F69F;
}

#mypopups {
  position: absolute;
}

.<?php echo $focusis; ?>.myerror {
  background-color: #FFCFFC;
}

</style>

<script type="text/javascript">

window.onload = initAll;
var myxhr = false, breal=0;
var cityName, countryName, urlis;
var myxhr2 = false;
var myCountriesArray = new Array();
var cis = "";

function init2All(myc) {
  document.getElementById("<?php echo $focusis; ?>").onkeyup = searchHelpout;
  
  
      if (window.XMLHttpRequest) {
        myxhr2 = new window.XMLHttpRequest;
    }
    else {
  try {
    myxhr2 = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      myxhr2 = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      myxhr2 = false;
    }
  }
    }

  if (myxhr2) {
        //console.log("prehere");

    myxhr2.onreadystatechange = setCountriesArray;
    myxhr2.open("GET", "<?php echo $thefile; ?>", true);
    myxhr2.send(null);
  } else {
    alert("Not able to create XMLHttpRequest ... sadly.");
  }
}

function setCountriesArray() {
  if (myxhr2.readyState == 4) {
    if (myxhr2.status == 200) {
      //console.log("here");
      if (myxhr2.responseXML) {
        var myAllCountries = myxhr2.responseXML.getElementsByTagName("<?php echo $bytagname; ?>");
        for (var myi=0; myi<myAllCountries.length; myi++) {
      //console.log("ahere");
      //console.log("yeshere at " + myAllCountries[myi].getElementsByTagName("name")[0].firstChild);
          myCountriesArray[myi] = myAllCountries[myi].getElementsByTagName("<?php echo $byintagname; ?>")[0].firstChild;
        }
      }      
    } else {
      //console.log("Problem: " + myxhr.status);
      alert("Problem: " + myxhr2.status);
    }
  }
}

function searchHelpout() {
  var mystr = document.getElementById("<?php echo $focusis; ?>").value;
  document.getElementById("<?php echo $focusis; ?>").className = "";
  if (mystr != "") {
    document.getElementById("mypopups").innerHTML = "";
    for (var myi=0; myi<myCountriesArray.length; myi++) {
      var myThisCountry = myCountriesArray[myi].nodeValue;
      
      if (myThisCountry.toLowerCase().indexOf(mystr.toLowerCase()) == 0) {
        var myTempDiv = document.createElement("div");
        myTempDiv.innerHTML = myThisCountry;
        myTempDiv.onclick = makeSelection;
        myTempDiv.className = "mysuggestions";
        document.getElementById("mypopups").appendChild(myTempDiv);
      }
      
    }
    var myFoundCt = document.getElementById("mypopups").childNodes.length;
    if (myFoundCt == 0) {
      document.getElementById("<?php echo $focusis; ?>").className = "myerror";
    }
    if (myFoundCt == 1) {
      document.getElementById("<?php echo $focusis; ?>").value = document.getElementById("mypopups").firstChild.innerHTML;
      cis = document.getElementById("mypopups").firstChild.innerHTML;
      //alert("cis=" + cis);
      document.getElementById("mypopups").innerHTML = "";
    }
  }
}

function makeSelection(evt) {
  if (evt) {
    var myThisDiv = evt.target;
  } else {
    var myThisDiv = window.event.srcElement;
  }
  //alert(92 + " " + myThisDiv.innerHTML); document.getElementById("<?php echo $focusis; ?>").value = myThisDiv.innerHTML;
  cis = myThisDiv.innerHTML;
<?php
    if (strpos($focusis,"CountryName") !== false) {
     echo "\n location.href = './get_weather_auto_completion.php?CitiesViaCountry=' + cis; \n";
    }
?>
      //alert("Cis=" + cis);
  document.getElementById("mypopups").innerHTML = "";
  gbit();
}


function gbit() {
  if (document.getElementById("<?php echo $focusis; ?>").value != "" && cis != "") {
    //document.getElementById("mygi").style.display = "block";
    //alert("https://maps.google.com/maps?q=" + cis + '&hl=en&hnear=' + cis + '&t=m&z=5');
    //window.open("https://maps.google.com/maps?q=" + cis, cis, "left=10,top=190,width=1300,height=520"); //,'mygi');
    //init2All(document.getElementById("<?php echo $focusis; ?>").value);
    document.getElementById("<?php echo $focusis; ?>").value = cis;
<?php
    if (strpos($focusis,"CountryName") !== false) {
     echo "\n location.href = './get_weather_auto_completion.php?CitiesViaCountry=' + cis; \n";
    }
?>
    cis = "";
  //} else {
  //  document.getElementById("mygi").style.display = "none";
  }
}



function createXMLData(incity, incountry) {
 var outxml = '<' + '?' + 'xml version="1.0" encoding="utf-8"' + '?' + '>';
 outxml = outxml + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
 outxml = outxml + '  <soap:Body>';
 outxml = outxml + '    <GetWeather xmlns="http://www.webserviceX.NET">';
 outxml = outxml + '      <CityName>' + incity + '</CityName>';
 outxml = outxml + '      <CountryName>' + incountry + '</CountryName>';
 outxml = outxml + '    </GetWeather>';
 outxml = outxml + '  </soap:Body>';
 outxml = outxml + '</soap:Envelope>';
 return outxml;
}

function initAll() {
  init2All("");
  if (window.XMLHttpRequest) {
        myxhr = new window.XMLHttpRequest;
    }
    else {
  try {
    myxhr = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      myxhr = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      myxhr = false;
    }
  }
    }

  if (myxhr) {
        //console.log("prehere");
    cityName = document.getElementById("CityName").value;
    countryName = document.getElementById("CountryName").value;
    var xml = createXMLData(cityName, countryName);
    
    myxhr.onreadystatechange = readGlobalWeatherXml;
    //myxhr.open("GET", "http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" + cityName + "&CountryName=" + countryName, true);
    myxhr.open("GET", "./get_weather_auto_completion.php?CityName=" + cityName + "&CountryName=" + countryName, true);
   //myxhr.open("POST","http://www.webservicex.net/globalweather.asmx/GetWeather",true);
if (1 == 2) {
	// Set request headers for message to send. Depends on the web service
	myxhr.setRequestHeader('Man', 'POST /globalweather.asmx HTTP/1.1');
	myxhr.setRequestHeader('Content-Type', 'text/xml');
	myxhr.setRequestHeader('Content-Length', xml.length);
	myxhr.setRequestHeader('SOAPAction', 'http://www.webserviceX.NET/GetCitiesByCountry');
    alert(xml);
    
    myxhr.send(xml);
}

    myxhr.send(null);
  
  } else {
    alert("Not able to create XMLHttpRequest ... sadly.");
  }
}

function readGlobalWeatherXml() {
  var wstuff;
  if (myxhr.readyState == 4 && breal == 1) {
    console.log("myxhr.status=" + myxhr.status);
    if (myxhr.status == 200) {
      console.log("here");
      if (myxhr.responseXML) {
        console.log("here1");
        var myAllLinks = myxhr.responseXML.getElementsByTagName("Location");
        
        for (var myi=0; myi<myAllLinks.length; myi++) {
          document.getElementById("Wind").innerHTML = "Wind: " +  myAllLinks[myi].getElementsByTagName("Wind")[0].firstChild;
          document.getElementById("Time").innerHTML = "Time: " +  myAllLinks[myi].getElementsByTagName("Time")[0].firstChild;
          document.getElementById("Visibility").innerHTML = "Visibility: " +  myAllLinks[myi].getElementsByTagName("Visibility")[0].firstChild;
          document.getElementById("SkyConditions").innerHTML = "Sky Conditions: " +  myAllLinks[myi].getElementsByTagName("SkyConditions")[0].firstChild;
          document.getElementById("Temperature").innerHTML = "Temperature: " +  myAllLinks[myi].getElementsByTagName("Temperature")[0].firstChild;
          document.getElementById("DewPoint").innerHTML = "Dew Point: " +  myAllLinks[myi].getElementsByTagName("DewPoint")[0].firstChild;
          document.getElementById("RelativeHumidity").innerHTML = "Relative Humidity: " +  myAllLinks[myi].getElementsByTagName("RelativeHumidity")[0].firstChild;
          document.getElementById("Pressure").innerHTML = "Pressure: " +  myAllLinks[myi].getElementsByTagName("Pressure")[0].firstChild;
  
        }
        
      } else if (myxhr.responseText) {
        console.log("here5=" + myxhr.responseText);
        var ws2, wstuff = myxhr.responseText.replace('</Time>','').replace('</Wind>','').replace('</SkyConditions>','').replace('</Visibility>','').replace('</DewPoint>','').replace('</RelativeHumidity>','').replace('</Temperature>','').replace('</Pressure>','').replace('</Location>','');
        document.getElementById("weather").style.display = 'block';
        for (var jjj=0; jjj<15; jjj++) {
          ws2 = wstuff.replace("<br>","");
          wstuff = ws2;
        }
        for (var jj=0; jj<15; jj++) {
          ws2 = wstuff.replace(">",": ").replace("<","");
          wstuff = ws2;
        }
        document.getElementById("weather").innerHTML = wstuff;
      }      
    } else {
      console.log("Problem: " + myxhr.status);
      //alert("Problem: " + myxhr.status);
    }
  }
}



</script>

</head>
<body>
<h2>Hover (or Click) for weather from GlobalWeather</h2>
                      <form style='background-color: lightgreen;' target="_blank" action='http://www.webservicex.net/globalweather.asmx/GetWeather' method="POST">                      
                        
                          <table cellspacing="0" cellpadding="4" frame="box" bordercolor="#dcdcdc" rules="none" style="border-collapse: collapse;">
                          <tr>
	<td class="frmHeader" background="#dcdcdc" style="border-right: 2px solid white;">Parameter</td>
	<td class="frmHeader" background="#dcdcdc">Value</td>
</tr>

                           <tr>
                            <td class="frmText" style="color: #000000; font-weight: normal;">CountryName:</td>
<?php
	echo '                            <td><input autocomplete="off" class="frmInput" type="text" ' . $onchange . ' size="50" id="CountryName" name="CountryName" onblur="gbit();" value="' . $deducedcountry . '"></td>';
?>
                          </tr>
                       
                          <tr>

                            <td class="frmText" style="color: #000000; font-weight: normal;"><select onchange=' if (this.value.indexOf(":") == -1) { document.getElementById("CityName").value = this.value; } else if (2 == 3) { document.getElementById("CityName").value = "";  } ' id='sCityName'><option value='CityName:'>CityName:</option><?php echo $cityopts; ?></select></td>
                            <td><input class="frmInput" type="text" size="50" id="CityName" name="CityName"></td>
                          </tr>
                          
                        
                        
                        <tr>
                          <td></td>
                          <td align="right"> <input onclick=' cityName = document.getElementById("CityName").value; countryName = document.getElementById("CountryName").value; urlis = "http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" + cityName + "&CountryName=" + countryName; window.open(urlis,"_blank"); ' onmouseover=" breal=1; initAll();" type="submit" value="Hover or Click (for new window)" id="submit" class="button"></td>
                        </tr>
                        </table>
                        
                        <p id="Time"></p>
                        <p id="Wind"></p>
                        <p id="Visibility"></p>
                        <p id="SkyConditions"></p>
                        <p id="Temperature"></p>
                        <p id="DewPoint"></p>
                        <p id="Pressure"></p>
                        

<div id="mypopups"> </div>
                    </form>
<?php
  echo '<textarea id="weather" style="display: none; background-color: yellow;"  rows="14" cols="80"> ' . $ans . '</textarea>';
?>
<script>
<?php
  echo "\n document.getElementById('" . $focusis . "').focus(); ";
  echo "\n document.getElementById('sCityName').size = " . $one . "; ";
?>
</script>
</body>
</html>
