// Scriptaculous Autocomplete Event Handler

//see http://tetlaw.id.au/view/blog/adding-a-local-cache-to-ajaxautocompleter/
Ajax.CachedAutocompleter = Class.create();
    Object.extend(Object.extend(Ajax.CachedAutocompleter.prototype, Autocompleter.Base.prototype), {
      initialize: function(element, update, url, options) {
        this.baseInitialize(element, update, options);
        this.options.asynchronous  = true;
        this.options.onComplete    = this.onComplete.bind(this);
        this.options.defaultParams = this.options.parameters || null;
        this.url                   = url;
        this.cache                 = {};
      },
   
      getUpdatedChoices: function() {
        var t = this.getToken();
        if(this.cache[t]) {
            this.updateChoices(this.cache[t]);
        } else {
            entry = encodeURIComponent(this.options.paramName) + '=' + 
              encodeURIComponent(t);
  
            this.options.parameters = this.options.callback ?
              this.options.callback(this.element, entry) : entry;
  
            if(this.options.defaultParams) 
              this.options.parameters += '&' + this.options.defaultParams;
  
            new Ajax.Request(this.url, this.options);
        }
      },
      onComplete: function(request) {
        this.updateChoices(this.cache[this.getToken()] = request.responseText);
      }
    }); 

aC = {
init: function()
	{
        if($('Country_auto_complete'))
		{
          new Ajax.CachedAutocompleter('Country', 'Country_auto_complete', '/keylist.php', {autoSelect: 'true'});
        }

		if($('State_auto_complete'))
		{
          new Ajax.CachedAutocompleter('State_Province', 'State_auto_complete', '/keylist.php', {autoSelect: 'true'});
        }

		if($('City_auto_complete'))
		{
          new Ajax.Autocompleter('City', 'City_auto_complete', '/keylist.php', {
		  							autoSelect: 'true',
									minChars: '2',
									afterUpdateElement: aC.ajaxUpdateFields});
        }

		//give first form element focus
		if(document.forms[0])
		{
			$A($$('#header1 input')).each(function(el)
			{
				el.observe('focus',function(el){
					Event.element(el).setStyle({
						background:'#f3ba21'});
				});

				el.observe('blur',function(el){
					Event.element(el).setStyle({
						backgroundImage:'url(/images/forminput.gif)'});
				});
			});

			Form.focusFirstElement(document.forms[0]);

			$('Email').value		  = '@';
		}
    },

ajaxUpdateFields: function(field, el)
		{
				var city  		   = field.value;										//get the city name
				var stateClassName = 'informal';
				var urlState	   = 'fillstate.php';

				// search for the text inside the SPAN named 'informal' (i.e. the abbriviation of the state
				el.descendants().each(function(el)
				{
					if(stateClassName == el.className)
                    {
						//console.log(e.innerHTML);	// innerHTML is similar to 'firstChild.nodeValue'
						var myAjax = new Ajax.Request( urlState, { method: 'get',
													   parameters: 's=' + el.innerHTML,
													   onComplete: aC.fillState });
                        if(el.innerHTML.match(/.{4,39}/))     // min. and max length of city name
                        {
                            $('Postal_Code').value = el.innerHTML;
                            $('Email').focus();
                        }
                    }
				});
		},

fillState:	function(request)
	{
		$('State_Province').value = request.responseText;
		//$('Country').value = 'United States of America';

	}

};

Event.observe(window, "load", aC.init);