﻿//globals 
var first = "state"; //id of first SELECT 
var second = "counties"; //id of second SELECT 

function sendRequest(url,params,HttpMethod) { 
   if(!HttpMethod) { //check if http method is defined, if not, set it to GET 
      HttpMethod="GET"; 
   } 
   var el = document.getElementById(first); 
   var selected = el.selectedIndex; 
   url = 'fetch.asp?state='+el.options[selected].value;
   // 
   // initialize request object 
   req=null; 
   if(window.XMLHttpRequest){ 
      req=new XMLHttpRequest; //mozilla/safari 
   } else if(window.ActiveXObject){ 
      req=new ActiveXObject("Microsoft.XMLHTTP"); //internet explorer         
} 

//define callback handler 
if(req) { 
    //     
    //while(E1.hasChildNodes()) { //removes items from dropdown if some already exist 
         //removeChild(E1.firstChild); 
       //}        
       req.onreadystatechange=onReadyState; 
       req.open(HttpMethod,url,true); 
       req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
       req.send(params); 
    } 
} 

// 
function onReadyState() { 
// 
    var ready=req.readyState; 
    var data=null; 
    var El = document.getElementById(second);     
    El.disabled=0; 
    if(ready==4){ //check ready state                    
       data=req.responseText; //read response data 
       var items = data.split(','); 
       var length = items.length; 
       if (El.hasChildNodes()) El.removeChild(El.firstChild)
       for(var i = 0; i < length; i++) { 
          var childEl = document.createElement('option'); //create option           
          El.appendChild(childEl); //then append it to the second dropdown list 
          childEl.value = items[i]; 
          childEl.innerHTML = items[i]; 
       } 
    } 
} 
// 
function populateCounties() {     
    // 
    var el = document.getElementById(first); 
    var ob2= document.getElementById(second);     
    var selected = el.selectedIndex; 
    // 
    while(ob2.hasChildNodes()) { //removes items from dropdown if some already exist 
       ob2.removeChild(ob2.firstChild); 
    } 
    if(selected!= 0) { //if they choose something other than the first select-->"Select state first" 
       // Add a please wait option...
       var childEl = document.createElement('option'); //create option           
       ob2.appendChild(childEl); 
       ob2.disabled=1;
       childEl.value = ""; 
       childEl.innerHTML = "Please wait...";               
       setTimeout("sendRequest();", 1000);                      
    } else { //otherwise add the Select state First option and disable it 
       var childEl = document.createElement('option'); 
       ob2.appendChild(childEl); 
       childEl.innerHTML = 'Select state first'; 
       ob2.disabled=1; 
    } 
} 
 

