﻿var idx=0;
var imgLeft='images/before.jpg';
var imgRight='images/next.jpg';
var imgClose='images/close.gif';

ThailandCalendar = {
    _month: new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
    _weak: new Array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
    _day: new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31),
    _currentyear: new Date().getFullYear(),
    _currentmonth: new Date().getMonth(),
    _currentdate: new Date().getDate(),
    _selectmonth: new Date().getMonth(),
    _selectyear: new Date().getFullYear(),
    _startmonth: new Date().getMonth(),
    _sdate: new Date().getDate(),
    _smonth: new Date().getMonth(),
    _syear: new Date().getFullYear(),
    _startyear: new Date().getFullYear(),
    _object: '',
    _nextE: 0,
    chkinBox: '',
    chkoutBox: '',
    _input: '',
    _x: 0,
    _y: 0,
    _cal: '',
    _calWidth: 426,
    _tdh1: null,
    _tdh2: null,
    $: function () {
        var elements = new Array();

        for (var i = 0; i < arguments.length; i++) {
            var element = arguments[i];
            if (typeof element == 'string')
                element = document.getElementById(element);

            if (arguments.length == 1)
                return element;

            elements.push(element);
        }

        return elements;
    },
    setSelectdate: function () {
        var i_date = this._input.value;
        i_date = i_date.split('/');
        i_date = new Date(i_date[1] + '/' + i_date[0] + '/' + i_date[2]);
        this._smonth = i_date.getMonth();
        this._syear = i_date.getFullYear();
        this._sdate = i_date.getDate();

        if (this._currentyear == this._syear) {
            if (this._currentmonth == this._smonth) {
                this._nextE = 0;
            }
            else {
                this._nextE = this._smonth - this._currentmonth;
            }
        } else {
            this._nextE = 12 - (this._currentmonth - this._smonth);
        }
        this._selectmonth = this._smonth;
        this._selectyear = this._syear;
    },
    initialize: function () {
        //ThailandCalendar._object=document.forms[0];
        ThailandCalendar._object = ThailandCalendar.$('calendarcontrol');
        ThailandCalendar._cal = document.createElement('div');
        ThailandCalendar.setID(ThailandCalendar._cal, 'myCalendar');
        ThailandCalendar.setClass(ThailandCalendar._cal, 'ThailandCalendar');
        ThailandCalendar._object.appendChild(ThailandCalendar._cal);
        ThailandCalendar.setWidth(ThailandCalendar._cal, ThailandCalendar._calWidth);
        ThailandCalendar.hideCalendar();
    },
    createEvent: function () {
        var anchrs = document.getElementsByTagName('a');
        for (var i = 0; i < anchrs.length; i++) {
            if (anchrs[i].rel == 'startdate') {
                anchrs[i].onclick =
                    function (event) {
                        ThailandCalendar._input = ThailandCalendar.$(ThailandCalendar.chkinBox);
                        ThailandCalendar.showCalendar(this, event);
                    };
            }
            if (anchrs[i].rel == 'enddate') {
                anchrs[i].onclick =
                    function (event) {
                        ThailandCalendar._input = ThailandCalendar.$(ThailandCalendar.chkoutBox);
                        ThailandCalendar.showCalendar(this, event);
                    };
            }
        }
    },
    createCalendar: function () {
        this.checkSelect();
        this.createmonth(0, this._cal);
        this._selectmonth = this._selectmonth + 1;
        this.checkSelect();
        this.createmonth(this._calWidth / 2, this._cal);
        this.setLeft(this._cal, this._x);
        this.setTop(this._cal, this._y);
        this.setPosition(this._cal, 'absolute');
    },
    checkSelect: function () {
        if (this._selectmonth > 11) {
            this._selectmonth = 0;
            this._selectyear = this._selectyear + 1;
        }
        else if (this._selectmonth < 0) {
            this._selectmonth = 11;
            this._selectyear = this._selectyear - 1;
        }
    },
    createbutton: function () {
        var mainTable = document.createElement('table');
        mainTable.cellPadding = '5';
        mainTable.border = '0';
        mainTable.width = '100%';

        var _main_tr = mainTable.insertRow(mainTable.rows.length);
        var _main_tc = _main_tr.insertCell(_main_tr.cells.length);
        //_main_tc.colSpan='2';
        this.setAlign(_main_tc, 'right');
        this.setClass(_main_tc, 'CalendarHeader');
        //this.setClass(div,'CalendarHeader');

        var img = document.createElement('img');
        img.alt = 'Close calendar';
        img.title = 'Close calendar';
        img.src = imgClose;
        img.style.cursor = 'pointer';
        img.height = '16';
        img.width = '16';
        img.onclick = ThailandCalendar.hideCalendar;
        _main_tc.appendChild(img);

        _main_tr = mainTable.insertRow(mainTable.rows.length);

        _main_tc = _main_tr.insertCell(_main_tr.cells.length);
        _main_tc.width = '100%';

        this._tdh1 = _main_tc;

        //_main_tc = _main_tr.insertCell(_main_tr.cells.length);
        //_main_tc.width='50%';

        //this._tdh2 = _main_tc;

        this._cal.appendChild(mainTable);

        var lb = document.createElement('div');
        if (this._nextE > 0)
            lb.innerHTML = "<img id='imgLeft' alt='Previous Month' title='Previous Month' src='" + imgLeft + "' style='cursor:pointer' onclick='ThailandCalendar.Prevcalendar();'/>";
        var rb = document.createElement('div');
        if (this._nextE < 12)
            rb.innerHTML = "<img id='imgLeft' alt='Next Month' title='Next Month' src='" + imgRight + "' style='cursor:pointer' onclick='ThailandCalendar.NextCalendar();'/>";

        this.setClass(lb, 'monthPre');
        this.setClass(rb, 'monthNext');

        this._cal.appendChild(lb);
        this._cal.appendChild(rb);
    },
    createmonth: function (_l, _o) {
        var _dt = new Date(this._selectyear, this._selectmonth, 1);

        var _layer = document.createElement('div');
        this.setPosition(_layer, 'absolute');
        this.setLeft(_layer, _l + 5);

        //_o.appendChild(_layer);
        var obj = null;
        if (_l == 0) {
            if (this._tdh1 == null) return;
            else obj = this._tdh1;
        } else {
            if (this._tdh1 == null) return;
            else obj = this._tdh1;
        }
        if (obj == null) return;

        obj.appendChild(_layer);

        /* Create Month-Year Table */
        _header = document.createElement('table');
        this.setClass(_header, 'monthHolder');
        _layer.appendChild(_header);
        this.setCellPadding(_header, 0);
        this.setCellSpacing(_header, 0);

        /* Create TR1 for month-year */
        _header_tr = _header.insertRow(_header.rows.length);
        this.setBackgroundColor(_header_tr, '#BF4904');

        /* Create Header 1 */
        _header_th = document.createElement('th');
        _header_tr.appendChild(_header_th);
        this.setClass(_header_th, 'monthHeader');
        _header_th.colSpan = '7';
        _header_th.innerHTML = this._month[_dt.getMonth()] + ' ' + _dt.getFullYear();
        this.setAlign(_header_th, 'center');

        /* Create TR1 for month-year */
        _header_tr = _header.insertRow(_header.rows.length);
        this.setBackgroundColor(_header_tr, '#BF4904');


        /* create Table calendar days */
        var _cal = document.createElement('table');
        _layer.appendChild(_cal);
        this.setCellPadding(_cal, 0);
        this.setCellSpacing(_cal, 2);
        this.setClass(_cal, 'monthHolder');

        var _c = 0;
        var _start = 0;
        var totalday = this.DaysArray(_dt.getMonth());
        for (var w = 0; w < 7; w++) {
            _cal_tr = _cal.insertRow(_cal.rows.length);
            for (var d = 0; d < 7; d++) {

                if (w == 0) {
                    _header_th = document.createElement('th');
                    this.setAlign(_header_th, 'center');
                    _header_th.innerHTML = this._weak[d];
                    _header_tr.appendChild(_header_th);
                }
                else {
                    _cal_tc = _cal_tr.insertCell(_cal_tr.cells.length);
                    if ((w == 1) && (d + 1 == _dt.getDay()))
                        _start = 1;
                    else if ((w == 1) && (_dt.getDay() == 0) && d == 6)
                        _start = 1;
                    if (totalday == _c)
                        _start = 0;
                    if (_start == 1) {
                        if (_c == this._currentdate - 1 && this._selectmonth == this._currentmonth && this._selectyear == this._currentyear) {
                            this.setClass(_cal_tc, 'todayDate');
                            if (idx == 0)
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,0," + this._day[_c] + ");");
                            else
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,1," + this._day[_c] + ");");
                        }
                        else if (_c == this._sdate - 1 && this._smonth == this._selectmonth && this._syear == this._selectyear) {
                            this.setClass(_cal_tc, 'selecteddate');
                            if (idx == 0)
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,0," + this._day[_c] + ");");
                            else
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,1," + this._day[_c] + ");");
                        }
                        else if (_c < this._currentdate - 1 && this._selectmonth == this._currentmonth && this._selectyear == this._currentyear)
                            this.setClass(_cal_tc, 'pastdate');
                        else {
                            this.setMouseEvent(_cal_tc);
                            this.setCursor(_cal_tc);
                            if (idx == 0)
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,0," + this._day[_c] + ");");
                            else
                                _cal_tc.setAttribute("onclick", "ThailandCalendar.setDate(this,1," + this._day[_c] + ");");
                        }

                        this.setAlign(_cal_tc, 'center');
                        _cal_tc.innerHTML = this._day[_c];
                        _c++;
                    }
                    else {
                        this.setClass(_cal_tc, 'nodate');
                    }
                }
            }
        }
        _cal_tr = _cal.insertRow(_cal.rows.length);
        _cal_tc = _cal_tr.insertCell(_cal_tr.cells.length);
        var hidden = document.createElement('input');
        hidden.type = 'hidden';
        this.setID(hidden, 'date' + idx);
        hidden.value = this._selectmonth + 1 + '/' + this._selectyear;
        _cal_tc.appendChild(hidden);
        this.setClass(_cal_tc, 'nodate');
        if (idx == 0) idx = 1; else idx = 0;
    },
    daysInFebruary: function (year) {
        return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
    },
    DaysArray: function (i) {
        var returnParam = 31
        if (i == 3 || i == 5 || i == 8 || i == 10) { returnParam = 30 }
        if (i == 1) { returnParam = this.daysInFebruary(this._currentyear); }
        return returnParam;
    },
    Prevcalendar: function () {
        if (this._selectmonth == 0) {
            this._selectmonth = 10;
            this._selectyear -= 1;
        }
        else
            this._selectmonth -= 2;

        this.checkSelect();
        this._nextE--;
        this._cal.innerHTML = '';
        this.createbutton();
        this.createmonth(-this._calWidth / 2, this._cal);

        this._selectmonth += 1;
        this.checkSelect();
        this.createCalendar();

        this._selectmonth -= 1;
        this.checkSelect();
        this.fidding(0);

    },
    NextCalendar: function () {
        this._nextE++;
        this._cal.innerHTML = '';
        this.createbutton();

        this._selectmonth -= 1;
        this.checkSelect();
        this.createCalendar();

        this._selectmonth += 1;
        this.checkSelect();
        this.createmonth(this._calWidth, this._cal);

        this.fidding(1);
    },
    fidding: function (i) {

        var _l1 = this.getLeft(this._tdh1.childNodes[0]);
        var _l2 = this.getLeft(this._tdh1.childNodes[1]);
        var _l3 = this.getLeft(this._tdh1.childNodes[2]);

        if (i == 1) {
            _l1 -= 20;
            _l2 -= 20;
            _l3 -= 20;
        }
        else {
            _l1 += 20;
            _l2 += 20;
            _l3 += 20;
        }
        this.setLeft(this._tdh1.childNodes[0], _l1);
        this.setLeft(this._tdh1.childNodes[1], _l2);
        this.setLeft(this._tdh1.childNodes[2], _l3);
        if (_l2 < 6 && i == 1) {
            this.setLeft(this._tdh1.childNodes[1], 5);
            this.setLeft(this._tdh1.childNodes[2], this._calWidth / 2 + 5);
            this._tdh1.removeChild(this._tdh1.childNodes[0]);
            return;
        }
        else if ((_l1 > -6) && (i == 0)) {
            this.setLeft(this._tdh1.childNodes[0], 5);
            this.setLeft(this._tdh1.childNodes[1], this._calWidth / 2 + 5);
            this._tdh1.removeChild(this._tdh1.childNodes[2]);
            return;
        }
        setTimeout("ThailandCalendar.fidding(" + i + ");", 2);
    },
    getDate: function (idate) {
        var i_date = idate.split('/');
        return new Date(i_date[1] + '/' + i_date[0] + '/' + i_date[2]);
    },
    setDate: function (_o, i, v) {
        var idate = v + '/' + ThailandCalendar.$('date' + i).value;
        var i_date = ThailandCalendar.getDate(idate);
        if (ThailandCalendar._input.id.indexOf('checkIn') != -1) {
            i_date.setDate(i_date.getDate() + 5);
            var month = parseInt(i_date.getMonth()) + 1;
            ThailandCalendar.$(ThailandCalendar.chkoutBox).value = i_date.getDate() + '/' + month + '/' + i_date.getFullYear();
        }
        else {
            var odate = ThailandCalendar.getDate(ThailandCalendar.$(ThailandCalendar.chkinBox).value);
            var isvalid = true;
            if (i_date.getFullYear() < odate.getFullYear()) {
                isvalid = false;
            }
            else if (i_date.getFullYear() == odate.getFullYear()) {
                if (i_date.getMonth() < odate.getMonth()) {
                    isvalid = false;
                } else if (i_date.getMonth() == odate.getMonth() && i_date.getDate() <= odate.getDate()) {
                    isvalid = false;
                }
            }
            if (!isvalid) {
                alert('Check out date should not be prior to check in date');
                return false;
            } else {
                var diff = new Date();
                diff.setTime(Math.abs(i_date.getTime() - odate.getTime()));

                var timediff = diff.getTime();

                var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));

                timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

                var days = Math.floor(timediff / (1000 * 60 * 60 * 24));

                var days = (parseInt(weeks) * 7) + parseInt(days);

                if (days > 90) {
                    alert('You can not select more than 3 months period');
                    return false;
                }
            }
        }
        ThailandCalendar._input.value = idate;
        ThailandCalendar.hideCalendar();
    },
    hideCalendar: function () {
        ThailandCalendar.setDisplay(ThailandCalendar._cal, 'none');
    },
    showCalendar: function (_obj, evt) {
        this._cal.innerHTML = '';
        this._nextE = 0;
        this.setSelectdate();
        this.setDisplay(this._cal, 'block');
        this.createbutton();
        this.createCalendar();
        var e = evt || window.event;
        this._x = e.pageX || e.clientX;
        this._y = e.pageY || e.clientY;
        this.setLeft(this._cal, this._x);
        this.setTop(this._cal, this._y);
        this.setPosition(this._cal, 'absolute');
    },

    addLoadEvent: function (func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        }
        else {
            window.onload = function () {
                oldonload();
                func();
            }
        }
    },
    setClass: function (element, classname) {
        element.className = classname;
    },
    setAlign: function (element, alignment) {
        element.align = alignment;
    },
    setVAlign: function (element, alignment) {
        element.vAlign = alignment;
    },
    setMouseEvent: function (element) {
        element.onmouseover = function () { element.style.backgroundColor = '#DCE4F9'; }
        element.onmouseout = function () { element.style.backgroundColor = ''; }
        //	    Event.observe(element,'mouseover',function(){element.style.backgroundColor='';});
        //	    Event.observe(element,'mouseout',function(){element.style.backgroundColor='';});
    },
    setCursor: function (element) {
        element.style.cursor = 'pointer';
    },
    setCellPadding: function (element, _v) {
        element.cellPadding = _v;
    },
    setCellSpacing: function (element, _v) {
        element.cellSpacing = _v;
    },
    setID: function (element, id) {
        element.setAttribute('id', id);
    },
    setTop: function (element, top) {
        element.style.top = top + 'px';
    },
    setLeft: function (element, left) {
        element.style.left = left + 'px';
    },
    setDisplay: function (element, display) {
        element.style.display = display;
    },
    setPosition: function (element, position) {
        element.style.position = position;
    },
    getLeft: function (element) {
        return parseInt(element.style.left.replace('px', ''));
    },
    getOfsetWidth: function (element) {
        return element.offsetWidth;
    },
    setWidth: function (element, width) {
        element.style.width = width + 'px';
    },
    setHeight: function (element, height) {
        element.style.height = height + 'px';
    },
    setBackgroundColor: function (element, bg) {
        element.style.backgroundColor = bg;
    }
}
ThailandCalendar.addLoadEvent(ThailandCalendar.initialize);
ThailandCalendar.addLoadEvent(ThailandCalendar.createEvent);






