
var sendZip = Class.create({
	initialize: function(zip_id, city_id){

		this.zip_id  = zip_id;
		this.pref_id = city_id;
		
		this.server_url  = 'test.php';
		this.zip_list_id = 'auto_zip_list';
		this.zip_value   = '';
		
		this.load();
	},
	
	load: function(){
		document.observe('dom:loaded', function() {

			this.zip_value = $F(this.zip_id);

			new PeriodicalExecuter(this.ajax_zip.bind(this), 0.5);

			$(this.pref_id).observe('focus', function(event){
				$(this.zip_list_id).hide();

			}.bind(this));
			
			
			$(this.zip_id).insert({
				after: '<div id="' +this.zip_list_id+ '" style="display:none;position:absolute;z-index:999;background-color:lightyellow;border:solid 1px silver;padding:2px"></div>'

			});
		}.bind(this));
	},
	
	ajax_zip: function(){
		if(this.zip_value == $F(this.zip_id)) return;
		this.zip_value = $F(this.zip_id);
		
		new Ajax.Updater(
			this.zip_list_id,
			this.server_url,
			{
				"method": "get",
				"parameters": "zip=" + this.zip_value,
				
				onSuccess: function(request) {
					if(request.responseText == ''){
						$(this.zip_list_id).hide();
					}else{
						$(this.zip_list_id).show();
						
					}
				}.bind(this),
				
				onComplete: function(request) {

					$$('#' + this.zip_list_id + ' a').each(function(anchor){
						if(anchor.identify() == 'auto_zip_credit'){
							return;
						}
						anchor.observe('click', function(){
							var text = anchor.innerHTML;
							var a = text.split(' ');
							if(a[0]) this.zip_value = a[0];
							if(a[0]) $(this.zip_id).setValue(a[0]);
							if(a[1]) $(this.pref_id).setValue(a[1]);
							$(this.zip_list_id).hide();
						}.bind(this));
					}.bind(this));
				}.bind(this),
				
				onFailure: function(request) {
					$(this.zip_list_id).hide();
				}.bind(this),
				
				onException: function (request) {
					$(this.zip_list_id).hide();
				}.bind(this)
			}
		);
	}
});

