// Variables for showLargeImage function
PositionX = 10;
PositionY = 10;
defaultWidth  = 600;
defaultHeight = 400;

var urlPath = "";
function reportError(message)
{
	var errorSpan = document.getElementById("errorSpan");
	if (errorSpan)
	{
		errorSpan.style.display = "";
		errorSpan.innerHTML = message;
}
}
function clearError()
{
	var errorSpan = document.getElementById("errorSpan");
	if (errorSpan)
	{
		errorSpan.style.display = "none";
		errorSpan.innerHTML = "";
	}
}
function validationError(message)
{
	var validation = document.getElementById("validation");
	if (validation)
		validation.innerHTML = message;
}
function startLoading()
{
   document.getElementById("loadImage").style.display = "block";
   document.getElementById("loadImage").style.left = (document.body.scrollLeft + 350) + "px";
   document.getElementById("loadImage").style.top = (document.body.scrollTop + 400) + "px";
}
function stopLoading()
{
   document.getElementById("loadImage").style.display = "none";
}
function quote_html(str)
{
   str = str.replace(/&/gi, "&amp;");
   str = str.replace(/</gi, "&lt;");
   str = str.replace(/>/gi, "&gt;");
   str = str.replace(/&amp;#/gi, "&#");
   return str;
}
function quote_htmlBr(str)
{
   return quote_html(str).replace(/\n/, "<br/>");
}
function setTemplateProperty(template, name, val)
{
    var ret = eval("template.replace(/\\#\\{" + name + "\\}/gi, val)");
    ret = eval("ret.replace(/\\#\\%7B" + name + "\\%7D/gi, val)");
    return ret;
}
function escapeEx(str)
{
	if (!str)
		return "";
	
	var ret = '';
	
	for (i=0; i<str.length; i++)
	{
		var n = str.charCodeAt(i);
		if (n >= 0x410 && n <= 0x44F)
			n -= 0x350;
		else if (n == 0x451)
			n = 0xB8;
		else if (n == 0x401)
			n = 0xA8;
		if ((n < 65 || n > 90) && (n < 97 || n > 122) && n < 256)
		{
			if (n < 16)
				ret += '%0'+n.toString(16);
			else
				ret += '%'+n.toString(16);
		}
		else
			ret += String.fromCharCode(n);
	}
	
	return ret;
}


function getChildByTagName(node, tagName)
{
    var ret;

    for (var i = 0; !ret && i < node.childNodes.length; i++)
    {
        if (node.childNodes[i].tagName && node.childNodes[i].tagName.toLowerCase() == tagName)
            ret = node.childNodes[i];
    }

    return ret;
}
function getChildById(node, id)
{
    var ret;

    for (var i = 0; !ret && i < node.childNodes.length; i++)
    {
        if (node.childNodes[i].id && node.childNodes[i].id == id)
            ret = node.childNodes[i];
    }

    return ret;
}
function getChildByClassName(node, className)
{
    var ret;

    for (var i = 0; !ret && i < node.childNodes.length; i++)
    {
        if (node.childNodes[i].className && node.childNodes[i].className == className)
            ret = node.childNodes[i];
    }

    return ret;
}


function loadCategory(node)
{
	document.location.href = urlPath + node.getAttribute("categorykey") + "/";//"articles.html?id=" + id;
}
function showClicker(td)
{
	var child = getChildByClassName(td, "clicker");
	if (child)
		child.childNodes[0].src = urlPath + "images/clicker_active2.gif";
}
function hideClicker(td)
{
	var child = getChildByClassName(td, "clicker");
	if (child)
		child.childNodes[0].src = urlPath + "images/clicker_passive2.gif";
}
function overSection(td)
{
	if (td.style.backgroundImage.indexOf("_over") == -1)
	{
		var k = td.style.backgroundImage.lastIndexOf(".");
		if (k != -1)
			td.style.backgroundImage = td.style.backgroundImage.substring(0, k) + "_over" + td.style.backgroundImage.substring(k);
	}
}
function outSection(td)
{
	if (td.style.backgroundImage.indexOf("_over") != -1)
	{
		var k1 = td.style.backgroundImage.lastIndexOf("_over");
		var k2 = td.style.backgroundImage.lastIndexOf(".");
		if (k1 != -1 && k2 != -1)
			td.style.backgroundImage = td.style.backgroundImage.substring(0, k1) + td.style.backgroundImage.substring(k2);
	}
}


function loginAction()
{
	startLoading();
	login(document.getElementById("login").value, 
				escapeEx(document.getElementById("password").value), 
				document.getElementById("remember").checked ? document.getElementById("remember").value : "", 
				loginCallback);
}
function loginCallback(result)
{
	stopLoading();
	if (result == "" || result == "R")
	{
		document.getElementById("login").value = "";
		document.getElementById("password").value = "";
		document.getElementById("loginArea").style.display = "none";
		document.getElementById("logoutArea").style.display = "";
		clearError();
		
		//need reload
		if (result == "R")
			document.location.href = document.location.href;
	}
	else
	{
		reportError(result);
	}
}
function logoutAction()
{
	startLoading();
  logout();
}
function logoutCallback(result)
{
	stopLoading();
	if (result == "")
	{
		document.getElementById("loginArea").style.display = "";
		document.getElementById("logoutArea").style.display = "none";
		var href = document.location.href;
		document.location.href = urlPath + "index.html?logout=1";
	}
	else
	{
		reportError(result);
	}
}
var preloadImages = new Array();
function pageLoad()
{
	try {
    document.execCommand( "BackgroundImageCache", false, true );
	} catch( e ) { };
	lineUp();
	
	for (var i = 0; i < preloadImages.length; i++)
	{
		var im = new Image();
		im.src = preloadImages[i];
	}
}
function lineUp()
{
	var logoArea = document.getElementById("logoArea");
	var contentContainer = document.getElementById("contentContainer");
	if (logoArea && contentContainer)
	{
		var lHeight = logoArea.offsetHeight;
		var cHeight = contentContainer.offsetHeight;
		if (lHeight < cHeight)
			logoArea.style.height = cHeight;
		else
			contentContainer.style.height = lHeight;
	}
}


function validateUserAction()
{
	startLoading();
	validateUser();
}
function validateUserCallback(result)
{
	stopLoading();
	if (result == "")
	{
		document.forms["registerForm"].submit();
	}
	else
	{
		validationError(result);
	}
}
function validateEditUserAction()
{
	startLoading();
	validateEditUser();
}
function validateEditUserCallback(result)
{
	stopLoading();
	if (result == "")
	{
		document.forms["editForm"].submit();
	}
	else
	{
		validationError(result);
	}
}
function checkEmailAction()
{
	startLoading();
	checkEmail();
}
function checkEmailCallback(result)
{
	stopLoading();
	if (!result)
	{
		document.forms["resetForm"].submit();
	}
	else
	{
		validationError("Пользователя с таким e-mail адресом не существует.");
	}
}
function addCommentAction()
{
	startLoading();
	var td = document.getElementById("message___Frame").contentWindow.document.getElementById("xEditingArea");
	var iframe = td.childNodes[0];
	var message = iframe.contentWindow.document.body.innerHTML;
	addComment(document.getElementById("articleid").value, 
							escapeEx(message), 
							escapeEx(document.getElementById("username").value), 
							document.getElementById("useremail") ? document.getElementById("useremail").value : "", 
							addCommentCallback);
}
function addCommentCallback(result)
{
	stopLoading();
	if (result.indexOf("Error") != 0)
	{
		var td = document.getElementById("message___Frame").contentWindow.document.getElementById("xEditingArea");
		var iframe = td.childNodes[0];
		var message = iframe.contentWindow.document.body.innerHTML;
		
		var data = result.split("\n");
		var createdate = data[0];
		var username = data[1];
		var useremail = data[2];
		var template = document.getElementById("commentTemplate");
		var commentNode = template.cloneNode(true);
		commentNode.style.display = "";
		commentNode.id = "";
		commentNode.innerHTML = setTemplateProperty(commentNode.innerHTML, "createdate", createdate);
		commentNode.innerHTML = setTemplateProperty(commentNode.innerHTML, "username", username);
		commentNode.innerHTML = setTemplateProperty(commentNode.innerHTML, "useremail", useremail);
		commentNode.innerHTML = setTemplateProperty(commentNode.innerHTML, "message", message);
		
		if (useremail == "")
		{
			var removeNodes = new Array();
			var spanNode = getChildByClassName(commentNode, "smalltitle");
			for (var i = 0; i < spanNode.childNodes.length; i++)
			{
				var child = spanNode.childNodes[i];
				if (child.nodeType == 3)
					continue;
				if (child.getAttribute("isemail") == "1")
					removeNodes[removeNodes.length] = child;
			}
			for (var i = 0; i < removeNodes.length; i++)
				spanNode.removeChild(removeNodes[i]);
		}
		
		template.parentNode.insertBefore(commentNode, template);
		
		if (document.getElementById("commentsTitle").style.display == "none")
			document.getElementById("commentsTitle").style.display = "";
		
		var contentContainer = document.getElementById("contentContainer");
		if (contentContainer)
			contentContainer.style.height = contentContainer.offsetHeight + commentNode.offsetHeight;
		lineUp();
	}
	else
	{
		validationError(result.substring("Error".length));
	}
}
function validateArticleAction()
{
	startLoading();
	validateArticle(escapeEx(document.forms["articleForm"]["title"].value), 
									escapeEx(document.forms["articleForm"]["key"].value), 
									escapeEx(document.forms["articleForm"]["id"].value), 
									escapeEx(document.forms["articleForm"]["description"].value), 
									escapeEx(document.forms["articleForm"]["createdate"].value), 
									validateArticleCallback);
}
function validateArticleCallback(result)
{
	stopLoading();
	if (result == "")
	{
		document.forms["articleForm"].submit();
	}
	else
	{
		validationError(result);
	}
}

var saveAction;
function doUploadImage()
{
	var f = document.forms[1];
	saveAction = f.action;
	f.action = urlPath + "upload_image.php";
	f.target = "uploadImageFrame";
	f.submit();
}
function afterUploadImage(imagePath)
{
	var f = document.forms[1];
	f.action = saveAction;
	f.target = "_self";
	
	var textFrame = document.getElementById("message___Frame");
	if (!textFrame || !textFrame.contentWindow)
		return false;

	editor = textFrame.contentWindow.FCK;
	if (!editor)
		return false;
	
	var text = "<img src='" + imagePath + "'/>";
	editor.InsertHtml(text);
	
	if (f.addImageBtn)
		f.addImageBtn.blur();
}

function showLargeImage(url)
{
	window.open('/showlargeimage.php?url=' + url);
}

//don't touch
function showLargeImage(url)
{
  var imgWin = window.open('/showlargeimage.php?url=' + url,'_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
  if (!imgWin)
		return true;//popup blockers should not cause errors
	
  if (imgWin.focus)
		imgWin.focus();
	
  return false;
}