$(function() {
	
	//initEdit();
	initRoles();
//	initProvince();
//	initProducts();
//	initPlatforms();
	initValidate();
	
	$("#btn_save").click(function() {
		alert(222);
		submit();
	});

	if (readOnly) {
		$("input").attr("disabled", "disabled");
		$("select").attr("disabled", "disabled");
		$('#organType').attr("disabled",false);
		$("#btn_save").hide();
	}
	
	//选择不同组织类型时存储勾选商户
	var organType = null;
	$('#organType').change(function(){
		var str = "";
		$('.classOrgan').each(function(){
			if($(this).attr("checked")=="checked"){
				str =  $(this).val()+":"+$(this).parent().text()+"/"+str;
			}
		})
		if($('#organType').val()=='order_meal'){
			$('#OrganIdWifi').val(str);
		}else{
			$('#OrganIdMeal').val(str);
		}
		var url = ctx + "/user/returnOrganList?organType="+$('#organType').val();
		$('#modelBody').load(url,function(){
			$('#dataAuthModal').show();
			if($('#loginName').val()!=''){
				$.ajax({
					url : ctx + "/user/showModelForEdit",
					type : "POST",
					dataType : 'json',
					data : [ {
						name : 'loginName',
						value : $('#loginName').val()
					},{
						name : 'organType',
						value : $('#organType').val()
					} ],
					success : function(data) {
						adornToModel(data);
						if(readOnly){	
							$("#modelBody :checkbox").attr("disabled","disabled");
							
							$("#addDevice").attr("disabled","disabled");
						}
					}
				});
			}
		});
		
	});
	
});

function initProducts(){
	var p = $('#productIds').multiselect({
		checkAllText : "全选",
		uncheckAllText : "全部取消",
		noneSelectedText : "请选择产品",
		selectedText : "已选择#项",
		minWidth: 170,
		selectedList : 4
	}).empty();
	p.multiselect("refresh");
	$.ajax({
		url : ctx + "/anon/getPermitProducts",
		type : 'POST',
		dataType : 'json',
		async : false,
		data : [{
			name : 'loginName',
			value : curUserLoginName
		}],
		success : function(data) {
			var userProductIds = $.map(userProducts,function(a){
				return a.id;
			})
			$.each(data,function(i,product){
				if($.inArray(product.id,userProductIds)<0){
					p.append("<option value='{1}'>{0}</option>".format(product.cnName,product.id));
				}else {
					p.append("<option value='{1}' selected='selected'>{0}</option>".format(product.cnName,product.id));
				}
			});
			p.multiselect("refresh");
		}
	})
	$("#productIds").change(function(){
		initPlatforms();
	});
}

function initPlatforms(){
	var p = $('#platformIds').multiselect({
		checkAllText : "全选",
		uncheckAllText : "全部取消",
		noneSelectedText : "请选择平台",
		selectedText : "已选择#项",
		minWidth: 170,
		selectedList : 4
	}).empty();
	p.multiselect("refresh");
	var productIds = $("#productIds").val();
	if(!productIds) return;
	$.ajax({
		url : ctx + "/anon/getPermitPlatforms",
		type : 'POST',
		dataType : 'json',
		async : false,
		data : [{
			name : 'loginName',
			value : curUserLoginName
		},{
			name : 'productIds',
			value : productIds
		}],
		success : function(data) {
			var userPlatformIds = $.map(userPlatforms,function(a){
				return a.id;
			})
			$.each(data,function(i,platform){
				if($.inArray(platform.id,userPlatformIds)<0){
					p.append("<option value='{1}'>{0}</option>".format(platform.name,platform.id));
				}else {
					p.append("<option value='{1}' selected='selected'>{0}</option>".format(platform.name,platform.id));
				}
			});
			p.multiselect("refresh");
		}
	})
}

function initProvince() {
	var p = $("#province").empty();
	$.ajax({
		url : ctx + "/area/permitProvinces",
		type : 'POST',
		dataType : 'json',
		success : function(data) {
			if (data.length == 1) {
				p.empty();
			}
			var ids = [];
			$.each(data, function(i, a) {
				ids.push(a.id);
				p.append("<option value='{0}'>{1}</option>".format(a.aiid, a.name));
			});
			if ($.inArray(userProvinceId, ids) >= 0) {
				p.val(userProvinceId);
			}
			initCity();
		}
	});
	p.change(function() {
		initCity();
	});
}

function initCity() {
	var c = $("#city").empty();
	c.append("<option value=''>选择城市</option>");
	$.ajax({
		url : ctx + "/area/permitCitys",
		type : 'POST',
		dataType : 'json',
		data : [ {
			name : 'provinceId',
			value : $("#province").val()
		} ],
		success : function(data) {
			if (data.length == 1) {
				c.empty();
			}
			var ids = [];
			$.each(data, function(i, a) {
				ids.push(a.id);
				c.append("<option value='{0}'>{1}</option>".format(a.aiid, a.name));
			});
			if ($.inArray(userCityId, ids) >= 0) {
				c.val(userCityId);
			}
		}
	});
}

function initPasswordValidate() {
	$("#password_form").validate({
		onfocusout : false,
		onkeyup : false,
		onclick : false,
		focusInvalid : true,
		rules : {
			oldPassword : {
				required : true,
				maxlength : 32,
				minlength : 6
			},
			newPassword : {
				required : true,
				maxlength : 32,
				minlength : 6
			},
			confirmPassword : {
				required : true,
				equalTo : '#newPassword'
			}
		},
		showErrors : function(errorMap, errorList) {
			$(this.currentForm).find("span.error").remove();
			if (errorList.length > 0) {
				var err = errorList[0];
				var el = $(err.element);
				var target = el.parentsUntil('form', '.controls');
				target.append("<span class='error'>{0}</span>".format(err.message));
			}
		}
	});
}

function showModel(loginName){
	adornSelect(loginName);
	organType = $('#organType').val();
	var url = ctx + "/user/showModel?organType="+organType;
	$('#modelBody').load(url,function(){
		$('#dataAuthModal').show();
		if(loginName!=''){
			$.ajax({
				url : ctx + "/user/showModelForEdit",
				type : "POST",
				dataType : 'json',
				data : [ {
					name : 'loginName',
					value : loginName
				},{
					name : 'organType',
					value : $('#organType').val()
				} ],
				success : function(data) {
					adornToModel(data);
					if(readOnly){
						$("#modelBody :checkbox").attr("disabled","disabled");
						$("#addDevice").attr("disabled","disabled");
					}
				}
			});
		}
	});	
}

function adornSelect(loginName){
	var count=$("#organType option").length;
	if(loginName!=0){
		$.ajax({
			url : ctx + "/user/returnOrganType",
			type : "POST",
			dataType : 'json',
			async: false,
			data : [ {
				name : 'loginName',
				value : loginName
			}],
			success : function(data) {				
				for(var i=0;i<count;i++){
					var organType = $("#organType").get(0).options[i].value;
					if(organType == data.organType){  
			            $("#organType").get(0).options[i].selected = true;  			          
			            break;  
			        }  
			    }
			}
		});
	}else{
		for(var i=0;i<count;i++){
			if($("#organType").get(0).options[i].value == "order_meal"){  
	            $("#organType").get(0).options[i].selected = true;  			          
	            break;  
	        }  
	    }
	}

}

//暂停函数  
function Pause(obj,iMinSecond){   
   if (window.eventList==null) window.eventList=new Array();   
   var ind=-1;   
   for (var i=0;i<window.eventList.length;i++){   
       if (window.eventList[i]==null) {   
         window.eventList[i]=obj;   
         ind=i;   
         break;   
        }   
    }   
   if (ind==-1){   
   ind=window.eventList.length;   
   window.eventList[ind]=obj;   
   }   
  setTimeout("GoOn(" + ind + ")",iMinSecond);   
}   
  
//继续函数  
function GoOn(ind){   
  var obj=window.eventList[ind];   
  window.eventList[ind]=null;   
  if (obj.NextStep) obj.NextStep();   
  else obj();   
}   


function adornToModel(data){

	var resList = data.resList;
	var cityList = new Array();
	var organList= new Array();
	for(var i = 0;i<resList.length;i++){
	
		var provinceId = resList[i].provinceId;
		$('#pro_'+provinceId).attr("checked","checked");
		cityList.push(resList[i].latnList);
	}
	for(var i=0;i<cityList.length;i++){
		var citys = cityList[i];
		for(var j = 0;j<citys.length; j++){
			var cityId = citys[j].latnId;
			$('#city_'+cityId).attr("checked","checked");
			organList.push(citys[j].organList);
		}
	}
	for(var i=0;i<organList.length;i++){
		var organs = organList[i];
		for(var j = 0;j<organs.length;j++){
			var OrganIdWifi = organs[j].organCode;
			$('#organ_'+OrganIdWifi).attr("checked","checked");
		}
	}
	
}


function checkBoxProvince(obj,provinceId){
	if($('#'+obj.id).attr("checked")=="checked"){
		$('.checkBoxLatn_'+provinceId).attr("checked","checked");
		$('.checkBoxOrgan_'+provinceId).attr("checked","checked");
	}else{
		$('.checkBoxLatn_'+provinceId).attr("checked",false);
		$('.checkBoxOrgan_'+provinceId).attr("checked",false);
	}
}

function checkBoxCity(obj,pro,latnId,index){
	if($('#'+obj.id).attr("checked")=="checked"){
		$('.subCheck_'+latnId).attr("checked","checked");
	}else{
		$('.subCheck_'+latnId).attr("checked",false);
		if($('#'+obj.id).parent().parent().siblings().find('input').attr("checked")=="checked"){
			return;
		}else{
			$('#pro_'+pro).attr("checked",false);
		}
		
	}
}

function addOrgan(){
	var str = "";
	$('.classOrgan').each(function(){
		if($(this).attr("checked")=="checked"){
			str =  $(this).val()+":"+$(this).parent().text()+"/"+str;
		}
	})
	if($('#organType').val()=='order_meal'){
		$('#OrganIdMeal').val(str);
	}else{
		$('#OrganIdWifi').val(str);
	}
	$('#OrganId').val($('#OrganIdMeal').val()+$('#OrganIdWifi').val());
	$("#dataAuthModal").modal("hide");
	//alert($('#OrganIdWifi').val());
}

function generateProvinceList(data){
	var provinceList = data.provinceList;
	for(var i=0;i<provinceList.length;i++){
		$('#modelBody').append(" <li class=\"provinceLi\"><label><input class=\"provinceCheck\" id=province_"+i+" onclick=\"checkBoxClick(this,"+provinceList[i].aiid+")\" name=\"Fruit\" type=\"checkbox\" value="+provinceList[i].aiid+" />"+provinceList[i].name+"</label></li>");
	}
}

function checkBoxClick(obj,aiid){
	
	if($('#'+obj.id).attr("checked")=="checked"){
		$.ajax({
			url : ctx + "/user/showCity",
			type : "POST",
			dataType : 'json',
			data : [ {
				name : 'province',
				value : aiid
			} ],
			success : function(data) {
				//generateProvinceList(data);
				generateCityList(data);
			}
		});
	}else{
		$('#'+obj.id).parent().parent().children().remove();
	}

}

function generateCityList(data){
	var par = data.cityList[0].parentId;
	$('.provinceCheck').each(function(){
		if($(this).val()==par){
			var cityList = data.cityList;
			for(var i=0;i<cityList.length;i++){
				$(this).parent().parent().append("<ul class=\"cityUl\"><label><input name=\"Fruit\" onclick=\"cityCheckOnclick(this,"+cityList[i].aiid+")\" class=\"checkBoxCity\" type=\"checkbox\" value="+cityList[i].aiid+" />"+cityList[i].name+"</label></ul>");
			}
		}
	});
}

function cityCheckOnclick(obj,aiid){
	if($('#'+obj.id).attr("checked")=="checked"){
		$.ajax({
			url : ctx + "/user/showOrgan",
			type : "POST",
			dataType : 'json',
			data : [ {
				name : 'latnId',
				value : aiid
			} ],
			success : function(data) {
				//generateProvinceList(data);
				generateOrganList(data);
			}
		});
	}else{
		//$('#'+obj.id).remove();
	}
}

function generateOrganList(data){
	var city = data.organList[0].latnId;
	$('.checkBoxCity').each(function(){
		if($(this).val()==city){
			var organList = data.organList;
			for(var i=0;i<organList.length;i++){
				$(this).parent().parent().append("<li class=\"shopLi\"><ul class=\"shopUl\" id=\"\"><label><input name=\"Fruit\" type=\"checkbox\" value="+organList[i].organ_code+" />"+organList[i].organ_name+"</label></ul></li>");
			}
		}
	});
	var organList = data.organList;
	
	for(var i=0;i<cityList.length;i++){
		var flag = cityList[i].aiid;
		alert(data.flag);
	}
}

function initValidate() {
	$("#user_form").validate({
		onfocusout : false,
		onkeyup : false,
		onclick : false,
		focusInvalid : true,
		rules : {
			loginName : {
				required : true,
				maxlength : 32,
				remote : {
					url : ctx + '/user/checkLoginName',
					type : 'POST',
					dataType : 'json',
					async : false,
					data : [ {
						name : 'id',
						value : function() {
							return $("#id").val();
						}
					}, {
						name : 'loginName',
						value : function() {
							return $("#loginName").val();
						}
					} ]
				}
			},
			trueName : {
				required : true,
				maxlength : 32
			},
			email : {
				email : true,
				remote : {
					url : ctx + '/user/checkEmail',
					type : 'POST',
					dataType : 'json',
					async : false,
					data : [ {
						name : 'id',
						value : function() {
							return $("#id").val();
						}
					}, {
						name : 'email',
						value : function() {
							return $("#email").val();
						}
					} ]
				}
			},
			phone : {
				digits : true,
				maxlength : 11,
				minlength : 11
			},
			roleIds : {
				required : true
			}
		},
		showErrors : function(errorMap, errorList) {
			$(this.currentForm).find("span.error").remove();
			if (errorList.length > 0) {
				var err = errorList[0];
				var el = $(err.element);
				var target = el.parentsUntil('form', '.controls');
				target.append("<span class='error'>{0}</span>".format(err.message));
			}
		}
	});
}

function submit() {
	alert(111);
	if(!$("#user_form").valid()){
		return;
	}
	$("#btn_save").attr("disabled", "disabled");
	
	//生成选择角色
	var str="";
	$("#roles").find('input').each(function(){ 
        if($(this).attr("checked")){
            str += $(this).val()+","
        }
    })
    alert(str);
	$('#roleIds').val(str);
	return;
	$.ajax({
		url : ctx + "/user/save",
		type : "POST",
		dataType : 'json',
		data : $("#user_form").serializeArray(),
		complete : function() {
			$("#btn_save").removeAttr("disabled");
		},
		success : function(user) {
			$("#id").val(user.id);
			history.go(-1);
		}
	});

}

function initEdit() {
	var id = $("#id").val();
	if (id) {
		$.ajax({
			url : ctx + "/user!findById.do",
			type : "POST",
			dataType : 'json',
			async : false,
			data : [ {
				name : 'id',
				value : id
			} ],
			success : function(user) {
				if(user!=null) {
					renderUser(user);
				}
			}
		});
	}

}

function renderUser(user) {
	window.user = user;
//	var level = user.area.level;
//	if (level == 1 || level == 2) {
//		window.userProvinceId = user.area.id;
//	}
//	if (level == 3) {
//		window.userProvinceId = user.area.parentId;
//		window.userCityId = user.area.id;
//	}
	$.ajax({
		url : ctx + "/user!findRolesByUser.do",
		type : "POST",
		dataType : 'json',
		async : false,
		data : [ {
			name : 'userId',
			value : user.id
		} ],
		success : function(roles) {
			window.userRoles = roles;
			$.each(roles, function(i, role) {
				window.userRoleIds.push(role.id);
			});
		}
	});
	
	$("#loginName").val(user.loginName);
	$("#trueName").val(user.trueName);
	$("#status").val(user.status);
	$("input[name='sex'][value='{0}']".format(user.sex)).prop({
		checked : true
	});
	$("#phone").val(user.phone);
	$("#email").val(user.email);
	$("#dataAuth").attr("onclick","showModel('"+user.loginName+"');")

}

function initRoles() {
	var html = $("#roles").html();
	$("#roles").empty();
	$.ajax({
		url : ctx + "/user!permitRoles.do",
		type : "POST",
		dataType : 'json',
		async : false,
		maskTarget : '#permission_tab',
		success : function(roles) {
			var roleIds = $.map(roles,function(role){
				return role.id;
			})
			$.each(userRoles,function(i,a){
				if($.inArray(a.id,roleIds)<0){
					var roleEl = $("#roles").append(html.format(a.id,a.name));
					roleEl.find("input").prop({checked : true}).attr("disabled","disabled");
				}
			})
			
			$.each(roles, function(i, a) {
				$("#roles").append(html.format(a.id,a.name));
				if ($.inArray(a.id, userRoleIds)<0) {
				}else {
					$("#roles #role_{0}".format(a.id)).prop({
						checked : true
					});
				}
			});
		}
	});
}
