﻿//
//	Copyright Agoda 2007, all rights reserved!
//  Author: Thalwin Hulsebos
//  Version: 1.0.0beta
//  Date: 15-May-2007

var cal_fixedX = -1;            // x position (-1 if to appear below control)
var cal_fixedY = -1;            // y position (-1 if to appear below control)
var cal_startAt = 0;            // 0 - sunday ; 1 - monday
var cal_showWeekNumber = 0;     // 0 - don't show; 1 - show
var cal_showToday = 1; 	    // 0 - don't show; 1 - show
var cal_enablehistory = false;

var cal_crossObj, cal_crossMonthObj, cal_crossYearObj, cal_monthSelected, cal_yearSelected, cal_dateSelected, ocal_monthSelected, ocal_yearSelected, ocal_dateSelected, cal_monthConstructed, cal_yearConstructed, cal_intervalID1, cal_intervalID2
var cal_timeoutID1, cal_timeoutID2, cal_ctlToPlaceValue, cal_ctlNow, cal_dateFormat, cal_nStartingYear;
var cal_monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var cal_oFunctions;
var cal_bShow = false;

/* hides <select> and <applet> objects (for IE only) */
function cal_hideElement(elmID, overDiv) {
    if (ie) {
        for (i = 0; i < document.all.tags(elmID).length; i++) {
            obj = document.all.tags(elmID)[i];
            if (!obj || !obj.offsetParent) {
                continue;
            }

            // Find the element's offsetTop and offsetLeft relative to the BODY tag.
            objLeft = obj.offsetLeft;
            objTop = obj.offsetTop;
            objParent = obj.offsetParent;

            // Add HTML check solved problem using calendar within box_search
            while (objParent.tagName.toUpperCase() != "BODY" && objParent.tagName.toUpperCase() != "HTML") {
                objLeft += objParent.offsetLeft;
                objTop += objParent.offsetTop;
                objParent = objParent.offsetParent;
            }

            objLeft = chkLeftPos(objLeft + 2);
            objHeight = obj.offsetHeight;
            objWidth = obj.offsetWidth;

            // condition to check if there is no need to hide obj
            if ((overDiv.offsetLeft + overDiv.offsetWidth) <= objLeft);
            else if ((overDiv.offsetTop + overDiv.offsetHeight) <= objTop);
            else if (overDiv.offsetTop >= (objTop + objHeight));
            else if (overDiv.offsetLeft >= (objLeft + objWidth));
            else {
                obj.style.visibility = "hidden";
            }
        }
    }
}

/* unhides <select> and <applet> objects (for IE only)   */
function cal_showElement(elmID) {
    if (ie) {
        for (i = 0; i < document.all.tags(elmID).length; i++) {
            obj = document.all.tags(elmID)[i];
            if (!obj || !obj.offsetParent) {
                continue;
            }
            obj.style.visibility = "";
        }
    }
}

function swapImage(srcImg, destImg) {
    if (ie) {
        document.getElementById(srcImg).setAttribute("src", cal_imgDir + destImg);
    }
}

function init_calendar() {
    if (dom) {
        var calwidth = 200;
        calwidth = 384;
        var outstr = "<table width=" + ((cal_showWeekNumber == 1) ? calwidth : (calwidth - 25)) + " class='table-style' border='0'><tr class='title-background-style'><td><table width='100%' border='0'><tr><td class='title-style'><B><span id='caption'></span></B></td></tr></table></td></tr><tr><td class='body-style'><span id='content'></span></td></tr>"
        if (cal_showToday == 1) {
            outstr += "<tr class='today-style'><td><span id='lblToday'></span></td></tr>";
        }
        outstr += "</table></div><div id='selectMonth' class='div-style'></div><div id='selectYear' class='div-style'>"
        divCal = document.createElement("div");
        divCal.id = "agoda_calendar";
        divCal.onclick = setShow;
        divCal.className = "div-style";
        divCal.innerHTML = outstr;
        document.body.appendChild(divCal);
    }
    cal_monthName = cal_monthNames;
    if (cal_startAt == 0) {
        cal_dayName = cal_shortDays;
    } else {
        cal_dayName = new Array(cal_shortDays[1], cal_shortDays[2], cal_shortDays[3], cal_shortDays[4], cal_shortDays[5], cal_shortDays[6], cal_shortDays[0]);
    }

    if (!ns4) {
        // correction for browsers as Opera
        if (cal_yearNow < 1900) {
            cal_yearNow += 1900;
        }
        cal_crossObj = (dom) ? document.getElementById("agoda_calendar").style : ie ? document.all.agoda_calendar : document.agoda_calendar;
        hideCalendar();

        cal_crossMonthObj = (dom) ? document.getElementById("selectMonth").style : ie ? document.all.selectMonth : document.selectMonth;
        cal_crossYearObj = (dom) ? document.getElementById("selectYear").style : ie ? document.all.selectYear : document.selectYear;

        cal_monthConstructed = false;
        cal_yearConstructed = false;

        if (cal_showToday == 1) {
            document.getElementById("lblToday").innerHTML = cal_todayString + " <a class='today-style' title='" + cal_gotoString + "' href='javascript:cal_monthSelected=cal_monthNow;cal_yearSelected=cal_yearNow;constructCalendar();'>" + cal_dayName[(cal_today.getDay() - cal_startAt == -1) ? 6 : (cal_today.getDay() - cal_startAt)] + ", " + cal_dateNow + " " + cal_monthName[cal_monthNow].substring(0, 3) + " " + cal_yearNow + "</a>";
        }
        document.getElementById("lblToday").innerHTML = "<a href='javascript:hideCalendar()' class='closecal' title='" + cal_txtClose + "'>" + cal_txtClose + "</a>";

        sHTML1 = "<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr>";
        sHTML1 += "<td width='15' class'titles' style='width:15px'><span id='spanLeft' title='" + cal_scrollLeftMessage + "' class='title-control-normal-style' onmouseover='swapImage(\"changeLeft\",\"left2.gif\");this.className=\"title-control-select-style\";' onclick='javascript:decMonth()' onmouseout='clearInterval(cal_intervalID1);swapImage(\"changeLeft\",\"left1.gif\");this.className=\"title-control-normal-style\";' onmousedown='clearTimeout(cal_timeoutID1);cal_timeoutID1=setTimeout(\"StartDecMonth()\",500)' onmouseup='clearTimeout(cal_timeoutID1);clearInterval(cal_intervalID1)'><IMG id='changeLeft' SRC='" + cal_imgDir + "left1.gif' width=14 height=15 BORDER=0></span></td>";
        sHTML1 += "<td width='44%' class'titles' align='center'><span id='spanMonth' class='title-control-style'></span></td>";
        sHTML1 += "<td width='44%' class'titles' align='center'><span id='spanMonth2' class='title-control-style'></span></td>";
        sHTML1 += "<td width='15' class'titles' style='width:15px' align='right'><span id='spanRight' title='" + cal_scrollRightMessage + "' style='width:18px' class='title-control-normal-style' onmouseover='swapImage(\"changeRight\",\"right2.gif\");this.className=\"title-control-select-style\";' onmouseout='clearInterval(cal_intervalID1);swapImage(\"changeRight\",\"right1.gif\");this.className=\"title-control-normal-style\";' onclick='incMonth()' onmousedown='clearTimeout(cal_timeoutID1);cal_timeoutID1=setTimeout(\"StartIncMonth()\",500)' onmouseup='clearTimeout(cal_timeoutID1);clearInterval(cal_intervalID1)'><img id='changeRight' src='" + cal_imgDir + "right1.gif' width='14' height='15' border='0'></span></td>";
        sHTML1 += "</tr></table>";
        document.getElementById("caption").innerHTML = sHTML1;
        cal_bPageLoaded = true;
    } else {
        alert("Your browser does not support this feature!");
    }

}

function hideCalendar() {
    if (cal_crossObj) {
        cal_crossObj.visibility = "hidden";
        if (cal_crossMonthObj != null) { cal_crossMonthObj.visibility = "hidden"; }
        if (cal_crossYearObj != null) { cal_crossYearObj.visibility = "hidden"; }
        if (document.getElementById("spanLeft")) { document.getElementById("spanLeft").style.visibility = "hidden"; }
        if (document.getElementById("spanRight")) { document.getElementById("spanRight").style.visibility = "hidden"; }

        cal_showElement('SELECT');
        cal_showElement('APPLET');
    }
}

function padZero(num) {
    return (num < 10) ? '0' + num : num;
}

function cal_constructDate(d, m, y) {
    var sTmp = cal_dateFormat;
    sTmp = sTmp.replace("dd", padZero(d));
    sTmp = sTmp.replace("d", d);
    sTmp = sTmp.replace("mmm", cal_monthName[m]);
    sTmp = sTmp.replace("mm", padZero(m + 1));
    return sTmp.replace("yyyy", y);
}

function closeCalendar() {
    hideCalendar();
    cal_ctlToPlaceValue.value = cal_constructDate(cal_dateSelected, cal_monthSelected, cal_yearSelected);
    if (typeof (cal_oFunctions) == "function") {
        cal_oFunctions(cal_ctlToPlaceValue, cal_dateSelected, cal_monthSelected + 1, cal_yearSelected);
    }
}

/*** Month Pulldown	***/
function StartDecMonth() {
    cal_intervalID1 = setInterval("decMonth()", 80);
}

function StartIncMonth() {
    cal_intervalID1 = setInterval("incMonth()", 80);
}

function incMonth() {
    cal_monthSelected++;
    if (cal_monthSelected > 11) {
        cal_monthSelected = 0;
        cal_yearSelected++;
    }
    constructCalendar();
}

function decMonth() {
    cal_monthSelected--;
    if (cal_monthSelected < 0) {
        cal_monthSelected = 11;
        cal_yearSelected--;
    }
    constructCalendar();
}


function getLeftPos(obj) {
    // Find the element's offsetLeft relative to the BODY tag.
    var objLeft = obj.offsetLeft;
    var objParent = obj.offsetParent;

    while (objParent.tagName.toUpperCase() != "BODY") {
        objLeft += objParent.offsetLeft;
        objParent = objParent.offsetParent;
    }
    return objLeft;
}

/*** Year Pulldown ***/
function incYear() {
    for (i = 0; i < 7; i++) {
        newYear = (i + cal_nStartingYear) + 1;
        if (newYear == cal_yearSelected) {
            txtYear = "&nbsp;<B>" + newYear + "</B>&nbsp;";
        } else {
            txtYear = "&nbsp;" + newYear + "&nbsp;";
        }
        document.getElementById("y" + i).innerHTML = txtYear;
    }
    cal_nStartingYear++;
    cal_bShow = true;
}

function decYear() {
    for (i = 0; i < 7; i++) {
        newYear = (i + cal_nStartingYear) - 1;
        if (newYear == cal_yearSelected) {
            txtYear = "&nbsp;<B>" + newYear + "</B>&nbsp;";
        }
        else {
            txtYear = "&nbsp;" + newYear + "&nbsp;";
        }
        document.getElementById("y" + i).innerHTML = txtYear;
    }
    cal_nStartingYear--;
    cal_bShow = true;
}


/*** calendar ***/
function WeekNbr(today) {
    Year = takeYear(today);
    Month = today.getMonth();
    Day = today.getDate();
    now = Date.UTC(Year, Month, Day + 1, 0, 0, 0);
    var Firstday = new Date();
    Firstday.setYear(Year);
    Firstday.setMonth(0);
    Firstday.setDate(1);
    then = Date.UTC(Year, 0, 1, 0, 0, 0);
    var Compensation = Firstday.getDay();
    if (Compensation > 3) Compensation -= 4;
    else Compensation += 3;
    NumberOfWeek = Math.round((((now - then) / 86400000) + Compensation) / 7);
    return NumberOfWeek;
}

function takeYear(theDate) {
    x = theDate.getYear();
    var y = x % 100;
    y += (y < 38) ? 2000 : 1900;
    return y;
}

function cal_selection(nDay, nMonth, nYear) {
    cal_dateSelected = nDay;
    cal_monthSelected = nMonth;
    cal_yearSelected = parseInt(nYear);
    closeCalendar();
}

function getMonthTable(selYear, selMonth) {
    // correction for doublemonths
    if (selMonth == 12) {
        selMonth = 0;
        selYear += 1;
    }

    var dateMessage;
    var startDate = new Date(selYear, selMonth, 1);
    var endDate = new Date(selYear, selMonth + 1, 1);
    endDate = new Date(endDate - (24 * 60 * 60 * 1000));
    numDaysInMonth = endDate.getDate();

    datePointer = 0;
    dayPointer = startDate.getDay() - cal_startAt;

    if (dayPointer < 0) {
        dayPointer = 6;
    }

    var sHTML = "<table	border='0' class='body-style' cellpadding='0' cellspacing='0' width='100%'><tr class='dayofweeks'>";
    if (cal_showWeekNumber == 1) {
        sHTML += "<td width='22' align='center'><b>" + cal_weekString + "</b></td><td width='1' rowspan='7' class='weeknumber-div-style'><img src='" + cal_imgDir + "divider.gif' width='1'></td>";
    }
    for (i = 0; i < 7; i++) {
        sHTML += "<td width='22' align='right' style='padding-right:2px'>" + cal_dayName[i] + "</td>";
    }
    sHTML += "</tr><tr>";

    if (cal_showWeekNumber == 1) {
        sHTML += "<td align=right>" + WeekNbr(startDate) + "&nbsp;</td>";
    }
    for (var i = 1; i <= dayPointer; i++) {
        sHTML += "<td>&nbsp;</td>";
    }

    var bDayEnabled;
    var sDisabled = "";
    for (datePointer = 1; datePointer <= numDaysInMonth; datePointer++) {
        dayPointer++;
        bDayEnabled = true;

        //Check if day should be enabled or disabled for selection
        if (typeof (chkEnableDay) == "function") {
            bDayEnabled = chkEnableDay(datePointer, selMonth, selYear);
        }
        sHTML += "<td align='right' class='cal_day'>";
        var sStyle = "normal-day-style"; //regular day
        if ((datePointer == cal_dateNow) && (selMonth == cal_monthNow) && (selYear == cal_yearNow)) { //today
            sStyle = "current-day-style";
        }
        else if (dayPointer % 7 == (cal_startAt * -1) + 1) { //end-of-the-week day
            sStyle = "end-of-weekday-style";
        }

        //selected day
        if ((datePointer == ocal_dateSelected) && (selMonth == ocal_monthSelected) && (selYear == ocal_yearSelected)) {
            sStyle += " selected-day-style";
        }
        sDisabled = "";
        sHint = txtSelectDay;
        if (bDayEnabled == false) {
            sStyle = "disabled-" + sStyle;
            sDisabled = " disabled";
            sHint = txtDayDisabled;
        }

        var regexp = /\"/g;
        sHint = sHint.replace(regexp, "&quot;");
        dateMessage = "";

        if (bDayEnabled)
            sHTML += "<a class='" + sStyle + "' " + dateMessage + " title=\"" + sHint + "\" href='javascript:cal_selection(" + datePointer + "," + selMonth + "," + selYear + ");'>&nbsp;" + datePointer + "&nbsp;</a>"
        else
            sHTML += "<label class='" + sStyle + "' " + sDisabled + " title=\"" + sHint + "\" >&nbsp;" + datePointer + "&nbsp;</label>"

        sHTML += "";
        if ((dayPointer + cal_startAt) % 7 == cal_startAt) {
            sHTML += "</tr><tr>";
            if ((cal_showWeekNumber == 1) && (datePointer < numDaysInMonth)) {
                sHTML += "<td align=right>" + (WeekNbr(new Date(selYear, selMonth, datePointer + 1))) + "&nbsp;</td>";
            }
        }
    }
    sHTML += "</tr></table>"
    return sHTML;
}

function constructCalendar() {
    cal_bShow = true;
    var dateMessage;
    var startDate = new Date(cal_yearSelected, cal_monthSelected, 1);
    var endDate = new Date(cal_yearSelected, cal_monthSelected + 1, 1);
    endDate = new Date(endDate - (24 * 60 * 60 * 1000));
    numDaysInMonth = endDate.getDate();

    datePointer = 0;
    dayPointer = startDate.getDay() - cal_startAt;

    if (dayPointer < 0) {
        dayPointer = 6;
    }

    //Check if day should be enabled or disabled for selection
    var bPrevEnabled = true;
    var bNextEnabled = true;
    if (cal_monthSelected <= cal_monthNow && cal_yearSelected == cal_yearNow && cal_enablehistory == false) {
        bPrevEnabled = false;
    }
    if (bPrevEnabled)
        bPrevEnabled = chkEnableDay(1, cal_monthSelected, cal_yearSelected);

    if (typeof (chkEnableDay) == "function") {
        bNextEnabled = chkEnableDay(1, cal_monthSelected + 2, cal_yearSelected);
    }


    if (bPrevEnabled) {
        document.getElementById("spanLeft").style.visibility = (dom || ie) ? "visible" : "show";
        document.getElementById("spanLeft").disabled = false;
    } else {
        document.getElementById("spanLeft").style.visibility = "hidden";
        document.getElementById("spanLeft").disabled = true;
    }
    if (bNextEnabled) {
        document.getElementById("spanRight").style.visibility = (dom || ie) ? "visible" : "show";
        document.getElementById("spanRight").disabled = false;
    } else {
        document.getElementById("spanRight").style.visibility = "hidden";
        document.getElementById("spanRight").disabled = true;
    }
    // script for month table
    var mnt1Html = getMonthTable(cal_yearSelected, cal_monthSelected);
    var mnt2Html = getMonthTable(cal_yearSelected, cal_monthSelected + 1);
    sHTML = "<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td valign='top' align='left'>" + mnt1Html + "</td><td><img src='" + cal_imgDir + "spacer.gif' width='1' border='0' alt='spacer'></td><td bgcolor='#909090' width='2'><img src='" + cal_imgDir + "spacer.gif' width='2' height='90' border='0' alt='Divider'></td><td><img src='" + cal_imgDir + "spacer.gif' width='1' border='0' alt='spacer'></td><td valign='top' align='right'>" + mnt2Html + "</td></tr></table>"

    document.getElementById("content").innerHTML = sHTML;
    document.getElementById("spanMonth").innerHTML = frmtDate(cal_dsplMonthFormat, cal_dateSelected, cal_monthSelected, cal_yearSelected);
    var calMonth2 = cal_monthSelected + 1;
    var calYear2 = cal_yearSelected;
    if (calMonth2 == 12) {
        calMonth2 = 0;
        calYear2 += 1;
    }
    document.getElementById("spanMonth2").innerHTML = frmtDate(cal_dsplMonthFormat, cal_dateSelected, calMonth2, calYear2);
}

function popUpCalendar(ctl, ctl2, format, OtherFunctions) {
    var leftpos = 0;
    var toppos = 0;

    cal_oFunctions = OtherFunctions;
    if (cal_bPageLoaded) {
        if (cal_crossObj.visibility == "hidden") {
            cal_ctlToPlaceValue = ctl2;
            cal_dateFormat = format;

            formatChar = " ";
            aFormat = cal_dateFormat.split(formatChar);
            if (aFormat.length < 3) {
                formatChar = "/";
                aFormat = cal_dateFormat.split(formatChar);
                if (aFormat.length < 3) {
                    formatChar = ".";
                    aFormat = cal_dateFormat.split(formatChar);
                    if (aFormat.length < 3) {
                        formatChar = "-";
                        aFormat = cal_dateFormat.split(formatChar);
                        if (aFormat.length < 3) {
                            // invalid date	format
                            formatChar = "";
                        }
                    }
                }
            }

            tokensChanged = 0;
            if (formatChar != "") {
                // use user's date
                aData = ctl2.value.split(formatChar);

                for (i = 0; i < 3; i++) {
                    if ((aFormat[i] == "d") || (aFormat[i] == "dd")) {
                        cal_dateSelected = parseInt(aData[i], 10);
                        tokensChanged++;
                    }
                    else if ((aFormat[i] == "m") || (aFormat[i] == "mm")) {
                        cal_monthSelected = parseInt(aData[i], 10) - 1;
                        tokensChanged++;
                    }
                    else if (aFormat[i] == "yyyy") {
                        cal_yearSelected = parseInt(aData[i], 10);
                        tokensChanged++;
                    }
                    else if (aFormat[i] == "mmm") {
                        for (j = 0; j < 12; j++) {
                            if (aData[i] == cal_monthName[j]) {
                                cal_monthSelected = j;
                                tokensChanged++;
                            }
                        }
                    }
                }
            }
            if ((tokensChanged != 3) || isNaN(cal_dateSelected) || isNaN(cal_monthSelected) || isNaN(cal_yearSelected)) {
                cal_dateSelected = cal_dateNow;
                cal_monthSelected = cal_monthNow;
                cal_yearSelected = cal_yearNow;
            }

            ocal_dateSelected = cal_dateSelected;
            ocal_monthSelected = cal_monthSelected;
            ocal_yearSelected = cal_yearSelected;

            aTag = ctl;
            //alert(document.body.scrollLeft);
            do {
                aTag = aTag.offsetParent;
                leftpos += aTag.offsetLeft;
                toppos += aTag.offsetTop;
            } while (aTag.tagName != "BODY" && aTag.tagName != "HTML");
            // Add HTML check solved problem using calendar within box_search

            //Need to convert to string for firefox
            var posleft = ctl.offsetLeft + leftpos + 2;
            // Check leftpos to document.body.offsetWidth
            posleft = chkLeftPos(posleft);

            var strLeft = new String(posleft + "px");
            var postop = ctl.offsetTop + toppos + ctl.offsetHeight + 2;
            var strTop = new String(postop + "px");

            cal_crossObj.left = cal_fixedX == -1 ? strLeft : cal_fixedX;
            cal_crossObj.top = cal_fixedY == -1 ? strTop : cal_fixedY;

            constructCalendar(1, cal_monthSelected, cal_yearSelected);
            cal_crossObj.visibility = (dom || ie) ? "visible" : "show";

            cal_hideElement('SELECT', document.getElementById("agoda_calendar"));
            cal_hideElement('APPLET', document.getElementById("agoda_calendar"));

            cal_bShow = true;
        }
    }
    else {
        init_calendar();
        popUpCalendar(ctl, ctl2, format, OtherFunctions);
    }
}

function chkLeftPos(lefpos) {
    var retval = lefpos;
    var rightpos = lefpos + document.getElementById("agoda_calendar").offsetWidth;
    var winWidth = document.body.offsetWidth;
    var offset = 0;

    if (rightpos > winWidth) {
        offset = rightpos - winWidth + 1;
        retval -= offset;
        if (retval < 0)
            retval = 0;
    }
    return retval
}
function setShow() {
    cal_bShow = true;
}
document.onkeypress = function hidecal1() {
    if (event.keyCode == 27) {
        hideCalendar();
    }
}
document.onclick = function hidecal2() {
    if (!cal_bShow) {
        hideCalendar();
    }
    cal_bShow = false;
}

