define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('datepicker')($);
	require('uriTemplate')($);
	require('jqueryCSS');
	require('grid')($);
	//require('ganttDebug')($);

	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();
		initDate();
		hotKeyConcierge();
		hotKeyDistrict();
		initGantt();
		bindEvent();
	});
	
	//加载gantt图
	function initGantt(){
		
		   if(!validateCondition()){
			   return;
		   }
		   
		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();
		if(innerLocck){
			innerLocck = false;
		   $.ajax({
			   url:getUrl,
			   type:"POST",
			   dataType:"json",
    		   data:para,
			   timeout:5000,
			   success:function(response,ioArgs){
				   desc=i18n["Entity.concierge.level"]+response.data.desc;
			       var list = response.data;
			        $(".gantt").gantt({
			        	source: list, 
			        	navigate: 'scroll', 
			        	scale: 'hours', 
			        	maxScale: 'weeks', 
			        	minScale: 'hours', 
			        	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');
	    					//location.href = url;
						},
						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');
	    					//location.href = url;
						},
						onConflictItemClick: function (currentId, currentRentalNo ,conflictIds , conflictRentalNos){
							//重新提交取得conflictIds
							createConflictSegmentsList(currentId, currentRentalNo, conflictIds, conflictRentalNos);
							var div = $('#conflictIds');
							$.msg.alert(i18n["Validation.send.plzchoose"],div,{
								buttons:
									IFA.generateJson(i18n["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');
				    					//location.href = url;
									}),
									width:350,height:210
							});
						},
						//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;
						}
			        });

		       }
		   });}
	}
	
	function initDate(){
		$("#startTime").datepicker();
		var d;
		if(reservationId==""){
			d = new Date();
			d.setDate(d.getDate()-1);
		}else{
			var da = $("#startTime").val().split("-");
			d =new Date(da[0],da[1]-1,da[2]);
			d.setDate(d.getDate()-1);
		}
		$("#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);
		$("a[id^='detail']").live('click',function(){
			
			var reservationId = $("#reservationId").val();
			var url2 = $("#queryVehicleUsabilityMapDetailNoMenuUrl").val();
			var urlStr = url2?url2:$("#queryVehicleUsabilityMapDetailUrl").val();
			var urlTemp = new $.Template(urlStr);
			var urlParams = {'districtId':$(this).attr("districtId"),'categoryId':$(this).attr("categoryId"),'startTime':$("#startTime").val(),'vehicleId':$(this).attr("id").substring(6,$(this).attr("id").length),'reservationId':reservationId==""?$("#restEmpty").val():reservationId};
			var url = urlTemp.expand(urlParams);
			$("#openDetailForm").attr("action",url).attr("target","vehicleConditionMap").submit();
		});
		$(document).bind("keyup",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
				search();
			}
		});
		
	}
	
	//礼宾名字热键
	function hotKeyConcierge(){
	  	/*$.ajax({
			type:"get",
			url:$("#hotkeyConcierge").val(),
			success:function(response){
			var acdata=response.concierge;
			$("conciergeHokKey").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.conciergeName, row.conciergeName);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.conciergeName, row.conciergeName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.conciergeName);
						}
					}).result(function(event, data, formatted) {
						$("#conciergeId").val(data.conciergeId);
					});
		}
		});*/
		
		$.ajax({
			type:"get",
			url:$("#hotkeyConcierge").val(),
			success:function(response){
			var acdata=response.concierge;
			$("#conciergeHokKey").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: 3,
						formatItem: function(row, i, max) {
							return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.conciergeName, row.level);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.conciergeName, row.level);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.conciergeName);
						}
					}).result(function(event, data, formatted) {
						$("#conciergeId").val(level);
					});
		}
		});
	}
	//地区热键
	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());
		}
	}
	
	function validateCondition(){

		var lockDateStart = $("#startTime").val();
		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)};
   }
   
});