$(document).ready(function(){
    $("ul.sf-menu").superfish({
/*            animation: {height:'show'},
            delay:     100*/
        });
});

var run = true;
var run2 = true;
var run3 = true;
var validatedFields = new Array();

function in_array(needle, arr)
{
	for(var i = 0, l = arr.length; i < l; i++)
	{
		if(arr[i] == needle)
		{
			return true;
		}
	}
}

function countText(textEl, numEl, maxVal)
{
	var text = document.getElementById(textEl);
	var num = document.getElementById(numEl);
	if (text && num)
	{
		var inputStr = text.value;
		if (inputStr.length >= maxVal)
		{
			text.value = inputStr.substring(0, maxVal);
			inputStr = text.value;
		}
		num.innerHTML = maxVal - inputStr.length;
	}
}

function changeInputType(oldObject, oType, val)
{
	var newObject = document.createElement('input');
	newObject.type = oType;

	if(oldObject.size)
		newObject.size = oldObject.size;
	if(typeof(val) != 'undefined')
		newObject.value = val;
	if(oldObject.name)
		newObject.name = oldObject.name;
	if(oldObject.id)
		newObject.id = oldObject.id;
	if(oldObject.className)
		newObject.className = oldObject.className;

	oldObject.parentNode.replaceChild(newObject,oldObject);
	return newObject;
}

function getMouseXY(e)
{
	tempX = e.pageX+ document.body.scrollLeft
	tempY = e.pageY
}

function getXhr()
{
	var xhr = null;
	if(window.XMLHttpRequest)
	{
		xhr = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		try
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	else
	{
		alert("Can't create XMLHTTPRequest");
		xhr = false;
	}
	return xhr;
}
function validateField(fieldid, url, exec)
{
	if(run === false && typeof(exec) == "undefined" && in_array(fieldid, validatedFields))
	{
		return;
	}
	el = document.getElementById(fieldid);
	if (el)
	{
		var value = el.value;
		value = encodeURIComponent(value);

		if(url.indexOf("?") < 0) url += "?";
		var xhr = getXhr();

		xhr.onreadystatechange = function()
		{
			if (xhr.readyState == 4 && xhr.status == 200)
			{
				var resp = xhr.responseText;
				if (document.getElementById)
				{
					reciever = document.getElementById(fieldid+"Error");
				}
				else if (document.all)
				{
					reciever = document.all[fieldid+"Error"];
				}
				if (resp == "ok")
				{
					reciever.innerHTML = "";
					reciever.className = "valid";
				}
				else
				{
					var obj = document.getElementById(fieldid);
					if(obj)
					{
						var objvalue = obj.value.replace(/^\s+|\s+$/g, '');
						if(obj.attributes['required'] || objvalue != "")
						{
							reciever.innerHTML = resp;
							reciever.className = "error";
						}
						else
						{
							reciever.innerHTML = "";
							reciever.className = "valid";
						}
					}
				}
				validateEditForm();

				setTimeout('validateField("'+fieldid+'", "'+url+'", true)', 1000);
				run = false;
				validatedFields[validatedFields.length] = fieldid;
			}
		}
		xhr.open("GET",url+"&value="+value,true);
		xhr.send(null);
	}
}
function validateEditForm(exec)
{
	if(run2 === false && typeof(exec) == "undefined")
	{
		return;
	}
	var el = document.getElementById("form").elements;
	var len = el.length;
	var ok = true;
	for(i = 0 ; i < len ; i++)
	{
		var element = el[i];
		if (document.getElementById)
		{
			var errObj = document.getElementById(element.name+"Error");
		}
		else if (document.all)
		{
			var errObj = document.all[element.name+"Error"];
		}
		if (errObj)
		{
			var errClass = errObj.className;
			if (element.attributes['required'] && ((errClass != "valid") && (errClass != "")))
			{
				ok = false;
			}
			if ((!element.attributes['required']) && (errClass == "error"))
			{
				ok = false;
			}
		}
		else
		{
			if (element.attributes['required'])
			{
				var val = element.value.replace(/^\s+|\s+$/g, '');
				if (val == "")
				{
					ok = false;
				}
			}
		}
	}
	if (ok)
	{
		document.getElementById('btnSubmit').disabled = false;
		document.getElementById('btnSubmit').className = "save_btn";
	}
	else
	{
		document.getElementById('btnSubmit').disabled = true;
		document.getElementById('btnSubmit').className = "save_btndisabled";
	}
	setTimeout('validateEditForm(true)', 1000);
	run2 = false;
}

function validateCompare(id1, id2, err, exec)
{
	if(run3 === false && typeof(exec) == "undefined")
	{
		return;
	}
	reciever = document.getElementById(id1+"Error");
	el1 = document.getElementById(id1);
	el2 = document.getElementById(id2);
	if(el1.value != el2.value)
	{
		reciever.innerHTML = err;
		reciever.className = "error";
	}
	else
	{
		reciever.innerHTML = "";
		reciever.className = "valid";
	}
	validateEditForm();
	setTimeout('validateCompare("'+id1+'", "'+id2+'", "'+err+'", true)', 1000);
	run3 = false;
}

function updateTag(updatedElementId, toUrl, options)
{
	xhr = getXhr();
	var updatedElement = document.getElementById(updatedElementId);
	xhr.onreadystatechange = function()
	{
		if (xhr.readyState == 4 && xhr.status == 200)
		{
			if (document.getElementById)
			{
				updatedElement.innerHTML = xhr.responseText;
				initLightbox();
				if (typeof(options) != 'undefined')
				{
					var arr = options.split(',');
					setTimeout("initTiny("+arr[0]+", "+arr[1]+", "+arr[2]+", '')", 500);
				}
			}
		}
	}
	xhr.open("GET",toUrl,true);
	xhr.send(null);
}

function updateTagPost(updatedElementId, toUrl, params, text)
{
	xhr = getXhr();
	var updatedElement = document.getElementById(updatedElementId);
	xhr.onreadystatechange = function()
	{
		if (xhr.readyState != 4 || xhr.status != 200)
		{
			if (document.getElementById && text != '')
			{
				updatedElement.innerHTML = text;
			}
		}
		else if (xhr.readyState == 4 && xhr.status == 200)
		{
			if (document.getElementById)
			{
				//if (xhr.responseText != '')
				{
					updatedElement.innerHTML = xhr.responseText;
					initLightbox();
				}
			}
		}
	}
	xhr.open("POST",toUrl,true);
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", params.length);
	xhr.setRequestHeader("Connection", "close");
	xhr.send(params);
}

//========================================================================================== TinyMCE functions
function initTiny(w, h, admin, exact)
{
	var linkStr = "";
	var codeStr = "";
	if (exact != "")
	{
		if (admin == 1)
		{
			 linkStr = "link,unlink,";
			 codeStr = "code,";
		}
		tinyMCE.init(
		{
			language : "bg",
			mode : "exact",
			elements : exact,
			theme : "advanced",
			plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
			theme_advanced_buttons1 : codeStr+"bold,italic,underline,"+linkStr+"bullist,numlist,hr,charmap",
			theme_advanced_buttons2 : "", //"pastetext,pasteword,code",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			//paste_use_dialog : false,
			paste_auto_cleanup_on_paste : true,
			theme_advanced_resizing : false,
			width: w,
			height: h,
			content_css : "/css/frontend.css"
		}
		);
	}
	else
	{
		if (admin == 1)
		{
			 linkStr = "link,unlink,";
			 codeStr = "code,";
		}
		tinyMCE.init(
		{
			language : "bg",
			mode : "textareas",
			theme : "advanced",
			plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
			theme_advanced_buttons1 : codeStr+"bold,italic,underline,"+linkStr+"bullist,numlist,hr,charmap",
			theme_advanced_buttons2 : "", //"pastetext,pasteword,code",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			//paste_use_dialog : false,
			paste_auto_cleanup_on_paste : true,
			theme_advanced_resizing : false,
			width: w,
			height: h,
			content_css : "/css/frontend.css"
		}
		);
	}
}
function flash_display(source, width, height)
{
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,65,0" width="'+width+'" height="'+height+'" align="middle">' + "\n");
	document.write(' <param name="allowScriptAccess" value="sameDomain">' + "\n");
	document.write(' <param name="movie" value="'+source+'">' + "\n");
	document.write(' <param name="menu" value="false">' + "\n");
	document.write(' <param name="quality" value="high">' + "\n");
	document.write(' <param name="scale" value="noscale">' + "\n");
	document.write(' <param name="bgcolor" value="">' + "\n");
	document.write(' <embed src="'+source+'" menu="false" quality="high" bgcolor="" wmode="transparent" width="'+width+'" height="'+height+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>' + "\n");
	document.write('</object>' + "\n");
}
//========================================================================================== FLASH PLAYER
function displayflashplayer(path)
{
	flvplayerContainer = document.getElementById("playerdiv");

	flvplayerContainer.innerHTML =
	'<span id="frame"><object id="player" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,65,0" width="320" height="240"  align="middle">' + "\n"+
	'<param name="allowScriptAccess" value="sameDomain">' + "\n"+
	'<param name="movie" value="player_clips.swf">' + "\n"+
	'<param name="menu" value="false">' + "\n"+
	'<param name="quality" value="high">' + "\n"+
	'<param name="wmode" value="transparent">' + "\n"+
	'<param name="scale" value="noscale">' + "\n"+
	'<param name="bgcolor" value="">' + "\n"+
	'<param name=FlashVars value="path='+path+'">' + "\n"+
	'<embed FlashVars="path='+path+'" wmode="transparent" src="player_clips.swf" menu="false" quality="high" scale="noscale" bgcolor="" width="320" height="240"  align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>' + "\n"+
	'</object>' + "\n";
}
//==========================================================================================
function setActive(id,id2,id3)
{
	var elm = document.getElementById(id);
	var len = elm.options.length;
	if (elm.options[elm.options.selectedIndex].value == 'other')
	{
		document.getElementById(id3).style.display = 'block';
		document.getElementById(id2).readOnly = false;
		document.getElementById(id2).focus();
		document.getElementById(id2).style.border = "solid 1px red";
	}else{
		document.getElementById(id2).value = '';
		document.getElementById(id2).readOnly = true;
		document.getElementById(id2).blur();
		document.getElementById(id2).style.border = "solid 1px #A8ACAF";
		document.getElementById(id3).style.display = 'none';
	}
}

var loadingImage = '/images/loading.gif';
var closeButton = '/images/close.gif';
function getPageScroll()
{
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {
		yScroll = document.body.scrollTop;
	}
	arrayPageScroll = new Array('',yScroll)
	return arrayPageScroll;
}

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){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}
function showLightbox(objLink)
{
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	if (objLoadingImage)
	{
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	imgPreload = new Image();
	imgPreload.onload=function()
	{
		objImage.src = objLink.href;
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);

		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
		objLightboxDetails.style.width = imgPreload.width + 'px';

		//if(objLink.getAttribute('title'))
		//{
			//objCaption.style.display = 'block';
			//objCaption.innerHTML = objLink.getAttribute('title');
		//}
		//else
		{
			objCaption.style.display = 'none';
		}
		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			pause(250);
		}
		if (objLoadingImage)
		{
			objLoadingImage.style.display = 'none';
		}

		selects = document.getElementsByTagName("select");
		for (i = 0; i != selects.length; i++)
		{
			selects[i].style.visibility = "hidden";
		}
		objLightbox.style.display = 'block';

		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');

		listenKey();
		return false;
	}
	imgPreload.src = objLink.href;
}
function hideLightbox()
{
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++)
	{
		selects[i].style.visibility = "visible";
	}
	document.onkeypress = '';
}
function initLightbox()
{
	if (!document.getElementsByTagName)
	{
		return;
	}
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox"))
		{
			anchor.onclick = function ()
			{
				showLightbox(this); return false;
			}
		}

	}
	var objBody = document.getElementsByTagName("body").item(0);
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var imgPreloader = new Image();
	imgPreloader.onload=function()
	{
		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);

		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);
		imgPreloader.onload=function(){};
		return false;
	}
	imgPreloader.src = loadingImage;
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	//objLink.setAttribute('title','');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);
	var imgPreloadCloseButton = new Image();
	imgPreloadCloseButton.onload=function()
	{
		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);
		return false;
	}
	imgPreloadCloseButton.src = closeButton;
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objKeyboardMsg.innerHTML = '<a href="#" onclick="hideLightbox(); return false;"></a>';
	objLightboxDetails.appendChild(objKeyboardMsg);
}
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload();
			func();
		}
	}
}
addLoadEvent(initLightbox);

function showTime(lang)
{
	var timeElement = document.getElementById('timer');
	if (timeElement)
	{
		if (lang == 'bg')
		{
			var d_names = new Array("Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота");
			var	m_names = new Array("Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември");
		}
		else
		{
			var d_names = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
			var	m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
		}
		var currentTime = new Date();
		var hours = currentTime.getHours();
		var minutes = currentTime.getMinutes();
		var seconds = currentTime.getSeconds()
		if (minutes < 10)
		{
			minutes = "0" + minutes;
		}
		if (hours < 10)
		{
			hours = "0" + hours;
		}
		if (seconds < 10)
		{
			seconds = "0" + seconds;
		}

		var curr_day = currentTime.getDay();
		var curr_date = currentTime.getDate();
		var curr_month = currentTime.getMonth();
		var curr_year = currentTime.getFullYear();

		if (lang == 'bg')
		{
			curr_month++;
			if (curr_month < 10)
			{
				curr_month = "0" + curr_month;
			}
			if (curr_date < 10)
			{
				curr_date = "0" + curr_date;
			}
			str = '<span class="time">'+ hours + ":" + minutes + ":" + seconds + '</span> <span class="day">' + d_names[curr_day] + ', ' + curr_date + '.' + m_names[curr_month] + '.' + curr_year + ' г.</span>';
		}
		else
		{
			var sup = "";
			if (curr_date == 1 || curr_date == 21 || curr_date == 31)
			{
				sup = "st";
			}
			else if (curr_date == 2 || curr_date == 22)
			{
				sup = "nd";
			}
			else if (curr_date == 3 || curr_date == 23)
			{
				sup = "rd";
			}
			else
			{
				sup = "th";
			}
   			str = '<span class="time" id="current_time">'+ hours + ":" + minutes + '</span> <span class="day">' + d_names[curr_day] + ' ' + curr_date + '<SUP>' + sup + '</SUP> ' + m_names[curr_month] + ' ' + curr_year + '</span>';;
		}
		timeElement.innerHTML = str;
	}
	setTimeout("showTime('"+lang+"')", 1000);
}

/* AJAX */

function loadAjaxPage( linkURL, containerID ) {
	$.ajax({
		url: linkURL,
		success: function(msg){
			$("#"+containerID).html( msg );
		}
	});
}