define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('uriTemplate')($);
	require('dialog')($);
	require('dateTimePicker')($);
	require('validation')($);
	require('jqueryCSS');
	require('grid')($);
	require('block')($);
	require('../../../../styles/cim/cim-grid.css');
	require('../../../../styles/cim/validation.css');
	require('../../../../styles/cim/autoComplete.css');
	require('../../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../../js/jquery/jquery.fn.gantt.js')($);
	require('../../../../styles/gantt/style.css');
	var reservationId;
	var innerLocck = true;
	$(function(){
		window.name = "vehicleConditionMap";
		reservationId = $("#reservationId").val();
		hotKeyCity();
		initDate();
		hotKeyDistrict();
		$("#mostrar").click(function(event) {
			event.preventDefault();
			$("#caja").slideToggle();
			this.text('test');
			});

			$(".close").click(function(event) {
			event.preventDefault();
			$("#caja").slideUp();
			});
		//首次可能从其他处进来,可能是空不应该调用
		if($("#startTime").val()!=""&&$("#districtHokKey").val()!=""){
			initGantt();
		}
		bindEvent();
		
		$("#addForm").validate({
			rules:{
			lockDate:{
			required:true	
			},
			unlockDate:{
			required:true	
			}
			},
			messages:{
			lockDate:{
			required:i18ns("VehicleConditionMap.Validate.lockTime")	
			},
			unlockDate:{
			required:i18ns("VehicleConditionMap.Validate.unlockTime")	
			}	
			}
			});
	});
	
	//加载gantt图
	function initGantt(){
		
		   if(!validateCondition()){
			   return;
		   }
		$(".gantt").show();
		var urlStr = new $.Template($("#ganttUrl").val());
		var segmentId = $("#reservationId").val();
		var urlparams = {'reservationId':segmentId};
		var getUrl = urlStr.expand(urlparams);
		
		
		var categoryName = $("#categoryId").find("option:selected").text();
		var para = $("#queryUsabilityMapForm").serialize();

		var monthlyUrl;
		var weeklyUrl;
		if ($("#noMenu").val()=="true") {
			 monthlyUrl=$("#monthlyViewUrl").val();
			weeklyUrl=$("#noMenuWeeklyGanttChartUrl").val();
		}else {
			 monthlyUrl=$("#monthlyViewUrl").val();
			 weeklyUrl=$("#vehicleWeeklyUsabilityUrl").val();
		}
		weeklyUrl=new $.Template(weeklyUrl);
		var districtId=setDefaultParam($("#districtId").val());
		var districtName=setDefaultParam($("#districtHokKey").val());
		var categoryId=setDefaultParam($("#categoryId").val());
		var plateNumber=setDefaultParam($("#plateNumber").val());
		var params = {
		'districtId':districtId,
		'districtName':districtName,
		'categoryId':categoryId,
		'plateNumber':plateNumber,
		'startTime':$("#startTime").val(),
		'leasingType':$("#leasingType").val()
		};
		weeklyUrl=weeklyUrl.expand(params);
		if(innerLocck){
			$.blockUI({
				message:i18ns("Entity.Operation.Wait"),
				timeout:10000,
				css: {color:'#fff',border:'3px solid #aaa'},
				overlayCSS: { opacity:'0.0',top:'108px',left:'208px'}
				});
			innerLocck = false;
		   $.ajax({
			   url:getUrl,
			   type:"POST",
			   dataType:"json",
    		   data:para,
			   timeout:5000,
			   success:function(response,ioArgs){
			       var list = response.data;
			        $(".gantt").gantt({
			        	source: list, 
			        	navigate: 'scroll', 
			        	scale: 'hours', 
			        	maxScale: 'weeks', 
			        	minScale: 'hours', 
			        	itemsPerPage: 10,
			        	dayViewUrl: '#',
			        	weekViewUrl:weeklyUrl,
			        	monthViewUrl:monthlyUrl,
			        	usability: response.usability,
			        	segment: response.segmentData,
			        	startPos: response.lockDateStart,
			        	category: categoryName,
			        	currentSeg: segmentId,
			        	onItemClick: function(id) {
	    					var urlString=new $.Template($("#queryVehicleUsabilityMapDetailUrl").val());
	    					var urlParams={"reservationId":id};
	    					var url=urlString.expand(urlParams);
	    					window.showModalDialog(url,window,'dialogWidth=1050px;dialogHeight=700px');
	    					initGantt();
						},
						onDispatchItemClick: function(id) {
	    					var urlString=new $.Template($("#viewVehicleUsabilityMapDetailUrl").val());
	    					var urlParams={"reservationId":id};
	    					var url=urlString.expand(urlParams);
	    					window.showModalDialog(url,window,'dialogWidth=1050px;dialogHeight=700px');
	    					initGantt();
						},
						onConflictItemClick: function (currentId, currentRentalNo ,conflictIds , conflictRentalNos){
							//重新提交取得conflictIds
							createConflictSegmentsList(currentId, currentRentalNo, conflictIds, conflictRentalNos);
							var div = $('#conflictIds');
							$.msg.alert(i18ns("Validation.send.plzchoose"),div,{
								buttons:
									IFA.generateJson(i18ns("Entity.Operation.ok"),function(){
										$(this).dialog("close");
										var resId = $(":radio[name='cid']:checked").val();
										var urlString=new $.Template($("#viewVehicleUsabilityMapDetailUrl").val());
				    					var urlParams={"reservationId":resId};
				    					var url=urlString.expand(urlParams);
				    					window.showModalDialog(url,window,'dialogWidth=1100px;dialogHeight=700px');
				    					initGantt();
									}),
									width:350,height:210
							});
						},
						onNoneBillItemClick: function(noneBillId){
							showNoneBillInfo(noneBillId);
						},
						onMenuNameClick: function (vehicleId){
							addNoneBillable(vehicleId);
						},

						//invoke call back function to reload
						reload: function(day ,categoryId){
							
							var da = $("#startTime").val().split("-");
				    		var d =new Date(da[0],da[1]-1,da[2]);
				    		d.setDate(d.getDate() + day);
				    		$("#startTime").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+(d.getDate()));
				    		
				    		if(categoryId != null){
				    			$("#reservationId").val(categoryId);
				    		}
				    		
				    		initGantt();
						},
						//call back function to unlock gantt chart
						//prevent clicking too fast and make gantt chart die.
						onSuccess: function(){
							innerLocck =  true;
							$.unblockUI();
						}
			        });

		       }
		   });}
	}
	
	function selectCategory(categoryId){
		$("categoryId").val(categoryId);
		initGantt();
	}
	
	function initDate(){
		
		$("#startTime").datepicker({
			changeYear:true,
			changeMonth:true,
			dateFormat:"yy-mm-dd"
		});
		
		$("#lockDate").datetimepicker({
			stepHour:1,
			showMinute:false,
			showSecond:false,
			beforeShow : function(date) {
			},
			onSelect : function(date) {
				var date = $(this).datetimepicker("getDate");
				var returnDate = $("#unlockDate")
						.datetimepicker("getDate");
				var returnDateShow;
				if (returnDate) {
					returnDateShow = $("#unlockDate").val();
				}
				$("#unlockDate").datetimepicker("option", "minDate",
						new Date(date.getTime()));
				$("#unlockDate").datetimepicker("option", "minDateTime",
						new Date(date.getTime()));
				if (returnDate) {
					if (date.getTime() > returnDate.getTime()) {
						$("#unlockDate").val($(this).val());
					} else {
						$("#unlockDate").val(returnDateShow);
					}
				}
			}
			});
		$("#unlockDate").datetimepicker({
			stepHour:1,
			showMinute:false,
			showSecond:false,
			onSelect : function(date) {
				var date = $(this).datetimepicker("getDate");
				var pickupDate = $("#lockDate").datetimepicker(
						"getDate");
				var pickupDateShow;
				if (pickupDate) {
					pickupDateShow = $("#lockDate").val();
				}
				$("#lockDate").datetimepicker("option", "maxDate",
						new Date(date.getTime()));
				$("#lockDate").datetimepicker("option", "maxDateTime",
						new Date(date.getTime()));
				if (pickupDate) {
					if (date.getTime() < pickupDate.getTime()) {
						$("#lockDate").val($(this).val());
					} else {
						$("#lockDate").val(pickupDateShow);
					}
				}
			}
			});
		
		var d;
		if(reservationId!=""){
			var da = $("#startTime").val().split("-");
			d =new Date(da[0],da[1]-1,da[2]);
			d.setDate(d.getDate());
		}else if($("#dto").val()!=""){
			var da = $("#startTime").val().split("-");
			d =new Date(da[0],da[1]-1,da[2]);
			d.setDate(d.getDate());
		}else{
			d = new Date();
			d.setDate(d.getDate());
		}
		$("#startTime").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+(d.getDate()));
	}

	function createConflictSegmentsList(currentSegmentId, currentRentalNo, conflictIds,conflictRentalNos){
		$("#conflictIds").empty();
		$("#conflictIds").append("<input type='radio' name='cid' value='"+ currentSegmentId +"' checked='true' />" + currentRentalNo + "<br>");
		
		for (var i = 0; i < conflictIds.length; i++){			
			$("#conflictIds").append("<input type='radio' name='cid' value='"+ conflictIds[i] +"' checked='false' />" + conflictRentalNos[i] + "<br>");		
		}
	}
	
	function bindEvent(){
		$("#btnGantt").bind('click',initGantt);
		$("#resetCondition").bind('click',resetCondition);
		$("#btnNomenu").bind('click',noMenu);
		$("#weeklyCycle").bind('click',weeklyCycleFunc);
	}
	
	//地区热键
	function hotKeyDistrict(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyDistrict").val(),
			success:function(response){
			var acdata=response.district;
			$("#districtHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18ns("JS.districtHotKey.caption"),
						findCaption: "&nbsp;,"+i18ns("JS.districtHotKey.findCaption"),
						noFindCaption: "&nbsp;&nbsp;"+i18ns("JS.hotkey.district.city.noFindCaption")+":&nbsp; ",
						width: 200,
						max: 4,
						formatItem: function(row, i, max) {
							return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.districtHotkey, row.districtName);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.districtHotkey, row.districtName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.districtName);
						}
					}).result(function(event, data, formatted) {
						$("#districtId").val(data.districtId);
					});
		}
		});
	}
	
	
	//地区热键
	function hotKeyCity(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyCity").val(),
			success:function(response){
			var acdata=response.district;
			$("#cityHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18ns("JS.districtHotKey.caption"),
						findCaption: "&nbsp;,"+i18ns("JS.districtHotKey.findCaption"),
						noFindCaption: "&nbsp;&nbsp;"+i18ns("JS.hotkey.district.city.noFindCaption")+":&nbsp; ",
						width: 200,
						max: 4,
						formatItem: function(row, i, max) {
							return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.districtHotkey, row.districtName);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.districtHotkey, row.districtName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.districtName);
						}
					}).result(function(event, data, formatted) {
						$("#cityId").val(data.districtId);
					});
		}
		});
	}
	/**
	 * reset query condtion
	 */
	function resetCondition(){
		$("#cityHokKey").val('');
		$("#cityId").val('');
		$("#districtHokKey").val($("#districtNameReset").val());
		$("#districtId").val($("#districtIdReset").val());
		$("#startTime").val($("#pickupDateReset").val());
		var categoryId = $("#categoryIdReset").val();
		$("#categoryId").find('option[value='+categoryId+']').attr("selected","selected");
		if(reservationId==""){
			var d = new Date();
			$("#startTime").val(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate());
		}
		$("#plateNumber").val('');
		$("#leasingType").val('S');
	}
	
	function validateCondition(){

		var lockDateStart = $("#startTime").val();
		var districtHotKey = $("#districtHokKey").val();
		if(districtHotKey==""){
			$.msg.alert(i18ns('Entity.vehicle.districtRequired'));
			return false;
		}else if(lockDateStart==""){
			$.msg.alert(i18ns('ConditionMap.PlselectTime'));
			return false;
		}
		return true;
	}
	
   function addNoneBillable(vehicleId){
	   
		$("#noneBillableId").val("");
		$("#lockDate").val("");
		$("#unlockDate").val("");
		$("#remark").val("");		
		$("#vehicleId").val(vehicleId);
		
		$.msg.alert(i18ns("VehicleConditionMap.addNonbusiness"),$("#addTemplate"),function(){
		},{width:580,height:330,buttons:
			IFA.generateJson(i18ns("ConditionMap.ok"),function(){
			var	url = $("#checkNoneBillableUrl").val();
			if($("#addForm").valid()&& atLeastOne()==true){				
				$.ajax({
					 url:url,
					 type:"POST",
					 dataType:"json",
					 data:$("#addForm").serialize(),
					 timeout:5000,
					 success:function(response,ioArgs){
						 
						 if(response.result == -1){
							 $.msg.alert(i18ns('Page.Dialog.title'),i18ns("VehicleConditionMap.nonbusinessExist"));
						 } else if(response.result == 0) {
							 var conflictRes = response.listRes;
							 var strResNos = "";
							 for (var i = 0; i < conflictRes.length; i++){	
									strResNos += "<font color='red'>" + conflictRes[i].segmentId + "</font><br/>";
							}
							 var warnMessage = i18ns('ConditionMap.addNoneBill.WarningMessage') + "<br/>" + strResNos; 
									
							 $.msg.alert(i18ns('Page.title.dialogshow.warnning'),warnMessage, {buttons:
									IFA.generateJson(i18ns("Entity.Operation.ok"),function(){
										createNoneBillable();
										$(this).dialog("close");
									},
									i18ns("ConditionMap.cancel"),function(){		
										$(this).dialog("close");
									})
							});
						 } else {
							 createNoneBillable();
						 }
					 }
				});
				$(this).dialog("close");
			}
			},
			i18ns("ConditionMap.cancel"),function(){
				$(this).dialog("close");
			}
		)});
   }
   
   function showNoneBillInfo(noneBillId){
	   
	    var url = $("#getNoneBillableUrl").val();	
		  $.ajax({
			   url:url,
			   type:"POST",
			   dataType:"json",
			   data:"noneBillableId="+noneBillId,
			   timeout:5000,
			   success:function(response,ioArgs){
				   var noneBill = response.noneBillRes;
				   var father = response.father;
				   
				   $("#show_noneBillableId").val(noneBillId);
				   $("#show_codeId").val(noneBill.codeId);	
				   $("#show_repairshopId").val(noneBill.repairshopId);
				   $("#show_lockDate").val(new Date(noneBill.lockDate).format("yyyy-MM-dd hh:mm"));
				   $("#show_unlockDate").val(new Date(noneBill.unlockDate).format("yyyy-MM-dd hh:mm"));
				   $("#show_remark").val(noneBill.remark);
				
				   $.msg.alert(i18ns("VehicleConditionMap.deleteNonbusiness"),$("#showTemplate"),function(){
					},{width:550,height:400,buttons:
						
						IFA.generateJson(i18ns("Entity.Operation.delete"),function(){
						if($("#delNoneBillable").val()=="true"){
							$.msg.alert(i18ns("Entity.Sure.tip"),function(){},{buttons:
								IFA.generateJson(i18ns('ConditionMap.ok'),function(){
										$(this).dialog("close");
										
										delNoneBillable(noneBillId);
										
									},
									i18ns("ConditionMap.cancel"),function(){
										$(this).dialog("close");
									})
								});
								
							$(this).dialog("close");
						}else{ $.msg.alert(i18ns("NoneBillableAauthority"))}
						},
						i18ns('Entity.Operation.deleteAll'),function(){
							if($("#delAllNoneBillable").val()=="true"){
							if(father!=null){
								
							$.msg.alert(i18ns('VehicleGanttMap.deleteALLBetween').patchContent(father.lockDate,father.unlockDate),function(){},{buttons:
								IFA.generateJson(i18ns('ConditionMap.ok'),function(){
										$(this).dialog("close");
										
										delWeeklyNoneBillable(noneBillId);
										
									},
									i18ns("ConditionMap.cancel"),function(){
										$(this).dialog("close");
									})
								});
								
							}else{
								$.msg.alert(i18ns('VehicleGanttMap.deleteALLBetween').patchContent("",""),function(){},{buttons:
									IFA.generateJson(i18ns("ConditionMap.cancel"),function(){
										$(this).dialog("close");
										})
									});
							}
							$(this).dialog("close");
							}else{ $.msg.alert(i18ns("NoneBillableAauthority"))}
						},	
						i18ns("ConditionMap.cancel"),function(){
							$(this).dialog("close");
						}
					)});
			   }
		  });		
  }  

   function createNoneBillable(){
	   
		var url = $("#addNoneBillableUrl").val();
		
		$.post(url,$("#addForm").serialize(),function(data){
			if($("#addNoneBillable").val()=="true"){
			$.msg.alert(i18ns('VehicleMap.Dispatch.Success'),function(){},{buttons:
				IFA.generateJson(i18ns('ConditionMap.ok'),function(){
					$("#weeklyCycle").attr('checked',false);		
					$("#divRight input[type='checkbox']").attr('checked','checked');
					$("#divRight").hide();
						$(this).dialog("close");
						initGantt();
					})
				});
			
		}else{ $.msg.alert(i18ns("NoneBillableAauthority"))}});
	}  

   
   function delNoneBillable(noneBillId){
	   
	   var url = $("#delNoneBillableUrl").val();
	   
	   $.ajax({
		   url:url,
		   type:"POST",
		   dataType:"json",
		   data:"noneBillableId="+noneBillId,
		   timeout:5000,
		   success:function(response,ioArgs){
			   var result = response.result;
			   
			   if(result == 1){
				   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("Entity.page.Delete.Success"),function(){},{buttons:
					   IFA.generateJson(i18ns('ConditionMap.ok'),function(){
						   initGantt();
						   $(this).dialog("close");	   
					})
				});
			   }else{
				   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("Entity.page.Delete.Failed"));
			   }
		   }
		   }
	  );
   }
   
   function noMenu(){
	   	var daylyUrl=new $.Template($("#noMenuGanttChartUrl").val());
		var districtId=setDefaultParam($("#districtId").val());
		var districtName=setDefaultParam($("#districtHokKey").val());
		var categoryId=setDefaultParam($("#categoryId").val());
		var plateNumber=setDefaultParam($("#plateNumber").val());
		var params = {
		'districtId':districtId,
		'districtName':districtName,
		'categoryId':categoryId,
		'plateNumber':plateNumber,
		'startTime':$("#startTime").val(),
		'leasingType':$("#leasingType").val()
		};
		var noMenuUrl=daylyUrl.expand(params);
	   //window.showModalDialog(noMenuUrl,window, 'dialogLeft=0;dialogTop=0;dialogWidth='+window.screen.width+'px;dialogHeight='+window.screen.height+'px');
	   window.open(noMenuUrl,'window');
   }
   function setDefaultParam(param){
	   if(!param){
		   return $("#restEmpty").val();
	   }else{
		   return param; 
	   }
   }
   function weeklyCycleFunc(){
	   if($("#weeklyCycle").attr('checked')=='checked'){
		   $("#weeklyCycle").val(1);
			$("#divRight").show();			
		}else{
			$("#divRight").hide();
			$("#weeklyCycle").val(0);
		} 
   }
   
   function delWeeklyNoneBillable(noneBillId){
	   
	   var url = $("#delWeeklyNoneBillableUrl").val();
	   
	   $.ajax({
		   url:url,
		   type:"POST",
		   dataType:"json",
		   data:"noneBillableId="+noneBillId,
		   timeout:5000,
		   success:function(response,ioArgs){	
			   var result=response.result;
			   if(result > 0){
				   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("Entity.page.Delete.Success"),function(){},{buttons:
					   IFA.generateJson(i18ns('ConditionMap.ok'),function(){
						   initGantt();
						   $(this).dialog("close");	   
					})
				});
			   }else{
				   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("Entity.page.Delete.Failed"));
			   }
			   }
		   }		   
	  );
   }
   function atLeastOne(){
	   if($("#weeklyCycle").attr('checked')=='checked'){
		   if($("#sun").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#mon").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#tue").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#wed").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#thu").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#fri").attr('checked')=='checked'){
			   return true;
		   }
		   if($("#sat").attr('checked')=='checked'){
			   return true;
		   }
		   $.msg.alert(i18ns('Page.Dialog.title'),i18ns("VehicleGanttMap.selectDay"));
		   return false;
	   }else{
		   return true;
	   }
   }
});