var close=true;
var path=null;
var this_url = null;

E=function(id){return document.getElementById(id)};
function getElementsByClass(c,n,t){var e=new Array();if(!n){n=document}if(!t){t='*'}var l=n.getElementsByTagName(t),p=new RegExp("(^|\\s)"+c+"(\\s|$)");for(i=0,j=0;i<l.length;i++){if(p.test(l[i].className)){e[j]=l[i];j++}}return e}
function findPos(o){var l=t=0;if(o.offsetParent){l=o.offsetLeft;t=o.offsetTop;while(o=o.offsetParent){l+=o.offsetLeft;t+=o.offsetTop}}return[l,t]}
function kill(f,e){var l=f.elements.length;if(!l){return false}for(n=0;n<l;n++){if((f.elements[n].type=='select-one'||f.elements[n].type=='select-multiple')&&f.elements[n].selectedIndex&&f.elements[n].value==''){continue}if(!e&&(f.elements[n].value==''||f.elements[n].value=='0')&&f.elements[n].type!='hidden'){f.elements[n].disabled=true}else if(e&&f.elements[n].type=='text'){f.elements[n].value=''}}}
var xml=new Array(); 
function get3(u,x,h,f,nu,d,l){
	
	var c=xml.length;sXML(c);
	if(!xml[c]){return false}
	var ul=(nu?'':'/ajax.php')+u+'&round='+Math.floor(Math.random()*1000);

	xml[c].open('GET',ul,true);
	xml[c].onreadystatechange=function(){
		if(xml[c].readyState==4){
			
			var r=xml[c].responseText;
		
			if(r){if(!h){try{eval(r)}catch(e){alert("XML ERROR: "+e.message+"\n\n"+ul+"\n\n"+r)}}
			else if(h&&h.style){h.style.display='';h.innerHTML=r}
			if(nu){r=null}
		}
		else if(h){h.style.display='none'}}
	};
	xml[c].send(null)
}
function sXML(c){if(!xml[c]){if(typeof(XMLHttpRequest)!='undefined'){xml[c]=new XMLHttpRequest()}else if(window.ActiveXObject){xml[c]=new ActiveXObject("Microsoft.XMLHTTP")}else{xml[c]=false}}}

function selectMenu(o, url) {
	get3(url);
	closeAll();
}

function closeAndToggle(href) {

	var id = $(href).attr('id');
	
	var exitFunction = false;

	$('div[id^="but_"]').each(function(indexInArray, valueOfElement){
	 	if ($(this).css('display') != 'none'){
	 		if ($(this).attr('id') == 'lomat_' + id){
				exitFunction = true;
				$(this).toggle('slow'); 			
	 		}else{
	 			$(this).toggle();
	 		}
	 	}
	 });
	 
	 
	 if (exitFunction){
	 	return false;
	 }
 
	$('#but_'+id).toggle('slow');
}

function addToFavour(id) {
	get3('?get=trip&save=favourites&idString='+id);
}
function remFromFavour(id) {
	get3('?get=trip&rem=favourites&idString='+id);
}

function scrollToDiv(divName){
	if ($('#' + divName).length != 0)
		$.scrollTo( '#' + divName, 800, {queue:true} );
}

function initElements(){
	$(".maa_l").click(function(){
			close=true;
			closeAll('maa');
			$(".maa_d").toggle("fast");
		});
		$(".city_l").click(function(){
			close=true;
			closeAll('city');
			$(".city_d").toggle("fast");
		});
		$(".country_l").click(function(){
		
			close=true;
			closeAll('country');
			$(".country_d").toggle("fast");
		});
		
		
		$(".type_l").click(function(){
			close=true;
			closeAll('type');
			$(".type_d").toggle("fast");
		});
		
		$(".nights_l").click(function(){
			close=true;
			closeAll('nights');
			$(".nights_d").toggle("fast");
		});
		$(".calendar_l").click(function(){
			close=true;
			closeAll('calendar');
			$("#date_picker_error").css("display", "none");
			$(".calendar_d").toggle("fast");
		});
		
		
		
		var dates = $( "#datepicker_start, #datepicker_end" ).datepicker({
			dateFormat:'dd.mm.yy',
			onSelect: function( selectedDate ) {
				var dateId = this.id;
				var option = this.id == "datepicker_start" ? "minDate" : "maxDate";
				
				if (this.id == 'datepicker_end'){
					$("#datepicker_end_str").val(selectedDate);	
				}else if (this.id == 'datepicker_start'){
					$("#datepicker_start_str").val(selectedDate);
				}
				
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
			}
		});
		
		/*
		$("#datepicker_start").datepicker({
			 onSelect: function(dateText){
		    	$("#datepicker_start_str").val(dateText);
			},
			dateFormat:'dd.mm.yy'
		});
		
		$("#datepicker_end").datepicker({
		 onSelect: function(dateText){
		 	$("#datepicker_end_str").val(dateText);
			},
			dateFormat:'dd.mm.yy'
		});
		*/
		$(".theme_l").click(function(){
			close=true;
			closeAll('theme');
			$(".theme_d").toggle("fast");
		});
		$(".bus_l").click(function(){
			close=true;
			closeAll('bus');
			$(".bus_d").toggle("fast");
		});
		$(".dt_l").click(function(){
			close=true;
			closeAll('dt');
			$(".dt_d").toggle("fast");
		});
		
	$('#country_close').click(function() {
		closeAll();		
	});
	 $('#type_close').click(function() {
		closeAll();		
	});
	
	 $('#city_close').click(function() {
		closeAll();		
	});
	 $('#calendar_close').click(function() {
		closeAll();		
	});
	 $('#nights_close').click(function() {
		closeAll();		
	});
	 $('#theme_close').click(function() {
		closeAll();		
	});
	 $('#bus_close').click(function() {
		closeAll();		
	});
	 $('#dt_close').click(function() {
		closeAll();		
	});
}
function init(p,cal_url) {
	path = p;
	this_url = cal_url;
}


function submitDate(){
	var ajax = true;
	var date_start = $("#datepicker_start_str").val();
	var date_end = $("#datepicker_end_str").val();
	$("#date_picker_error").css("display", "none");
	
	if (date_start != '' && date_end != ''){

			// if both dates selected
			var date1 = Date.parse(date_start.replace(/\./g, '/'));
			var date2 = Date.parse(date_end.replace(/\./g, '/'));
			
			var compare = compareDates(date_start, 'dd.MM', date_end, 'dd.MM');
			if (compare == 1){
					$("#date_picker_error").css("display", "inline");
					ajax= false;
				}
	}
	if (ajax){ //ajax call only if no trouble
		var url_str = this_url;
		if (date_start != ''){
			url_str += '&dp='+date_start;
		}
		if (date_end != ''){
			url_str += '&dp2='+date_end;
		}
		selectMenu(null, url_str);
	}
}


function customRange(input) { 
	    return {minDate: (input.id == "enddate" ? $("#startdate").datepicker("getDate") : '+1'), 
	    maxDate: (input.id == "startdate" ? $("#enddate").datepicker("getDate") : null)}; 
	} 

/* people count in request form */
var people = 0;
function createPeopleFields(el) {
	
	repeat = parseInt($('option:selected', el).text());
	if (repeat > people) {
		for (i = people + 1; i <= repeat;i++) {
			$('#people' + i).show();
		}
	}
	
	if (repeat < people) {
		for (i = people; i > repeat; i--) {
			$('#people' + i + ' input').val('');
			$('#people' + i).hide();
		}
	}
	
	people = repeat;
}

function closeAll(c){
	if(!close) return false;
	var d=getElementsByClass('dropped');
	for(i=0;i<d.length;i++) {
		if (c+'_d dropped' != d[i].className) {
			d[i].style.display = 'none';
		}
	}	
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-6628509-3']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

function recordOutboundLink(link, category, action) {
  try {
  	$('#load_div').css('display', 'block');
  	$('#load_div').css('position', 'fixed');
	$('#load_div').css('top', '0px');
	$('#load_div').css('bottom', '0px');
	$('#load_div').css('right', '0px');
 	$('#load_div').css('left', '0px'); 
 	$('#load_div').css('z-index', '99999');
	
    var pageTracker=_gat._getTracker("UA-6628509-3");
    pageTracker._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
}


(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


$(document).ready(function(){

	  function addMenuStyles()
	  {
		  
		  $("#topmenu > ul > li").each( function(index) {
		  		
		  	 	if ($(this).children("ul").children("li").size() == 1)
		  	 	{
			  		$(this).addClass("only-one");
			 	}
			 	
			 	if ($(this).children("ul").children("li").children("ul").size() == 0)
		  	 	{
			  		$(this).addClass("only-one-ul");
			 	}
		  });
	  } 
		
	  function addMega(){  
	  	  $(this).addClass("hovering");

		  
	   	  
	    }  
	  function removeMega(){  
	    	$(this).removeClass("hovering");
	    	//$(this).removeClass("only-one");  
	    } 

	  var megaConfig = {  
		         interval: 0,  
		         sensitivity: 4,   
		         over: addMega,  
		         timeout: 100,  
		         out: removeMega  
	  }; 

	  addMenuStyles();
	  
	  $("#topmenu ul li").hoverIntent(megaConfig);
	  

	
	
	  $('.tabs').tabs();
	
	  $('.tabs_fl').tabs();
		var destination = '<cms:value.city_code>';
		$('#Mihin_ed_value').val(destination);
		$('#Mihin_ed_dyn_value').val(destination);

	
		

var dates = $( "#from, #to" ).datepicker({
			beforeShow: customRange,
			showOn: 'both', 
			defaultDate: "+1w",
			buttonImage: "/img/new/booking_input_grey_cal.png",
			buttonImageOnly: true,
			changeMonth: true,
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				var option = this.id == "from" ? "minDate" : "maxDate",
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
			}
		});
		
var dates2 = $( "#dyn_from, #dyn_to" ).datepicker({
			beforeShow: customRange,
			showOn: 'both', 
			defaultDate: "+1w",
			buttonImage: "/img/new/booking_input_grey_cal.png",
			buttonImageOnly: true,
			changeMonth: true,
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				var option = this.id == "from" ? "minDate" : "maxDate",
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
			}
		});
});




/* cities scripts */



function bookHotel(){
		var hotel_id = $('#booking_hotel_id').val();
		var date_from = $('#popup_from').val();
		var date_to = $('#popup_to').val();
		var city_to = $('#booking_city_to').val();
		var rooms = $('#booking_rooms').val();
		var adults = $('#booking_adults').val();
		var children = $('#booking_children').val();
		var dep_city_flight_hotel = $('#dep_city_flight_hotel').val();
		
		if (date_from && date_to){
			var link = '';
			if( $('input[name=book_type]:checked').val() == 'flight_hotel')
			{
				link = 'http://varaamo2.sagamatkat.fi/intres/saga/i7pro/DynPack/dynpacksearch.aspx?&sender=1&fromIATA=' + dep_city_flight_hotel + '&roomCount=' + rooms + '&adult=' + adults + '&child=' + children + '&beginDate=' + date_from + '&endDate=' + date_to + '&hotelId='+hotel_id + '&toIATA=' + city_to;
			}
			else{
				link = 'http://varaamo2.sagamatkat.fi/intres/saga/i7pro/accommodation/accsearch.aspx?&sender=1&roomCount=' + rooms + '&adult=' + adults + '&child=' + children + '&beginDate=' + date_from + '&endDate=' + date_to + '&hotelId='+hotel_id + '&toIATA=' + city_to;
			}
			window.location = link;
		}else{
			alert('Ole hyvä ja valitse lähtöpäivät.');
		}
}

function openPopup(id, name){
	$('#TB_window').addClass("city_popup");
	tb_show('Booking','#TB_inline?height=280&width=500&inlineId=booking_popup&modal=true','');
	//$('#booking_popup').hide();
	//$('#booking_popup').show(700);
	
	// document.write(id);
	// document.write(name);
	
	$('#booking_hotel_id').val(id);
	$('#booking_hotel_name').html(name);
		
		$('#popup_from').val('Lähtö');
		$('#popup_to').val('Paluu');
		
		
		
	var dates = $( "#popup_from, #popup_to" ).datepicker({
			beforeShow: customRange,
			showOn: 'both', 
			defaultDate: "+1w",
			buttonImage: "/img/new/booking_input_grey_cal.png",
			buttonImageOnly: true,
			changeMonth: true,
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				var option = this.id == "popup_from" ? "minDate" : "maxDate",
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
			}
		});
	
	
	
}

function openOrderPopup(city, hotel){
	$('#TB_window').css('margin-top','20px!important');
	$('#TB_window').css('height','100%!important');
	$('#TB_window').css('top','20px!important');
	tb_show('Booking','#TB_inline?height=550&width=600&inlineId=order_popup&modal=true','');
	
	
	$('#booking_hotel_id').val(id);
	$('#booking_hotel_name').html(name);

	
	
}




function childAges(form, select){
	if (form != "dyn"){
		$('#sagaFlights #children_ages_div').html('');
	}else{
		$('#sagaDynFlights #children_ages_div').html('');
	}
	
	value = select.options.selectedIndex;
	if (value == 0){
		return true;
	}
	if (value != 0){
		$('#age_header').show();
	}	
	
	for (i=1; i<=value; i++){
		select = '<select class="select_a2vlapsi" name="ChildrenAges_' + i + '" id="ChildrenAges_' + i + '"> </select> &nbsp;';
		
	
		if (form != "dyn"){
			$('#sagaFlights #children_ages_div').append(select);
		}else{
			$('#sagaDynFlights #children_ages_div').append(select);
		}		
        for (j=0; j<= 18; j++){
        	if (form != "dyn"){
        		$('#sagaFlights #ChildrenAges_' + i).append('<option value="' + j + '" >' + j + '</option>');
        	}else{
        		$('#sagaDynFlights #ChildrenAges_' + i).append('<option value="' + j + '" >' + j + '</option>');
        	}
        }	
	}
	

}



function validateDyn(){
	if ($('#Mihin_ed_dyn_value').val()==''){
		alert('Plaese select destination.');
		return false;
	}
	
	var from = $( "#dyn_from" ).val();
	var to = $( "#dyn_to" ).val();
	if (from == '' || to == ''){
		alert('Please select valid date range');
		return false;
	}
	return true;
}

function validateForm(){
	if ($('#Mihin_ed_value').val()==''){
		alert('Please select destination.');
		return false;
	} 
	var from = $( "#from" ).val();
	var to = $( "#to" ).val();
	if (from == '' || to == ''){
		alert('Please select valid date range');
		return false;
	}
	return true;
}

function doSubmit(form){
	$('#message').show();
	
	if(validateForm())
		document.sagaDynFlights.submit();	
}
 
function validateFormType(radio){
	if (radio.value == 'hotel'){
		$('.only_hotel').hide();
	}else{
		$('.only_hotel').show();
	}
	 
}
function validateFormType2(radio){
	if (radio.value == 'hotel'){
		$('.dep_city_flight_hotel').hide();
	}else{
		$('.dep_city_flight_hotel').show();
	}
	 
}


/*
 * This script brakes other js
 * menuYloc = $('#booking_popup').css("top").substring(0,$('#booking_popup').css("top").indexOf("px"))
$(window).scroll(function () {  
    var offset = menuYloc + $(document).scrollTop();
    offset = offset +"px";
     
    $('#booking_popup').animate({top:offset},{duration:500,queue:false});  
}); */ 


