var is_comment_div_init = false;
// создаём массив объектов для юнитов
var	units = new Array();
var unid2i = new Array();


///****************************************
// * A general helper function
// * $() replaces document.getElementById()
// ****************************************/
//if(typeof($)=='undefined'){
//  function $(elementId){
//    var element = document.getElementById(elementId);
//    return element;
//  }
//}

function regCheck(elem, regss)
{
	var ss = elem.value; 
	var pattern = new RegExp(regss, "i");
	var result = pattern.exec(ss);
	//alert (result);
	if (!result || result == 'null')
		result = '';
	elem.value = result;
}

function regValidate(value, regss)
{
	var patt = new RegExp("^" + regss + "$", "i");
//	var result = str.match(/^$/i)[1];
	var result = patt.exec(value);
	if (!result || result == null)
		return false;
//	alert (result[0]);
	if (result[0] == value)
		return true;
	return false;
}

function leadingZero(num, len) // дополнения числа num лидирующими нулями до длины length
{						
	var str = num.toString();
	for(var i=str.length; i<len; ++i)
		str ="0" + str;			
	return str;
}

function showComment(ss)
{
	hideComment();
	var comment_div = document.createElement('DIV');
	comment_div.style.position = 'absolute';
	comment_div.style.left = (getClientWidth() - 284) + 'px'; //'290px';
	comment_div.style.top = '105px';
	comment_div.style.width = '250px';
	comment_div.style.heigth = '190px';
	comment_div.id = 'commentDiv1';
	comment_div.style.display='block';
	var comment_text_div = document.createElement('div');
	comment_text_div.style.paddingLeft = '5px';
	comment_text_div.style.paddingRight = '5px';
	comment_text_div.style.paddingBottom = '5px';
	comment_text_div.style.position = 'relative';
	comment_text_div.style.diplay = "inline";
	
	var comm_string = "";
	comm_string += "<img src='../images/nofix.png'><br>";
//	comm_string += "<img src='../images/about.png'><br>";
	comm_string += ss;
	comment_text_div.innerHTML = comm_string;
	
	comment_div.appendChild(comment_text_div);	
	document.body.appendChild(comment_div);
	is_comment_div_init=true;
}

function hideComment()
{
  if (is_comment_div_init)
	{
	  is_comment_div_init=false;
	  document.body.removeChild(document.getElementById('commentDiv1'));
	}
}

function getClientWidth()
{
  myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
	return myWidth;
}

function getClientHeight()
{
  myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
	return myHeight;
}

	//прототип объекта unit
	function uunit(id, name, follow, lat, lon, alt, speed, course, sat, hdop, batt, fsdt, usdt, /*comment,*/ icon, label, active)
	{
		this.id = id;
		this.name = name;
		this.follow = follow;
		this.lat = parseFloat(lat);
		this.lon = parseFloat(lon);
		this.alt = parseFloat(alt);
		this.speed = parseFloat(speed);
		this.course = parseFloat(course);
		this.sat = parseInt(sat);
		this.hdop = parseFloat(hdop);
		this.batt = parseInt(batt);
		this.fsdatetime = fsdt; //датавремя в текстовом формате SQL - последний отчёт с определённой позицией  //сек
		this.usdatetime = usdt; //датавремя в текстовом формате SQL - последний отчёт с неопределённой позицией  //сек
		/*this.comment = comment;*/
		this.active = active;
		this.tableicon = "../icons/16/" + icon + ".png";
		this.mapicon = "../icons/32/" + icon + ".png";
	//	this.mapicon = "pic.php?t=" + name;
		this.marker = null;
		this.selected = false;
		//вычисляемые поля
		this.lasttime = 0;  //сек
		this.shortdt = "00-01-01";
		this.longdt = "2000-01-01 00:00:00";
		this.fixedlongdt = "2000-01-01 00:00:00";
		this.fixed = 0;
		this.online = 0;
		this.htmlcomment = "";
		this.label = null;
		this.labelname = "<nobr>" + label + "</nobr>";
		this.labeltitle = label;
		this.showname = "";
		this.icontd = "";
		this.alerted = false;
		this.lasteventid = -1;

		if (showlabels == 1 || showlabels == 3)
			this.showname = this.labelname;	
		else
			this.showname = this.name;	

		//метод для обновления значений вычисляемых полей										
		this.update = UpdateUnitFields;
		function UpdateUnitFields()
		{
			//по разнице времён определим текущее состояние фикса
			if (this.fsdatetime >= this.usdatetime)
			{
				this.lasttime = this.fsdatetime;
				this.fixed = 1;
			}
			else
			{
				this.lasttime = this.usdatetime;
				this.fixed = 0;
			};
			//по отдалённости последнего отчёта определим, на связи ли сейчас юнит. 
			if ((servertime - this.lasttime) > pause)
			{
				this.online = 0;
			}
			else
			{
				this.online = 1;
			};
			//дата/время в коротком виде для таблицы юнитов
			this.shortdt = dt2shortlongdt(this.lasttime, 1);
			
			//дата/время крайнего отчёта в длинном виде для облака и таблицы информации
			this.longdt = dt2shortlongdt(this.lasttime, 2);
			
			//дата/время крайней определённой позиции в длинном виде для облака и таблицы информации
			this.fixedlongdt = dt2shortlongdt(this.fsdatetime, 2);
	
			this.htmlcomment = "<div style='width:250px;'>";
			this.htmlcomment +=	"<strong>" + this.showname + "</strong><br><br>";
			this.htmlcomment +=	"<table width='100%'>";
			this.htmlcomment +=	"<tr><td width='100'>Широта:</td><td>" + this.lat + "&deg;</td></tr>";
			this.htmlcomment +=	"<tr><td>Долгота:</td><td>" + this.lon + "&deg;</td></tr>";
			this.htmlcomment +=	"<tr><td>Высота:</td><td>" + this.alt + " м</td></tr>";		
			this.htmlcomment +=	"<tr><td>Скорость:</td><td>" + this.speed + " км/ч</td></tr>";	
			this.htmlcomment +=	"<tr><td>Курс:</td><td>" + this.course + "&deg;</td></tr>";
			if (this.sat != 0)
			{
				this.htmlcomment +=	"<tr><td>Спутники:</td><td>" + this.sat + "</td></tr>";
			}
			if (this.hdop != 0)
			{
				this.htmlcomment +=	"<tr><td>HDOP:</td><td>" + this.hdop + "</td></tr>";
			}
			if (this.batt != 0)
			{
				this.htmlcomment +=	"<tr><td>Заряд батареи:</td><td>" + this.batt + "%</td></tr>";
			}
			this.htmlcomment +=	"<tr><td>Время позиции:</td><td>" + this.fixedlongdt + "</td></tr>"; 
			this.htmlcomment +=	"<tr><td>Время отчёта:</td><td>" + this.longdt + "</td></tr>"; 
			this.htmlcomment +=	"</table></div>";
			
			//определим иконку статуса юзера
			if (this.active == 0)  //если объект неактивен (не оплачен)
			{
				this.icontd = "<td class='piclocked' onclick='window.location=\"finance.php\";' title='Объект не оплачен или оплаченный заказ не активирован. Кликните для перехода на страницу \"Финансы\"'>&nbsp;</td>";
			}
			else //if (this.active == 0)
			{

				if (taximode)
				{
					if (this.alerted) //если есть неотложное событие...
					{
						this.icontd = "<td class='picsos' onclick='unitEventClick(" +  this.lasteventid + ")' title='SOS'>&nbsp;</td>";
					}
					else //if (this.alerted)
						if (this.fixed == 1 && this.online == 1)
						{
							this.icontd = "<td class='pic3dfix' onClick='unitNameClick(" + this.id + ")' title='Позиция определена'>&nbsp;</td>";
						}
						else //if (this.fixed == 1 && this.online == 1) 
							if (this.fixed == 0 && this.online == 1)
							{
								this.icontd = "<td class='picnofix' onClick='unitNameClick(" + this.id + ")' title='Данные поступают, позиция не определена'>&nbsp;</td>";
							}
							else //if (this.fixed == 0 && this.online == 1)
							{
								this.icontd = "<td class='picnoconn' onClick='unitNameClick(" + this.id + ")' title='Нет данных от устройства более ";
								this.icontd += (pause/60);
								this.icontd += " минут.'>&nbsp;</td>";
							}
				}
				else //if (taximode)
				{
					if (this.lasteventid >= 0) //если есть неотложное событие...
					{
						this.icontd = "<td class='picsos' onclick='unitEventClick(" +  this.lasteventid + ")' title='SOS'>&nbsp;</td>";
					}
					else //if (this.lasteventid >= 0)
						if (this.fixed == 1 && this.online == 1)
						{
							this.icontd = "<td class='pic3dfix' onClick='unitNameClick(" + this.id + ")' title='Позиция определена'>&nbsp;</td>";
						}
						else //if (this.fixed == 1 && this.online == 1) 
							if (this.fixed == 0 && this.online == 1)
							{
								this.icontd = "<td class='picnofix' onClick='unitNameClick(" + this.id + ")' title='Данные поступают, позиция не определена'>&nbsp;</td>";
							}
							else //if (this.fixed == 0 && this.online == 1)
							{
								this.icontd = "<td class='picnoconn' onClick='unitNameClick(" + this.id + ")' title='Нет данных от устройства более ";
								this.icontd += (pause/60);
								this.icontd += " минут.'>&nbsp;</td>";
							}
				} ////if (taximode)

			} //if (this.active == 0)


			
			
			
			
		}; //UpdateUnitFields()
	}; //unit