var windowid;

//车辆历史轨迹
CarTrace.gpsCarHisLine = null;
//车辆实时追踪画线
CarTrace.gpsCarRealLineList = [];
//实时追踪起点
CarTrace.gpsCarRealStartPoint = null;
//实时追踪终点
CarTrace.gpsCarRealEndPoint = null;
//实时追踪第一个点
CarTrace.gpsCarCurrentData = null;
//实时追踪的车辆编号
CarTrace.carTraceId = null;
//历史轨迹查询时间
CarTrace.hisCarTraceQueryTime = {};
//车辆起点、终点
CarTrace.carTraceMarker = [];
CarTrace.carTraceReplayId = null;
CarTrace.carTraceReplayEndPoint = null;
CarTrace.carTraceReplayTempPoint = null;
CarTrace.carTraceReplayLineList = [];
CarTrace.carTraceReplayAscArray = null;
CarTrace.carTraceReplayDescArray = null;
CarTrace.carTraceReplayTempArray = null;
CarTrace.startMove = null;

function CarTrace () {
	
}



//历史轨迹查询窗口
CarTrace.hisCarTrace = function(vdId, channelId){
	var data = {};
	data.vdId = vdId;
	data.channelId = channelId;
	var vdChannelId = vdId + '-' + channelId;
	if (CarTrace.hisCarTraceQueryTime) 
		data.timeObj = CarTrace.hisCarTraceQueryTime[vdChannelId];
	windowid = top.$.createWin({
        title    :     '轨迹时段查询',
        width    :      300,
        height    :     160,
        data	: data,
        url    :    top.sysUrl + '/szmap/business/chetrack/HisCarTraceQuery.jsp',
        buttons: [{
            text:$.fn.textbox.defaults.ok,
            handler:function(){CarTrace.hisCarTraceSure();}
        }]
    });    
}


CarTrace.hisCarTraceSure = function(){
	var mm = CarTrace.getHisCarTraceParam();
	GpsDataSetService.select_GpsDataSet_page(mm,function(rs){
		if(rs.length >=2){
			CarTrace.clearGpsCarAllTrace();
			CarTrace.carTraceReplayAscArray = rs;
			CarTrace.carTraceReplayDescArray = [];
			for (var i=0; i<rs.length; i++) {
				CarTrace.carTraceReplayDescArray[i] = rs[rs.length - i - 1];
			}
			var tmpStartPoint = rs[0];
			var tmpEndPoint = rs[rs.length-1];
			var startIcon = MapConst.MARKER_ICON_START;
			var endIcon = MapConst.MARKER_ICON_END;
			tmpStartPoint = CarTrace.getCarInfo(tmpStartPoint);
			tmpEndPoint = CarTrace.getCarInfo(tmpEndPoint);
			var startMarker = CarTrace.drawMarker(tmpStartPoint, 36, 36,startIcon, PopUpBase.getGpsCarHisStartPointHtml);
			CarTrace.carTraceMarker = [];
			CarTrace.carTraceMarker.push(startMarker);
			var endMarker = CarTrace.drawMarker(tmpEndPoint, 33, 33, endIcon, PopUpBase.getGpsCarHisEndPointHtml);
			CarTrace.carTraceMarker.push(endMarker);
			MapAPI.centerAndZoom(new Point(tmpStartPoint.longitude,tmpStartPoint.latitude), top.mapLevel);
			startMarker.openInfoWindowHtml(PopUpBase.getGpsCarHisStartPointHtml(tmpStartPoint));
			MapMain.setCurrPupUpObject([]);
			startMarker.flash2(2);
			endMarker.flash2(2);
			CarTrace.drawGpsCarHisLineTrace(rs);	
		}else{
			$.showMsg("车辆暂无轨迹！");
		}
		top.$('#'+windowid).dialog('close');
	});
}


//取得车辆信息
CarTrace.getCarInfo = function (data) {
	var car = {};
	var vdChannelId = data.vdId + '-' + data.channelId;
	var car2 = MapMain.getLayer(MapConst.LAYER_CHEGPS).getGpsObj(vdChannelId);
	CarTrace.copyObj(car, car2);
	car.longitude = data.longitude;
	car.latitude = data.latitude;
	car.alarmTime = data.alarmTime;
	return car;
}

CarTrace.copyObj = function (data, data2) {
	for (var key in data2) {
		data[key] = data2[key];
	}
}

//取得历史轨迹查询条件
CarTrace.getHisCarTraceParam = function () {
	var frame    =    top.$("#"+windowid).children("iframe")[0];
    var win        =    frame.contentWindow||frame.window;
	var vdId = win.$('#vdId').val();
	var channelId = win.$('#channelId').val();
	var startTime = win.$('#startTime').textbox('getValue');
	var endTime = win.$('#endTime').textbox('getValue');
	var vdChannelId = vdId + "-" + channelId;
	CarTrace.saveTraceQueryTime(vdChannelId, startTime, endTime);
	var tableparam = " AND alarmTime >= '" +startTime + "' AND alarmTime <= '"+endTime+"'";
	var mm = {};
	mm.vdId = vdId;
	mm.channelId = channelId;
	mm.start = 0;
	mm.limit = 2000;
	mm.tableparam = tableparam;
	mm.order = "order by alarmTime asc";
	return mm;
}

//保存轨迹查询时间
CarTrace.saveTraceQueryTime = function (vdChannelId, startTime, endTime) {
	var timeObj = {};
	timeObj.startTime = startTime;
	timeObj.endTime = endTime;
	if (CarTrace.hisCarTraceQueryTime)
		CarTrace.hisCarTraceQueryTime[vdChannelId] = timeObj;
}

//添加轨迹起点、终点
CarTrace.drawMarker = function (result, width, height, iconSource, popUpBaseFunc) {
	var pIcon=new Icon(); 
	pIcon.height = width;
	pIcon.width = height;
	pIcon.topOffset = -10;
	pIcon.leftOffset = -10;
	pIcon.image = iconSource;
	var point=new Point(result.longitude,result.latitude);	
	var resultMsg = popUpBaseFunc && popUpBaseFunc(result);
	
	var marker = new Marker(point,pIcon) ;
	if (resultMsg) { 
		marker.addListener("click", function () {
			marker.openInfoWindowHtml(resultMsg);
			MapMain.setCurrPupUpObject([]);
		});	
	}
	marker.setZIndex(MapConst.MARKER_ZINDEX_TRACE);
	MapAPI.addOverlay(marker);
	return marker;
}
//移除上一个轨迹
CarTrace.clearPreCarHisTrace = function () {
	if (CarTrace.gpsCarHisLine) {
		MapAPI.removeOverlay(CarTrace.gpsCarHisLine);
		CarTrace.gpsCarHisLine = null;
	}
	
	if (CarTrace.carTraceMarker) {
		
		for (var i=0; i<CarTrace.carTraceMarker.length; i++) {
			CarTrace.closeInfoWindowHtml(CarTrace.carTraceMarker[i]);
			MapAPI.removeOverlay(CarTrace.carTraceMarker[i]);
		}
		CarTrace.carTraceMarker = [];
	}
}



//画轨迹
CarTrace.drawGpsCarHisLineTrace = function (data) {
	var pointList=[];
	for(var i=0;i<data.length;i++){
		pointList.push(new Point(data[i].longitude, data[i].latitude));
	}
	CarTrace.gpsCarHisLine = new Polyline(pointList, "red", 4);
	CarTrace.gpsCarHisLine.setZIndex(MapConst.MARKER_ZINDEX_TRACELINE);
	MapAPI.addOverlay(CarTrace.gpsCarHisLine);
}


//启用追踪画线
CarTrace.currentCarTrace = function (data) {
	var vdChannelId = data.vdId+"-"+data.channelId;	
	var cheGpsLayer = MapMain.getLayer(MapConst.LAYER_CHEGPS);
	if(cheGpsLayer.getGpsObj(vdChannelId)){
		//画线
		var tmpLineList = [];
		tmpLineList.push(new Point(CarTrace.gpsCarCurrentData.longitude,CarTrace.gpsCarCurrentData.latitude));		
		var point = new Point(data.longitude,data.latitude);
		tmpLineList.push(new Point(data.longitude,data.latitude));
		var carLine = new Polyline(tmpLineList, "red", 4);
		MapAPI.addOverlay(carLine);
		CarTrace.gpsCarRealLineList.push(carLine);
		MapAPI.centerAndZoom(point, top.mapLevel);
		//画终点-先移除
		if(CarTrace.gpsCarRealEndPoint!=null){
			MapAPI.removeOverlay(CarTrace.gpsCarRealEndPoint);
			if (CarTrace.startMove) {
				var startData = CarTrace.gpsCarCurrentData;
				CarTrace.gpsCarRealStartPoint = CarTrace.getGpsCarRealStartPoint(startData);
				CarTrace.gpsCarRealStartPoint.flash2(2);
				CarTrace.gpsCarRealStartPoint.setZIndex(MapConst.MARKER_ZINDEX_TRACE);
				MapAPI.addOverlay(CarTrace.gpsCarRealStartPoint);
		    	CarTrace.startMove = false;
			}
		}
		var marker = cheGpsLayer.getMark(data, MapConst.MARKER_ICON_ACTIVE_CHEGPS);
		MapAPI.addOverlay(marker);
		cheGpsLayer.tryOpenWindowHtml(marker, data);
		var resultMsg = PopUpBase.createChePopUp(data);
		CarTrace.gpsCarRealEndPoint = marker;
		CarTrace.gpsCarCurrentData = data;
		//更新点位
		cheGpsLayer.addMarkerToMarkerObj(vdChannelId, marker);
	} else {
		CarTrace.stopGpsCarRealTrace(data.vd, data.channelId);
	}
	
}


//车辆停止追踪
CarTrace.stopGpsCarRealTrace= function(vdId, channelId){
	if (CarTrace.carTraceId) {
		CarTrace.carTraceId = '';
		$.showMsg("已停止追踪！");
	}
	var pop = MapMain.getCurrPupUpObject();
	if (pop && pop.length > 1 && pop[0] == MapConst.LAYER_CHEGPS) {
		MapMain.getEzmap().closeInfoWindow();
		MapMain.setCurrPupUpObject([]);
	}
}

//车辆开始追踪
CarTrace.startCarTrace = function(vdId,channelId){
//	ocx.iSeeOcxNewWindow(3);
//	ocx.iSeeOcxSetScreenModeEx(0,6);
	var vdChannelId = vdId+"-"+channelId;
	//清车辆图层轨迹
	CarTrace.clearGpsCarAllTrace();
	CarTrace.carTraceId = vdChannelId;
	var cheGpsLayer = MapMain.getLayer(MapConst.LAYER_CHEGPS);
	var tmpCarChannel = cheGpsLayer.getGpsObj(vdChannelId);
	if (tmpCarChannel) {
		CarTrace.gpsCarCurrentData = tmpCarChannel;
		CarTrace.gpsCarRealEndPoint = cheGpsLayer.getMarkerBy(vdChannelId);
		MapAPI.centerAtLatLng(new Point(tmpCarChannel.longitude,tmpCarChannel.latitude));
		CarTrace.startMove = true;
		$.showMsg('已启用实时追踪！');
	}
}

//清除车辆画线及点位
CarTrace.clearGpsCarAllTrace = function(vdId,channelId){
	CarTrace.clearPreCarHisTrace();
	CarTrace.clearCarRealTrace();
	CarTrace.stopCarTraceReplay();
	CheTravel.clearPreCarHisTrace();
}
//清除实时轨迹车辆并停止追踪
CarTrace.clearCarRealTrace = function(vdId,channelId){
	var list = CarTrace.gpsCarRealLineList;
	for (var i=0; i<list.length; i++) {
		MapAPI.removeOverlay(list[i]);
	}
	CarTrace.gpsCarRealLineList = [];
	if (CarTrace.gpsCarRealStartPoint) {
		CarTrace.closeInfoWindowHtml(CarTrace.gpsCarRealStartPoint);
		MapAPI.removeOverlay(CarTrace.gpsCarRealStartPoint);
	}
	CarTrace.stopGpsCarRealTrace(vdId,channelId);
}

//取得实时追踪起点marker
CarTrace.getGpsCarRealStartPoint = function(data){
	//起点图标
	var icon=new Icon();
    icon.height = 40;
	icon.width = 40;
	icon.topOffset = -10;
	icon.leftOffset = -10;
	var marker=null;
	icon.image = MapConst.MARKER_ICON_START;
    marker = new Marker(new Point(data.longitude,data.latitude),icon);  
    var strHtml2 = PopUpBase.getGpsCarRealStartPointHtml(data);
    marker.addListener("click", function() {
    	marker.openInfoWindowHtml(strHtml2);
    	MapMain.setCurrPupUpObject([]);
	});	   
    return marker;
}

//车辆历史轨迹回放
CarTrace.carTraceReplay = function(type){
	if (CarTrace.carTraceReplayId) {
		$.showMsg('正在轨迹回放！');
		return;
	} 
	if (CarTrace.gpsCarHisLine) {
		MapAPI.removeOverlay(CarTrace.gpsCarHisLine);
		CarTrace.gpsCarHisLine = null;
	}
	if (type == 'desc') {
		CarTrace.carTraceReplayTempArray = CarTrace.carTraceReplayDescArray;
	} else if (type == 'asc') {
		CarTrace.carTraceReplayTempArray = CarTrace.carTraceReplayAscArray;
	}
	var tempData = CarTrace.carTraceReplayTempArray[0];
	CarTrace.carTraceReplayEndPoint = CarTrace.getGpsCarRealStartPoint(tempData);
	MapAPI.centerAtLatLng(new Point(tempData.longitude,tempData.latitude));
	var cheGpsLayer = MapMain.getLayer(MapConst.LAYER_CHEGPS);
	MapMain.setCurrPupUpObject([cheGpsLayer.seq, 'carTraceReplay', tempData.longitude,tempData.latitude]);
	var num = 0;
	CarTrace.carTraceReplayId = setInterval(function() {
        num++;
        CarTrace.drawCarTraceReplay(num);
        if (num >= CarTrace.carTraceReplayTempArray.length -1) {
            clearInterval(CarTrace.carTraceReplayId);
            $.showMsg('轨迹回放结束！');
        }
    }, 3000);

}
//车辆历史轨迹回放划线
CarTrace.drawCarTraceReplay = function(index){
	if(CarTrace.carTraceReplayEndPoint!=null){
		CarTrace.carTraceReplayTempPoint = CarTrace.carTraceReplayEndPoint;
		MapAPI.removeOverlay(CarTrace.carTraceReplayEndPoint);
	}
	var tempData = CarTrace.carTraceReplayTempArray[index];
	var cheGpsLayer = MapMain.getLayer(MapConst.LAYER_CHEGPS);
	tempData = CarTrace.getCarInfo(tempData);
	CarTrace.carTraceReplayEndPoint = CarTrace.drawMarker(tempData, MapConst.LAYER_ICON_WIDTH, MapConst.LAYER_ICON_HEIGHT, MapConst.MARKER_ICON_CHEGPS, PopUpBase.getGpsCarHisStartPointHtml);
	CarTrace.carTraceReplayEndPoint.addListener("click", function () {
		var resultMsg = PopUpBase.getGpsCarHisStartPointHtml(tempData);
		CarTrace.carTraceReplayEndPoint.openInfoWindowHtml(resultMsg);
		MapMain.setCurrPupUpObject([cheGpsLayer.seq, 'carTraceReplay', tempData.longitude,tempData.latitude]);
	});	
	var pointList=[];
	pointList.push(new Point(CarTrace.carTraceReplayTempPoint.point.x, CarTrace.carTraceReplayTempPoint.point.y));
	pointList.push(new Point(CarTrace.carTraceReplayEndPoint.point.x, CarTrace.carTraceReplayEndPoint.point.y));
	var carTraceReplayLine = new Polyline(pointList, "blue", 1);
	CarTrace.carTraceReplayLineList = CarTrace.carTraceReplayLineList || [];
	CarTrace.carTraceReplayLineList.push(carTraceReplayLine);
	carTraceReplayLine.setZIndex(MapConst.MARKER_ZINDEX_TRACELINE);
	MapAPI.addOverlay(carTraceReplayLine);
	MapAPI.centerAtLatLng(new Point(tempData.longitude,tempData.latitude));
	CarTrace.tryOpenWindowHtml(CarTrace.carTraceReplayEndPoint, tempData, MapConst.LAYER_CHEGPS);
}

//停止车辆历史轨迹回放划线
CarTrace.stopCarTraceReplay = function(){
	if (!CarTrace.carTraceReplayId) {
//		$.showMsg('未开始轨迹回放！');
		return;
	} 
	else {
		clearInterval(CarTrace.carTraceReplayId);
		CarTrace.carTraceReplayId = null;
		if (CarTrace.carTraceReplayEndPoint) {
			CarTrace.carTraceReplayEndPoint.map && CarTrace.carTraceReplayEndPoint.closeInfoWindowHtml();
			MapAPI.removeOverlay(CarTrace.carTraceReplayEndPoint);
			CarTrace.carTraceReplayEndPoint = null;
		}
		CarTrace.clearPreCarHisTrace();
		if (CarTrace.carTraceReplayLineList) {
			for (var index = 0; index < CarTrace.carTraceReplayLineList.length; index++) {
				MapAPI.removeOverlay(CarTrace.carTraceReplayLineList[index]);
			}
			CarTrace.carTraceReplayLineList = [];
		}
		$.showMsg('已停止轨迹回放！');
	}
}

CarTrace.tryOpenWindowHtml = function(marker, data, seq){
	var pop = MapMain.getCurrPupUpObject();
	if (pop && pop.length > 1 && 'carTraceReplay' == pop[1] && seq == pop[0]) {
		marker.openInfoWindowHtml(PopUpBase.getGpsCarHisStartPointHtml(data));
	}
}

CarTrace.closeInfoWindowHtml = function (marker) {
	var pop = MapMain.getCurrPupUpObject();
	if (pop && pop.length == 0) {
		marker.closeInfoWindowHtml();
	}
	if (pop && pop.length > 1 && 'carTraceReplay' == pop[1] ) {
		marker.closeInfoWindowHtml();
	}
}