var destinationId	= 'ss';
var ci_day			= 'checkin_monthday';
var ci_month_year	= 'checkin_year_month';
var co_day			= 'checkout_monthday';
var co_month_year	= 'checkout_year_month';
var avail_check	= 'do_availability_check';

var calendar		= new Object();


function getParentOrSelf( contextElm, nodeName )
{
	nodeName = nodeName.toLowerCase();
	while(contextElm.nodeName.toLowerCase() != nodeName && contextElm.parentNode)
		contextElm = contextElm.parentNode;
	return contextElm;
}

function getChildImage( contextElm )
{
	contextElm = contextElm.firstChild;
	while(contextElm.nodeName.toLowerCase() != 'img' && contextElm.nextSibling)
		contextElm = contextElm.nextSibling;
	return contextElm;
}

function checkDateOrder(me)
{
	if (document.getElementById)
	{
		var frm = getParentOrSelf(me, 'form');

		var my = frm[ci_month_year].value.split("-");
		var ci = new Date (my[0], my[1]-1, frm[ci_day].value, 12, 0, 0, 0);

		my = frm[co_month_year].value.split("-");
		var co = new Date (my[0], my[1]-1, frm[co_day].value, 12, 0, 0, 0);

		if (ci >= co)
		{
			co.setTime(ci.getTime() + 1000 * 60 * 60 * 24);
			frm[co_day].value =  co.getDate();
			var com = co.getMonth()+1;
			frm[co_month_year].value = co.getFullYear() + "-" + com;
		}
	}
}


function tickCheckBox(el)
{
	if (document.getElementById)
	{
		if (document.getElementById(el))
			document.getElementById(el).checked=true;
	}
	return true;
}


function updateDaySelect( me )
{
	//if(!days3) return;
	var frm = getParentOrSelf(me, 'form');

	if(!frm[ci_day] || !frm[co_day] || !frm[ci_month_year] || !frm[co_month_year])
    return;

	var ci_d = frm[ci_day];
	var co_d = frm[co_day];
	var ci_my = frm[ci_month_year].value.split("-");
	var co_my = frm[co_month_year].value.split("-");

	var ci_sel = ci_d.selectedIndex;
	var co_sel = co_d.selectedIndex;

	var monthDays = [], opt;

	// Checkin month
	monthDays = buildDaysForMonth(ci_my[0], ci_my[1]);
	ci_d.innerHTML = '';
	for(var i = 0; i < monthDays.length; i++) {
		opt = document.createElement('option');
		opt.innerHTML = (monthDays[i]);
//		opt.innerHTML = (monthDays[i] + ' ' + (i+1));
		opt.value = (i+1);
		ci_d.appendChild(opt);
	}
	ci_d.options[ci_sel].defaultSelected = ci_d.options[ci_sel].selected = true;

	// Checkout month
	monthDays = buildDaysForMonth(co_my[0], co_my[1]);
	co_d.innerHTML = '';
	for(var i = 0; i < monthDays.length; i++) {
		opt = document.createElement('option');
		opt.innerHTML = (monthDays[i]);
//		opt.innerHTML = (monthDays[i] + ' ' + (i+1));
		opt.value = (i+1);
		co_d.appendChild(opt);
	}
	co_d.options[co_sel].defaultSelected = co_d.options[co_sel].selected = true;
}


function buildDaysForMonth( year, month )
{
	var monthDate = new Date(year, month-1);
	var orgMonth = monthDate.getMonth();
	var dayArray = [], weekDay;
	var i=1;
	while(monthDate.getMonth() == orgMonth)
	{
		weekDay = (monthDate.getDay() == 0) ? 6 : (monthDate.getDay()-1);
		//dayArray.push(days3[weekDay]);
		dayArray.push(i++);
		monthDate.setDate(monthDate.getDate()+1);
	}
	return dayArray;
}

function showCalendar(me, calId, dt)
{
	getDimensions(me);
	if (document.getElementById)
	{
		var c = document.getElementById(calId); // elemento che conterrà il calendario
		var i = getChildImage(me); // elemento che contiene il link che apre il calendario (icona calendario)
		var f = getParentOrSelf(me, 'form');
		calendar.cal = c; // calendar è una var globale
		calendar.caldt = dt;
		calendar.calf = f;
		var my = f[(dt=='in'?ci_month_year:co_month_year)].value.split("-");
		year=my[0];
		month=my[1];
		day=f[(dt=='in'?ci_day:co_day)].value;
		buildCal(year,month,day);
		var callerBox = getDimensions(i); // dimensioni dell'elemento che chiama il calendario
		var left = callerBox.x;	// x: la stessa dell'elemento che chiama il calendario
		var top = (callerBox.y + i.offsetHeight); // y: la stessa dell'elemento che chiama il calendario, più la sua dimensione verticale
		c.style.left = left+'px';
		c.style.top = top+'px';
		c.style.display="block";
	}
}

function getDimensions( elm )
{
	var box = { x:0, y:0, w:0, h:0 };
	if(document.getBoxObjectFor)
	{
		var boxRef = document.getBoxObjectFor(elm);
		box.x = boxRef.x;
		box.y = boxRef.y;
		box.w = boxRef.width;
		box.h = boxRef.height;
	}
	else if(elm.getBoundingClientRect)
	{
		var rxIE50 = /MSIE 5\.0/g;
		//alert(rxIE50 + '.test("' + navigator.appVersion + '" = ' + rxIE50.test(navigator.appVersion));
		var boxRef = elm.getBoundingClientRect();
		box.x = boxRef.left;
		box.y = boxRef.top;
		box.w = (boxRef.right - boxRef.left);
		box.h = (boxRef.bottom - boxRef.top);
		//var s='';for(p in boxRef) s+=p+'    '; alert(s);
		// Damn IE...
		if(document.compatMode && document.compatMode != 'BackCompat') {
			// IE6/compliance mode
			box.x += document.documentElement.scrollLeft - 2;
			box.y += document.documentElement.scrollTop - 2;
		}
		else /*if(!gClientIsIE5)*/ {
			// IE5.5
			box.x += document.body.scrollLeft - 2;
			box.y += document.body.scrollTop - 2;
		}
	}
	else
	{
		// No known box information available, walking
		// manually through offsetParents to calculate x/y coordinates
		box.w = elm.offsetWidth;
		box.h = elm.offsetHeight;
		while(elm) {
			box.x += elm.offsetLeft;
			box.y += elm.offsetTop;
			if(elm.offsetParent) // Required for Safari 1.3 :(
				elm = elm.offsetParent;
			else
				break;
		}
	}
	var cc;
	if(cc = document.getElementById('bodyconstraint'))
		box.x -= cc.offsetLeft;
	return box;
}

function getRelativeDimension( elm, contId )
{
	var box = { x:0, y:0, w:0, h:0 };
	box.w = elm.offsetWidth;
	box.h = elm.offsetHeight;

//	Loop che cicla risalendo sul padre di ogni elemento, fino al body (o all'id specificato)
//	sommando via via le coordinate dell'elemento rispetto al padre
	while( elm && ( elm.id!=contId || contId=='' ) )
//	while( elm )
	{
		box.x += elm.offsetLeft;
		box.y += elm.offsetTop;
//		alert( "id:" + elm.id + ", position:" + elm.style.display + ", parent:" + elm.offsetParent + ', x: ' + box.x + ', y: ' + box.y  )
		if(elm.offsetParent) // Required for Safari 1.3 :(
			elm = elm.offsetParent;
		else
			break;
	}
	var cc;
	if(cc = document.getElementById('bodyconstraint'))
		box.x -= cc.offsetLeft;
	return box;
}

function buildCal(y,m,d)
{
	var daysInMonth=[31,0,31,30,31,30,31,31,30,31,30,31];
	td=new Date();
	if (!y)
		y = td.getFullYear();
	if (!m)
		m = td.getMonth()+1;
	if (!d)
		d = td.getDate;
	var dt = calendar.caldt;

	var mDate = new Date(y, m-1, 1);
	var firstMonthDay = mDate.getDay();
	daysInMonth[1]=(((mDate.getFullYear()%100!=0)
	&&(mDate.getFullYear()%4==0)) || (mDate.getFullYear()%400==0))?29:28;

//	head
	var t='<table class="caltable" cellspacing="0"><tr>';
	t+='<td class="header" class="monthYear">';
	if (y==td.getFullYear() && m==td.getMonth()+1)
		t+='<img class="calNoPrevMonth" src="' + imgDir + '/blank.gif" width="24" height="24" alt="'+tr.prevMonth+'">';
	else
		t+='<a class="calPrevMonth" href="" onclick="prevMonth('+y+','+m+');	return false;" title="'+tr.prevMonth+'"><img src="' + imgDir + '/arrow-previous.png" width="24" height="24" alt="'+tr.prevMonth+'"></a>';

//	months selectbox

//	t+='&nbsp;<select name="ym" onchange="goYearMonth(this.options[this.selectedIndex].value)">';
	var mn=td.getMonth()+1;var yr=td.getFullYear();
	var last_month=0;
	for(n=0;n<=9;n++)
	{
		//t+='<option value="' + yr + '-' + mn + '"';
		if (mn == m && yr == y)
		{
			//t+=' selected="selected"';
			last_month=1;
		}
		else
			last_month=0;
		//t+='>' + months[mn-1] + ' ' + yr +'</option>';
		mn++; if (mn>12) { mn=1;yr++ }
	}
	//t+= ' </select>&nbsp;';

	t+='</td><td class="header" colspan="5" class="monthYear">'+ months[m-1] + ' ' + y + '</td><td class="header">';
	if (last_month==1)
		t+='<img class="calNoNextMonth" src="' + imgDir + '/blank.gif" width="24" height="24" alt="' + tr.nextMonth + '">';
	else
		t+='<a class="calNextMonth" href="" onclick="nextMonth('+y+','+m+'); return false;" title="' + tr.nextMonth +'"><img src="' + imgDir + '/arrow-next.png" width="24" height="24" alt="' + tr.nextMonth + '"></a>';
	t+='</td></tr>';

//	nomi giorni
	t+='<tr class="dayNames">';
	for(dn=0;dn<7;dn++)
	{
		var cl = '';
		if ((dn%7==5) || (dn%7 == 6))
			cl += ' weekend';
		t+='<td class="'+cl+'">'+days[dn]+'</td>';
	}
	t+='</tr><tr class="days">';

//	giorni
	for(i=1;i<=42;i++)
	{
		var x = i - (firstMonthDay+6)%7;
		if (x > daysInMonth[m-1] || x <1)
			x = '&nbsp;';
		var cl = '';
		var href = 0;
		if ((i%7==0) || (i%7 == 6))
			cl += ' weekend';
		if (x>0)
		{
			var xDay = new Date(y, m-1, x);
			if ((xDay.getFullYear() == y) && (xDay.getMonth()+1 == m)&& (xDay.getDate() == d))
			{
				cl += ' selected';
				href=1;
			}
			if ((xDay.getFullYear() == td.getFullYear())	&& (xDay.getMonth() == td.getMonth())	&& (xDay.getDate() == td.getDate()))
			{
				cl += ' today';
				href=1;
			}
			else
			{
				if (xDay > td)
				{
					cl += ' future';
					href=1;
				}
				else
				{
					if (xDay < td)
					{
						cl += ' past';
					}
				}
			}
		};
		t+='<td class="'+cl+'" width="25" height="25" align="center" valign="middle">';
		if (href)
		{
			t+='<a href="#" onclick="setCalendarDate('+y+','+m+','+x+',\''+dt+'\'); return false;">'+x+'</a>';
		}
		else
		{
			t+=x;
		}
		t+='</td>';
		if(((i)%7==0)&&(i<36))
		{
			t+='</tr><tr class="days">';
		}
	}
	t+='</tr><tr><td colspan="7" class="footer"><a href="#" onclick="hideCalendar();return false;">' + tr.closeCalendar + '</a></td></tr></table>';
	document.getElementById("calendar").innerHTML= t;
}

function prevMonth(y,m) {
    if (new Date(y,m-1,1) < td) return;
    if (m > 1) {m--} else {m = 12; y--};
    buildCal(y,m);
}

//does this finction need to check for max month/year?
function nextMonth(y,m) {
    if (m<12){m++;} else {m=1;y++;}
    buildCal(y,m);
}

function goYearMonth(ym){
	var ymlist = ym.split("-");
    buildCal(ymlist[0],ymlist[1]);
}

function setCalendarDate(year,month,day,inout)
{
	var f = calendar.calf;
	var dt = calendar.caldt;
	f[(inout=='in'?ci_month_year:co_month_year)].value = year + "-"  + month;
	f[(inout=='in'?ci_day:co_day)].value = day;
	tickCheckBox(avail_check);
	if (inout == "in")
		checkDateOrder(f, ci_day, ci_month_year, co_day, co_month_year);
	hideCalendar();
	updateDaySelect(f);
}

function hideCalendar() {
    calendar.cal.style.display='none';
}

function updateRate(amountId,ratesId,resultId)
{
	var amount	= parseFloat( document.getElementById(amountId).value.toString().replace(',','.') );
	if ( isNaN(amount) )
		amount = 0;
	var rate		= parseFloat( document.getElementById(ratesId).options[document.getElementById(ratesId).selectedIndex].value );
	
	document.getElementById(resultId).innerHTML = truncateFloat(rate*amount);
}

function truncateFloat(num) 
{
	string = "" + num;
	if (string.indexOf('.') == -1)
		return string + '.00';
	seperation = string.length - string.indexOf('.');
	if (seperation > 3)
		return string.substring(0,string.length-seperation+3);
	else if (seperation == 2)
		return string + '0';
	return string;
}

function showCurrencyConverter(selectedItemId,curencyConverterId,hotelItemClass)
{
	var	selectedItem		= document.getElementById(selectedItemId);
	var	curencyConverter	= document.getElementById(curencyConverterId);
	
	if ( selectedItem && curencyConverter )
	{
		var hotelItems = $$('.'+hotelItemClass);
		
		if ( hotelItems )
			for ( i=0; i<hotelItems.lenght; i++ )
				hotelItems[i].removeChild(curencyConverter);
		
		selectedItem.appendChild(curencyConverter);
		showElement(curencyConverterId);
	}
}

function checkFormList(listId,errorMsg)
{
	if ( document.getElementById(listId).selectedIndex > 0 )
		return true;
	else
	{
		alert(errorMsg);
		return false;
	}
}

function checkFormInput(inputId,errorMsg)
{
	if ( document.getElementById(inputId).value!='' )
		return true;
	else
	{
		alert(errorMsg);
		return false;
	}
}