function hideValue(what, def)
{
	if(trim(what.value) == def)
	{
		what.value = "";
	}
	return;
}

function showValue(what, def)
{
	if(trim(what.value) == '')
	{
		what.value = def;
	}
	return;
}

// Removes leading whitespaces
function LTrim( value )
{
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value )
{
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value )
{
	return LTrim(RTrim(value));
	
}

function loadImages(path, pics)
{
	pics_arr = pics.split(',');
	for(i=0; i < pics_arr.length; i++)
	{
		eval('c' + i + ' = new Image();');
		eval('c' + i + '.src = path + "' + pics_arr[i] + '";');
	}
}

function changeBgck(what, img)
{
	document.getElementById(what).style.backgroundImage = "url('"+img+"')";
	//document.getElementById(what).style.backgroundPosition = 'middle';
}

function preloadImages(img_array)
{
	pics_array = img_array.split(',');
	for(i = 0; i < pics_array.length; i++)
	{
		eval("c"+i+" = new Image; c"+i+".src = pics_array[i];");
	}
}

var timer_id;
var direction=0;
var curr = 0;
function scroll_iframe(frm,inc,dir)
{
  if (timer_id) clearTimeout(timer_id);
  if (window.frames[frm])
  {
    if (direction == 0)
    {
    	curr += inc;
    	window.frames[frm].scrollBy(0, inc);
    	if(curr >= window.frames[frm].document.body.offsetHeight)
    	{
    		direction = 1;
    		curr = window.frames[frm].document.body.offsetHeight;
    	}
    }
    else if (direction == 1)
    {
    	curr -= inc;
    	window.frames[frm].scrollBy(0, -inc);
    	if(curr <= 0)
    	{
    		direction = 0;
    		curr = 0;
    	}
    }
    //else window.frames[frm].scrollBy(inc, 0);
    timer_id = setTimeout("scroll_iframe('" + frm + "'," + inc + ",'" + dir + "')", 5);
  }
}

function stopScroll()
{
	if (timer_id) clearTimeout(timer_id);
}

function change_class(tid, cfg)
{
	if(cfg == 1) newclass = 'admin_button';
	else if(cfg == 2) newclass = 'admin_button_over';
	
	//var dtarget = document.getElementById(tid);
	
	tid.className = newclass;
}

Array.prototype.in_array = function ( obj )
{
	var len = this.length;
	for ( var x = 0 ; x <= len ; x++ )
	{
		if ( this[x] == obj ) return true;
	}
	return false;
}

function checkForm(formname, fields_array, errors_array)
{
	eval("var reg = document." + formname + ";");
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.' + formname + '.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	reg.submit();
}

function check_video_title()
{
	var vtitle = document.getElementById("videoTitle");
	var vtext = document.getElementById("videoText");
	
	if( trim(vtitle.value) != '' && trim(vtext.value) != '' )
	{
		document.getElementById("player").style.display = '';
		document.getElementById("url_video").style.display = '';
	}
	else
	{
		document.getElementById("player").style.display = 'none';
		document.getElementById("url_video").style.display = 'none';
	}
}

function startUpload()
{
	if(document.getElementById("details_div")) document.getElementById("details_div").style.display = 'none';
}

function cancelUpload()
{
	if(document.getElementById("details_div")) document.getElementById("details_div").style.display = '';
}

function submitVideo(val)
{
	document.getElementById('vname').value = val;
	document.addVideo.submit();
}

function voteForVideo(video_id)
{
	var pars = 'do=1&video_id=' + video_id + '&vote=' + document.getElementById('vote').value;
	
	new Ajax.Request('http://www.izvanzemni.com/ajax/video_vote.php', { method:'post', postBody: pars, onSuccess: function(transport)
		{
			document.getElementById('rating_count').style.width = transport.responseText + 'px';
		} });
	
	document.getElementById('voting_block').style.display = 'none';
}

function voteForArticle(article_id, vote)
{
	var pars = 'do=1&article_id=' + article_id + '&vote=' + vote;
	
	new Ajax.Updater('article_votes', 'http://www.izvanzemni.com/ajax/article_vote.php', { method:'post', postBody: pars, onSuccess: function()
		{
			if(vote == 'up') document.getElementById('voting_block').innerHTML = '<span class="green bold">дадохте позитивен глас</span>';
			else if(vote == 'down') document.getElementById('voting_block').innerHTML = '<span class="red bold">дадохте негативен глас</span>';
		} });
	
	//document.getElementById('voting_block').style.display = 'none';
}

function voteForTranslation(translation_id, vote)
{
	var pars = 'do=1&translation_id=' + translation_id + '&vote=' + vote;
	
	new Ajax.Updater('translation_votes', 'http://www.izvanzemni.com/ajax/translation_vote.php', { method:'post', postBody: pars, onSuccess: function()
		{
			if(vote == 'up') document.getElementById('voting_block').innerHTML = '<span class="green bold">дадохте позитивен глас</span>';
			else if(vote == 'down') document.getElementById('voting_block').innerHTML = '<span class="red bold">дадохте негативен глас</span>';
		} });
	
	//document.getElementById('voting_block').style.display = 'none';
}

function voteForExperience(experience_id, vote)
{
	var pars = 'do=1&experience_id=' + experience_id + '&vote=' + vote;
	
	new Ajax.Updater('experience_votes', 'http://www.izvanzemni.com/ajax/experience_vote.php', { method:'post', postBody: pars, onSuccess: function()
		{
			if(vote == 'up') document.getElementById('voting_block').innerHTML = '<span class="green bold">дадохте позитивен глас</span>';
			else if(vote == 'down') document.getElementById('voting_block').innerHTML = '<span class="red bold">дадохте негативен глас</span>';
		} });
	
	//document.getElementById('voting_block').style.display = 'none';
}

function voteForGallery(gallery_id, vote)
{
	var pars = 'do=1&gallery_id=' + gallery_id + '&vote=' + vote;
	
	new Ajax.Updater('gallery_votes', 'http://www.izvanzemni.com/ajax/gallery_vote.php', { method:'post', postBody: pars, onSuccess: function()
		{
			if(vote == 'up') document.getElementById('voting_block').innerHTML = '<span class="green bold">дадохте позитивен глас</span>';
			else if(vote == 'down') document.getElementById('voting_block').innerHTML = '<span class="red bold">дадохте негативен глас</span>';
		} });
	
	//document.getElementById('voting_block').style.display = 'none';
}

function setHomepage(what)
{
	if (document.all)
	{
		what.style.behavior='url(#default#homepage)';
		what.setHomePage('http://www.izvanzemni.com/');
	}
	else if (window.sidebar)
	{
		if(window.netscape)
		{
			try
			{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}  
			catch(e)
			{
				var msg = "Това действие е забранено от Вашия браузер. Ако искате да го активирате, моля въведете 'about:config' в адресната линия, и сменете стойноста на 'signed.applets.codebase_principal_support' на 'true'";
				showLightboxAlert(msg, 'Грешка', '');
			}
		}
	}
}

function checkPA(picnum)
{
	var tar = document.getElementById('pa' + picnum);
	
	if(tar)
	{
		if(tar.checked) tar.checked = false;
		else tar.checked = true;
	}
}

function write_comment()
{
	if(document.getElementById('write_comment_holder').style.display == '') Effect.BlindUp('write_comment_holder');
	else Effect.BlindDown('write_comment_holder');
}

function reply_comment(comment_id)
{
	if(document.getElementById('comment_reply_form_' + comment_id).style.display == '') Effect.BlindUp('comment_reply_form_' + comment_id);
	else Effect.BlindDown('comment_reply_form_' + comment_id);
}

function comment_replies(comment_id)
{
	if(document.getElementById('comment_replies_holder_' + comment_id).style.display == '') Effect.BlindUp('comment_replies_holder_' + comment_id);
	else Effect.BlindDown('comment_replies_holder_' + comment_id);
}

function checkComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) == '')
	{
		showLightboxAlert('Въведете коментар.', 'Грешка', 'document.commentform.comment.focus();');
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		showLightboxAlert('Въведете кодът за сигурност.', 'Грешка', 'document.commentform.verify_code.focus();');
		return false;
	}
	
	var pars = 'do=1&article_id=' + reg.article_id.value + '&comment=' + reg.comment.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_article_comment.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image').src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				write_comment();
				
				getArticleComments(reg.article_id.value, 1);
			}
		} });
}

function getArticleComments(article_id, pageID)
{
	var pars = 'do=1&article_id=' + article_id + '&pageID=' + pageID;
	new Ajax.Updater('comments_holder', 'http://www.izvanzemni.com/ajax/get_article_comments.php', {method:'post', postBody:pars, evalScripts:true});
}

function checkTranslationComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) == '')
	{
		showLightboxAlert('Въведете коментар.', 'Грешка', 'document.commentform.comment.focus();');
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		showLightboxAlert('Въведете кодът за сигурност.', 'Грешка', 'document.commentform.verify_code.focus();');
		return false;
	}
	
	var pars = 'do=1&translation_id=' + reg.translation_id.value + '&comment=' + reg.comment.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_translation_comment.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image').src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				write_comment();
				
				getTranslationComments(reg.translation_id.value, 1);
			}
		} });
}

function getTranslationComments(translation_id, pageID)
{
	var pars = 'do=1&translation_id=' + translation_id + '&pageID=' + pageID;
	new Ajax.Updater('comments_holder', 'http://www.izvanzemni.com/ajax/get_translation_comments.php', {method:'post', postBody:pars, evalScripts:true});
}

function checkExperienceComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) == '')
	{
		showLightboxAlert('Въведете коментар.', 'Грешка', 'document.commentform.comment.focus();');
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		showLightboxAlert('Въведете кодът за сигурност.', 'Грешка', 'document.commentform.verify_code.focus();');
		return false;
	}
	
	var pars = 'do=1&experience_id=' + reg.experience_id.value + '&comment=' + reg.comment.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_experience_comment.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image').src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				write_comment();
				
				getExperienceComments(reg.experience_id.value, 1);
			}
		} });
}

function getExperienceComments(experience_id, pageID)
{
	var pars = 'do=1&experience_id=' + experience_id + '&pageID=' + pageID;
	new Ajax.Updater('comments_holder', 'http://www.izvanzemni.com/ajax/get_experience_comments.php', {method:'post', postBody:pars, evalScripts:true});
}

function checkVideoComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) == '')
	{
		showLightboxAlert('Въведете коментар.', 'Грешка', 'document.commentform.comment.focus();');
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		showLightboxAlert('Въведете кодът за сигурност.', 'Грешка', 'document.commentform.verify_code.focus();');
		return false;
	}
	
	var pars = 'do=1&video_id=' + reg.video_id.value + '&comment=' + reg.comment.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_video_comment.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image').src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				write_comment();
				
				getVideoComments(reg.video_id.value, 1);
			}
		} });
}

function getVideoComments(video_id, pageID)
{
	var pars = 'do=1&video_id=' + video_id + '&pageID=' + pageID;
	new Ajax.Updater('comments_holder', 'http://www.izvanzemni.com/ajax/get_video_comments.php', {method:'post', postBody:pars, evalScripts:true});
}

function checkCommentReply(crtype, comment_id)
{
	eval("var reg = document.addanswer" + comment_id + ";");
	
	if(trim(reg.cmanswer.value) == '')
	{
		showLightboxAlert('Въведете отговор.', 'Грешка', 'document.addanswer'+ comment_id + '.cmanswer.focus();');
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		showLightboxAlert('Въведете кодът за сигурност.', 'Грешка', 'document.addanswer'+ comment_id + '.verify_code.focus();');
		return false;
	}
	
	var pars = 'do=1&crtype=' + crtype + '&comment_id=' + comment_id + '&reply=' + reg.cmanswer.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_comment_reply.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image' + comment_id).src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				reply_comment(comment_id);
				
				var pars = 'do=1&crtype=' + crtype + '&comment_id=' + comment_id;
				new Ajax.Updater('comment_replies_holder_' + comment_id, 'http://www.izvanzemni.com/ajax/get_comment_replies.php', {method:'post', postBody:pars, evalScripts:true, onSuccess:function()
					{
						if(document.getElementById('comment_replies_holder_' + comment_id).style.display == 'none') Effect.BlindDown('comment_replies_holder_' + comment_id);
					}
				});
			}
		} });
	
	return false;
}

function addGalleryUrlPic()
{
	var reg = document.add_gallery;
	
	if(trim(reg.pic_url.value) == '')
	{
		showLightboxAlert('Въведете URL адрес към снимката, която искате да добавите.', 'Грешка', 'document.add_gallery.pic_url.focus();');
		return false;
	}
	
	var rand = parseInt(777 * Math.random(0, 1));
	var pars = 'img=' + reg.pic_url.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/check_image.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(transport.responseText != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			
			reg.pics_count.value = parseInt(reg.pics_count.value) + 1;
			
			//create image
			var npic = document.createElement('img');
			npic.id = 'pic_' + reg.pics_count.value;
			npic.style.position = 'static';
			npic.style.cssFloat = 'left';
			npic.style.styleFloat = 'left';
			npic.style.width = 100 + 'px';
			npic.style.height = 75 + 'px';
			npic.style.border = '#709aad 1px solid';
			npic.src = reg.pic_url.value;
			npic.setAttribute('alt', 'Снимка ' + reg.pics_count.value);
			npic.style.marginRight = 10 + 'px';
			/*npic.style.marginTop = 10 + 'px';*/
			npic.style.marginBottom = 10 + 'px';
			
			//create close div
			var ncdiv = document.createElement('div');
			ncdiv.id = 'div_c' + reg.pics_count.value;
			ncdiv.style.position = 'relative';
			ncdiv.style.cssFloat = 'left';
			ncdiv.style.styleFloat = 'left';
			ncdiv.style.width = 16 + 'px';
			ncdiv.style.height = 16 + 'px';
			ncdiv.style.padding = '2px 2px 0px 2px';
			ncdiv.style.marginTop = '-87px';
			ncdiv.style.backgroundColor = '#ffffff';
			ncdiv.style.borderBottom = '#cacaca 1px solid';
			ncdiv.style.borderRight = '#cacaca 1px solid';
			ncdiv.innerHTML = '<a href="javascript:void(0);" onclick="removeGalleryUrlPic(\'' + reg.pics_count.value + '\');"><img src="http://www.izvanzemni.com/images/default/drop.png" alt="Изтрий снимка ' + reg.pics_count.value + '" style="border:0px;"/></a>';
			
			//create hidden input
			var new_fel = document.createElement('input');
			new_fel.id = 'url_pic_' + reg.pics_count.value;
			new_fel.name = 'url_pic_' + reg.pics_count.value;
			new_fel.setAttribute('name', 'url_pic_' + reg.pics_count.value);
			new_fel.setAttribute('type', 'hidden');
			new_fel.value = reg.pic_url.value;
			new_fel.setAttribute('value', reg.pic_url.value);
			
			//create div holder
			var ndiv = document.createElement('div');
			ndiv.id = 'div_m' + reg.pics_count.value;
			ndiv.style.position = 'static';
			ndiv.style.cssFloat = 'left';
			ndiv.style.styleFloat = 'left';
			ndiv.style.width = 110 + 'px';
			
			//visualize on page
			ndiv.appendChild(new_fel);
			ndiv.appendChild(npic);
			ndiv.appendChild(ncdiv);
			document.getElementById('url_pics_holder').appendChild(ndiv);
			
			reg.pic_url.value = '';
		}});
}

function removeGalleryUrlPic(pid)
{
	var reg = document.add_gallery;
	
	var tdiv = document.getElementById('div_m' + pid);
	if(tdiv)
	{
		document.getElementById('url_pics_holder').removeChild(tdiv);
		
		if(reg.pics_count.value == pid) parseInt(reg.pics_count.value) - 1
	}
}

function IsImageOk(img)
{
	if(!img.complete)
	{
		return false;
	}
	
	if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
	{
		return false;
	}
	
	return true;
}

function picbrowse(what)
{
	var fbtn = document.getElementById('pic_pc_fake');
	if(fbtn)
	{
		fbtn.value = what;
	}
}

function picbrowse_small(what)
{
	var fbtn = document.getElementById('pic_pc_fake_small');
	if(fbtn)
	{
		fbtn.value = what;
	}
}

function remoteUploadPic()
{
	var reg = document.remote_upload_form;
	
	if(trim(reg.pic_pc.value) == '')
	{
		showLightboxAlert('Изберете снимка от компютърът си, която искате да добавите.', 'Грешка', '');
		return false;
	}
	
	//document.getElementById('upload_target').onload = function() { addGalleryPcPic(); };
	
	reg.submit();
}

function addGalleryPcPic(what)
{
	if(trim(what) == '') return false;
	
	var tiframe = document.getElementById('upload_target');
	var ret = tiframe.contentWindow.document.body.innerHTML;
	var reg = document.add_gallery;
	var reg_upl = document.remote_upload_form;
	
	if(trim(ret) == '')
	{
		showLightboxAlert('Невалидна снимка.', 'Грешка', '');
		return false;
	}
	
	var rand = parseInt(777 * Math.random(0, 1));
	var pars = 'img=' + ret;
	new Ajax.Request('http://www.izvanzemni.com/ajax/check_image.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(transport.responseText != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			
			reg.pics_count.value = parseInt(reg.pics_count.value) + 1;
			
			//create image
			var npic = document.createElement('img');
			npic.id = 'pic_' + reg.pics_count.value;
			npic.style.position = 'static';
			npic.style.cssFloat = 'left';
			npic.style.styleFloat = 'left';
			npic.style.width = 100 + 'px';
			npic.style.height = 75 + 'px';
			npic.style.border = '#709aad 1px solid';
			npic.src = ret;
			npic.setAttribute('alt', 'Снимка ' + reg.pics_count.value);
			npic.style.marginRight = 10 + 'px';
			/*npic.style.marginTop = 10 + 'px';*/
			npic.style.marginBottom = 10 + 'px';
			
			//create close div
			var ncdiv = document.createElement('div');
			ncdiv.id = 'div_c' + reg.pics_count.value;
			ncdiv.style.position = 'relative';
			ncdiv.style.cssFloat = 'left';
			ncdiv.style.styleFloat = 'left';
			ncdiv.style.width = 16 + 'px';
			ncdiv.style.height = 16 + 'px';
			ncdiv.style.padding = '2px 2px 0px 2px';
			ncdiv.style.marginTop = '-87px';
			ncdiv.style.backgroundColor = '#ffffff';
			ncdiv.style.borderBottom = '#cacaca 1px solid';
			ncdiv.style.borderRight = '#cacaca 1px solid';
			ncdiv.innerHTML = '<a href="javascript:void(0);" onclick="removeGalleryUrlPic(\'' + reg.pics_count.value + '\');"><img src="http://www.izvanzemni.com/images/default/drop.png" alt="Изтрий снимка ' + reg.pics_count.value + '" style="border:0px;"/></a>';
			
			//create hidden input
			var new_fel = document.createElement('input');
			new_fel.id = 'url_pic_' + reg.pics_count.value;
			new_fel.name = 'url_pic_' + reg.pics_count.value;
			new_fel.setAttribute('name', 'url_pic_' + reg.pics_count.value);
			new_fel.setAttribute('type', 'hidden');
			new_fel.value = ret;
			new_fel.setAttribute('value', ret);
			
			//create div holder
			var ndiv = document.createElement('div');
			ndiv.id = 'div_m' + reg.pics_count.value;
			ndiv.style.position = 'static';
			ndiv.style.cssFloat = 'left';
			ndiv.style.styleFloat = 'left';
			ndiv.style.width = 110 + 'px';
			
			//visualize on page
			ndiv.appendChild(new_fel);
			ndiv.appendChild(npic);
			ndiv.appendChild(ncdiv);
			document.getElementById('url_pics_holder').appendChild(ndiv);
			
			reg_upl.reset();
		}});
}

function submitForm(formname)
{
	eval("var reg = document." + formname + ";");
	
	reg.submit();
}

function checkGalleryForm(formname)
{
	var min_pics_in_gallery = parseInt(5);
	eval("var reg = document." + formname + ";");
	
	if(reg.pics_count.value < min_pics_in_gallery)
	{
		alert('Изберете поне ' + min_pics_in_gallery + ' снимки за галерията.');
		reg.pics_count.focus();
		return false;
	}
	
	reg.submit();
}

function checkGalleryComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) == '')
	{
		alert('Въведете коментар.');
		reg.comment.focus();
		return false;
	}
	else if(trim(reg.verify_code.value) == '')
	{
		alert('Въведете кодът за сигурност.');
		reg.verify_code.focus();
		return false;
	}
	
	var pars = 'do=1&gallery_id=' + reg.gallery_id.value + '&comment=' + reg.comment.value + '&verify_code=' + reg.verify_code.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/put_gallery_comment.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(trim(transport.responseText) != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			else
			{
				document.getElementById('verify_code_image').src = 'http://www.izvanzemni.com/captcha.php';
				reg.reset();
				write_comment();
				
				getGalleryComments(reg.gallery_id.value, 1);
			}
		} });
}

function getGalleryComments(gallery_id, pageID)
{
	var pars = 'do=1&gallery_id=' + gallery_id + '&pageID=' + pageID;
	new Ajax.Updater('comments_holder', 'http://www.izvanzemni.com/ajax/get_gallery_comments.php', {method:'post', postBody:pars, evalScripts:true});
}

function addArticleUrlPic(formname)
{
	eval("var reg = document." + formname + ";");
	
	if(trim(reg.pic_url.value) == '')
	{
		showLightboxAlert('Въведете URL адрес към снимката, която искате да добавите.', 'Грешка', 'document.add_article.pic_url.focus();');
		return false;
	}
	
	var rand = parseInt(777 * Math.random(0, 1));
	var pars = 'img=' + reg.pic_url.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/check_image.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(transport.responseText != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			
			var dhl = document.createElement('div');
			dhl.className = 'url_images_list';
			dhl.setAttribute('class','url_images_list');
			dhl.innerHTML = '<label for="pa'+parseInt(reg.pic_max_num.value)+'"><b>Снимка '+parseInt(reg.pic_max_num.value)+'</b></label> <input type="checkbox" id="pa'+parseInt(reg.pic_max_num.value)+'" name="fpics_array[]" value="'+reg.pic_url.value+'" checked="checked"/><br/><label for="pa'+parseInt(reg.pic_max_num.value)+'"><a href="javascript:void(0);" onclick="checkPA(\''+parseInt(reg.pic_max_num.value)+'\');"><img src="'+reg.pic_url.value+'" alt=""/></a></label>';
			
			document.getElementById('picshldr').appendChild(dhl);
			
			reg.pic_url.value = '';
			reg.pic_max_num.value = parseInt(reg.pic_max_num.value) + 1;
		}});
}

function addArticlePcPic(what)
{
	if(trim(what) == '') return false;
	
	var tiframe = document.getElementById('upload_target');
	var ret = tiframe.contentWindow.document.body.innerHTML;
	var reg = document.add_gallery;
	var reg_upl = document.remote_upload_form;
	
	if(trim(ret) == '')
	{
		showLightboxAlert('Невалидна снимка.', 'Грешка', '');
		return false;
	}
	
	var rand = parseInt(777 * Math.random(0, 1));
	var pars = 'img=' + ret;
	new Ajax.Request('http://www.izvanzemni.com/ajax/check_image.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(transport.responseText != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			
			reg.pics_count.value = parseInt(reg.pics_count.value) + 1;
			
			//create image
			var npic = document.createElement('img');
			npic.id = 'pic_' + reg.pics_count.value;
			npic.style.position = 'static';
			npic.style.cssFloat = 'left';
			npic.style.styleFloat = 'left';
			npic.style.width = 100 + 'px';
			npic.style.height = 75 + 'px';
			npic.style.border = '#709aad 1px solid';
			npic.src = ret;
			npic.setAttribute('alt', 'Снимка ' + reg.pics_count.value);
			npic.style.marginRight = 10 + 'px';
			/*npic.style.marginTop = 10 + 'px';*/
			npic.style.marginBottom = 10 + 'px';
			
			//create close div
			var ncdiv = document.createElement('div');
			ncdiv.id = 'div_c' + reg.pics_count.value;
			ncdiv.style.position = 'relative';
			ncdiv.style.cssFloat = 'left';
			ncdiv.style.styleFloat = 'left';
			ncdiv.style.width = 16 + 'px';
			ncdiv.style.height = 16 + 'px';
			ncdiv.style.padding = '2px 2px 0px 2px';
			ncdiv.style.marginTop = '-87px';
			ncdiv.style.backgroundColor = '#ffffff';
			ncdiv.style.borderBottom = '#cacaca 1px solid';
			ncdiv.style.borderRight = '#cacaca 1px solid';
			ncdiv.innerHTML = '<a href="javascript:void(0);" onclick="removeGalleryUrlPic(\'' + reg.pics_count.value + '\');"><img src="http://www.izvanzemni.com/images/default/drop.png" alt="Изтрий снимка ' + reg.pics_count.value + '" style="border:0px;"/></a>';
			
			//create hidden input
			var new_fel = document.createElement('input');
			new_fel.id = 'url_pic_' + reg.pics_count.value;
			new_fel.name = 'url_pic_' + reg.pics_count.value;
			new_fel.setAttribute('name', 'url_pic_' + reg.pics_count.value);
			new_fel.setAttribute('type', 'hidden');
			new_fel.value = ret;
			new_fel.setAttribute('value', ret);
			
			//create div holder
			var ndiv = document.createElement('div');
			ndiv.id = 'div_m' + reg.pics_count.value;
			ndiv.style.position = 'static';
			ndiv.style.cssFloat = 'left';
			ndiv.style.styleFloat = 'left';
			ndiv.style.width = 110 + 'px';
			
			//visualize on page
			ndiv.appendChild(new_fel);
			ndiv.appendChild(npic);
			ndiv.appendChild(ncdiv);
			document.getElementById('url_pics_holder').appendChild(ndiv);
			
			reg_upl.reset();
		}});
}

function addTranslationUrlPic(formname)
{
	eval("var reg = document." + formname + ";");
	
	if(trim(reg.pic_url.value) == '')
	{
		showLightboxAlert('Въведете URL адрес към снимката, която искате да добавите.', 'Грешка', 'document.add_translation.pic_url.focus();');
		return false;
	}
	
	var rand = parseInt(777 * Math.random(0, 1));
	var pars = 'img=' + reg.pic_url.value;
	new Ajax.Request('http://www.izvanzemni.com/ajax/check_image.php', {method:'post', postBody:pars, onSuccess:function(transport)
		{
			if(transport.responseText != '')
			{
				showLightboxAlert(transport.responseText, 'Съобщение', '');
				return false;
			}
			
			var dhl = document.createElement('div');
			dhl.className = 'url_images_list';
			dhl.setAttribute('class','url_images_list');
			dhl.innerHTML = '<label for="pa'+parseInt(reg.pic_max_num.value)+'"><b>Снимка '+parseInt(reg.pic_max_num.value)+'</b></label> <input type="checkbox" id="pa'+parseInt(reg.pic_max_num.value)+'" name="fpics_array[]" value="'+reg.pic_url.value+'" checked="checked"/><br/><label for="pa'+parseInt(reg.pic_max_num.value)+'"><a href="javascript:void(0);" onclick="checkPA(\''+parseInt(reg.pic_max_num.value)+'\');"><img src="'+reg.pic_url.value+'" alt=""/></a></label>';
			
			document.getElementById('picshldr').appendChild(dhl);
			
			reg.pic_url.value = '';
			reg.pic_max_num.value = parseInt(reg.pic_max_num.value) + 1;
		}});
}

function fixLoginUser(what)
{
	if(trim(what.value) == 'потребител') what.value = '';
	else if(trim(what.value) == '') what.value = 'потребител';
}

function fixLoginPass(what)
{
	if(trim(what.value) == 'парола') what.value = '';
	else if(trim(what.value) == '') what.value = 'парола';
}

function fixSearch(what)
{
	if(trim(what.value) == 'търси ...') what.value = '';
	else if(trim(what.value) == '') what.value = 'търси ...';
}

function setLoginPage(page_name)
{
	var pars = 'page_name=' + page_name;
	new Ajax.Updater('login_box', 'http://www.izvanzemni.com/modules/login/remote_page.php', {method:'post', postBody:pars, evalScripts:true});
}

function checkRegisterForm()
{
	var reg = document.registerForm;
	
	if(trim(reg.username.value) == '')
	{
		showLightboxAlert('Моля, въведете желаното потребителско име.', 'Грешка', 'document.registerForm.username.focus();');
		return false;
	}
	
	if(trim(reg.password.value) == '')
	{
		showLightboxAlert('Моля, въведете желаната паролата към Вашия профил.', 'Грешка', 'document.registerForm.password.focus();');
		return false;
	}
	
	if(trim(reg.password_retype.value) == '')
	{
		showLightboxAlert('Моля, повторете желаната парола към Вашия профил.', 'Грешка', 'document.registerForm.password_retype.focus();');
		return false;
	}
	
	if(trim(reg.password.value) != trim(reg.password_retype.value))
	{
		showLightboxAlert('Паролите Ви не съвпадат.', 'Грешка', 'document.registerForm.password_retype.focus();');
		return false;
	}
	
	if(trim(reg.email.value) == '')
	{
		showLightboxAlert('Моля, въведете Вашия e-mail.', 'Грешка', 'document.registerForm.email.focus();');
		return false;
	}
	
	if(!valid_email(trim(reg.email.value)))
	{
		showLightboxAlert('Моля, въведете валиден e-mail.', 'Грешка', 'document.registerForm.email.focus();');
		return false;
	}
	
	if(!reg.terms.checked)
	{
		showLightboxAlert('Моля, потвърдете че сте съгласни с условията за ползване на сайта.', 'Грешка', '');
		return false;
	}
	
	reg.submit();
}

function checkLostPassForm()
{
	var reg = document.lostPassForm;
	
	if(trim(reg.email.value) == '')
	{
		showLightboxAlert('Моля, въведете e-mail с който сте се регистрирали.', 'Грешка', 'document.lostPassForm.email.focus();');
		return false;
	}
	
	if(!valid_email(trim(reg.email.value)))
	{
		showLightboxAlert('Моля, въведете валиден e-mail.', 'Грешка', 'document.lostPassForm.email.focus();');
		return false;
	}
	
	reg.submit();
}

function checkLoginForm()
{
	var reg = document.loginForm;
	
	if(trim(reg.username.value) == '' || trim(reg.username.value) == 'потребител')
	{
		showLightboxAlert('Моля, въведете Вашето потребителско име.', 'Грешка', 'document.loginForm.username.focus();');
		return false;
	}
	
	if(trim(reg.password.value) == '' || trim(reg.password.value) == 'парола')
	{
		showLightboxAlert('Моля, въведете Вашата парола.', 'Грешка', 'document.loginForm.password.focus();');
		return false;
	}
	
	reg.submit();
}

function valid_email(email)
{
	var chk = /^[^@]{1,64}@[^@]{1,255}$/g;
	if ( !email.match ( chk ) )
	{
		return false;
	}
	
	email_array = email.split("@");
	local_array = email_array[0].split(".");
	for (var i = 0; i < local_array.length; i++)
	{
		var chk = /^(([A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/g;
		if ( !local_array[i].match ( chk ) )
		{ 
			return false;
		}
	}
	
	var chk = /^\[?[0-9\.]+\]?$/g;
	if ( !email_array[1].match ( chk ) )
	{
		domain_array = email_array[1].split(".");
		if(domain_array.length < 2) return false;
		for (var i = 0; i < domain_array.length; i++)
		{
			if(domain_array[i].length < 2) return false;
			
			var chk = /^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/g;
			if ( !domain_array[i].match ( chk ) ) return false;
		}
	}
	return true;
}

function checkAvatarForm()
{
	var reg = document.avatarForm;
	
	if(trim(reg.pic_pc_fake_small.value) == '')
	{
		showLightboxAlert('Моля, изберете снимка за аватар.', 'Грешка', 'document.avatarForm.pic_pc_fake_small.focus();');
		return false;
	}
	
	reg.submit();
}

function checkSearchForm()
{
	var reg = document.searchform;
	
	if(trim(reg.phrase.value) == '' || trim(reg.phrase.value) == 'търси ...')
	{
		showLightboxAlert('Моля, въведете фраза за търсене.', 'Грешка', 'document.searchform.phrase.focus();');
		return false;
	}
	
	if(trim(reg.phrase.value).length < 3)
	{
		showLightboxAlert('Моля, въведете фраза по-дълга от 2 символа.', 'Грешка', 'document.searchform.phrase.focus();');
		return false;
	}
	
	reg.submit();
}

function submitOnEnter(myfield, submit_function, e)
{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	{
		eval(submit_function);
		return false;
	}
	else return true;
}

function addToFavorites(url, title)
{
	// Mozilla Firefox Bookmark
	if ( window.sidebar )
	{
		window.sidebar.addPanel(title, url, "");
	}
	// IE Favorite
	else if( window.external )
	{
		window.external.AddFavorite( url, title);
	}
	// Opera Hotlist
	else if( window.opera && window.print )
	{
		//Opera Hotlist
    obj.setAttribute('href', url);
    obj.setAttribute('title', title);
    obj.setAttribute('rel', 'sidebar');
    obj.click();
    return false;
	}
}

function setBigImage(bimage, imgname)
{
	var wtime = 450; //millisec
	var it_div = document.getElementById('fullimg');
	var it = document.getElementById('bimage');
	
	//speed for each frame 
	var speed = Math.round(wtime / 100); 
	var timer = 0;
	
	for(i = 100; i >= 0; i--)
	{ 
      setTimeout("changeOpac(" + i + ",'fullimg'," + 100 + ", document.getElementById('bimage') , '" + bimage + "', '" + imgname + "', " + wtime + ")",(timer * speed)); 
      timer++;
  }
}

function opacity(id, opacStart, opacEnd, millisec)
{ 
	//speed for each frame 
	var speed = Math.round(millisec / 100); 
	var timer = 0;
	
	//determine the direction for the blending, if start and end are the same nothing happens 
	if(opacStart > opacEnd) { 
	    for(i = opacStart; i >= opacEnd; i--) { 
	        setTimeout("changeOpac(" + i + ",'" + id + "'," + opacEnd + ")",(timer * speed)); 
	        timer++;
	    }
	} else if(opacStart < opacEnd) { 
	    for(i = opacStart; i <= opacEnd; i++) 
	        { 
	        setTimeout("changeOpac(" + i + ",'" + id + "'," + opacEnd + ")",(timer * speed)); 
	        timer++; 
	    }
	}
} 

//change the opacity for different browsers 
function changeOpac(opacity, id, opacEnd, it, bimage, imgname, wtime)
{
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
	
	if(opacity == 15 && it != '')
	{
		it.src = bimage;
		if(document.getElementById('bimage_link'))
		{
			document.getElementById('bimage_link').href = 'javascript:showBigGallery(\'http://www.izvanzemni.com/athumb/600/1/'+imgname+'\',\''+it.alt+'\');';
		}
		
		if(it.complete)
		{
			it.onload = function()
			{
				//speed for each frame 
				var speed = Math.round(wtime / 100); 
				var timer = 0;
			  
			  for(i = 0; i <= 100; i++) 
			  { 
			      setTimeout("changeOpac(" + i + ",'fullimg'," + 0 + ", '', '', '', '')",(timer * speed)); 
			      timer++; 
			  }
			};
		}
	}
	
	//if(opacity == 0 && opacEnd == 0 && object) document.body.removeChild(document.getElementById(id));
}

function shiftOpacity(id, millisec)
{ 
	//if an element is invisible, make it visible, else make it ivisible 
	if(document.getElementById(id).style.opacity == 0)
	{ 
		opacity(id, 0, 100, millisec); 
	}
	else
	{ 
		opacity(id, 100, 0, millisec); 
	}
}

var ismoving = 0;

function setMargin(tel, margin)
{
	tel.style.marginLeft = margin + 'px';
}

function moveRight(pc)
{
	var tel = document.getElementById('gallery_items');
	var cw = tel.style.width;
	var cm = 448;
	var cmp = 75;
	
	//speed for each frame 
	var speed = Math.round(300 / 100); 
	var timer = 0;
	
	if(ExtractNumber(tel.style.marginLeft) <= 0 && ExtractNumber(tel.style.marginLeft) > -((parseInt(pc) - Math.ceil(parseInt(cm) / parseInt(cmp)))) * parseInt(cmp)) // && ismoving == 0
	{
		for(i = ExtractNumber(tel.style.marginLeft); i >= ExtractNumber(tel.style.marginLeft) - parseInt(cmp); i--)
		{
			setTimeout("setMargin(document.getElementById('gallery_items'), " + i + ")", (timer * speed));
			timer++;
			ismoving = 1;
		}
		ismoving = 0;
	}
}

function moveLeft()
{
	var tel = document.getElementById('gallery_items');
	var cw = tel.style.width;
	var cm = 448;
	var cmp = 75;
	
	//speed for each frame 
	var speed = Math.round(300 / 100); 
	var timer = 0;
	
	if(ExtractNumber(tel.style.marginLeft) < 0) // && ismoving == 0
	{
		for(i = ExtractNumber(tel.style.marginLeft); i <= ExtractNumber(tel.style.marginLeft) + parseInt(cmp); i++)
		{
			setTimeout("setMargin(document.getElementById('gallery_items'), " + i + ")", (timer * speed));
			timer++;
			ismoving = 1;
		}
		ismoving = 0;
	}
}

function closeBox(eval_script)
{
	if(document.getElementById('showMessage')) 
	{
		document.body.removeChild(document.getElementById('showMessage'));
		document.body.removeChild(document.getElementById('showMessageBox'));
		
		eval(eval_script);
		
		//enable scroll
		var elementBody = document.getElementsByTagName('html');
		elementBody[0].style.overflow = '';
		elementBody[0].onselectstart = function() {return true;};
	}
}

function showLightboxAlert(msg, msg_title, eval_script)
{
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.style.position = 'absolute';
	dl.style.width = '100%';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.backgroundColor = '#000000';
	dl.style.top = 0+'px';
	dl.style.left = scrollWidth+'px';
	dl.style.textAlign = 'center';
	dl.style.filter='alpha(opacity=70)';
	dl.style.opacity='.70';
	dl.style.zIndex = 1000;
	
	//msg div
	pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.style.width = '300px';
	pl.style.position = 'absolute';
	pl.style.backgroundColor = '#FFFFFF';
	pl.style.top = ((windowHeight/2)+scrollHeight)-100+'px';
	pl.style.left = '50%';
	pl.style.marginLeft = '-150px';
	pl.style.padding = '0px';
	pl.style.textAlign = 'left';
	pl.style.border = '#000000 1px solid';
	pl.style.zIndex = 1001;
	
	//close div
	cl = document.createElement('div');
	cl.id = 'showMessageBoxClose';
	cl.className = 'alert_bottom';
	cl.innerHTML = '<button class="login_button" onfocus="this.blur();" onclick="closeBox(\'' + eval_script + '\');"><img src="http://www.izvanzemni.com/images/default/iz_close_button.gif" alt=""/></button>';
	//cl.innerHTML = '<input type="button" onclick="javascript:closeBox(\'' + eval_script + '\');" class="input-btn" value="Затвори"/>';
	
	pl.innerHTML = '<div class="alert_top"><b>' + msg_title + '</b></div>';
	pl.innerHTML += '<div class="alert_holder">' + msg + '</div>';
	pl.appendChild(cl);
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	//disable scroll
	var elementBody = document.getElementsByTagName('html');
	elementBody[0].style.overflow = 'hidden';
	elementBody[0].onselectstart = function() {return false;};
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowW, windowH;
	if (self.innerHeight) {	// all except Explorer
		windowW = self.innerWidth;
		windowH = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowW = document.documentElement.clientWidth;
		windowH = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowW = document.body.clientWidth;
		windowH = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowH){
		pageHeight = windowH;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowW){	
		pageWidth = windowW;
	} else {
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowW,windowH) 
	return arrayPageSize;
}

function winWidth()
{
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' )
  {
    //Non-IE
    myWidth = window.innerWidth;
  }
  else if( document.documentElement && document.documentElement.clientWidth )
  {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  }
  else if( document.body && document.body.clientWidth )
  {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

function winHeight()
{
  var myHeight = 0;
  if( typeof( window.innerHeight ) == 'number' )
  {
    //Non-IE
    myHeight = window.innerHeight;
  }
  else if( document.documentElement && document.documentElement.clientHeight )
  {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  }
  else if( document.body && document.body.clientHeight )
  {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function getScrollY()
{
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfY = window.pageYOffset;
  }
  else if( document.body && document.body.scrollTop )
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  }
  else if( document.documentElement && document.documentElement.scrollTop )
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function getScrollY()
{
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfY = window.pageYOffset;
  }
  else if( document.body && document.body.scrollTop )
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  }
  else if( document.documentElement && document.documentElement.scrollTop )
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function getScrollX()
{
  var scrOfX = 0;
  if( typeof( window.pageXOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfX = window.pageXOffset;
  }
  else if( document.body && document.body.scrollLeft )
  {
    //DOM compliant
    scrOfX = document.body.scrollLeft;
  }
  else if( document.documentElement && document.documentElement.scrollLeft )
  {
    //IE6 standards compliant mode
    scrOfX = document.documentElement.scrollLeft;
  }
  return scrOfX;
}

function checkContactsForm()
{
	var reg = document.contacts_form;
	var fields_array = Array('name','email','phone','txt');
	var messages_array = Array('Моля, въведете Вашето име!','Моля, въведете Вашия e-mail адрес!','Моля, напишете Вашият телефонен номер!','Моля, въведете Вашия текст!');
	
	for(i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		
		if(trim(curr_field.value) == '')
		{
			curr_field.focus();
			showLightboxAlert(messages_array[i], 'Грешка', 'document.contacts_form.' + fields_array[i] + '.focus();');
			return false;
		}
		else if(fields_array[i] == 'email')
		{
			var regex = new RegExp(/^(.+){3,}\@(.+){3,}\.([a-z]+){2,}$/);
			var match = regex.exec(curr_field.value);
			if (match == null)
			{
				curr_field.focus();
				showLightboxAlert('Въведете валиден e-mail адрес!', 'Грешка', 'document.contacts_form.' + fields_array[i] + '.focus();');
				return false;
			}
		}
	}
	
	reg.submit();
	return true;
}

function closePic()
{
	if(document.getElementById('showPreview')) 
	{
		document.body.removeChild(document.getElementById('showPreview'));
		document.body.removeChild(document.getElementById('showPreviewPic'));
		
		//enable scroll
		//var elementBody = document.getElementsByTagName('html');
		//elementBody[0].style.overflow = '';
		//elementBody[0].onselectstart = function() {return true;};
	}
}

function showBigGallery(img, txt)
{
	//opera fix
	var agt = navigator.userAgent.toLowerCase();
  var is_opera = (agt.indexOf("opera") != -1);
	//if(is_opera) txt = url.decode(txt);
	
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	dl = document.createElement('div');
	dl.id = 'showPreview';
	dl.style.position = 'absolute';
	dl.style.width = '100%';
	//dl.style.height = parseInt(document.getElementById('allover').offsetHeight) + 40 + 'px';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.backgroundColor = '#000000';
	dl.style.top = 0+'px';
	//dl.style.top = scrollHeight+'px';
	dl.style.left = scrollWidth+'px';
	dl.style.textAlign = 'center';
	dl.style.filter='alpha(opacity=70)';
	dl.style.opacity='.70';
	dl.style.zIndex = 1000;
	
	//pic div
	pl = document.createElement('div');
	pl.id = 'showPreviewPic';
	pl.style.cssText = 'float:left;';
	pl.style.position = 'absolute';
	pl.style.backgroundColor = '#FFFFFF';
	pl.style.top = ((windowHeight/2)+scrollHeight)-250+'px';
	pl.style.left = '50%';
	pl.style.marginLeft = '-305px';
	pl.style.padding = '10px 5px 10px 14px';
	pl.style.width = '610px';
	//pl.style.height = '645px';
	pl.style.textAlign = 'center';
	pl.style.zIndex = 1001;
	pl.style.backgroundImage = 'url(\'http://www.izvanzemni.com/images/default/spinner.gif\')';
	pl.style.backgroundPosition = 'center';
	pl.style.backgroundRepeat = 'no-repeat';
	
	//close div
	cl = document.createElement('div');
	cl.id = 'showPreviewPicClose';
	cl.style.cssText = 'float:left;';
	cl.style.width = '610px';
	//cl.style.border = 'red 1px solid';
	cl.style.backgroundColor = '#FFFFFF';
	cl.style.textAlign = 'left';
	cl.style.padding = '10px 0px 10px 0px';
	cl_in = '<div style="float:left;width:500px;color:#2f5b77;font-size:12px;">' + txt + '</div>';
	cl_in += '<div style="float:right;width:90px;text-align:left;"><a href="javascript:closePic();" style="text-decoration:none;color:#666666;white-spacing:nowrap;">Затвори <img src="http://www.izvanzemni.com/images/default/close.gif" alt="Затвори" style="vertical-align:middle;border:0px;"/></a></div>';
	cl.innerHTML = cl_in;
	
	//pic
	pic_div = document.createElement('div');
	pic_div.style.cssText = 'float:left;';
	pic_div.style.width = '600px';
	//pic_div.style.height = '600px';
	
	pic = document.createElement('img');
	pic.id = 'imagePreview';
	pic.src = img;
	pic.setAttribute('alt', '');
	pic.setAttribute('border', '0');
	
	pic_div.appendChild(pic);
	pl.appendChild(pic_div);
	pl.appendChild(cl);
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	//disable scroll
	//var elementBody = document.getElementsByTagName('html');
	//elementBody[0].style.overflow = 'hidden';
	//elementBody[0].onselectstart = function() {return false;};
}

function showBigBox(targetURL, twidth, theight, txt)
{
	//opera fix
	var agt = navigator.userAgent.toLowerCase();
  var is_opera = (agt.indexOf("opera") != -1);
	//if(is_opera) txt = url.decode(txt);
	
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.style.position = 'absolute';
	dl.style.width = '100%';
	//dl.style.height = parseInt(document.getElementById('allover').offsetHeight) + 40 + 'px';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.backgroundColor = '#000000';
	dl.style.top = 0+'px';
	//dl.style.top = scrollHeight+'px';
	dl.style.left = scrollWidth+'px';
	dl.style.textAlign = 'center';
	dl.style.filter='alpha(opacity=70)';
	dl.style.opacity='.70';
	dl.style.zIndex = 1000;
	
	//content div
	pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.style.cssText = 'float:left;';
	pl.style.position = 'absolute';
	pl.style.backgroundColor = '#FFFFFF';
	pl.style.top = ((windowHeight/2)+scrollHeight)-250+'px';
	pl.style.left = '50%';
	pl.style.marginLeft = '-' + (twidth + 3)/2 +'px';
	pl.style.padding = '10px 5px 10px 14px';
	pl.style.width = twidth + 3 + 'px';
	//pl.style.height = theight + 45 + 'px';
	pl.style.textAlign = 'center';
	pl.style.zIndex = 1001;
	pl.style.backgroundImage = 'url(\'http://www.izvanzemni.com/images/default/spinner.gif\')';
	pl.style.backgroundPosition = 'center';
	pl.style.backgroundRepeat = 'no-repeat';
	
	//close div
	cl = document.createElement('div');
	cl.id = 'showBoxContentClose';
	cl.style.cssText = 'float:left;';
	cl.style.width = twidth + 7 + 'px';
	//cl.style.border = 'red 1px solid';
	cl.style.backgroundColor = '#FFFFFF';
	cl.style.textAlign = 'left';
	cl.style.padding = '10px 0px 10px 0px';
	cl_in = '<div style="float:left;padding-left:5px;width:' + (twidth - 105) + 'px;font-size:12px;">' + txt + '</div>';
	cl_in += '<div style="float:right;width:90px;text-align:left;"><a href="javascript:closeBox(\'\');" style="text-decoration:none;color:#666666;white-spacing:nowrap;">Затвори <img src="http://www.izvanzemni.com/images/default/close.gif" alt="Затвори" style="vertical-align:middle;border:0px;"/></a></div>';
	cl.innerHTML = cl_in;
	
	//content
	content_div = document.createElement('div');
	content_div.style.cssText = 'float:left;';
	content_div.style.width = twidth + 'px';
	//content_div.style.height = theight + 'px';
	content_div.id = 'contentBox';
	
	pl.appendChild(content_div);
	pl.appendChild(cl);
	
	var pars = '';
	new Ajax.Updater('contentBox', targetURL, {method:'get', postBody:pars, evalScripts:true});
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	//var elementBody = document.getElementsByTagName('html');
	//elementBody[0].style.overflow = 'hidden';
	//elementBody[0].onselectstart = function() {return false;};
}

function setFontSize(what)
{
	var default_size = 11;
	var min_size = 9;
	var max_size = 18;
	
	var _fontElement = 'slider_t1';
	
	if(ExtractNumber(document.getElementById(_fontElement).style.fontSize) == 0) document.getElementById(_fontElement).style.fontSize = default_size + 'px';
	
	if(what == 'default')
	{
		document.getElementById(_fontElement).style.fontSize = default_size + 'px';
	}
	else if(what == 'big')
	{
		if(ExtractNumber(document.getElementById(_fontElement).style.fontSize) + 1 <= max_size)
		{
			document.getElementById(_fontElement).style.fontSize = ExtractNumber(document.getElementById(_fontElement).style.fontSize) + 1 + 'px';
		}
	}
	else if(what == 'small')
	{
		if(ExtractNumber(document.getElementById(_fontElement).style.fontSize) - 1 >= min_size)
		{
			document.getElementById(_fontElement).style.fontSize = ExtractNumber(document.getElementById(_fontElement).style.fontSize) - 1 + 'px';
		}
	}
	else
	{
		if(Get_Cookie('fontSize')) document.getElementById(_fontElement).style.fontSize = ExtractNumber(Get_Cookie('fontSize')) + 'px';
		else document.getElementById(_fontElement).style.fontSize = default_size + 'px';
	}
	
	Set_Cookie( 'fontSize', ExtractNumber(document.getElementById(_fontElement).style.fontSize), 30, '/', '.izvanzemni.com' );
}

function ExtractNumber(value)
{
	var n = parseInt(value);
	return n == null || isNaN(n) ? 0 : n;
}

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;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	
	return unescape( document.cookie.substring( len, end ) );
}

function checkExternalVideo()
{
	reg = document.addVideo;
	
	if(trim(reg.url.value) != '')
	{
		var pars = 'do=1&url=' + reg.url.value;
		
		new Ajax.Request('http://www.izvanzemni.com/ajax/external_video.php', { method:'post', postBody: pars, onSuccess: function(transport)
		{
			var result = transport.responseText;
			
			if(result == 0)
			{
				reg.url.focus();
				showLightboxAlert('Въвели сте невалиден адрес или страницата не се поддържа', 'Грешка', 'document.addVideo.url.focus();');
				return false;
			}
			else
			{
				var result_array = result.split('|');
				
				reg.embed_script.value = result_array[0];
				reg.embed_img.value = result_array[1];
				
				reg.submit();
			}
		} });
	}
	else
	{
		reg.url.focus();
		showLightboxAlert('Въведете адреса на страницата с клипа', 'Грешка', 'document.addVideo.url.focus();');
		return false;
	}
}

function setTooltip(what, keyword)
{
	var pars = 'do=1&keyword=' + keyword;
	
	new Ajax.Request('http://www.izvanzemni.com/ajax/get_keyword_info.php', { method:'post', postBody: pars, onSuccess: function(transport)
		{
			if(transport.responseText != '')
			{
				Tip(transport.responseText);
				//what.onmouseout = function() { UnTip(); };
			}
		}
	});
}

function convertWord(type, content)
{
	switch (type)
	{
		// Gets executed before the built in logic performes it's cleanups
		case "before":
		// do nothing
		break;
		
		// Gets executed after the built in logic performes it's cleanups
		case "after":
		content = content.replace(/<(!--)([\s\S]*)(--)>/gi, "");
		break;
	}
	
	return content;
}

function checkGalleryInfoForm(formname)
{
	var fields_array = Array('ftitle','fdescription','fcat_id');
	var errors_array = Array('Въведете име на галерията.','Въведете кратко описание на галерията','Изберете категория.');
	
	eval("var reg = document." + formname + ";");
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.' + formname + '.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	
	if(
		(trim(reg.fsource_label.value) != '' && trim(reg.fsource_link.value) == '')
		||
		(trim(reg.fsource_label.value) == '' && trim(reg.fsource_link.value) != '')
	)
	{
		showLightboxAlert('Попълнете и двете полета за информация за източник на галерията!', 'Грешка');
		return false;
	}
	
	reg.submit();
}

function convertWord(type, content)
{
	switch (type)
	{
		// Gets executed before the built in logic performes it's cleanups
		case "before":
		// do nothing
		break;
		
		// Gets executed after the built in logic performes it's cleanups
		case "after":
		content = content.replace(/<(!--)([\s\S]*)(--)>/gi, "");
		break;
	}
	
	return content;
}
