// 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 preloadImages(img_array, script_path, stat)
{
	for(i = 0; i < img_array.length; i++)
	{
		eval("c"+i+" = new Image; c"+i+".src = script_path + img_array[i] + '-' + stat;");
	}
}

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 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 checkForm(formname, fields_array, errors_array, nofocus)
{
	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) == '')
		{
			if(!nofocus || nofocus != 1) curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', (!nofocus || nofocus != 1 ? 'document.' + formname + '.' + fields_array[i] + '.focus();' : ''));
			return false;
		}
	}
	reg.submit();
}

function setHomepage(what)
{
	if (document.all)
	{
		what.style.behavior='url(#default#homepage)';
		what.setHomePage('http://www.bghora.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 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 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 IsImageOk(img)
{
	if(!img.complete)
	{
		return false;
	}
	
	if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
	{
		return false;
	}
	
	return true;
}

function closeBox(eval_script)
{
	if(document.getElementById('showMessage')) 
	{
		JQ("#showMessageBox").animate({opacity: "0", marginLeft: "+=500", height: "10", width: "10"}, 300, function() {
			
				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;};
				
			});
		//	.animate({opacity: "0.4", top: "-=" + (endtop - 20), marginLeft: "-=500", height: "20", width: "20"}, 130)
		//	.animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "200", width: "300"}, 130)
		//	return false;
	}
}

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
	var dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.className = 'lba_main';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.left = scrollWidth+'px';
	
	var endtop = ((windowHeight/2)+scrollHeight)-100;
	
	//msg div
	var pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.className = 'lba_container';
	pl.style.top = 10 + 'px';
	pl.style.width = 20 + 'px';
	pl.style.height = 20 + 'px';
	pl.style.left = '50%';
	pl.style.marginLeft = -220 + 'px'
	
	var tl = document.createElement('div');
	tl.className = 'lba_top';
	var bm = document.createElement('div');
	bm.className = 'lba_bottom';
	var lc = document.createElement('div');
	lc.className = 'lba_holder';
	
	var lba_mes = document.createElement('div');
	lba_mes.innerHTML = msg;
	
	//close div
	var cl = document.createElement('div');
	cl.id = 'showMessageBoxClose';
	cl.className = 'clrbth dpt10';
	cl.innerHTML = '<button class="lba_button" onfocus="this.blur();" onclick="closeBox(\'' + eval_script + '\');"><img src="http://www.bghora.com/images/default/bgh_lba_button.gif" alt="Затвори"/></button>';
	
	lba_mes.appendChild(cl);
	lc.appendChild(lba_mes);
	
	//fix div
	var fd = document.createElement('div');
	fd.style.width = 260 + 'px';
	fd.style.height = 123 + 'px';
	
	fd.appendChild(tl);
	fd.appendChild(lc);
	fd.appendChild(bm);
	
	pl.appendChild(fd);
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	JQ("#showMessageBox").animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "123", width: "260"}, 400)
	//	.animate({opacity: "0.4", top: "-=" + (endtop - 20), marginLeft: "-=500", height: "20", width: "20"}, 130)
	//	.animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "200", width: "300"}, 130)
	//	return false;
	
	//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 = 999;
	
	//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 = 1000;
	pl.style.backgroundImage = 'url(\'http://www.bghora.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.bghora.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 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 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 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 fixField(what, default_phrase)
{
	if(trim(what.value) == default_phrase) what.value = '';
	else if(trim(what.value) == '') what.value = default_phrase;
}

function checkLoginForm()
{
	var reg = document.loginform;
	var fields_array = Array('username','password');
	var errors_array = Array('Въведете вашето потребителско име.','Въведете вашата парола.');
	
	//if(reg.username.value == 'потребителско име') reg.username.value = '';
	//if(reg.password.value == 'парола') reg.password.value = '';
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'потребителско име' || trim(curr_field.value) == 'парола')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.loginform.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	reg.submit();
}

function checkRegisterForm()
{
	var reg = document.registerform;
	var fields_array = Array('username','password','password_retype','email','name','vcode','verify_code');
	var errors_array = Array('Въведете потребителско име.','Въведете парола.','Повторете паролата.','Въведете e-mail адрес.','Въведете вашето име.','Въведете код групата, в която танцувате.','Въведете кодът за сигурност.');
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'потребителско име' || trim(curr_field.value) == 'парола' || trim(curr_field.value) == 'e-mail' || trim(curr_field.value) == 'вашето име' || trim(curr_field.value) == 'код за сигурност' || trim(curr_field.value) == 'код на групата')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.registerform.' + fields_array[i] + '.focus();');
			return false;
		}
		//check retype
		if(i == 2)
		{
			if(trim(reg.password.value) != trim(reg.password_retype.value))
			{
				curr_field.focus();
				showLightboxAlert('Повторете паролата правилно.', 'Грешка', 'document.registerform.' + fields_array[i] + '.focus();');
				return false;
			}
		}
	}
	reg.submit();
}

function checkLostPassForm()
{
	var reg = document.lostpassform;
	var fields_array = Array('email');
	var errors_array = Array('Въведете e-mail адрес.');
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'e-mail')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.lostpassform.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	reg.submit();
}

function checkChangePassForm()
{
	var reg = document.changepassform;
	var fields_array = Array('password','password_retype');
	var errors_array = Array('Въведете новата си парола.','Повторете новата си парола.');
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'парола')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.changepassform.' + fields_array[i] + '.focus();');
			return false;
		}
		if(i == 1)
		{
			if(trim(reg.password.value) != trim(reg.password_retype.value))
			{
				curr_field.focus();
				showLightboxAlert('Повторете новата парола правилно.', 'Грешка', 'document.changepassform.' + fields_array[i] + '.focus();');
				return false;
			}
		}
	}
	reg.submit();
}

function checkChangePassFormFull()
{
	var reg = document.changepassform;
	var fields_array = Array('old_password','password','password_retype');
	var errors_array = Array('Въведете старата си парола.','Въведете новата си парола.','Повторете новата си парола.');
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'парола')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.changepassform.' + fields_array[i] + '.focus();');
			return false;
		}
		if(i == 2)
		{
			if(trim(reg.password.value) != trim(reg.password_retype.value))
			{
				curr_field.focus();
				showLightboxAlert('Повторете новата парола правилно.', 'Грешка', 'document.changepassform.' + fields_array[i] + '.focus();');
				return false;
			}
		}
	}
	reg.submit();
}

function checkGlogForm()
{
	var reg = document.glogform;
	var fields_array = Array('name','email','text','verify_code');
	var errors_array = Array('Въведете вашето име.','Въведете e-mail адрес.','Въведете вашето запитване.','Въведете кодът за сигурност.');
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		if(trim(curr_field.value) == '' || trim(curr_field.value) == 'име' || trim(curr_field.value) == 'e-mail' || trim(curr_field.value) == 'текст' || trim(curr_field.value) == 'код за сигурност')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Грешка', 'document.glogform.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	reg.submit();
}

function setProgramsPicFields(formname)
{
	eval("var reg = document." + formname + ";");
	
	var cpc = reg.pics_count.value;
	var npc = cpc + 1;
	
	reg.pics_count.value = npc;
	
	var dtp = document.getElementById('pics_fields');
	
	var npf = document.createElement('input');
	npf.name = 'pic_' + npc;
	npf.className = 't1';
	npf.setAttribute('type','file');
	npf.style.marginTop = 5 + 'px';
	npf.value = '';
	npf.onchange = function(){
			setProgramsPicFields(formname);
		};
	
	var ntf = document.createElement('input');
	ntf.name = 'pic_' + npc + '_title';
	ntf.className = 't1';
	ntf.setAttribute('type','text');
	ntf.style.marginTop = 5 + 'px';
	ntf.value = 'име на снимката';
	ntf.onfocus = function(){
			eval("fixField(reg.pic_" + npc + "_title, 'име на снимката');");
		};
	ntf.onblur = function(){
			eval("fixField(reg.pic_" + npc + "_title, 'име на снимката');");
		};
	
	var sep = document.createElement('hr');
	
	eval("reg.pic_" + cpc + ".onchange = function(){ return false; };");
	
	dtp.appendChild(sep);
	dtp.appendChild(npf);
	dtp.appendChild(ntf);
}

function changeGalleryPic(gallery_id, pics_array, titles_array, pos_array, user_id, direction)
{
	if(direction)
	{
		if(direction == 'next')
		{
			if((current_pic + 1) > pics_array.length) current_pic = 1;
			else current_pic = current_pic + 1;
		}
		else if(direction == 'prev')
		{
			if((current_pic - 1) > 0) current_pic = current_pic - 1;
			else current_pic = pics_array.length;
		}
	}
	else
	{
		if((current_pic + 1) > pics_array.length) current_pic = 1;
		else current_pic = current_pic + 1;
	}
	
	document.getElementById('pic_current_num').innerHTML = current_pic;
	
	var imgsrc = 'http://www.bghora.com/thumb_asp.php?p=620-' + pics_array[(current_pic - 1)] + '-1';
	var limg = new Image();
	limg.src = imgsrc;
	
	JQ("#pic_preview_src").animate({"opacity": "hide"}, 300, function() {
		document.getElementById('pic_preview_src').src = imgsrc;
		document.getElementById('pic_preview_src').alt = titles_array[(current_pic - 1)];
		document.getElementById('pic_preview_href').title = titles_array[(current_pic - 1)];
		document.getElementById('pic_preview_title').innerHTML = titles_array[(current_pic - 1)];
		
		if(document.getElementById('download_pic_img') && document.getElementById('download_pic_text'))
		{
			var download_link = 'http://www.bghora.com/dnpic.php?gallery_id='+gallery_id+'&user_id='+user_id+'&pos='+pos_array[(current_pic - 1)];
			
			document.getElementById('download_pic_img').href = download_link;
			document.getElementById('download_pic_text').href = download_link;
		}
		
		JQ("#pic_preview_src").animate({"opacity": "show"}, 500);
		
		if(document.getElementById('comments'))
		{
			view_all_comments = 0;
			document.commentform.comment_pic_pos.value = pos_array[(current_pic - 1)];
			showGalleryPicComments(gallery_id, pos_array[(current_pic - 1)], user_id);
		}
	});
}

function fixCommentField(what, default_phrase)
{
	if(trim(what.value) == default_phrase)
	{
		what.value = '';
		document.getElementById('submit_comment_holder').style.display = 'block';
	}
	else if(trim(what.value) == '')
	{
		what.value = default_phrase;
		document.getElementById('submit_comment_holder').style.display = 'none';
	}
}

function putGalleryPicComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) != '' && trim(reg.comment.value) != 'напишете коментар...')
	{
		var pars = 'do=1&gallery_id='+reg.comment_gallery_id.value+'&pos='+reg.comment_pic_pos.value+'&user_id='+reg.comment_user_id.value+'&comment='+reg.comment.value;
		new Ajax.Request('http://www.bghora.com/ajax/put_gallery_pic_comment.php',{method:'post', postBody:pars, onSuccess:function(transport)
			{
				reg.comment.value = 'напишете коментар...';
				document.getElementById('submit_comment_holder').style.display = 'none';
				
				showGalleryPicComments(reg.comment_gallery_id.value,reg.comment_pic_pos.value,reg.comment_user_id.value);
			}
		});
	}
	return false;
}

var all_comments = 0;
var view_all_comments = 0;
function showGalleryPicComments(gallery_id, pic_pos, user_id)
{
	//var currentDate = new Date();
	
	var pars = 'do=1&gallery_id='+gallery_id+'&pos='+pic_pos+'&user_id='+user_id+'&view_all='+view_all_comments;//+'&urtm='+currentDate.getTime();
	
	new Ajax.Updater('comments_list','http://www.bghora.com/ajax/get_gallery_pic_comments.php',{method:'post', postBody:pars, evalScripts:true});
}

function viewAllGalleryPicComments()
{
	view_all_comments = 1;
	
	var reg = document.commentform;
	
	showGalleryPicComments(reg.comment_gallery_id.value,reg.comment_pic_pos.value,reg.comment_user_id.value);
}

function putGalleryComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) != '' && trim(reg.comment.value) != 'напишете коментар...')
	{
		var pars = 'do=1&gallery_id='+reg.comment_gallery_id.value+'&user_id='+reg.comment_user_id.value+'&comment='+reg.comment.value;
		new Ajax.Request('http://www.bghora.com/ajax/put_gallery_comment.php',{method:'post', postBody:pars, onSuccess:function(transport)
			{
				reg.comment.value = 'напишете коментар...';
				document.getElementById('submit_comment_holder').style.display = 'none';
				
				showGalleryComments(reg.comment_gallery_id.value,reg.comment_user_id.value);
			}
		});
	}
	return false;
}

function showGalleryComments(gallery_id, user_id)
{
	//var currentDate = new Date();
	
	var pars = 'do=1&gallery_id='+gallery_id+'&user_id='+user_id+'&view_all='+view_all_comments;//+'&urtm='+currentDate.getTime();
	
	new Ajax.Updater('comments_list','http://www.bghora.com/ajax/get_gallery_comments.php',{method:'post', postBody:pars, evalScripts:true});
}

function viewAllGalleryComments()
{
	view_all_comments = 1;
	
	var reg = document.commentform;
	
	showGalleryComments(reg.comment_gallery_id.value,reg.comment_user_id.value);
}

function putVideoComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) != '' && trim(reg.comment.value) != 'напишете коментар...')
	{
		var pars = 'do=1&video_id='+reg.comment_video_id.value+'&comment='+reg.comment.value;
		new Ajax.Request('http://www.bghora.com/ajax/put_video_comment.php',{method:'post', postBody:pars, onSuccess:function(transport)
			{
				reg.comment.value = 'напишете коментар...';
				document.getElementById('submit_comment_holder').style.display = 'none';
				
				showVideoComments(reg.comment_video_id.value);
			}
		});
	}
	return false;
}

function showVideoComments(video_id)
{
	//var currentDate = new Date();
	
	var pars = 'do=1&video_id='+video_id+'&view_all='+view_all_comments;//+'&urtm='+currentDate.getTime();
	
	new Ajax.Updater('comments_list','http://www.bghora.com/ajax/get_video_comments.php',{method:'post', postBody:pars, evalScripts:true});
}

function viewAllVideoComments()
{
	view_all_comments = 1;
	
	var reg = document.commentform;
	
	showVideoComments(reg.comment_video_id.value);
}

function putNewsComment()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) != '' && trim(reg.comment.value) != 'напишете коментар...')
	{
		var pars = 'do=1&news_id='+reg.comment_news_id.value+'&comment='+reg.comment.value;
		new Ajax.Request('http://www.bghora.com/ajax/put_news_comment.php',{method:'post', postBody:pars, onSuccess:function(transport)
			{
				reg.comment.value = 'напишете коментар...';
				document.getElementById('submit_comment_holder').style.display = 'none';
				
				showNewsComments(reg.comment_news_id.value);
			}
		});
	}
	return false;
}

function showNewsComments(news_id)
{
	//var currentDate = new Date();
	
	var pars = 'do=1&news_id='+news_id+'&view_all='+view_all_comments;//+'&urtm='+currentDate.getTime();
	
	new Ajax.Updater('comments_list','http://www.bghora.com/ajax/get_news_comments.php',{method:'post', postBody:pars, evalScripts:true});
}

function viewAllNewsComments()
{
	view_all_comments = 1;
	
	var reg = document.commentform;
	
	showNewsComments(reg.comment_news_id.value);
}

function closePrivateMessage()
{
	if(document.getElementById('showMessage')) 
	{
		JQ("#showMessageBox").animate({opacity: "0", marginLeft: "+=500", height: "10", width: "10"}, 300, function() {
			
				document.body.removeChild(document.getElementById('showMessage'));
				document.body.removeChild(document.getElementById('showMessageBox'));
			});
	}
	return false;
}

function sendPrivateMessage(to_user_id)
{
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	var dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.className = 'lba_main';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.left = scrollWidth+'px';
	
	var endtop = ((windowHeight/2)+scrollHeight)-150;
	
	//msg div
	var pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.className = 'pm_container';
	pl.style.top = 10 + 'px';
	pl.style.width = 20 + 'px';
	pl.style.height = 20 + 'px';
	pl.style.left = '50%';
	pl.style.marginLeft = -260 + 'px'
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	var pars = 'do=1&to_user=' + to_user_id;
	new Ajax.Updater('showMessageBox', 'http://www.bghora.com/ajax/send_message.php', {method:'post', postBody:pars, evalScripts:true, onSuccess: function()
		{
			JQ("#showMessageBox").animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "234", width: "406"}, 400)
		}
	});
}

function putPrivateMessage()
{
	var reg = document.pmform;
	
	if(trim(reg.pmtext.value) == '')
	{
		alert('Въведете текст на съобщението.');
		reg.pmtext.value = '';
		reg.pmtext.focus();
		return false;
	}
	
	var pars = 'do=1&to_user=' + reg.to_user.value + '&pmtext=' + reg.pmtext.value;
	new Ajax.Updater('showMessageBox', 'http://www.bghora.com/ajax/send_message.php', {method:'post', postBody:pars, evalScripts:true});
	
	return false;
}

function putForumPost()
{
	var reg = document.commentform;
	
	if(trim(reg.comment.value) != '' && trim(reg.comment.value) != 'напишете коментар...')
	{
		var pars = 'do=1&forum_id='+reg.comment_forum_id.value+'&comment='+reg.comment.value;
		new Ajax.Request('http://www.bghora.com/ajax/put_forum_post.php',{method:'post', postBody:pars, onSuccess:function(transport)
			{
				reg.comment.value = 'напишете коментар...';
				document.getElementById('submit_comment_holder').style.display = 'none';
				
				showForumPosts(reg.comment_forum_id.value);
			}
		});
	}
	return false;
}

function showForumPosts(forum_id)
{
	//var currentDate = new Date();
	
	var pars = 'do=1&forum_id='+forum_id+'&view_all='+view_all_comments;//+'&urtm='+currentDate.getTime();
	
	new Ajax.Updater('comments_list','http://www.bghora.com/ajax/get_forum_posts.php',{method:'post', postBody:pars, evalScripts:true});
}

function viewAllForumPosts()
{
	view_all_comments = 1;
	
	var reg = document.commentform;
	
	showForumPosts(reg.comment_forum_id.value);
}

function changeProgramPic(pic, ptitle)
{
	//var cacheimage = new Image();
	//cacheimage.src = 'http://www.bghora.com/thumb_asp.php?p=160-' + pic;
	
	document.getElementById('main_pic_prev').src = 'http://www.bghora.com/thumb_asp.php?p=160-' + pic;
	document.getElementById('main_pic_prev').alt = ptitle;
}

function changeNewsPic(pic, ptitle)
{
	//var cacheimage = new Image();
	//cacheimage.src = 'http://www.bghora.com/thumb_asp.php?p=160-' + pic;
	
	document.getElementById('main_pic_prev').src = 'http://www.bghora.com/thumb_asp.php?p=160-' + pic;
	document.getElementById('main_pic_prev').alt = ptitle;
}

function showBirthdayUsers()
{
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	var dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.className = 'lba_main';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.left = scrollWidth+'px';
	
	var endtop = ((windowHeight/2)+scrollHeight)-150;
	
	//msg div
	var pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.className = 'pm_container';
	pl.style.top = 10 + 'px';
	pl.style.width = 20 + 'px';
	pl.style.height = 20 + 'px';
	pl.style.left = '50%';
	pl.style.marginLeft = -260 + 'px';
	
	pl.innerHTML = 'edi koi si ima tojden den dnes!';
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	var pars = 'do=1';
	new Ajax.Updater('showMessageBox', 'http://www.bghora.com/ajax/birthday_notification.php', {method:'post', postBody:pars, evalScripts:true, onSuccess: function()
		{
			JQ("#showMessageBox").animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "234", width: "406"}, 400)
		}
	});
}

function getUsersByName(formname, uname, search_for, no_options)
{
	eval('var reg = document.' + formname + ';');
	
	if(trim(uname.value).length > 0)
	{
		if(reg.to_user)
		{
			reg.to_user.value = '';
			document.getElementById('selected_to_user').innerHTML = '-';
		}
		
		if(!document.getElementById('contentBox'))
		{
			var el = document.createElement('div');
			el.id = 'contentBox';
			el.className = 'ulist_by_name';
			
			document.body.onclick = function(e)
			{
				var target = e ? e.target : event.srcElement;
				if(target != document.getElementById('contentBox') && target != uname)
				{
					document.getElementById('search_results').removeChild(document.getElementById('contentBox'));
					document.body.onclick = function(){ return; };
				}
			};
			
			document.getElementById('search_results').appendChild(el);
		}
		
		var pars = 'do=1&uname=' + uname.value + '&no_options=' + (no_options ? no_options : 0) + '&search_for=' + (search_for ? search_for : 5);
		new Ajax.Updater('contentBox', 'http://www.bghora.com/ajax/get_users_by_name.php', {method:'post', postBody:pars, evalScripts:true});
	}
	else if(document.getElementById('contentBox'))
	{
		if(reg.to_user)
		{
			reg.to_user.value = '';
			document.getElementById('selected_to_user').innerHTML = '-';
		}
		document.getElementById('search_results').removeChild(document.getElementById('contentBox'));
		document.body.onclick = function(){ return; };
	}
}

function checkNewMessages()
{
	var pars = 'do=1';
	new Ajax.Request('http://www.bghora.com/ajax/check_new_messages.php', {method:'post', postBody: pars, onSuccess: function(transport)
		{
			if(parseInt(transport.responseText) > 0)
			{
				document.getElementById('new_messages_alarm').style.display = 'block';
				document.getElementById('new_messages_alarm_count').innerHTML = transport.responseText;
			}
			else
			{
				document.getElementById('new_messages_alarm').style.display = 'none';
				document.getElementById('new_messages_alarm_count').innerHTML = 0;
			}
		}
	});
}

function closeCustomPrivateMessage()
{
	if(document.getElementById('showMessage')) 
	{
		JQ("#showMessageBox").animate({opacity: "0", marginLeft: "+=500", height: "10", width: "10"}, 300, function() {
			
				document.body.removeChild(document.getElementById('showMessage'));
				document.body.removeChild(document.getElementById('showMessageBox'));
			});
	}
	return false;
}

function sendCustomPrivateMessage()
{
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	var dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.className = 'lba_main';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.left = scrollWidth+'px';
	
	var endtop = ((windowHeight/2)+scrollHeight)-150;
	
	//msg div
	var pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.className = 'pm_container';
	pl.style.top = 10 + 'px';
	pl.style.width = 20 + 'px';
	pl.style.height = 20 + 'px';
	pl.style.left = '50%';
	pl.style.marginLeft = -260 + 'px'
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	var pars = 'do=1';
	new Ajax.Updater('showMessageBox', 'http://www.bghora.com/ajax/send_custom_message.php', {method:'post', postBody:pars, evalScripts:true, onSuccess: function()
		{
			JQ("#showMessageBox").animate({opacity: "1", top: endtop, marginLeft: "+=100", height: "234", width: "406"}, 400)
		}
	});
}

function putCustomPrivateMessage()
{
	var reg = document.pmform;
	
	if(reg.to_user.value == '')
	{
		alert('Изберете до кого ще изпратите съобщението.');
		reg.to_user_name.focus();
		return false;
	}
	else if(trim(reg.pmtext.value) == '')
	{
		alert('Въведете текст на съобщението.');
		reg.pmtext.value = '';
		reg.pmtext.focus();
		return false;
	}
	
	var pars = 'do=1&to_user=' + reg.to_user.value + '&pmtext=' + reg.pmtext.value;
	new Ajax.Updater('showMessageBox', 'http://www.bghora.com/ajax/send_custom_message.php', {method:'post', postBody:pars, evalScripts:true});
	
	return false;
}

function chooseNoOptionUser(user_id, user_name)
{
	if(document.pmform)
	{
		document.pmform.to_user.value = parseInt(user_id);
		document.pmform.to_user_name.value = trim(user_name);
		
		document.getElementById('selected_to_user').innerHTML = trim(user_name);
	}
}
