// open a popup window
function showPopup(which,w,h)
{
	
  popWindow = open(which,"popup","width=" + w + ",height=" + h + ",location,menubar,resizable,scrollbars,status,toolbar");
  popWindow.opener = self;
  popWindow.focus();

}
// return to list of B&B or apartments
// if the visitor came from the list, just go back
// if the visitor came from a search engine or a bookmark, 
// go to full list (bb_all or apt_all) for the correct language
function backToList()
{
	// if the user got here through links on our site, just go back
	if (document.referrer.indexOf("b-b.rm.it") != -1) 
	{   
		history.go(-1);
	}
	// otherwise, the user came directly from a search engine 
	// or another site, load the list of properties...
	else
	{
		location.href="index.php";
	}
	
}
// set the photo at the top right and set the selected menu button
function initPage(which,level,theLang)
{
	path = "";
	
	for(i=0;i<level;i++)
	{
		path += "../";
	}
	path += "images" + "/common/foto_" + which + ".jpg";
	//alert(path);
	document.images['top_foto'].src = path;
	
	setSelButton(which,level,theLang);
}
// turn off all buttons
function turnAllOff(level,theLang)
{
	setButton('breakfast',level,theLang,"off");
	setButton('apartment',level,theLang,"off");
	setButton('who',level,theLang,"off");
	setButton('reviews',level,theLang,"off");
	setButton('info_rome',level,theLang,"off");
	setButton('info_italy',level,theLang,"off");
	setButton('bb_italy',level,theLang,"off");
	setButton('bb_world',level,theLang,"off");
	setButton('policy',level,theLang,"off");
	setButton('contact',level,theLang,"off");
	setButton('home',level,theLang,"off");
	
}
// set the selected button
function setSelButton(which, level, theLang)
{
	
	turnAllOff(level,theLang);
	if(which != "" && document.images[which])
	{
		document.images[which].src = buildPath(which,level,theLang,"sel");
	}
	
}
// preload images for mouseover
function preLoad(which, level, lang, setting)
{
	
	theImage = new Image();
	//alert(buildPath(which, level, lang, setting));
	theImage.src = buildPath(which, level, lang, setting);
	return(theImage);
}
// show mouseover
function turnOn(which, level, lang)
{
	if(isSel(which))
		return;
	//alert(buildPath(which, level, lang, "on"));
	setButton(which, level, lang, "on");
}
// show mouseoff
function turnOff(which, level, lang)
{
	
	if(isSel(which))
		return;
	//alert(buildPath(which, level, lang, "on"));
	setButton(which, level, lang, "off");
}
// set a button to the proper state
function setButton(which, level, lang, setting)
{	
	//alert(buildPath(which, level, lang, setting));
	document.images[which].src = buildPath(which, level, lang, setting);
}

// build path to image
function buildPath(which, level, lang, setting)
{
	path = "";

	for(i=0;i<level;i++)
	{
		path += "../";
	}

	path +=	"images/" + 
		(lang==null?"":lang) +
		(lang==null?"":"/") +
		which + 
		(setting==null?"":"_"+setting) +
		".gif";
	return(path);
}
// replace image
function replaceImage(which,imgName)
{
	document.images[which].src = "../images/" + imgName + ".gif";
}

// determines if button is selected in order to disable/enable mouseover functions
function isSel(which)
{
	if(document.images[which] &&
	   document.images[which].src &&
	   document.images[which].src.indexOf("_sel") == -1)
		return false;
	else
		return true;	

}

// make sure at least 1 property has been selected
// before going to the form, if not, warn user
// saves the selected properties
function gotoForm(selType,lang) 
{
	str = setSelRefs();
	if(str.length == 0)
	{
		if(selType == "bb")
		{
			return(showWarning("No B&Bs selected", "B&B", 'bb', str));
		}
		else
		{ 
			return(showWarning("No Apartments selected", "Apartment", 'apt', str));
		}
	}
	else
	{
		return(true);
 	}
}


/**
 * build a string with the selected reference numbers of bb/apartments
 * and send to form, ex "ref2rp, ref7rp"
 * NOTE: assumes all reference numbers are of type CheckBox and name 
 * begins with 'ref'
 */
function getRefs() {

 theForm = document.forms[0]; 
 str = "";
 for(i=0;i<theForm.elements.length;i++)
 {
 	if(theForm.elements[i].type == "checkbox")
 	{
 		if(theForm.elements[i].name.substr(0,3) == "ref")
 		{
 		 	if(theForm.elements[i].checked)
 			{
 				if(str != "")
 				{
 					str += ",";
 				}
 				str += theForm.elements[i].name
 				
 			} 
  		}
  	}	
 }
 return(str);

}
// show the selected properties by checking the boxes on the form
function setRefs(theForm) {

	var str = getCookie("SelectedRefs");
	if(str == "")
		return;
	//alert(str);	
 	var arrStr = str.split(',');
	//alert(arrStr.length)
 	for(i=0;i<arrStr.length;i++)
 	{
		//alert(arrStr[i]);
		if(theForm.elements[arrStr[i]])
 			theForm.elements[arrStr[i]].checked = true;	
 	}

}
// save the selected properties in a cookie
function setSelRefs()
{
	var strNew = getRefs(); // currently selected
	var strOld = getCookie("SelectedRefs"); // already selected
	//alert('new: ' + strNew);
	//alert('old: ' + strOld);
	var str = eliminateDuplicates(strNew,strOld);
	
	setCookie("SelectedRefs", str);
	return(str);
}

function eliminateDuplicates(strNew,strOld)
{
	var arrNew = strNew.split(',');
	var arrOld = strOld.split(',');
	var arr = new Array();
	var found= false;
	for(i=0;i<arrNew.length;i++)
	{
		arr[i] = arrNew[i];
	}
	var j=arr.length;
	for(i=0;i<arrOld.length;i++)
	{
		for(k=0,found=false;k<arr.length;k++)
		{
			if(arr[k] == arrOld[i]) 
			{
				found=true;
				break;
			}			
		}
		if(found==false)
			arr[j++] = arrOld[i];	
	}
	return(arr.join());
}

function clearSelRefs()
{
	setCookie("SelectedRefs", "");
}

// Sets cookie values. Expiration date is optional
function setCookie(name, value, expire) 
{   
	document.cookie = name + "=" + escape(value)   
	+ ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}
// get cookie value
function getCookie(Name) 
{   
	var search = Name + "=";   
	if (document.cookie.length > 0) 
	{ // only if there are any cookies      
		offset = document.cookie.indexOf(search);       
		if (offset != -1) 
		{ // only if cookie exists          
			offset += search.length;          
			// set index of beginning of value         
			end = document.cookie.indexOf(";", offset);          
			// set index of end of cookie value         
			if (end == -1)             
				end = document.cookie.length;         
			return unescape(document.cookie.substring(offset, end));      
		}    
	}
	return("");
}

// check required fields
function checkRequiredFields(theForm, lang)
{
	if(theForm.name.value == "")
	{
		if(lang == "english")
			alert("Please insert your full name.");
		else if(lang == "italiano")
			alert("Inserite i vostri nome e cognome, grazie.");
		else if(lang == "francais")
			alert("Insérez votre nom et prénom, merci.");
		theForm.name.focus();	
		return(false);
	}
	if(theForm.submit_by.value == "")
	{
		if(lang == "english")
			alert("Please insert your email address.");
		else if(lang == "italiano")
			alert("Inserite la vostra e-mail, grazie.");
		else if(lang == "francais")
			alert("Insérez votre adresse e-mail, merci.");
		theForm.submit_by.focus();	
		return(false);
	}
	if(theForm.CountryList != null)
	{
		if(theForm.CountryList[theForm.CountryList.selectedIndex].value == "0")
		{
			if(lang == "english")
				alert("Please select a country.");
			else if(lang == "italiano")
				alert("Si prega di specificare la nazione.");
			else if(lang == "francais")
				alert("Préciser le pays d'origine, merci.");

			theForm.CountryList.focus();
			return(false);
		}
	}	

	
	return(true);	
}
// warning in english for no selected properties
function showWarning(title, which, selType, str)
{
  var msg = "";
  msg = msg + "No " + which + "s were selected\n\n";
  msg = msg + "If you are interested in a particular " + which + ", click \"Cancel\" to return to the list and select ";
  msg = msg + "the check box next to the reference number.\n\n";
  msg = msg + "Otherwise, you may continue by clicking \"OK\" to request general information.";
  
  return(confirm(msg));

}
// warning in italian for no selected properties
function showWarningIt(title, which, selType, str)
{
  var msg = "";
  msg = msg + "Nessun " + which + " è stato selezionato\n\n";
  msg = msg + "Se vi interessa un " + which + " in particolare, cliccate \"Annulla\" per tornare alla lista e selezionatelo con il mouse\n\n";
  msg = msg + "Altrimenti, cliccate \"OK\" per chiedere informazioni generali.";
  
  return(confirm(msg));

}
// warning in french for no selected properties
function showWarningFr(title, which, selType, str)
{
  
  var msg = "";
  msg = msg + "Aucun " + which + " n'a été sélectionné\n\n";

  msg = msg + "Si vous etes intéressé à un " + which + " en particulier, cliquez \"Annulez\" pour retourner à la liste et sélectionnez-le.\n\n";
  msg = msg + "Autrement, cliquez sur \"OK\" pour des informations générales.";
  
  return(confirm(msg));

}

function doTop(level)
{
	document.write('<a h');
	document.write('ref="ma');
	document.write(getStart());
	document.write('uiry');
	document.write(getCode());
	document.write('rm.it" on');
	document.write('MouseOver');
	document.write('="turnOn(\'');
	document.write('indr\',the');
	document.write('Level,\'com');
	document.write('mon\')" onM');
	document.write('ouseOut="tu');
	document.write('rnOff(\'ind');
	document.write('r\',theLevel');
	document.write(',\'common\')"');
	document.write('><IMG NAME="');
	document.write('email" SRC="');
	if(level == "1")
		document.write('../');
	document.write('images/co');
	document.write('mmon/indr_o');
	document.write('ff.gif" WIDTH');
	document.write('="100" HEIGH');
	document.write('T="29" BORDE');
	document.write('R="0"></a>');
}

function getStart()
{
	return('ilto:inq');
}

function getCode()
{
	return(getSep() + 'b-b.');
}

function getSep()
{
	x = 23;
	y = 40;
	return("&#" + eval("x + y + 1"))
}
function getMid()
{
	return('quiry' + getSep() + 'b-');
}

function getLink()
{
	return('terbb' + getSep() + 'b-');
}

function dopaii(level)
{
	document.write('<a href="ma');
	document.write('il');
	document.write('to:in');	
	document.write(getMid());
	document.write('b.rm.it');
	document.write('"><img s');
	document.write('rc="' + (level=="1"?'../im':'im'));
	document.write('ages/commo');
	document.write('n/posta-pri');
	document.write('ncipale.g');
	document.write('if" widt');
	document.write('h="101" h');
	document.write('eight="13');
	document.write('" align="a');
	document.write('bsmiddle" b');
	document.write('order="0');
	document.write('"></a>');
	

}

function doLinks(lang)
{
	var msg = '';
	if(lang == 'japan')
		msg = "message";
	else if(lang == 'italiano')
		msg = "messaggio";
	else if(lang == 'francais')
		msg = "mail";
		
	document.write('<a hr');
	document.write('ef="m');
	document.write('ai');
	document.write('lto:webmas');
	document.write(getLink());
	document.write('b.rm.i');
	document.write('t">' + msg + '</a>');
}

function getCon(which)
{
	if(which == 1)
		return('iry' + getSep() + 'b-b.r');
	else if (which == 2)
		return('odation' + getSep() + 'b');
	else if (which == 3)
		return('rtment' + getSep() + 'b');
	else if (which == 4)
		return('tri' + getSep() + 'b-b.r');
	else if (which == 5)
		return('b' + getSep() + 'b-b.r');
	else if (which == 6)
		return('ioni' + getSep() + 'b-');
	else if (which == 7)
		return('ent' + getSep() + 'b-b.r');
	else if (which == 8)
		return('n' + getSep() + 'b-b.rm.');		
	else if (which == 9)
		return('tri' + getSep() + 'b-b.r');		
	else if (which == 10)
		return('bb' + getSep() + 'b-b.');		

}

function doConJapGen()
{
	document.write('<a hr');
	document.write('ef="mai');
	document.write('lto:japa');
	document.write(getCon(8));
	document.write('it"><img src=".');
	document.write('./images/common/pos');
	document.write('ta-japan.gif" width="1');
	document.write('55" height="14" border="');
	document.write('0"></a>');
}

function doConJapFeed()
{
	document.write('<a h');
	document.write('ref="mai');
	document.write('lto:f.ala');
	document.write(getCon(9));
	document.write('m.it"><img s');
	document.write('rc="../images/co');
	document.write('mmon/posta-jap-f');
	document.write('b.gif" width="155" he');
	document.write('ight="14" border=');
	document.write('"0"></a>');
}
function doConJapWeb()
{
	document.write('<a h');
	document.write('ref="mai');
	document.write('lto:webm');
	document.write('aster');
	document.write(getCon(10));
	document.write('rm.it"><img src="../i');
	document.write('mages/common/posta-j');
	document.write('ap-web.gif" width="1');
	document.write('55" height="14" borde');
	document.write('r="0"></a>');
}

// indirizzo email in base a paese di provenienza
function getIndirizzo()
{
	indSel = document.forms[0].CountryList.selectedIndex
	indCode = document.forms[0].CountryList[indSel].value.substring(0,2);
	if(indCode == "01")
		document.forms[0].submit_to.value = "eng-bb";
	else if(indCode == "02")
		document.forms[0].submit_to.value = "inq-bb";
	else if(indCode == "03")
		document.forms[0].submit_to.value = "ass-bb";
	else if(indCode == "04")
		document.forms[0].submit_to.value = "it-bb";
	else if(indCode == "05")
		document.forms[0].submit_to.value = "eng-apt";
	else
		document.forms[0].submit_to.value = "no-bb";
	//alert(document.forms[0].submit_to.value);
	document.forms[0].country.value = document.forms[0].CountryList[indSel].text;
	//alert(document.forms[0].country.value);	
}	

/////////////////////////////////////////////
//          jscal functions                //
/////////////////////////////////////////////

// validate dates and set number of nights 
function setNumNights(cal) {
	var diff = 0.0;
	if(document.getElementById("to").value == "")
	{
		if(document.getElementById("from").value == "")
			return;
		// if calendar is from date and to date not yet set, set it to from date + 1 day	
		if(cal.params.inputField == document.getElementById("from")) 
		{	
			var toDate = new Date(cal.date.getTime() + Date.DAY);
			document.getElementById("to").value = toDate.print("%d/%m/%Y");
		}
	}
	//else both dates set, validate	
	dateComps = fromField.value.split("/");
	fromDate = new Date(dateComps[2], dateComps[1]-1, dateComps[0],0,0,0,0);
	dateComps = toField.value.split("/");
	toDate = new Date(dateComps[2], dateComps[1]-1, dateComps[0],0,0,0,0);
	diff = toDate.getTime()-fromDate.getTime();
	if(diff <= 0)
	{
		if(theLang=="english")	
			alert("Attention: The date you have entered is invalid. Please check the dates specified.");
		else if(theLang == "italiano")
			alert("Attenzione! La data che avete inserito è sbagliata. Per favore verificatela.");
		else if(theLang == "espanol")
			alert("Atención: La fecha que ha introducido no es válido. Por favor, comprueba las fechas indicadas.");
		else if(theLang == "francais")
			alert("Attention! La date que vous avez inserée est erronée. Veuillez la vérifier s'il vous plaît.");
		else if(theLang == "svensk")
			alert("Attention: The date you have entered is invalid. Please check the dates specified.");
		numNightsField.value = "Error";
		return;
	}
	diff = diff / 1000 / 60 / 60 / 24;
	numNightsField.value = Math.round(diff);
}
// disable dates in the past
function dateStatusHandler(date, y, m, d) {
	var time = date.getTime();
	var today = new Date();
	if (time < today.getTime()-Date.DAY)
		return true;
	else
		return false;	
}


