/*****************
Created 24.04.2007
*****************/

var reports = new Array();
var reports_pending = '';
var list_reports = '';
var timerID = 0;
var timerFreq = 15000;
var url = '';
var server = '';
var lang = '';
var report = '';
var gps_ids = '';
var complete = true;
var loading_img = '<img src="../images/mozilla_blu.gif">';
var updated_time = '';
var timezone_offset = 0;
var no_report = '';
var globalLog = new Array();
var text_show_all = '';
var text_show_last = '';
var text_config_file_exists = '';
var text_delete_modify = '';
var text_sending_confg = '';
var text_invalid_command = '';
var text_command_sintax = '';
var text_message_too_long = '';
var text_invalid_response_id = '';

/**************
on window load
***************/
function loadAjax() {
	updateTimer();
}

/***************
on window unload
***************/
function unloadData(){
	window.clearTimeout(timerID);
}

/*************************
update timer and if last 
ajax request was complete, 
make a new one
*************************/
function updateTimer(){
	if ( complete == true ){
		updateData();   
	};
	timerID = setTimeout("updateTimer()", timerFreq);
}

/************************
make a new ajax requst 
to update cars flags
************************/
function updateData(){
	complete = false;
	document.getElementById("ajax_loading").innerHTML = loading_img;
	var myDate = new Date();

    var myAjax = new Ajax.Request(
        url + '&gps_ids='+gps_ids+'&rand=' + myDate.getTime(), 
        {
            method: 'get',
            onComplete: refreshFlags
        }
    );

    myDate=null;
}

/*************************
if request was completed 
succesfully redraw the flags
*************************/
function refreshFlags(response){
    if ( response.readyState == 4 ){
        if ( response.status == 200 ){
            drawFlags(eval('(' + response.responseText + ')'));
        };
        complete = true;
        return true;
    };
}

/***************
redraw the flags
***************/
function drawFlags(data){
    var flags = data.fleet;
    var updated_text = data.text.last_updated;
    var user_name = data.user_name;
    
    for ( var i=0; i<flags.length; i++ ){
        var alias_content = document.getElementById('alias_' + flags[i].id);
        if (alias_content) {
            var text_node;
            if ( user_name == 'root' ) {
            	text_node = document.createTextNode(flags[i].vehicle + ' / ' + flags[i].psn + ' / ' + flags[i].imei + ' / ' + flags[i].swv);
            }
            else {
            	text_node = document.createTextNode(flags[i].vehicle);
            };
            alias_content.removeChild(alias_content.lastChild);
            alias_content.appendChild(text_node);
            text_node = null;
            
            // driver info
			var driver_info = document.getElementById('driver_'+flags[i].id);
            if ( flags[i].driver ) {
            	driver_info.innerHTML = flags[i].driver.name;
            }
            else {
            	driver_info.innerHTML = '';
            };
			driver_info = null;
			            
            if ( flags[i].config_file == 1 ) {            
	            if ( !document.getElementById('sending_config_'+flags[i].id) ) {
					var a = document.getElementById('a_config_'+flags[i].id);
		            var img = document.createElement('img');
		            img.id = 'sending_config_' + flags[i].id;
		            img.setAttribute('src', '../images/up.png');
		            img.setAttribute('border', '0');           
		            img.setAttribute('title', text_sending_config); 
		            alias_content.insertBefore(img, a);
		            img = null;
		            a = null;
	            };       
            }
            else if ( document.getElementById('sending_config_'+flags[i].id) ) {
            	alias_content.removeChild(document.getElementById('sending_config_'+flags[i].id));
            };
        };
        alias_content = null;

        var gps_content = document.getElementById(flags[i].id);
        var children = gps_content.childNodes;

        var j=0;
        while ( j<children.length ) {
            if ( children[j].tagName != "A" && children[j].tagName != "a" ) {
                gps_content.removeChild(children[j]);
            }
            else {
                j++;
            };
        };
        
        gps_content.innerHTML = flags[i].position.date + flags[i].flags;
        
        var a = document.createElement('a');
        a.target = 'map';
        a.border = 0;
        a.href = server + '/main/mapctrl.cgi?focus_gps_id=' + flags[i].id + '&latitude=' + flags[i].position.lat + 
            '&longitude=' + flags[i].position.lon + '&alias=' + flags[i].vehicle + '&date=' + flags[i].position.date + '&lang=' + lang + '&user_name=' + user_name;
        if ( flags[i].position.invalid != 1 && flags[i].gis_link  ) { 
            a.innerHTML = flags[i].gis_link;
        }
        else {
            a.innerHTML = '';
        };
        gps_content.appendChild(a);
        
        a = document.createElement('a');
        a.href = 'index.cgi?content_name=gps_detailed_report&lang=' + lang + '&search_by=psn&to_date=' + flags[i].position.date +
            '&search_text=' + flags[i].psn + '&submit=Search';
        a.innerHTML = '<img border="0" title="' + report + '" src="../images/folder.gif"/>';
        gps_content.appendChild(a);

        var alerts = gps_content.nextSibling;
        if ( alerts.tagName != 'TD' ) {alerts = alerts.nextSibling};
        if ( flags[i].alerts ) {
            alerts.innerHTML = flags[i].alerts;
        }
        else {
            alerts.innerHTML = "";
        };

        gps_content = null;
        children = null;
        alerts = null;
        a = null;
        
        // update realtime reports period
        var t = flags[i].position.date;
        var x = t.split(' ');
        t = x[0] + ' 00:00:00';
        
        if ( document.getElementById('time_'+flags[i].id) ) {
        	document.getElementById('time_'+flags[i].id).innerHTML = t + ' - ' + flags[i].position.date;
        };
        
        // if there is a real time report print it
        var r_div;
        if ( document.getElementById('reports_div_'+flags[i].id) ) {
	        r_div = document.getElementById('reports_div_'+flags[i].id);
	        r_div.innerHTML = "";
        };
        if ( r_div && flags[i].reports ) {
        	if ( flags[i].reports.pending == 1 ) {
        		r_div.innerHTML = '<img src="../images/processing.gif" border=0 title="'+ flags[i].reports.start_date+' - '+flags[i].reports.end_date+'">';
        	}
        	else {
        		var a = document.createElement('a');
        		a.id = 'list_reports_'+flags[i].id;
        		a.setAttribute('onclick', 'return overlay(this, "show_reports_'+flags[i].id+'", "right");');
        		a.href = '#show_reports_'+flags[i].id;
        		        		
        		var img = document.createElement('img');
        		img.src = flags[i].reports.status == 0 ? '../images/witherrors.png' : '../images/ok_report.png';
        		img.style.borderWidth = '0px';
        		img.title = list_reports;
        		a.appendChild(img);
        		img = null;
        		
        		r_div.appendChild(a);
        		a = null;
        		
        		var div = document.createElement('div');
        		div.id = 'show_reports_'+flags[i].id;
        		div.style.border = '1px solid rgb(0, 51, 153)';
        		div.style.padding = '8px';
        		div.style.position = 'absolute';
        		div.style.backgroundColor = 'white';
        		div.style.display = 'none';
        		div.style.whiteSpace = 'nowrap';
        		
        		var adiv = document.createElement('div');
        		adiv.align = 'right';
        		
        		a = document.createElement('a');
        		a.setAttribute('onclick', 'overlayclose("show_reports_'+flags[i].id+'"); return false;');
        		a.href = '#show_reports_'+flags[i].id;
        		a.innerHTML = '<img border="0" alt="" src="../images/windowclose.gif"/>';
        		adiv.appendChild(a);
        		a = null;
        		div.appendChild(adiv);
        		adiv = null;
        		
        		div.appendChild(document.createTextNode(flags[i].reports.start_date+' - '+flags[i].reports.end_date));
        		div.appendChild(document.createElement('br'));
        		div.appendChild(document.createElement('br'));
        		
        		for ( var j = 0; j<flags[i].reports.reports.length; j++ ) {
	        		if ( flags[i].reports.reports[j].status == 1 ) {
		        		a = document.createElement('a');
		        		a.href = flags[i].reports.reports[j].url;
		        		if ( flags[i].reports.reports[j].id == 1 ) {
		        			a.target = 'map';
		        		}
		        		else {
		        			a.target = '_blank';
		        		};
		        		var x = document.createElement('tt');
		        		x.innerHTML = flags[i].reports.reports[j].longname;
		        		a.appendChild(x);
		        		x = null;
	        		}
	        		else {
	        			a = document.createElement('font');
	        			a.color = 'red';
	        			a.innerHTML = flags[i].reports.reports[j].longname;
	        		};
	        		
	        		div.appendChild(a);
	        		div.appendChild(document.createElement('br'));
	        		a = null;
        		};
        		r_div.appendChild(div);
        		div = null;
        	};
        };
    };
    
    var mydate = new Date();
    var s = compute(mydate.getUTCHours()) + ":" + compute(mydate.getUTCMinutes()) + ":" + compute(mydate.getUTCSeconds());
    
    mydate.setTime(mydate.getTime() + (mydate.getTimezoneOffset() * 60000) + (timezone_offset * 1000));
    
    updated_time = updated_text + ": " + compute(mydate.getHours()) + ":" + compute(mydate.getMinutes()) + ":" + compute(mydate.getSeconds()) +
                    '<BR>GMT: ' + s;
    document.getElementById("ajax_loading").innerHTML = updated_time;
    date = null;
}

function compute(nr){
    if ( nr>=10 ) {return nr;};
    return '0' + nr;
}

function getReports(gps_id) {
	document.getElementById('reports_' + gps_id).innerHTML = loading_img;
	
	var params = server + '/main/json.cgi?realtimereports=1&gps_id=' + gps_id;
    var myAjax = new Ajax.Request(
        params, 
        {
            method: 'get',
            onComplete: loadReports
        }
    );		
}

function loadReports(response) {
    if ( response.readyState == 4 ){
        if ( response.status == 200 ){
            fillReports(eval('(' + response.responseText + ')'));
        };
        return true;
    };	
}

function fillReports(data) {
	var gps_id = data.gps_id;
	var rep = data.reports;
	
	var div = document.getElementById('reports_' + gps_id);
	div.innerHTML = '';
	
	var table = document.createElement('table');
	var body = document.createElement('body');
	var tr = document.createElement('tr');
		
	for ( var i = 0; i < rep.length; i++ ) {
		var td = document.createElement('td');
		td.style.whiteSpace = 'nowrap';
		
		var reportdata = getReport(rep[i].id);
		
		var input;
		if ( window.ActiveXObject ) {
			input = document.createElement('<input name="report" />');
		}
		else {
			input = document.createElement('input');
			input.name = 'report';
		};
		input.type = 'checkbox';
		//input.name = 'report';
		input.value = reportdata.id;	
		td.appendChild(input);

		var text = document.createTextNode('(' + reportdata.id + ') ' + reportdata.longname + ' ');
		td.appendChild(text);
		
		tr.appendChild(td);
		if ( i % 2 != 0 ) {
			body.appendChild(tr);
			tr = null;
			tr = document.createElement('tr');
		};
		
		td = null;
		text = null;
		input = null;
	};
	
	if ( rep.length % 2 != 0 ) {
		body.appendChild(tr);
	};
	tr = null;
	
	table.appendChild(body);
	body = null;
	div.appendChild(table);
	table = null;
	div = null;
	
//	div = document.getElementById('do_'+gps_id);
//	var left = div.style.left;
//	var width = div.clientWidth;
//	
//	left = left.substring(0, left.indexOf('p'))*1;
//	left = left - width + 230;
//	div.style.left = left+'px';
	
	return overlay(document.getElementById('mydo_'+gps_id), 'do_'+gps_id, 'right');
}

function getReport(id) {
	for ( var i = 0; i < reports.length; i++ ) {
		if ( reports[i].id == id ) return reports[i];
	};
	
	return;
}

function submitReports(gps_id) {
	var dates = document.getElementById('time_'+gps_id).innerHTML.split(' - ');
	var reports = document.getElementById('reports_'+gps_id).getElementsByTagName('input');
	
	var report = [];
	var found = 0;
	for ( var i = 0; i < reports.length; i++ ) {
		if (reports[i].checked == true) {
			report.push(reports[i].value);
			found = 1;
		};
	};
	
	if ( found == 0 ) {
		alert(no_report);
		return;
	};
	
	var params = server + '/main/json.cgi?postrealtimereports=1&gps_id=' + gps_id + '&start_date='+dates[0]+'&end_date='+dates[1]+'&doreports='+report + '&lang=' + lang;
    var myAjax = new Ajax.Request(
        params, 
        {
            method: 'get',
            onComplete: postReports
        }
    );
    overlayclose('do_'+gps_id);
}

function postReports(response) {
    if ( response.readyState == 4 ){
        if ( response.status == 200 ){
            var data = eval('(' + response.responseText + ')');
            var gps_id = data.gps_id; 
            document.getElementById('reports_div_'+gps_id).innerHTML = '<img src="../images/processing.gif" border=0';
        };
        complete = true;
        return true;
    };	
}

function changeTab(tab) {
	
	var names = tab.id.split('_');	
	var parent = tab.parentNode;

	var grandpa = parent.parentNode.childNodes;
	for ( var i = 0; i < grandpa.length; i++ ) {
		if ( grandpa[i].tagName && grandpa[i].tagName == 'TD' && grandpa[i].attributes.length > 0 && grandpa[i].attributes[0].value != 'lastTab' ) {
			var g_elem = grandpa[i].getElementsByTagName('A')[0];
			if ( g_elem ) {
				grandpa[i].style.backgroundColor = '#f4f4f4';
				g_elem.style.fontWeight = 'normal';
				var g_names = g_elem.id.split('_');
				document.getElementById(g_names[1] + '_' + g_names[2]).style.display = 'none';
				g_names = null;
			};
		};
	};
	parent.style.backgroundColor = '#cad3bf';
	tab.style.fontWeight = 'bold';
	document.getElementById(names[1] + '_' + names[2]).style.display = 'block';
	
	parent = null;
	grandpa = null;
	
	if ( names[1] == 'log' ) {
		getLastLog(names[2]);
	}
	else if ( names[1] == 'advanced' ) {
		getConfig(names[2]);
	};
	names = null;
}

function getConfig(gps_id) {
	var myAjax = new Ajax.Request(
        server + '/main/json.cgi?gps_id='+gps_id+'&loadcommands=1&check=1', 
        {
            method: 'get',
            onComplete: fillCommands
        }
    );
}

function deleteAndLoadConfig(gps_id) {
	var myAjax = new Ajax.Request(
        server + '/main/json.cgi?gps_id='+gps_id+'&loadcommands=1&delete=1', 
        {
            method: 'get',
            onComplete: fillCommands
        }
    );
}

function fillCommands(response) {
	if ( response.readyState == 4 ){
        if ( response.status == 200 ){
            completeCommands(eval('(' + response.responseText + ')'));
        };
        complete = true;
        return true;
    };		
}

function completeCommands(data) {
	var gps_id = data.gps_id;
	
	var table = document.getElementById('advanced_'+gps_id).getElementsByTagName('TABLE')[0].getElementsByTagName('TBODY')[0];
	var childs = table.childNodes;
	while ( childs.length > 0 ) {
		table.removeChild(childs[childs.length - 1]);
	};
	childs = null;
	
	if ( data.commands_exist ) {
		var tr = document.createElement('tr');
		var td = document.createElement('td');
		td.appendChild(document.createTextNode(text_config_file_exists));
		td.appendChild(document.createElement('br'));
		
		var a = document.createElement('a');
		a.setAttribute('href', '#');
		a.style.fontWeight = 'bold';
		a.setAttribute('onClick', 'deleteAndLoadConfig('+gps_id+')');
		a.innerHTML = text_delete_modify;
		td.appendChild(a);
		a = null;
		tr.appendChild(td);
		td = null;
		table.appendChild(tr);
		tr = null;
	}
	else {
		var commands = data.commands;
		var tr = document.createElement('tr');
		var td = document.createElement('td');
		var textarea = document.createElement('textarea');
		textarea.style.border = '1px solid #f4f4f4';
		textarea.setAttribute('rows', '10');
		textarea.setAttribute('name','commands')
		textarea.id = 'textarea_'+gps_id;
		textarea.value = commands;
		td.appendChild(textarea);
		textarea = null;
		tr.appendChild(td);
		td = null;
		table.appendChild(tr);
		tr = null;
		
		tr = document.createElement('tr');		
		td = document.createElement('td');
		td.setAttribute('align', 'right');
		td.innerHTML = '<input type="image" src="../images/check.gif" onClick="return checkValidCommand('+gps_id+')" style="border=0;">';
		tr.appendChild(td);
		td = null;
		table.appendChild(tr);
		tr = null;
		
		tr = document.createElement('tr');		
		td = document.createElement('td');
		td.innerHTML = text_command_sintax;
		tr.appendChild(td);
		td = null;
		table.appendChild(tr);
		tr = null;
	};
	table = null;
}

function checkValidCommand(gps_id) {
	var content = document.getElementById('textarea_'+gps_id).value.split('\n');
	for ( var i = 0; i < content.length; i++ ) {
		var start_char = /^Q|R|r|S|s|C|c|P|p/;
		var escape_char = /\/\/$/;
		if ( (content[i].length > 0 && (content[i].search(start_char) ==-1 || content[i].search(escape_char) == -1)) || content[i].length >160 ) {
			alert(text_invalid_command);
			return false;
		};
	};
	return true;
}

function checkValidMessage(gps_id) {
	var c = document.getElementById('textarea_message_'+gps_id).value;
	var count = 0;
	
	for ( var i = 0; i < c.length; i++ ) {
		var dec_val = ord(c[i]);
		var no_octet = 0;
		if ( dec_val <= 127 ) {
			count+=1;
		}
		else if ( dec_val <= 2047 ) {
			count+=2;
		}
		else if ( dec_val <= 65535 ) {
			count+=3;
		}
		else {
			count+= 4;
		};
		
		if ( count > 155 ) {
			alert(text_message_too_long);
			return false;
		};
	};
	alert(count);
	
	
	if ( count > 155 ) {
		alert(text_message_too_long);
		return false;
	};
	
	if ( document.getElementsByName('message_type_'+gps_id).value == 3 ) {
		var val = document.getElementsByName('response_id_'+gps_id).value;
		if ( !value || value > 40 || value < 1 ) {
			alert(text_invalid_response_id);
			
			val = null;
			return false;
		};
		val = null;
	};
	
	return true;
}

function getLastLog(gps_id) {
	var myLog = null;	
	if ( globalLog.length > 0 ) {
		for ( var i = 0; i < globalLog.length; i++ ) {
			if ( globalLog[i]['gps_id'] == gps_id ) {
				myLog = globalLog[i];
				break;
			};
		};
	};
	
	if ( myLog == null ) {
	    var myAjax = new Ajax.Request(
	        server + '/main/json.cgi?gps_id='+gps_id+'&command_log=1', 
	        {
	            method: 'get',
	            onComplete: fillLog
	        }
	    );
	}
	else {
		showLastLog(myLog);
	};
	
	myLog = null;
}

function fillLog(response) {
    if ( response.readyState == 4 ){
        if ( response.status == 200 ){
            completeLog(eval('(' + response.responseText + ')'));
        };
        complete = true;
        return true;
    };		
}

function completeLog(data) {
	var newLog = new Object();
	newLog.gps_id = data.gps_id;
	newLog.log = data.log;
	
	globalLog.push(newLog);
	showLastLog(newLog);
	
	newLog = null;
}

function showLog(gps_id, last) {
	var table = document.getElementById('scroll_log_' + gps_id).getElementsByTagName('TABLE')[0].getElementsByTagName('TBODY')[0];
	
	var childs = table.childNodes;
	while ( childs.length > 0 ) {
		table.removeChild(childs[childs.length - 1]);
	};
	childs = null;
	for ( var i = 0; i < globalLog.length; i++ ) {
		if ( globalLog[i].gps_id == gps_id ) {
			if ( last ) {
				printLog(table, globalLog[i].log[globalLog[i].log.length - 1]);
				document.getElementById('show_it_'+gps_id).innerHTML = text_show_all;
				document.getElementById('show_it_'+gps_id).setAttribute('onClick', 'showLog('+gps_id+')');
			}
			else {
				for ( var j = 0; j < globalLog[i].log.length; j++ ) {
					printLog(table, globalLog[i].log[j]);
					
					var tr = document.createElement('tr');
					var td = document.createElement('td');
					td.setAttribute('colspan', "2");
					td.appendChild(document.createElement('hr'));
					tr.appendChild(td);
					td = null;
					table.appendChild(tr);
					tr = null;
				};
				document.getElementById('show_it_'+gps_id).innerHTML = text_show_last;
				document.getElementById('show_it_'+gps_id).setAttribute('onClick', 'showLog('+gps_id+', 1)');
			};
			table = null;
			return;
		};
	};
	table = null; 	
}

function showLastLog(myLog) {
	var table = document.getElementById('scroll_log_' + myLog.gps_id).getElementsByTagName('TABLE')[0].getElementsByTagName('TBODY')[0];
	
	var childs = table.childNodes;
	while ( childs.length > 0 ) {
		table.removeChild(childs[childs.length - 1]);
	}; 
	childs = null;
	
	var lastLog = myLog.log[myLog.log.length - 1];
	printLog(table, lastLog);
	
	lastLog = null;
	table = null;
	
	document.getElementById('show_it_'+myLog.gps_id).innerHTML = text_show_all;
	document.getElementById('show_it_'+myLog.gps_id).setAttribute('onClick', 'showLog('+myLog.gps_id+')');
}

function printLog(table, log) {
	for ( var i = 0; i <  log.length; i++ ) {
		var tr = document.createElement('tr');
		
		var td = document.createElement('td');
		td.setAttribute('valign', 'top');
		td.style.backgroundColor = '#f4f4f4';
		td.style.paddingTop = "3px";
		td.appendChild(document.createTextNode(log[i].time));
		tr.appendChild(td);
		td = null;
		
		td = document.createElement('td');
		td.style.backgroundColor = '#f4f4f4';
		td.setAttribute('valign', 'top');
		var table1 = document.createElement('table');
		table1.setAttribute('width', '100%');
		table1.setAttribute('cellpadding', '1');

		var tr1 = document.createElement('tr')
		var td1 = document.createElement('td');
		td1.style.backgroundColor = '#f4f4f4';
		td1.setAttribute('valign', 'top');
		td1.appendChild(document.createTextNode(log[i].command));
		tr1.appendChild(td1);
		td1 = null;
		table1.appendChild(tr1);
		tr1 = null;
		
		tr1 = document.createElement('tr');
		td1 = document.createElement('td');
		td1.style.backgroundColor = '#ffffcc';
		td1.style.paddingBottom = '2px';
		td1.style.paddingTop = '2px';
		td1.appendChild(document.createTextNode(log[i].response));
		tr1.appendChild(td1);
		td1 = null;
		table1.appendChild(tr1)
		tr1 = null;
		
		td.appendChild(table1);
		table1 = null;
		tr.appendChild(td);
		td = null;
		
		table.appendChild(tr);
		tr = null;
	};
};

function ord (string) {
    // Returns the codepoint value of a character  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ord    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ord('K');
    // *     returns 1: 75    // *     example 2: ord('\uD800\uDC00'); // surrogate pair to create a single Unicode character
    // *     returns 2: 65536
    var str = string + '';
    
    var code = str.charCodeAt(0);    
    if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
        var hi = code;
        if (str.length === 1) {
            return code; // This is just a high surrogate with no following low surrogate, so we return its value;
                                    // we could also throw an error as it is not a complete character, but someone may want to know        
		}
        var low = str.charCodeAt(1);
        if (!low) {
            return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
        }        
    }
    if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
        return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
                                // we could also throw an error as it is not a complete character, but someone may want to know    
	}
    return code;
}

function checkMessageType(select) {
	var a = select.name.split('_');
	if ( select.value == 3 ) {
		document.getElementById('response_messages_'+a[2]).style.display = 'block';
	}
	else {
		document.getElementById('response_messages_'+a[2]).style.display = 'none';
	};
	a = null;
}

//window.load = load();
window.unload = unloadData();
