var articleId="";
var voteArticleId="";
var userExits="";
var voteType="";
var xmlhttp=false;
var responsetxt = "";
var localId="";
var LinkId="";
var className="";
var myPicture=parseInt(Math.random()*99999999);
var oldSectionValue=0;
var nfiles = 1;
var offsetHeightUpload=0;
var authInfo = '1';
var server = getHost(window.location.href);
var mouseOnTooltip = false;
var duplicateArgs = '';
var msgSelected = false;
var forceLoad = false;
var sec = 0;
var curFadeBtn = null;
var utube = 1;

var anim = new Image(313,90); 
anim.src = server+"/img/anim3.gif"; 
 

function getHost(url)
{
	var temp = new Array();
	temp = url.split('/');
	return temp[0]+'//'+temp[1]+temp[2];
}


String.prototype.trim = function() {

  return this.replace(/(^\s *)|(\s*$)/g,"")
}

var browserName=navigator.appName; 


//function for adjustments footer with respect to the page contents
/*
function init()
{
	//document.getElementById("top").height = parseInt(document.getElementById("logo").offsetHeight + 2) 
	document.getElementById("left").style.top = parseInt(document.getElementById("top").offsetHeight ) + "px"
	if(document.getElementById("right")){
		if(document.getElementById("right").style.display!="none")
			document.getElementById("right").style.top = parseInt(document.getElementById("top").offsetHeight ) + "px"
		}
	/*if (parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) >= 300){
		document.getElementById("footer").style.top = parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) + 25 + "px"
	}
	
	callSize(0,0);

	document.getElementById("footer").style.display="block";
}*/
//function validate to search option apper in header
/*
function checksearch(){

	if (document.getElementById('searchFor').value.trim()==""){
		alert(searchForString);
		document.getElementById('searchFor').value = "";
		document.getElementById('searchFor').focus();
		return false;
	}
}*/

function getSessionForNoCookies(withChar)
{
	return '';//savādāk atgriež undefined
}

function Expand()
{
  
  nfiles++ ;
  document.frmForm.txtFileNumber.value = nfiles ;
  
  if (nfiles>100){
	  return false;
  }
   var c = '&nbsp;&nbsp;<font style="color: #68b4ff; font: normal 10px arial;"> * lodziņā ieraksti bildes adresi internetā un spied "Pievienot" vai</font><br>';
   c = c + '&nbsp;&nbsp;<font style="color: #68b4ff; font: normal 10px arial;"> * spied "Browse" un sameklē bildi savā datorā</font>';
   var adh = '<div class="profile_row"><label style="padding-top: 10px;">Attēls:</label> <label class="col2" id="label'+nfiles+'" style="padding-top: 10px;"><input type="file" name="File'+nfiles+'" id="File'+nfiles+'" size="25" class="inputText2" onChange="Expand();"></label>'+c+'</div>';
   adh = adh + '<div class="profile_row"><label>Attēla apraksts:</label> <label id="col2" style=" // width: 500px;"><Input Name="Desc-File'+nfiles+'" Size=20 value="" class="inputText2">&nbsp;</label></div>';
   //adh = adh + '<a id="addmore'+nfiles+'" href="#" OnClick="return(Expand());">Pievienot vēl attēlus</a></LABEL></div>';
   
  //document.getElementById('addmore'+(nfiles-1)).style.display="none";
  document.getElementById('files' + nfiles).innerHTML=adh;
  document.getElementById('files' + nfiles).style.display="block";
  window.scrollBy(0,65);
	if(browserName!="Microsoft Internet Explorer"){
			offsetHeightUpload = offsetHeightUpload + 22 ;
	}
	else
	{
		offsetHeightUpload = offsetHeightUpload - 48 ;
	}

  offsetHeightUpload = offsetHeightUpload + parseInt(document.getElementById('files' + nfiles).offsetHeight);
  return false;
}
//function for enable login with enter key
function enableEnterKeyLogin(pageScript, event)
	  {

		if(!event){
			var keyCode = window.event.keyCode;
		}else{
			var keyCode = event.keyCode;
		}
		if (keyCode == 13)	{
			loginCheck_username(pageScript);
			keyCode = 0;
		}
	  }
function functionOnEnter(functionName, event){
	if(!event){
		var keyCode = window.event.keyCode;
	}else{
		var keyCode = event.keyCode;
	}
	if(keyCode == 13){
		eval(functionName+"()");
		keyCode = 0;
	}
}
  
function enableEnterKeySearch(event)
  {
	if(!event){
		var keyCode = window.event.keyCode;
	}else{
		var keyCode = event.keyCode;
	}
	if (keyCode == 13)	{
		if (document.getElementById('searchFor').value.trim()==""){
			alert(searchForString);
			document.getElementById('searchFor').value = "";
			document.getElementById('searchFor').focus();
		}
		else{
			document.frmSearch.submit();
		}
		keyCode = 0;
	}
  }
function RSSfeedLink()
{
	document.frmFeed.submit();
}

var code;
/*
function callLinkHits(articleId,uid,linkType,redirectLocation)
{
	
	document.frm.articleId.value=articleId;
	document.frm.uid.value=uid;
	document.frm.linkType.value=linkType;
	document.frm.redirectLocation.value=redirectLocation;	
	
	document.frm.target="_blank";
	document.frm.action="gotoURL.php"+getSessionForNoCookies('?');
	document.frm.submit();
	
}*/

function deleteProfileImage(imageId){
	window.location.href = '/deleteProfileImage.php?imageid='+imageId;
}

function activeCategory(){
	document.getElementById("frmUser").action="activeCategory.php"+getSessionForNoCookies('?');
	document.getElementById("frmUser").submit();
}

function checkArticle(userExists, id){
	if(userExists==0){
		alert(logIntoComments)
	}
	else{
		document.frm.articleId.value=id;
		document.frm.action="articleView.php"+getSessionForNoCookies('?');
		document.frm.submit();
	//window.location.href='comments.php?articleId=' + id;
	}
}

function checkArticleType(type){
		document.Form1.approvalType.value=type;
		document.Form1.pages.value=1;
		document.Form1.action="articleApproval.php"+getSessionForNoCookies('?');
		document.Form1.submit();
}

function winOnLoad()
{
  var w = 150, h = 24;
  f1 = xGetElementById('form1');
  xAddEventListener(document, 'keypress', onKeypress, false);
  xAddEventListener(document, 'keyup', onKeyup, false);
  xAddEventListener(document, 'keydown', onKeydown, false);
}
function onKeypress(evt)
{
  var e = new xEvent(evt);
  f1.kp.value = e.keyCode;
  return onKeyEvent(evt, e);
}
function onKeyup(evt)
{
  var e = new xEvent(evt);
  f1.ku.value = e.keyCode;
  return onKeyEvent(evt, e);
}
function onKeydown(evt)
{
  var e = new xEvent(evt);
  f1.kd.value = e.keyCode;
  return onKeyEvent(evt, e);
}
function onKeyEvent(evt, xe)
{
  f1.et.value = xName(xe.target);
  f1.mx.value = xe.pageX;
  f1.my.value = xe.pageY;
  if (f1.sp.checked) xStopPropagation(evt);
  if (f1.pd.checked) {
    xPreventDefault(evt);
    return false;
  }
  return true;
}

function checkArticleSubmission(mode) 
{ 
	var num=0;
	var chkbool=0;
	var checkCount=0;
	var strID='';

	heading1=document.getElementById("heading");
	
	link11=document.getElementById("link1");
	
	utube1=document.getElementById("utube");

	description1=document.getElementById("description");

	if (heading1.value.trim()=="")
	{
		alert('Nav norādīts virsraksts!');
		heading1.focus();
		return false;	
	}

	// check tag
	var i=0;
	var count = 0;
	for (i=0; i<110; i++)
	{
		if (document.getElementById('tag_'+i))
			if (document.getElementById('tag_'+i).checked == true)
				count++;
	}
	if (count != 1)
	{
		alert('Jāizvēlas viena kategorija!');
		return false;
	}

	if (document.getElementById('rules'))
	if (document.getElementById('rules').checked==false)
	{
		alert('Jāpiekrīt lietošanas noteikumiem!');
		return false;
	}

	if (document.getElementById('progressBarStatus'))
		if (document.getElementById('progressBarStatus').innerHTML>'' && document.getElementById('progressBarStatus').innerHTML != 'Visas bildes ielādētas!')
			{
				alert('Uzgaidi, vēl tiek lādētas bildes!');
				return false;
			}
	if (getImageCount()==0)
	{
		alert('Jāielādē vismaz viena bilde!');
		return false;
	}

	if (mode == 'edit') document.frmForm.action = "articleUpdate.php";
	if (mode == 'add') document.frmForm.action = "articleConfirmation.php";
	if (mode == 'preview') document.frmForm.action = "articleConfirmation.php?preview=true";

	document.getElementById('comments_description_in_form').value = CKEDITOR.instances.comments_description.getData();
	//if (mode == 'edit') 
	//	document.getElementById('thumbnails_in_form').innerHTML = document.getElementById('thumbnails').innerHTML;

	changeType();
	document.frmForm.submit();
	setFlash();

	if (document.getElementById('btn_1')) document.getElementById('btn_1').style.display='none';
	if (document.getElementById('btn_2')) document.getElementById('btn_2').style.display='none';

	//if (duplicateArgs > "") processVote();
} 

function processVote()
{
 	var args = duplicateArgs.split('|||');
	var id = args[0];
	var subid = args[1];
	var user = args[2];
	//add_vote(user, 0, id, 1, subid);
}

function changeType()
{
	var n = 0;
	var el;
	var label;
	var str = "";
	for (n=1; n<=nfiles; n++)
	{
		if(document.getElementById("File"+n))
		{
			el = document.getElementById("File"+n);
			str = el.value;
			if (str.length>4 && str.substring(0,4) == "http")
			{	
				//el.type = "text";
				//el.value = str;
				label = document.getElementById("label"+n);
				label.innerHTML = '<input type="text" value="'+str+'" name="File'+n+'" id="File'+n+'" size="25" class="inputText2" onChange="Expand();">';
			}
		}
	}
}

function setFlash()
{
	
	if (nfiles>1 || isVideo() || isGal())
	{
		var flash = document.getElementById('flashDiv');
		var pos = findPos(document.getElementById('bottom'));
		flash.style.width = screen.width;
		flash.style.height = (pos[1]+100)+'px';
		flash.style.display = '';
		if (browserName != 'Microsoft Internet Explorer')
		{
			document.getElementById('upload_div').style.left = ((document.body.clientWidth-289)/2);
			document.getElementById('upload_div').style.top = ((document.body.clientHeight-132)/2);
		}
		document.getElementById('upload_div').style.display = "";
	}
}

function isGal()
{
	return (document.getElementById('isGal'));
}

function isVideo()
{
	var is = false;
	if (document.getElementById('video_file'))
	{
		var val = document.getElementById('video_file').value;
		if (val > "") is = true;
	}
	return is;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	//return [curleft,curtop];
	return curtop;
}


function verifyTag(id)
{
	var i=0;
	var count = 0;
	for (i=0; i<110; i++)
	{
		if (document.getElementById('tag_'+i))
		{
			document.getElementById('tag_'+i).checked = false;
			document.getElementById('tag_'+i).parentNode.childNodes[0].className = 'jqTransformCheckbox';
		}
	}
	document.getElementById('tag_'+id).checked = true;
	/*
	if (id==39 || id==40)
	{
		if (document.getElementById('isOriginal'))
		{
			document.getElementById('isOriginal').checked = true;
			document.getElementById('isOriginal').parentNode.childNodes[0].className = 'jqTransformCheckbox jqTransformChecked';
		}
	}*/

}

function approve_disapprove(articleId, chkbox)
{	
		
	if (document.getElementById(chkbox).checked == true)		
		approve=1;
	else
		approve=0;
	
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+ myRand + "&articleId="+encodeURI(articleId) + "&approve="+approve+getSessionForNoCookies('&');
	var posturl="check_approve_disapprove.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {
	//xmlhttpChange_approval(response); }});	
	
	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttpChange_approval(response)}});
}

function xmlhttpChange_approval(originalRequest)
{
	//approve = originalRequest.responseText;
	var approve = originalRequest;
	if(approve.trim() == 1)
	 alert(approved);
	else
	 alert(disapproved);
}


function active_deactive(articleId, chkbox)
{	
	if (document.getElementById(chkbox).checked == true)		
		approve=1;
	else
		approve=0;
		
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+ myRand + "&articleId="+encodeURI(articleId) + "&approve="+approve;
	var posturl="check_active.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {
	//xmlhttpChange_active(response, approve); }});		

	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttpChange_active(response, approve);}});
}

function xmlhttpChange_active(originalRequest, approve1)
{
	approve = originalRequest;
	if(approve.trim() == 1)
	 alert(active);
	else
	 alert(disactive);
}

function useractive_deactive(userId,chkbox)
{	
	
	if (document.getElementById(chkbox).checked == true)		
		approve=1;
	else
		approve=0;
		
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+ myRand + "&userId="+encodeURI(userId) + "&approve="+approve;
	var posturl="user_check_active.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {
	//xmlhttpUserChange_active(response, approve); }});	
	$.ajax({type:'POST', url:posturl, data:poststr, success:function(response){xmlhttpUserChange_active(response);}});
}

function xmlhttpUserChange_active(originalRequest)
{
	approve = originalRequest;
	if(approve == '1') alert('Darīts!');
}

function login_chk()
{
	//alert("chk");
	if (document.getElementById("txtUserName").value=="")
	{
	alert(username);
	document.getElementById("txtUserName").focus();
	return false;
	}
	
	if (""==document.getElementById("txtPwd").value)
	{
	alert(password);
	document.getElementById("txtPwd").focus();
	return false;
	}

}

function validate_reg_form() {

	document.getElementById("tmp").value = document.getElementById("username").value;
	
	if(!document.getElementById("rules").checked) {
		alert(rules);
		return false;			
	}
	
	if( "" == document.getElementById("username").value.trim() ) {
		alert(username);
		document.getElementById("username").focus();
		return false;
	}
	
	if( 4 > (document.getElementById("username").value.trim()).length ) {
		alert(min_username);
		document.getElementById("username").focus();
		return false;
	}
	
	if( document.getElementById("password").value.trim() != document.getElementById("confirm_password").value.trim() ) 
		{
		alert(match_password);
		document.getElementById("confirm_password").focus();
		return false;
	}
	var str = document.getElementById("emailAddress").value.trim();
	if ( str.length < 5) 
	{
		alert('E-pasts jāievada obligāti');
		document.getElementById("emailAddress").focus();
		return false;
	}
}

function chaekspace() 
{
	document.getElementById("password").value = document.getElementById("password").value.trim();
}

function chkEmail()
{
	Email=document.getElementById("emailAddress").value;
	if(!Email.match(/^[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,6}$/i)) 
	{ 
//		alert("InValid Email ID!");
//		document.frm.emailAddress.focus();
		return false; 
	}
	else
	{ 
	   return true; 
	} 
		
}

function validateCommentForm()
{
	var a = CKEDITOR.instances.comments_description.getData();
	
	if(a.trim() == "" )
	{
		alert('Jāievada teksts!');
		return false;
	}
	document.getElementById("antispam").value = 'abrakadabra';
	document.getElementById("btn_add").style.display='none';
}

function forget_form()
{
	//alert(document.getElementById("emailAddress").value.trim());
	if(document.getElementById("emailAddress").value.trim() == "") {
		alert(emailaddress);
		document.getElementById("emailAddress").value = document.getElementById("emailAddress").value.trim();
		document.getElementById("emailAddress").focus();
		return false;
	}
	if( false == chkEmail2() ) {
		alert(valid_email);
		return false;
	}

	document.getElementById("emailAddress").value = document.getElementById("emailAddress").value.trim();

}

function validate_forget_form()  {
	if( "" == document.getElementById("secretAnswer").value.trim()) {
		alert(secret);
		return false;
	}
	document.getElementById("secretAnswer").value = document.getElementById("secretAnswer").value.trim();
}

function chkEmail2()
{
	Email=document.getElementById("emailAddress").value.trim();
	if(!Email.match(/^[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,6}$/i)) 
	{ 
//		alert("InValid Email ID!");
//		document.frm.emailAddress.focus();
		return false; 
	}
	else
	{ 
	   return true; 
	} 
}

function validate_change_password_form()
{
	if( "" == document.getElementById("old_Password").value.trim() ) {
		alert(current_password);
		return false;
	}
	
	if( "" == document.getElementById("new_password").value.trim() ) {
		alert(new_password);
		document.getElementById("new_password").focus();
		return false;
	}
	if( 5 > (document.getElementById("new_password").value.trim()).length ) {
		alert(password_spec);
		document.getElementById("new_password").focus();
		return false;
	}

	if( "" == document.getElementById("confirm_password").value.trim() ) {
		alert(confirm_password);
		document.getElementById("confirm_password").focus();
		return false;
	}
	
	if( document.getElementById("new_password").value.trim() != document.getElementById("confirm_password").value.trim() ) {
		alert(match_password);
		document.getElementById("confirm_password").focus();
		return false;
	}

}
/*
function search_validation()  {

	if(document.getElementById("advancesearchFor").value.trim()=="") {
		alert(searchmsg);
		//alert(searchmsg);
		return false;
	}
}*/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return '';
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

function genId()
{
	var r1=parseInt(Math.random()*9999999999);
	var r2=parseInt(Math.random()*9999999999);
	return r1.toString()+r2.toString();
}

//function add_vote(userExists, pointId, articleId, voteType1, submitterId)
function add_vote(pointId, voteType)
{
	var params = '';
		
	if (voteType == 1)
		params = document.getElementById('plusVoteParams'+pointId).value;
	else
		params = document.getElementById('minusVoteParams'+pointId).value;
	paramArr = params.split("|||");	

	//alert(params);
	if (params>'')
	{

		
	var userExists = paramArr[0];
	var voteArticleId = paramArr[2];
	var voteType = paramArr[3];
	var submitterId = paramArr[4];
		
		if(userExists==0)
		{
			window.location.href = '/login.php';
			/*
			document.Form1.action = '/login.php'
			document.Form1.modeType.value = 'vote';
			document.Form1.submit();
			return false;*/
		}
		else{
			if(userExists==submitterId)
			{
				alert("Nevar balsot par savu rakstu!");
				return false;
			}
			else{
				var myRand=parseInt(Math.random()*99999999);
				var poststr="myRand="+ myRand + "&articleId="+encodeURI(voteArticleId)+"&voteType=" +voteType+"&submitterId=" +submitterId+getSessionForNoCookies('&') ;
				var posturl="/votes.php";

				$.ajax({type:'POST', url:posturl, data:poststr, success:function(response){xmlhttpChangeVote(response,pointId, voteType);}});
			}
		}
	}
	else alert('Uzgaidi, lapa vēl lādējas!...');
}


function xmlhttpChangeVote(originalRequest, pointId, voteType1)
{
	
	//alert(originalRequest);
	var voteType = voteType1 ;
	var retCheck = originalRequest;
	if (retCheck=='limit')
	{
		alert('Sasniegts balsošanas limits!');
		return false;
	}
	if (retCheck=='timeout')
	{
		alert('Tu tikko jau nobalsoji!');
		return false;
	}

	//alert(retCheck);
	var temp1=retCheck.split("|||");


	document.getElementById('pointplus' + pointId).innerHTML = temp1[1];
	document.getElementById('pointminus' + pointId).innerHTML = temp1[2];
	
	 var up = document.getElementById("imgUp" + pointId);
	 var down = document.getElementById("imgDn" + pointId);

	if(voteType==1)
		if(up.src == server+"/img/plus0.png")
		{
			up.src = server+"/img/plus1.png";
			down.src = server+"/img/minus0.png";
		}
		else
		{
			up.src = server+"/img/plus0.png";
		}
	if(voteType==0)
		if(down.src == server+"/img/minus0.png")
		{
			down.src = server+"/img/minus1.png";
			up.src = server+"/img/plus0.png";
		}
		else
		{
			down.src = server+"/img/minus0.png";
		}
}



//function add_vote_comments(userExists, commentId, articleId, voteType1, submitterId)
function add_vote_comments(commentId, voteType)
{
	var params = '';
		
	if (voteType == 1)
		params = document.getElementById('plusVoteCommentParams'+commentId).value;
	else
		params = document.getElementById('minusVoteCommentParams'+commentId).value;
	paramArr = params.split("|||");	
	//alert(params+' '+commentId);

	
	if (params>'')
	{
		
	var userExists = paramArr[0];
	var articleId = paramArr[2];
	var voteType = paramArr[3];
	var submitterId = paramArr[4];
	
	var voteArticleId = articleId;
	
	if(userExists==0)
	{
		//alert(logIntoVote);
		document.location.href="/login.php";
		return false;
	}
	else
	{
		if(userExists==submitterId)
		{
			alert('Nevar balsot par savu komentāru!');
			return false;
		}
		else
		{
			var myRand=parseInt(Math.random()*99999999);
			var poststr="myRand="+ myRand + "&articleId="+encodeURI(voteArticleId)+"&voteType=" +voteType+"&commentId=" + commentId +"&submitterId=" + submitterId ;
			//poststr = poststr.join("")
			var posturl="/votesComments.php";

			$.ajax({type:'POST', url:posturl, data:poststr, success:function(response){ xmlhttpChangeVoteComment(response,commentId, voteType)}});
		}
	}
	}
	else
		if(forceLoad==false)
		{
			forceLoad = true;
			loadArticle();
		}


}

function xmlhttpChangeVoteComment(originalRequest, commentId, voteType1)
{
	var voteType = voteType1;
	var retCheck = originalRequest;

	if (retCheck=='limit')
	{
		alert('Sasniegts balsošanas limits!');
		return false;
	}
	if (retCheck=='timeout')
	{
		alert('Tu tikko jau nobalsoji!');
		return false;
	}

	var temp1=retCheck.split("|||");

	document.getElementById('comvotesplus' + commentId).innerHTML = temp1[1];
	document.getElementById('comvotesminus' + commentId).innerHTML = temp1[2];

	
	var up = document.getElementById("imgUp" + commentId);
	var down = document.getElementById("imgDn" + commentId);

	if(voteType==1)
		if(up.src == server+"/img/plus0.png")
		{
			up.src = server+"/img/plus1.png";
			down.src = server+"/img/minus0.png";
		}
		else
		{
			up.src = server+"/img/plus0.png";
		}
	if(voteType==0)
		if(down.src == server+"/img/minus0.png")
		{
			down.src = server+"/img/minus1.png";
			up.src = server+"/img/plus0.png";
		}
		else
		{
			down.src = server+"/img/minus0.png";
		}
}

function add_vote_gallery(userExists, pointId, imageId, voteType1, submitterId)
{
		var voteImageId = imageId;
		var voteType = voteType1 ;
		
		if(userExists==0){
			document.Form1.action = '/login.php'
			document.Form1.modeType.value = 'vote';
			document.Form1.submit();
			return false;
		}
		else{
			if(userExists==submitterId){
				alert('Nevar balsot par savu attēlu!');
				return false;
			}
			else{
				var myRand=parseInt(Math.random()*99999999);
				var poststr="myRand="+ myRand + "&imageId="+encodeURI(voteImageId)+"&voteType=" +voteType+"&submitterId=" +submitterId+getSessionForNoCookies('&') ;
				var posturl="/votesGallery.php";
				//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete: xmlhttpChangeVote});
				//alert(pointId)
				//var myAjax = new Ajax.Request(posturl, {method: 'post', parameters: poststr, onComplete:function(response) {
				//	 xmlhttpChangeVoteGallery(response,pointId, voteType);
				//	}});

				$.ajax({type:'POST', url:posturl, data: poststr, success:function(response){xmlhttpChangeVoteGallery(response,pointId, voteType)}});
			}
		}
}

function xmlhttpChangeVoteGallery(originalRequest, pointId, voteType1)
{
	
	//alert(originalRequest);
	var voteType = voteType1 ;
	var retCheck = originalRequest;
	
	if (retCheck=='limit')
	{
		alert('Sasniegts balsošanas limits!');
		return false;
	}
	if (retCheck=='timeout')
	{
		alert('Tu tikko jau nobalsoji!');
		return false;
	}
	//alert(retCheck);
	var temp1=retCheck.split("|||");


	document.getElementById('pointplus' + pointId).innerHTML = temp1[1];
	document.getElementById('pointminus' + pointId).innerHTML = temp1[2];
	
	 var up = document.getElementById("imgUp" + pointId);
	 var down = document.getElementById("imgDn" + pointId);

	if(voteType==1)
		if(up.src == server+"/img/plus0.png")
		{
			up.src = server+"/img/plus1.png";
			down.src = server+"/img/minus0.png";
		}
		else
		{
			up.src = server+"/img/plus0.png";
		}
	if(voteType==0)
		if(down.src == server+"/img/minus0.png")
		{
			down.src = server+"/img/minus1.png";
			up.src = server+"/img/plus0.png";
		}
		else
		{
			down.src = server+"/img/minus0.png";
		}
}


function showCommentDiv(userExists)
{
	
	//if(userExists == 0 )
	//{
		//alert(logInComments);
		//return false;
	//}
	//else
	//{	
		if(document.getElementById("message").style.display == "none" ) {
			document.getElementById("message").style.display="block";
		}
	//}
	
	/*if (parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) >= 250){
		document.getElementById("footer").style.top = parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) + 25 + "px"
	}
	*/
	callSize()
}

function hideCommentDiv(){
	if(document.getElementById("message").style.display == "block" ) {
			document.getElementById("message").style.display="none";
		}
		/*
	if (parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) >= 250){
		document.getElementById("footer").style.top = parseInt(document.getElementById("left").offsetHeight + document.getElementById("top").offsetHeight) + 25 + "px"
	}
	*/
	callSize()
}

function hideDiv(id)
{
	document.getElementById("div" + id).innerHTML="";
}
function checkVal(id)
{
	if( document.getElementById("text" + id).value.trim() == "" )
	{
		document.getElementById("text" + id).value == "";
		document.getElementById("text" + id ).focus();
		alert("Please enter Comment");
		return false;
	}
}

function showTextArea(userExists, divId, articleId)
{	
	/*if(userExists==0){
		alert(logInReply);
		return false;
	}*/
	if(document.getElementById("div" + divId).innerHTML == "" )
	{
		document.getElementById("div" + divId).innerHTML +="<br><form method='post' action='comments.php'><input type='hidden' name='parentId' value='" + divId + "'><input type='hidden' name='action' value='add'><input type='hidden' name='articleId' value=" + articleId +"><textarea name='usercomment' id='text" + divId + "' rows='5' cols='60' class='comments_description'></textarea><br><input type='submit' name='addComment' value='Submit' class='buttonClass' onClick='javascript: return checkVal(" + divId + ");'>&nbsp;&nbsp;<input type='button' name='cancel' value='Cancel' class='buttonClass' onClick='javascript: hideDiv(" + divId + ");' ></form>";
		document.getElementById("text" + divId ).focus();

		callSize()
	}
}


function doEdit(divId, articleId) {
	
	if(document.getElementById("div" + divId).innerHTML == "" )
	{
		var commentDesc = document.getElementById(divId).innerHTML;
		//alert(document.getElementById(divId));
		document.getElementById("div" + divId).innerHTML +="<br><form method='post' action='comments.php'><input type='hidden' name='id' value='" + divId + "'><input type='hidden' name='action' value='edit'><input type='hidden' name='articleId' value="+ articleId + "><textarea name='usercomment' id='text" + divId + "' rows='5' cols='60' class='comments_description'>" + commentDesc +  "</textarea><br><input type='submit' name='addComment' value='Submit' onClick='javascript: return checkVal(" + divId + ");' class='buttonClass'>&nbsp;&nbsp;<input type='button' name='cancel' value='Cancel' class='buttonClass' onClick='javascript: hideDiv(" + divId + ");' ></form>";
		document.getElementById("text" + divId ).focus();

	}

}
	
function validate_change_password_form()
{
	if( "" == document.getElementById("old_Password").value.trim() ) {
		alert(current_password);
		return false;
	}

	if( "" == document.getElementById("new_password").value.trim() ) {
		alert(new_password);
		return false;
	}
	if( 5 > (document.getElementById("new_password").value.trim() ).length ) {
		alert(min_password);
		return false;
	}

	if( "" == document.getElementById("confirm_password").value.trim() ) {
		alert(confirm_password);
		return false;
	}
	if( 5 > (document.getElementById("confirm_password").value.trim() ).length ) {
		alert(min_confirm_password);
		return false;
	}

	if( document.getElementById("new_password").value.trim() != document.getElementById("confirm_password").value.trim() ) {
		alert(match_password);
		return false;
	}
}


function search_header()  {
	if( "" == document.getElementById("searchFor").value.trim() ) {
		alert(searchmsg);
		return false;
	}
}

function validate_karmapoints()
{
	if( "" == document.getElementById("viewing_article_points").value.trim() ) {
		alert(inputvalue + viewing_article_points + fields);
		document.getElementById("viewing_article_points").focus();
		return false;
	}
	if(!IsNumeric(document.getElementById("viewing_article_points").value, 0) ) {
		alert(numeric_value + viewing_article_points + fields);
		document.getElementById("viewing_article_points").focus();
		return false;
	}
	if( "" == document.getElementById("voting_article_points").value.trim() ) {
		alert(inputvalue + voting_article_points + fields);
		document.getElementById("voting_article_points").focus();
		return false;
	}
	if(!IsNumeric(document.getElementById("voting_article_points").value,0) ) {
		alert(numeric_value + voting_article_points + fields);
		document.getElementById("voting_article_points").focus();
		return false;
	}
	if( "" == document.getElementById("article_approve_points").value.trim() ) {
		alert(inputvalue + article_approve_points + fields);
		document.getElementById("article_approve_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("article_approve_points").value,0) ) {
		alert(numeric_value + article_approve_points + fields);
		document.getElementById("article_approve_points").focus();
		return false;
	}
	if( "" == document.getElementById("article_disapprove_ponts").value.trim() ) {
		alert(inputvalue + article_disapprove_ponts + fields);
		document.getElementById("article_disapprove_ponts").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("article_disapprove_ponts").value,0) ) {
		alert(numeric_value + article_disapprove_ponts + fields);
		document.getElementById("article_disapprove_ponts").focus();
		return false;
	}
	if( "" == document.getElementById("article_view").value.trim() ) {
		alert(inputvalue + article_view + fields);
		document.getElementById("article_view").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("article_view").value,0) ) {
		alert(numeric_value + article_view + fields);
		document.getElementById("article_view").focus();
		return false;
	}
	if( "" == document.getElementById("upvote_article_points").value.trim() ) {
		alert(numeric_value + upvote_article_points + fields);
		document.getElementById("upvote_article_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("upvote_article_points").value,0) ) {
		alert(inputvalue + upvote_article_points + fields);
		document.getElementById("upvote_article_points").focus();
		return false;
	}
	if( "" == document.getElementById("downvote_article_points").value.trim() ) {
		alert(inputvalue + downvote_article_points + fields);
		document.getElementById("downvote_article_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("downvote_article_points").value,0) ) {
		alert(numeric_value + downvote_article_points + fields);
		document.getElementById("downvote_article_points").focus();
		return false;
	}
	if( "" == document.getElementById("upvote_comment_submitter_points").value.trim() ) {
		alert(inputvalue + upvote_comment_submitter_points + fields);
		document.getElementById("upvote_comment_submitter_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("upvote_comment_submitter_points").value,0) ) {
		alert(numeric_value + upvote_comment_submitter_points + fields);
		document.getElementById("upvote_comment_submitter_points").focus();
		return false;
	}
	if( "" == document.getElementById("upvote_comment_votter_points").value.trim() ) {
		alert(inputvalue + comment_votter_points + fields);
		document.getElementById("upvote_comment_votter_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("upvote_comment_votter_points").value,0) ) {
		alert(numeric_value + comment_votter_points + fields);
		document.getElementById("upvote_comment_votter_points").focus();
		return false;
	}
	if( "" == document.getElementById("downvote_comment_submitter_points").value.trim() ) {
		alert(inputvalue + downvote_comment_submitter_points + fields);
		document.getElementById("downvote_comment_submitter_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("downvote_comment_submitter_points").value, 0) ) {
		alert(numeric_value + downvote_comment_submitter_points + fields);
		document.getElementById("downvote_comment_submitter_points").focus();
		return false;
	}

	if( "" == document.getElementById("comments_points").value.trim() ) {
		alert(inputvalue + comments_points + fields);
		document.getElementById("comments_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("comments_points").value, 0) ) {
		alert(numeric_value + comments_points + fields);
		document.getElementById("comments_points").focus();
		return false;
	}
	if( "" == document.getElementById("admin_delete_comments").value.trim() ) {
		alert(inputvalue + admin_delete_comments + fields);
		document.getElementById("admin_delete_comments").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("admin_delete_comments").value, 0) ) {
		alert(numeric_value + admin_delete_comments + fields);
		document.getElementById("admin_delete_comments").focus();
		return false;
	}
	if( "" == document.getElementById("normal_karma_points").value.trim() ) {
		alert(inputvalue + normal_karma_points + fields);
		document.getElementById("normal_karma_points").focus();
		return false;
	}
	if( !IsNumeric(document.getElementById("normal_karma_points").value, 0) ) {
		alert(numeric_value + normal_karma_points + fields);
		document.getElementById("normal_karma_points").focus();
		return false;
	}
	
	if( "" == document.getElementById("high_karma_points").value.trim() ) {
		alert(inputvalue + high_karma_points + fields);
		document.getElementById("high_karma_points").focus();
		return false;
	}
	if(!IsNumeric(document.getElementById("high_karma_points").value, 0) ) {
		alert(numeric_value + high_karma_points + fields);
		document.getElementById("high_karma_points").focus();
		return false;
	}
}


function IsNumeric(sText, allowDecimal)
{
   var ValidChars = "0123456789";
   if (allowDecimal == 1)
	   ValidChars = ValidChars + ".";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}


function add_language()
{
	if( "" == document.getElementById("fullname").value.trim() ) {
		alert(fullname);
		return false;
	}
	
	
	if( "" == document.getElementById("abbreviation").value.trim() ) {
		alert(abbreviation);
		return false;
	}
	
	if( "" == document.getElementById("languagefile").value.trim() ) {
		alert(languagefile);
		return false;
	}
	
}


function ShowType(type, id)
{
	document.frmComments.type.value=type;
	document.frmComments.articleId.value=id;
	document.frmComments.submit();
}	
function showModeType(type, tagId) {
	if(tagId>0){
		var addTagInUrl = "&tagId="+tagId;
	}else{
		var addTagInUrl = "";
	}
	window.location.href="/index.php?modeType="+type+addTagInUrl+getSessionForNoCookies('&');
}	


function callPopup(articleId,imageId,description,submitterId)
{
	//alert(submitterId);
	var poststr="?articleId="+ encodeURI(articleId) + "&imageId="+imageId + "&description="+description;
	document.getElementById("img1").src="galleryDisplay.php"+poststr;
	//window.open('popup.php'+poststr, '', "left=10, top=10, menubar=no, addressbar=no, scrollbars=yes, width=400, height=400");
	//alert(document.getElementById("img1").Height);
	//callSize();	
	imageHits(articleId,imageId,submitterId);
	getImageDescription(imageId);
	//document.getElementById("footer").style.top = "600px";
	
}

function migrateArticle(migrateType)
{
	srcList = window.document.frm2.articleList;
	var strArticle="";
	
	for(var i = 0; i < srcList.length; i++) 
	{
	if ((srcList.options[i] != null) && (srcList.options[i].selected)) 
		{
		strArticle=strArticle+srcList.options[i].value.trim()+"^";
		}
	}
	//categoryId=srcList.options[i-1].value;
	categoryId=document.getElementById('sourceCategory').value;
	targetCategoryId=window.document.frm2.targetCategory.value.trim();
	if(targetCategoryId==categoryId)
	{
	alert(artMigr_target_category_same);
	return false;
	}
	
	if(targetCategoryId=="0")
	{
	alert(artMigr_no_target_category);
	return false;
	}
	if(srcList.options[0].value=='')
	{
	alert(artMigr_no_article_selected);
	return false;
	}
	
	if(!confirm(artMigr_confirmation))
	return false;
	
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+ myRand + "&list="+strArticle + "&categoryId="+categoryId + "&migrateType="+migrateType + "&targetCategoryId="+targetCategoryId+getSessionForNoCookies('&');
	var posturl="doMigrate.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {
	// xmlhttpChange_migrateArticle(response,migrateType); }});
	$.ajax({type:'GET', url:posturl, data: poststr, success:function(response){xmlhttpChange_migrateArticle(response,migrateType);}});
			
}

function xmlhttpChange_migrateArticle(originalRequest,migrateType)	{
	var retCheck = originalRequest.responseText;
	addSrcToDestList();
	if(migrateType=='Move')
	deleteFromSourceList();
}


function addSrcToDestList() {

destList1 = window.document.frm2.destList;
srcList = window.document.frm2.articleList;
var len = destList1.length;
for(var i = 0; i < srcList.length; i++) {
if ((srcList.options[i] != null) && (srcList.options[i].selected)) {

var found = false;
for(var count = 0; count < len; count++) {
if (destList1.options[count] != null) {
if (srcList.options[i].text == destList1.options[count].text) {
found = true;
break;
}
}
}

if (found != true) {
destList1.options[len] = new Option(srcList.options[i].text);
len++;
}
}
}
}


function deleteFromSourceList() {
	var destList1 = window.document.frm2.articleList;
	var len = destList1.length;
	for(var i = (len-1); i >= 0; i--) {
		if ((destList1.options[i] != null) && (destList1.options[i].selected == true)) {
			destList1.options[i] = null;
		}
	}
}

function clearDestinationList(){
	var destList = window.document.frm2.destList;
	var len = destList.length;
	for(var i=(len-1); i>=0; i--){
		if((destList.options[i] != null)){
			destList.options[i] = null;
		}
	}
}

function showCategory(id){
		
		document.frmCategory.categoryId.value=id;
		document.frmCategory.action="viewCategory.php"+getSessionForNoCookies('?');
		document.frmCategory.submit();
	}
	
function changePwd(){
		
		document.getElementById("frmUser").action="changePassword.php"+getSessionForNoCookies('?');
		//alert(document.getElementById("Form1").action);
		//document.getElmentById("Form1").submit();
		document.getElementById("frmUser").submit();
	}
function changePassword(id)
{
	document.frm12.userId.value=id;
	document.frm12.action="changePassword.php"+getSessionForNoCookies('?');
	document.frm12.submit();
}


function xmlhttpChange_listArticle1(originalRequest)	{
	var retCheck = originalRequest.responseText;
}


function getMessage(id){
	var message = document.getElementById('message_'+id);
	if(message.style.display == 'none'){
		if(document.getElementById('getContent_'+id).value==0){
			document.getElementById('message_content_'+id).innerHTML="<img src='/img/loading.gif' />";
			var myRand=parseInt(Math.random()*99999999);
			var poststr="myRand="+ myRand + "&msgId="+id+getSessionForNoCookies('&');
			var posturl="getMessage.php";
			//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) //{
			//xmlhttp_getMessage(response,id); }});
			$.ajax({type:'GET', url:posturl, data: poststr, success:function(response){xmlhttp_getMessage(response,id);}});
		}else{
			message.style.display = '';
		}
	}else{
		message.style.display = 'none';
	}
	return false;
}

function xmlhttp_getMessage(originalRequest, id){
	var retCheck = originalRequest;
	//alert(retCheck);
	if(retCheck){
		var temp=retCheck.split("|||");
		if(temp[0]==1){
			document.getElementById('getContent_'+id).value = 1;
			if(temp[1]==1){
				document.getElementById('msgLink_'+id).style.fontWeight = 'normal';
			}
		}
		document.getElementById('message_content_'+id).innerHTML = temp[2];
		document.getElementById('message_'+id).style.display = '';
	}
}

function selectAllMessages()
{
	if (msgSelected) msgSelected = false;
	else msgSelected=true;

	var form = document.getElementById('deleteForm');
	for (var i = 0; i < form.elements.length; i++){    
		eval("form.elements[" + i + "].checked = msgSelected");
	}
	var arr = document.getElementsByTagName('a');
	for (i = 0; i < arr.length; i++) 
	{
		if (arr[i].className == 'jqTransformCheckbox' || arr[i].className == 'jqTransformCheckbox jqTransformChecked')
		{
			if (msgSelected) arr[i].className = 'jqTransformCheckbox jqTransformChecked';
			else arr[i].className = 'jqTransformCheckbox';
		}	
	}
	
}

function deleteMessage(id)
{
	document.getElementById('msg'+id).checked=true;
	document.deleteForm.submit();
}

function addPoll(pollId)
{
	var userid = document.getElementById('polluser').value;
	//alert(pollId+' '+userid);
	if(userid==0 || userid==undefined)
	{
		//alert(userid);
		window.location.href="/login.php";
		//document.Form1.action = '/login.php'
		//document.Form1.modeType.value = 'poll';
		//document.Form1.submit();
		//return false;
	}
	var form = document.getElementById('pollForm');
	var isChecked = false;
	var checkedId = '';
	for(var i = 0; i< form.elements.length; i++){
		if(form.elements[i].checked == true){
			isChecked = true;
			checkedId = checkedId+form.elements[i].value+'_';
		}
	}
	if(!isChecked){
		alert('Lūdzu atzīmējiet savu atbildi!');
	}else
	{
		var moduleItem='<img src="/img/loading.gif">';
		document.getElementById('pollQuiz').innerHTML=moduleItem;
		var myRand=parseInt(Math.random()*99999999);
		var poststr="myRand="+ myRand + "&pollId="+pollId+"&checkedId="+checkedId;
		//alert(poststr);
		var posturl="/submitPoll.php";
		//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {
		//xmlhttp_submitPoll(response); }});
		$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttp_submitPoll(response);}});
	}	
	return false;
}

function xmlhttp_submitPoll(originalRequest)
{
	var retCheck = originalRequest;
	//alert(retCheck);
	if(retCheck){
		var temp=retCheck.split("|||");
		if(temp[0]==1)
		{
			document.getElementById('pollAnswers').innerHTML = temp[1];
			document.getElementById('pollQuiz').style.display='none';
			document.getElementById('pollAnswers').style.display='';
		}
		else
		{
			//document.getElementById('pollAnswers').innerHTML = "fail";
		}
	}
}

function checkTag(id){
	if(document.getElementById('tag_'+id).checked==true){
		document.getElementById('tag_'+id).checked = false;
	}else{
		document.getElementById('tag_'+id).checked = true;
	}
	
	
}

function changeUserGroup(userId, groupId){
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+myRand+"&userId="+userId+"&groupId="+groupId;
	var posturl="/changeUserGroup.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {xmlhttp_changeUserGroup(response);}});
	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttp_changeUserGroup(response);}});
}
function xmlhttp_changeUserGroup(progress){
	var status = progress;
	if(status==1){
		alert(userGroupChange_done);
	}else{
		alert(userGroupChange_fail);
	}
}

function changeUserVoteLimit(userId, voteLimit){
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+myRand+"&userId="+userId+"&voteLimit="+voteLimit;
	var posturl="/users.php";
	$.ajax({type:'POST', url:posturl, data:poststr, success:function(response){xmlhttp_changeUserVoteLimit(response);}});
}
function xmlhttp_changeUserVoteLimit(progress){
	var status = progress;
	if(status==1){
		alert("Veiksmīgi nomainīts");
	}else{
		alert("Kļūda");
	}
}

function prepareResponse(commentId)
{
	document.getElementById('responseOf').value = commentId;
	document.getElementById('comments_description').focus();
	var element = document.getElementById('comments_description');
	ScrollToElement(element);
}

function ScrollToElement(theElement)
{
  var selectedPosX = 0;
  var selectedPosY = 0;
            
  while(theElement != null)
 { 
	selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }						  

 window.scrollTo(selectedPosX-100,selectedPosY-100);
}

function showTooltip(text, element, link)
{
	document.getElementById('tooltip_a').innerHTML = text;
	y = findPos(document.getElementById(element));
	h = document.getElementById(element).offsetHeight;
	document.getElementById('tooltip').style.left = 70;
	document.getElementById('tooltip').style.top = y+h+15;
	document.getElementById('tooltip').style.display = "";
	document.getElementById('tooltip_a').href=link;
}

function hideTooltip()
{
	document.getElementById('tooltip').style.display = "none";
}


function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function showMailBox()
{
	document.getElementById("mailBox").style.display = "";
}

function showWarning(target)
{
	
	if (browserName != 'Microsoft Internet Explorer')
	{
		document.getElementById('warning').style.left = ((document.body.clientWidth-289)/2);
		document.getElementById('warning').style.top = ((document.body.clientHeight-132)/2);
	}
	
	document.getElementById('warning').style.display="";
	targetLink = target;
}

function hideWarning()
{
	document.getElementById('warning').style.display="none";
}

function openTargetTag(age)
{
	window.location.href=window.location.href+'&isAge='+age;
}

function commentEdit(commentId, text)
{
	var comment = document.getElementById('commentText_'+commentId);
	var html = '';
	if(comment)
	{
		if(document.getElementById('commentEditBox_'+commentId)!==null)
			if (text>'') comment.innerHTML = text;
			else comment.innerHTML = document.getElementById('commentEditBox_'+commentId).value;
		else
		{
			var temp = comment.innerHTML; 

			html = '<div style="border: 1px solid #84c2f0; -moz-border-radius: 5px;">'
  			html = html + '<textarea id="commentEditBox_'+commentId+'"  class="ck_edit" >'+temp+'</textarea>';
			html = html + '</div>';
			html = html + '<input type="button" value="Izmainīt" onClick="changeComment('+commentId+');" /><input type="button" value="Atcelt" onClick="commentEdit('+commentId+')" />';
			comment.innerHTML = html;

			CKEDITOR.config.height = '50px';
			CKEDITOR.config.toolbarStartupExpanded = false;
			CKEDITOR.replace( 'commentEditBox_'+commentId );

			//innerHTML = "<textarea  style='width:510px;height:100px;' id='commentEditBox_"+commentId+"'>"+temp+"</textarea><input type='button' value='Izmainīt' onClick='changeComment("+commentId+");' /><input type='button' value='Atcelt' onClick='commentEdit("+commentId+")' />";

			
		}
	}
}
function changeComment(commentId)
{
	var myRand=parseInt(Math.random()*99999999);
	var comment = CKEDITOR.instances['commentEditBox_'+commentId].getData();
	//var comment = document.getElementById('commentEditBox_'+commentId).value;
	//var poststr="myRand="+myRand+"&commentId="+commentId+"&comment="+htmlentities(comment);
	var posturl="/changeComment.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'post', parameters: {myRand: myRand, commentId: commentId, comment:comment}, onComplete:function(response) {xmlhttp_changeComment(response, commentId);}});
	$.ajax({type:'POST', url:posturl, data: {myRand: myRand, commentId: commentId, comment:comment}, success:function(response){xmlhttp_changeComment(response, commentId);}});
}
function xmlhttp_changeComment(progress, commentId)
{
	var status = '';
	var resp = progress.split('|||');
	status = resp[0];
	if(status==1)
		commentEdit(commentId, resp[1]);
	else
		alert('Neizdevās labot komentāru');
}


function commentGalleryEdit(commentId)
{
	var comment = document.getElementById('commentText_'+commentId);
	if(comment)
	{
		if(document.getElementById('commentEditBox_'+commentId)!==null)
			comment.innerHTML = document.getElementById('commentEditBox_'+commentId).value;
		else
		{
			var temp = comment.innerHTML; 
			comment.innerHTML = "<textarea style='width:510px;height:100px;' id='commentEditBox_"+commentId+"'>"+temp+"</textarea><input type='button' value='Izmainīt' onClick='changeGalleryComment("+commentId+");' /><input type='button' value='Atcelt' onClick='commentEdit("+commentId+")' />";
		}
	}
}

function changeGalleryComment(commentId)
{
	var myRand=parseInt(Math.random()*99999999);
	var comment = document.getElementById('commentEditBox_'+commentId).value;
	//var poststr="myRand="+myRand+"&commentId="+commentId+"&comment="+htmlentities(comment);
	var posturl="/changeGalleryComment.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'post', parameters: {myRand: myRand, commentId: commentId, comment:comment}, onComplete:function(response) {xmlhttp_changeGalleryComment(response, commentId);}});
	$.ajax({type:'POST', url:posturl, data:{myRand: myRand, commentId: commentId, comment:comment}, success:function(response){xmlhttp_changeGalleryComment(response, commentId);}});
}

function xmlhttp_changeGalleryComment(progress, commentId)
{
	var status = progress;
	//alert(status);
	if(status==1){
		commentEdit(commentId);
	}else{
		alert('Fail');
	}
}

function addInputFile(nr, parentDivId, name, max){
	if(nr<max){
		var parentDiv = document.getElementById(parentDivId);
		var newDiv = document.createElement('div');
		var newDiv2 = document.createElement('div');
		newDiv.innerHTML = '<input type="file" name="'+name+'['+nr+']" id="'+name+'_'+nr+'" onChange="addInputFile('+(nr+1)+',\''+parentDivId+'\',\''+name+'\','+max+');changeAvailable('+(nr+1)+','+max+');" />';
		parentDiv.appendChild(newDiv);

		newDiv2.innerHTML = '<input style="margin:5px 0 5px 0" type="text" name="title['+nr+']" id="title_'+nr+'" maxlength="50" value="apraksts"  onFocus="if (this.value==\'apraksts\') this.value=\'\'"/>';
		parentDiv.appendChild(newDiv2);
	}
	document.getElementById(name+'_'+(nr-1)).setAttribute('onChange', 'return false;');
}

function addVideoInputFile(nr, parentDivId, name, max)
{
	if(nr<max){
		var parentDiv = document.getElementById(parentDivId);
		var newDiv = document.createElement('div');
		var newDiv2 = document.createElement('div');
		var newDiv3 = document.createElement('div');
		var newDiv4 = document.createElement('div');
		
		newDiv.innerHTML = '<div class="galText2">video fails</div><input type="file" name="'+name+'['+nr+']" id="video_'+nr+'"  />';
		parentDiv.appendChild(newDiv);

		newDiv2.innerHTML = '<div class="galText2">embed</div><input type="text" name="embed['+nr+']" id="embed_'+nr+'"  />';
		parentDiv.appendChild(newDiv2);

		newDiv3.innerHTML = '<div class="galText2">preview bilde</div><input type="file" name="image['+nr+']" id="image_'+nr+'" />';
		parentDiv.appendChild(newDiv3);

		newDiv4.innerHTML = '<div class="galText2">apraksts</div><input style="margin-bottom:10px" type="text" name="title['+nr+']" id="title_'+nr+'" maxlength="50" onChange="addVideoInputFile('+(nr+1)+',\''+parentDivId+'\',\''+name+'\','+max+');changeAvailable('+(nr+1)+','+max+');"/>';
		parentDiv.appendChild(newDiv4);
	}
	document.getElementById(name+'_'+(nr-1)).setAttribute('onChange', 'return false;');
}

function changeAvailable(nr, max)
{
	var elem = document.getElementById('available');
	elem.innerHTML = max-nr;
}

function deleteUserImage(imageId)
{
	if (confirm('Tiešām dzēst?') == true)
	{
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+myRand+"&imageId="+imageId;
	var posturl="/deleteUserImage.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {xmlhttp_deleteUserImage(response, imageId);}});

	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttp_deleteUserImage(response, imageId);}});
	}

}
function xmlhttp_deleteUserImage(response, imageId)
{
	var status = response;
	//alert(status);
	if(status==1)
	{
		document.getElementById('userImage_'+imageId).style.display='none';
		var avail = document.getElementById('available').innerHTML;
		avail++;
		document.getElementById('available').innerHTML = avail;
		if (avail == 24)
			document.getElementById('toProfile').click();
	}
	else
	{
		alert('Fail');
	}
}

function deleteUserVideo(imageId)
{
	var myRand=parseInt(Math.random()*99999999);
	var poststr="myRand="+myRand+"&imageId="+imageId;
	var posturl="/deleteUserVideo.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {xmlhttp_deleteUserVideo(response, imageId);}});
	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){xmlhttp_deleteUserVideo(response, imageId);}});
}

function xmlhttp_deleteUserVideo(response, imageId)
{
	var status = response;
	//alert(status);
	if(status==1)
	{
		document.getElementById('userImage_'+imageId).style.display='none';
		var avail = document.getElementById('available').innerHTML;
		avail++;
		document.getElementById('available').innerHTML = avail;
		if (avail == 5)
			document.getElementById('toProfile').click();
	}
	else
	{
		alert('Fail');
	}
}

function prepareReplyMessage(div_id)
{
	window.location.href='/showMessages.php?replayTo='+div_id;
}

function prepareForwardMessage(div_id)
{
	window.location.href='/showMessages.php?forwardTo='+div_id;
}


function confirm_link(msg, link)
{
	input_box=confirm(msg);
	if (input_box==true)
	{ 
		document.location.href=link;
	}
}

function confirm18(msg,link)
{
	input_box=confirm(msg);
	if (input_box==false)document.location.href=link;
	else {createCookie('18','1',0.02); document.location.href=document.location.href;}
}

function addVideoStats2(articleId, userId, userIp, param)
{
	//alert(articleId+' '+userId+' '+userIp);
	var poststr="userId="+ userId + "&userIp="+userIp+ "&articleId="+articleId+"&param="+param;
	var posturl="/addVideoStats2.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'post', parameters: poststr, onComplete:function(response) { }});
}

function submitForm(name, link)
{
	document.getElementById(name).action=link;
	document.getElementById(name).submit();
}

function mailDeleteConfirm()
{
	input_box=confirm('Tiešām dzēst visas vēstules?');
	if (input_box==true)
	{ 
		window.location.href='/showMessages.php?delete=all';
	}
}

function buyForCookies(cookies)
{
	document.getElementById('cookies').value = cookies;
	document.buy_for_cookies_form.submit();
}

function loadAdvert_1()
{
	var str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="Nerealitate_lv.Spoki.Teksta_reklama.150x150_kreisa" src="\'+location.protocol+\'//nerealitatelv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=3KWmlD.78o5Vts.gulmicGCP7f2vDZu__XVbMUt5ler.h7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	eval(str);
}

function loadAdvert_2()
{
	
	var str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="Nerealitate_lv.Spoki.Visas_lapas.Kreisas_malas_tornis" src="\'+location.protocol+\'//nerealitatelv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=pXla4AAjUy8O880IlY.xwAcMrojQdRtDF3u7EVEfdUT.E7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	eval(str);
}

function loadAdvert_3(ageLimit)
{
	if (ageLimit == 0)
		str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="apollo_lv.spoki.spoki_VP.180x150 #1" src="\'+location.protocol+\'//s1.apollolv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=3jsBzxadb.NHQtcCvMD_wQ78LT5pDuc0UB9VVaFMk8f.l7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	else
		str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="apollo_lv.spoki.spoki_18.180x150 #1" src="\'+location.protocol+\'//s1.apollolv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=.BigifB4l9hqMUcZ1nxF_h5WjG_xOp.LoKzvfiZ2.vn.67/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	eval(str);
}

function loadAdvert_nrlt()
{
	var str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="Nerealitate_lv.Spoki.Visas_lapas.Labas_malas_180x150" src="\'+location.protocol+\'//nerealitatelv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=oIUKKcvwo2mUq5zxvtfBmgP0ngiSoHrEjJ7rBHInhwn.R7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	eval(str);
}

function loadAdvert_4(ageLimit)
{
	if (ageLimit == 0)
		str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="apollo_lv.spoki.spoki_VP.180x150 #2" src="\'+location.protocol+\'//s1.apollolv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=YcfnK989d62Enbx.xdYxYaScXQ0i6MdDn6hFv8_qcYH.w7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	else
		str = 'if(location.protocol.substr(0,4)==\'http\')document.write(unescape(\'%3C\')+\'script id="apollo_lv.spoki.spoki_VP.180x150 #2" src="\'+location.protocol+\'//s1.apollolv.adocean.pl/_\'+(new Date()).getTime()+\'/ad.js?id=YcfnK989d62Enbx.xdYxYaScXQ0i6MdDn6hFv8_qcYH.w7/x=\'+screen.width+\'/y=\'+screen.height+\'" type="text/javascript"\'+unescape(\'%3E%3C\')+\'/script\'+unescape(\'%3E\'));';
	eval(str);
}


function favorite(articleId,mode)
{
	var poststr="articleId="+articleId+"&mode="+mode;
	//alert(poststr);
	var posturl="/favorites.php";
	//var myAjax = new Ajax.Request(posturl, {method: 'get', parameters: poststr, onComplete:function(response) {favorite_resp(response,mode);}});
	$.ajax({type:'GET', url:posturl, data:poststr, success:function(response){favorite_resp(response,mode);}});
}

function favorite_resp(response, mode)
{
	var status = response;
	//alert(status);
	if (status=='0')
	{
		if (mode=='add') alert('Raksts pievienots favorītiem!');
	}
	else
		if (status=='2') window.location.href='/login.php';
}

function do_attack(user)
{
	input_box=confirm('Tiešām uzbrukt?');
	if (input_box==true)
	{ 
		
	
	
	var form = document.createElement("form");
	form.method='post';
	form.action='/user_cr_attack.php';

	var input = document.createElement("input");
	input.name = 'cr_defender';
	input.type='hidden';
	input.value = user;

	form.appendChild(input);

	var div = document.getElementById('top');
	div.appendChild(form);

	form.submit();

	}
}

function DraugiemSay( title, url, titlePrefix ){
 window.open(
  'http://www.draugiem.lv/say/ext/add.php?title=' + encodeURIComponent( title ) +
  '&link=' + encodeURIComponent( url ) +
  ( titlePrefix ? '&titlePrefix=' + encodeURIComponent( titlePrefix ) : '' ),
  '',
  'location=1,status=1,scrollbars=0,resizable=0,width=530,height=400'
 );
 return false;
}

function setOldMethod()
{
	document.getElementById('image_loader_new').style.display = 'none';
	document.getElementById('image_loader_old').style.display = '';
	document.getElementById('upload_method').value='old';
}

function drawDaySelect()
{
	var str = '';
	var i=0;
	str = '<select name="day" style="width: 90px;">';
	str = str + '<option value="1">1</option>';
	for (i=2; i<=31; i++)
		str = str + '<option value="'+i+'">'+i+'</option>';
	str = str + '</select>';

	document.write(str);
}

function drawMonthSelect()
{
	var mon_arr = Array();
	mon_arr[1] = 'Janvāris';
	mon_arr[2] = 'Februāris';
	mon_arr[3] = 'Marts';
	mon_arr[4] = 'Aprīlis';
	mon_arr[5] = 'Maijs';
	mon_arr[6] = 'Jūnijs';
	mon_arr[7] = 'Jūlijs';
	mon_arr[8] = 'Augusts';
	mon_arr[9] = 'Septembris';
	mon_arr[10] = 'Oktobris';
	mon_arr[11] = 'Novembris';
	mon_arr[12] = 'Decembris';

	var str = '';
	var i=0;
	str = '<select name="month" style="width: 90px;">';
	str = str + '<option value="1">Janvāris</option>';
	for (i=2; i<=12; i++)
		str = str + '<option value="'+i+'">'+mon_arr[i]+'</option>';
	str = str + '</select>';

	document.write(str);
}

function drawYearSelect()
{
	var str = '';
	var i=0;
	str = '<select name="year" style="width: 90px;">';
	str = str + '<option value="2009">2009</option>';
	for (i=2008; i>=1909; i--)
		str = str + '<option value="'+i+'">'+i+'</option>';
	str = str + '</select>';

	document.write(str);
}

function showItemInfo(id, data)
{	
	//alert(id+' '+data);
	var el = document.getElementById(id);
	var dataArr = data.split('||');

	var tooltip = document.getElementById('itemInfo');
	tooltip.innerHTML = 'aa';

	var pos = findPos(el);

	var totalX = pos[0];
	if (pos[0]+30+205 > screen.width) totalX = screen.width-205-30;

	tooltip.style.left = totalX;
	tooltip.style.top = pos[1]+30;
	tooltip.style.display = '';

}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
	//return curtop;
}

function hideItemInfo()
{
	document.getElementById('itemInfo').style.display = 'none';
}

function fade_in(element, opacity, max) {
	var reduceOpacityBy = 5;
	var rate = 30;	// 15 fps

	if (opacity < max) {
		opacity += reduceOpacityBy;
		if (opacity > max) {
			opacity = max;
		}

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (opacity < max) {
		setTimeout(function () {
			fade_in(element, opacity, max);
		}, rate);
	}
}

function showMore(hide, show)
{
	document.getElementById(hide).style.display='none';
	var el = document.getElementById(show);
	el.style.opacity = 0;
	el.style.display = '';
	fade_in(el, 0, 100);
}

function openShopDialog(id, icon, name, price, price_type, uniq_name)
{
	var d = document.getElementById('shopDialog');
	var ico = document.getElementById('shopIcon_'+id);

	document.getElementById('buyIcon').src=icon;
	document.getElementById('buyTitle').innerHTML=name;

	var priceStr = '';
	if (price_type=='cookies') priceStr = price+' cepumi';
	else priceStr = price+' Ls';
	document.getElementById('buyPrice').innerHTML='Cena: '+priceStr;

	document.getElementById('buyId').value=id;

	document.getElementById('colorInput').style.display='none';
	document.getElementById('avatarInput').style.display='none';
	document.getElementById('nickInput').style.display='none';
	document.getElementById('nickInput2').style.display='none';
	document.getElementById('articleInput').style.display='none';

	if (uniq_name=='zimulis')
	{
		document.getElementById('colorInput').style.display='';
	}
	if (uniq_name=='avatars')
	{
	    document.getElementById('avatarInput').style.display='';
	}
	if (uniq_name=='niks')
	{
		document.getElementById('nickInput').style.display='';
	}
	if (uniq_name=='sirds' || uniq_name=='sirds2')
	{
		document.getElementById('nickInput2').style.display='';
	}
	if (uniq_name=='pacelt' || uniq_name=='izcelt')
	{
		document.getElementById('articleInput').style.display='';
		document.getElementById('articleUrl').readOnly=false;
	}
	
	var pos = findPos(ico);

	d.style.left = pos[0]+200;
	d.style.top = pos[1]-50;
	
	d.style.opacity = 0;
	d.style.display = '';
	fade_in(d, 0, 100);
}

function closeShopDialog()
{
	var d = document.getElementById('shopDialog');
	d.style.display='none';
}

function openSimpleShopDialog(msg, id)
{
	var d = document.getElementById('simpleShopDialog');
	document.getElementById('simpleTitle').innerHTML = msg;
	var ico = document.getElementById('shopIcon_'+id);

	var pos = findPos(ico);
	d.style.left = pos[0]+200;
	d.style.top = pos[1]-20;
	
	d.style.opacity = 0;
	d.style.display = '';
	fade_in(d, 0, 100);
}

function openDropDialog(id, name)
{
	var d = document.getElementById('dropDialog');
	document.getElementById('dropTitle').innerHTML = 'Vai tiešām gribi atteikties no spējas "'+name+'" ?';
	var ico = document.getElementById('shopIcon_'+id);

	document.getElementById('dropId').value = id;

	var pos = findPos(ico);
	d.style.left = pos[0]+200;
	d.style.top = pos[1]-20;
	
	d.style.opacity = 0;
	d.style.display = '';
	fade_in(d, 0, 100);
}

function closeDropDialog()
{
	var d = document.getElementById('dropDialog');
	d.style.display='none';
}

function closeSimpleShopDialog()
{
	var d = document.getElementById('simpleShopDialog');
	d.style.display='none';
}

function showStatBox(id)
{
	var i=0;
	for (i=1; i<=4; i++)
	{
		if (i != id) document.getElementById('prof_stat_'+i).style.display='none';
		else 
		{
			var el = document.getElementById('prof_stat_'+i);
			el.style.opacity = 0;
			el.style.display = '';
			fade_in(el, 0, 100);
		}
	}
}

function setEditor()
{
	var wrapper = document.getElementById('editorWrapper');
	var box = document.getElementById('editorBox');
	var pos = findPos(wrapper);

	box.style.left = pos[0];
	box.style.top = pos[1];
	box.style.display = '';
}

function showNextVideoInput()
{
	if (utube<5)
	{
		utube++;

		var src = document.getElementById('utube1_wrapper');
		var dest = document.getElementById('utube'+utube+'_wrapper_in');
		var global = document.getElementById('utube'+utube+'_wrapper');

		if (navigator.appName=="Microsoft Internet Explorer")
		{
			dest.innerHTML = src.innerHTML;
			dest.childNodes[4].style.display='none';
			dest.childNodes[2].style.display='none';
			dest.childNodes[0].childNodes[0].childNodes[0].childNodes[0].id='utube'+utube;
			dest.childNodes[0].childNodes[0].childNodes[0].childNodes[0].name='utube'+utube;
			document.getElementById('utube'+utube).value='';
		}
		else
		{
			dest.innerHTML = src.innerHTML;
			dest.childNodes[5].style.display='none';
			dest.childNodes[3].style.display='none';
			dest.childNodes[1].childNodes[0].childNodes[0].childNodes[0].id='utube'+utube;
			dest.childNodes[1].childNodes[0].childNodes[0].childNodes[0].name='utube'+utube;
		}

		global.style.display = '';

	}
}

function checkUserField(what)
{
	var value = document.getElementById(what).value;

	var return_el = document.getElementById(what+'_return');
	
	var resp = '';
	$.ajax({url:'/checkUserData.php',data:what+'='+value, success:function(response){resp = response;}, async: false});	

	var sp = document.getElementById('username_comment');
	if (resp=='1')
	{
		return_el.src = "/img/accept.png";
		sp.innerHTML = '';
		sp.style.color = 'green';
	}
	else
	{
		return_el.src = "/img/denied.png";
		sp.innerHTML = 'izvēlies citu vārdu';
		sp.style.color = 'red';
	}
}

function selectSetItems(str)
{
	var items = str.split('||||');
	for (i=1; i<=3; i++)
	{
		var select = document.getElementById("showItem"+i);
		var optionCount = select.options.length;
		for (j=0; j<optionCount; j++)
		{
			if (select.options[j].value==items[i-1])
			{
				select.options[j].selected = true;
				break;
			}
		}
	}
}

function switch_tabs(id)
{
	if (id=='tab_2') window.location.href="http://speles.spoki.lv";
}


function dateDiff(d)
{
	var now = new Date();
	var zoneOffset = now.getTimezoneOffset();
	var retStr = '';

	now = Math.round(now.getTime()/1000);
	var diff = strtotime(d)-now+(zoneOffset*60);
	
	if (diff-(zoneOffset*60)>86400) retStr = 'daudz';
	else
		if (diff-(zoneOffset*60)>0) retStr = date('H:i:s',diff);
		else retStr = 'beidzies';
		
	return retStr;
}

function auction_countdown(elem)
{
	var str = document.getElementById('ach_'+elem).value;
		
	var newStr = dateDiff(str);
	document.getElementById('ac_'+elem).innerHTML = newStr;

	if (newStr != 'daudz' && newStr != 'beidzies') setTimeout("auction_countdown("+elem+")", 1000);

}
function strip_tags (str, allowed_tags) 
{

    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';

    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };

    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }

    str += '';

    matches = str.match(/(<\/?[\S][^>]*>)/gi);

    for (key in matches) {
        if (isNaN(key)) {
            continue;
        }

        html = matches[key].toString();

        allowed = false;

        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); 
        }
    }

    return str;
}


function commentReply(id)
{
	var t = document.getElementById('commentText_'+id).innerHTML;
	var a = document.getElementById('commentAuthor_'+id).innerHTML;
	var use = '';
	if (t.indexOf('atbildot uz')>-1)
	{
		var i = t.indexOf('</em>');
		use = t.substring(i+5, t.length);
	}
	else
	{
		use = t;
	}

	use = strip_tags(use);
	if (use.length>50) use = use.substring(0,47)+'...';
	var resp = '<em>atbildot uz '+a+' komentāru "'+use+' "</em><br><br><br>';
	
	
	CKEDITOR.instances.comments_description.setData(resp);
	CKEDITOR.instances.comments_description.focus();
	var element = document.getElementById('commentBlock');
	ScrollToElement(element);
	//document.getElementById('responseOf').value = id;
}

$(document).ready(function()
{
  $("#cat_list a").live('click', function(){ save_click('cat_list', this.href);});
  $("#content_r a").live('click', function(){ save_click('content_r', this.href);});
  $("#top a").live('click', function(){ save_click('top', this.href);}); 
  $("#drlv a").live('click', function(){ save_click('article', 'draugiem');}); 
  $("#twit a").live('click', function(){ save_click('article', 'twitter');}); 
  $("#friend a").live('click', function(){ save_click('article', 'pastasti-draugam');}); 
  $("#selfAdverts a").live('click', function(){ save_click('article', 'lasi-vel');}); 
  $(".search_btn").live('click', function(){ save_click('content_r', 'search_btn');});
  $("#a_item_shop").live('click', function(){ save_click('profile_menu', 'item_shop');});
});

function save_click(box, link)
{
	var loc = window.location.href;
	var posturl = '/click_stats.php';
	var poststr = 'box='+box+'&link='+link+'&location='+loc;
	$.ajax({async:false, type:'POST', url:posturl, data:poststr, success:function(response){}});	
}

function closeBanner(id)
{
	var divs = document.body.getElementsByTagName('div');
	var s = divs.length;
	var j = 0;
	for(i=s-1; i>=0;i--)
	{
		var str = divs[i].id;
		if (str.substring(0,3)=='ox_')
		{
			divs[i].style.display='none';
			j++;
		}
		if (j>=2) break;
	}
}