//CALENDAR
var n=navigator,B=(n.userAgent+n.appName).toLowerCase(),V=parseInt(n.appVersion);
var N4=(B.indexOf("netscape")!=-1&&V==4),IE=(B.indexOf("microsoft")!=-1);

var calForm,dropDay1,dropMonth1,dropDay2,dropMonth2,currButtonNo,initDay,initMonth,initYear,endDay,endMonth,numMonths,bPressed,calendar,g_endDate;

var calWidth=142;
var calHeight=182;
var calendarHTML="";
var monthNames=new Array("x","x","x","x","x","x","x","x","x","x","x","x");//placeholders

if(!N4)document.onmouseup=function(e){
	//alert('DEBUG:TRYING TO HIDE THE CALENDAR ' +e);
	calendar.hide();
	if(bPressed){
		bPressed=false;
		//alert('DEBUG:CALENDAR REMOVED');
		showCalendar(e);}
		//alert('DEBUG:CALENDAR APPEAR');
}

function startUpCalendar(stDate,endDate,formName,dd1,dm1,dd2,dm2,sync,syncCal){
	if(N4)return;

//Following line commented out due to clash with touch clarity logging scripts - Shiraz	
//if(!document.all)document.all=document.getElementsByTagName("*");
	calForm=document.forms[formName];
	
	dropDay1=calForm[dd1];
	dropMonth1=calForm[dm1];
	
	dropDay2=calForm[dd2];
	dropMonth2=calForm[dm2];

	calendar=new LayerFrame('cIframe');
	stPos=currpos=0;
	
	todayDate = new Date();
	todayDate = todayDate.getDate()+'/'+(todayDate.getMonth()+1)+'/'+todayDate.getFullYear();
	initDate = todayDate.split('/');
	initDay=initDate[0]*1;
	initMonth=initDate[1]*1;
	initYear=initDate[2];
  // Setup popup calendar date params
  if (syncCal!=false){
    // If calendar is to sync with dropdowns
    calDay=initDay=initDate[0]*1;
    calMonth=initMonth=initDate[1]*1;
    calYear=initYear=initDate[2];
  } else {
    // If calendar is not to sync with dropdowns
    //(e.g. if pre-pop date is in the future but we still want current dates to be available.)
    d=new Date()
    calDay=d.getDate();
    calMonth=d.getMonth()+1;
    calYear=d.getFullYear();
  }

	g_endDate = endDate;
	endDate=endDate.split('/');
	endDay=endDate[0]*1,endMonth=endDate[1]*1,endYear=endDate[2];
	
	/* not in use - not reliable
	if(endMonth>initMonth)numMonths=endMonth-initMonth+1;
	else numMonths=(12-initMonth)+endMonth+1;
	//if(endMonth==initMonth)numMonths=1;
	*/
	
	// get the real number of months
	numMonths = 12*(endYear-initYear);
	numMonths = (endMonth < initMonth) ? numMonths - (initMonth - endMonth) : numMonths + (endMonth - initMonth);
	numMonths++;
	
  if (sync!=false){
  	if(dropMonth1) if(dropDay1.options[0].value!="0")setDropdowns(initDay,initMonth,1);
	  if(dropMonth2){setDropdowns(initDay,initMonth,2);currButtonNo=1;syncDropdowns();}
  }

	_13_months_fix();
}

function setCalendar(buttonNo){
	bPressed=true;
	currButtonNo=buttonNo;
	var ops=eval('dropMonth'+buttonNo);
	//alert(ops.selectedIndex);
	for(i=0;i<ops.length;i++){
		var opVal=ops.options[i].value;
		monthNames[opVal]=ops.options[i].text;
	}
	var currMonth=getChronMonth(eval('dropMonth'+buttonNo).value*1);
	currpos=calHeight*currMonth;
  if (calendarHREF.indexOf('?') > -1)  queryStart = '&';
  else queryStart = '?';
//	cIframe.document.write(calendarHTML);
  if (buttonNo=='2') selectedDates = '&selDay=' + dropDay1.options[dropDay1.selectedIndex].value + '&selMonth=' + dropMonth1.options[dropMonth1.selectedIndex].value;
  else selectedDates = '';
  cIframe=parent.frames['cIframe'];
  // This is needed to get around weirdness with end of month dates and calendar start dates which are in the future.
  tempDate = new Date()
  if (initMonth-1>tempDate.getMonth() && ops.selectedIndex!=0){
    addMonth = ops.selectedIndex-1
  } else {
    addMonth = ops.selectedIndex
  }
  cIframe.document.location.href = calendarHREF + queryStart + 'MONTH=' + addMonth + '&cal_period=' + numMonths + '&cal_day=' + calDay + '&cal_month=' + calMonth + '&cal_year=' + calYear + selectedDates + '&endDate=' + g_endDate;
  //alert('DEBUG:PROCESS');
}

function showCalendar(e){
	var button=new posElement((IE)?event.srcElement:e.target);
	posX=button.x;posY=button.y;
	doc_height=document.body.clientHeight+(IE?document.body.scrollTop:0);
	//alert("DEBUG:"+ doc_height + button);
	if(posY>doc_height-calHeight){
		//alert("DEBUG:Case 1");
		calendar.show(posX+36,posY-calHeight+20);
	}
	else{ 
		//alert("DEBUG:Case 2");
		calendar.show(posX+36,posY);
	}
}


function posElement(element)
{
	// get position relative to... 
	this.x=element.offsetLeft;
	this.y=element.offsetTop;
  var pElement=element.offsetParent;
  while(pElement && pElement.id!='master_center')
		{
    this.x+=pElement.offsetLeft;
    this.y+=pElement.offsetTop;
    pElement=pElement.offsetParent;
		}
	if (navigator.appName == 'Netscape' && !N4) this.y += calHeight - 20;
}

function LayerFrame(id){
	this.style=eval(document.getElementById(id)).style;
	this.reset=cReset;
	
	this.show=function(x,y){cReset();this.style.left=x+"px";this.style.top=y+"px";}
			
	this.hide=function(){this.style.top="-2000px";}
	this.next=scrollDown;
	this.previous=scrollUp;
}

function cReset(){
	//cIframe.scroll(0,stPos);currpos=stPos;
	//Modification: Joseph Wilk 29/10/2004@15:50
	//DEPRECIATED: cIframe.scroll(0,0);//keep state
	//This scroll trys to move within the iframe
	//this caused the iframe to scroll to the white space
	//lossing the focus of the calendar
}

function scrollDown(){
	currpos+=calHeight;
	cIframe.scroll(0,currpos);
}

function scrollUp(){
	currpos-=calHeight;
	if(currpos>0)cIframe.scroll(0,currpos);
	else{currpos=stPos;calendar.reset();}
}

function displayDate(dt){
	calendar.hide();

	var DMY=dt.split("/");
	var day=DMY[0];
	var month=DMY[1];

	var curDate = new Date();
	var curM = curDate.getMonth() + 1;
	var curY = curDate.getFullYear();

	var index = getChronMonth(month);

	if(curM==parseInt(month)){
		index = (curY==parseInt(DMY[2])) ? 0 : 12;
	}

	setDropdowns(day,month,currButtonNo,index);
	if(dropDay2)syncDropdowns();
}

function syncDropdowns(){
	var d1=dropDay1.value*1;
	var d2=dropDay2.value*1;
	var m1=dropMonth1.value*1;
	var m2=dropMonth2.value*1;

	m1i = dropMonth1.selectedIndex;
	m2i = dropMonth2.selectedIndex;
	if(m1i>m2i || m1i==m2i && d2<d1){
		if(currButtonNo==1){
			var d_maxIndex = dropDay1.length - 1;
			var m_maxIndex = dropMonth1.length - 1;
			var d_index = dropDay1.selectedIndex + 1;
			var m_index = dropMonth1.selectedIndex;
			
			if(d_index > d_maxIndex){ d_index = 0; m_index++;}
			if(m_index > m_maxIndex){ m_index = m_maxIndex; d_index = d_maxIndex;}
			
			dropDay2.selectedIndex = d_index;
			dropMonth2.selectedIndex = m_index;
		}
		else{
			var d_maxIndex = dropDay2.length - 1;
			var m_maxIndex = dropMonth2.length - 1;
			var d_index = dropDay2.selectedIndex + 1;
			var m_index = dropMonth2.selectedIndex;
			
			if(d_index > d_maxIndex){ d_index = 0; m_index++;}
			if(m_index > m_maxIndex){ m_index = m_maxIndex; d_index = d_maxIndex;}
			
			dropDay1.selectedIndex = d_index;
			dropMonth1.selectedIndex = m_index;
		}
	}
}

//setDrodowns2 - to deal with 13-month dropdowns
function setDropdowns2(d,m_index,btn){
	var el_d = eval("dropDay"+btn);
	var el_m = eval("dropMonth"+btn);
	el_m.selectedIndex = m_index;
	//setDays(btn);
	if(dv) selOptionVal(el_d, d);
	setCheckOut();
}

function setDropdowns(dv,mv,bn,index){
	var drDay=eval("dropDay"+bn);
	var drMonth=eval("dropMonth"+bn);
	selOptionVal2(drMonth,index);
		setDays(bn);
	if(dv) selOptionVal(drDay,dv);
                setCheckOut();
}

/*
 this function is compatible with the 13-month dropdown
*/
function selOptionVal2(ob,index){
	ob.selectedIndex = index;
}

function selOptionVal(ob,val){
	var ops=new Object();
	for(var i=0;i<ob.length;i++)ops[ob[i].value]=ob[i];
	if(ops[val] && ops[val].selected!=true) ops[val].selected=true;
}

function hasOptionVal(ob,val){
	var ops=new Object();
	for(var i=0;i<ob.length;i++)ops[ob[i].value]=ob[i];
	if(ops[val])return true;
	else return false;
}

function getChronMonth(month){
	var cM=month-initMonth;
	return (cM<0)?cM+12:cM;
}

function getCalendarHTML(){
	calendarHTML="";
	var currDate=new Date(Date.UTC(initYear,initMonth-1,initDay));//yyyy/mm from 0/d from 1

	calendarHTML+='<html><head><title>Calendar</title>';
  calendarHTML+='<style type="text/css">\
		body{font-family:Verdana,sans-serif;font-size:13px;}\
		a{text-decoration:none;}\
		a:hover{text-decoration:underline;}\
		td{font-family:Verdana,Helvetica,sans-serif;font-size:10px;text-align:center;color:#cccccc}\
		td a{color:#000000;}\
		b{color:#000000;}\
		.white{color:#FFFFFF;font-weight:bold;}\
		</style></head><body bgcolor="#000000" leftmargin="1" topmargin="1">'

	for(i=1;i<=numMonths;i++){//For each month

		var month=currDate.getMonth()+1;//mm is from 0
		var numDays=getNumDays(month);
		var year=currDate.getYear();if(year<2000)year+=1900;

		currDate.setDate(1);//set to first of the month and get day of the week
		var firstDay=currDate.getDay()-1;//Sun is 0 from getDay() but we run from Mon
		if(firstDay<0)firstDay=6;

	//Compile HTML
		var monthHTML='\
			<table border="0" cellspacing="0" cellpadding="0" height="180" width="140" bgcolor="#FFFFFF">\
			<tr><td height="20" width="15" bgcolor="#E43784">';
		if(i>1)
			monthHTML+='<a href="javascript:top.calendar.previous()"><img src="http://www.lastminute.com/lmn/calendar/images/arrowl.gif" hspace="2" width="15" height="13" border="0"></a>';
		else
			monthHTML+='<img src="http://www.lastminute.com/lmn/calendar/images/trans.gif" width="20" height="13" border="0">';

			monthHTML+='</td><td colspan="5" width="100" bgcolor="#E43784" class="white">'+ monthNames[currDate.getMonth()+1] +
			' ' + year + '</td><td bgcolor="#E43784" width="20">';
			
		if(i<numMonths)
			monthHTML+='<a href="javascript:top.calendar.next()"><img src="http://www.lastminute.com/lmn/calendar/images/arrowr.gif" hspace="2" width="15" height="13" border="0"></a>';
		else
			monthHTML+='<img src="http://www.lastminute.com/lmn/calendar/images/trans.gif" width="15" height="13" border="0">';

			monthHTML+='</td></tr><tr><td height="20" width="20"><b>M</b></td><td width="20"><b>T</b></td><td width="20"><b>W</b></td>\
			<td width="20"><b>T</b></td><td width="20"><b>F</b></td><td width="20"><b>S</b></td><td width="20"><b>S</b></td></tr>';

		for(j=0;j<42;j+=7){//for 6 week slots in month

			monthHTML+='<tr>';

			for(k=1;k<8;k++){//for each day of week

				var slotNo=j+k;
				var countFromFirstDay=slotNo-firstDay;
				var isLink=(slotNo>firstDay)&&(countFromFirstDay<=numDays);
				var preDays=(month==initMonth&&countFromFirstDay<initDay);
				if(currButtonNo==2){
					var M=dropMonth1.value*1,D=dropDay1.value*1;
					var M1=getChronMonth(M),cM=getChronMonth(month);
					preDays=(cM<M1)||(cM==M1&&countFromFirstDay<D);}
				var postDays=(month==endMonth&&countFromFirstDay>endDay);
				var dateToShow=(isLink)?countFromFirstDay:'';

			//compile displayDate('dd/mm/yyyy') argument for link
				var dateDay=countFromFirstDay;
				var dateMonth=currDate.getMonth()+1;
				var dateYear=currDate.getYear();
				var dateString=dateDay+"/"+dateMonth+"/"+dateYear;

			//Write table cell with link
				monthHTML+='<td height="20">';
				if(isLink&&!preDays&&!postDays)
				monthHTML+='<a href="javascript:parent.displayDate(\''+dateString+'\')">';
				monthHTML+=dateToShow;
				if(isLink&&!preDays&&!postDays)
				monthHTML+='</a>';
				monthHTML+='</td>';
			}
			monthHTML+='</tr>';
		}
			monthHTML+='\
			<tr><td height="20" bgcolor="#E43784" class="white">&nbsp;</td>\
			<td colspan="5" bgcolor="#E43784"><a href="javascript:top.calendar.hide()" class="white">Close</a></td>\
			<td bgcolor="#E43784" class="white">&nbsp;</td></tr>\
			<tr><td colspan="7" bgcolor="#000000"><img src="http://www.lastminute.com/lmn/calendar/images/trans.gif" width="140" height="2"></td></tr></table>'
	
		calendarHTML+=monthHTML+'</body></html>';

		currDate.setMonth(currDate.getMonth()+1);
	}
}

function getNumDays(M){
	if(M==2){
		// currentMonth defined to work around DP search being 14 days ahead (initMonth therefore being March in some cases)
		var currentMonth = new Date().getMonth()+1;
		var febYear=(initMonth<=2 || currentMonth<=2)?initYear:initYear*1+1;
		var febDate=new Date(Date.UTC(febYear,1,29));//yyyy/mm from 0/d from 1
		return (febDate.getMonth()==1)?29:28;
	}
	else return (M==9||M==4||M==6||M==11)?30:31;
}

//DROPDOWNS--
function setDays(buttonNo){
	if(N4)return;
	if(!eval("dropDay"+buttonNo) || !eval("dropMonth"+buttonNo)) return;
	var D=eval("dropDay"+buttonNo).value*1;
	var M=eval("dropMonth"+buttonNo).value*1;
	var daysDD=eval("dropDay"+buttonNo);
	//lm.log('run: '+buttonNo+' Month: '+M);
 	//if(daysDD.length>=1){
	if (daysDD.options[0].value=="0"){
		daysDD.length=1;
		for(i=1;i<getNumDays(M)+1;i++) daysDD.options[i]=new Option(i+1,i+1);
	}
	else {
		daysDD.length=0;
		for(i=0;i<getNumDays(M);i++) daysDD.options[i]=new Option(i+1,i+1);
	}
	if(hasOptionVal(daysDD,D)) selOptionVal(daysDD,D);//keep day selected
	else daysDD[0].selected=true;//or set to first
	//}
	//if (typeof updateCheckOut !== 'undefined') {
	//   updateCheckOut(stayLength.options[stayLength.selectedIndex].value);
	// }
}

function setDates(buttonNo){//onchange from month dropdown
	if(N4)return;
	setDays(buttonNo);
	currButtonNo=buttonNo;
	if(dropDay2) syncDropdowns();
	if(buttonNo==1){ setDays(2); }
}
function setCheckOut(){
	setDates(1);
	if (stayLength = document.getElementById('lengthOfStay')){updateCheckOut(stayLength.options[stayLength.selectedIndex].value);}
}

// fix for the month dropdowns getting set to next year's month due to the fact that two options (first and last) in the dropdown have the same value
// Note: this function runs twice: it's called in startUpCalendar() (in this file) and then on 'domload' (this is to prevent the fields changing back and forth during loading)
function _13_months_fix(){
	var out_day, out_month, in_day, in_month = false;
	var cookie = JSON.parse(lm.cookie.sFastBrowse)['dp_search'];

	//convert the cookie object to a nice array
	var cookies = [];
	for(i in cookie){
		for(j in cookie[i]) cookies[j] = cookie[i][j];
	}


	var ddDayOut = dropDay1.value*1;
	var ddMonthOut = dropMonth1.value*1;
	var ddDayIn = (dropDay2) ? dropDay2.value*1 : false;
	var ddMonthIn = (dropMonth2) ? dropMonth2.value*1 : false;

	out_day = cookies['date_out_day'] | ddDayOut;
	out_month = cookies['date_out_month'] | ddMonthOut;
	in_day = cookies['date_in_day'] | ddDayIn;
	in_month = cookies['date_in_month'] | ddMonthIn;

	var convert = function(m,d){
		var pad = function(str){
			return (str.length < 2) ? '0'+str : str+'';
		}
		return (pad(m)+pad(d))*1;
	}
	var cur = convert(initMonth, initDay);
	//out date
	var sel = convert(out_month, out_day);
	var date_out_year = (cur <= sel) ? initYear : initYear*1+1;
	var index_out = getChronMonth(out_month);
	if(initMonth==out_month*1){
		index_out = (initYear==date_out_year*1) ? 0 : 12;
	}
	if(index_out==0) setDropdowns(out_day, out_month, 1, index_out);

	//in date
	if(dropDay2 && dropMonth2){
		var sel = convert(in_month, in_day);
		var date_in_year = (cur <= sel) ? initYear : initYear*1+1;
		var index_in = getChronMonth(in_month);
		if(initMonth==in_month*1){
			index_in = (initYear==date_in_year*1) ? 0 : 12;
		}
		if(index_in==0) setDropdowns(in_day, in_month, 2, index_in);
	}
}

lm.addEvent({
	eT: 'domload',
	fn : _13_months_fix
})	
