// 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";
	document.images['top_foto'].src = path;
	
	setSelButton(which,level,theLang);
}
// set the photo at the top right and set the selected menu button
function initSubPage(which,level)
{
	document.images[which].src = buildPath("arrow",level,"common",null);
}

// set the selected button
function setSelButton(which, 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;
	setButton(which, level, lang, "on");
}
// show mouseoff
function turnOff(which, level, lang)
{
	
	if(isSel(which))
		return;
	setButton(which, level, lang, "off");
}
// set a button to the proper state
function setButton(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(lang) 
{
	str = setSelRefs();
	if(str.length == 0)
	{
		if(lang == "eng")
			return(showWarning("No accommodations selected"));
		else if (lang == "it")
			return(showWarningIt("Nessun alloggio selezionato"));
		else if (lang == "es")
			return(showWarningEs("No se ha seleccionado ningún tipo de alojamiento"));
		else if (lang == "svensk")
			return(showWarningSv("Inget boende har valts"));
		else
			return(showWarningFr("Aucun hébergement n'a été sélectionné"));
				
	}
	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;
	
 	var arrStr = str.split(',');
	
 	for(i=0;i<arrStr.length;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
	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 == "espanol")
			alert("Se ruega introducir el propio nombre.");
		else if(lang == "francais")
			alert("Insérez votre nom et prénom, merci.");
		else if(lang == "svensk")
			alert("Var vänlig och skriv ditt fullständiga namn.");
		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 == "espanol")
			alert("Se ruega introducir el propio email.");
		else if(lang == "francais")
			alert("Insérez votre email, merci.");	
		else if(lang == "svensk")
			alert("Var vänlig och skriv din emailadress.");
		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 == "espanol")
				alert("Se ruega seleccionar un país.");
			else if(lang == "francais")
				alert("Préciser le pays d'origine, merci.");
			else if(lang == "svensk")
				alert("Var vänlig välj land.");

			theForm.CountryList.focus();
			return(false);
		}
	}	
	
	return(true);	
}
// warning in english for no selected properties
function showWarning(title)
{
  var msg = "";
  msg = msg + "No accommodations were selected\n\n";
  msg = msg + "If you are interested in a particular accommodation, 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)
{
  var msg = "";
  msg = msg + "Nessun alloggio č stato selezionato\n\n";
  msg = msg + "Se vi interessa una sistemazione 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)
{
  
  var msg = "";
  msg = msg + "Aucun hébergement n'a été sélectionné\n\n";

  msg = msg + "Si vous etes intéressé ŕ un hébergement 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));

}
// warning in swedish for no selected properties
function showWarningSv(title)
{
  var msg = "";
  msg = msg + "Inget boende har valts\n\n";
  msg = msg + "Om du är intresserad av ett speciellt boende tryck \"Cancel\" för att ĺtervända till listan där du väljer det alternativ du är interesserad av genom att makera rutan brevid det aktuella referensnumret. ";
  msg = msg + "Du kan även välja att göra en allmän förfrĺgan. I sĺ fall tryck \"OK\".";
  
  return(confirm(msg));

}
// warning in swedish for no selected properties
function showWarningEs(title)
{
  var msg = "";
  msg = msg + "No se ha seleccionado ningún tipo de alojamiento\n\n";
  msg = msg + "Si estáis interesados en algún tipo de alojamiento, pinchad Anula para volver a la lista y seleccionar la casilla correspondiente al número de referencia\n\n";
  msg = msg + "O bien, podéis seguir y pinchar OK para pedir informaciones de carácter general.";
  
  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('indr" 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 getMid()
{
	return('quiry' + getSep() + 'b-');
}

function getLink()
{
	return('terbb' + getSep() + 'b-');
}

function getSep()
{
	x = 23;
	y = 40;
	return("&#" + eval("x + y + 1"))
}

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 == 'english')
		msg = "message";
	else if(lang == 'italiano')
		msg = "messaggio";
	else if(lang == 'francais')
		msg = "mail";
	else if(lang == 'espanol')
		msg = "e-mail";
	else if(lang == 'svensk')
		msg = "meddelande";
		
	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 doConGen()
{
	document.write('<a hre');
	document.write('f="mai');
	document.write('lto:inqu');
	document.write(getCon(1));
	document.write('m.it"><i');
	document.write('mg src=".');
	document.write('./images/co');
	document.write('mmon/posta');
	document.write('-generale.');
	document.write('gif" widt');
	document.write('h="211" hei');
	document.write('ght="15" bor');
	document.write('der="0"></a>');
}
function doConBB()
{
	document.write('<a ');
	document.write('hre');
	document.write('f="ma');
	document.write('ilto:b');
	document.write('b.accomm');
	document.write(getCon(2));
	document.write('-b.rm.it"><');
	document.write('img src');
	document.write('="../ima');
	document.write('ges/comm');
	document.write('on/posta-b');
	document.write('b.gif" wid');
	document.write('th="211" hei');
	document.write('ght="15" bor');
	document.write('der="0');
	document.write('"></a>');
}

function doConApt()
{
	document.write('<a hre');
	document.write('f="mai');
	document.write('lto:apa');
	document.write(getCon(3));
	document.write('-b.rm.i');
	document.write('t"><img s');
	document.write('rc="../im');
	document.write('ages/com');
	document.write('mon/post');
	document.write('a-apt.gif');
	document.write('" width="2');
	document.write('11" heigh');
	document.write('t="15" bor');
	document.write('der="0"><');
	document.write('/a>');
}
function doConFeed()
{
	document.write('<a h');
	document.write('ref="ma');
	document.write('ilto:f.ala');
	document.write(getCon(4));
	document.write('m.it"><im');
	document.write('g src="../i');
	document.write('mages/comm');
	document.write('on/posta-f');
	document.write('eedback.gi');
	document.write('f" width="2');
	document.write('11" height="1');
	document.write('5" border="0');
	document.write('"></a>');
}

function doConWeb()
{
	document.write('<a h');
	document.write('re');
	document.write('f="mai');
	document.write('lto:we');
	document.write('bmasterb');
	document.write(getCon(5));
	document.write('m.it"><im');
	document.write('g src="../im');
	document.write('ages/common/p');
	document.write('osta-webma');
	document.write('ster.gif" wid');
	document.write('th="211" heigh');
	document.write('t="15" borde');
	document.write('r="0"></a>');
}

function doConItal()
{
	document.write('<a hre');
	document.write('f="m');
	document.write('ailto:pr');
	document.write('enotaz');
	document.write(getCon(6));
	document.write('b.rm.i');
	document.write('t"><im');
	document.write('g src="../');
	document.write('images/co');
	document.write('mmon/post');
	document.write('a-prenot');
	document.write('e.gif" wid');
	document.write('th="211" he');
	document.write('ight="15" bo');
	document.write('rder="0"></a>');
}

function doConFr()
{
	document.write('<a');
	document.write(' href="m');
	document.write('ailt');
	document.write('o:logem');
	document.write(getCon(7));
	document.write('m.it"><img s');
	document.write('rc="../image');
	document.write('s/common/posta-');
	document.write('francese.gi');
	document.write('f" width="21');
	document.write('1" height="1');
	document.write('5" border="0');
	document.write('"></a>');
}
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 if(indCode == "06")
		document.forms[0].submit_to.value = "fr-apt2";
	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);	
}	



// JavaScript Document
function calcSconto(sconto, percentuale, days, idx)
{
	
	if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
	{
		prezzo = document.forms["prenota"].elements["PrezzoUApplicato[]"][idx].value;
		// set opposite field to zero (only one; maggiorazione or sconto)
		if(sconto < 0)
			// maggiorazione
			document.forms["prenota"].elements["Sconto[]"][idx].value = 0;
		else
			// sconto
			document.forms["prenota"].elements["Maggiorazione[]"][idx].value = 0;
	} else {
		prezzo = document.forms["prenota"].elements["PrezzoUApplicato[]"].value;
		// set opposite field to zero (only one; maggiorazione or sconto)
		if(sconto < 0)
			// maggiorazione
			document.forms["prenota"].elements["Sconto[]"].value = 0;
		else
			// sconto
			document.forms["prenota"].elements["Maggiorazione[]"].value = 0;

	}
	prezzo = prezzo - (prezzo*sconto/100);
	calcTotale(prezzo, percentuale, days, idx);


}

function calcTotale(prezzo, percentuale, days, idx)
{
	
	if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
	{
		document.forms["prenota"].elements["PrezzoUApplicato[]"][idx].value = formatCurrency(prezzo);
		document.forms["prenota"].elements["SocietaUApplicato[]"][idx].value = formatCurrency(prezzo*percentuale/100);
		document.forms["prenota"].elements["propApplicato[]"][idx].value = formatCurrency(prezzo - (prezzo*percentuale/100));
		document.forms["prenota"].elements["Prezzo[]"][idx].value = formatCurrency(document.forms["prenota"].elements["PrezzoUApplicato[]"][idx].value * days);
		document.forms["prenota"].elements["Societa[]"][idx].value = formatCurrency(document.forms["prenota"].elements["SocietaUApplicato[]"][idx].value * days);
		document.forms["prenota"].elements["prop[]"][idx].value = formatCurrency(document.forms["prenota"].elements["propApplicato[]"][idx].value * days);
	}
	else
	{
		document.forms["prenota"].elements["PrezzoUApplicato[]"].value = formatCurrency(prezzo);
		document.forms["prenota"].elements["SocietaUApplicato[]"].value = formatCurrency(prezzo*percentuale/100);
		document.forms["prenota"].elements["propApplicato[]"].value = formatCurrency(prezzo - (prezzo*percentuale/100));
		document.forms["prenota"].elements["Prezzo[]"].value = formatCurrency(document.forms["prenota"].elements["PrezzoUApplicato[]"].value * days);
		document.forms["prenota"].elements["Societa[]"].value = formatCurrency(document.forms["prenota"].elements["SocietaUApplicato[]"].value * days);
		document.forms["prenota"].elements["prop[]"].value = formatCurrency(document.forms["prenota"].elements["propApplicato[]"].value * days);
	}

}

function calcPerDay(prezzo, percentuale, days, idx)
{
	
	if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
	{
		document.forms["prenota"].elements["Prezzo[]"][idx].value = formatCurrency(prezzo);
		document.forms["prenota"].elements["Societa[]"][idx].value = formatCurrency(prezzo*percentuale/100);
		document.forms["prenota"].elements["prop[]"][idx].value = formatCurrency(prezzo - (prezzo*percentuale/100));

		document.forms["prenota"].elements["PrezzoUApplicato[]"][idx].value = formatCurrency(document.forms["prenota"].elements["Prezzo[]"][idx].value / days);
		document.forms["prenota"].elements["SocietaUApplicato[]"][idx].value = formatCurrency(document.forms["prenota"].elements["Societa[]"][idx].value / days);
		document.forms["prenota"].elements["propApplicato[]"][idx].value = formatCurrency(document.forms["prenota"].elements["prop[]"][idx].value / days);
	}
	else
	{
		document.forms["prenota"].elements["Prezzo[]"].value = formatCurrency(prezzo);
		document.forms["prenota"].elements["Societa[]"].value = formatCurrency(prezzo*percentuale/100);
		document.forms["prenota"].elements["prop[]"].value = formatCurrency(prezzo - (prezzo*percentuale/100));

		document.forms["prenota"].elements["PrezzoUApplicato[]"].value = formatCurrency(document.forms["prenota"].elements["Prezzo[]"].value / days);
		document.forms["prenota"].elements["SocietaUApplicato[]"].value = formatCurrency(document.forms["prenota"].elements["Societa[]"].value / days);
		document.forms["prenota"].elements["propApplicato[]"].value = formatCurrency(document.forms["prenota"].elements["prop[]"].value / days);
	}

}

function calcSoc(soc, days, idx)
{
	if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
	{
		document.forms["prenota"].elements["propApplicato[]"][idx].value = formatCurrency(document.forms["prenota"].elements["PrezzoUApplicato[]"][idx].value - soc);
		document.forms["prenota"].elements["Societa[]"][idx].value = formatCurrency(document.forms["prenota"].elements["SocietaUApplicato[]"][idx].value * days);
		document.forms["prenota"].elements["prop[]"][idx].value = formatCurrency(document.forms["prenota"].elements["propApplicato[]"][idx].value * days);
	}
	else
	{
		document.forms["prenota"].elements["propApplicato[]"].value = formatCurrency(document.forms["prenota"].elements["PrezzoUApplicato[]"].value - soc);
		document.forms["prenota"].elements["Societa[]"].value = formatCurrency(document.forms["prenota"].elements["SocietaUApplicato[]"].value * days);
		document.forms["prenota"].elements["prop[]"].value = formatCurrency(document.forms["prenota"].elements["propApplicato[]"].value * days);
	}

}

function calcSocPerDay(soc, days, idx)
{
	if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
	{
		document.forms["prenota"].elements["prop[]"][idx].value = formatCurrency(document.forms["prenota"].elements["Prezzo[]"][idx].value - soc);
		document.forms["prenota"].elements["Societa[]"][idx].value = formatCurrency(soc);
		document.forms["prenota"].elements["SocietaUApplicato[]"][idx].value = formatCurrency(soc / days);
		document.forms["prenota"].elements["propApplicato[]"][idx].value = formatCurrency(document.forms["prenota"].elements["prop[]"][idx].value / days);
	}
	else
	{
		document.forms["prenota"].elements["prop[]"].value = formatCurrency(document.forms["prenota"].elements["Prezzo[]"].value - soc);
		document.forms["prenota"].elements["Societa[]"].value = formatCurrency(soc);
		document.forms["prenota"].elements["SocietaUApplicato[]"].value = formatCurrency(soc / days);
		document.forms["prenota"].elements["propApplicato[]"].value = formatCurrency(document.forms["prenota"].elements["prop[]"].value / days);
	}

}

function calcPostiLetto(posti, percentuale, days, idx)
{
	if(eval("document.forms['prenota'].elements['posti_" + idx + "_" + posti + "']") != null)
	{
		var prezzo = eval("document.forms['prenota'].elements['posti_" + idx + "_" + posti + "'].value");
		calcTotale(prezzo, percentuale, days, idx)
	}
	else
	{
		alert("Non sono disponibili " + posti + " postiletto.");
		//alert("document.forms['prenota'].elements['posti_" + idx + "_" + posti + "']");
		if(document.forms["prenota"].elements["Prezzo[]"].length > 1)
		{
			posti = document.forms["prenota"].elements["origposti[]"][idx].value;
			document.forms["prenota"].elements["Ospiti[]"][idx].value = posti;
		}
		else
		{
			posti = document.forms["prenota"].elements["origposti[]"].value;
			document.forms["prenota"].elements["Ospiti[]"].value = posti;

		}
		calcPostiLetto(posti, percentuale, days, idx);
	}
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	//for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		//dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
}

function numbersonly(myfield, e)
{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
   		return true;
	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
	   return true;
	else
   		return false;
}

function vaiRif(tipo)
{
	sel = document.forms[0].perRif;
	id = sel.options[sel.selectedIndex].value;
	mod = (document.forms[0].mod?document.forms[0].mod.value:"");
	tipo = (document.forms[0].tipo?document.forms[0].tipo.value:"");
	location.href = "dettagli.php?id=" + id + "&mod=" + mod + "&tipo=" + tipo;

}
function vaiCommenti()
{
	sel = document.forms[0].perRif;
	id = sel.options[sel.selectedIndex].value;
	location.href = "commenti.php?idBB=" + id;

}

function vaiNonDisp(tipo)
{
	sel = document.forms[0].perRif;

	id = sel.options[sel.selectedIndex].value;
	location.href = "stampe.php?s=nondisp&id=" + id + "&tipo=" + tipo;

}

// date validation
function isLeap (y) {
	return (((y%4==0) && ((!(y%100==0)) || (y%400==0))) ? true : false );
}

function daysInMonth (m,y) {
	mArr = new Array (31,28,31,30,31,30,31,31,30,31,30,31);
	return (m==2 && isLeap(y)) ? 29 : mArr[m-1];
}

function fixYear (y) {
	return (y <= 10 ) ? y + 2000 : (y < 100) ? y + 1900 : y;
}

function validDMY (d,m,y) {
	return  (y < 1650 || m < 0 || m > 12 || d < 0 || d > daysInMonth(m,y)) ? false : true;
}

function checkDate (f,nullOK) {
if (nullOK && f.value=='')
    return true;
else {
    var RE = /(\d{1,2})\W(\d{1,2})\W(\d{2,4})/.exec(f.value);
    if (RE) {
        if (validDMY(RE[1]*1, RE[2]*1, fixYear(RE[3]*1))) {
            //f.value = RE[1]*1 + "/" + RE[2]*1 + "/" + fixYear(RE[3]*1);
            return true;
            }
        else {
            setTimeout ('document.' + f.form.name + '.' + f.name + '.focus()',100);
            setTimeout ('window.alert (\'Data non valida. Si prega di inserire la data nel formato dd/mm/yyyy.\')', 100);
            return false;
            }
        }
    else {
        setTimeout ('document.' + f.form.name + '.' + f.name + '.focus()',100);
            setTimeout ('window.alert (\'Data non valida. Si prega di inserire la data nel formato dd/mm/yyyy.\')', 100);
        return false;
        }
    }
}

/////////////////////////////////////////////
//          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("OBS: Det datum som uppgivits är inte korrekt. Vänligen kontrollera att du angivit rätt datum.");
		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;	
}

