$(function(){

	$("#city-picker").cityPicker({
		toolbarTemplate: '<header class="bar bar-nav">\
			<button class="button button-link pull-right close-picker">确认</button>\
			<h1 class="title">城市区域</h1>\
			</header>'
	});


	var myreg = /(1[3-9]\d{9}$)/;
	var user = fetchUSER();

	fillUSER = function(){
		if(user.nick!=''){
			$("#name").val(user.nick);
		}
		if(myreg.test(user.uname)){
			$("#phone").val(user.uname);
		}
	};


	fetchAddr = function(){
		if(user.hostId==""||user.hostId==0){
			gotoLogin();
			return;
		}
		var _path=buildHTTP("/custom/addr/"+user.hostId+".shtml");
		$.ajax({
			url: _path, 
			type: "get", 
			dataType: "json",
			contentType:"application/json",
			success: function(data) { 
				if(data.code=='01'){
					var _addr = data.content;
					if(_addr!=null){
						$("#addrId").val(_addr.addrId);
						$("#name").val(_addr.name);
						$("#phone").val(_addr.phone);
						$("#addr").val(_addr.addr);
						if(_addr.province!=null && _addr.province!=''){
							$("#city-picker").val(_addr.province+"	"+_addr.city+"	"+_addr.strict);
						}
						if(_addr.first=='1'){
							$("#isDefault").attr("checked","true");
						}
					}else{
						fillUSER();
					}

				}else{
					$.toast("获取地址信息失败");
				}
			}
		});
	}

	fetchAddr(); // 填充地址

	$("#saveBtn").click(function(){
		var addrId = $("#addrId").val();
		var name = $("#name").val();
		var phone = $("#phone").val();
		var addr = $("#addr").val();

		var picker = $.trim($("#city-picker").val());
		var keys =picker.split(/\s+/);
		var province=keys[0],city=keys[1],strict='';
		if(keys.length==3){
			strict = keys[2];
		}
		if(!myreg.test(phone)){
			$.toast("请填写正确的电话号码");
			return;
		}
		if(name==''){
			$.toast("请填写姓名");
			return;
		}
		if(addr==''){
			$.toast("详细地址不能为空");
			return;
		}
		$.confirm("确认保存当前地址？", function(){

			var _method = "post";
			if(addrId==''||addrId=='0'){
				_method = "put";
			}
			var params = {
					addrId:addrId,
					hostId:user.hostId,
					name:name,
					addr:addr,
					phone:phone,
					first:'1',
					province:province,
					city:city,
					strict:strict
			};

			var _path=buildHTTP("/custom/addr.shtml");
			$.ajax({
				url: _path, 
				type: _method, 
				dataType: "json",
				data:$.toJSON(params),   
				contentType:"application/json",
				success: function(data) { 
					if(data.code=='01'){
						$("#addrId").val(data.recordId);
						$.toast("保存成功");
					}else{
						$.toast("保存失败");
					}
				}
			});
		});
	});

	$.init();
});