/**
 * JavaScrits
 *
 * @author Aurimas Tubis a.k.a Okanakis <aurimas@kryptis.lt>
 */

sfHover = function() {
	var sfEls = document.getElementById("navmenu").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

//if (window.attachEvent) window.attachEvent("onload", sfHover);
//----------------------------------------------------------

/*
	Strips spaces from start and end of string
	Param:
		str string (text)
*/
function trimString (str)
{
	while (str.charAt(0) == ' ')
		str = str.substring(1);
	while (str.charAt(str.length - 1) == ' ')
		str = str.substring(0, str.length - 1);

	return str;
}
//---------------------------------------------------------------

/*
	Opens popup window, whitch is centered in screen
	Param:
		url string (link to the file you want to open)
		type string ('console', 'standard', 'fullscreen')
		width int (window width)
		height int (window height)
*/
function openPopup(url,type,width,height) {
	ifrm = document.createElement("IFRAME");
	ifrm.setAttribute("src", url);
	ifrm.style.width = 1+"px";
	ifrm.style.height = 1+"px";        
	document.getElementById('hidden-container').appendChild(ifrm); 	
	return false;

	var rnd = (Math.round((Math.random()*999)+1));
	
	scrollbars = 'yes';

    type = type.toLowerCase();
    
    if (type == "fullscreen"){
        width = screen.availWidth;
        height = screen.availHeight;
		var top = 0;
		var left = 0;
    } else {
		var top = (screen.height) ? (screen.height-height)/2 : 0;
		var left = (screen.width) ? (screen.width-width)/2 : 0;
	}
	
    var tools="";
    if (type == "standard") tools = "resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width="+width+",height="+height+",top="+top+",left="+left;
    if (type == "console" || type == "fullscreen") tools = "resizable,toolbar=no,location=no,scrollbars=no,width="+width+",height="+height+",top="+top+",left="+left;
	
	my_window = window.open(url, "w"+rnd, tools);
	my_window.document.close();
}
//---------------------------------------------------------------

var lastKeyword = '';
function proceedText(form, c)
{
	var value = trimString(form.query.value);
	var formObj = $('#'+form.id);
	
	/*
	value = value.replace(/&/, '');
	value = value.replace(/=/, '');
	value = value.replace(/\?/, '');
	*/
	/*
	value = value.replace(/ą/gi, 'a');
	value = value.replace(/č/gi, 'c');
	value = value.replace(/ę/gi, 'e');
	value = value.replace(/ė/gi, 'e');
	value = value.replace(/į/gi, 'i');
	value = value.replace(/š/gi, 's');
	value = value.replace(/ų/gi, 'u');
	value = value.replace(/ū/gi, 'u');
	value = value.replace(/ž/gi, 'z');
	*/
	
	if (value.length > 2) {
		formObj.addClass('opened');
		if ((value == lastKeyword) && (c)) {
			return;
		}
		lastKeyword = value;
		var baseUri = baseUrl + 'search/ajaxSearch/'; //?query=' + value;
		var data = $('#searchField').serialize();
		var elms = new Array();
		elms['documents'] = (form.documents.checked) ? 1 : 0;
		elms['structure'] = (form.structure.checked) ? 1 : 0;
		elms['news'] = (form.news.checked) ? 1 : 0;
		elms['events'] = (form.events.checked) ? 1 : 0;
		var t = 0;
		for (var key in elms) {
			if (elms[key])
				t++;
		}
		for (var key in elms) {
			if (t == 0)
				elms[key] = 1;
			data = data + '&' + key + '=' + elms[key];
		}
		
		//alert(baseUri);
		proceedAjaxSearchRequest(baseUri, data, 'ajax_results_inner');
		
	} else if (formObj.hasClass('opened')) {
		formObj.removeClass('opened');
	}
}
//---------------------------------------------------------------

function proceedAjaxSearchRequest(baseUri, data, dest)
{
	var n = 0;
	
	$("#"+dest).ajaxStart(function(){
		if (n++ > 0) return;
			
		$('#results_read_more').hide();
		$("#"+dest).html('<img src="/images/ajax-loading-small.gif" alt="Loading..." />');
	});
	
	$.ajax({
		url: baseUri, 
		cache: false,
		data: data,
		success: function(html){
			if (html)
			{
				var tmp = baseUri.replace(/ajaxSearch\//, '');
				$('#results_read_more a').attr('href', tmp + '?' + data);
				$('#results_read_more').show();
				$("#"+dest).html(html);
			} else {
				$('#results_read_more').hide();
				$("#"+dest).html(searchNoResults);
			}
		}
	});
}
//---------------------------------------------------------------

function swapBlock(pid, a, b) {
	var key = pid.replace(a, '');
	var id = b + '-' + key;
	var obj = $('#' + id);
	if (obj.length) {
		$('.' + b).hide();
		obj.show();
		return id;
	} else {
		return false;
	}
}
//---------------------------------------------------------------

var timer = 0;
var lastActiveItem = '';

function setTimer(id) {
	timer = setTimeout("closeSubNav('" + id + "')", 500);
}
//---------------------------------------------------------------

function unsetTimer(id) {
	if (lastActiveItem == id)
	{
		clearTimeout(timer);
		if (timer)
			timer = 0;
	}
}
//---------------------------------------------------------------

function closeSubNav(id) {
	$('#' + id).fadeOut(500);
	//alert('L: ' + lastActiveItem.split('-')[1] + ' id: ' + id.split('-')[1]);
	/*
	if ((lastActiveItem) && (lastActiveItem.split('-')[1] != id.split('-')[1])) {
		$('#' + id + ' a').removeClass('active');
		$('#' + lastActiveItem + ' a').addClass('active');
	}
	*/
	unsetTimer();
}
//---------------------------------------------------------------

function closeAjaxResults() {
	var form = $('#searchForm');
	if (form.length) {
		form.removeClass('opened');
		var field = $('#searchField');
		if (field.length)
		{
			field.focus();
			field.val('');
			field.blur();
		}
	}
}
//---------------------------------------------------------------

$(document).ready(function()
{
	/*
	$('body').click(function(){
		var form = $('#searchForm');
		if (form.length) {
			form.removeClass('opened');
		}
	});
	*/
	//---------------------------------------------------------------	
	
	/*
	$('#searchField').keyup(function(a){
		switch(a.keyCode)
		{
			case 38:
				return;
			case 40:
				return;
		}
	});
	*/
	//---------------------------------------------------------------	

	$("#navmenu a").click(function(){
		var res = true;
		var parent = $(this).parent();
		var pid = parent.attr('id');
		if (pid) {
			if ((pid == 'navmenu-home') && (useTimer)) {
				return true;
			}
			var id = swapBlock(pid, 'navmenu-', 'subnav');
			if (id) {
				lastActiveItem = id;
				res = false;
			}
			/*
			//useTimer - was set in 'index1.html'
			if ((id) && (useTimer)) {
				setTimer(id);
			}
			*/
			//lastActiveItem = pid;
		}
		$('#navmenu a').removeClass('active');
		$(this).addClass('active');
		$(this).blur();
        
        if (!res) {
            var href = $(this).attr('href');
            window.location.hash = href;
            $.cookie('nav-block-view', href, { expires: 30, path: '/' });
            return false;
        }
        else
            return true;
	});
	//---------------------------------------------------------------	
	
	$("#content_nav a").click(function(){
		var res = true;
		var parent = $(this).parent();
		var pid = parent.attr('id');
		if (pid) {
			var id = swapBlock(pid, 'content_nav-', 'content_block');
			if (id)
				res = false;
		}
		$('#content_nav a').removeClass('active');
		$(this).addClass('active');
		$(this).blur();
        
        if (!res) {
            var href = $(this).attr('href');
            window.location.hash = href;
            $.cookie('block-view', href, { expires: 30, path: '/' });
            return false;
        }
        else
            return true;
	});
	//---------------------------------------------------------------
	
	$('#overlay').click(function() {
		closeOverlay();
	});
	//---------------------------------------------------------------

    function initTab() {
        var hash = window.location.hash;
        var tabs = new Array();
        
        if ($.cookie('nav-block-view'))
            tabs['nav-block-view'] = $.cookie('nav-block-view');
        if ($.cookie('block-view'))
            tabs['block-view'] = $.cookie('block-view');
        
        if (hash) {
            for(var i in tabs) {
                if (tabs[i] == hash) {
                    tabs[i] == hash;
                    hash = '';
                    break;
                }
            }
        }
        
        if (hash) {
            tabs['hash'] = hash;
        }
        
        for(var i in tabs)
        {
            hash = tabs[i];
            if (hash) {
                //var linkObj = $('#content_nav li a[href$=\\'+hash+']');
                var linkObj = $('ul li a[@href$='+hash+']');
                if (linkObj.length)
                {
                    linkObj.trigger('click');
                }
            }
        }
    }
	//---------------------------------------------------------------
    
    // Kintamasis useTimer = true, jei vidinis puslapis ir false - jei index puslapis
    if (!useTimer)
    {
        initTab();
    }
});
//---------------------------------------------------------------

setBoxPosition = function() {
	var sizes = getPageSizes();
	var scrolls = getPageScrolls();
	
	var top = parseInt((sizes[3]/2) - 220);
	var left = parseInt((sizes[0]/2) - 220);
	
	var iev = getIEVersion();
	if (iev !== false)
	{
		if (iev < 7)
		{
			top += parseInt(scrolls[1]);
			left += parseInt(scrolls[0]);
		}
	}

	if ((!top) || (top < 0)) {
		top = 0;
	}
	if ((!left) || (left < 0)) {
		left = 0;
	}
	$('#overlay_box').css({	top: top+'px' });
	$('#overlay_box').css({	left: left+'px' });
}
//---------------------------------------------------------------

showContactForm = function() {
	//html = $('#contact_box_content').html();
	setBoxPosition();
	setOverlay();
	$('#overlay_box').show();
	$('#overlay_box').focus();
	//$('#overlay_box').html(html);
}
//---------------------------------------------------------------

setOverlay = function() {
	var sizes = getPageSizes();
	var w = sizes[0];
	var h = sizes[1];
	var h_body = parseInt($('body').height());
	var h_top = parseInt($('#top').height());
	if (h < h_body)
		h = h_body;
	if (h < h_top)
		h = h_top;
	
	$('#overlay').css({	width: w+'px' });
	$('#overlay').css({	height: h+'px' });
	$('#overlay').show();
}
//---------------------------------------------------------------

closeOverlay = function() {
	$('#overlay').hide();
	$('#overlay_box').hide();
	//$('#overlay_box').html('');
}
//---------------------------------------------------------------

function getPageSizes() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		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 windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}
//---------------------------------------------------------------

function getPageScrolls() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}
//---------------------------------------------------------------

function getIEVersion()
{
	var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
	if (isIE)
	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		{
			rv = parseFloat( RegExp.$1 );
			return rv;
		}
	}
	
	return false;
}
//---------------------------------------------------------------


function showDocumentIcons()
{
	var fileTypes = {
		doc: 'doc.gif',
		xls: 'xls.gif',
		pdf: 'pdf.gif'
	};
	 /*
	$.each(fileTypes, function(extension, image)
		{
			$('a[href$="' + extension + '"]').
			css({
				paddingLeft: '18px',
				background: 'transparent url("/images/' + image + '") no-repeat center left'
			});
		}
	);
	*/
}
//---------------------------------------------------------------

function logout()
{
	//jQuery.get(baseUrl + '/userl/logout');
	//alert(baseUrl + '/users/logout');
}
//---------------------------------------------------------------

