define(function(require){
	var $ = require('jquery');
	require('grid')($);
	require('uriTemplate')($);
	require('dialog')($);
    require("../../../styles/cim/jquery-ui-1.8.14.custom.css"); 
    require('../../../styles/cim/cim-grid.css'); 
    var IFA = require('util');
    
    $(function(){
    	   $("#province").one("click",function(){getProvince();});
		   $("#province").change(function(){getDistrictForId();});
		   $("#district").change(function(){getTownForId();});
		   
		   $("#district").attr("disabled","disabled");
		   $("#town").attr("disabled","disabled");
		   
		   $('#btnSaveProvince').bind("click",function(){
			   insertProvince();
			   return false;
			});
		   
		   $('#btnSaveDistrict').bind("click",function(){
			   insertDistrict();
			   return false;
			});
		   
		   $('#btnSaveTown').bind("click",function(){
			   insertTown();
			   return false;
			});
		   
		   $("#resetBtn").bind("click",reset);
	  });

    
    function getProvince(){
		   var params ={"rankID":0,"parentId":0};
		   var getUrl = $("#getUrl").val()+".json";
		   $.ajax({
			   url:getUrl,
			   type:"POST",
			   data:params,
			   dataType:"json",
			   success:function(response,ioArgs){
			       var list = response.cityList;
			       if(list!=null && list.length>0){
			    	   $("#province").empty();
					   $("<option></option>").val(-1).text(i18n["Title.city.choose"]).appendTo($("#province"));
					   $.each(list,function(index,item){
						    $("<option></option>").val(item.id).text(item.name).appendTo($("#province"));
					   });	
			       }
		    	   	resetSelect($("#town"));
			   		resetSelect($("#district"));
			        freshNewAndDel($("#districtDel"),$("#districtNew"),false);
		       }		   
		   })
		   ;

	   };
	   
	   
	// 获取城市级别信息
	   function getDistrictForId(){
		   var parentId = $("#province").val(); // 获取父节点编号
		   if(parentId>0){
			   var params ={"rankID":1,"parentId":parentId};
			   var getUrl = $("#getUrl").val()+".json";
			   $.ajax({
				   url:getUrl,
				   type:"POST",
				   data:params,
				   dataType:"json",
				   success:function(response,ioArgs){
				       var list = response.cityList;
				       if(list!=null && list.length>0){
				    	   $("#district").empty();
						   $("<option></option>").val(-1).text(i18n["Title.city.choose"]).appendTo($("#district"));
						   $.each(list,function(index,item){
							    $("<option></option>").val(item.id).text(item.name).appendTo($("#district"));
						   });
						   $("#district").removeAttr("disabled"); 
				       }else{				    	   
					   		resetSelect($("#district"));
				    	}
			       }
			   });

		   }else{
		   		resetSelect($("#district"));
		   }
		   if($("#province").val() != -1){			   
			   freshNewAndDel($("#districtDel"),$("#districtNew"),true);
		   }
		   else{
			   freshNewAndDel($("#districtDel"),$("#districtNew"),false);
		   }
	       freshNewAndDel($("#townDel"),$("#townNew"),false);
		   resetSelect($("#town"));
	   };
	   
		// 获取城市级别信息
	   function getTownForId(){
		   var parentId = $("#district").val(); // 获取父节点编号
		   if(parentId>0){
			   var params ={"rankID":2,"parentId":parentId};
			   var getUrl = $("#getUrl").val()+".json";
			   $.ajax({
				   url:getUrl,
				   type:"POST",
				   data:params,
				   dataType:"json",
				   success:function(response,ioArgs){
				       var list = response.cityList;
				       if(list!=null && list.length>0){
				    	   $("#town").empty();
						   $("<option></option>").val(-1).text(i18n["Title.city.choose"]).appendTo($("#town"));
						   $.each(list,function(index,item){
							    $("<option></option>").val(item.id).text(item.name).appendTo($("#town"));
						   });
						   $("#town").removeAttr("disabled"); 
				       }
				       else{
				    	   resetSelect($("#town"));
				       }
				       freshNewAndDel($("#townDel"),$("#townNew"),true);
			       }
			   });
		   }else{	
			   freshNewAndDel($("#townDel"),$("#townNew"),false);
			   resetSelect($("#town"));
		   }
	   };
	   
	   function resetSelect($obj){
		   $obj.empty();
		   $("<option></option>").val(-1).text(i18n["Title.city.choose"]).appendTo($obj);
		   $obj.attr("disabled","disabled");
		   
		   if($obj.attr("id") == "district"){
			   freshNewAndDel($("#townDel"),$("#townNew"),false);
		   }
	   }
	    
	    $("#provinceDel").click(function(){
	    	var provinceId = $("#province").val();
	    	if(provinceId == -1){
				$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.city.DeleteProvinceCheck"],{
				    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
				        $(this).dialog("close");
				    }), //buttons结束
				   width:350,height:150
		 	 });
				return;
	    	}
	    	$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.Sure.tip"],{
				  buttons:IFA.generateJson(i18n["Entity.page.YES"],function() {
					  
			    	   var params ={"id":provinceId};
					   var delUrl = $("#delUrl").val()+".json";
					   $.ajax({
						   url:delUrl,
						   type:"POST",
						   data:params,
						   dataType:"json",
						   success:function(response,ioArgs){
							     $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.succeed"],{
			  		    		 buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
									        $(this).dialog("close");
									        getProvince();
									        }),
									   width:350,height:150
							 	 });
						   },
				    	        error:function(response,ioArgs){
				    	        	$(this).dialog("close");
									 $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.failed"],{
										    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
										        $(this).dialog("close");
										        getProvince();
										    }), //buttons结束
										   width:350,height:150
								 	 });// $.msg.alert()结束
				    	        }
				    	   });
					   		freshNewAndDel($("#districtDel"),$("#districtNew"),false);					   		
					   		resetSelect($("#district"));
					   		resetSelect($("#town"));
					   		$('#txtProvince').hide();
					   		$('#btnSaveProvince').hide();
			    	       $(this).dialog("close");
					   },i18n["Entity.page.No"],function() {$(this).dialog("close");}
		 		 ),
				width:350,height:150
		 		});
	    	
	    	
	    });
	    
	    $("#districtDel").click(function(){
			var districtId = $("#district").val();
	    	if(districtId == -1){
				$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.city.DeleteDistinctCheck"],{
				    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
				        $(this).dialog("close");
				    }), //buttons结束
				   width:350,height:150
		 	 });
				return;
	    	}
	    	$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.Sure.tip"],{
				  buttons:IFA.generateJson(i18n["Entity.page.YES"],function() {

			    	   var params ={"id":districtId};
					   var delUrl = $("#delUrl").val()+".json";
					   $.ajax({
						   url:delUrl,
						   type:"POST",
						   data:params,
						   dataType:"json",
						   success:function(response,ioArgs){
							     $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.succeed"],{
			  		    		 buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
									        $(this).dialog("close");
									        getDistrictForId();
									        }),
									   width:350,height:150
							 	 });
						   },
				    	        error:function(response,ioArgs){
				    	        	$(this).dialog("close");
									 $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.failed"],{
										    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
										        $(this).dialog("close");
										        getDistrictForId();
										    }), //buttons结束
										   width:350,height:150
								 	 });// $.msg.alert()结束
				    	        }
				    	   });
					   resetSelect($("#town"));
			    	   $(this).dialog("close");
					   },i18n["Entity.page.No"],function() {$(this).dialog("close");}
		 		 ),
				width:350,height:150
		 		});
	    });
	    
	    $("#townDel").click(function(){
	    	var townId = $("#town").val();
	    	if(townId == -1){
				$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.city.DeleteTownCheck"],{
				    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
				        $(this).dialog("close");
				    }), //buttons结束
				   width:350,height:150
		 	 });
				return;
	    	}
	    	$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.Sure.tip"],{
				  buttons:IFA.generateJson(i18n["Entity.page.YES"],function() {

			    	   var params ={"id":townId};
					   var delUrl = $("#delUrl").val()+".json";
					   $.ajax({
						   url:delUrl,
						   type:"POST",
						   data:params,
						   dataType:"json",
						   success:function(response,ioArgs){
							     $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.succeed"],{
			  		    		 buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
									        $(this).dialog("close");
									        getTownForId();
									        }),
									   width:350,height:150
							 	 });
						   },
				    	        error:function(response,ioArgs){
				    	        	$(this).dialog("close");
									 $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.delete.failed"],{
										    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
										        $(this).dialog("close");
										        getTownForId();
										    }), //buttons结束
										   width:350,height:150
								 	 });// $.msg.alert()结束
				    	        }
				    	   });
			    	       $(this).dialog("close");
					   },i18n["Entity.page.No"],function() {$(this).dialog("close");}
		 		 ),
				width:350,height:150
		 		});
	    });


	    $('#provinceNew').click(function(){	
	    	switchHidden($('#txtProvince'),$('#btnSaveProvince'));
			return false;
		});
	    
	    $('#districtNew').click(function(){	
	    	switchHidden($('#txtDistrict'),$('#btnSaveDistrict'));
			return false;
		});

	$('#townNew').click(function(){	
		switchHidden($('#txtTown'),$('#btnSaveTown'));
		return false;
	});
	
	function switchHidden($obj1, $obj2){
    	if($obj1.is(":hidden")){
    		$obj1.show();
    		$obj2.show();	
    	}
    	else{
    		$obj1.hide();
    		$obj2.hide();	
    	}
	}
	
	function submitInsert(params,refreshobj){
		var addUrl = $("#addUrl").val()+".json";
		   $.ajax({
			   url:addUrl,
			   type:"POST",
			   data:params,
			   dataType:"json",
			   success:function(response,ioArgs){	
				   
				   if(response.message != "success"){
					   $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.Date.repeat"],{
						    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
						        $(this).dialog("close");
						    }), //buttons结束
						   width:350,height:150
				 	 });
					 return ;
					   
				   }
				   if(refreshobj == 0){
					   getProvince();
					}
				   else if (refreshobj == 1){
					   getDistrictForId();
				   }
				   else if (refreshobj == 2){
					   getTownForId();
				   }
				   
				   $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.cityAdd.success"],{
					    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
					        $(this).dialog("close");
					    }), //buttons结束
					   width:350,height:150
			 	 });
		       },
   	           error:function(response,ioArgs){
				 $.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.cityAdd.fail"],{
					    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
					        $(this).dialog("close");
					    }), //buttons结束
					   width:350,height:150
			 	 });// $.msg.alert()结束
	        }
		   });
	}
	
	function insertProvince(){
		 	$("#btnSaveProvince").attr({"disabled":"disabled"});
			var province = $("#txtProvince").val();
			if(province.length > 0){
				var params ={"rankID":0, "parentId":0, "name":province};
				submitInsert(params,0);
			}		
			$("#txtProvince").val("");
			$("#btnSaveProvince").removeAttr("disabled");
			
	};
	
	function insertDistrict(){
		var provinceId = $("#province").val();		
		if(provinceId < 0) {
			$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.city.InsertDistinctCheck"],{
			    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
			        $(this).dialog("close");
			    }), //buttons结束
			   width:350,height:150
	 	 });
			return;
		}
	 	$("#btnSaveDistrict").attr({"disabled":"disabled"});
		var province = $("#txtDistrict").val();
		if(province.length > 0){
			var params ={"rankID":1, "parentId":provinceId, "name":province};
			submitInsert(params,1);
		}		
		$("#txtDistrict").val("");
		$("#btnSaveDistrict").removeAttr("disabled");
		
	};

	function insertTown(){
		var districtId = $("#district").val();		
		if(districtId < 0) {
			$.msg.alert(i18n["Page.title.dialogshow.title"], i18n["Entity.city.InsertTownCheck"],{
			    buttons: IFA.generateJson(i18n["Entity.Operation.ok"], function() {
			        $(this).dialog("close");
			    }), //buttons结束
			   width:350,height:150
	 	 });
			return;
		}
		$("#btnSaveTown").attr({"disabled":"disabled"});
		var province = $("#txtTown").val();
		if(province.length > 0){
			var params ={"rankID":2, "parentId":districtId, "name":province};
			submitInsert(params,2);
		}
		$("#txtTown").val("");
		$("#btnSaveTown").removeAttr("disabled");
	
	};
	
	function reset(){
		$("input[type='text']").val("");
		$("#town").get(0).value = -1;
		$("#district").get(0).value = -1;
		$("#province").get(0).value = -1;
		$("#town").attr({"disabled":"disabled"});
		$("#district").attr({"disabled":"disabled"});
		freshNewAndDel($("#districtDel"),$("#districtNew"),false);
		freshNewAndDel($("#townDel"),$("#townNew"),false);
		$('#txtTown').hide();
		$('#btnSaveTown').hide();
		$('#txtDistrict').hide();
		$('#btnSaveDistrict').hide();
		$('#txtProvince').hide();
		$('#btnSaveProvince').hide();
	}
	
	function freshNewAndDel($delButton,$newButton,isShow){
		if(isShow){
			$delButton.show();
			$newButton.show();
		}
		else{
			
			$delButton.hide();
			$newButton.hide();
			
			if($delButton.attr("id") == "districtDel"){	
				$("#txtDistrict").hide();
				$("#btnSaveDistrict").hide();
			}
			
			if($delButton.attr("id") == "townDel")
			{
				$("#txtTown").hide();
				$("#btnSaveTown").hide();
			}
		}
	}
	
});