/**
 * @author robin
 * @package map2fun.control.ui
 * @class LocationSelect
 */
map2fun.control.ui.LocationSelect = function(name){
    map2fun.control.ui.UIElement.call(this, name);
    this.selectors = new Object();
	this.holder = $("#selectArea");
    this._province = new String();
    this._city = new String();
	try{
		this.init();
	}catch(e) {
		var _class = this;
		setTimeout(function() {
			_class.init();
		},1000);
	}
	
};

map2fun.control.ui.LocationSelect.prototype = new map2fun.control.ui.UIElement();
delete map2fun.control.ui.LocationSelect.prototype.status;
delete map2fun.control.ui.LocationSelect.prototype.name;

map2fun.control.ui.LocationSelect.province = new Array();
map2fun.control.ui.LocationSelect.city = new Array();
map2fun.control.ui.LocationSelect.district = new Array();

map2fun.control.ui.LocationSelect.prototype.loadData = function(callback){
    var _class = this;
    $.getJSON("lib/json/areas.json", function(data){
        map2fun.control.ui.LocationSelect.province = data.province;
        map2fun.control.ui.LocationSelect.district = data.district;
        map2fun.control.ui.LocationSelect.city = data.city;
        if (callback) 
            callback();
    });
};

map2fun.control.ui.LocationSelect.prototype.setDefaultLocation = function(){
    var _class = this;
    var geocoder = new GClientGeocoder();
    var userLatLng = new google.maps.LatLng(app.accountManager.clientGeo.latitude, app.accountManager.clientGeo.longitude);
    geocoder.getLocations(userLatLng, function(response){
        if (!response || response.Status.code != 200) {
            app.debug("no results from reverse geocoding!");
        }
        else {
            var node = response.Placemark[0];
            
            _class._province = node.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            _class._city = node.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
            
            var _pCode, _cCode;
            $.each(map2fun.control.ui.LocationSelect.province, function(i, item){
                var str = "<option value='" + item.code + "'>" + item.name + "</option>";
                $(_class.selectors.province).append(str);
                if (item.name == _class._province) {
                    _pCode = item.code;
                }
            });
            _class.selectors.province[0].value = _pCode;
            
            $.each(map2fun.control.ui.LocationSelect.city, function(i, item){
                if (item.code.startsWith(_pCode.substring(0, 2))) {
                    _class.selectors.city.append("<option value='" + item.code + "'>" + item.name + "</option>");
                    if (item.name == _class._city) {
                        _cCode = item.code;
                    }
                }
                
            });
            
            _class.selectors.city[0].value = _cCode;
            _class.selectors.city.change();
            
        }
    });
    
};

map2fun.control.ui.LocationSelect.prototype.get = function(){
    var type = "";
    this.checkbox.each(function(){
        if (this.checked) {
            type += (this.value + ",");
        }
    });
    var info = {
        "province": this.selectors.province.val() == 0 ? "" : this.selectors.province[0].options[this.selectors.province[0].selectedIndex].text,
        "city": this.selectors.city.val() == 0 ? "" : this.selectors.city[0].options[this.selectors.city[0].selectedIndex].text,
        "district": this.selectors.district.val() == 0 ? "" : this.selectors.district[0].options[this.selectors.district[0].selectedIndex].text,
        "key": this.input.val(),
        "types": type
    };
    return info;
};

map2fun.control.ui.LocationSelect.prototype.serialize = function(){
    var o = this.get();
    delete o.types;
    return map2fun.utils.serialize(o);
};

map2fun.control.ui.LocationSelect.prototype.init = function(){
	var _class = this;
	dataControl = app.dataControl;
    this.input = $("input#desc");
    this.button = $("button#goFind").click(function(){
		var key = $("input#desc").val();
		
		$("#selectType, #desc").clearBubble();
		if((app.ui.mainView.activity == "findNode" || app.ui.mainView.activity == "sharePath") && app.ui.location.get().types == "") {
			$("#selectType").bubble(true);
			return false;
		}
        if (key == "" || key == "地点关键词") {
			$("input#desc").bubble(true);
            return false;
		}
			
        app.map.clearOverlays();
        switch (app.ui.mainView.activity) {
            case "findNode":
                dataControl.getUnits();
                break;
            case "shareNode":
                dataControl.getNodes();
                break;
            case "sharePath":
                dataControl.getUnits();
                break;
            case "findPath":
                dataControl.getPaths();
                break;
        };
    });
	
    this.selectors.province = this.holder.find("select[name='province']");
    this.selectors.city = this.holder.find("select[name='city']");
    this.selectors.district = this.holder.find("select[name='district']");
    this.checkbox = $("#selectType").find("input[name='type']");
    this.status = map2fun.COMPONENT_LOADED;
    
    this.input.keydown(function(e){
        if (e.keyCode == 13) {
            _class.button.click();
            return false;
        }
    }).focus(function(e){
        if (e.target.value == "地点关键词") {
            e.target.value == "";
        }
        e.target.select();
    });
    
    
    this.loadData(function(){
    
        $(_class.selectors.city).change(function(evt){
            fetch(evt.target);
        });
        $(_class.selectors.province).change(function(evt){
            fetch(evt.target);
        });
        $(_class.selectors.district).change(function(){
            _class.get();
        });
        
        _class.setDefaultLocation();
    });
    
    function fetch(target){
    
        var _start, //leading string of code
 _result = new Array(), //filtered result array
 _d, //data to be inserted
 _s, //the selector that requested the fetching
 _o, //html string of default option element
 n = target.value;//value of option code in the former select element
        if (zero(n) == 4) {//省份 获取 城市信息
            _start = n.substring(0, 2);
            _s = _class.selectors.city;
            _d = map2fun.control.ui.LocationSelect.city;
            if (!_class._pCode || !_class._cCode) {
                _o = "<option value='0'>请选择一个城市</option>";
            }
            $(_class.selectors.district).find("option[value!='0']").remove();
            
        }
        else {// 城市 获取 区域信息
            _s = _class.selectors.district;
            _start = n.substring(0, 6 - zero(n));
            _d = map2fun.control.ui.LocationSelect.district;
            if (!_class._pCode || !_class._cCode) {
                _o = "<option value='0'>请选择一个区</option>";
            }
        }
        $(_s).find("option").remove();
        if (_o) 
            $(_s).append(_o);
        $.each(_d, function(i, item){
            if (item.code.startsWith(_start)) {
                _result.push(item);
            }
        });
        $.each(_result, function(i, item){
            var str = "<option value='" + _result[i].code + "'>" + _result[i].name + "</option>";
            $(_s).append(str);
        });
        
        /*
         * how many zero are the in the end of a string
         */
        function zero(a){
            var i = a.length, n = 0;
            if (a) {
                while (i > 0) {
                    i--;
                    if (a.charAt(i) == "0") 
                        n++;
                }
            }
            return n;
        };
    };
    
    
}


