
// Getting element dimensions
function getDim( elm ) {
	var box = { x:0, y:0, w:0, h:0 };
		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;
		}

	return box;
}

// onload handling
function addListener( elm, event, handler ) {
	if(elm.addEventListener)
		elm.addEventListener(event, handler, false);
	else if(elm.attachEvent)
		elm.attachEvent('on'+event, handler);
	else
		elm['on'+event] = handler;
}


var DOM = {
	isParentOf: function( parentElm, contextElm) {
		while(contextElm && (contextElm != parentElm))
			contextElm = contextElm.parentNode;
		return (contextElm == parentElm);
	},
	getParentOrSelf: function( contextElm, nodeName ) {
		nodeName = nodeName.toLowerCase();
		while(contextElm.nodeName.toLowerCase() != nodeName && contextElm.parentNode)
			contextElm = contextElm.parentNode;
		return contextElm;
	},
	addClass: function( elm, className ) {
		elm.className += ' '+className;
	},
	removeClass: function( elm, className) {
		var classMatch = new RegExp('\\b'+className+'\\b', 'g');
		if(classMatch.test(elm.className))
			elm.className = elm.className.replace(classMatch, ' ');
	}	
};
    

var gClientIsGecko = (window.controllers) ? true : false;
var gClientIsOpera = (window.opera) ? true : false;
var gClientIsIE    = (document.all && !gClientIsOpera) ? true : false;
var gClientIsIE5   = (gClientIsIE && /MSIE 5\.0/.test(navigator.appVersion)) ? true : false;
var gClientIsIE55  = (gClientIsIE && /MSIE 5\.5/.test(navigator.appVersion)) ? true : false;
var gClientIsIE6   = (gClientIsIE && /MSIE 6\.0/.test(navigator.appVersion)) ? true : false;
var gClientIsIE7   = (gClientIsIE && /MSIE 7\.0/.test(navigator.appVersion)) ? true : false;
var gClientIsMac   = (/Mac/.test(navigator.appVersion)) ? true : false;

// Onload function
function _init() {
	//alert(gClientIsIE5);
	if(window.initDaySelect)
		initDaySelect();
}
//window.onload = _init;
addListener(window, 'load', _init);








/* */
// popCal without requirements for unique ids
//	@me	DOMNode context node
//	@calId	String	id of calendar node
//	@dt	String	'checkin' or 'checkout' prefix
function popCal(me, calId, dt){ // eg this 'calendar' 'in'
	getDim(me);
    if (document.getElementById){
        var c = document.getElementById(calId);

		var i = getChildImage(me);
		var f = DOM.getParentOrSelf(me, 'form');

        calendar.cal = c;
        calendar.caldt = dt;
        calendar.calf = f;
        var my = f[dt + 'monthyear'].value.split("-");
        y=my[0];m=my[1];d=f[ dt + 'day'].value;
        createCal(y,m,d);

		var box = getDim(i);
		var left = box.x, top = (box.y + i.offsetHeight);
        c.style.left = left+'px';
        c.style.top = top+'px';
        c.style.display="block";
	}
}

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

function createCal(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 frm = calendar.calfrm;
    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;
 

   	var t='<table class="caltab" cellspacing="0"><tr>';
    t+='<td class="calheader" colspan="7">';

    t+='<select name="ym" onchange="goYearMonth(this.options[this.selectedIndex].value)">';
    var mn=td.getMonth()+1;var yr=td.getFullYear();
    var last_month=0;
	var month_count = 12;
	if ( months_ahead ) {
		month_count = months_ahead;
	}
    for(n=0;n<month_count;n++){ //pw
        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;';
    if (y==td.getFullYear() && m==td.getMonth()+1) {
        t+='<img class="calNoPrevMonth" src="' + cv.iconpath + 'transparent.png" width="16" height="16" alt="'+cv.prevMonth+'">&nbsp;';
    }
    else {
        t+='<a class="calPrevMonth" href="" onclick="monthBack('+y+','+m+'); return false;" title="'+cv.prevMonth+'"><img src="' + cv.iconpath + 'transparent.png" width="16" height="16" alt="'+cv.prevMonth+'"></a>&nbsp;';
    }

    if (last_month==1) {
        t+='<img class="calNoNextMonth" src="' + cv.iconpath + 'transparent.png" width="16" height="16" alt="' + cv.nextMonth + '">';
    }
    else {
        t+='<a class="calNextMonth" href="" onclick="monthForward('+y+','+m+'); return false;" title="' + cv.nextMonth +'"><img src="' + cv.iconpath + 'transparent.png" width="16" height="16" alt="' + cv.nextMonth + '"></a>';
    }
    t+='</td></tr>';
    t+='<tr class="weekdays">';
    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">';
    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 += ' gone'}
                }
            }
        };
        t+='<td class="'+cl+'">';
        if (href){
            t+='<a href="#" onclick="chooseDate('+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 class="calfoot" colspan="7"><a href="#" onclick="killCal();return false;">' + cv.closeCalendar + '</a></td></tr></table>';
                                         
	//Pierce Added ieMat. It creates an iFrame between #calendar and .caltab to
	//fix calendar appearing behind selects  in IE 5-6.
	var ieMat=document.createElement('iframe');
		if(document.location.protocol == "https:")
			ieMat.src="//0";
		else if(window.opera != "undefined")
			ieMat.src="";
		else
			ieMat.src="javascript:false";
		ieMat.scrolling="no";
		ieMat.frameBorder="0";
	    //ieMat.style.width= document.getElementById("calendar").offsetWidth+ "px";   
		//ieMat.style.height=ieULs[j].offsetHeight+"px";
		ieMat.style.zIndex="-1";

    document.getElementById("calendar").innerHTML= t;        

	//Pierce added this: It drops ieMat in the correct place.
	document.getElementById("calendar").insertBefore(ieMat, document.getElementById("calendar").childNodes[0]);

}

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

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

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

//pw consolidate overlapping select setting functionality
function chooseDate(y,m,d,dt){
	if ( m < 10 ) m = "0" + m;
    killCal();
	setDayMonth(y,m,d,dt); // in datesmultiyear.jsp
}

function xchooseDate(y,m,d,dt){
    // set form values
    var f = calendar.calf;
    var dt = calendar.caldt;
    f[dt + 'monthyear'].value = y + "-"  + m;
    f[dt + 'day'].value = d;
	if (dt == "in"){
		checkDateOrder(f, 'inday', 'inmonthyear', 'outday', 'outmonthyear');
	}
    killCal();
	updateDaySelect(f);
}

function initDaySelect() {
	var forms = document.getElementsByTagName('form');
	for(var i=0; i<forms.length; i++)
		if(forms[i]['inday'])
			updateDaySelect(forms[i]);
}


function updateDaySelect( me ) {

	// 1-2 testing
	if(!days_long) return;
	
	// IE5/Mac not supported
	if(gClientIsIE5 && gClientIsMac)
		return;
	
	var frm = DOM.getParentOrSelf(me, 'form');
	
  // Check if we have all fields. If not, we are in the first stage
  // of the book process and should not auto-update selects since there
  // is only the check-in select and the amount of nights.
	if(!frm['inday'] || !frm['outday'] || !frm['inmonthyear'] || !frm['outmonthyear'])
    return;

  
  var ci_d = frm['inday'];
	var co_d = frm['outday'];
	var ci_my = frm['inmonthyear'].value.split("-");
	var co_my = frm['outmonthyear'].value.split("-");
	
	var ci_sel = ci_d.selectedIndex;
	var co_sel = co_d.selectedIndex;

	var monthDays = [], opt;
	
	// Checkin month
	monthDays = getDaysForMonth(ci_my[0], ci_my[1]);
	ci_d.innerHTML = '';
	for(var i = 0; i < monthDays.length; i++) {
		opt = document.createElement('option');
		//pw opt.innerHTML = (monthDays[i] + ' ' + (i+1));
		opt.innerHTML = ('' + (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 = getDaysForMonth(co_my[0], co_my[1]);
	co_d.innerHTML = '';
	for(var i = 0; i < monthDays.length; i++) {
		opt = document.createElement('option');
		//pw opt.innerHTML = (monthDays[i] + ' ' + (i+1));
		opt.innerHTML = ('' + (i+1));
		opt.value = (i+1);
		co_d.appendChild(opt);
	}
	co_d.options[co_sel].defaultSelected = co_d.options[co_sel].selected = true;
}

function getDaysForMonth( year, month ) {
	// Month index starts on 0(-11) in Date()-object
	var monthDate = new Date(year, month-1);
	var orgMonth = monthDate.getMonth();
	var dayArray = [], weekDay;
	while(monthDate.getMonth() == orgMonth) {
		// Week starts on Sunday in Date()-object
		weekDay = (monthDate.getDay() == 0) ? 6 : (monthDate.getDay()-1);
		dayArray.push(days_long[weekDay]);
		monthDate.setDate(monthDate.getDate()+1);
	}
	return dayArray;
}



function checkDateOrder(me, ci_day, ci_month_year, co_day, co_month_year) {
	if (document.getElementById) {
		//var frm = document.getElementById(frm);
		// Do findup to get form instead of fixed id
		var frm = DOM.getParentOrSelf(me, 'form');

		// create date object from checkin values
		// set date to 12:00 to avoid problems with one
		// date being wintertime and the other summertime
		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);

        // create date object from checkout values
	    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 checkin date is at or after checkout date,
		// add a day full of milliseconds, and set the
		// selectbox values for checkout date to new value
	    if (ci >= co){
    	    co.setTime(ci.getTime() + 1000 * 60 * 60 * 24);
	        frm[co_day].value =  co.getDate();
    	    var com = co.getMonth()+1;
			if ( com < 10 ) com = "0" + com; //pw
	        frm[co_month_year].value = co.getFullYear() + "-" + com;
    	}
	}
}


// Searches children to find image
function getChildImage( contextElm ) {     
	contextElm = contextElm.firstChild;
	while(contextElm.nodeName.toLowerCase() != 'img' && contextElm.nextSibling)
		contextElm = contextElm.nextSibling;
	return contextElm;
}


