// tags map
//1//Файл с общими для всех функциями


function init(a, t) { //функция инициализации всех данных полученных от сервера в самом начале
	_tmp['response'] = a;
	if (isError(a)) {
		jAlert(isError(a))
		return false;
	}

	if (_u == null) {
		_u = new User(a.Response.user);
	}

	// показываем меню заказов	
	if (_u.has_couriers == "1") {
		$('#courier').css('display', 'block');
	}

	if (a.Response.messages) initHistory(a.Response.messages);

	if (t == "otchet") {
		if (a.Response.objects) if (typeof a.Response.objects.object.object_id == "undefined") for (var key in a.Response.objects.object)
		_o[a.Response.objects.object[key].object_id] = new ObjLite(a.Response.objects.object[key]);
		else _o[a.Response.objects.object.object_id] = new ObjLite(a.Response.objects.object);
		colorBalanse(1);
	}
	if (t == "cams") {
		if (a.Response.cameras) initCams(a.Response.cameras);
		colorBalanse(0);
	}
	if (t == "map") {
		if (a.Response.groups) initGroups(a.Response.groups);
		if (a.Response.objects) initObjects(a.Response.objects);
		if (a.Response.events) initRules(a.Response.events)
		colorBalanse(1);

	}

	if (_mu.length > 0) _w.pagerShow();

	if (_u.isDemo) { //ограничения для демо
		$("#settings .dark-button").click(function() {
			jAlert("Извините, вы не можете сохранять настройки в демо режиме.", "Ограничения");
			return false;
		});
	}
	else {
		$("#settings .dark-button").removeClass("dark-button").addClass("orange-button");
	}

	insertUserDataOnTop();
	return true;
}
function getNormalBalanse(q){
	return (1*q).toFixed(2);
}
function changeLang(bb) {
	setCookie("lang", bb);
	jConfirm("<?= _('Для смены языка интерфейса необходимо обновить страницу, сделать это сейчас?'); ?>", "<?= _('Предупреждение'); ?>", function(a) {
		if (a) {
			window.location.reload(true);
		}
	})
	return false
}

function colorBalanse(f) {
	var t = (f ? _o : _cam);
	var i = 0;
	for (var j in _o)
	i++;
	if (1 * _u.balanse < 100 * i) $("#user_balanse").css('color', "#CA7777");
	else $("#user_balanse").css('color', "#000000");
	return false;
}

function removePack(id, element) {
	jConfirm("Вы действительно хотите удалить это фото?", "Подтверждение", function(a) {
		if (a) {

			$.post("/api/index.php?action=deletephoto&handler=cameras", {
				pack_id: id
			}, function(a) {
				if (isError(a)) {
					jAlert(_l['errors'][isError(a)] || isError(a));
				}
				else {
					jAlert("Фото успешно удалено!");
					$(element).parent().remove();

				}
			}, "json");

		}
	})

	return false
}

function insertUserDataOnTop() {
var user_i=_u || userInfo;
user_i.fio= user_i.fio || (user_i.jur_name || (user_i.first_name + " " + user_i.last_name));

	$("#user_name").html(user_i.fio);
	$("#user_id").html("ID: " + (user_i.id || user_i.user_id));
	$("#credits_info").show();
	$("#credits_info p").show();

	$("#user_balanse").html((user_i.balanse ||  getNormalBalanse(user_i.balance)) + " " + valuta);
	if (user_i.credits > 0) $("#user_credits").html(getNormalBalanse(user_i.credits)+ " " + valuta);
	else $("#user_credits").parent().hide();
	return false
}

function initCams(a) { //инициализируют камеры
	if (typeof a.camera.camera_id == "undefined") for (var key in a.camera)
	_cam[a.camera[key].camera_id] = new Camera(a.camera[key]);
	else _cam[a.camera.camera_id] = new Camera(a.camera);
	return false;
}

function initHistory(a) { //инициализируют события
	if (typeof a.history.history_id == "undefined") for (var key in a.history)
	_a[a.history[key].event_id] = new Message(a.history[key]);
	else _a[a.history.event_id] = new Message(a.history);
	return false;
}

function initObjects(a) { //инициализируют объекты
	if (typeof a.object.object_id == "undefined") for (var key in a.object)
	_o[a.object[key].object_id] = new Obj(a.object[key]);
	else _o[a.object.object_id] = new Obj(a.object);
}

function initGroups(a) { //инициализируют группы
	if (typeof a.group.group_id == "undefined") for (var key in a.group)
	_g[a.group[key].group_id] = new Group(a.group[key]);
	else _g[a.group.group_id] = new Group(a.group);
}

function initRules(a) { //инициализируют правила
	if (typeof a.event.event_id == "undefined") for (var key in a.event)
	_a[a.event[key].event_id] = new Fact(a.event[key]);
	else _a[a.event.event_id] = new Fact(a.event);
}

function isError(a) { //возвращает описание ошибки если произошла ошибка иначе тру
	if (a.Response.status.___attributes.id == "error") {
		return a.Response.status.___attributes.description;
	}
	return false;
}

function getCookie(name) { //cookie return
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) end = cookie.length;
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return (setStr);
}

function setCookie(name, value, expires, path, domain, secure) { //insert cookie
	document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function getNormalTime(t, f) { //Возвращает нормальную дату из datestamp'a (2009-09-16 10:14:57)
	if (f) return t.substr(8, 2) + "/" + t.substr(5, 2) + "/" + t.substr(0, 4) + "&nbsp;в&nbsp;" + t.substr(11, 5);
	return t.substr(8, 2) + "/" + t.substr(5, 2) + "/" + t.substr(0, 4);
}

function logout() { // снимает кукисы и перенаправляет на страницу авторизации
	//setCookie("PHPSESSID", "", "-1", "/");
	setCookie("hash", "", "-1", "/");
	window.location.href = "/";
	return false;
}

function recoveryPassword() {
	_w.auth.hide();
	_w.recovery.show();
	return false;
}

function registration() {
	_w.auth.hide();
	_w.registration.show();
	return false;
}

function register() {

	return false;
}

function readAllMessage() {
	$.get("/api/index.php?action=removeAll&handler=alerts", {
		"history_id": "0"
	});
	for (var i in _mu)
	delete _mu[i];
	_w.pager.hide();
	return false;
}

function getTimeForMap(o) {
	var day = (o.getDate() < 10) ? "0" + o.getDate() : o.getDate();
	var month = ((1 + o.getMonth()) < 10) ? "0" + (1 + o.getMonth()) : (1 + o.getMonth());
	var hours = (o.getHours() < 10) ? "0" + o.getHours() : o.getHours();
	var mins = (o.getMinutes() < 10) ? "0" + o.getMinutes() : o.getMinutes();
	return day + "/" + month + "/" + o.getFullYear() + " " + hours + ":" + mins;
}

function selectModel(a) {
	$("#objectCode").removeAttr("disabled");
	$("#objectNewImei").removeAttr("disabled");
	$("#objectNewImei2").removeAttr("disabled");
	$("#anotationNewObject").show();

	switch (a) {
	case "winMobile":
		$("#objectCode").attr("disabled", "disabled");
		$("#anotationNewObject").hide();
		break;
	case "bt-cd110m":
		$("#objectNewImei").attr("disabled", "disabled");
		$("#objectNewImei2").attr("disabled", "disabled");
		$("#objectCode").attr("disabled", "disabled");
		$("#anotationNewObject").hide();
		break;
	default:
		break;
	}
	return false;
}

function showAddress(response) {
	if (!response || response.Status.code != 200) {
		return ("Status Code:" + response.Status.code);

		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml('<b>Address:</b>');
	}
}

function getShortAdress(p) {
	return p.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
}

function postAjaxCheck(a, xml, show) {
	xml = xml ? xml : false; //по умолчанию не XML
	show = show ? show : true; //по умолчанию показывать сообщение
	if (!xml) {
		if (a.Response.status.___attributes.id == "error") {
			if (show) switch (a.Response.status.___attributes.number) {
			case 666:
				jAlert(_l['errors']['ini'], _l['errors']['0'], logout());
				break;
			default:
				jAlert((typeof _l['errors'][isError(a)] != "undefined") ? _l['errors'][isError(a)] : isError(a), _l['errors']['0']);
			}
			return false;
		}
		else return true;
	}
	else {
		if (a.Response.status.id == "error") {
			if (show) {
				switch (a.Response.status.number) {
				case 666:
					//jAlert(_l['errors']['ini'], _l['errors']['0'], logout());
					break;
				default:
					jAlert((typeof _l['errors'][a.Response.status.description] != "undefined") ? _l['errors'][a.Response.status.description] : a.Response.status.description, _l['errors']['0']);
				}
			}
			return false;
		}
		else return true;
	}

	return true;
}

function getNormalTimeWithMonth(a) {
	var m = {
		"01": "Января",
		"02": "Февраля",
		"03": "Марта",
		"04": "Апреля",
		"05": "Мая",
		"06": "Июня",
		"07": "Июля",
		"08": "Августа",
		"09": "Сентября",
		"10": "Октября",
		"11": "Ноября",
		"12": "Декабря"
	};
	return a.substr(8, 2) + " " + m[a.substr(5, 2)];
}

function getNormalNumZapis(a) {
	//return a.toFixed(2);
	a = Math.round(a * 10) / 10;
	return a + (("" + a).indexOf(".") >= 0 ? "" : ".0");
}

function xex() {
	$("#mapZoomer").css("top", (32 + 102 - 6 * map.getZoom()) + "px");
}

function letsShowAdress(a, x, y) {
	var geocoder = new GClientGeocoder();
	geocoder.getLocations(new GLatLng(x, y), function() {
		$("#" + a).text();
	});
	return false;
}

function changePasswordInSettings() {
	_w.settings.hide();
	_w.changePassword.show();
	$("#changePasswordForm").resetForm();

	$("#changePasswordLogin").val(_u.login);
	$("#changePasswordPHPSESSID").val(_u.user_hash);

	$("#changePasswordForm").validate({
		submitHandler: function(form) {
			$.postJSON("/api/index.php?action=changepassword&handler=users", $(form).formSerialize(), function(a) {
				if (isError(a)) jAlert((typeof _l['errors'][isError(a)] != "undefined") ? _l['errors'][isError(a)] : isError(a), _l['errors']['0']);
				else {
					jAlert("Пароль сменен");
					_w.settings.show();
					_w.changePassword.hide();
				}
				return false;
			});
		}
	});
	return false;
}

function rgb2rgb(color) {
	//rgb(1, 2, 256) -> 0102ff
	color = color.replace(/\s/g, "");
	var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);
	if (aRGB) {
		color = '';
		for (var i = 1; i <= 3; i++) color += Math.round((aRGB[i][aRGB[i].length - 1] == "%" ? 2.55 : 1) * parseInt(aRGB[i])).toString(16).replace(/^(.)$/, '0$1');
	}
	else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');
	return color;
}

function padStringLeft(str, chr, len) {
	str = new String(str);
	chr = new String(chr);
	while (str.length < len)
	str = chr.concat(str);
	return str;
}

function padStringRight(str, chr, len) {
	str = new String(str);
	while (str.length < len)
	str = str.concat(chr);
	return str;
}

Date.prototype.formatDefinition = {
	// day
	'd': ['\\d{2}', function(val) {
		this._day = parseInt(val);
	}, function() {
		return padStringLeft(this.getDate(), '0', 2);
	}],
	// month
	'm': ['\\d{2}', function(val) {
		this.setMonth(parseInt(val) - 1);
	}, function() {
		return padStringLeft(this.getMonth() + 1, '0', 2);
	}],
	// year
	'Y': ['\\d{4}', function(val) {
		this.setFullYear(parseInt(val));
	}, function() {
		return padStringLeft(this.getFullYear(), '0', 4);
	}],
	// hours
	'H': ['\\d{2}', function(val) {
		this.setHours(val);
	}, function() {
		return padStringLeft(this.getHours(), '0', 2);
	}],
	// minutes
	'i': ['\\d{2}', function(val) {
		this.setMinutes(val);
	}, function() {
		return padStringLeft(this.getMinutes(), '0', 2);
	}],
	// seconds
	's': ['\\d{2}', function(val) {
		this.setSeconds(val);
	}, function() {
		return padStringLeft(this.getSeconds(), '0', 2);
	}],
	// escaping RegExp special characters
	'?': '\\?',
	'*': '\\*',
	'(': '\\(',
	')': '\\)',
	'[': '\\[',
	']': '\\]',
	'\\': '\\\\',
	'.': '\\.',
	'^': '\\^',
	'$': '\\$',
	'|': '\\|',
	'+': '\\+'
};

Date.fromString = Date.prototype.fromString = function(format, source) {
	var that = (this instanceof Date) ? this : new Date();
	var match = [];
	var replace = that.formatDefinition;
	format = '^' + format.replace(/./gi, function(letter) {
		if (typeof replace[letter] != 'undefined') {
			var m = replace[letter];
			if (m instanceof Array) {
				match.push(m[1]);
				return '(' + m[0] + ')';
			}
			else return m;
		}
		return letter;
	}) + '$';
	format = new RegExp(format);
	var info = format.exec(source);
	if (info) for (var i = 0; i < match.length; ++i) {
		var val = (new String(info[i + 1])).replace(/^0+/, '');
		match[i].call(that, val);
	}
	that.setDate(that._day);
	delete that._day;
	return that;
};

Date.prototype.before = function(sec) {
	var res = new Date();
	res.setTime(this.getTime() - sec * 1000);
	return res;
};

Date.prototype.after = function(sec) {
	var res = new Date();
	res.setTime(this.getTime() + sec * 1000);
	return res;
};

Date.prototype.format = function(format) {
	var replace = this.formatDefinition;
	var that = this;
	var res = format.replace(/./gi, function(letter) {
		if (typeof replace[letter] != 'undefined') {
			var m = replace[letter];
			if (m instanceof Array) {
				return m[2].call(that);
			}
		}
		return letter;
	});
	return res;
};

var phoneDenyCodes = {
	'81#0': true,
	'87#0': true,
	'69#0': true,
	'82#0': true,
	'84#0': true,
	'89#0': true,
	'85#0': true,
	'73#0': true,
	'79#0': true,
	'80#0': true,
	'219#0': true,
	'221#0': true,
	'220#0': true,
	'65#0': true,
	'83#0': true,
	'68#0': true,
	'70#0': true,
	'71#0': true,
	'72#0': true,
	'74#0': true,
	'75#0': true,
	'76#0': true,
	'59#0': true,
	'222#0': true,
	'90#0': true,
	'88#0': true,
	'67#0': true,
	'86#0': true,
	'66#0': true,
	'78#0': true,
	'77#0': true,
	'188#0': true,
	'190#0': true,
	'191#0': true,
	'192#0': true,
	'111#0': true,
	'106#0': true,
	'109#0': true,
	'107#0': true,
	'110#0': true,
	'61#0': true,
	'16#0': true,
	'57#1': true,
	'48#1': true,
	'49#1': true,
	'50#1': true,
	'51#1': true,
	'52#1': true,
	'53#1': true,
	'54#1': true,
	'55#1': true,
	'56#1': true,
	'32#0': true,
	'109#1': true,
	'61#1': true
};

PhoneValidator = function(node) {
	node = $(node);
	var lastValid = '+7';
	var isDenyCode = function(e) {
			if (typeof e.ctrlKey != 'undefined' && e.ctrlKey) return false;
			if (typeof e.metaKey != 'undefined' && e.metaKey) return false;
			if (typeof e.altKey != 'undefined' && e.altKey) return false;
			var key = e.keyCode;
			if (typeof e.shiftKey == 'undefined') key += '#0';
			else key += '#' + (e.shiftKey ? '1' : '0');
			return (typeof phoneDenyCodes[key] != 'undefined');
		};
	node.focus(function() {
		if (/^\+\d{0,14}$/.test(this.value)) lastValid = this.value;
		else lastValid = '+7';
	}).keydown(function(e) {
		if (isDenyCode(e)) return false;
		var c = String.fromCharCode(e.keyCode);
		if (/^\+\d{0,14}$/.test(this.value)) lastValid = this.value;
	}).keypress(function() {
		if (/^\+\d{0,14}$/.test(this.value)) lastValid = this.value;
	}).keyup(function() {
		if (!/^\+\d{0,14}$/.test(this.value)) {
			if (!this.value.length) {
				lastValid = this.value = '+7';
				return false;
			}
			this.value = lastValid;
			return false;
		}
	}).change(function() {
		if (/^\+\d{0,14}$/.test(this.value)) lastValid = this.value;
		else if (!this.value.length) lastValid = this.value = '+7';
		else this.value = lastValid;
	});
};

PhoneValidator.init = function(selector) {
	if (!(selector instanceof jQuery)) selector = jQuery(selector);
	selector.each(function() {
		new PhoneValidator(this);
	});
};

$(function() {
	PhoneValidator.init('input.PhoneField');
});
