var docType = "HTML";
var isSafari = navigator.appVersion && navigator.appVersion.indexOf("Safari",0)>=0;
var IE  = (document.all) ? true : false;                      // ie4+
if(navigator.userAgent.indexOf("Opera") != -1) var O = true;  // Opera
// JavaScript Document
var agent = navigator.userAgent;
//alert(agent);
var version = parseFloat(navigator.appVersion);
var isOpera = agent.indexOf("Opera") > -1;
var isIE = agent.indexOf("compatible") > -1 && agent.indexOf("MSIE") > -1 && !isOpera;
var isGecko = agent.indexOf("Gecko") > -1;
var isFF = isGecko && agent.indexOf("Firefox") > -1;
var isNetscape=navigator.appName.indexOf("Netscape")!=-1;
var isIE7 = agent.indexOf("MSIE 7") > -1;

function dialog(url, _width, _height) {
	if(IE) window.event.cancelBubble = true; //Kad neeitu i ta linka kuri paspaudeme
	if(IE) window.event.returnValue = false; //paspaudej - ir nieko negrazino tau!!!
	var pav;
	nr_temp=Math.floor(Math.random()*1000);
	if (arguments[3]) pav=arguments[3];
		else pav=nr_temp;
	if (arguments[4]) scrollbar="yes";
		else scrollbar="no";
	window.open(url, pav, "top=100, left=100, width="+_width+", height="+_height+", menubar=no, resizeable=yes, scrollbars="+scrollbar+", staus=1, toolbar=no, location=no, directories=no");
}

function get_width() {
	return Math.max(Math.round(document.body.clientWidth/2), 390) - 176;
}

function get_menu(obj) {
	var temp_obj=obj;
	for (i=0; i<3; i++)
		temp_obj = (IE) ? temp_obj.parentElement : temp_obj.parentNode;
	return temp_obj.offsetLeft + Math.max(Math.round(document.body.clientWidth/2)-394, -5);
}

function get_height() {
	return Math.max(Math.round(document.body.clientHeight/2), 280) - 195;
}

///// menu

var im_src=new Array('arrow','arrow.over','arrow.menu','arrow.menu.over', 'plus.gif', 'minus.gif', 'bullet.gif');
var im=new Array();
for (i=0; i<im.length; i++) {
	im[i]=new Image();
	im[i].src="images/"+im_src[i]+".gif";
}

var last_obj = new Object();
var menu_obj = new Object();
var menu_arr = new Array();
var menu_nr=1;
var menu_top = 161;

						 //new menu   parent    naujo_nr
function menu_over(tr_obj, menu_name, obj_name, temp_nr) {
	var x, y, tr_obj, temp, offset_x=(IE) ? 0: 5;
	if (IE)	event.cancelBubble=true; //!!
	menu_obj = document_all("menu_"+menu_name);
		menu_kill(temp_nr);
		menu_arr[temp_nr]=menu_obj;
	tr_obj.className="menu_tr_over";
	if (arguments.length<5) { //From sub menu
		last_obj = document_all("menu_"+obj_name);
		if (IE) x = last_obj.style.pixelLeft  + last_obj.clientWidth + offset_x;
		else {
			temp=last_obj.style.left;
			x=temp.substr(0, temp.length-2)*1 + tr_obj.offsetWidth + offset_x + "px";//last_obj.style.width;
		}
		if (IE) y = last_obj.style.pixelTop   + tr_obj.offsetTop;
		else {
			temp=last_obj.style.top;
			y=temp.substr(0, temp.length-2)*1 + tr_obj.offsetTop + "px";
		}
	} else { //From main menu
		x = arguments[4];
		y = menu_top + tr_obj.offsetTop;
	}
	if (is_object(menu_obj)) { //draw menu
		menu_obj.style.left=x;
		menu_obj.style.top =parseInt(y)-10+"px";
	}
}


function menu_make (menu_name) { //shot name
	var all="", arrow, tr_over, arr, row;
		var re = new RegExp("([_]+)", "g");
			var temp_len = menu_name.replace(re, "");
		temp_nr = menu_name.length - temp_len.length; //kiek "_";
	all ="<DIV ID=\"menu_"+menu_name+"\" class=air onmouseover=\"event.cancelBubble=true;\" width=1 height=1>";  //ID=>IE,
	all+="<TABLE cellpadding=0 cellspacing=0><TR><TD valign=top><IMG src=\"images/spacer.gif\"  width=5 height=29></TD><TD>";
	all+="<TABLE cellpadding=0 cellspacing=0 style='border: 0px solid #013364; background-color: #288EC1;'>";
	all+=row="<TR class=menu_tr height=10><TD colspan=3></TD></TR>";
	for (var i=1; i<arguments.length; i++) {
		arr=arguments[i];
		if (!arr[2]) arr[2]=arrow="";
				else arrow="class=arrow_menu";
		tr_over="onmouseover=\"menu_over(this, '"+arr[2]+"','"+menu_name+"',"+(temp_nr+1)+");\"";
		//all+="<TR class=menu_tr height=2><TD colspan=3></TD></TR>";
		all+="<TR ID=tr_"+arr[2]+" "+tr_over+" class=menu_tr onmouseout=\"menu_out(this);\" onclick=\"menu_click('"+arr[1]+"');\" height=19><TD width=15></TD><TD>"+arr[0]+"</TD><TD width=22 "+arrow+"></TD></TR>";
		//all+="<TR class=menu_tr height=2><TD colspan=3></TD></TR>";
	}
	all+=row;
	all+="</TABLE>";
	all+="</TD></TR></TABLE>";
	all+="</DIV>";
	document.writeln(all);
}


function menu_kill(temp_nr, evn) {
	if (!IE && !temp_nr && (evn.target.tagName=="TD" || evn.target.tagName=="A")) //for body
			return false; //panasiai kaip cancelBubble
	if (temp_nr>10) temp_nr=1;
	for (var i=temp_nr; i<=menu_nr; i++) {
		temp_obj = menu_arr[i];
		if (is_object(temp_obj)) {
			temp_obj.style.left="-1000px";
			menu_arr[i].last_tr.className="menu_tr";
		}
	}
	menu_nr=temp_nr; //sumaziname menu_nr, kad greiciau veiktu po to
}


function menu_out (tr_obj) {
	///2004-07-29
	if (is_object(menu_arr[menu_nr]))
		 menu_arr[menu_nr].last_tr=tr_obj; //nuoroda i paskutini pazymeta "tr"
	else
		 tr_obj.className="menu_tr";
}


function menu_click(temp_href) {
	window.document.location.href=temp_href;
}


function document_all(temp_id) {
	return (IE) ? document.all[temp_id]: document.getElementById(temp_id);
}


function is_object(temp_obj) {
	return (temp_obj=="[object]" || temp_obj=="[object HTMLDivElement]");
}


//////// for resizing iframe height /////////
function adjustIFrameSize (iframeWindow) {
	if (iframeWindow.document.height) {
		var iframeElement = parent.document.getElementById(iframeWindow.name);
		iframeElement.style.height = iframeWindow.document.height + 'px';
//		iframeElement.style.width = iframeWindow.document.width + 'px';
	}
	else if (document.all) {
		var iframeElement = parent.document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat') {
			iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 3 + 'px';
//			iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
		}
		else {
			iframeElement.style.height = iframeWindow.document.body.scrollHeight + 3 + 'px';
//			iframeElement.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
		}
  	}
}

/*
*   NEW IMAGE SHOWING AND POPUP METHODS
*   By Viacheslav 2008-03-05
*   Function openPopup may be used for other than showing image purposes
*   openPopup( opacity, background_color, html_code_of_popup );
*   opacity and background_color is for the surrounding area.
*   opacity must be a value from 0 to 100
*   background color is given as a CSS style (ex.: #FFFF00)
*   if no html code is given then only overlay will be visible
*/
function getBodyWidth() {
	if( (isFF || isNetscape || isIE7 || isOpera) && docType == "XHTML" )
        return document.documentElement.scrollWidth;
    return document.body.scrollWidth;
}
function getBodyHeight() {
	if( (isFF || isNetscape || isIE7 || isOpera) && docType == "XHTML" )
        return document.documentElement.scrollHeight;
    return document.body.scrollHeight;
}
function getScrollLeft() {
	if( !isIE )
	    return window.pageXOffset;
	return ( docType == "XHTML" )?document.body.parentNode.scrollLeft:document.body.scrollLeft;
}
function getScrollTop() {
	if( !isIE )
	    return window.pageYOffset;
	return ( docType == "XHTML" )?document.body.parentNode.scrollTop:document.body.scrollTop;
}
function getVisibleBodyWidth() {
	if( isOpera || docType != "XHTML" )
	    return document.body.clientWidth;
    return document.body.parentNode.clientWidth;
}
function getVisibleBodyHeight() {
	if( isOpera || docType != "XHTML" )
	    return document.body.clientHeight;
    return document.body.parentNode.clientHeight;
}
function getElementWidth( elm ) {
	return elm.offsetWidth;
}
function getElementHeight( elm ) {
	return elm.offsetHeight;
}
function getElementLeft( elm ) {
	var x = 0, p = elm;
	do x += p.offsetLeft; while(p = p.offsetParent);
	return x;
}
function getElementTop( elm ) {
	var y = 0, p = elm;
	do y += p.offsetTop; while(p = p.offsetParent);
	return y;
}
function mouseX(e) {
	return e.pageX?e.pageX:(e.clientX + getScrollLeft()) - ((isIE && !isOpera)?2:0);
}
function mouseY(e) {
	return e.pageY?e.pageY:(e.clientY + getScrollTop()) - ((isIE && !isOpera)?2:0);
}

var CurrentPopup = null;
var InnerPopupBlock = null;
var SizingTimer = null;
var OriginalWidth = 0;
var OriginalHeight = 0;

function checkPopup() {
	var width, height, w1,w2,h1,h2;
	if( !CurrentPopup ) {
	    clearTimeout( SizingTimer );
	    return;
	}
	w1 = OriginalWidth;
	w2 = getVisibleBodyWidth();
	h1 = OriginalHeight;
	h2 = getVisibleBodyHeight();
	width = ((w1>w2)?w1:w2);
	height = ((h1>h2)?h1:h2);
	CurrentPopup.style.width = width + "px";
	CurrentPopup.style.height = height + "px";
	CurrentPopup.style.background = CurrentPopup.setBG;

	InnerPopupBlock.style.display = "block";
	w1 = getElementWidth( InnerPopupBlock );
	h1 = getElementHeight( InnerPopupBlock );
	InnerPopupBlock.style.left = (getScrollLeft() + ((w2-w1) / 2)) + "px";
	InnerPopupBlock.style.top = (getScrollTop() + ((h2-h1) / 2)) + "px";
}

function closePopup() {
	if( !CurrentPopup )
	    return;
    clearTimeout( SizingTimer );
    SizingTimer = null;
	if( InnerPopupBlock.parentNode )
		InnerPopupBlock.parentNode.removeChild( InnerPopupBlock );
	if( CurrentPopup.parentNode )
		CurrentPopup.parentNode.removeChild( CurrentPopup );
	delete InnerPopupBlock;
	delete CurrentPopup;
	InnerPopupBlock = CurrentPopup = null;
	if( window.event ) {
    	window.event.cancelBubble = true;
    	window.event.returnValue = false;
	}
    return false;
}

function openPopup( opacity, bg, html, center_noclick, surrounding_noclick ) {
	var div, div2, width, height, w1,w2,h1,h2;
	if( CurrentPopup )
	    closePopup();

	div = document.createElement( "DIV" );
	div.style.zIndex = "100000";
	div.style.position = "absolute";
	div.style.left = "0";
	div.style.top = "0";
	w1 = OriginalWidth = getBodyWidth();
	w2 = getVisibleBodyWidth();
	h1 = OriginalHeight = getBodyHeight();
	h2 = getVisibleBodyHeight();
	width = ((w1>w2)?w1:w2);
	height = ((h1>h2)?h1:h2);
	div.style.width = width + "px";
	div.style.height = height + "px";
	if( IE && !O )
	    div.style.filter = "alpha(opacity=" + opacity + ")";
	else
		div.style.opacity = Math.floor(opacity) / 100.0;
	div.setBG = bg;
	if( !surrounding_noclick ) {
		div.style.cursor = "pointer";
		div.onclick = closePopup;
	}

	div2 = document.createElement( "DIV" );
	div2.innerHTML = html;
	div2.style.position = "absolute";
	div2.style.zIndex = "100001";
	div2.style.display = "none";
	div2.style.left = "-10000px";
	div2.style.top = "-10000px";
	if( !center_noclick ) {
		div2.style.cursor = "pointer";
		div2.onclick = closePopup;
	}

	InnerPopupBlock = div2;
	CurrentPopup = div;
	document.body.appendChild( div );
	document.body.appendChild( div2 );
	SizingTimer = setInterval( "checkPopup();", 50 );
}

function popupImage( src, w, h, opacity, bg, do_start ) {
	var img;
	if( !opacity ) opacity = 50;
	if( !bg ) bg = "black";
	if( !do_start ) {
		openPopup( opacity, bg, "<div style='position:relative; background:white; width:42px; height:42px;'><div style='position:relative; padding:5px;'><img src=\"images/loading.gif\" width=\"32\" height=\"32\" /></div></div>" );
		setTimeout( "popupImage( '" + src + "', " + w + ", " + h + ", " + opacity + ", '" + bg + "', true );", 10 );
	} else {
	    img = new Image();
		img.doWidth = w;
		img.doHeight = h;
		img.onload = function() {
		    var w, h;
		    if( !InnerPopupBlock )
		        return;
		    if( !this.doWidth ) this.doWidth = this.width;
		    if( !this.doHeight ) this.doHeight = this.height;
		    InnerPopupBlock.style.display = "none";
   		    InnerPopupBlock.innerHTML = "<div style='position:relative; background:white; width:" + (this.doWidth+10) + "px; height:" + (this.doHeight+10) + "px;'><div style='position:relative; padding:5px;'><img src=\"" + this.src + "\" width=\"" + this.doWidth + "\" height=\"" + this.doHeight + "\" /></div></div>";
		}
	    img.src = src;
	}
	if( window.event ) {
    	window.event.cancelBubble = true;
    	window.event.returnValue = false;
	}
    return false;
}

function buildup() {
	var txt = "";
	for( var i=0; i<arguments.length; i++ )
		txt = arguments[i] + txt;
	document.write( "<a target=\"_blank\" href=\"mailto:" + txt + "\">" + txt + "</a>" );
}

function showGMap(id, point, size, height) {
	var html = '<div style="border: 4px solid #ffffff; overflow: hidden;">' +
		'<div id="' + id + '" mapx="' + point.x + '" mapy="' + point.y + '" maph="' + height + '" ' +
		'style="overflow: hidden; width: ' + size.w + 'px; height: ' + size.h + 'px;">'+'<'+'!-- --'+'>'+
		'</div></div>';
	openPopup( 50, "#000000", html, true, false, false );
	setTimeout("testGMapReady('" + id + "')", 100);
}

var gmaps_map = null;
var gmaps_geocoder = null;
var gmaps_debug_marker = null;
function drawGMap(id, point, height) {
	if (GBrowserIsCompatible()) {
		var o = null, map = null;
		o = document.getElementById(id);
		if (!o) return false;
		map = new GMap2(o);
		gmaps_map = map;
		//map.addControl(new GSmallMapControl());
		//map.addControl(new GLargeMapControl());
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
		map.addControl(new GLargeMapControl3D(), topRight);
		
		if (point) {
			map.setCenter(new GLatLng(point.x, point.y), height);
			map.addOverlay(createMarker(new GLatLng(point.x, point.y), null));
		} else {
			map.setCenter(new GLatLng(55.698541, 21.147317), height);
		}
		if (!gmaps_geocoder) gmaps_geocoder = new GClientGeocoder();
		
		var gdebug = document.getElementById("gmaps_debug");
		if (gdebug) {
			var center = gmaps_map.getCenter();
			gmaps_debug_marker = new GMarker((center ? center : { x: 0, y: 0 }), { draggable: true });
			GEvent.addListener(gmaps_debug_marker, "dragend", function() {
				var gdebug = document.getElementById("gmaps_debug");
				if (gdebug) {
					var center = gmaps_map.getCenter();
					gdebug.innerHTML = center.x + "," + center.y;
				}
			});
			gmaps_map.addOverlay(gmaps_debug_marker);
			function AddressSearch() {}
			AddressSearch.prototype = new GControl();
			
			AddressSearch.prototype.initialize = function(map) {
				var container = document.createElement("div");
				var input = document.createElement("input");
				var btn = document.createElement("input");
				input.type = "text";
				input.id = "gmaps_address_search";
				btn.type = "button";
				container.appendChild(input);
				container.appendChild(btn);
				GEvent.addDomListener(btn, "click", function() {
					var inp = document.getElementById("gmaps_address_search");
					if (inp) { showAddress(inp.value); }
				});
				GEvent.addDomListener(input, "keyup", function(event) {
					if (event.keyCode == 13) {
						var inp = document.getElementById("gmaps_address_search");
						if (inp) { showAddress(inp.value); }
					}
				});
				
				gmaps_map.getContainer().appendChild(container);
				return container;
			}

			gmaps_map.addControl(new AddressSearch());
			/*GEvent.addListener(map, "moveend", function() {
				var center = map.getCenter();
				
				mes.innerHTML = "Koordinates: " + center.toString();
			});*/
		}
		return map;
	}
	return null;
}

function showAddress(address) {
	if (gmaps_geocoder) {
		gmaps_geocoder.getLatLng(address,
			function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					gmaps_map.setCenter(point, gmaps_map.getZoom());
					gmaps_debug_marker.setLatLng(point);
					var gdebug = document.getElementById("gmaps_debug");
					if (gdebug) {
						gdebug.innerHTML = point.x + "," + point.y;
					}
				}
			}
		);
	}
}

function createMarker(point, content, opt) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = base_addr + "images/marker.png";
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	if (content) GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(content, opt); });
	return marker;
}

function createMarkerFromAddress(address, content) {
	if (gmaps_geocoder) {
		gmaps_geocoder.getLatLng(address,
			function(point) {
				if (!point) {
					//alert(address + " not found");
				} else {
					gmaps_points[gmaps_points.length] = point;
					address.map.setCenter(getAveragePoint(), address.map.getZoom());
					address.map.addOverlay(createMarker(point, address.content, address.opt));
				}
			}
		);
	}
}

var gmaps_points = new Array();
var gmaps_alp = false;

function getAveragePoint() {
	var min_x = false, max_x = 0, min_y = 0, max_y = 0;
	for (var i = 0; i < gmaps_points.length; i++) {
		if (min_x === false) {
			min_x = max_x = gmaps_points[i].x;
			min_y = max_y = gmaps_points[i].y;
		} else {
			if (gmaps_points[i].x < min_x) min_x = gmaps_points[i].x;
			if (gmaps_points[i].x > max_x) max_x = gmaps_points[i].x;
			if (gmaps_points[i].y < min_y) min_y = gmaps_points[i].y;
			if (gmaps_points[i].y > max_y) max_y = gmaps_points[i].y;
		}
	}
	var x = (min_x + max_x) / 2;
	var y = (min_y + max_y) / 2;

	return new GLatLng(y, x);
}

function testGMapReady(id) {
	var cont = document.getElementById(id);
	if (cont) {
		if (cont.clientWidth > 0 && cont.clientHeight > 0) {
			var map = drawGMap(id, false, 14);
			var mtype = cont.getAttribute("mtype");
			if (mtype) map.setMapType((mtype == 'hybrid') ? G_HYBRID_MAP : G_NORMAL_MAP);
			var data = cont.getAttribute("lang");
			if (data) {
				var list = data.split("#");
				var inf = urldecode(cont.getAttribute("info")).split("##");
				var h = list[0]*1; if (h > 0) map.setZoom(h);
				var pc = 0;
				for (var i = 1; i < list.length; i++) {
					if (list[i]) createMarkerFromAddress(
						{ map: map, content: inf[i - 1], address: list[i], opt: { maxWidth: 148 },
							toString: function() { return this.address; } }, null);
				}
			}
		} else {
			setTimeout("testGMapReady('" + id + "')", 100);
		}
	}
}

function urldecode( str ) {
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    ret = decodeURIComponent(ret);
 
    return ret;
}

/*
function testGMapReady(id) {
	var cont = document.getElementById(id);
	if (cont) {
		if (cont.clientWidth > 0 && cont.clientHeight > 0) {
			var map = drawGMap(id, false, 0);
			var data = cont.getAttribute("lang");
			if (data) {
				var x = 0, y = 0, h = 0, centerIsSet = false;
				var list = data.split("#");
				if (list.length > 0) {
					data = list[0].split(",");
					if (data.length > 0) h = data[0]*1;
					if (data.length > 2) {
						x = data[1]*1;
						y = data[2]*1;
						map.setCenter(new GLatLng(x, y), h);
						centerIsSet = true;
					}
				}
				for (var i = 1; i < list.length; i++) {
					data = list[i].split(",");
					if (data.length > 0) x = data[0]*1;
					if (data.length > 1) y = data[1]*1;
					if (!centerIsSet) { map.setCenter(new GLatLng(x, y), h); centerIsSet = true; }
					map.addOverlay(createMarker(new GLatLng(x, y), null));
				}
			}
		} else {
			setTimeout("testGMapReady('" + id + "')", 100);
		}
	}
}*/