/* Copyright (c) 2006 Ceneka Pty. Ltd. */

function xmlHttp (url,id) {
   new liveForm(url,id);
}

var liveForm = Class.create();

liveForm.prototype = {
  
  initialize: function(url,idc) {
    this.url = url;
    this.idc = idc;
    this.retrieve();
  },

  retrieve: function() {
    var xh = new Ajax.Request(this.url, { method:'post',  parameters:'',  onComplete:this.inputFactory.bind(this) });
  },
  	        
  inputFactory: function (req) {

  	var response = req.responseText;
	var array = eval(response);
	var si = '';

	// count number of elements in array
	maxi = array.length;

	// Identify what type of tag we are working with
	// (input, select, div, etc)
	var fields = new Array();

	if (this.idc.indexOf(';') != -1) {
	  fields = this.idc.split(';');
	}
	else {
	  fields[0] = this.idc;
	}

	for (var f = 0; f < fields.length; f++) {
	  field = fields[f];
	  
	  el = document.getElementById(field);
	  tag = el.tagName.toUpperCase();

	  if (tag == 'INPUT' && field == 'city') {
	     $(field).value = array[0].city;
	  }

	  else if (tag == 'SELECT' && field == 'state') {	     
	     var state = document.getElementById(field);
	     var si = 0;
	     for (var ii=0; ii < state.options.length; ii++) {
	       s = state.options[ii].value;
	       if ( s == array[0].state) {
	         si = ii;
	       }
	     }
	     state.selectedIndex = si;
	  }
	 

	  // Select Box
	  else if (tag = 'SELECT') {
		// delete all options first
		with (document.getElementById(field)) {
			for (i=0; i <= options.length; i++) {
				options[i] = null;
			}
		}
			
		// then repopulate with new values
        with (document.getElementById(field)) {
			options[0] = new Option('Please choose...', '');
			for (var i = 0; i <= maxi; i++) {
			    if (typeof(array[i])=="object") {
					options[i] = new Option(array[i].opt, array[i].val);
				} //end if
			} //end for
		} //end with
	  } // end if (Tag = select)



	} // end for
  
  } // end inputFactory
  
} // end class