function loadStates( country, state_id, states ){
  $(state_id).style.display = 'inline';
  $(state_id).innerHTML = null;

  if( states.length == 0 ) {
     $(state_id).style.display = 'none'; 
     return;
  }
  addStateType( country, state_id );
  for( var a = 0; a < states.length; a++){
    var option = document.createElement('option');
    option.text = states[a];
    option.value = states[a];
    $(state_id).options.add(option, (a+1));
  }
  //$(state_id).focus();
}

function getCountry( country ){
  for(var a = 0; a < locationArray.length; a++){
    if( locationArray[a].country == country )
      return locationArray[a];
  }
  return null;
}

function addStateType( country, state_id ){
  var option = document.createElement('option');
  if( country == 'Canada' ) option.text = "Select Provience:";
  else if( country == 'United States' ) option.text = "Select State:";
  else option.text = "Select Country:";
  option.value = null;
  $(state_id).options.add(option, 0);
}

function countryChange( select, state_id ){
  if( select.value == null || select.value.length == 0 ){
    $(state_id).style.display = 'none';
    $(state_id).innerHTML = null;
  }else{
    var country = getCountry( select.value );
    if(country) loadStates( select.value, state_id, country.states );
    else {
        $(state_id).style.display = 'none';
        $(state_id).innerHTML = null;
    }
  }
}

function countryLoad( select, state_id, p_country, p_state ){
   chooseSelection( select, p_country );
   if( !p_state || p_state == null ) return;
   var country = getCountry( p_country );
   if(country) loadStates( p_country, state_id, country.states );
   chooseSelection( $(state_id), p_state );
}

