// JavaScript Document utf8 čęįėčųį9ėį ывшывародж
var cookieDays = 0;
if (readCookie('rememberMe') == 'yes') { cookieDays = 365; }

var map360open = false;
function change360state()
{
	var open_timing = 500;
	if (!map360open)
	{
		createCookie('map360Ostate','open',cookieDays);
		$('#stores_nearest_btn').fadeOut(200);
		$('#ch_state').hide(200,function()
		{
			_obj('ch_state_img').src = 'images/map_close_'+def_language+'.png';
			$('#ch_state').show(200);
		});
		$('.vid_cont').stop().animate({marginTop:"-4px"},open_timing,function(){$('.map_navigation').fadeIn(200); $('.map_left_side').add('.map_right_side').css('display','block'); } );
		$('.inncont_lbord').add('.inncont_rbord').stop().animate({height:"0px"},open_timing);
		$('.inncont_lshad').add('.inncont_rshad').stop().animate({marginTop:"0px"},open_timing);
		$('.marker').animate({top:"22px"},open_timing);
	}
	else
	{
		createCookie('map360Ostate','closed',cookieDays);
		$('.map_left_side').add('.map_right_side').css('display','none');
		$('.map_navigation').fadeOut(200,function()
		{
			$('#ch_state').hide(200,function()
			{
				_obj('ch_state_img').src = 'images/map_open_'+def_language+'.png';
				$('#ch_state').show(200);
				$('#stores_nearest_btn').fadeIn(200);
			});
			$('.vid_cont').stop().animate({marginTop:"-330px"},open_timing);
			$('.inncont_lbord').add('.inncont_rbord').stop().animate({height:"330px"},open_timing);
			$('.inncont_lshad').add('.inncont_rshad').stop().animate({marginTop:"330px"},open_timing);
			$('.marker').animate({top:"7px"},open_timing);
		});
	}
	map360open = !map360open;
}

function resetAllCookies()
{
	eraseCookie('map360Ostate');
	eraseCookie('rememberMe');
	eraseCookie('m360marketSet');
	eraseCookie('m360mapAngle');
	eraseCookie('iam18');
	eraseCookie('m360marketLat');
	eraseCookie('m360marketLng');
	eraseCookie('m360mapZoom');
	eraseCookie('m360mapType');
	eraseCookie('m360mapAngle');
	eraseCookie('NearestStoreId');
	eraseCookie('NearestStoreDistance');
	eraseCookie('GTowerDistance');
	page_refresh();
}

function scrolltop(y)
{
	var vscroll_speed = 800;	
	var timing = Math.round(($(window).scrollTop()-y)/vscroll_speed*1000);
	if (timing<0) { timing = -1 * timing; }
	$('html, body').animate({scrollTop : y},timing);
}


var pbar_animate = false;
function pbar_start()
{
	pbar_animate = true;
	pbar_cycle();
}
function pbar_stop()
{
	pbar_animate = false;
	$('.prbar').stop();
	pbar_animate = false;
}
function pbar_cycle()
{
	if (pbar_animate) 
	{ 
		$('.prbar').animate({width:"100%"},1600,function()
		{
			$('.prbar').animate({width:"7%"},100,function(){ pbar_cycle(); });
		}); 
	}
}

var remember_iam18 = false;
function remember_chstate()
{
	$('.rem_inp').fadeOut(200,function()
	{
		if (!remember_iam18)
		{
			_obj('rem_inp').innerHTML = 'X';
		}
		else
		{
			_obj('rem_inp').innerHTML = '';
		}
		remember_iam18 = !remember_iam18;
		$('.rem_inp').fadeIn(200);
	});	
}

var global_angle = 0;


function hide_intro(noanimation)
{
	var markerIsSet = false;
	var defaultAngle = 225;
	if (readCookie('m360marketSet') == 'yes') { markerIsSet = true; }
	
	$('.prbar').stop();
	$('.rem_inp').stop();
	$('.question_cont').stop();
	$('.progress_cont').stop();
	
	if (markerIsSet) { m360Move2Angle(parseFloat(readCookie('m360mapAngle')),true); }
	else { if(!startpage) { m360Move2Angle(defaultAngle,true); } }
	
	var langAnimTime = 300;
	if (noanimation) { langAnimTime = 0; }
	$('.intro_body').add('.intro_languages').fadeOut(langAnimTime,function()
	{
		$('.page_height_block').css('display','block');

		if (startpage)
		{
			scroll(0,0);
			if(!markerIsSet) { m360Move2Angle(defaultAngle); }
			$('.left_bg').animate({width: '0%'},1600);
			$('.right_bg').animate({left:'100%'},1600,function()
			{
				$('.left_bg').fadeOut(0);
				$('.right_bg').fadeOut(0);
				$('.intro_cont').fadeOut(0);
				$('#bdy').removeClass("modal");
			});
			
			$.doTimeout(3100,function() 
			{
				//titulinio produktu animacija
				$('.product').mouseenter(function(e)
				{
					$(this).children('.img_cont').children('img').animate({width: '100%', marginTop:'0px', marginLeft:'20px'}, pres_product_over_time);
					$(this).children('.bg').fadeOut(pres_product_over_time);
				}).mouseleave(function(e)
				{
					$(this).children('.img_cont').children('img').animate({width: '92%', marginTop:'20px', marginLeft:'26px'}, pres_product_over_time);
					$(this).children('.bg').fadeIn(pres_product_over_time);
				});
				
				window.onresize = resizer;
				window.onscroll = scroller;
				
				//move maps
				$('.map_left').add('.map_left_side').mouseenter(function(e) { $('.map_left').stop().animate({opacity: 0.5},0,'', function() { $(this).animate({opacity: 1},300); }); m360Animate(1); }).mouseleave(function(e) { m360AniStop(); });
				$('.map_right').add('.map_right_side').mouseenter(function(e) { $('.map_right').stop().animate({opacity: 0.5},0,'', function() { $(this).animate({opacity: 1},300); }); m360Animate(-1); }).mouseleave(function(e) { m360AniStop(); });
				bindKeys();
	
				if((slide_count > 0)&&(slide_autostart == '1')) { slide_play(); } 
			});
			
		}
		else
		{
			var innerAniTime = 700;
			if (noanimation) { innerAniTime = 0; }
			$('.left_bg').animate({width: '0%', 'opacity':'0'},innerAniTime);
			$('.right_bg').animate({left:'100%', 'opacity':'0'},innerAniTime,function()
			{
				$('.left_bg').fadeOut(0);
				$('.right_bg').fadeOut(0);
				$('.intro_cont').fadeOut(0);
				$('#bdy').removeClass("modal");

				window.onresize = resizer;
				window.onscroll = scroller;

				//move maps
				$('.map_left').add('.map_left_side').mouseenter(function(e) { $('.map_left').stop().animate({opacity: 0.5},0,'', function() { $(this).animate({opacity: 1},300); }); m360Animate(1); }).mouseleave(function(e) { m360AniStop(); });
				$('.map_right').add('.map_right_side').mouseenter(function(e) { $('.map_right').stop().animate({opacity: 0.5},0,'', function() { $(this).animate({opacity: 1},300); }); m360Animate(-1); }).mouseleave(function(e) { m360AniStop(); });
				bindKeys();

				if((slide_count > 0)&&(slide_autostart == '1')) { slide_play(); } 
				
			});
		}
	});
}

var bindKeyDone = false;
var clicked = 0;
var last_key = '';
function bindKeys()
{
	if (!bindKeyDone)
	{
		bindKeyDone	= true;
		$(document).keydown(function(objEvent)
		{
			clicked++;
			_obj('fromST').innerHTML = clicked;
			if (objEvent.keyCode == 27 ) { escClick(); }
			if (last_key == '')
			{
				last_key = objEvent.keyCode;
				if (objEvent.keyCode == 37 ) { m360Animate(1); }
				if (objEvent.keyCode == 39 ) { m360Animate(-1); }
			}
		}).keyup(function(objEvent)
		{
			if (objEvent.keyCode == 37 ) { last_key = ''; m360AniStop(); }
			if (objEvent.keyCode == 39 ) { last_key = ''; m360AniStop(); }
		});
	}
}

function escClick()
{
	if (myPosModalVisible) { moPosModalCloseClk(); }
}

function iam18()
{
	if (remember_iam18) 
	{
		createCookie('rememberMe','yes',365);
		cookieDays = 365;
	} 
	else 
	{ 
		createCookie('rememberMe','no',0);
		cookieDays = 0;
	}
	
	createCookie('iam18','confirmed',cookieDays);
	if (!doc_loaded)
	{
		$('.question_cont').fadeOut(200,function()
		{
			$('.progress_cont').fadeIn(200);
			pbar_start();
		});
	}
	else
	{
		hide_intro();
	}
}

function iamtooyoung()
{
	_obj('question_cont').style.display = 'none';
	_obj('tooYoungMsg').style.display = 'block';
}


var doc_loaded = false;
var product_over_time = 200;
var pres_product_over_time = 150;
$(document).ready(function() 
{
	scroll(0,0);
	
	//start procedure
	if (readCookie('iam18') != 'confirmed')
	{
		_obj('question_cont').style.display = 'block';
	}
	else
	{
		if(startpage)
		{
			_obj('progress_cont').style.display = 'block';
			pbar_start();
		}
		else
		{
			hide_intro(true);
		}
	}
	
	//produktu sarasas
	$('.product_cont').mouseenter(function(e)
	{
		$(this).children('a.ilu').children('img').animate({width: '100%', marginTop:'0px', marginLeft:'0px'}, product_over_time);
		$(this).children('a.more1').fadeOut(product_over_time);
		$(this).children('a.more2').fadeIn(product_over_time);
	}).mouseleave(function(e)
	{
		$(this).children('a.ilu').children('img').animate({width: '85%', marginTop:'20px', marginLeft:'10px'}, product_over_time);
		$(this).children('a.more2').fadeOut(product_over_time);
		$(this).children('a.more1').fadeIn(product_over_time);
	});

	$('.progress_cont').click(function()
	{
		pbar_stop();
	});
	
	//tooltipai
	$('.tTData').each(function(index) 
	{
		var targetEl = $(this).attr('id').replace("_TT", "");
		var dataHTML = $(this).html();
		$(this).remove();
		$('.'+targetEl).mouseenter(function(e) { show_dTooltip($(this),dataHTML); }).mouseleave(function(e) { hide_dTooltip(); });
	});
	
	//blykstelejimo efektai
	if (!$.browser.msie)
	{
		$(".blink").live("mouseenter", function()
		{
			$(this).animate({opacity: 0.5},0,'', function() { $(this).animate({opacity: 1},300); });
		});
	}	

});



var dTooltip_init = false;
function show_dTooltip(targetObj,html)
{
	if (!dTooltip_init) 
	{
		$('body').append('<div id="dTooltip" class="dTooltip"><div id="dTooltipCont"><!-- --></div><div class="dToolTipArrow"><!-- --></div></div>'); 
		dTooltip_init = true;
	}
	$('#dTooltip').css({'left':'-900px'});
	_obj('dTooltipCont').innerHTML = html;
	var offset = targetObj.offset();

	if (targetObj.css('cursor') == 'pointer') { _obj('dTooltip').className = 'dTooltip mclk'; } else { _obj('dTooltip').className = 'dTooltip'; }

	_obj('dTooltip').style.left = (offset.left - 10)+'px';
	_obj('dTooltip').style.top = (offset.top - $('#dTooltip').outerHeight() - 20)+'px';
	$('#dTooltip').css('opacity','1').stop().fadeIn(100);
}
function hide_dTooltip()
{
	$('#dTooltip').stop().css({'display':'none','opacity':'1'}).fadeOut(300);
}

$(window).load(function() 
{
	doc_loaded = true;
	if (readCookie('iam18') == 'confirmed')
	{
		if ($.browser.msie && $.browser.version.substr(0,1)<8) //tikrinama narsykles versija
		{
			if (readCookie('bad_browser') != 'warned')
			{
				alert(error_bad_browser);
				createCookie('bad_browser','warned',0);
			}
		}
		if (startpage) { hide_intro(); }
	}
});


/* Scroller event difference */
var scroller_timeout = 500;
var scroller_timer = null;
function scroller()
{
	clearTimeout(scroller_timer);
	scroller_timer = setTimeout('scroller_action();', scroller_timeout);
}
function scroller_action()
{
	
}
/* Scroller event difference end */


/* Resizer event difference */
var resizer_timeout = 500;
var resizer_timer = null;
function resizer()
{
	clearTimeout(resizer_timer);
	resizer_timer = setTimeout('resizer_action();', resizer_timeout);
}
function resizer_action()
{
	update_postions();
}
/* Resizer event difference end */

function update_postions()
{
	if(myPosModalVisible) { myPosModalRedraw(); }
	wind_width = $(window).width();
	var left_offset = Math.round(($(window).width() - 960)/2);
	var bg_offset = Math.round(($(window).width() - 2000)/2);
	var intro_offset = Math.round($(window).height()/2)-150;
	$('.tools_cont').css('backgroundPosition',bg_offset+'px 0px');
	$('.product_pres').css('backgroundPosition',bg_offset+'px 0px');
	$('.main_cont').add('#tmenu').add('.map_navigation').css('marginLeft',left_offset+'px');
	$('.intro_body').css('marginTop',intro_offset+'px');
}


/*===================*/
/* zemelapio modalas */
/*===================*/

var myPosModalVisible = false;
var myPosModalMapLoaded = false;
var myPosModalMapStatus = '';
var myPosModalMap = null;
var myPosMarker = null;
var myPosMarkerImage = null;
var storeMarkerImage = null;
var last_active_iw = -1;
var directionsService = null;
var directionsDisplay = null;

var openStoreId = -1;
var openStoreIndex = -1;
function showStoreOnMap(store_id) //rodome parduotuve
{
	myPosModalMapStatus = 'showShop';
	openStoreId = store_id;
	openStoreIndex = getMarkerIndById(openStoreId);
	scroll(0,0);
	myPosModalShow();
}

function findNearestClck() //ieskome arciausios parduotuves
{
	myPosModalMapStatus = 'findNearest';
	scroll(0,0);
	myPosModalShow();
}

function showNearestOnMap() //show nearest shop
{
	var nearest = readCookie('NearestStoreId');	
	showStoreOnMap(nearest);
}

function myPosModalRedraw()
{
	var map_height = $(window).height() - 150 - 60;
	var modal_offset = Math.round(($(window).height() - map_height - 150)/2);
	$('#modal_map_cont').css('height',map_height + 'px');
	$('.modal_body').css('marginTop',modal_offset + 'px');
	$('.sh_top').css('marginTop',(-1*map_height) + 'px');
	$('.sh_left').add('.sh_right').css({'height':(map_height-16)+'px', 'marginTop':(-1*(map_height-8))+'px'});
}

function myPosModalHide()
{
	$('#bdy').removeClass("modal");
	$('#myPosModal').fadeOut(200);
	myPosModalVisible = false;
}

function moPosModalCloseClk() //tai kaip cancel mygtukas, jei tas kas jau buvo patvirtintas ir dabar pakeitus spaudzia - close, grazinam i patvirtinto tasko stovi
{
	myPosModalHide();
	nearest_ind = -1;
	$.doTimeout(500,function() 
	{
		myPosModalMap.setOptions({zoom:7, center:new google.maps.LatLng(55.2297794869,24.0498046875)});
		directionsDisplay.setMap(null);
		if (myPosMarker != null) { myPosMarker.setMap(null); }
		if (last_active_iw > -1) { markers[last_active_iw][7].close(); last_active_iw = -1; }
	});
}

function myPosModalShow()
{
	$('#bdy').addClass("modal");
	hide_dTooltip();

	if (myPosModalMapStatus == 'findNearest')
	{
		$('.btns a').css('display','block');
		_obj('myPosModalCap').innerHTML = myposmodalCap;
		_obj('myPosModalDescr').innerHTML = myposmodalDescr;
		$('.btns a').addClass("disabled");	
	}
	if (myPosModalMapStatus == 'showShop')
	{
		$('.btns a').css('display','none');
		_obj('myPosModalCap').innerHTML = markers[openStoreIndex][4];
		_obj('myPosModalDescr').innerHTML = '&nbsp;';
	}
	
	myPosModalRedraw();

	$('#myPosModal').fadeIn(300,function()
	{
		$('#myPosModal').stop();
		if (!myPosModalMapLoaded) { myPosModalLoadMap(); }

		if (readCookie('m360marketSet') == 'yes')
		{
			var myposLoc = new google.maps.LatLng(parseFloat(readCookie('m360marketLat')),parseFloat(readCookie('m360marketLng')));
			if (myPosMarker != null) { myPosMarker.setPosition(myposLoc); myPosMarker.setMap(myPosModalMap); }
			else { myPosMarker = new google.maps.Marker({position: myposLoc, map:myPosModalMap, icon:myPosMarkerImage, zIndex:1000}); }
			var nearestInd = getMarkerIndById(parseFloat(readCookie('NearestStoreId')));
			var destinationLoc = new google.maps.LatLng(markers[nearestInd][1],markers[nearestInd][2]);
			if ( (myPosModalMapStatus == 'showShop') && (openStoreIndex == nearestInd) ) { directionsDisplay.setOptions({preserveViewport: false}); }
			else { directionsDisplay.setOptions({preserveViewport: true}); }
			drawRouteToLocation(myposLoc,destinationLoc)
		}

		if (myPosModalMapStatus == 'findNearest')
		{
			myPosModalMap.setOptions({ draggableCursor: 'crosshair' });
			$.doTimeout(800,function() { directionsDisplay.setOptions({preserveViewport: false}); });
		}
		
		if ((myPosModalMapStatus == 'showShop')&&(openStoreId > -1))
		{
			if ( (myPosModalMapStatus == 'showShop') && (openStoreIndex == nearestInd) ) 
			{
			}
			else
			{
				myPosModalMap.setOptions({draggableCursor: 'default', zoom:13, center:new google.maps.LatLng(markers[openStoreIndex][1],markers[openStoreIndex][2])});
				directionsDisplay.setOptions({preserveViewport: true});
			}
			$.doTimeout(800,function() 
			{
				openInfoWindById(openStoreId);
				openStoreId = -1;
			});
		}
	});
	myPosModalVisible = true;
}

function myPosModalLoadMap()
{
	if (myPosModalMapLoaded) { return; }
	var mapZoom = 7;
	var mapLat = 55.2297794869;
	var mapLng = 24.0498046875;
	var mapType = google.maps.MapTypeId.HYBRID;
	if (readCookie('m360mapType') == 'hybrid') { mapType = google.maps.MapTypeId.HYBRID; } else { mapType = google.maps.MapTypeId.ROADMAP; }
	if ((myPosModalMapStatus == 'showShop')&&(openStoreId > -1))
	{
		mapZoom = 15;
		mapLat = markers[openStoreIndex][1];
		mapLng = markers[openStoreIndex][2];
	}
	var myOptions = 
	{
		zoom: mapZoom,
		maxZoom:17,
		center: new google.maps.LatLng(mapLat,mapLng),
		mapTypeId: mapType, //google.maps.MapTypeId.ROADMAP
		mapTypeControl: true, //paslepsim
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.TOP_RIGHT},
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN, position: google.maps.ControlPosition.TOP_LEFT},
		scaleControl: false,
		scaleControlOptions: {position: google.maps.ControlPosition.TOP_LEFT}
	}
		
	directionsService = new google.maps.DirectionsService();
    myPosModalMap = new google.maps.Map(document.getElementById("modal_map_cont"), myOptions);
	myPosMarkerImage = new google.maps.MarkerImage('images/marker_point.png', new google.maps.Size(39, 48), new google.maps.Point(0,0), new google.maps.Point(20, 46));
	google.maps.event.addListener(myPosModalMap, 'click', function(event) { myPosModalMapClck(event.latLng); });
	directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true, suppressInfoWindows: true, hideRouteList: true, polylineOptions:{strokeColor:'#c03919'}, preserveViewport: true});
	
	storeMarkerImage = new google.maps.MarkerImage('images/marker_shop.png', new google.maps.Size(29, 26), new google.maps.Point(0,0), new google.maps.Point(13, 25));
	for(var c=0; c<markers.length; c++) 
	{  
		markers[c][6] = new google.maps.Marker({position: new google.maps.LatLng(markers[c][1],markers[c][2]), map:myPosModalMap, icon:storeMarkerImage, zIndex:(1000+c) });
		markers[c][7] = new google.maps.InfoWindow({ content: '<div class="gm_iw"><h3>'+markers[c][4]+'</h3>'+markers[c][5]+'<div class="iw_stores_link">'+shop_list_link+'</div></div>', maxWidth: 250 });
		google.maps.event.addListener(markers[c][6], 'click', function() 
		{
			var ind = this.getZIndex()-1000;
			if ((last_active_iw > -1)&&(last_active_iw != ind)) { markers[last_active_iw][7].close(); }
			last_active_iw = ind;
			markers[ind][7].open(myPosModalMap,markers[ind][6]);
		});
	}
	myPosModalMapLoaded = true;
}

function get_distance(location1,location2)
{
	function toRad(deg) 
	{
		return deg * Math.PI/180;
	}
	
	var R = 6371;
	var dLat = toRad(location2.lat()-location1.lat());
	var dLon = toRad(location2.lng()-location1.lng());
	var dLat1 = toRad(location1.lat());
	var dLat2 = toRad(location2.lat());
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(dLat1) * Math.cos(dLat1) * Math.sin(dLon/2) * Math.sin(dLon/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var d = R * c;
	return d;
}

function getNearestMarkerIndToLocation(location)
{
	var nearest = 999999999;
	var temp = -1;
	for(var c=0; c<markers.length; c++) 
	{
		markers[c][8] = get_distance(new google.maps.LatLng(markers[c][1],markers[c][2]),location);
		if (markers[c][8] < nearest) { nearest = markers[c][8]; temp = c; }
	}
	return temp;
}

function drawRouteToLocation(originLoc,destinationLoc)
{
	directionsService.route({origin:originLoc, destination:destinationLoc, travelMode:google.maps.DirectionsTravelMode.DRIVING}, function(response, status)
	{
		if (status == google.maps.DirectionsStatus.OK)
		{
			directionsDisplay.setMap(myPosModalMap);
			directionsDisplay.setDirections(response);
		}
	});
}

var nearest_ind = -1;
function myPosModalMapClck(location)
{
	if (myPosModalMapStatus == 'findNearest')
	{
		nearest_ind = getNearestMarkerIndToLocation(location);
		if (nearest_ind > -1)
		{
			directionsDisplay.setMap(null);
			if (myPosMarker != null) { myPosMarker.setPosition(location); myPosMarker.setMap(myPosModalMap); }
			else { myPosMarker = new google.maps.Marker({position: location, map:myPosModalMap, icon:myPosMarkerImage, zIndex:1000}); }

			//myPosModalMap.panTo(location);
			$('.btns a').removeClass("disabled");

			drawRouteToLocation(location, new google.maps.LatLng(markers[nearest_ind][1],markers[nearest_ind][2]));

			//atveriam info window
			if ((last_active_iw > -1)&&(last_active_iw != nearest_ind)) { markers[last_active_iw][7].close(); last_active_iw = -1; }
			
			$.doTimeout(800,function() 
			{
				last_active_iw = nearest_ind;
				markers[nearest_ind][7].open(myPosModalMap,markers[nearest_ind][6]);
			});
		}
	}
}

function getMarkerIndById(id)
{
	for(var c=0; c<markers.length; c++) { if(markers[c][0] == id) { ind = c; return ind; } }
	return -1;
}

function openInfoWindById(id)
{
	var ind = getMarkerIndById(id);
	if (ind > -1)
	{
		if (last_active_iw > -1) { markers[last_active_iw][7].close(); }
		last_active_iw = ind;
		
		markers[ind][7].open(myPosModalMap,markers[ind][6]);
		//myPosModalMap.panTo( new google.maps.LatLng(markers[ind][1],markers[ind][2]));
	}
}

function myPosSubmit()
{
	if ((myPosMarker != null)&&(nearest_ind > -1))
	{		
		//sdes podtverzdaem marker
		var markerpos = myPosMarker.getPosition();
		var angle = getHeading(GT_lat, GT_lng, markerpos.lat(), markerpos.lng());
		var markerpos = myPosMarker.getPosition();
		createCookie('m360marketSet','yes',cookieDays);
		createCookie('m360marketLat',markerpos.lat(),cookieDays);
		createCookie('m360marketLng',markerpos.lng(),cookieDays);
		createCookie('m360mapZoom',myPosModalMap.getZoom(),cookieDays);
		createCookie('m360mapType',myPosModalMap.getMapTypeId(),cookieDays);
		createCookie('m360mapAngle',angle,cookieDays);
		
		createCookie('NearestStoreId',markers[nearest_ind][0],cookieDays);
		createCookie('NearestStoreDistance',markers[nearest_ind][8],cookieDays);
		createCookie('GTowerDistance',get_distance(markerpos,new google.maps.LatLng(GT_lat,GT_lng)),cookieDays);
		//_obj('fromGP').innerHTML = parseFloat(readCookie('GTowerDistance')).toFixed(2);
		_obj('fromST').innerHTML = parseFloat(readCookie('NearestStoreDistance')).toFixed(2);

		setActiveStoreHTML(markers[nearest_ind][0]);
	
		myPosModalHide();
		$.doTimeout(200,function() 
		{
			myPosModalMap.setOptions({zoom:7, center:new google.maps.LatLng(55.2297794869,24.0498046875)});
			if (last_active_iw > -1) { markers[last_active_iw][7].close(); last_active_iw = -1; }
			m360Move2Angle(angle);
		});
	}
}

var store_page = false;
function setActiveStoreHTML(id)
{
	if (store_page) //jei esame krautuviu puslapyje - keiciam artimiausia
	{
		if ((last_nearest_store > 0)&&(_obj('store_cont_'+last_nearest_store))) { _obj('store_cont_'+last_nearest_store).style.display = 'block'; }

		if (_obj('store_cont_'+id)) 
		{
			_obj('store_cont_'+id).style.display = 'none';
			_obj('nearest_cont').innerHTML = _obj('store_cont_'+id).innerHTML;
		}
		last_nearest_store = id;
		anim_pr_timing = 0;
		update_portfolio(last_pf_num);
		anim_pr_timing = 500;
	}
}
/*===================*/






/*===================*/
/*   360 zemelapis   */
/*===================*/

var GT_lat = 54.68669472718384; //gedemino bokstas
var GT_lng =  25.290833294391632;

function m60GetAngle(x,y) //0-360 between 0,0 and coords x,y
{
	//atan2(y,x)
	//return (Math.atan2(y,x)*180/Math.PI);
	//return getHeading(GT_lat, GT_lng, lat2, lon2)
}

function getHeading(lat2, lon2, lat1, lon1) 
{
	var lat1 = lat1 * Math.PI / 180;
	var lat2 = lat2 * Math.PI / 180;
	var dLon = (lon2 - lon1) * Math.PI / 180;
	var y = Math.sin(dLon) * Math.cos(lat2);
	var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
	var brng = Math.atan2(y, x);
	return ((   (((brng * 180 / Math.PI) + 360) % 360)   -270)*-1);
}


var m360State = 0; //0 - spokojstvie, 1 - razgon, 2 - zamedlenie
var m360Width = 6160;
var m360AniTimer = null;
var m360AniDir = null;
var m360Conf = 12; //12 or 21
var wind_width = $(window).width();
var m360TrainPos = -4000;
var m360FPS = 40;
var m360StepLength = 2;
var m360markerOffset = 42;
var m360markerVisible = false;
var m360markerTrainOffset = 0;
var m360markerBlockWidth = 200;

function m360Animate(direction)
{
	if (moving2angle) return;
	m360AniDir = direction;
	//m360AniTimer = setInterval('m360AnimateStep();',1000/m360FPS);
	m360State = 1;
	m360StepLength = 2;
	clearTimeout(m360AniTimer);
	m360AniTimer = setTimeout('m360AnimateStep();',1000/m360FPS);
}

function m360AniStop()
{
	//clearInterval(m360AniTimer);
	//clearTimeout(m360AniTimer);
	m360State = 2;
}

function m360AnimateStep()
{
	if ((m360State == 1)&&(m360StepLength < 16)) { m360StepLength+= 1; }
	if ((m360State == 2)&&(m360StepLength > 0)) { m360StepLength-= 1; }
	
	var new_pos = 0;
	if (m360AniDir > 0) //dvigaem vpravo, smotrim i proveriaem levuju granicu
	{
		new_pos = m360TrainPos + (m360AniDir * m360StepLength);
		if (new_pos > 0) //traukinis isvazioja uz ribu
		{
			if (m360Conf == 12)
			{
				_obj('map2').style.left = (m360TrainPos - m360Width)+'px';
				m360Conf = 21;
			}
			else
			{
				_obj('map1').style.left = (m360TrainPos - m360Width)+'px';
				m360Conf = 12;
			}
			new_pos-= m360Width;
		}
		m360TrainPos = new_pos;
	}
	else //dvigaem vlevo
	{
		new_pos = m360TrainPos + (m360AniDir * m360StepLength);
		if (new_pos+(m360Width*2) < wind_width) //traukinis isvazioja uz ribu
		{
			if (m360Conf == 12)
			{
				_obj('map1').style.left = (m360TrainPos + (m360Width*2))+'px';
				m360Conf = 21;
			}
			else
			{
				_obj('map2').style.left = (m360TrainPos + (m360Width*2))+'px';
				m360Conf = 12;
			}
			new_pos+= m360Width;
		}
		m360TrainPos = new_pos;
	}
	
	if (m360Conf == 12) { _obj('map1').style.left = m360TrainPos+'px'; _obj('map2').style.left = (m360TrainPos + m360Width)+'px'; }
	else { _obj('map2').style.left = m360TrainPos+'px'; _obj('map1').style.left = (m360TrainPos + m360Width)+'px'; }

	if (m360markerVisible)
	{
		var newmpos = m360TrainPos+m360markerTrainOffset;
		var temp = m360TrainPos + m360markerTrainOffset + m360Width;
		if ((temp+m360markerBlockWidth >= 0) && (temp <= m360Width-m360markerBlockWidth)) { newmpos+= m360Width; }
		else
		{
			temp+= m360Width;
			if ((temp+m360markerBlockWidth >= 0) && (temp <= m360Width-m360markerBlockWidth)) { newmpos+= m360Width*2; }
		}
		_obj('m360marker').style.left = newmpos + 'px';
	}
	
	//_obj('console').innerHTML = 'm360Conf:'+m360Conf+' m360TrainPos:'+m360TrainPos+' m360markerTrainOffset:'+m360markerTrainOffset+' newmpos:'+newmpos;

	//check if repeat
	if ((m360State == 2)&&(m360StepLength <= 0)) {}
	else { m360AniTimer = setTimeout('m360AnimateStep();',1000/m360FPS); }
	
}

var moving2angle = false;
function m360Move2Angle(angle,no_animation)
{
	var m360animTime = 500;
	if (no_animation) { m360animTime = 0; }
	
	var show_marker = false;
	if (readCookie('m360marketSet') == 'yes') { show_marker = true; }

	m360State = 2;
	clearTimeout(m360AniTimer);

	var deg0offset = 3540-109; 
	var spos = deg0offset - Math.round(angle*m360Width/360) + m360Width;

	while(spos > m360Width) { spos-= m360Width; } //gaubam atstuma nuo kairiojo krasto
	m360markerTrainOffset = spos;
	if (spos < (m360Width/2)) { spos+= m360Width; } //pervaja polovina vtorogo varona
	
	if (show_marker) { _obj('m360marker').style.left = (m360TrainPos+spos-m360markerOffset)+'px'; }
	
	var marker_new_pos = Math.round(wind_width/2)-m360markerOffset;
	
	if(m360Conf == 12)
	{
		var map1_new_pos = -1 * spos + marker_new_pos;
		var map2_new_pos = map1_new_pos + m360Width;
		if (m360animTime > 0)
		{
			var path = m360TrainPos - map1_new_pos;
			if (path < 0) { path = -1 * path; }
			m360animTime = Math.round(path / 350) * 1000;
		}
		m360TrainPos = map1_new_pos;
	}
	else
	{
		var map2_new_pos = -1 * spos + marker_new_pos;
		var map1_new_pos = map2_new_pos + m360Width;
		if (m360animTime > 0)
		{
			var path = m360TrainPos - map1_new_pos;
			if (path < 0) { path = -1 * path; }
			m360animTime = Math.round(path / 350) * 1000;
		}
		m360TrainPos = map1_new_pos;
	}

	if (show_marker)
	{
		m360markerVisible = true; //pranesame slaideriams, kad markeri irgi reiktu skrolint
		//_obj('fromGP').innerHTML = parseFloat(readCookie('GTowerDistance')).toFixed(2);
		_obj('fromST').innerHTML = parseFloat(readCookie('NearestStoreDistance')).toFixed(2);
		$('#m360marker').css('display','block').animate({left:marker_new_pos+'px'},m360animTime);
	}
	
	moving2angle = true;
	$('#map1').animate({left:map1_new_pos+'px'},m360animTime,function(){ moving2angle = false; });
	$('#map2').animate({left:map2_new_pos+'px'},m360animTime);
}

/*===================*/


function subscribe()
{
	if (def_language == 'LT')
	{
		var err = 'Įveskite teisingą el.pašto adresą!';
		var succ = 'Ačiū, Jūs sėkmingai užsiprenumeravote naujienas iš mūsų svetainės!';
		var lang_id = 1;
	}
	else if (def_language == 'EN')
	{
		var err = 'Please enter correct email address!';
		var succ = 'Thank you! You successfully signed up for the latest news from our site!';
		var lang_id = 2;
	}
	else 
	{
		var err = 'Введите правильный адрес эл. почты!';
		var succ = 'Спасибо! Вы успешно подписались на последние новости с нашего сайта!';
		var lang_id = 3;
	}
	
	prenum_email = _obj('subscr_email').value;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (!reg.test(prenum_email)) { alert(err); }
	else
	{
		$.get('fast.php?act=subscribe&email='+escape(prenum_email)+'&lid='+lang_id, function(data) 
		{
			if (data == 'OK') { alert(succ); }
			else { alert(data); }
		});
	}
	
}



//$.doTimeout(200,function() { chStateBtnRedraw(); });
