// Based on Livesearch ;)
/*
** init function is called on the load of the page:
**   - initializes state variable is_processing
**   - calls the callback function
*/                                          //
function init() {
	is_processing = false;
	new Form.Element.Observer('zip_field', 0.01, zipsearch);
}
/*
** The callback function which will be called every 0.01s:
**   - switches on the number of characters typed
**   - and in case, launch the request
**/
function zipsearch() {
  if (document.getElementById('zip_field').value.length >= 8) {
    if (is_processing) return false;

  is_processing = true;
  Element.show($('waitzip')); // display eggtimer
  var url = 'includes/wsgetzip.php'      // cross-domain not allowed -> calling local file
  var params = 'cep='+$F('zip_field');
  var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: params,
      onComplete: zipsearchLoad
    }
  );

  }

}

 /*
 ** function called when the request have been completed
 **   - loads results into results area
 */
function zipsearchLoad(response) {
    Element.hide($('waitzip')); //hide eggtimer
    is_processing = false;
    eval(response.responseText);
    $('city_field').value = unescape(resultadoCEP['cidade']);
    $('address_1_field').value = unescape(resultadoCEP['tipo_logradouro'])+' '+unescape(resultadoCEP['logradouro']);
    Field.activate('address_2_field');

    $A($('state')).each(function(option,i){
        if(option.value == unescape(resultadoCEP['uf']))
            $('state').options.selectedIndex = i;
    });
}

//we execute init() function:
Event.observe(window, 'load', init, false);
