////////////////////////////////////////
//Check user more then one hours no click
var g_userLastCilckTime	= new Date();

function checkTimout(){
	var outTime 	= 60*60*1000;
	var delayTime	= 10*1000;	
	
	var d = new Date();
	var oldTime = g_userLastCilckTime.getTime();
	var nowTime = d.getTime();
	
	if( nowTime - oldTime > outTime ){
		cmdLogout();
		setTimeout( 
			function(){
				//alert( getStr(s_UserUseTimeout) );
				window.location.href="index.html";	
			}, 
			delayTime 
		);
	}
	else{
		setTimeout( 'checkTimout()', outTime );
	}			
}

/////////////////////////////////////////
// Local time to UTC time
// input :"MM/DD/YYYY 08:08:08"
//		 : date object
var		TEISLOCAL = true;

function LocaltoUTC(Local){
	var		d;
	var		zone;
	var  	c;
	
	if( typeof(Local) == 'object' ){
		d = Local;
	}
	else{
		d = new Date( Local );	
	}	
	if( TEISLOCAL ){
		zone = 0;
	}
	else{
		zone = d.getTimezoneOffset()*60*1000;
	}
	c = new Date();
	c.setTime( d.getTime() + zone );	
	return c;
}

//////////////////////////////////////////
// UTC Time to local
// input: second( from 19700101 to now )
function UTCtoLocal( UTC ){

	var 	zone;
	var		d = new Date( UTC*1000 );	
	if( TEISLOCAL ){
		zone = 0;
	}	
	else{
		zone = d.getTimezoneOffset()*60*1000;
	}
	d.setTime( d.getTime() + zone );
	return d;
}

function GetLocalTime()
{
	var d = new Date();
	return d;
}

/////////////////////////////////////////////////////////////////////
function getTEUIDByLicense(license){
	var	TEUID="";
	if( g_oVechile != null ){
		TEUID = g_oVechile.getVechileTEUIDByLicense( license );
	}
	return	TEUID;
}

function getLicenseByTEUID( TEUID ){
	var			license="";
	if( g_oVechile != null ){
		license = g_oVechile.getVechileLicenseByUID( TEUID );
	}
	return	license;
}

function getTENOByTEUID( TEUID ){
	var		SIM = "";	
	if( g_oVechile != null ){
		SIM = g_oVechile.getTENOByUID( TEUID );
	}
	return SIM;
}
/////////////////////////////////////////////////////////////////////
function getLocalUserName()
{	
	var username;
	if(g_oUser != null){
		username = g_oUser.Username;
	}
	return username;
}

/////////////////////////////////////////////////////////////////////
function getUserPrivilege()
{	
	var Privilege = 0;
	if(g_oUser != null){
		Privilege = g_oUser.Privilege;
	}
	return Privilege;
}

/////////////////////////////////////////////////////////////////////
function getUserPrivilegeStr( Privilege )
{	
	if( Privilege < 0 ){
		Privilege = 0;
	}
	else if( Privilege >= LangUserPrivilege.length ){
		Privilege = LangUserPrivilege.length-1;
	}
	return getStr( LangUserPrivilege[Privilege]);
}

/////////////////////////////////////////////////////////////////////
function getstrTEType( Type ){
	
	var		str;
	
	if( Type < 0 ){
		Type = 0;	
	}
	if( Type >= LangTEType.length ){
		Type = 	LangTEType.length-1;
	}
	return getFileStr( LangTEType, Type );
}

function getiTETypeBystrTEType( strTEType ){
	var iTEType = -1;
	var len = LangTEType.length;
	for( var i=0; i<len; i++ ){
		if( strTEType == getFileStr( LangTEType, i ) ){
			iTEType = i;
			break;
		}
	}
	return iTEType;
}

/////////////////////////////////////////////////////////////////////
function getTETypeByTEUID( TEUID ){
	var			TEType="";
	if( g_oVechile != null ){
		TEType = g_oVechile.getTETypeByUID( TEUID );
	}
	return	TEType;
}

function setVechileDisplayEnalbe( license , flag ){
	
	TEUID = getTEUIDByLicense( license );	
	g_oVechile.setVechileDisplayEnalbe(TEUID, flag );
	if( flag == true ){
		var		objGPS = g_oGPSData.getGPS( TEUID );
		if( objGPS != null ){
			updateMapByGPS( objGPS, false );
			mapCenter( objGPS.LON, objGPS.LAT );			
		}
		else{
			cmdUpdateGPSTEUID( TEUID );
		}	
	}	
	else{
		mapDeleteMarker( license )
	}
}
function getVechileLen( ){
	if( g_oVechile != null ){
		return g_oVechile.getLen( );
	}
	else{
		return 0;
	}	
}
function getVechileData( index ){
	if( g_oVechile != null ){
		return g_oVechile.getVechile( index );	
	}
	else{
		return null;
	}
}
function IsVechileDisplay( TEUID ){
	if( g_oVechile != null ){
		return g_oVechile.IsVechileDisplayEnalbe( TEUID );	
	}
	else{
		return null;
	}		
}
////////////////////////////////////////////////////////////////////
function getUserFLName( ){
	if( g_oUser != null ){
		return g_oUser.FLName;	
	}
	else{
		return " ";
	}		
}
////////////////////////////////////////////////////////////////////
function getUserPassword( ){
	if( g_oUser != null ){
		return g_oUser.Password;	
	}
	else{
		return " ";
	}		
}
////////////////////////////////////////////////////////////////////
function getUserUID(){
	if( g_oUser != null ){
		return g_oUser.UserID;	
	}
	else{
		return " ";
	}		
}
//////////////////////////////////////////////////////////////////
//write feedback info into feedback info table
function getDirectionDescription( direction ){
	
	var			i = 0;

	if ( direction <= 20 || direction >340 ){
		i = 0;
	}
	else if ( direction <= 70 ){
		i = 1;
	}
	else if ( direction <= 110 ){
		i = 2;
	}
	else if ( direction <= 160 ){
		i = 3;
	}
	else if ( direction <= 200 ){
		i = 4;
	}
	else if ( direction <= 250 ){
		i = 5;
	}
	else if ( direction <= 290 ){
		i = 6;
	}
	else if ( direction <= 340 ){
		i = 7;
	}
	return getStr(s_driection[i]);
}

function addFeedbackInfo( license, otime, state, speed, direction, lon, lat){
	
	if( feedbackinfo != null ){	
		var data = new Array();
		data.push( otime.toLocaleString() );		
		data.push( license );
		data.push( state );
		data.push( speed );
		data.push( getDirectionDescription(direction) );
		data.push( lon );
		data.push( lat );
		feedbackinfo.addData(data);
	}	
}

//////////////////////////////////////////////////////////////////
//write alarm info into feedback alarm table
function addAlarmInfo( license, otime, state, speed, direction, lon, lat){
	
	if( alarminfo != null ){	
		var data = new Array();
		data.push( otime.toLocaleString() );		
		data.push( license );
		data.push( state );
		data.push( speed );
		data.push( getDirectionDescription(direction) );
		data.push( lon );
		data.push( lat );
		alarminfo.addData(data);
	}	
}

///////////////////////////////////////////////////////////////////
// maps operation
function mapGetIconUrl( speed, direction, alarm ){	
	var			iconurl;
	
	iconurl = "image/car/Car10";
	
	if( alarm  == true ){	
		iconurl += "1";
	}
	else if( speed > 10 ){
		iconurl += "2";
	}
	else {
		iconurl += "3";
	}
	
	var		 i = Math.floor( direction / 45 + 1 );
	
	iconurl += i;
	iconurl += ".gif";
	return iconurl;
}

function mapAddMarker( obj ){	
	centerpanel.getActiveTab().addMarker(obj);
}

function mapAddMarker2( name, lng, lat, speed, direction, alarm ){	
	mapAddMarker({
		name: name,
		icon: mapGetIconUrl( speed, direction, alarm ),
		lng	: lng,
		lat	: lat,
		speed:	speed,
		alarm:	alarm
	});
}
function mapDeleteMarker( name ){	
	centerpanel.getActiveTab().deleteMarker(name);
}

function mapDrawLine( obj ){
	centerpanel.getActiveTab().addLine( obj );
}
function mapCenter( lng, lat ){
	centerpanel.getActiveTab().center(lng, lat );
}
function mapBestView( points ){
	centerpanel.getActiveTab().bestMaps( points );
}

function mapTrackStart( objArray ){
	if( g_oTrackObj != null ){
		g_oTrackObj.start( objArray, false );	
	}	
}

function mapTrackplay ( ){
	if( g_oTrackObj != null ){
		g_oTrackObj.play();
		mapTrackNext( );
	}	
}
function mapTrackPause( ){
	if( g_oTrackObj != null ){
		g_oTrackObj.pause( );	
	}	
}
function mapTrackNext( ){
	if( g_oTrackObj != null ){
		if( g_oTrackObj.next( ) ){
			setTimeout( "mapTrackNext( )", 1000 );
		}
	}	
}
function mapTrackStop( ){	
	if( g_oTrackObj != null ){
		g_oTrackObj.stop( );	
	}	
}

function isTrackPlayValid( ){
	if( g_oTrackObj != null ){
		return g_oTrackObj.isTrackValid( );	
	}
	else{
		return false;
	}	
}
function mapTrackEnd( ){	
	if( g_oTrackObj != null ){
		g_oTrackObj.end( );	
	}	
}
function mapGetStartUrl(obj){
	return "";
}
function mapGetEndUrl(obj){
	return "";
}
function mapGetParkUrl(obj){
	return "";
}

//////////////////////////////////////////////////////////////////////
function getAlarmStr( obj ){
	
	var result = "";		
	if( obj.A_URGENCY){
		if( result.length > 0 ) result += "|";
		result += getStr(s_UrgencyAlarm);	        
	}
	if( obj.A_CUSTOM1){
		if( result.length > 0 ) result += "|";
		result += getStr(s_CustomAlarm1);      		
	}
	if( obj.A_CUSTOM2){
		if( result.length > 0 ) result += "|";
		result += getStr(s_CustomAlarm2);      		
	}
	if( obj.A_CUSTOM3){
		if( result.length > 0 ) result += "|";
		result += getStr(s_CustomAlarm3);      		
	}
	if( obj.A_CUSTOM4){
		if( result.length > 0 ) result += "|";
		result += getStr(s_CustomAlarm4);      		
	}
	if( obj.A_POWEROFF){
		if( result.length > 0 ) result += "|";
		result += getStr(s_MainPowerOffAlarm);     		
	}
	if( obj.A_LOWPOWER){
		if( result.length > 0 ) result += "|";
		result += getStr(s_LowPowerAlarm);       	
	}
	if( obj.A_PARKOVERTIME){
		if( result.length > 0 ) result += "|";
		result += getStr(s_ParkCarTimeOutAlarm);    			
	}
	if( obj.A_IN_AREA){
		if( result.length > 0 ) result += "|";
		result += getStr(s_InAreaAlarm);        	
	}
	if( obj.A_OUT_AREA){
		if( result.length > 0 ) result += "|";
		result += getStr(s_OutAreaAlarm);        	
	}
	if( obj.A_IL_ACCON){
		if( result.length > 0 ) result += "|";
		result += getStr(s_IllegalStart);   			
	}
	if( obj.A_IL_DOOROPEN){
		if( result.length > 0 ) result += "|";
		result += getStr(s_IllegalOpenDoor);     		
	}
	if( obj.A_OVERSPEED){
		if( result.length > 0 ) result += "|";
		result += getStr(s_OverSpeedAlarm);       
	}
	return result;
}
function updateMap( ){
		
	var			objGPS = null;
	
	if( g_oGPSData == null || g_oVechile == null  ){
		return;
	}	
	// update maps
	for( var i = 0; i < g_oGPSData.getLen(); i++ ){
		
		
		objGPS = g_oGPSData.getGPS( i );
		
		if( objGPS.hasUpdate == true  ){	
			updateMapByGPS( objGPS, true );
			g_oGPSData.setUpdateFlag( i, false );	
		}			
	}	
}

function updateMapByGPS( objGPS, bDisplayFeedback ){
		
	var		state;
	
	if( objGPS.VALID == 1 ){
		state= getStr(s_HasPosition);
	}
	else{
		state= getStr(S_NoPosition);	   
	}
	
	if( isTrackPlayValid() == false  ){
		mapAddMarker2( 	getLicenseByTEUID( objGPS.TEUID), 
						objGPS.LON, 
						objGPS.LAT, 
						objGPS.SPEED, 
						objGPS.DIRECTION, 
						objGPS.A_URGENCY||objGPS.A_CUSTOM1||objGPS.A_CUSTOM2||objGPS.A_CUSTOM3||objGPS.A_CUSTOM4||objGPS.A_POWEROFF||objGPS.A_LOWPOWER||objGPS.A_PARKOVERTIME||objGPS.A_IN_AREA||objGPS.A_OUT_AREA||objGPS.A_IL_ACCON||objGPS.A_IL_DOOROPEN||objGPS.A_OVERSPEED );
						
		if( objGPS.first == true ){				
			mapCenter( objGPS.LON, objGPS.LAT );	
		}
	}	
	
	if( bDisplayFeedback ){
		addFeedbackInfo( getLicenseByTEUID( objGPS.TEUID ), UTCtoLocal(objGPS.TIME), state, objGPS.SPEED, objGPS.DIRECTION, objGPS.LON, objGPS.LAT );
		
		state = getAlarmStr( objGPS );
		if( state.length > 0 ){
			addAlarmInfo( getLicenseByTEUID( objGPS.TEUID ), UTCtoLocal(objGPS.TIME), state, objGPS.SPEED, objGPS.DIRECTION, objGPS.LON, objGPS.LAT );					
		}
	}
	return;
}

function CheckPassword( strTitle, CallFunc ){
	if( !strTitle || !CallFunc ){
		//alert("no Title or CallFunction");
		return;
	}
	
	var text_Password = new Ext.form.TextField({
		width		:	130,		
        baseCls		: 	'x-plain',		
        fieldLabel	:	getStr(s_InpuPassword),
        inputType	: 	'password',
        listeners	:	{   
			'specialkey' : function(txt, ev) {
				if (ev.getKey() == ev.ENTER) {
                	ok(); 
				}
			}
        }   
	});
	
	function ok(){
		var text = text_Password.getValue();
		if( text==getUserPassword() ){
			winCheckPassword.close();
			CallFunc();
		}
		else{
			winCheckPassword.close();
			Ext.Msg.alert( getStr(s_Tip), "&nbsp;&nbsp;&nbsp;&nbsp;" + getStr(s_Alert_PasswordError)+"&nbsp;&nbsp;&nbsp;&nbsp;" );	
		}
	}
	
	var winCheckPassword = new Ext.Window({
	    title		: 	strTitle,
	    resizable 	: 	false,
	    width		: 	280,
	    height		: 	120,
	    layout		:	'form',
	    bodyStyle	: 	'padding:15px 0px 0px 15px;',
	    items		:	[ text_Password ],
	    buttons		:	[
	    	{
	    		text	:	getStr( s_Ok ),
	    		handler	:	function(){
	    			ok();
	    		}	
	    	},{
	    		text	:	getStr( s_Cancel ),
	    		handler	:	function(){
	    			winCheckPassword.close();
	    		}
	    	}
	    ]
	});
	
	var winAlert = new Ext.Window({
	    title		: 	getStr(s_Alarm),
	    //draggable 	:	false,
	    resizable 	: 	false,
	    width		: 	500,
	    height		: 	210,
	    bodyStyle	: 	'padding:10px 10px 10px 10px;',
	    items		:	[{ 
	    	baseCls		: 	'x-plain', 
	    	html		:	getStr(s_LegalTips)
	    }],
	    buttons		:	[
	    	{
	    		text	:	getStr( s_Agree ),
	    		handler	:	function(){
	    			winAlert.close();
	    			winCheckPassword.show();
	    		}	
	    	},{
	    		text	:	getStr( s_Deny ),
	    		handler	:	function(){
	    			winAlert.close();
	    		}
	    	}
	    ]
	});
	winAlert.show();

}

function showAjaxStatus( str ){
	var obj = document.getElementById("CMDStatus");
	if( obj ){
		if( str ){
			obj.style.backgroundColor='#006699';
			obj.innerHTML= "&nbsp;"+str;		
		}
		else{
			obj.style.backgroundColor="" ;
			obj.innerHTML="";		
		}		
	}
}	

function waiting(){
	if( Ext.getCmp('window_LoadWait') ){
		return;
	}
	
	var p = new Ext.ProgressBar({
		id		:	'ProgressBar_LoadWait'
	});
	p.wait({
		interval	: 	100, 
		increment	: 	15
	});
	var Window = new Ext.Window({
		id			:	'window_LoadWait',
	    title		: 	'Loading...',
	    resizable 	: 	false,
	    width		: 	200,
	    items		: 	p
	});
	Window.on('close',
		function(){
			if( Ext.getCmp('ProgressBar_LoadWait') ){
				Ext.getCmp('ProgressBar_LoadWait').reset( true );
			}
		}
	);
	Window.show();    
}
function wait_end(){
	if( Ext.getCmp('ProgressBar_LoadWait') ){
		Ext.getCmp('ProgressBar_LoadWait').reset( true );
	}
	if( Ext.getCmp('window_LoadWait') ){
		Ext.getCmp('window_LoadWait').close();
	}	
}
function needShowWaitDlg( StrXML ){
	
	for( var n = 0; n < XMLCMD.length; n ++){
		if ( StrXML.indexOf( XMLCMD[n] ) >= 0 ){
			return true;
		}
	}	
	return false;
} 
function setDefaultTime( StartTimeID, EndTimeID ){
	var d = new Date();
	
	var nowyyyy=d.getYear();
	var nowmm=d.getMonth()+1;
	var nowdd=d.getDate();
	var nowHH=d.getHours();
	var nowMM=d.getMinutes();
	var nowSS=d.getSeconds();
	
	if (nowmm<10)
	    nowmm="0"+nowmm;  
	if (nowdd<10)
	    nowdd="0"+nowdd;
	if (nowHH<10)
	    nowHH="0"+nowHH;
	if (nowMM<10)
	    nowMM="0"+nowMM;
	if (nowSS<10)
	    nowSS="0"+nowSS;
	    
	var StartTime=nowyyyy+"-"+nowmm+"-"+nowdd+" 00:00:00";
	var EndTime=nowyyyy+"-"+nowmm+"-"+nowdd+" "+nowHH+":"+nowMM+":"+nowSS;
	if( StartTimeID ){
		Ext.getCmp( StartTimeID ).setValue( StartTime );
	}
	if( EndTimeID ){
		Ext.getCmp( EndTimeID ).setValue( EndTime );
	}
}	
	
////////////////////////////////////////
function checkSameDay( oStartTime, oEndTime ){
	var sY = oStartTime.getYear();
	var sM = oStartTime.getMonth();
	var sD = oStartTime.getDate();
	
	var eY = oEndTime.getYear();
	var eM = oEndTime.getMonth();
	var eD = oEndTime.getDate();
	
	if( sY==eY && sM==eM && sD==eD){
		return true;
	}
	else{
		return false;
	}
}

function getArrLicenseByUsername( User ){
	if( User == g_oUser.Username ){
		var arrLicense = new Array();
		var len = getVechileLen();
		for( var i=0; i<len; i++ ){
			arrLicense.push( g_oVechile.objArray[i].License );
		}
		return arrLicense;
	}
	else{
		var len = g_oUser.SubUser.length;
		for( var i=0; i<len; i++ ){
			if( User==g_oUser.SubUser[i].Username ){
				return g_oUser.SubUser[i].VechileList;
			}
		}		
	}
	return false;
}

function refreshUserCarList(){
	if( westpanel != null ){
		westpanel.reload( "" );
	}
}

////////////////////////////////////////
// Alarm MessageBox
function AlarmMessageBox(){
	var obj = Ext.getCmp('AlarmMessageBox');
	if( obj ){
	   return;
	}
	
	var window = new Ext.Window({
		id			:	'AlarmMessageBox',
		title		:	getStr(s_NoteAlarm),
	    resizable 	: 	false,
	    width		: 	100,
	    height		: 	100,
	    bodyStyle	: 	'padding:0px 25px 25px 0px;',
	    items		: 	[
	    	{
	    		baseCls	: 	'x-plain',	    		
	    		html	: 	'<img src="image/alarm.gif" width ="100" height="100" onclick="southpanel.activate( 1 )" />'  
	    	}	
	    ]
	});
	
	var left = (document.body.clientWidth-100);
	var top = (document.body.clientHeight-100);
	window.setPosition([ left, top ]);
	window.show();

}

function closeAlarmMessageBox(){
	var obj = Ext.getCmp('AlarmMessageBox');
	if( obj ){
	   obj.close();
	}
}

function CheckAlarmInfo(){
	if( alarminfo==null ){
		return;
	}
	var count = alarminfo.store.getCount();
	if( count > 0 ){
		AlarmMessageBox();
	}
	else{
		closeAlarmMessageBox();
	}
	setTimeout( "CheckAlarmInfo();", 1000 );
}

////////////////////////////////////////
function getGridArrData( columns, store ){
	if( !columns || !store ){
		//alert( "Download excel no data input ");
		return;
	}
	
	var arrData = new Array();
	arrData[0] = new Array();	
	
	//insert table head	
	var len = columns.length;
	for( var i=0; i<len; i++ ){
		if( columns[i].header ){
			arrData[0].push( columns[i].header );
		}
	}

	//insert data
	var RCount = store.getCount();
	for( var i=0; i<RCount; i++){
		arrData[ i+1 ] = new Array();
		var record = store.getAt(i);
		for( var n=0; n<len; n++){
			if( columns[n].dataIndex ){
				arrData[ i+1 ].push( record.get( columns[n].dataIndex ) );	
			}
		} 
	} 
	return arrData;
}

function DownloadExcel( arrData ){
	if( !arrData ){
		//alert("Create excel no input arrData");
		return;
	}
	
	var p = "<|>";
	var pp = "<||>";
	
	var strData = "";
	var len = arrData.length;
	for( var i=0; i<len; i++ ){

		strData += arrData[i][0];
		var rowLen = arrData[i].length;		
		for( var n=1; n<rowLen; n++ ){
			strData += p + arrData[i][n];
		}
		strData += pp;
	}
	strData = strData.substring( 0, strData.length - pp.length );

	if( waiting != null ){
		waiting();	
	}
	if( showAjaxStatus != null ){
		showAjaxStatus('Download...');
	}
	Ext.Ajax.request({
		method 	:	"POST",
		timeout :	60 * 1000,
		url		: 	"CreateExcel.asp",
		headers	: 	{
		   'charset'		:	'UTF-8'
		},
		params	: 	{
			Username	:	getLocalUserName(),
			strData		:	strData
		},
		success	: 	function(response) {
			if( wait_end != null ){
				wait_end();		
			}
			if( showAjaxStatus != null ){
				showAjaxStatus();
			}
			var RecvText = response.responseText;
			var Result = RecvText.split( p );
			if( Result[0] == "true" ){
				window.location.href = Result[1];
			}
			else{
				Ext.Msg.alert( getStr(s_Tip),getStr(s_downloadBusyWait) );	
			}
		},
		failure	:	function(){
			if( showAjaxStatus != null ){
				showAjaxStatus('Timeout...');
			}
			if( wait_end != null ){
				wait_end();		
			}
			Ext.Msg.alert( getStr(s_Tip),getStr(s_downloadBusyWait) );			
		}
	});
}

////////////////////////////////////////
function ChangeTheme( URL ){
	if( URL ){
		Ext.util.CSS.swapStyleSheet( "theme", URL );  
	}
	else{
		//alert("no Theme CSS url!");	
	}
}

function openNewWeb( str ){
	if( str.length < 1 ){
		str = "No Content !"
	}
	
	var newWeb = window.open( );
	newWeb.document.write( str );
}

////////////////////////////////////////
//
function PrivilegeIsValid( config ){
	if( config.key == null ){
		return false;
	}
	
	if( config.key == 'UserInfoManage' ){
		if( config.user == 'test'){
			Ext.Msg.alert( getStr(s_Tip),getStr(InsideLimitUserCanotOperation) );	
			return false;	
		}
	}
	
	if( config.key == 'setTEBackMode' ){
		if( config.privilege == 0 ){
			Ext.Msg.alert( getStr(s_Tip),getStr(s_NoPrivilegeSet) );	
			return false;	
		}
	}
	
	if( config.key == 'mileage' ){
		Ext.Msg.alert( getStr(s_Tip),getStr(s_NoPrivilegeSet) );
		return false;
	}
	
	return true;
}

//alert( "globalobj.js end" );
