var is_comment_div_init = false;
// создаём массив объектов для юнитов
var	units = new Array();
var unid2i = new Array();

function togCheck(id)
{
	var allChecked = true;
	$(id + ' input:checkbox:enabled').each(function()
		{
			if(!this.checked)
				allChecked = false;
		});
	$(id + ' input:checkbox:enabled').each(function(){this.checked = !allChecked;});
	return !allChecked;
}

function regCheck(elem, regss)
{
	var ss = elem.value; 
	var pattern = new RegExp(regss, "i");
	var result = pattern.exec(ss);
	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 imei_is_good(number) 
	{
		// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
		var number=number.replace(/\D/g, '');

		if (number.length == 0) 
			return false;
	
		// Set the string length and parity
		var number_length=number.length;
		var parity=number_length % 2;
	
		// Loop through each digit and do the maths
		var total=0;
		for (i=0; i < number_length; i++) 
		{
			var digit=number.charAt(i);
			// Multiply alternate digits by two
			if (i % 2 == parity) 
			{
				digit=digit * 2;
				// If the sum is two digits, add them together (in effect)
				if (digit > 9) 
				{
					digit=digit - 9;
				}
			}
			// Total up the digits
			total = total + parseInt(digit);
		}
	
		// If the total mod 10 equals 0, the number is valid
		if (total % 10 == 0) 
			return true;
		else 
			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 add0(str)
{
	return leadingZero(str, 2);
}	

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, clat, clon, 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.clat = parseFloat(clat);
		this.clon = parseFloat(clon);
		this.clat0 = 0;
		this.clon0 = 0;
		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 = parseInt(fsdt); //датавремя в текстовом формате SQL - последний отчёт с определённой позицией  //сек
		this.usdatetime = parseInt(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;
		this.type = 0; //тип объекта. 0 = обычный, 1 = объект + SOS (эфес), 2 = машины ГБР (эфес)

		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
	
	
	//прототип объекта eevent
	function eevent(id, typeid, dt, userid, lat, lon, medt, alt, speed, course, desc)
	{
		this.id = id;
		this.typeid = typeid;
		this.dt = dt;
		this.userid = userid;
		this.lat = parseFloat(lat);
		this.lon = parseFloat(lon);
		this.medt = medt;
		this.alt = alt;
		this.speed = speed;
		this.course = course;
		this.desc = desc;
		this.eventshortdt = ""; //"00-01-01";
		this.eventlongdt = ""; //"2000-01-01 00:00:00";
		this.lastfixshortdt = ""; //"00-01-01";
		this.lastfixlongdt = ""; //"2000-01-01 00:00:00";
		this.htmlcomment = "";
		this.alerted = false;
		
		//метод для обновления значений вычисляемых полей										
		this.update = UpdateEventFields;
		function UpdateEventFields()
		{
			//дата/время в коротком виде 
			if (this.eventshortdt.length == 0)
			{
				this.eventshortdt = dt2shortlongdt(this.dt, 1);
				this.lastfixshortdt = dt2shortlongdt(this.medt, 1);
				this.eventlongdt = dt2shortlongdt(this.dt, 2);
				this.lastfixlongdt = dt2shortlongdt(this.medt, 2);			
			}
		
			//добавим событие пользователю
			if (this.alerted)
			{
				if (!taximode)
					units[unid2i[this.userid]].alerted = true;
				units[unid2i[this.userid]].lasteventid = this.id;
			}
			
			//подготовим текст для облака
			if (this.alerted)
			{
				this.htmlcomment = "<div style='width:300px; background-color:#D03314; color:white;'>";  //width:260px; 
			}
			else
			{
				this.htmlcomment = "<div style='width:300px; background-color:white; color:black;'>";
			}
			this.htmlcomment +=	"<strong>Событие: " + eventtypes[this.typeid] + "</strong><br><br>";
			if (this.desc.length == 1 && this.desc == ".") //если описание пусто
				this.htmlcomment +=	"<strong>" + eventfdescs[this.typeid] + "</strong><br><br>";
			else
				this.htmlcomment +=	"<strong>" + eventfdescs[this.typeid] + ": <font color='red'>" + this.desc + "</font></strong><br><br>";
			this.htmlcomment +=	"<table width='100%'>"; //
			this.htmlcomment +=	"<tr><td width='100'>Имя:</td><td>" + units[unid2i[this.userid]].showname + "</td></tr>";
			this.htmlcomment +=	"<tr><td>Широта:</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>";
			this.htmlcomment +=	"<tr><td>Время события:</td><td>" + this.eventlongdt + "</td></tr>"; 
			this.htmlcomment +=	"<tr><td>Время позиции:</td><td>" + this.lastfixlongdt + "</td></tr>"; 
			this.htmlcomment +=	"</table>";
			if (this.alerted)
			{
				this.htmlcomment +=	"<br /><table width='100%'>";
				this.htmlcomment +=	"<tr align='center'>";
				this.htmlcomment +=	"<td width='35%' class='eventPopupButton' onclick='dismissAlert(" +  this.id + ", true)' ><strong>Сбросить <br />оповещение <br />и продолжить<br /></strong></td>";
				this.htmlcomment +=	"<td width='30%' class='eventPopupButton' onclick='dismissAlert(" +  this.id + ", false)' ><strong>Сбросить <br />оповещение <br />и остаться</strong></td>";
				this.htmlcomment +=	"<td width='30%' class='eventPopupButton' onClick='if (confirm (&quot;Вы действительно хотите сбросить все оповещения о событиях?&quot;)) {map.closeInfoWindow(); dismissAllAlerts();};' title='Сбросить все оповещения о событиях' ><strong>Сбросить <br />все <br />оповещения</strong></td>";
				this.htmlcomment +=	"</tr>";
				this.htmlcomment +=	"</table>";
			}
			this.htmlcomment +=	"</div>";
			
		}		
	} // eevent
	
	//прототип объекта aalert
	function aalert(id, ueid)
	{
		this.id = id;
		this.ueid = ueid;
	}
	
	//функция представления даты/времени (в сек) в коротком/длинном формате
	//type - требуемый формат (1 - короткий, 2 - длинный)
	function dt2shortlongdt(dt, type)
	{
		var tt = new Date(eval(dt)*1000);
		ttFullYear = tt.getUTCFullYear();
		ttMonth = add0(tt.getUTCMonth()+1);
		ttDate = add0(tt.getUTCDate());
		ttHours = add0(tt.getUTCHours());
		ttMinutes = add0(tt.getUTCMinutes());
		ttSeconds = add0(tt.getUTCSeconds());	
		
		if (dt < 100000) //если ещё не было ни одной позиции
		{
			return "-";
		}
		else 
		{
			if (type == 3)
			{
				//длинный формат
				return (ttFullYear + "-" + ttMonth + "-" + ttDate + " " +  ttHours + ":" + ttMinutes + ":" + ttSeconds).toString();
			}
			
			if (type == 2)
			{
				//длинный формат
				return (ttHours + ":" + ttMinutes + ":" + ttSeconds + " " + ttDate + "-" + ttMonth + "-" + ttFullYear).toString();
			}
			
			//короткий формат
			if (dt >= midnightsec) //если последний отчёт был в текущих сутках
			{
				return (ttHours + ":" + ttMinutes + ":" + ttSeconds).toString();
			}
			else
			{
				return (ttDate + "-" + ttMonth + "-" + fullToYear(ttFullYear)).toString();
			}

		}
	}
	
	function readCoockies()
	{
		// выставим чекбоксы объектов
		if ($.cookie("gh_"+userid+"_autozoom") != null && $.cookie("gh_"+userid+"_autozoom") == '0')
			$('#autozoom').attr('checked', false);	
		else
			$('#autozoom').attr('checked', true);	

		if ($.cookie("gh_"+userid+"_hide") != null && $.cookie("gh_"+userid+"_hide") == '1')
			$('#hideunchecked').attr('checked', true);	
		else
			$('#hideunchecked').attr('checked', false);	

//		if ($.cookie("gh_"+userid+"_objlist") != null)
//		{
//			var objarr = $.cookie("gh_"+userid+"_objlist").split(","); 
//			for(var key in objarr) 
//				$('#unitsReports_grid input:checkbox:enabled[id="' + objarr[key] + '"]').attr('checked', 'yes');
//		}
//		if ($.cookie("gh_"+userid+"_replist") != null)
//		{
//			var reparr = $.cookie("gh_"+userid+"_replist").split(","); 
//			for(var key in reparr) 
//				$('#reports_grid input:checkbox:enabled[id="' + reparr[key] + '"]').attr('checked', 'yes');
//		}
	}

	function loadingOn()
	{
		$("#loadingDiv").show();
	}

	function loadingOff()
	{
		$("#loadingDiv").hide();
	}