// Отмечаем группу чекбоксов
function checkParent(chcb) {
	var form = document.getElementById("formId");
	var el, id;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != "mstations") continue;
		id = el.id.substring(el.id.indexOf("_") + 1, el.id.length);
		if (id != chcb.id) continue;
		el.checked = chcb.checked;
	}
}

function checkParent2(chcb, name_field) {
	var form = document.getElementById("formId");
	var el, id;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != name_field) continue;
		id = el.id.substring(el.id.indexOf("_") + 1, el.id.length);
		if (id != chcb.id) continue;
		el.checked = chcb.checked;
	}
}

var DOM = (typeof(document.getElementById) != 'undefined');
function CheckedOnLoad() {
	if (DOM) {
		var thisCheckBoxes = document.getElementsByTagName('input');
		for (var i = 1; i < thisCheckBoxes.length; i++) {
			var chb = thisCheckBoxes[i];
			if (chb.name == 'id'){
				if (chb.checked) {
					chb.disabled = false;
					Colorize(document.getElementById(cb.id.replace('chb','str')), cb);
				}
			}
		}
	}
}

// меняем класс строки
function Colorize(Element, CHBElement) {
	if (Element && CHBElement) {
		var oldClassName = Element.className;
		Element.className = (CHBElement.checked ? 'selectStr' : 'noSelect');
		if (oldClassName.indexOf("noread")!=-1) Element.className = Element.className + ' noread';
	}
}

// чекаем по клику на строку
function CheckTR(Element,pageName,pageType,isFav) {
	if (DOM) {
		thisCheckbox = document.getElementById(Element.id.replace('str','chb'));
	//	thisCheckbox.checked = !thisCheckbox.checked;
		Colorize(Element, thisCheckbox);
	}
	var all_chB=0;var ch_chB=0;
	var i=0;
	var form=document.getElementById("MainId");
	for (i=0;i<form.elements.length;i++) {
		if((form.elements[i].checked==true)&&(form.elements[i].name=="id")) {ch_chB=ch_chB+1;}
		if(form.elements[i].name=="id") {all_chB=all_chB+1;}
	}
	if (ch_chB!=all_chB) form.mainCheck.checked = false;
	else form.mainCheck.checked = true;
	if (typeof isFav == "undefined") {
		saveInCookie(pageName, pageType, thisCheckbox);
	}
}

// чекаем один бокс
function CheckCB(Element,pageName,pageType) {
	// if (DOM) if (document.getElementById(Element.id.replace('chb','str'))) Element.checked = !Element.checked;
	if (DOM) if (document.getElementById(Element.id.replace('chb','str'))) CheckTR(document.getElementById(Element.id.replace('chb','str'),pageName,pageType));
	saveInCookie(pageName,pageType, Element);
}

// чекаем один бокс
function CheckCB2(Element,pageName,pageType) {
	// if (DOM) if (document.getElementById(Element.id.replace('chb','str'))) Element.checked = !Element.checked;
	if (DOM) if (document.getElementById(Element.id.replace('chb','str'))) 			CheckTR(document.getElementById(Element.id.replace('chb','str')),pageName,pageType,1);
}

// чекаем весь список результатов
function CheckAll(Element,Name,pageName,pageType,isFav) {
	if (DOM) {
		thisCheckBoxes = Element.parentNode.parentNode.parentNode.getElementsByTagName('input');
	for (i = 1; i < thisCheckBoxes.length; i++) {
		if (thisCheckBoxes[i].name == Name) {
			thisCheckBoxes[i].checked = Element.checked;
			Colorize(document.getElementById(thisCheckBoxes[i].id.replace('chb','str')), thisCheckBoxes[i]);
		}
	}
	if (typeof isFav == "undefined") traceAllChcb(pageName,pageType);
	}
}

// Обработка всей формы чекбоксов (для функции CheckAll)
function traceAllChcb(name, abbr) {
	var form = gebi("MainId");
	var el;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != "id") continue;
		saveInCookie(name, abbr, el);
	}
}
// Сохранение клика по чекбоксу в куки
function saveInCookie(name, abbr, chcb) {
	try {
		// Получим чекбокс
		if (typeof chcb.id == "undefined") return;
		var id = chcb.id.substring(3, chcb.id.length);
		reWriteCookie(name, abbr, id, chcb.checked);
	} catch(e) {
		// DEBUG alert('saveInCookie error');
	}
}
// Перезаписывание куки
function reWriteCookie(name, abbr, id, flag) {
	// Префикс
	var prefix = "realty_";
	// Получим и распарсим куки
	var cook, splitCook, curVar = abbr + id, exist = false;
	if (!(cook = getCookie(prefix + name))) splitCook = [];
	else splitCook = cook.split(",");
	// Сравним есть ли выбранная настройка в куках и удалим при необходимости

	curFavCount = 0;
		for (var i = 0; i < splitCook.length; i++) {
		if (splitCook[i].indexOf(abbr) == -1) continue;
		curFavCount++;
	}

//	curFavCount = splitCook.length;
	for (var i = 0; i < splitCook.length; i++) {
		if (curVar == splitCook[i]) {
			if (!flag) {
				splitCook[i] = false;
				curFavCount--;
			}
			exist = true;
			break;
		}
	}
	curFavCount += exist ? 0 : (flag ? 1 : 0);
	changeFavCount();
	setCookieTimestamp();
	// Запишем новую строку с куками
	var newcook = "";
	for (i = 0; i < splitCook.length; i++) {
		if (!splitCook[i]) continue;
		newcook += splitCook[i] + ",";
	}
	newcook = newcook.substring(0, newcook.length - 1)
	newcook = exist ? newcook : (newcook ? (flag ? newcook + "," + curVar : newcook) : curVar);
	setCookie(prefix + name, newcook);
	Count_curFavCountAll();
}

function defaultParseCookie(name, abbr) {
	try {
		var cook, id;
		var prefix = "realty_";
		var checkCount = 0;
		if (cook = getCookie(prefix + name)) {
			cook = cook.split(",");
			for (var i = 0; i < cook.length; i++) {
				if (cook[i].indexOf(abbr) == -1) continue;
				id = cook[i].substring(abbr.length, cook[i].length);
			try {
				gebi("chb" + id).checked = 1;
				gebi("str" + id).className = "selectStr";
			} 
			catch(e1) {}
				curFavCount++;
			}
		}
		changeFavCount();
	} catch(e) {
		// DEBUG alert('defaultParseCookie error');
	}
}

var curFavCount = 0;
function changeFavCount() {
	try {
		if (gebi("favCountTopId")) gebi("favCountTopId").firstChild.nodeValue = curFavCount;
		if (gebi("favCountBotId")) gebi("favCountBotId").firstChild.nodeValue = curFavCount;
	} catch(e) {}
}

// Формируем query_string для рапечатки списка
function printFromForm(formId, chcbName, name, abbr) {
	// Проверка на наличие
	if (
		typeof formId == "undefined" ||
		typeof chcbName == "undefined" ||
		typeof name == "undefined" ||
		typeof abbr == "undefined"
	) return false;
	// Начинаем формировать query_string
	var queryString = "/print/favorites/" + abbr + "/";
	// Обработка формы
	var form = gebi(formId), el;
	var empty = true;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != chcbName) continue;
		if (el.checked) {
			queryString += (empty ? "?" : "&") + "id=" + el.value;
			empty = false;
		}
	}
	if (empty) alert ("Вы не выбрали ни одного объекта для печати");
	else window.open(
		queryString,
		"print",
    		""
	);
	return false;
}
// Формируем query_string для рапечатки списка
function printFromForm1(formId, chcbName, name, abbr, addr) {
	// Проверка на наличие
	if (
		typeof formId == "undefined" ||
		typeof chcbName == "undefined" ||
		typeof name == "undefined" ||
		typeof abbr == "undefined"
	) return false;
	// Начинаем формировать query_string
	var queryString = addr + "/print/favorites/" + abbr + "/";
	// Обработка формы
	var form = gebi(formId), el;
	var empty = true;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != chcbName) continue;
		if (el.checked) {
			queryString += (empty ? "?" : "&") + "id=" + el.value;
			empty = false;
		}
	}
	if (empty) alert ("Вы не выбрали ни одного объекта для печати");
	else window.open(
		queryString,
		"print",
    		""
	);
	return false;
}



function deleteFromForm(formId, chcbName, name, abbr) {
	// Проверка на наличие
	if (
		typeof formId == "undefined" ||
		typeof chcbName == "undefined" ||
		typeof name == "undefined" ||
		typeof abbr == "undefined"
	) return false;
	// Обработка формы
	var form = gebi(formId), el;
	var empty = true;
	var node, removeNodeArray = [];
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		if (el.nodeName.toLowerCase() != "input") continue;
		if (el.type.toLowerCase() != "checkbox") continue;
		if (el.name != chcbName) continue;
		if (el.checked) {
			node = el;
			try {
				// Добираемся до строки таблицы <tr>
				while(node.nodeName.toLowerCase() != "tr") node = node.parentNode;
				// Запоминаем строки для удаления
				removeNodeArray.push(node);
			} catch(e){}
			// Удаляем запись из куки
			reWriteCookie(name, abbr, el.value, false);
			empty = false;
		}
	}
	if (removeNodeArray.length > 0) {
		for (i = 0; i < removeNodeArray.length; i++) {
			node = removeNodeArray[i];
			// Удаляем её
			node.parentNode.removeChild(node);
		}
	}
	if (empty) alert ("Вы не выбрали ни одного объекта для удаления");
	return false;
}

function setCookieTimestamp() {
	var curTime = new Date();
	curTime = curTime.getFullYear() + "-" +
		(parseInt(curTime.getMonth()) < 10 ? "0" + parseInt(curTime.getMonth()) : curTime.getMonth()) + "-" +
		(parseInt(curTime.getDay()) < 10 ? "0" + parseInt(curTime.getDay()) : curTime.getDay()) + " " +
		(parseInt(curTime.getHours()) < 10 ? "0" + parseInt(curTime.getHours()) : curTime.getHours()) + ":" +
		(parseInt(curTime.getMinutes()) < 10 ? "0" + parseInt(curTime.getMinutes()) : curTime.getMinutes())
	;
	var cook;
	if (cook = getCookie("lasttime")) {
		cook = cook.split(";");
		if (cook.length < 2) setCookie("lasttime", curTime + ";0");
		else setCookie("lasttime", curTime + ";" + (cook[1] ? 1 : 0));
	} else setCookie("lasttime", curTime + ";0");
}  

//подсчет кол-ва объектов в куки
function Count_curFavCountAll() {

	var curFavCountAll = 0;
	var cook, splitCook;
	if (!(cook = getCookie("realty_sale"))) splitCook = [];
	else splitCook = cook.split(",");
	curFavCountAll = curFavCountAll + splitCook.length;

	if (!(cook = getCookie("realty_rent"))) splitCook = [];
	else splitCook = cook.split(",");
	curFavCountAll = curFavCountAll + splitCook.length;

	try {
		if (gebi("favCountIdAll")) gebi("favCountIdAll").firstChild.nodeValue = curFavCountAll;
		if (gebi("favCountIdAllVis")){
			if (curFavCountAll == 0)
				gebi("favCountIdAllVis").style.display = "none";
			else
				gebi("favCountIdAllVis").style.display = "";
		}
	} catch(e) {}
} 
