define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('datepicker')($);
	require('uriTemplate')($);
	require('jqueryCSS');
	require('grid')($);
	require('block')($);
	require('validation')($);
	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();
		initGantt();
		bindEvent();
//		var today=new Date();
//		var count=0;
//		setInterval(function(){
//			today.setDate(today.getDate()-7);
//			$("#startTime").val(today.getFullYear()+'-'+(today.getMonth()+1)+'-'+(today.getDate()));
//			if(count<50){
//				count++;
//				initGantt();
//			}	
//		},3000);
		$("#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 segmentId = $("#reservationId").val();
		var categoryName = $("#categoryId").find("option:selected").text();
		var para = $("#queryUsabilityMapForm").serialize();
		
		var monthlyUrl;
		var daylyUrl;
		if ($("#noMenu").val()=="true") {
			 monthlyUrl=$("#monthlyViewUrl").val();	
			 daylyUrl=$("#noMenuGanttChartUrl").val();
		}else {
			 monthlyUrl=$("#monthlyViewUrl").val();	
			 daylyUrl=$("#daylyUrl").val();
		}
		daylyUrl=new $.Template(daylyUrl);
		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()
		};
		daylyUrl=daylyUrl.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:$("#ganttUrl").val(),
			   type:"POST",
			   dataType:"json",
    		   data:para,
			   timeout:10000,
			   success:function(response,ioArgs){
			       var list = response.data;
			        $(".gantt").gantt({
			        	source: list, 
			        	navigate: 'scroll', 
			        	scale: 'days', 
			        	maxScale: 'weeks', 
			        	minScale: 'days', 
			        	dayViewUrl: daylyUrl,
			        	weekViewUrl:'#',
			        	monthViewUrl: monthlyUrl,
			        	usability: response.usability,
			        	segment: response.segmentData,
			        	startPos: response.lockDateStart,
			        	category: categoryName,
			        	currentSeg: segmentId,
						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();
		$("#lockDate").datepicker();
		$("#unlockDate").datepicker();
		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);
	}
	
	
	//地区热键
	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: 5,
						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: 5,
						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(i18n['ConditionMap.PlselectTime']);
			return false;
		}
		return true;
	}
   

   
   /**
    * 获取所有时间点,以及分割区间的开始和结束以及驾驶员信息
    */
   function fillupMap(oneDayData){
	   var len = oneDayData.length;
	   var times=[];
	   var datas = {};
	   datas['divition'] = {};
	   for(var i=0;i<len;i++){
		   var oneRes = oneDayData[i];
		   var hourDivition = getHourDivition(oneRes.lockDate,oneRes.unLockDate);
		   var begin = hourDivition.begin;
			var end = hourDivition.end;
			var billable = oneRes.billable;
	   datas['divition']["res"+i]={"driver":oneRes.chauffeurId==null?i18n['ConditionMap.UnDispatch']:oneRes.cnName,"begin":begin,"end":end,"billable":billable};
		   for(var j=0;j<24;j++){
			   if(j>=begin&&j<=end){
				   times[j]=1;
			   }else{
				   if(!times[j]){
				      times[j]=0;
				   }
			   }
		   }
	   }
	   datas['times'] = times;
	   return datas;
   }
   
   /**
    * 获取时间间隔
    */
   function getHourDivition(lockDate,unlockDate){
	   var beginTime =  new Date(lockDate).getHours();
	   var endTime = new Date(unlockDate).getHours();
	   return {begin: Number(beginTime),end: Number(endTime)};
   }
   
   function addNoneBillable(vehicleId){
		$("#noneBillableId").val("");
		$("#lockDate").val("");
		$("#unlockDate").val("");
		$("#remark").val("");
		
		$("#vehicleId").val(vehicleId);
		
		$.msg.alert(i18ns("VehicleConditionMap.addNonbusiness"),$("#addTemplate"),function(){
		},{width:550,height:300,buttons:
			IFA.generateJson(i18ns("ConditionMap.ok"),function(){
			if($("#addForm").valid()){
			$(this).dialog("close");
			createNoneBillable();
			}
		},
		i18ns("ConditionMap.cancel"),function(){
			$(this).dialog("close");
		}
		)});
}
   
   function createNoneBillable(){
		var url = $("#addNoneBillableUrl").val();
		$.post(url,$("#addForm").serialize(),function(data){
			if(data.result=="-1"){
				$.msg.alert(i18n['Page.Dialog.title'],i18ns("VehicleConditionMap.exist"));
				 return;
			} else{
				$.msg.alert(i18n['VehicleMap.Dispatch.Success'],function(){},{buttons:
					IFA.generateJson(i18n['ConditionMap.ok'],function(){
						initGantt();
						})
					});
			}
			
		});
	}
   function noMenu(){
	   	var weeklyUrl=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=weeklyUrl.expand(params);
		window.open(noMenuUrl,'window');
   }
   function setDefaultParam(param){
	   if(!param){
		   return $("#restEmpty").val();
	   }else{
		   return param; 
	   }
   }
});