/**
 * @author Administrator
 */
var zp;
if (!zp)
    zp = {};
if (!zp.ui)
    zp.ui = {};
window.zp.ui = zp.ui;

zp.ui.locationSelector = {
	_area:null,
	_city:null,
	_province:null,
	
	doSelect:function(obj){
		this._province=obj.province;
		this._city=obj.city;
		this._area=obj.area;
		
		var isInited=obj.init;
		var _default=obj.withDefault;
		var _self=this;
		
		if(isInited){
		  this._init();	
		}
		
		$(_self._province).change(function(){
			var provinceId=$(this).val();
			_self.fillCity(provinceId,_default,0);
			$(_self._area).hide();
		})
		
		$(_self._city).change(function(){
			var cityId=$(this).val();
			if(cityId=='2687'){//if the selected value is anhui province
			    $(_self._area).show();
			    _self.fillArea(cityId, _default, 0);
			}else{
				$(_self._area).hide();
			}
		})
	},
	_init:function(obj){
		this.fillProvince(0);
		$(this._area).hide();
	},
	addDefault:function(target,info){
		$(target).append('<option value=' + 0 + '>' + info + '</option>');
	},
	fillProvince:function(value){
		 var _self=this;
		 $(provinces).each(function(){
		 	var option='<option value=' + $(this).attr('id');
			if(value==$(this).attr('id')){
				option += ' selected=true'
			}
			option+='>' + $(this).attr('name') + '</option>'
            $(_self._province).append(option);
        });
	},
	fillCity:function(provinceId,_default,value){
		var _self=this;
		$(_self._city).empty();
		if(_default){
			this.addDefault(_self._city,'市');
		}
		if(provinceId=='0'){
			this.addDefault(_self._city,'市');
		}
		$(cities).each(function(){
			if($(this).attr('pid')==provinceId){
				var option='<option value=' + $(this).attr('id');
				if($(this).attr('id')==value){
					option += ' selected=true'
				}
				option+='>' + $(this).attr('name') + '</option>'
				$(_self._city).append( option );
			}
		})
	},
	fillArea:function(cityId,_default,value){
		var _self=this;
		$(_self._area).empty();
		if (_default) {
		  this.addDefault(_self._area,'区');
		}
		$(areas).each(function(){
			if ($(this).attr('cid') == cityId) {
				var option='<option value=' + $(this).attr('id');
				if($(this).attr('id')==value){
					option += ' selected=true'
				}
				option+='>' + $(this).attr('name') + '</option>';
				$(_self._area).append(option);
			}
		})
	},
	initForm : function(target){
		var fields=($(target).val()).split(',');
		
		this.fillProvince(fields[0]);
		this.fillCity(fields[0],false,fields[1]);
		if(fields.length<=2){
			$(this._area).hide();
		}else{
			$(this._area).show();
			this.fillArea(fields[1],false,fields[2]);
		}
	},
	bindForm:function(target){
		var province=$(this._province).val();
		var city=$(this._city).val();
		var area=$(this._area).val();
		
		var data=provice+','+city;
		if(area!=''&&area!=null&&area!='0'){
			data+=area;
		}
		$(target).val(data);
	}
}