﻿var siteurl = "http://www.unelmamatkat.net"; 
var dropdowntarget = "";

var continents=new Array();
var countrys=new Array();
var destinations=new Array();



//Ajax
var request = false;
var request2 = false;
var request12 = false;
var request4 = false;
var request18 = false;
var request14 = false;
var request15 = false;
var request16 = false;
var request17 = false;

try
{
	 request = new XMLHttpRequest();
	 request2 = new XMLHttpRequest();
	 request12 = new XMLHttpRequest();
	 request4 = new XMLHttpRequest();
	 request18 = new XMLHttpRequest();
	 request14 = new XMLHttpRequest();
	 request15 = new XMLHttpRequest();
	 request16 = new XMLHttpRequest();
	 request17 = new XMLHttpRequest();
}
catch (trymicrosoft)
{
	try
	{
		request = new ActiveXObject("Msxml2.XMLHTTP");
		request2 = new ActiveXObject("Msxml2.XMLHTTP");
		request12 = new ActiveXObject("Msxml2.XMLHTTP");
		request4 = new ActiveXObject("Msxml2.XMLHTTP");
		request18 = new ActiveXObject("Msxml2.XMLHTTP");
		request14 = new ActiveXObject("Msxml2.XMLHTTP");
		request15 = new ActiveXObject("Msxml2.XMLHTTP");
		request16 = new ActiveXObject("Msxml2.XMLHTTP");
		request17 = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (othermicrosoft)
	{
		try
		{
			request = new ActiveXObject("Microsoft.XMLHTTP");
			request2 = new ActiveXObject("Microsoft.XMLHTTP");
			request12 = new ActiveXObject("Microsoft.XMLHTTP");
			request4 = new ActiveXObject("Microsoft.XMLHTTP");
			request18 = new ActiveXObject("Microsoft.XMLHTTP");
			request14 = new ActiveXObject("Microsoft.XMLHTTP");
			request15 = new ActiveXObject("Microsoft.XMLHTTP");
			request16 = new ActiveXObject("Microsoft.XMLHTTP");
			request17 = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (failed)
		{
			request = false;
			request2 = false;
			request12 = false;
			request4 = false;
			request18 = false;
			request14 = false;
			request15 = false;
			request16 = false;
			request17 = false;
		}  
	}
}

var windowwidth;
var windowheight;
function getWindowSize(){

	var winW = 1004, winH = 748;

	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
		}
	}
	
	windowwidth = winW;
	windowheight = winH;

}


function dropDownChangePage(dropdowntarget,group){
	
	if(group==1){
		if(dropdowntarget=='continent'){
			select_index = document.dropdownform1.dropdowncontinent1.selectedIndex;
			select_value = document.dropdownform1.dropdowncontinent1.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform1.dropdowncountry1.selectedIndex;
			select_value = document.dropdownform1.dropdowncountry1.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform1.dropdowndestination1.selectedIndex;
			select_value = document.dropdownform1.dropdowndestination1.options[select_index].value;
		}
	}
	else if(group==2){
		if(dropdowntarget=='continent'){
			select_index = document.dropdownform2.dropdowncontinent2.selectedIndex;
			select_value = document.dropdownform2.dropdowncontinent2.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform2.dropdowncountry2.selectedIndex;
			select_value = document.dropdownform2.dropdowncountry2.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform2.dropdowndestination2.selectedIndex;
			select_value = document.dropdownform2.dropdowndestination2.options[select_index].value;
		}
	}
	else if(group==3){
	if(dropdowntarget=='continent'){
			select_index = document.dropdownform3.dropdowncontinent3.selectedIndex;
			select_value = document.dropdownform3.dropdowncontinent3.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform3.dropdowncountry3.selectedIndex;
			select_value = document.dropdownform3.dropdowncountry3.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform3.dropdowndestination3.selectedIndex;
			select_value = document.dropdownform3.dropdowndestination3.options[select_index].value;
		}
	}
	
	if( select_value != 0 ){
		theUnLoadEvent()
		var url = siteurl+"/dropdownchangepage.php?page=" + dropdowntarget + "&id="+ select_value;
			
		request.open("GET", url, true);
		request.onreadystatechange = changePage;
		request.send('');
	}
}

function changePage(){
	if (request.readyState == 4){
		if ( (request.status == 200) || (request.status == 0) ){

			
			var vastaus = request.responseText;
			window.location = vastaus;
			
		}
		else if (request.status == 404){
			alert("Request URL does not exist - 404");
		}
		else{
			alert("Error: status code is " + request.status);
		}
	}
}


function dropDownChangeFavoritePage(group){
	
	if(group==1){
		select_index = document.dropdownform1.dropdownfavorite1.selectedIndex;
		select_value = document.dropdownform1.dropdownfavorite1.options[select_index].value;
	}
	else if(group==2){
		select_index = document.dropdownform2.dropdownfavorite2.selectedIndex;
		select_value = document.dropdownform2.dropdownfavorite2.options[select_index].value;
	}
	
	dropdowntarget = select_value.split("_");
	
	if( select_value != 0 ){
		theUnLoadEvent()
		var url = siteurl+"/dropdownchangepage.php?page=" + dropdowntarget[0] + "&id="+ dropdowntarget[1];
			
		request.open("GET", url, true);
		request.onreadystatechange = changePage;
		request.send('');
	}
}

function changeDropdown(dropdowntarget,group){
	if(group==1){
		if(dropdowntarget=='continent'){
			select_index = document.dropdownform1.dropdowncontinent1.selectedIndex;
			select_value = document.dropdownform1.dropdowncontinent1.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform1.dropdowncountry1.selectedIndex;
			select_value = document.dropdownform1.dropdowncountry1.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform1.dropdowndestination1.selectedIndex;
			select_value = document.dropdownform1.dropdowndestination1.options[select_index].value;
		}
	}
	else if(group==2){
		if(dropdowntarget=='continent'){
			select_index = document.dropdownform2.dropdowncontinent2.selectedIndex;
			select_value = document.dropdownform2.dropdowncontinent2.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform2.dropdowncountry2.selectedIndex;
			select_value = document.dropdownform2.dropdowncountry2.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform2.dropdowndestination2.selectedIndex;
			select_value = document.dropdownform2.dropdowndestination2.options[select_index].value;
		}
	}
	else if(group==3){
	if(dropdowntarget=='continent'){
			select_index = document.dropdownform3.dropdowncontinent3.selectedIndex;
			select_value = document.dropdownform3.dropdowncontinent3.options[select_index].value;
		}
		else if(dropdowntarget=='country'){
			select_index = document.dropdownform3.dropdowncountry3.selectedIndex;
			select_value = document.dropdownform3.dropdowncountry3.options[select_index].value;
		}
		else if(dropdowntarget=='destination'){
			select_index = document.dropdownform3.dropdowndestination3.selectedIndex;
			select_value = document.dropdownform3.dropdowndestination3.options[select_index].value;
		}
	}
	
	if( select_value != 0 ){
		var url = siteurl+"/populatedropdown.php?dropdown=" + dropdowntarget + "&dropdown_id="+ select_value;
			
		request.open("GET", url, true);
		request.onreadystatechange = updateDropdown;
		request.send('');
	}
}

function updateDropdown(){
	if (request.readyState == 4){
		if ( (request.status == 200) || (request.status == 0) ){
			if( document.getElementById('lastLoadedCommands') ){
				var t = document.getElementById('lastLoadedCommands');
				t.parentNode.removeChild(t);
			}
			var vastaus = request.responseText;
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.id = 'lastLoadedCommands';
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);
			document.getElementById('lastLoadedCommands').innerHTML = vastaus;
			
			document.getElementById('dropdowncontinent1').innerHTML = continents;
			document.getElementById('dropdowncountry1').innerHTML = countrys;
			document.getElementById('dropdowndestination1').innerHTML = destinations;
			
			document.getElementById('dropdowncontinent2').innerHTML = continents;
			document.getElementById('dropdowncountry2').innerHTML = countrys;
			document.getElementById('dropdowndestination2').innerHTML = destinations;
			
		}
		else if (request.status == 404){
			alert("Request URL does not exist - 404");
		}
		else{
			alert("Error: status code is " + request.status);
		}
	}
}




var image_idx;
var imageresponded = "no";

function populate_image_container(image_id){
	imageresponded = "no";
	image_idx = image_id;
	document.getElementById('imagecontainercontent').innerHTML='';
	var url = siteurl+"/populateimagecontainer.php?image_id=" + image_id;
	request2.open("GET", url, true);
	request2.onreadystatechange = updateImageContainer;
	request2.send('');
}

function reloadImagecontainer(){
	if( imageresponded == "no" ){
		populate_image_container(image_idx);
	}
}


function updateImageContainer(){
try{
	
	if (request2.readyState == 4){
	
		if ( (request2.status == 200) || (request2.status == 0) ){
			document.getElementById('imagecontainercontent').innerHTML='';
			var vastaus = request2.responseText;
			document.getElementById('imagecontainercontent').style.display='block';
			document.getElementById('imagecontainercontent').innerHTML = vastaus;
			imageresponded = "yes";
		}
		else if (request2.status == 404){
			
			alert("Request URL does not exist - 404");
		}
		else{

			alert("Error: status code is " + request2.status);
		}
	}		
}
catch(error){
	if( imageresponded == "no" ){
		populate_image_container(image_idx);
	}
}

}

function changeBestReviewedContent(nayta,currentpage_id){
	
	if( nayta == "maat" ){
		document.getElementById('matkakohteet').style.textDecoration = 'none';
		document.getElementById(nayta).style.textDecoration = 'underline';
		getBestReviewedContent('maat',currentpage_id);
	}
	if( nayta == "matkakohteet" ){
		document.getElementById('maat').style.textDecoration = 'none';
		document.getElementById(nayta).style.textDecoration = 'underline';
		getBestReviewedContent('matkakohteet',currentpage_id);
	}
}

function getBestReviewedContent(content,currentpage_id){
	var url = siteurl+"/bestreviewed.php?content=" + content+"&currentpage_id="+currentpage_id;
		
	request.open("GET", url, true);
	request.onreadystatechange = updateBestReviewedContent;
	
	request.send('');
}

function updateBestReviewedContent(){

	if (request.readyState == 4){
	
		if (request.status == 200){
			//alert("readyState=200");
			//document.getElementById(thechange).style.display = 'none';
			document.getElementById('best_rated_div').innerHTML='';
			var vastaus = request.responseText;
			document.getElementById('best_rated_div').innerHTML = vastaus;
		}
		else if (request.status == 404){
			
			alert("Request URL does not exist - 404");
		}
		else{

			alert("Error: status code is " + request.status);
		}
	}
}

var linkpagex;
var linkpage_idx;
var responded = "no";


function quickReview(linkpage, linkpage_id){
	responded = "no";
	linkpagex = linkpage;
	linkpage_idx = linkpage_id;
	
	document.getElementById('linkpage_maincontainer').innerHTML="<img src='"+ siteurl +"/images/loading.gif' alt='Loading...' />";
	var url = siteurl+"/gethover_ratings.php?linkpage=" + linkpage + "&linkpage_id="+linkpage_id;
	setTimeout("reloadQuickReview()", 2000);
	request.open("GET", url, true);
	request.onreadystatechange = updateQuickReview;
	
	request.send('');
}

function reloadQuickReview(){
	if( responded == "no" ){
		quickReview(linkpagex, linkpage_idx);
	}
}

function updateQuickReview(){
	if (request.readyState == 4){
		
		if (request.status == 200){
			document.getElementById('linkpage_maincontainer').style.display='block';
			var vastaus = request.responseText;
			document.getElementById('linkpage_maincontainer').innerHTML = vastaus;
			responded = "yes";
			
		}
		else if (request.status == 404){
			//alert("Request URL does not exist - 404");
		}
		else{
			//alert("Error: status code is " + request.status);
		}
	}		
}


function changeTempMonth(currentpage, currentpage_id, month){
	
	select_index = document.tempform.month.selectedIndex;
	month = document.tempform.month.options[select_index].value;
	
	var url = siteurl+"/changetempmonth.php?currentpage=" + currentpage + "&currentpage_id="+currentpage_id + "&month="+month;
	request.open("GET", url, true);
	request.onreadystatechange = updateTempMonth;
	
	request.send('');
}

function updateTempMonth(){

	if (request.readyState == 4){
	
		if ( (request.status == 200) || (request.status == 0) ){
			document.getElementById('temp_div').innerHTML='';
			var vastaus = request.responseText;
			document.getElementById('temp_div').innerHTML = vastaus;
			
		}
		else if (request.status == 404){
			
			alert("Request URL does not exist - 404");
		}
		else{

			alert("Error: status code is " + request.status);
		}
	}		
}

function mouseover( id,e,divi ){
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	
	div_width = 440;
	div_height = 380;
	limitposition_left = div_width+5;
	limitposition_right = windowwidth-div_width;
	limitposition_bottom = (posy-e.clientY)+windowheight-200;
	
	var varausdiv = document.getElementById(divi);
	
	if(posx>limitposition_right){

		varausdiv.style.left = posx-div_width-15+"px";
	}
	else{
		varausdiv.style.left = posx+25+"px";
	}
	
	if(posy>=limitposition_bottom){
		posy=limitposition_bottom;
	}

	varausdiv.style.top = posy-160+"px";
	varausdiv.style.display = "block";

}

function mouseover2( id,e,divi ){
	
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	
	var varausdiv = document.getElementById(divi);
	varausdiv.style.left = posx+5+"px";
	varausdiv.style.top = posy+5+"px";
	varausdiv.style.display = "block";
}

function mouseout( id,e,divi ){
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	var varausdiv = document.getElementById(divi);
	varausdiv.style.left = posx+10+"px";
	varausdiv.style.top = posy+10+"px";
	varausdiv.style.display = "none";
}



function changeNumberOfCountrys(number){
nocache = Math.random();
	if( document.getElementById('visitedid') ){
		var url = siteurl + "/getcountrylist.php?number="+number+"&nocache="+nocache+"&visited=jep";
	}
	else{
		var url = siteurl + "/getcountrylist.php?number="+number+"&nocache="+nocache;
	}
	
	request.open("GET", url, true);
	request.onreadystatechange = updateCountryLists;
	
	request.send(null);
}

function updateCountryLists(){
	if (request.readyState == 4){
		if ((request.status == 200) || (request.status == 0)){
			//alert("Valmis!"+agency);
			var vastaus = request.responseText;
			document.getElementById('countrys_container').innerHTML='';
			document.getElementById('countrys_container').innerHTML = vastaus;
		}
	}
}

function getCountrysDestinations(countryselect,destinationlist,number){
nocache = Math.random();
	destination_select = destinationlist;
	
	number = document.getElementById(number).value;
	selected_index = eval("document.offer_form.elements['"+countryselect+"'].selectedIndex");
	selected = eval("document.offer_form.elements['"+countryselect+"'].options["+selected_index+"].value");
	if (selected == '00'){
		return false;
	}
	var url = siteurl + "/getcountrysdestinations.php?country="+selected+"&number="+number+"&nocache="+nocache;
	request.open("GET", url, true);
	request.onreadystatechange = updateDestinationLists;
	request.send(null);
}

function updateDestinationLists(){

	if (request.readyState == 4){
		if ((request.status == 200) || (request.status == 0)){
			var vastaus = request.responseText;
			document.getElementById(destination_select).innerHTML='';
			document.getElementById(destination_select).innerHTML = vastaus;
			
		}
	}

}



function changeNumberOfDuration(number){
nocache = Math.random();
	var url = siteurl + "/getdayslist.php?number="+number+"&nocache="+nocache;
	request2.open("GET", url, true);
	request2.onreadystatechange = updateDaysList;
	
	request2.send(null);

}

function updateDaysList(){
	if (request2.readyState == 4){
		if ((request2.status == 200) || (request2.status == 0)){
			//alert("Valmis!"+agency);
			var vastaus = request2.responseText;
			document.getElementById('days_container').innerHTML='';
			document.getElementById('days_container').innerHTML = vastaus;
		}
	}
}


function changeDays(thevalue){
	if( thevalue == "yes" ){
		document.getElementById('single_container').style.display = "none";
		document.getElementById('days_container').style.display = "block";
	}
	else{
		document.getElementById('days_container').style.display = "none";
		document.getElementById('single_container').style.display = "block";
	}
}

function validateForm(){
	countrys = document.travelstory_form.travelstory_number_of_countrys.value;
	if( countrys == '' ){
		countrys = 'tyhjä';
	}
	isnumber = IsNumeric(countrys);
	if (isnumber == false){
		alert("VIRHE!\nMaiden määrä on "+countrys+", oikeellinen arvo on numero 1 - 20.");
		return false;
	}
	if ( countrys < 1 || countrys > 20 ){
		alert("VIRHE!\nMaiden määrä on "+countrys+", oikeellinen arvo on 1 - 20.");
		return false;
	}
	
	for(var i = 1; i <= countrys; i++){
		var hasSelections2 = false;
		for(var e = 1; e <= eval("document.travelstory_form.select_"+i+".options.length")-1; e++){
			if( eval("document.travelstory_form.select_"+i+".options["+e+"].selected") ){
				
				hasSelections2 = true;
				country_id = eval("document.travelstory_form.select_"+i+".options["+e+"].value");
				destinations = eval("document.travelstory_form.number_of_destinations_"+i+".value");
				destination_count=0;
				if( destinations == '' ){
					destinations = 'tyhjä';
				}
				isnumber = IsNumeric(destinations);
				if (isnumber == false){
					alert("VIRHE!\nMatkakohteiden määrä on "+destinations+", oikeellinen arvo on numero 1 - 20.");
					return false;
				}
				if ( destinations < 1 || destinations > 20 ){
					alert("VIRHE!\nMatkakohteiden määrä on "+destinations+", oikeellinen arvo on 1 - 20.");
					return false;
				}
				
				
				for(var x = 1; x <= destinations; x++){
					var hasSelections3 = false;
					for(var d = 1; d <= eval("document.travelstory_form.destination_"+country_id+"_"+x+".options.length"); d++){
						de = d-1;
						if( eval("document.travelstory_form.destination_"+country_id+"_"+x+".options["+de+"].selected") && eval("document.travelstory_form.destination_"+country_id+"_"+x+".options["+de+"].value") != 00 ){
							hasSelections3 = true;
							destination_count++;
							//alert("\nMatkakohde nro (x):"+x+" \nMatkakohteen vaihtoehto jota käydään läpi (d):"+de+"  \ndestination_count++ = "+destination_count+", \ndestinations = "+destinations);
						}
					}
				}
				if( destination_count < destinations ){
					
						alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtuja matkakohteita.");
						return false;
					
				}
			}
		}
		if(!hasSelections3){
			alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtuja matkakohteita.");
			return false;
		}
		if(!hasSelections2){
			alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtuja maita.");
			return false;
		}
	}
	travelstory_startdate = document.travelstory_form.travelstory_startdate.value;
	if( travelstory_startdate == '' ){
		travelstory_startdate = 'tyhjä';
	}
	isdate = isValidDate(travelstory_startdate, 'DMY');
	
	if ( isdate == false ){
		alert("VIRHE!\nLähtöpäivä on '"+travelstory_startdate+"', oikeellinen arvo on päivämäärä muodossa pp-kk-vvvv, esim. 30-04-2008");
		return false;
	}
	
	header = document.travelstory_form.travelstory_header.value;
	
	if ( (header.length > 100) || (header.length < 5) ){
		alert("VIRHE!\nMatkakertomuksen otsikko on "+header.length+" merkkiä, oikeellinen arvo on 5-100 merkkiä.");
		return false;
	}
	
	subheader = document.travelstory_form.travelstory_subheader.value;
	
	if ( subheader.length > 300 ){
		alert("VIRHE!\nMatkakertomuksen alaotsikko on "+subheader.length+" merkkiä, oikeellinen arvo on enintään 300 merkkiä.");
		return false;
	}
	
	duration_days = document.travelstory_form.travelstory_duration.value;
	if( duration_days == '' ){
		duration_days = 'tyhjä';
	}
	isnumber = IsNumeric(duration_days);
	if ( isnumber == false || duration_days < 1 ){
		alert("VIRHE!\nMatkan kesto on '"+duration_days+"', oikeellinen arvo on numero, esim. 14");
		return false;
	}
	
	if( document.travelstory_form.travelstory_days_or_single.value = 'yes' ){
		for( var i=1; i<=duration_days; i++ ){
			
			travelstory_day = eval("document.travelstory_form.day"+i+".value");
			
			if ( travelstory_day.length < 50 ){
				alert("VIRHE!\nMatkakertomuksen päivä "+ i +" on vain "+travelstory_day.length+" merkkiä, vähimmäispituus on 50 merkkiä.");
				return false;
			}
		}
	}
	else{
		travelstory_day = document.travelstory_form.singleday.value;
		if ( travelstory_day.length < 500 ){
			alert("VIRHE!\nMatkakertomuksen pituus on vain "+travelstory_day.length+" merkkiä, vähimmäispituus on 500 merkkiä.");
			return false;
		}
	}
}

function IsNumeric(sText){
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}


function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

function changeUserPageContent(selected){
	document.getElementById('profile_link').style.fontWeight  = "normal";
	if( document.getElementById('news_link') ){
		document.getElementById('news_link').style.fontWeight  = "normal";
	}
	document.getElementById('pictures_link').style.fontWeight  = "normal";
	document.getElementById('past_trips_link').style.fontWeight  = "normal";
	document.getElementById('future_trips_link').style.fontWeight  = "normal";
	document.getElementById('travelstorys_link').style.fontWeight  = "normal";
	if( document.getElementById('settings_link') ){
		document.getElementById('settings_link').style.fontWeight  = "normal";
	}
	document.getElementById(selected+"_link").style.fontWeight  = "bold";
	
	document.getElementById('profile_content').style.display = "none";
	if( document.getElementById('news_link') ){
		document.getElementById('news_content').style.display = "none";
	}
	document.getElementById('pictures_content').style.display = "none";
	document.getElementById('past_trips_content').style.display = "none";
	document.getElementById('future_trips_content').style.display = "none";
	document.getElementById('travelstorys_content').style.display = "none";
	if( document.getElementById('settings_content') ){
		document.getElementById('settings_content').style.display = "none";
	}
	document.getElementById(selected+"_content").style.display  = "block";
}

function changeThumbnailToImageAndComments(thumbnail_image_id,uid2){

	var url = siteurl+"/image_discussion.php?image_id=" + thumbnail_image_id + "&uid2=" + uid2;
	
	request2.open("GET", url, true);
	request2.onreadystatechange = updateImageAndComments;
	request2.send('');
}

function changeImageAndCommentsToThumbnail(){

}



function updateImageAndComments(){

	try{
		if(request2.readyState == 1){
			
		}
		if (request2.readyState == 4){
		
			if ( (request2.status == 200) || (request2.status == 0) ){
			
				var vastaus = request2.responseText;
				
				document.getElementById('profile_big_image_container').style.display='block';
				document.getElementById('profile_big_image_container').innerHTML = vastaus;
			}
			else if (request2.status == 404){
				
				alert("Request URL does not exist - 404");
			}
			else{

				alert("Error: status code is " + request2.status);
			}
		}		
	}
	catch(e){
	
	}
}

function changeOpacity(the_id, value){
	document.getElementById(the_id).style.opacity = value/10;
	
	document.getElementById(the_id).style.filter = 'alpha(opacity='+ value*10 + ')';
}

function theUnLoadEvent(){
	document.getElementById('page_darken').style.position = 'fixed';
	document.getElementById('page_darken').style.display = 'block';
	document.getElementById('page_darken_info').style.display = 'block';
}

function theLoadEvent(){
	document.getElementById('page_darken').style.display = 'none';
	document.getElementById('page_darken_info').style.display = 'none';
	
	if( screen.height  ){
		theheight = screen.height;
		document.getElementById('page_darken').style.height = theheight-100+"px";
		document.getElementById('page_darken_info').style.marginTop = (theheight-100)/2 - ((theheight-100)*0.1)+"px";
	}
}

function hideThis(value, value2){
	document.getElementById(value).style.display = 'none';
	if( value2 != 'null' ){
		document.getElementById(value2).style.display = 'none';
	}
}

//var t = setTimeout( "onloadTimeoutfunction()", 10000 );

function onloadTimeoutfunction(){
	if ( window.onLoad ){
		
	}
	else{
		//theLoadEvent()
	}
}

function changeAgencyPageContent(selected){
	document.getElementById('profile_link').style.fontWeight  = "normal";
	document.getElementById('news_link').style.fontWeight  = "normal";
	document.getElementById('pictures_link').style.fontWeight  = "normal";
	document.getElementById('offers_link').style.fontWeight  = "normal";
	document.getElementById('travelstorys_link').style.fontWeight  = "normal";
	if( document.getElementById('settings_link') ){
		document.getElementById('settings_link').style.fontWeight  = "normal";
	}
	document.getElementById(selected+"_link").style.fontWeight  = "bold";
	
	document.getElementById('profile_content').style.display = "none";
	document.getElementById('news_content').style.display = "none";
	document.getElementById('pictures_content').style.display = "none";
	document.getElementById('offers_content').style.display = "none";
	document.getElementById('travelstorys_content').style.display = "none";
	if( document.getElementById('settings_content') ){
		document.getElementById('settings_content').style.display = "none";
	}
	document.getElementById(selected+"_content").style.display  = "block";
}

function changeForumPage(direction, the_first, per_page){
	
	var url = siteurl+"/forum_content.php?direction=" + direction + "&the_first=" + the_first + "&per_page=" + per_page;
		
	request.open("GET", url, true);
	request.onreadystatechange = updateForumPosts;
	request.send('');
}

function updateForumPosts(){
	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
			
				document.getElementById('topics_container').innerHTML='';
				var vastaus = request.responseText;
				document.getElementById('topics_container').innerHTML = vastaus;
			}
			else if (request.status == 404){
				
				alert("Request URL does not exist - 404");
			}
			else{

				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}
}

function validateRegisterForm(){
	firstname = document.register.firstname.value;
	lastname = document.register.lastname.value;
	email = document.register.email.value;
	password = document.register.password.value;
	password_confirmed = document.register.password_confirmed.value;
	
	if( firstname == '' || lastname == '' || email == '' || password == '' || password_confirmed == '' ){
		alert('Ole hyvä ja täytä kaikki tiedot.');
		return false;
	}
}

function validateRegisterForm2(){
	homecity = document.register2.homecity.value;
	birthdate = document.register2.birthdate.value;
	gender = document.register2.groupGender.checked;
	
	if( homecity == '' || birthdate == '' || gender == 'false' ){
		alert('Ole hyvä ja täytä kaikki tiedot.\n(Profiilikuva ei ole pakollinen.)');
		return false;
	}
}

function validateNewTopic(){

	topic_main_topic = document.topic_newTopicForm.topic_main_topic.checked;
	topic_title = document.topic_newTopicForm.topic_title.value;
	topic_thetext = document.topic_newTopicForm.topic_thetext.value;
	
	if( topic_title == '' || topic_thetext == '' || topic_main_topic == 'false' ){
		alert('Ole hyvä ja täytä kaikki tiedot.');
		return false;
	}
	if ( topic_title.length > 150 ){
		alert('Aiheen pituus on liian suuri.\n(Maksimipituus 150 merkkiä.)');
		return false;
	}
	if ( topic_title.length < 2 ){
		alert('Aiheen pituus on liian pieni.\n(Minimipituus 2 merkkiä.)');
		return false;
	}
	if ( topic_thetext.length < 10 ){
		alert('Viestin pituus on liian pieni.\n(Minimipituus 10 merkkiä.)');
		return false;
	}
}

function Quote(quote_id){
	quote_text_id = quote_id.replace("image", "text");
	thequotetext = eval("document.getElementById('" + quote_text_id + "').innerHTML");
	thequotetext = thequotetext.replace(/<br>/g, "\n");
	thequotetext = thequotetext.replace(/<br \/g>/, "\n");
	thequotetext = thequotetext.replace(/<br\/>/g, "\n");
	thequotetext = thequotetext.replace(/\n\n\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/<div class="quote">/g, "[quote]");
	thequotetext = thequotetext.replace(/<\/div>/g, "[/quote]");
	
	previoustext = document.reply_newReplyForm.reply_thetext.value;
	thequotetext = thequotetext.replace(/<br>/g, "\n");
	thequotetext = thequotetext.replace(/<br \/g>/, "\n");
	thequotetext = thequotetext.replace(/<br\/>/g, "\n");
	thequotetext = thequotetext.replace(/\n\n\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/\n\n\n/g, "\n\n");
	thequotetext = thequotetext.replace(/<div class="quote">/g, "[quote]");
	thequotetext = thequotetext.replace(/<\/div>/g, "[/quote]");
	
	document.reply_newReplyForm.reply_thetext.value = previoustext + "\n\n[quote]" + thequotetext + "[/quote]";
}

function changeFastTravelsOrder(order, direction, only){
	var url = siteurl+"/fasttravels.php?order=" + order + "&direction=" + direction + "&only=" + only;	
	document.getElementById('loading_gif').style.display = "block";
	
	request.open("GET", url, true);
	request.onreadystatechange = updateFastTravelsOrder;
	request.send('');
}


function updateFastTravelsOrder(){
	try{
		if (request.readyState == 4){
			if ( (request.status == 200) || (request.status == 0) ){
			
				var vastaus = request.responseText;
				document.getElementById('loading_gif').style.display = "none";
				document.getElementById('all_fasttravels_container').innerHTML = vastaus;
			}
			else if (request.status == 404){
				
				alert("Request URL does not exist - 404");
			}
			else{

				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}

}

function toggleBGColor(element_id){
	
    var style2 = document.getElementById(element_id).style;
    style2.backgroundColor = style2.backgroundColor? "":"#FFFF00";
}

function submitComment(owner,image){
	
	comment = document.commentform.thecomment.value;
	if( document.commentform.commentisprivate.checked === true ){
		commentisprivate = "true";
	}
	else{
		commentisprivate = "false";
	}
	var url = siteurl+"/submitcomment.php?owner=" + owner + "&image=" + image + "&comment=" + comment + "&isprivate=" + commentisprivate;
	
	request.open("GET", url, true);
	request.onreadystatechange = updateComments;
	request.send('');
	document.commentform.thecomment.value = "";
	return false; 
}


function deleteComment(owner,id,image){
	
	var url = siteurl+"/deletecomment.php?owner=" + owner + "&id=" + id  + "&image=" + image;
	request.open("GET", url, true);
	request.onreadystatechange = updateComments;
	request.send('');
}

function updateComments(){
	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
			
				var vastaus = request.responseText;
				document.getElementById('discussion_all_messages_container').innerHTML = vastaus;
			}
			else if (request.status == 404){
				
				alert("Request URL does not exist - 404");
			}
			else{

				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}

}

function saveToMyVisitedPlaces( page, theid){
	
	var url = siteurl+"/savetovisited.php?page=" + page + "&id=" + theid;
	request.open("GET", url, true);
	request.onreadystatechange = updateMyVisitedPlaces;
	request.send('');
	return false; 
}


function updateMyVisitedPlaces(){

	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
				var vastaus = request.responseText;
				document.getElementById('stuff_added').innerHTML = vastaus;
			}
			else if (request.status == 404){
				alert("Request URL does not exist - 404");
			}
			else{
				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}

}

function deleteFromMyVisitedPlaces( page, theid){
	var url = siteurl+"/deletefromvisited.php?page=" + page + "&id=" + theid;
	request.open("GET", url, true);
	request.onreadystatechange = updateMyVisitedPlaces;
	request.send('');
	return false; 
}

function saveToMyGoingToPlaces( page, theid){
	date = document.going_to_form.date.value;
	var url = siteurl+"/savetogoingto.php?page=" + page + "&id=" + theid + "&when=" + date;
	
	request.open("GET", url, true);
	request.onreadystatechange = updateMyGoingToPlaces;
	request.send('');
	return false; 
}

function updateMyGoingToPlaces(){

	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
				var vastaus = request.responseText;
				document.getElementById('stuff_added').innerHTML = vastaus;
			}
			else if (request.status == 404){
				alert("Request URL does not exist - 404");
			}
			else{
				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}
}

function deleteFromMyGoingToPlaces( page, theid){
	
	var url = siteurl+"/deletefromgoingto.php?page=" + page + "&id=" + theid;
	request.open("GET", url, true);
	request.onreadystatechange = updateMyGoingToPlaces;
	request.send('');
	return false; 
}

var hintataso_freeze = false;
var ruoan_ja_juoman_hintataso_freeze = false;
var turismi_freeze = false;
var soveltuvuus_lapsille_freeze = false;
var luonto_freeze = false;
var siisteys_freeze = false;
var rikollisuus_freeze = false;
var aurinkoisuus_freeze = false;
var shoppailu_freeze = false;
var romanttisuus_freeze = false;
var biletys_freeze = false;
var kaupunkimaisuus_freeze = false;
var maaseutumaisuus_freeze = false;
var kokonaisvaikutelma_freeze = false;

function changeRating(what_to_change,how_much,file_word){
	if( eval( what_to_change + "_freeze") == false ){
		eval("document.getElementById('rating_background_"+what_to_change+"').style.background = 'url("+ siteurl +"/images/rates/" + file_word + "_" + how_much + ".png)'");
		eval("document.getElementById('rating_background_"+what_to_change+"').style.backgroundPosition = 'center right'");
		eval("document.getElementById('rating_background_"+what_to_change+"').style.backgroundRepeat = 'no-repeat'");
	}
}

function lockRating(what_to_lock,how_much,file_word){
	eval( what_to_lock + "_freeze = true");
	eval("document.ratethisform." + what_to_lock + ".value = '" + how_much + "'");
	eval("document.getElementById('rating_background_"+what_to_lock+"').style.background = 'url("+ siteurl +"/images/rates/" + file_word + "_" + how_much + ".png)'");
	eval("document.getElementById('rating_background_"+what_to_lock+"').style.backgroundPosition = 'center right'");
	eval("document.getElementById('rating_background_"+what_to_lock+"').style.backgroundRepeat = 'no-repeat'");
}

function saveToMyFavoritePlaces( page, theid){
	
	var url = siteurl+"/savetofavorite.php?page=" + page + "&id=" + theid;
	request.open("GET", url, true);
	request.onreadystatechange = updateMyFavoritePlaces;
	request.send('');
	return false; 
}

function updateMyFavoritePlaces(){
	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
				var vastaus = request.responseText;
				document.getElementById('stuff_added').innerHTML = vastaus;
			}
			else if (request.status == 404){
				alert("Request URL does not exist - 404");
			}
			else{
				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}

}

function deleteFromMyFavoritePlaces( page, theid){
	var url = siteurl+"/deletefromfavorite.php?page=" + page + "&id=" + theid;
	request.open("GET", url, true);
	request.onreadystatechange = updateMyFavoritePlaces;
	request.send('');
	return false; 
}

function falseFunction(){ 
	return false;
}

var noticel;
function friendRequest(what, uid, notice){
	noticel = notice;
	var url = siteurl+"/friendrequest.php?what=" + what + "&uid=" + uid;
	request.open("GET", url, true);
	request.onreadystatechange = updateFriendRequest;
	request.send('');
	return false; 
}

function updateFriendRequest(){

	try{
		if (request.readyState == 4){
		
			if ( (request.status == 200) || (request.status == 0) ){
			
				var vastaus = request.responseText;
				document.getElementById(noticel).innerHTML = vastaus;
			}
			else if (request.status == 404){
				
				alert("Request URL does not exist - 404");
			}
			else{

				alert("Error: status code is " + request.status);
			}
		}		
	}
	catch(e){
	
	}
}

function travelCompanyForm(){
	if( document.going_to_form.company.checked === true ){
		document.getElementById('travelcompanyform_container1').style.display = "block";
		document.getElementById('travelcompanyform_container2').style.display = "block";
		document.getElementById('travelcompanyform_container3').style.display = "block";
		document.getElementById('travelcompanyform_container4').style.display = "block";
		document.getElementById('travelcompanyform_container5').style.display = "block";
		document.getElementById('travelcompanyform_container6').style.display = "block";
		document.getElementById('travelcompanyform_container7').style.display = "block";
	}
	else{
		document.getElementById('travelcompanyform_container1').style.display = "none";
		document.getElementById('travelcompanyform_container2').style.display = "none";
		document.getElementById('travelcompanyform_container3').style.display = "none";
		document.getElementById('travelcompanyform_container4').style.display = "none";
		document.getElementById('travelcompanyform_container5').style.display = "none";
		document.getElementById('travelcompanyform_container6').style.display = "none";
		document.getElementById('travelcompanyform_container7').style.display = "none";
	}
}

function getCountrysDestinationVisitList(){
	select_index = document.visitcountryform.countrys.selectedIndex;
	required = document.visitcountryform.countrys.options[select_index].value;
	if( required != 0 ){
		var url = siteurl+"/getdestinationsforvisited.php?country=" + required;
			
		request.open("GET", url, true);
		request.onreadystatechange = updateDestinationsVisited;
		request.send('');
	}
}


function updateDestinationsVisited(){
	if (request.readyState == 4){
		if (request.status == 200){
			var vastaus = request.responseText;
			document.getElementById('destinations_container').innerHTML = vastaus;
		}
		else if (request.status == 404){
			
			alert("Request URL does not exist - 404");
		}
		else{
			alert("Error: status code is " + request.status);
		}
	}	
}

var searchbox= 1;
function searchSuggest( searchboxi ){
	searchbox = searchboxi;
	required = eval("document.searchform_" +searchbox+ ".elements[0].value");
	if ( (required.length > 2) && (required != null) ) {
		var url = siteurl+"/getsearchsuggest.php?search=" + required;
		request.open("GET", url, true);
		request.onreadystatechange = updateSearchSuggest;
		request.send('');
	}
	else{
		eval("document.getElementById('searchsuggest_container_"+ searchbox +"').style.display = 'none'");
		eval("document.getElementById('searchsuggest_container_"+ searchbox +"').innerHTML = ''");
	}	
}


function updateSearchSuggest(){
	if (request.readyState == 4){
		if (request.status == 200){
			var vastaus = request.responseText;
			if ( (vastaus.length != 0) && (vastaus != null) ) {
				eval("document.getElementById('searchsuggest_container_"+ searchbox +"').style.display = 'block'");
			}
			eval("document.getElementById('searchsuggest_container_"+ searchbox +"').innerHTML = vastaus");
			
		}
		else if (request.status == 404){
			//alert("Request URL does not exist - 404");
		}
		else{
			//alert("Error: status code is " + request.status);
		}
	}	
}

function ajax_get_list_of_offers(agency_id){

	nocache = Math.random();
	change = "visibles";
	select_index = document.offer_form.order.selectedIndex;
	order = document.offer_form.order.options[select_index].value;
	var url = siteurl + "/include/matkatoimisto/getoffers.php?visible=1&agency_id=" + agency_id + "&order=" + order+ "&nocache=" + nocache;
		
	request12.open("GET", url, true);
	request12.onreadystatechange = updatePage;
	request12.send(null);
}

function updatePage(){
	if(request12.readyState == 1){
		
		document.getElementById(change).innerHTML='';
		document.getElementById(change).innerHTML = 'Ladataan tarjouksia...';
	}
	if (request12.readyState == 4){
	
		if ((request12.status == 200) || (request12.status == 0)){
			
			var vastaus = request12.responseText;
			document.getElementById(change).innerHTML='';
			document.getElementById(change).innerHTML = vastaus;
		}
		else if (request12.status == 404){
			alert("Request URL does not exist - 404");
		}
		else{
			alert("Error: status code is " + request12.status);
		}
	}	
}




function getTravelTypes(){
	nocache = Math.random();
	var url = siteurl + "/include/matkatoimisto/gettraveltypes.php?nocache="+nocache;
	request4.open("GET", url, true);
	request4.onreadystatechange = updateTravelTypes;
	request4.send(null);
}

function updateTravelTypes(){

	if (request4.readyState == 4){
		if ((request4.status == 200) || (request4.status == 0)){
			var vastaus = request4.responseText;
			document.getElementById('travel_types_select').innerHTML='';
			document.getElementById('travel_types_select').innerHTML = vastaus;
		}
	}
}

function getTravelTypesTwo(){
nocache = Math.random();
	var url = siteurl + "/include/matkatoimisto/gettraveltypes.php?nocache="+nocache;
	request18.open("GET", url, true);
	request18.onreadystatechange = updateTravelTypesTwo;
	request18.send(null);

}

function updateTravelTypesTwo(){
	if (request18.readyState == 4){
		if ((request18.status == 200) || (request18.status == 0)){
			var vastaus = request18.responseText;
			document.getElementById('travel_types_select').innerHTML='';
			document.getElementById('travel_types_select').innerHTML = vastaus;
		}
	}
}

function clearForms(selected, agency_id){
	document.offer_form.number_of_countrys.value = '1';
	document.offer_form.cost.value = '';
	document.offer_form.this_is_starting_prize.checked = false;
	document.offer_form.undefined_accommodation.checked = false;
	document.offer_form.only_flight.checked = false;
	document.offer_form.travel_start_date.value = '';
	document.offer_form.duration_days.value = '7';
	document.offer_form.offer_header.value = '';
	document.offer_form.description.value = '';
	document.offer_form.use_signature.checked = true;
	document.offer_form.offer_id.value = selected;
	
	changeNumberOfCountrysTwo('1',agency_id) 
	getTravelTypesTwo()
	
	getDefaultWebAddress(agency_id);
	getDefaultPhone(agency_id);
	getDefaultSignature(agency_id);
}

function getDefaultWebAddress(agency){
	nocache = Math.random();
	require_this = 'web_address';
	var url = siteurl + "/include/matkatoimisto/populate_web_address.php?agency_id=" + agency + "&require_this=" + require_this+"&nocache="+nocache;
	request14.open("GET", url, true);
	request14.onreadystatechange = updateWebAddress;	
	request14.send(null);
}

function updateWebAddress(){

	if (request14.readyState == 4){
		if ((request14.status == 200) || (request14.status == 0)){
			var vastaus = request14.responseText;
			document.offer_form.web_address.value = vastaus;
		}
	}
}

function getDefaultPhone(agency){
nocache = Math.random();
	require_this = 'public_phone';
	var url = siteurl + "/include/matkatoimisto/populate_public_phone.php?agency_id=" + agency + "&require_this=" + require_this+"&nocache="+nocache;
	request15.open("GET", url, true);
	request15.onreadystatechange = updatePublicPhone;
	request15.send(null);
}

function updatePublicPhone(){

	if (request15.readyState == 4){
		if ((request15.status == 200) || (request15.status == 0)){
			var vastaus = request15.responseText;
			document.offer_form.public_phone.value = vastaus;
		}
	}
}

function getDefaultSignature(agency){
nocache = Math.random();
	require_this = 'signature';
	var url = siteurl + "/include/matkatoimisto/populate_signature.php?agency_id=" + agency + "&require_this=" + require_this+"&nocache="+nocache;
	
	request16.open("GET", url, true);
	request16.onreadystatechange = updateSignature;
	request16.send(null);

}

function updateSignature(){
	if (request16.readyState == 4){
		if ((request16.status == 200) || (request16.status == 0)){
			//alert("Valmis!"+agency);
			var vastaus = request16.responseText;
			document.offer_form.signature.value = '';
			document.offer_form.signature.value = vastaus;
		}
	}
}




function changeNumberOfCountrysTwo(number, agency){
nocache = Math.random();
	var url = siteurl + "/include/matkatoimisto/getcountrylist.php?number="+number+"&agency_id="+agency+"&nocache="+nocache;
	request17.open("GET", url, true);
	request17.onreadystatechange = updateCountryLists;
	request17.send(null);
}

function updateCountryListsTwo(){
	if (request17.readyState == 4){
		if ((request17.status == 200) || (request17.status == 0)){
			var vastaus = request17.responseText;
			document.getElementById('countrys_container').innerHTML='';
			document.getElementById('countrys_container').innerHTML = vastaus;
		}
	}
}

function showhide(obj){
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = 'block';
	}
}

function ajax_get_list_of_hidden_offers(agency_id){
	nocache = Math.random();
	change2 = "hiddens";
	order = 'offer.id';
	var url = siteurl + "/include/matkatoimisto/getoffers.php?visible=0&agency_id=" + agency_id + "&order=" + order+ "&nocache=" + nocache;
	request2.open("GET", url, true);
	request2.onreadystatechange = updatePageHiddens;
	request2.send(null);
}


function updatePageHiddens(){
	if(request2.readyState == 1){
		document.getElementById(change2).innerHTML='';
		document.getElementById(change2).innerHTML = 'Ladataan piilotettuja tarjouksia...';
	}
	if (request2.readyState == 4){
		if ((request2.status == 200) || (request2.status == 0)){
			var vastaus2 = request2.responseText;
			document.getElementById(change2).innerHTML='';
			document.getElementById(change2).innerHTML = vastaus2;
			
		}
		else if (request2.status == 404){
			
			alert("Request2 URL does not exist - 404");
		}
		else{
			alert("Error: status code is " + request2.status);
		}
	}
}

function validateOfferForm(){
	countrys = document.offer_form.number_of_countrys.value;
	if( countrys == '' ){
		countrys = 'tyhjä';
	}
	isnumber = IsNumeric(countrys);
	if (isnumber == false){
		alert("VIRHE!\nMaiden määrä on "+countrys+", oikeellinen arvo on numero 1 - 20.");
		return false;
	}
	if ( countrys < 1 || countrys > 20 ){
		alert("VIRHE!\nMaiden määrä on "+countrys+", oikeellinen arvo on 1 - 20.");
		return false;
	}
	for(var i = 1; i <= countrys; i++){
		var hasSelections2 = false;
		for(var e = 1; e <= eval("document.offer_form.select_"+i+".options.length")-1; e++){
			if( eval("document.offer_form.select_"+i+".options["+e+"].selected") ){
				
				hasSelections2 = true;
				country_id = eval("document.offer_form.select_"+i+".options["+e+"].value");
				destinations = eval("document.offer_form.number_of_destinations_"+i+".value");
				destination_count=0;
				if( destinations == '' ){
					destinations = 'tyhjä';
				}
				isnumber = IsNumeric(destinations);
				if (isnumber == false){
					alert("VIRHE!\nMatkakohteiden määrä on "+destinations+", oikeellinen arvo on numero 1 - 20.");
					return false;
				}
				if ( destinations < 1 || destinations > 20 ){
					alert("VIRHE!\nMatkakohteiden määrä on "+destinations+", oikeellinen arvo on 1 - 20.");
					return false;
				}
				
				for(var x = 1; x <= destinations; x++){
					var hasSelections3 = false;
					for(var d = 1; d <= eval("document.offer_form.destination_"+country_id+"_"+x+".options.length"); d++){
						de = d-1;
						if( eval("document.offer_form.destination_"+country_id+"_"+x+".options["+de+"].selected") && eval("document.offer_form.destination_"+country_id+"_"+x+".options["+de+"].value") != 00 ){
							hasSelections3 = true;
							destination_count++;
						}
					}
				}
				if( destination_count < destinations ){
					
						alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtavia matkakohteita.");
						return false;
					
				}
			}
		}
		if(!hasSelections3){
			alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtavia matkakohteita.");
			return false;
		}
		if(!hasSelections2){
			alert("VIRHE!\nEt ole valinnut kaikkia matkan aikana vierailtavia maita.");
			return false;
		}
	}
	
	cost = document.offer_form.cost.value;
	if( cost == '' ){
		cost = 'tyhjä';
	}
	isnumber = IsNumericWithDot(cost);
	if ( isnumber == false || cost < 10 ){
		alert("VIRHE!\nMatkan hinta on '"+cost+"', oikeellinen arvo on numero, esim. 395");
		return false;
	}
	
	travel_start_date = document.offer_form.travel_start_date.value;
	if( travel_start_date == '' ){
		travel_start_date = 'tyhjä';
	}
	isdate = isValidDate(travel_start_date, 'YMD');
	
	if ( isdate == false ){
		alert("VIRHE!\nLähtöpäivä on '"+travel_start_date+"', oikeellinen arvo on päivämäärä, esim. 2008-01-28 tai 2008.06.15");
		return false;
	}
	
	duration_days = document.offer_form.duration_days.value;
	if( duration_days == '' ){
		duration_days = 'tyhjä';
	}
	isnumber = IsNumeric(duration_days);
	if ( isnumber == false || duration_days < 1 ){
		alert("VIRHE!\nMatkan kesto on '"+duration_days+"', oikeellinen arvo on numero, esim. 14");
		return false;
	}
	
	if( document.offer_form.only_flight.checked && document.offer_form.undefined_accommodation.checked ){
		alert("VIRHE!\nEt voi valita matkalle 'vain lentoa' ja myös 'määrittelemätöntä majoitusta'.");
		return false;
	}
	
	public_phone = document.offer_form.public_phone.value;
	if( public_phone == '' ){
		public_phone = 'tyhjä';
	}
	isnumber = IsNumeric(public_phone);
	if ( isnumber == false || public_phone < 1 ){
		alert("VIRHE!\nMatkan tilaamiseen tarkoitettu puhelinnumero on '"+public_phone+"', oikeellinen arvo on numero ilman välimerkkejä tai välejä, esim. 0401234567");
		return false;
	}
	
	header = document.offer_form.offer_header.value;
	if( header == '' ){
		header = 'tyhjä';
	}
	if ( header.length > 40 ){
		alert("VIRHE!\nTarjouksen otsikko on "+header.length+" merkkiä, oikeellinen arvo on enintään 40 merkkiä pitkä.");
		return false;
	}
	
	travel_description = document.offer_form.description.value;
	if( travel_description == '' ){
		travel_description = 'tyhjä';
	}
	if ( travel_description.length < 100 ){
		alert("VIRHE!\nTarjouksen kuvaus on vain "+travel_description.length+" merkkiä, kuvauksen vähimmäispituus on 100 merkkiä.");
		return false;
	}
	
	var hasSelections = false;
	for(var i = 0; i < document.getElementById('travel_type').options.length; i++){
		if(document.getElementById('travel_type').options[i].selected){
			hasSelections = true;
			break;
		}
	}
	if(!hasSelections){
		alert("VIRHE!\nEt ole valinnut matkan tyyppiä, valitse vähintään yksi matkan tyyppi.");
		return false;
	}
}

function IsNumeric(sText){
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}

function IsNumericWithDot(sText){
	var ValidChars = "0123456789,";
	var IsNumber=true;
	var Char;


	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}


function showHideOffer(obje){

	var el = document.getElementById('offercontent_'+obje);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = 'block';
	}
	
	var el_footer = document.getElementById('offercontent_footer_'+obje);
	if ( el_footer.style.display != 'none' ) {
		el_footer.style.display = 'none';
	}
	else {
		el_footer.style.display = 'block';
	}
}

function showNumberOfLetters(measurethis,exporthere){
	var nWords = document.getElementById(measurethis).value.length;
	document.getElementById(exporthere).innerHTML = "Kirjaimia: <strong>"+nWords+"</strong> (Minimi 300)";
	if (nWords < 300){
		document.getElementById(exporthere).style.color = "red";
	}else{
		document.getElementById(exporthere).style.color = "green";
	}
}


var map;
var geocoder;
var maa = 0;

function load() {
  map = new GMap2(document.getElementById("map"));
  map.setCenter(new GLatLng(65.010338, 25.473379), 6);
  geocoder = new GClientGeocoder();
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  
	
	var options = {
      searchFormHint : "Etsi kartalta...",
	  resultList : document.getElementById("results")
      };
	map.addControl(new google.maps.LocalSearch(options),new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,-30)));
}
var lukumaara = 0;
// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
	//alert("Anteeksi, emme pystyneet paikallistamaan antamaanne osoitetta.");
	
	//var where_is = document.getElementById('karttapaikka').value.indexOf(', ');
	var destination_and_country_array= document.getElementById('karttapaikka').value.split(", ");
	var maa = destination_and_country_array[1];
	//alert ("Maa:"+destination_and_country_array[1]);
	document.getElementById('karttapaikka').value = maa;
	
	if (lukumaara <2){
		showLocation();
		lukumaara = lukumaara + 1;
	}
	
  } else {
	place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]);
	marker = new GMarker(point);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(place.address + '<br>' +
	  '<b>Maan tunnus:</b> ' + place.AddressDetails.Country.CountryNameCode);
  }
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
		var address = document.getElementById('karttapaikka').value;

  geocoder.getLocations(address, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
	document.getElementById('karttapaikka').value = address;
	showLocation();
}


function clearThis(elementti,oletus){
	var word = document.getElementById(elementti).value;
	//alert(word);
	if(word==oletus){
		document.getElementById(elementti).value='';
		document.getElementById(elementti).style.color = "#111111";
	}
}

function populateThisAgain(elementti,oletus){
	var word = document.getElementById(elementti).value;
	//alert(word);
	if(word==''){
		document.getElementById(elementti).value=oletus;
		document.getElementById(elementti).style.color = "#464646";
	}
}

var changediv;

function changeImageNew( page, cid, direction, im_id ){
	
	changediv = "bigimagecontainernew";
	var url = siteurl+"/changeimage.php?page="+page+"&cid="+cid+"&direction="+direction+"&im_id="+im_id;
		
	request.open("GET", url, true);
	request.onreadystatechange = updateBigImage;
	
	request.send(null);
}

function updateBigImage(){

	if(request.readyState == 1){
		
		document.getElementById(changediv+"_loading").innerHTML='';
		document.getElementById(changediv+"_loading").innerHTML = 'Ladataan kuvaa...';
		
	}
	if (request.readyState == 4){
	
		if ((request.status == 200) || (request.status == 0)){
			var vastaus = request.responseText;
			document.getElementById(changediv).innerHTML = vastaus;
			document.getElementById(changediv+"_loading").innerHTML='';
			
		}
		else if (request.status == 404){
			
			alert("Request URL does not exist - 404");
		}
		else{

			alert("Error: status code is " + request.status);
		}
	}		
	

}
