//*****************************************
var replace_menu = false;
var timeOut = "";
selectedTRclr = "#000";
//*****************************
function checkHours(input)
{
	if (!input.value)
		return;
	var value = parseInt(input.value);
	if ( (value < 0) || (value > 23) || (isNaN(value)) )
		input.value = "";
	else
		if ( (input.value.length == 2) && (input.value.charAt(0) == '0') && (parseInt(input.value.charAt(1)) >= 0) && (parseInt(input.value.charAt(1)) <= 23) )
			return;
		else
			input.value = value;
}
//*****************************
function checkMins(input)
{
	if (!input.value)
		return;
	var value = parseInt(input.value);
	if ( (value < 0) || (value > 59) || (isNaN(value)) )
		input.value = "";
	else
		if ( (input.value.length == 2) && (input.value.charAt(0) == '0') && (parseInt(input.value.charAt(1)) >= 0) && (parseInt(input.value.charAt(1)) <= 59) )
			return;
		else
			input.value = value;
}
//*****************************
function checkTR(tr)
{
	if (tr)
	{
		var TRs = tr.parentNode.children;
		for (var i = 1; i < TRs.length; i++)
		{
			TRs[i].className = "";
			TRs[i].style.backgroundColor = (TRs[i] == tr) ? selectedTRclr : "";
		}
	}
}
//*****************************************
function checkNeeded(form)
{
	for (var i = 0; i < form.length; i++)
	{
		if ( (form[i].type != 'button') && (form[i].type != 'submit') )
		{
			if (form[i].alt && !form[i].value)
			{
				drawErrorStatus(form[i], false, "Неободимо заполнить это поле");
				return false;
			}
		}
	}
	return true;
}
function visual_img(_targ, _opened_img, _closed_img, _imgID)
{
	if (!_imgID)
		_imgID = _targ + "_img";
	var target = document.getElementById(_targ);
	var img = document.getElementById(_imgID);
	if (target)
	{
		if (target.style.display == "none")
		{
			target.style.display = "";
			if (img)
				img.src = _opened_img;
			if (!startHash || startHash == 0)
				location.hash = '#id=' + _targ.match(/\d+/);
		}
		else
		{
			target.style.display = "none";
			if (img)
				img.src = _closed_img;
			location.hash = '';
		}
	}
}
//*************************************
//******************************************
function visual_tree(_targ, _show)
{
	if (!_show)
		_show = "auto";
	var target = document.getElementById(_targ);
	if (target)
	{
		if (_show == "auto")
		{
			if (target.style.display == "none")
			{
				target.style.display = "";
				location.hash = '#id=' + _targ.match(/\d+/);
			}
			else
			{
				target.style.display = "none";
				location.hash = '';
			}
		}
		else
		{
			target.style.display = _show;					
		}
	}					
}
//*************************************
function ajax(url, data, onload)
{
	var result;
	var req = window.XMLHttpRequest?
	new XMLHttpRequest() :
	new ActiveXObject("Microsoft.XMLHTTP");
	if (!req) 
		return false
	req.onreadystatechange = function () 
	{
		if (req.readyState == 4)
		{
			 onload(eval('(' + req.responseText + ')'));
		}
	}
	req.open("POST", url, true);
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset='+document.charset);
	req.send(data);
	return true;
}
//*****************************
function add_form_group(list, new_form_group, btn)
{
	if (!new_form_group)
		return;
	btn.disable = true;
	ajax("/admin/ajax_functions.php", "function=add_form_group&form_group_name=" + new_form_group.value, 
			function(result)
			{
				if (result['debug'])					
					alert(result['debug']);
				if (result['repeat'])
					list.selectedIndex = getIndex(list, result['id'])
				else
					list.add(new Option(new_form_group.value, result['id'], true, true));
				new_form_group.value = "";
				btn.disabled = false;
			}
		);
}
//*****************************
function getIndex(list, value)
{
	for (var i = 0; i < list.length; i++)
		if (list[i].value == value)
			return i;
	return false;
}
var editor_content;
//*****************************
function putAjaxTextInWin(str)
{
	ajax("/ajax_functions.php", str, 
			function(result)
			{
				windows.test_win.setDefaultSize(); 
					
				var myScreen = getElem('screen');
				windows.test_win.setContent(result['text']);
				if (result['title'])
					windows.test_win.setTitle(result['title']);
				if (result['width'])
					windows.test_win.setWidth(result['width']);
				if (result['height'])
					windows.test_win.setHeight(myScreen.offsetHeight - 30);
				
				windows.test_win.show();
				windows.test_win.setPos(myScreen.offsetWidth/2 - windows.test_win.container.offsetWidth/2, 10); 
				if (!result['script'] || result['script'] == 0)
				{
					CKEDITOR.replace('content',
					{
						toolbar : 'Full',
						uiColor : '#9AB8F3'
					});
				}
				else
				{
					editor_content = CodeMirror.fromTextArea(getElem('content'), 
						{
							lineNumbers: true,
							matchBrackets: true,
							enterMode: 'keep',
							tabMode: 'shift',
							mode: 'application/x-httpd-php',
							theme: 'night',
							onKeyEvent: function(i, e) 
							{
							  // Hook into ctrl-space
								if (e.keyCode == 32 && (e.ctrlKey || e.metaKey) && !e.altKey) 
								{
									e.stop();
									return startComplete(editor_content);
								}
								if ((e.keyCode == 122 || e.keyCode == 27) && e.type == 'keydown') 
								{
									e.stop();
									return toggleFullscreenEditing(editor_content);
								}
							}
							,onBlur: function(i, e) 
							{				
								editor_content.save();
							}		
						});	
					editor_content.getWrapperElement().style.height = '500px';
				}
			}
		)
}
//*****************************
function getAjaxText(str, parent)
{
	var container;
	if (container = document.getElementById(parent + '_container'))
	{
		container.innerHTML = "Loading...";
		ajax("/ajax_functions.php", str, 
				function(result)
				{
					container.innerHTML = result['text'];
				}
			);
	}
}
//*****************************
function AjaxFunc(str, errID, showWin)
{
	ajax("/ajax_functions.php", str, 
			function(result)
			{
				var err;				
				windows.test_win.setDefaultSize(); 
				if (result['success']) // если успех
				{
					windows.test_win.setContent(result['text']); //выводим текст об успехе
					setTimeout('window.location.reload()', 1500); //обновляем страничку
				}
				else
				{
					if (err = document.getElementById(errID)) // если есть элемент, куда выводить ошибки
					{
						if (result['title'])
							windows.test_win.setTitle(result['title']);
						if (result['width'])
							windows.test_win.setWidth(result['width']);
						if (result['height'])
							windows.test_win.setHeight(result['height']);
						err.innerHTML = result['text'] + result['error'];
						document.getElementById('btn').disabled = false;
					}
					else
						windows.test_win.setContent(result['text'] + result['error']); //иначе пишем их прямо в окно
				}
				if (showWin) //и если нужно, открываем окно - нужно подумать, где открывать
					windows.test_win.show();
			}
		)
}
//*****************************
function edit_menu(type, catID, parent, errID)
{
	var str = "";
	switch (type)
	{
		case "form_category":
		{
			putAjaxTextInWin("function=" + type + "&parent=" + catID, parent, errID);
			break;
		}
		case "form_category_edit":
		{
			putAjaxTextInWin("function=" + type + "&id=" + catID, parent, errID);
			break;
		}
		case "form_page":
		{
			putAjaxTextInWin("function=" + type + "&parent=" + catID, parent, errID);
			break;
		}
		case "form_page_edit":
		{
			putAjaxTextInWin("function=" + type + "&id=" + catID, parent, errID);
			break;
		}
		case "form_page_restore":
		{
			putAjaxTextInWin("function=" + type + "&id=" + catID + "&restore=1", parent, errID);
			break;
		}
	}	
}
//*****************************
var debug_str = "";
var replacement_color = "";
var replacement_id = "";
function class_rename(parent, search, replace)
{
	var children = 	parent.children;
	for (var i = 0; i < children.length; i++)
	{
		if (children[i].tagName == "TD")
		{
			if (children[i].className == search)
			{
				children[i].className = replace;
			}
			
		}
		class_rename(children[i], search, replace);
	}
}
//*****************************
function replace_menu_cat(id, parentID, sort)
{
	if ( (id != replacement_id) && (replace_menu) ) //если тыкаем не на ту же строчку
	{
		AjaxFunc("function=replace_category&id=" + replacement_id.match(/\d+/) + "&parent=" + parentID + "&sort=" + sort, "", true);
		return;
	}
	var target = document.getElementById(id);
	if (target)
	{		
		replace_menu = !replace_menu; 
		if (replace_menu)
		{		
			class_rename(document.getElementById("cat_menu"), "passive_replace", "active_replace"); 
			document.getElementById("cat_menu").style.cursor = "move";
			replacement_color = target.style.backgroundColor;
			target.style.backgroundColor = "#ff0000";
			replacement_id = id;
		}
		else 
		{
			class_rename(document.getElementById("cat_menu"), "active_replace", "passive_replace"); 
			document.getElementById("cat_menu").style.cursor = "auto";
			target.style.backgroundColor = replacement_color;
			replacement_color = "";			
			replacement_id = "";
		}
		
	}
}
//*******************************
function draw_button(content, clr_normal, clr_over)
{
	var over = "";
	if (clr_over)
		over = "onmouseover='this.style.backgroundColor=\"" + clr_over + "\";' onmouseout='this.style.backgroundColor=\"" + clr_normal + "\";'";
	return "<div class='calendar_btn' style='background-color: " + clr_normal + ";' " + over + "><div><div><div><div>" + content + "</div></div></div></div></div>";
}
//*******************************
var startHash = 0;
function parseHash()
{
	var requestID;
	if (location.hash)
		requestID = location.hash.substring(4, location.hash.length); 
	if (requestID)
	{
		startHash = requestID;
		visual_img('cat_' + requestID, "/img/menu/minus.gif", "/img/menu/plus.gif");
		getParents(requestID);
		startHash = 0;
	}
}
//*******************************
var debug_str = "";
function getParents(id)
{
	var parent = document.getElementById('cat_menu_' + id).parentNode.parentNode.parentNode;
	if (parent.id != "cat_menu")
	{
		var parentID = parent.id.match(/\d+/);
		visual_img('cat_' + parentID, "/img/menu/minus.gif", "/img/menu/plus.gif");
		getParents(parentID);
	}
}
//*******************************
function checkInt(input)
{
	input.value = input.value.replace(/[^\d]+/, '');
}
//********************************
function insertAfter(newElement, targetElement) 
{
	var parent = targetElement.parentNode;
 
	//if the parents lastchild is the targetElement...
	if(parent.lastchild == targetElement) 
		parent.appendChild(newElement);
	else
		parent.insertBefore(newElement, targetElement.nextSibling);
}
//*************************************
function getElementComputedStyle(elem, prop)
{
	if (typeof elem != "object") 
		elem = document.getElementById(elem);
  
	// external stylesheet for Mozilla, Opera 7+ and Safari 1.3+
	if (document.defaultView && document.defaultView.getComputedStyle)
	{
		if (prop.match(/[A-Z]/)) 
			prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
		return document.defaultView.getComputedStyle(elem, "").getPropertyValue(prop);
	}	  
	// external stylesheet for Explorer and Opera 9
	if (elem.currentStyle)
	{
		var i;
		while ((i=prop.indexOf("-"))!=-1) 
			prop = prop.substr(0, i) + prop.substr(i+1,1).toUpperCase() + prop.substr(i+2);
		return elem.currentStyle[prop];
	}	  
	return "";
}
//*************************************
function trim(txt)
{
	return txt.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
//*************************************
function innerText(node) 
{
//  return node.innerText; //хорошая вещь в ИЕ
//  return node.innerHTML; //из стадарта W3C, но не совсем то что нужно
	var ret = "";
	if (typeof(node) == "object")
	{
		for(var i = 0; i < node.childNodes.length; i++) 
		{
			switch(node.childNodes[i].nodeType) 
			{
				case 1: ret+=innerText(node.childNodes[i]); 
					break; //если элемент
				case 3: ret+=node.childNodes[i].nodeValue; //если текстовая нода
			}
		}
	}
	return ret;
}
//*************************************
function search_form(txt, table, fieldNum)
{
	fieldNum = (fieldNum) ? fieldNum : 0;
	if (table)
	{
		var td, searchStr, matchInTD;
		var total_matched = 0;
		var pattern = new RegExp('(^|\\s)' + txt + '.*', 'gi');
		var list = table.children[0].children;
		for (var i = 1; i < list.length; i++)
		{
			if (txt)
			{
				var tds = (fieldNum == "all") ? list[i].children : new Array(list[i].children[fieldNum]);
				matchInTD = 0;
				for (var cnt = 0; cnt < tds.length; cnt++)
				{
					td = tds[cnt];
					searchStr = innerText(td);
					if (searchStr.match(pattern))
						matchInTD++;
				}
				if (!matchInTD)
					list[i].style.display = "none";
				else
					list[i].style.display = "";
			}
			else
				list[i].style.display = "";
			total_matched += matchInTD;
		}
		if (txt)
		{
			var no_matches;
			if (no_matches = getElem('no_data_found'))
				no_matches.innerHTML = (total_matched > 0) ? "" : "Отсутствуют совпадения для '" + txt + "'";
		}
		table.children[0].style.display = ( (!txt) || (total_matched > 0) ) ? "" : "none";
	}
}
//*************************************
function show_engine(elem)
{
	if (elem)
	{
		var toHide = elem.parentNode.nextSibling.children[0];
		toHide.style.display = (toHide.style.display) ? "" : "none";
	}
}
//*************************************
//*********SORTING*********************
initOnLoad("tSearchResults");
function initOnLoad(sElementName) //проверяем загружен ли уже нужный нам элемент. если нет, то проверям снова
 {  
	var oElement = (sElementName == "body") ? document[sElementName] : document.getElementById(sElementName); 
	if(oElement != null && typeof(oElement) != "undefined") 
	{ 
		attachRSortEvents(); 
	} 
	else 
		setTimeout(function() { initOnLoad(sElementName); }, 0); 
} 
//**************************************
function rSort(sortTD, scrollable)
{
	scrollable = (scrollable); // таблица с фиксированным заголовком
	var startTR = (scrollable) ? 0 : 1;
	// если сортируем таблицу с фиксированным заголовком, то берем следующую таблицу за таблицей, содержащей данную ячейку
	var sourceTBody = false;
	if (scrollable)
	{
		if (sortTD.parentNode.parentNode.parentNode.nextSibling.firstChild.nodeName == "TABLE")
			sourceTBody = sortTD.parentNode.parentNode.parentNode.nextSibling.firstChild.firstChild;
		else
			return;
	}
	else
		sourceTBody = sortTD.parentNode.parentNode;
		
	if (sourceTBody.nodeName == "TBODY")
	{
		var sortType = "asc";
		if (sortTD.alt && (sortTD.alt == "asc") )
			sortType = "desc";
		var sortTDs = sortTD.parentNode.children;
		var sortTD_num = -1;
		for (var i in sortTDs)
		{
			if (sortTDs[i] == sortTD)
				sortTD_num = i;
			else
			{
				if (sortTDs[i].className && sortTDs[i].className.match(/^|\s(rSort|rSortScroll)\s|$/))
				{
					sortTDs[i].style.backgroundImage = "url(/img/icons/sort/default.gif)";
					sortTDs[i].alt = "";
				}
			}
		}
		if (sortTD_num == -1)
			return;
		sortTD.alt = sortType;
		sortTD.style.backgroundImage = "url(/img/icons/sort/" + sortType + ".gif)";
	
		var elems2Sort = new Array();
		var sourceTRs = sourceTBody.children;
		for (var i = startTR; i < sourceTRs.length; i++)
		{
			elems2Sort[i - startTR] = new Array(i, innerText(sourceTRs[i].children[sortTD_num]));
		}
		elems2Sort = elems2Sort.sort(engineSort);
		if (sortType == "desc")
			elems2Sort.reverse();
		for (var i = 0; i < elems2Sort.length; i++)
		{
			sourceTBody.insertBefore(createElement('tr'), sourceTRs[elems2Sort[i][0]]);
			sourceTBody.appendChild(sourceTRs[elems2Sort[i][0] + 1]);
			
		}
		while (sourceTRs.length > elems2Sort.length + startTR)
			sourceTBody.removeChild(sourceTRs[1]);
		
	}
	else
		alert('Unexpected node: ' + sourceTBody.nodeName);
}
//*************************************
function engineSort(a, b)
{
	if (a[1].match(/^\d+(\.|,)?\d*$/) && b[1].match(/^\d+(\.|,)?\d*$/))
		return a[1] - b[1];
	
	if (a[1] == b[1])
		return 0;
	else
		return (a[1] > b[1]) ? 1 : -1;
}
//*************************************
function attachRSortEvents()
{
	var rSortElems = getElementsByClass("rSort");
	for (var i in rSortElems)
	{
		Event.add(rSortElems[i], "click", 
			function(e) 
			{ 
				rSort(this);
			});
	}
	
	var rSortElems = getElementsByClass("rSortScroll");
	for (var i in rSortElems)
	{
		Event.add(rSortElems[i], "click", 
			function(e) 
			{ 
				rSort(this, 1);
			});
	}
}
//*************************************
function getElementsByClass(searchClass, node, tag) 
{
	var classElements = new Array();
	if ( !node )
		node = document;
	if ( !tag )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
	var j = 0;
	for (var i in els) 
	{
		
		if ( pattern.test(els[i].className) ) 
			classElements[j++] = els[i];
	}
	return classElements;
}
//*************************************
function formatInt(val) 
{
	if (val.match(/^-?\d+$/) && (Math.abs(val) > 1000) )
	{
		return formatInt(val/1000) + ' ' + (val%1000);
	}
	return val;
}

