// ajax
function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		//Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

//tiesiogine transliacija
/*function get_online_games() {
	$.ajax({
	  url: '/client/ajax/online_games.php?sid=' + Math.random(),
	  success: function(data) {
		document.getElementById('online_game_container').innerHTML = data;
	  }
	});
}*/

// pranesk apie komentara
function report(id) {
	var url = '/client/ajax/report_comment.php?id=' + id + '&sid=' + Math.random();

	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = reportStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function reportStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("report_msg")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("report_msg")[0].childNodes[i].nodeValue;
			}
			
			var len2 = xmlDoc.getElementsByTagName("rid")[0].childNodes.length;
			
			// display
			var results2 = "";
			for( var i = 0; i< len2; i++ ) {
				results2 += xmlDoc.getElementsByTagName("rid")[0].childNodes[i].nodeValue;
			}
			
			if (results && results2) {
				document.getElementById('report_container_' + results2).innerHTML = results;
			}
		}
	}
}

function reply_comment(id) {
	$('#reply_' + id).toggle('500');
}

//naujienos apklausa
function get_news_poll(nr) {
	document.getElementById('news_poll_container').innerHTML = '<br /><img src="/client/images/ajax-loader.gif" border="0" alt="" />';
	var url = '/client/ajax/news_question.php?id=' + nr + '&sid=' + Math.random();
	
	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = newsContestStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function newsContestStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("item_question")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("item_question")[0].childNodes[i].nodeValue;
			}
			if (results) {
				document.getElementById('news_poll_container').innerHTML = results;
			}
		}
	}
}

//naujienos konkursas
function get_news_contests(nr) {
	document.getElementById('news_contests_container').innerHTML = '<br /><img src="/client/images/ajax-loader.gif" border="0" alt="" />';
	var url = '/client/ajax/news_contests.php?id=' + nr + '&sid=' + Math.random();
	
	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = pollStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function pollStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("contests")[0].childNodes.length;
			var len2 = xmlDoc.getElementsByTagName("dataid")[0].childNodes.length;
			var len3 = xmlDoc.getElementsByTagName("total_img")[0].childNodes.length;
			var len4 = xmlDoc.getElementsByTagName("width")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("contests")[0].childNodes[i].nodeValue;
			}
			var dataid = "";
			for( var i = 0; i< len2; i++ ) {
				dataid += xmlDoc.getElementsByTagName("dataid")[0].childNodes[i].nodeValue;
			}
			var total_img = "";
			for( var i = 0; i< len3; i++ ) {
				total_img += xmlDoc.getElementsByTagName("total_img")[0].childNodes[i].nodeValue;
			}
			var width = "";
			for( var i = 0; i< len4; i++ ) {
				width += xmlDoc.getElementsByTagName("width")[0].childNodes[i].nodeValue;
			}
			if (results) {
				document.getElementById('news_contests_container').innerHTML = results;
				init_contest_gallery(dataid, total_img, width);
			}
		}
	}
}

// sauniausios poreles kunkursui
function get_poll(nr) {
	document.getElementById('poll_container').innerHTML = '<br /><img src="/client/images/ajax-loader.gif" border="0" alt="" />';
	var url = '/client/ajax/poreles.php?id=' + nr + '&sid=' + Math.random();

	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = itemsStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function itemsStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("poll")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("poll")[0].childNodes[i].nodeValue;
			}
			if (results) {
				document.getElementById('poll_container').innerHTML = results;
			}
		}
	}
}

// konkursai
function get_contest(nr) {
	document.getElementById('contest_container').innerHTML = '<br /><img src="/client/images/ajax-loader.gif" border="0" alt="" />';
	var url = '/client/ajax/contest.php?id=' + nr + '&sid=' + Math.random();

	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = contestStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function contestStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("poll")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("poll")[0].childNodes[i].nodeValue;
			}
			if (results) {
				document.getElementById('contest_container').innerHTML = results;
			}
		}
	}
}

// dienos klausimas
function get_day_question(nr) {
	document.getElementById('day_question_container').innerHTML = '<br /><img src="/client/images/ajax-loader.gif" border="0" alt="" />';
	var url = '/client/ajax/day_question.php?id=' + nr + '&sid=' + Math.random();

	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = dayQuestionStatusChange;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function dayQuestionStatusChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseXML && xmlHttp.responseXML.documentElement) {
			var xmlDoc = xmlHttp.responseXML.documentElement;
			
			var len = xmlDoc.getElementsByTagName("day_question")[0].childNodes.length;
			
			// display
			var results = "";
			for( var i = 0; i< len; i++ ) {
				results += xmlDoc.getElementsByTagName("day_question")[0].childNodes[i].nodeValue;
			}
			if (results) {
				document.getElementById('day_question_container').innerHTML = results;
			}
		}
	}
}

// coockie
function readCookie(name) {
	var cookiename = name + "=";
	var ca = document.cookie.split(';');
	for ( var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(cookiename) == 0)
			return c.substring(cookiename.length, c.length);
	}
	return null;
}

function setCookie(c_name, value, expiredays) {
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000);

	document.cookie = c_name + "=" + escape(value) + ";expires="
			+ expire.toGMTString() + ";path=/";
}

//
// Martin Saulis for BALSAS.LT
//

$(function() {

	// adding rounded corner containers

	// v2

	$sel_items = $(".sub_cols");
	$top_pos = 0;
	$last_changed = 0;
	for ( var i = 0; i < $sel_items.length; i++) {
		$h1 = $($sel_items[i]).find('.sub_col1').height();
		$h2 = $($sel_items[i]).find('.sub_col2').height();
		if ($h2 > $h1)
			$($sel_items[i]).find('.sub_col1').height($h2);
	}

	$(".tabmenu li").click(function() {
		var index = $(".tabmenu li").index(this);
		$(this).parents(".tabs").find(".tab").hide();
		$(this).parents(".tabmenu").find("li").removeClass("active");
		$(this).addClass("active");
		var tab = $(this).parents(".tabs").find(".tab").get(index);
		$(tab).show();
		return false;
	});
	
	$(".tabmenu2 li").click(function() {
		var index = $(".tabmenu2 li").index(this);
		$(this).parents(".tabs2").find(".tab2").hide();
		$(this).parents(".tabmenu2").find("li").removeClass("active");
		$(this).addClass("active");
		var tab = $(this).parents(".tabs2").find(".tab2").get(index);
		$(tab).show();
		return false;
	});

	$(".photoswitcher td").hover(function() {
		if (!($(this).hasClass(".image"))) {
			// mouse over
			$(this).parents("table").find("td").removeClass("current");
			$(this).addClass("current");

			// change video / foto img
			$(this).parents("table").find("td").find(".video_ico").attr("src", "/img/video_grey_bg.gif");
			$(this).parents("table").find("td").find(".foto_ico").attr("src", "/img/foto_grey_bg.gif");
			$(this).parents("table").find("td").find(".audio_ico").attr("src", "/img/audio_grey_bg.gif");
			// $(this).find("a").find("img").attr("src",
			// "/img/video_red_bg.gif");
			$(this).find(".video_ico").attr("src", "/img/video_red_bg.gif");
			$(this).find(".foto_ico").attr("src", "/img/foto_red_bg.gif");
			$(this).find(".audio_ico").attr("src", "/img/audio_red_bg.gif");

			var image_src = $(this).children("img");
			var image_link = image_src[0].src;
			var table_bg = $(this).parents("table");
			
			var a_link_obj = $(this).children("a");
			a_link = a_link_obj[0].href;
			
			$("a#main_link").attr("href", a_link);
			
			$(table_bg).css( {
				background : "url('" + image_link + "') no-repeat"
			})

			var p_src = $(this).find("p");
			$(this).parents(".inside").find(".content").find("p").empty();
			$(this).parents(".inside").find(".content").find("p").append(
					p_src.html());
		}
	});
	$(".photoswitcher td").click(function() {
		var a = $(this).find("a");
		if (a) {
			location.href = a[0].href;
		}
	});

	// end v2

	/*
	 * var rounded = new Array( "#top_menu li a", "#main_menu td > a",
	 * "#main_menu div > a", "#sub_menu", "#search_menu form", ".box", "#media
	 * .menu a", "#orai .menu a", "#files .menu a", "#videos .menu a", "#archive
	 * .menu a", "#top .menu a", ".video .button", ".column_button", ".play" );
	 * rounded = Array();
	 * 
	 * 
	 * for(i = 0; i < rounded.length; i++){
	 * 
	 * var corners = "<span class='corner tl'>&nbsp;</span><span
	 * class='corner tr'>&nbsp;</span><span class='corner bl'>&nbsp;</span><span
	 * class='corner br'>&nbsp;</span>";
	 * 
	 * for(j=0;j<$(rounded[i]).length;j++){ x = $($(rounded[i])[j]);
	 * $(x).append(corners); } }
	 */

	// adding comment counter containers
	// $(".comments a:empty").remove();
	// $(".comments:empty").remove();
	// $(".comments").wrap("<span class='comments2'></span>");
	// $(".comments").before("<span class='comments3'>&nbsp;</span>");
	$(".advertisment").show()

	// setting text size

//	$("a").filter(function() {
//		if (this.hostname == 'balsuotojas.balsas.lt')
//			return !(this.hostname && this.hostname !== location.hostname);
//		else
//			return this.hostname && this.hostname !== location.hostname;
//	}).attr('target', '_blank');

	size = get_cookie("balsas_text_size");

	if (size < 151 && size > 99)
		$("#content *").css( {
			"font-size" : size + "%"
		});

	// dropdown menu

	$("#main_menu td > div").hover(function() {
		$(this).css( {
			"z-index" : "10"
		});
		$(this).addClass("current");
		$(this).addClass("hover");
		$("a:first", this).css( {
			"z-index" : "50"
		});
		$("ul", this).show();
	}, function() {
		$("ul", this).hide();
		$(this).removeClass("current");
		$(this).removeClass("hover");
	});

	// media

	$("#media_left").click(function() {
		var z = 0;
		if ($(".videos:visible .item:visible").length > 6) {
			$($(".videos:visible .item:visible")[0]).hide("fast");
		}
		return false;

	});

	$("#media_right").click(function() {
		var z = 0;
		if ($(".videos .item:hidden:last").length > 0) {
			$($(".videos .item:hidden:last")[0]).show("fast");
		}
		return false;

	});

	// orai

	/*
	 * $("#orai_left").click(function(){ var z = 0; if($(".videos:visible
	 * .item:visible").length>6){ $($(".videos:visible
	 * .item:visible")[0]).hide("fast"); } return false;
	 * 
	 * });
	 * 
	 * $("#orai_right").click(function(){ var z = 0; if($(".videos
	 * .item:hidden:last").length>0){ $($(".videos
	 * .item:hidden:last")[0]).show("fast"); } return false;
	 * 
	 * });
	 */

	// $("#top > div").hide(); // not needed now
	var size = 110;
	$(".plus").click(function() {
		size += 10;
		size = size > 150 ? 150 : size;
		document.cookie = "balsas_text_size=" + size + "; path=/;";
		$("#content *").css( {
			"font-size" : size + "%"
		});
	});

	$(".minus").click(function() {
		size -= 10;
		size = size < 100 ? 100 : size;
		document.cookie = "balsas_text_size=" + size + "; path=/;";
		$("#content *").css( {
			"font-size" : size + "%"
		});
	});

	$("#top > ul li a").click(function() {
		/*
		 * id = $(this).attr('href').replace(/#/g, '');
		 * 
		 * $(this).parents("div:first").find("div").hide();
		 * $(this).parents("div:first").find("*").removeClass("current");
		 * 
		 * $(this).parent().addClass("current");
		 * 
		 * $(this).parents("div:first").find("div[class='"+id+"']").show();
		 */
		tab(this);
		return false;
	});

	$("#media > ul li a").click(function() {
		tab(this);
		return false;
	});

	$("#videos > ul li a").click(function() {
		tab(this);
		return false;
	});

	$("#orai > ul li a").click(function() {
		tab(this);
		return false;
	});

});

function tab(e) {
	id = $(e).attr('href').replace(/#/g, '');

	// $(e).parents("div:first").find("div").hide();
	first = $(e).parents("div:first")[0];
	$("> div", first).hide();

	$(e).parents("div:first").find("*").removeClass("current");

	$(e).parent().addClass("current");

	$(e).parents("div:first").find("div[class*='" + id + "']").show();
	return false;
}

function viewport() {
	var x, y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	} else if (document.documentElement
			&& document.documentElement.clientHeight)
	// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [ x, y ];
}

function scrollsize() {
	var x, y;
	if (self.pageYOffset) // all except Explorer
	{
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop)
	// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return [ x, y ];
}
var v = {
	w : null,
	h : null,
	x : null,
	y : null
}
function video_maximize() {
	m = document.getElementById("video");
	/*
	 * m.style.marginBottom = "-22em"; m.style.height = "56em";
	 * m.style.marginRight = "-25.5em"; m.style.width = "65.5em"; m.style.top =
	 * "-10em"; m.style.left = "-1em";
	 */
	v.w = m.offsetWidth;
	v.h = m.offsetHeight;
	// console.log(v);

	m.style.marginLeft = "-1px";
	m.style.padding = "0";
	m.style.position = "absolute";
	m.style.left = "-10px";
	m.style.top = "-2px";
	m.style.width = "1000px";
	m.style.height = viewport()[1] - 20 + "px";

	// $(m).parent().css({"position":"static"});
}
function video_minimize() {
	// console.log(v);
	m = document.getElementById("video");
	m.style.width = v.w / 10 + "px";
	m.style.height = v.h / 10 + "px";
	m.style.position = "relative";
	m.style.top = "0";
	m.style.left = "0";
}

function popup(href, title, width, height, center) {
	var left = 100;
	var top = 100;
	if (center) {
		left = (screen.width - width) / 2;
		top = (screen.height - height) / 2;
	}
	window
			.open(
					href,
					title,
					'width='
							+ width
							+ ', height='
							+ height
							+ ', left='
							+ left
							+ ', top='
							+ top
							+ ', directories=no, location=no, resizable=no, menubar=no, toolbar=no, scrloobars=no, status=no');
	return false;
}

function findPos(obj) { // quirksmode
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [ curleft, curtop ];
}

function get_cookie(cookie_name) {
	var results = document.cookie
			.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
	if (results)
		return (unescape(results[2]));
	else
		return null;
}
function changeArrow()
{
	if($('#toggleLoginForm').attr('class') == 'arrowUp')
	{
		$('#toggleLoginForm').removeClass('arrowUp').addClass('arrowDown');
		
	}
	else
	{
		$('#toggleLoginForm').removeClass('arrowDown').addClass('arrowUp');
	}
}
function writeUserMenu(containerId, height)
{
    var status = get_cookie("epasas_status");
    var url = get_cookie("epasas_frameUrl");
    
    if (!status || !url)
    {
        $('#' + containerId).html("<p>Norėdami prisijungti, turite įsijungti slapukus</p>");
        return;
    }
    
    var templates = {
        "anonymous": '<div id="toggleLoginForm" class="arrowDown">'
                     + '<a href="#" onclick="$(\'#EpasasFrame\').toggle(); changeArrow(); return false"> </a>'
                     + '</div>'
                     + '<style> #EpasasFrame { display: none; }</style>'
                     + '<iframe width="290" height="'+height+'" id="EpasasFrame" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" src="{$url}"></iframe>',
        "user": '<iframe width="290" height="'+height+'" id="EpasasFrame" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" src="{$url}"></iframe>' 
                + '<ul class="userMenu">' 
                + '<li><a href="/naujienlaiskiu-nustatymai">Naujienlaiškiai</a></li>' 
                + '<li><a href="/anketa">Mano anketa</a></li>'
                + '</ul>' 
    };

    var html = templates[status].replace('{$url}', url);
    
    $('#' + containerId).html(html);
}

/* scrollai */
$(document).ready( function () {
    var $cronics = $("#stickyCronics");
    var $menu = $('#stickyMenu');
    var $tops = $('#stickyTops');
    var $bottomline;
    
    // check if we have videobox - then floater should stop at the top of it
    if ($('div.videobox').length > 0) {
	$bottomline = $('div.videobox');
	bottomlineTopOffset = 30;
    // if not - set vbar as the bottom menu
    } else {
	$bottomline = $('#bottom');
	bottomlineTopOffset = 15;
    }
    
    cbar = $cronics.offset();
    mbar = $menu.offset();
    tbar = $tops.offset();
    vbar = $bottomline.offset();
    
    if (cbar == undefined || mbar == undefined || tbar == undefined || vbar == undefined)
        return;
    
    
    $(window).scroll(function() {
	
	if ($(window).scrollTop() > mbar.top) {
		if ($cronics.length > 0) {
			if ($(window).scrollTop() + $menu.height() + 7 + $cronics.height() < vbar.top - bottomlineTopOffset) {
				$menu.stop().animate({ top: $(window).scrollTop() - mbar.top + 15 }, 0);
				$cronics.stop().animate({ top: $(window).scrollTop() - cbar.top + $menu.height() + 7 + 15 }, 0);
			}
		} else {
			if ($(window).scrollTop() + $menu.height() < vbar.top - bottomlineTopOffset) {
				$menu.stop().animate({ top: $(window).scrollTop() - mbar.top + 15 }, 0);
			}
		}
	}
	if ($(window).scrollTop() < mbar.top) {
		if (mbar.top < $menu.offset().top) {
			$menu.stop().animate({ top: 0 }, 0);
		}
		if ($cronics.length > 0) {
			if (cbar.top < $cronics.offset().top) {
				$cronics.stop().animate({ top: 0 }, 0);
			}
		}
	}

        if ($(window).scrollTop() > tbar.top && $(window).scrollTop() + $tops.height() < vbar.top - bottomlineTopOffset) {
		$tops.stop().animate({ top: $(window).scrollTop() - tbar.top + 15 }, 0);
	}
	if ($(window).scrollTop() < tbar.top) {
		if (tbar.top < $tops.offset().top) {
			$tops.stop().animate({ top: 0 }, 0);
		}
	}
    });
});
