var localizedMessages = {};


function my_stripslashes(str) {
	return str.replace(/\\\\/g, "\\").replace(/\\\'/g, "'").replace(/\\\"/g, "\"");
}
function my_addslashes(str) {
	return str.replace(/\\/g, "\\\\").replace(/\'/g, "\\'");
}
function my_convertspecialchars(str) {
	if (navigator.appVersion.indexOf("KHTML") > 0) {
		return str;
	}
	return str.replace(/\&/g, "&amp;");
}
function my_converthtmlchars(str) {
	return str.replace(/\</g, "&lt;");
}
function xaction(url, params) {
	h = 850;
	w = 1000;
	l = 10;
	t = 10;
	if (w > 1) {
		l = screen.availWidth / 2 - w / 2;
		t = screen.availHeight / 2 - h / 2;
	}
	window.open("/" + url + "?" + params, "action" + parseInt(Math.random() * 1000000), "directories=0,toolbar=0,menubar=0,personalbar=0,location=0," + "scrollbars=1,status=1,resizable=1,left=" + l + ",top=" + t + ",height=" + h + ",width=" + w);
}

function activateBox(id) {
	document.getElementById(id).checked = true;
}
function cancelServiceForm() {
	document.getElementById("service").style.display = "none";
}
var STATUS_INFO = "green";
var STATUS_ERROR = "red";
var STATUSMSG_RECORD_SAVED = "Данные сохранены успешно";
var STATUSMSG_RECORD_SAVE_ERROR = "Ошибка записи данных";
var STATUSMSG_RECORD_DELETED = "Данные удалены успешно";
var STATUSMSG_RECORD_DELETE_ERROR = "Ошибка удаления данных";

function showStatusMessage(type, text) {
	statusbar = document.getElementById("status");
	if (statusbar == null) {
		return;
	}
	statusbar.style.color = type;
	statusbar.innerHTML = text;
//opacity("status", 0, 100, 200);
	statusbar.style.display = "inline";
}

function hideStatus() {
	statusbar = document.getElementById("status");
	if (statusbar == null) {
		return;
	}
//if (statusbar.style.display=="block" && statusbar.innerHTML!="") opacity("status", 100, 0, 200);
	if (statusbar.style.display != "none") {
		statusbar.style.display = "none";
	}
}

function setWorkingStatus(status) {
	if (status==0) {
		document.body.style.cursor = "default";
	} else {
		document.body.style.cursor = "wait";
	}
}

var maxPages = 9;
var onEachSize = (maxPages - 1)/2;
var onEachSizePlusCenter = (maxPages - 1)/2 + 1;

function getFirstOffset(o,t,pp) {
	var first = 0;
	if (o > onEachSize*pp && (t/pp > maxPages)) {
		first = o - onEachSize*pp;
		res = (t - t%pp)/pp - o/pp; 
		//res = Math.trunc(t/pp - o/pp); 
		if (res <= onEachSize) {
			first = first - ((onEachSizePlusCenter*pp) - (res*pp));
			if (t%pp > 0) {
				first =	first + pp;
			}
		}
	}
	return first;
}

function getMaxTotal(o,t,pp) {
	var maxTotal = t;
	var first = getFirstOffset(o,t,pp)/pp;
	var max = t/pp;
	
	if (((max - first)+1) > maxPages && max > maxPages) {
		maxTotal = (first + maxPages)*pp;
	}
	return maxTotal;
}

function fillDataScroll(o,t,pp,link,nextLabel,backLabel,firstLabel,lastLabel) {
	var dataScroll = Array();
	var pg = getFirstOffset(o,t,pp)/pp + 1;
	var i = getFirstOffset(o,t,pp);
	for (i=i;i<getMaxTotal(o,t,pp);i+=pp) {
		dataScroll[i] = { "page": pg };
		pg += 1;
		if (o != i) {
			dataScroll[i]["link"] = link.replace("%OFFSET%", i);
			}
	}
	if (dataScroll.length<2) return Array();
	return dataScroll;
}


var sortCol = "id";
var sortDirection = "asc";
var sortRerender = function() {}

function changeSorting(newSortCol) {
	if (sortCol==newSortCol) {
		if (sortDirection == "asc") {
			sortDirection = "desc";
		} else {
			sortDirection = "asc";
		} // end if asc
	} else {
		SortDirection = "asc";
		sortCol = newSortCol;
	}
	sortRerender();
}

function findPosX(obj) {
	var curleft = 0;
    
    if (obj.offsetParent) {
        while(1) {
			curleft += obj.offsetLeft;
			if (!obj.offsetParent) {
				break;
			}
			
			obj = obj.offsetParent;
		}
    } else if (obj.x) {
        curleft += obj.x;
	}
	
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    
	if (obj.offsetParent) {
		while(1) {
			curtop += obj.offsetTop;
          
			if (!obj.offsetParent) {
				break;
			}
			
			obj = obj.offsetParent;
        }
	} else if (obj.y) {
		curtop += obj.y;
	}
    return curtop;
}
 
/**
 * Predefined variables
 */ 
var HELPER_IFRAME_ID = "IFrmHelper";
var LOADER_DIV_ID = 'dProgress';
var topDivZIndex = 10000;
var oBody;
var oHelperIframe;
var bodyOnLoad;

function bodyOnLoadInternal() {
	var oBody = document.getElementsByTagName("body").item(0);
	var oHelperIframe = document.createElement("div");
	oHelperIframe.setAttribute("id", HELPER_IFRAME_ID);
	oHelperIframe.style.border = 0;
	//oHelperIframe.width = 0;
	//oHelperIframe.height = 0;
	oHelperIframe.style.position = "absolute";
	var obj_val = document.createTextNode(" ");
	oHelperIframe.appendChild(obj_val);
	oBody.appendChild(oHelperIframe);
	if (bodyOnLoad != null) {
		bodyOnLoad();
	}
}

function getDivWidth(divId) {
	return document.getElementById(divId).offsetWidth;
}

function getDivHeight(divId) {
	return document.getElementById(divId).offsetHeight;
}

function showLoaderDiv() {
	var oHelperIframe = document.getElementById(HELPER_IFRAME_ID);
	
	if (!oHelperIframe) {
		throw new Error("001", "Can't find element with ID="+HELPER_IFRAME_ID);
	}
	
	var oDiv = document.getElementById(LOADER_DIV_ID);
	
	if (!oDiv) {
		throw new Error("001", "Can't find element with ID="+LOADER_DIV_ID);
	}
	
	oDiv.style.zIndex = topDivZIndex;
	oHelperIframe.style.zIndex = topDivZIndex - 1000;
	topDivZIndex += 1;
	oHelperIframe.style.top = oDiv.style.top;
	oHelperIframe.style.left = oDiv.style.left;
	oHelperIframe.width = (getDivWidth(LOADER_DIV_ID));
	oHelperIframe.height = (getDivHeight(LOADER_DIV_ID));
	
	showme(HELPER_IFRAME_ID);
	showme(LOADER_DIV_ID);
}

function hideLoaderDiv(divId) {
	var oDiv = document.getElementById(divId);
	hideLoaderDivEl(oDiv);
}

function hideLoaderDivEl(oDiv) {
	var oHelperIframe = document.getElementById(HELPER_IFRAME_ID);
	oHelperIframe.style.visibility = 'hidden';
	oHelperIframe.style.display = 'none';
	oDiv.style.visibility = 'hidden';
	oDiv.style.display = 'none';
}

function moveDiv(divId, Xpos, Ypos) {
	var oHelperIframe = document.getElementById(HELPER_IFRAME_ID);
	var oDiv = document.getElementById(divId);
	Xpos = Math.round(Xpos);
	Ypos = Math.round(Ypos);

	oHelperIframe.style.top = (Ypos + 1) + "px";
	oHelperIframe.style.left = (Xpos + 1) + "px";
	oDiv.style.top = Ypos + "px";
	oDiv.style.left = Xpos + "px";
}

function hideme(divId) {
	var oDiv = document.getElementById(divId);
	if (oDiv == null) {
		alert(divId + " is null");	
	} else {
		oDiv.style.display = 'none';
		oDiv.style.visibility = 'hidden';	
	}
}

function showme(divId) {
	var oDiv = document.getElementById(divId);
	if (oDiv == null) {
		alert(divId + " is null");	
	} else {
		oDiv.style.display = 'block';
		oDiv.style.visibility = 'visible';
	}
}

function hideIt(divId) {
	var oDiv = document.getElementById(divId);
	if (oDiv != null) {
		oDiv.style.display = 'none';
		oDiv.style.visibility = 'hidden';	
	}
}

function showIt(divId) {
	var oDiv = document.getElementById(divId);
	if (oDiv != null) {
		oDiv.style.display = 'inline';
		oDiv.style.visibility = 'visible';
	}
}

function cleanFileInput(outerElemId, fileElem) {
	if (fileElem.value != '') {
		var isIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
		if (!isIE) {
			fileElem.value = '';		
		} else { 
			var outerElem = document.getElementById(outerElemId);
			if (outerElemId == fileElem.parentNode.id) {		
				outerElem.innerHTML = outerElem.innerHTML.replace('value="' + fileElem.value + '"', 'value=""');
			} else {
				var len = outerElem.childNodes.length;
				for (var i = 0; i < len; i++) {           
					if (outerElem.childNodes[i].id == fileElem.parentNode.id) {
						var innerElem = outerElem.childNodes[i];
						innerElem.innerHTML = innerElem.innerHTML.replace('value="' + fileElem.value + '"', 'value=""');				
						break;
					}
				}
			}
		}
	}
}

function toggleUploadFormFields(type) {
	var field1 = document.getElementById("uploadFileInput");
	var field2 = document.getElementById("uploadFromInetInput");
	
	if (field1.style.display != "none") {
		hideme('uploadFileInput'); 
		showme('uploadFromInetInput');
		hideIt('uploadLabel2');
		showIt('uploadLabel1');
		
		var fileElem = document.getElementById("file");
		if (fileElem != null) {
			cleanFileInput('uploadFileInput', fileElem);
		}

	} else if (field2.style.display != "none") {

		showme('uploadFileInput'); 
		hideme('uploadFromInetInput');
		hideIt('uploadLabel1');
		showIt('uploadLabel2');
		
        if (type == "photo") {
			document.getElementById("urlToFile").value = '';
	    } else if (type == "video") {
		    document.getElementById("urlToVideo").value = '';
	    }
	} 
}

function showHideLinkAndCode() {
	var linkBlock1 = document.getElementById("codeLink1");
	var linkBlock2 = document.getElementById("codeLink2");
	var codeBlock = document.getElementById("linkAndCode");
	
	if (linkBlock1.style.display != "none" && codeBlock.style.display == "none") {
		hideIt('codeLink1');
		showIt('codeLink2');
		showme('linkAndCode');
		
	} else if (linkBlock2.style.display != "none" && codeBlock.style.display != "none") {
		hideIt('codeLink2');
		showIt('codeLink1');
		hideme('linkAndCode');
	} 
}

function copyToClipboard(inputId) {
    var input = document.getElementById(inputId);
    input.select();
    if (navigator.appName != "Microsoft Internet Explorer") {
		alert("Ваш браузер не поддерживает функцию копирования текста. Пожалуйста, скопируйте адрес ролика вручную");
		return;
	}
 	copiedTxt = document.selection.createRange();
    copiedTxt.execCommand("Copy");
}


function toggleme(divId) {
	var oDiv = document.getElementById(divId);
	
	if (oDiv.style.display == 'block') {
		oDiv.style.display = 'none';
	} else {
		oDiv.style.display = 'block';
	}	
}

function showLoadingProgress(obj) {
	var x = 0;
	var y = 0;
	var winW = 200;
	var winH = 200;
	
	var isDOM = document.getElementById;
	var isOpera = window.opera && isDOM;
	var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	
	if (parseInt(navigator.appVersion) > 3) {
		if (navigator.appName=="Netscape" || isOpera) {
			winW = window.innerWidth;
			winH = window.innerHeight;
	 	} 
	 	
	 	if (navigator.appName.indexOf("Microsoft") != -1) {
			winW = document.body.offsetWidth;
			winH = document.documentElement.clientHeight; //IE7
//			winH = document.body.offsetHeight; //pre-IE7
	 	}
		
		if (obj) {
  			x = winW / 2 - 50 + posLeft();
  			y = winH / 2 - 50 + posTop();
  		}
  	} else if (obj) {
		var x = findPosX(obj);
		var y = findPosY(obj);
	}
	
	x = x - 100;
	y = (isIE6) ? y : y/2

	moveDiv(LOADER_DIV_ID, x, y);
	showLoaderDiv();
}

function hideLoadingProgress() {
	hideLoaderDiv(LOADER_DIV_ID);
}

function fillCheckedArrey(myarray) {
 var checkedCount = 0;
 for(var i=offset;i<=(perPage+offset);i++) {
  var box = document.getElementById('checkBox_' + i);
  if (box != null) {
 	if (box.checked) {
 		myarray[i] = box.value;
 		checkedCount += 1;
 	} else {
 		myarray[i] = "";
 	}
   }
 }
 return checkedCount;
}

function checkAll(firstMarkAll, secondMarkAll) {
	var mainBox = document.getElementById('markAll');
	if (typeof firstMarkAll != 'undefined') {
		mainBox = document.getElementById(firstMarkAll);
	}
	if (mainBox != null) {
		mainBox.checked=mainBox.checked? 1:0;
		for(var i=offset;i<=(perPage+offset);i++) {
	 		var box = document.getElementById('checkBox_' + i);
			if (box != null) {
			 	box.checked=mainBox.checked;
			}
		}
	}
	if (typeof secondMarkAll != 'undefined') {
		document.getElementById(secondMarkAll).checked=mainBox.checked;
	}
}

function deleteMarked(pagename,msgPrompt,root) {	
var myarray = new Array(perPage);
var count = fillCheckedArrey(myarray);
if (count == 0) {
	alert("Ничего не выбрано");
	return;
}
if (!confirm(msgPrompt)) return;
url = root + 'ajax/' + pagename;
AjaxRequest.post({
	'url':url, 
	'parameters':{
		'a':'deleteList', 
		'array':myarray
	}, 
"onSuccess":function (req) {
	if (req.responseText == "OK") {
	  offset-=10;
	  sortRerender(root, pagename);
	} 
}, "onError":function (req) {
	var el = document.getElementById("error");
	if (el != null)
	 el.innerHTML = eval("\"" + req.responseText + "\"");
}});
}

function openChatWindow(url) {
	openContact(url,'messages',580,785);
	
}

function openContact(url,name,width,height) {
	if (!width) {
		width = 580;
	}
	if (!height) {
		height = 785;
	}
	var w=window.open(url,name,"width="+width+",height="+height+",resizable=1,toolbar=0,location=0,status=0,menubar=0,directories=0,scrollbars=yes,top=0,left=0");
	w.focus();
}

function getCurrentDate(id) {
	var mydate=new Date();
	var year=mydate.getYear();
	if (year < 1000) {
		year+=1900;
	}
	var day=mydate.getDay();
	var month=mydate.getMonth()+1;
	if (month<10) {
		month="0"+month;
	}
	var daym=mydate.getDate();
	if (daym<10) {
		daym="0"+daym;
	}
	document.getElementById(id).innerHTML = daym+"."+month+"."+year;
}
function hide(ele) {
	var srcElement = document.getElementById(ele);
	if (srcElement != null) {
     	srcElement.style.display= "none";
	}
	return false;
}
function show(ele,contEle) {
    var srcElement = document.getElementById(ele);
    if (srcElement != null) {
	    if (typeof contEle != "undefined") {
	        srcElement.innerHTML = contEle;
	    } else {
	       	srcElement.style.display="";
	    }
    }
    return false;
  }
function checkCookies() {
	Set_Cookie('test', 'none', '', '/', '', '');
	if (Get_Cookie('test')) {
		Delete_Cookie('test', '/', '');
	} else {
		alert('Для корректной роботы сайта необходимо включить Cookies!');
		return false;
	}
	return true;
}

function Set_Cookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if (expires)
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert('today ' + today.toGMTString());// this is for testing purpose only
	var expires_date = new Date(today.getTime() + (expires));
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") + 
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for (i = 0; i < a_all_cookies.length; i++)
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if (cookie_name == check_name)
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1)
			{
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found)
	{
		return null;
	}
}
function Delete_Cookie(name, path, domain) {
	if (Get_Cookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function getConfirmRememberPass(/*login*/) {
	var chbox = document.getElementById("rememberMe");
	if (typeof chbox.checked != "undefined") {
		/*if (typeof login == "undefined" || login == "" || (document.getElementById("f_login").value != login)) {	*/
//			if (!confirm("Вы уверены, что хотите запомнить логин и пароль?")) {
//				document.getElementById("notRemember").value = "true";
//			}
		/*}*/
	}
	//return true;
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) { // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		countfield.value = maxlimit - field.value.length;
	} else { // otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length;
	}
}

//Browser Window Size and Position
//http://javascript.about.com/od/guidesscriptindex/a/screen.htm

function pageWidth() {
	return window.innerWidth != null? window.innerWidth : 
		document.documentElement && document.documentElement.clientWidth ?  document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
} 

function pageHeight() {
	return  window.innerHeight != null? window.innerHeight : 
		document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
} 

function posLeft() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : 
		document.documentElement && document.documentElement.scrollLeft ?   document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
} 

function posTop() {
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : 
		document.documentElement && document.documentElement.scrollTop ?    document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
} 

function posRight() {
	return posLeft()+pageWidth();
} 

function posBottom() {
	return posTop()+pageHeight();
}

function cloneAForm(formName) {
	var origForm = document.forms[formName];
	var acopy = origForm.cloneNode(true);
	
	var fields = acopy.elements;	
	for(var i=0; i < fields.length; i++) {
		var elem = fields[i];
		if (elem.tagName == "SELECT" || (elem.tagName == "input")) {
			var source_sel = origForm.elements[elem.name];
			elem.value = source_sel.value;
		} else if (elem.tagName == "INPUT") {
			var source_sel = origForm.elements[elem.name];
			if (elem.type == "checkbox") {			
				elem.checked = source_sel.checked;
			} 
			// other types, need to be copied separately
		}
		//this is for test, in case you dont know what are you missed in form
		//alert('elem.tagName: ' + elem.tagName + "; elem.type: " + elem.type + ";");
	}
	return acopy;
}

/**
 * Generates pagination html output. 
 *
 * @param     Array      pages_data    : an array of the pages data.
 * @param     Boolean    is_top        : A flag, whish inform about position of the pagination block.
 * @param     String     class         : A css-class of the pagination container.
 * @param     String     args          : An additional arguments of the pagination container.
 *
 * @return    String     result        : Return a html-code of the pagination block.
 */
function getPagination(pages_data, is_top, container_id, css_class, args) {

	var result = '';
	
	if (pages_data != null) {
	
		var d = pages_data;
			
		var container_id = (container_id != null) ? container_id : 'pagination';
		var container_class = (css_class != null) ? 'class = "' + css_class + '"' : 'class="pagescroll"';
		var container_args = (args != null) ? args : '';
	
		result += '<div id="' + container_id + ((is_top != null && is_top) ? '_top' : '') + '" ' + 
		           container_class + ' ' + container_args + '>';
	
		for (p in d) {			
			if (d[p].link) {
//				result += '<a href="#' + container_id + '_top" onclick="' + d[p].link + '">';
				var prog_bar_func = getProgBarFunc(d[p].link);
				result += '<a href="javascript:void(0);" onClick="javascript: window.document.location.href=\'#' + container_id + '_top\'; ' + prog_bar_func + '">';
				result += d[p].page;
				result += '</a>';			
			} else {
				result += '<span class="search_nav">';
				result += d[p].page;
				result += '</span>';			
			}
		}
		
		result += '</div>';
	}
	
	return result;
}  /*--- End of function getPagination(...) ---*/


function getProgBarFunc(orig) {
	return orig.substring(11, orig.length);
}

function getFrameTop(root) {
	if (typeof root == 'undefined') {
		root='/';
	}
	str='<table class="frame" cellpadding="0" cellspacing="0">';
	str+='<tr>';
	str+='<td class="topleft"><img src="' + root + 'images/spacer.gif" width="5" height="5" alt="" /></td>';
	str+='<td class="topcenter"></td>';
	str+='<td class="topright"><img src="' + root + 'images/spacer.gif" width="5" height="5" alt="" /></td>';
	str+='</tr>';
	str+='<tr>';
	str+='<td class="midleft"></td>';
	str+='<td class="midcenter">';
	return str;
}

function drawFrameTop(root) {
	frametop = getFrameTop(root);
	document.write(frametop);
}

function getFrameBottom() {
	str='</td>';
	str+='<td class="midright"></td>';
	str+='</tr>';
	str+='<tr>';
	str+='<td class="bottomleft"></td>';
	str+='<td class="bottomcenter"></td>';
	str+='<td class="bottomright"></td>';
	str+='</tr>';
	str+='</table>';
	return str;
}

function drawFrameBottom() {
	framebottom = getFrameBottom()
	document.write(framebottom);
}

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime) {
			return;
		}
	}
}

function allowSingleSubmit(form_name) {
	return true;
}

/*var formSubmited = new Array();
function allowSingleSubmit(form_name) {
	var allow = false;
	if (formSubmited[form_name] == null) {
		formSubmited[form_name] = true;
		allow = true;
	}
	return allow;
}

function resetAllowSingleSubmit(form_name) {
	formSubmited[form_name] = null;
}*/

/*
 * Return GET value by parameter name
 */
function getParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}

/**
 * Set focus by ID for some element.
 */
function setFocus(id) {
	if (id != 'undefined' && id != '') {
		document.getElementById(id).focus();
	}
}

function jump2Anchor(id) {
	if (id != 'undefined' && id != '') {
		window.location.hash=id;
	}
}

/**
 * Login form. Login as ZaMnoy user or as OpenID.
 */
 
function toggleFormPart(id) {
	var formPart1 = document.getElementById("loginAsUser");
	var formPart2 = document.getElementById("loginAsOpenId");
	
	if (formPart1.style.display != "none" && id == "loginAsOpenId") {
		hideme('loginAsUser'); 
		document.getElementById("login").value = '';
		document.getElementById("password").value = '';
		showme('loginAsOpenId');
		document.getElementById("loginType").value = '1';

	} else if (formPart2.style.display != "none" && id == "loginAsUser") {
		showme('loginAsUser'); 
		hideme('loginAsOpenId');
		document.getElementById("openId").value = '';
		document.getElementById("loginType").value = '0';
	}
}


function clickOnOpenIdIcon(index, textId) {
    var b1 = document.getElementById("b1");
    var b2 = document.getElementById("b2");
    if (b1.checked == true) {
    	b2.checked = true;
    	b1.checked = false;
    	toggleFormPart('loginAsOpenId');
    }
	var myselect = document.getElementById("openIdTypeSelect");
	myselect.selectedIndex = index;
	onOpenIdTypeSelected(myselect, textId);
}

function onOpenIdTypeSelected(myselect, textFieldId) {  
	var exampleField = document.getElementById(textFieldId);
		if (myselect.selectedIndex == 0) {
			exampleField.innerHTML = 'domain';    
		} else if (myselect.selectedIndex == 1) {
			exampleField.innerHTML = 'livejournal';
		} else if (myselect.selectedIndex == 2) {
			exampleField.innerHTML = 'blogspot';
		}
}

function clickOnOpenIdCommentIcon(index, textId) {
	var myselect = document.getElementById("commentOpenIdSelector");
	myselect.selectedIndex = index;

	changeOpenIdFieldText(myselect, textId);
}

function changeOpenIdFieldText(myselect, textFieldId) { 
	var textField = document.getElementById(textFieldId);
	if (textField.value == ''
		|| textField.value == 'username.domain.com' 
		|| textField.value == 'username.livejournal.com'
		|| textField.value == 'username.blogspot.com') {
		if (myselect.selectedIndex == 0) {
			textField.value = 'username.domain.com';    
		} else if (myselect.selectedIndex == 1) {
			textField.value = 'username.livejournal.com';
		} else if (myselect.selectedIndex == 2) {
			textField.value = 'username.blogspot.com';
		}
	}
}

function setValues(index, textField) {
	var sel = document.getElementById('openIdTypeSelect');
	sel.selectedIndex = index;
	onOpenIdTypeSelected(sel, textField);
}

function removeOpenIdText(textInput) {
    if (textInput.value == 'username.domain.com' || textInput.value == 'username.livejournal.com' || textInput.value == 'username.blogspot.com') {
	    textInput.value = '';
	}
}

function removeOpenIdTextByName(formName, textInputName) {
    var frm = document.forms[formName];
    if (frm != null) {
	    var inputEl = frm.elements[textInputName];
	    if (inputEl != null) {
	        removeOpenIdText(inputEl);
	    }    
    }
}

function capitalize(str) {
	return str.charAt(0).toUpperCase() + str.substr(1);
}

function clearHolder(id) {
	var el = document.getElementById(id);
	
	if (!el) {
		var err = new Error('001', 'Can not find the element with ID=' + id);
		err.name = 'getElementById error';
		throw (err);
	} else {
		el.innerHTML = "";
	}
}
  
function addFormEventHandler( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
} 

function showHideViewsLink (link1, link2) {
	hideIt(link1); 
	showIt(link2);
}

function ctrlEnter(event) {
	var pressed = false;
	if((event.ctrlKey) && ((event.keyCode == 0xA)||(event.keyCode == 0xD))) {  
		pressed = true;   
	}
	
	return pressed;
}