MyCalendarEngine = Class.create({
    Version: '1.0',

    initialize: function() {
        this.TargetDiv = 'divCalendar102938';
        this.DivCreated = false;
        this.AttachedField = null;
        this.DivPosition = [0,0];
        this.tmpColorBackground = "";
        this.options = {};
        this.dataInitial = "";
        this.visible = false;
        this.isProcessing = false;
    },

    show: function (target) {
        this.visible = true;
        this.AttachedField = target;
        this.DivPosition = this._findPos( this.AttachedField );
        this.dataInitial = this._getDate(this.AttachedField.value );
        this._displayDropDownsIE6(false);
        this._draw( this.dataInitial );
        document.getElementById(this.TargetDiv).style.top = this.DivPosition[1] + 'px';
        document.getElementById(this.TargetDiv).style.left = this.DivPosition[0] + 'px';
    },

    hide: function () {
        this.visible = false;
        document.getElementById(this.TargetDiv).style.top = '-5000px';
        document.getElementById(this.TargetDiv).style.left = '-5000px';
        this._displayDropDownsIE6(true);
    },

    init: function () {
         if (this.DivCreated == false) {
            this.DivCreated = true;
            while (document.getElementById(this.TargetDiv)) {
                this.TargetDiv = 'divCalendar' + Math.ceil(Math.random() * 1000);
            }
/*            
            var theString = "<div id='" + this.TargetDiv + "' style='position: absolute; z-Index:100; left: -5000px; top: -5000px;'></div>";
            if ( document.body.insertAdjacentHTML ) {
                document.body.insertAdjacentHTML( 'beforeEnd', theString );
            } else if( typeof( document.body.innerHTML ) != 'undefined' ) {
                document.body.innerHTML += theString;
            }
*/
            var z = new Element('div', {'id': this.TargetDiv, 'style': 'position: absolute; z-Index:100; left: -5000px; top: -5000px;'});
            document.body.appendChild(z);
        }
        Event.observe(document, 'mousedown', this._onMouseDown.bind(this));
        Event.observe(document, 'keydown', this._onKeyDown.bind(this));
    },

    change: function (newdate) {
        if (!this.isProcessing) {
            this.isProcessing = true;
            if (newdate.getMonth) {
                this._draw( newdate );
            } else {
                this._draw( this._getDate(newdate) );
            }
            this.isProcessing = false;
        }
        return false;
    },

    mouseOver: function (care) {
        this.tmpColorBackground = care.style.backgroundColor;
        care.style.backgroundColor = "#cccccc";
    },

    mouseOut: function (care) {
        care.style.backgroundColor = this.tmpColorBackground;
    },

    returnDate: function (textdata) {
        var splitted = (textdata) ? textdata.toString().split("/") : new Array();
        var day = splitted[2];
        var month = splitted[1];
        var year = splitted[0];
        day = (day < 10) ? ("0" + day) : day;
        month = (month < 10) ? ("0" + month) : month;
        this.AttachedField.value =  day + '/' + month + '/' + year;
        $(this.AttachedField).removeClassName('emptyValueField');
        this.hide();
    },

    clearDate: function () {
        this.AttachedField.value =  '';
        $(this.AttachedField).removeClassName('emptyValueField');
        this.hide();
    },

    //private
    _displayDropDownsIE6: function(show) {
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            var versiuneIE = new Number(RegExp.$1);
        }
        if (versiuneIE && (versiuneIE < 7)) {
            var elements = $$('select');
            if (show) {
                for (var i=0; i<elements.length; i++) {
                    elements[i].style.visibility = 'visible';
                }
            } else {
                for (var i=0; i<elements.length; i++) {
                    elements[i].style.visibility = 'hidden';
                }
            }
        }
    },

    _onMouseDown: function(event) {
        var element = event.element();
        if ((this.visible) && (element.identify() != this.TargetDiv) && (!element.descendantOf(this.TargetDiv))) {
            this.hide();
        }
    },

    _onKeyDown: function(ev) {
        if (this.visible) {
            switch (ev.keyCode) {
                case Event.KEY_ESC:
                case Event.KEY_TAB:
                    this.hide();
                break;
            }
        }
    },

    _getDate: function(textdata) {
        var splitted = (textdata) ? textdata.toString().split("/") : new Array();
        var varData = (splitted.length == 3) ? new Date(splitted[2], splitted[1]-1, splitted[0]) : null;
        return varData;
    },

    _fGetXY: function(a) {
        var p=[0,0],tn;
        while(a) {
            tn = a.tagName.toUpperCase();
            p[0] += a.offsetLeft-(!KO3&&tn=="DIV"&&a.scrollLeft?a.scrollLeft:0);
            p[1] += a.offsetTop-(!KO3&&tn=="DIV"&&a.scrollTop?a.scrollTop:0);
            if (tn == "BODY") break;
            a = a.offsetParent;
        }
        return p;
    },

    _findPos: function (obj) {
        // merge doar la onload in firefox
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
        } else {
            curleft = (obj.x) ? obj.x : 0;
            curtop = (obj.y) ? obj.y : 0;
        }
        return [curleft, curtop];
    },

    _draw: function (date) {
        var stilTablou = 'background-color:#ffffff;color:#000000;width:166px;border: 1px solid #000000;font-size:12px;';
        var stilTop = 'background-color:#e0e0e0;color:#0000ee;height:20px;font-size:12px;text-align:center;font-weight:bold;';
        var stilBottom = 'cursor:pointer;cursor:hand;background-color:#e0e0e0;font-size:11px;text-align:center;color:#01528d;font-weight:bold;height:25px;';
        var stilDay = 'cursor:pointer;cursor:hand;background-color:#f0f0f0;color:#01528d;font-size:12px;text-align:center;';
        var stilWeekEnd = 'cursor:pointer;cursor:hand;background-color:#bababa;color:#01528d;font-size:12px;text-align:center;';
        var stilTheDayWeekEnd = 'cursor:pointer;cursor:hand;background-color:#bababa;color:#01528d;font-size:12px;text-align:center;font-weight:bold;border:1px solid #000000;'
        var stilTheDay = 'cursor:pointer;cursor:hand;background-color:#ffffff;color:#01528d;font-size:12px;text-align:center;font-weight:bold;border:1px solid #000000;';
        var stilSelectedDay = 'cursor:pointer;cursor:hand;background-color:#ffffff;color:#01528d;font-size:12px;text-align:center;border:1px solid #01528d;';

        var selectedDay = 0;

        //If no parameter is passed use the current date.
        if (date == null) {
            date = new Date();
        } else {
            if ((this.dataInitial != null) && (this.dataInitial.getMonth() == date.getMonth()) && (this.dataInitial.getFullYear() == date.getFullYear()))
                selectedDay = this.dataInitial.getDate();
        }
        var currentDate = new Date();
        var day = currentDate.getDate();
        var month = date.getMonth();
        var year = date.getFullYear();
        if (!((currentDate.getMonth() == month) && (currentDate.getFullYear() == year))) {
            day=32; //nu afiseaza
        }
        var months = new Array('Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie');
        var zile = new Array('Lu','Ma','Mi','Jo','Vi','Sâ','Du');

        var this_month = new Date(year, month, 1);
        var next_month = new Date(year, month + 1, 1);
         
        //Find out when this month starts and ends.
        var first_week_day = this_month.getDay();
        first_week_day = (first_week_day == 0) ? 7 : first_week_day;
        var days_in_this_month = Math.round((next_month.getTime() - this_month.getTime()) / (1000 * 60 * 60 * 24));
         
        var calendar_html = '<table style="'+stilTablou+'">';
        //inchide + titlu
        //calendar_html += '<tr><td colspan="6" style="'+stilBottom+';text-align:left;">Calendar</td><td style="'+stilBottom+';text-align:center;" onclick="myCalendar.hide();">X</td></tr>';
        //header tabel
        calendar_html += '<tr><td colspan="7" style="'+stilTop+';vertical-align:top;"><nobr>';
        calendar_html += '<input style="font-size:10px;width: 22px; height:22px;padding:0;margin:0;" type="button" value="&lt;" onclick="myCalendar.change(new Date('+year+','+ (month - 1)+', 1));"/>';
        calendar_html += '<select style="font-size:11px;color:#000000;height:22px;padding:0;margin:0;" id="selectCalendar" size="1" onchange="myCalendar.change(get_selected(\'selectCalendar\'))">';
        var i=0;
        var tmpmonth = currentDate.getMonth()+1;
        var tmpyear = currentDate.getFullYear();
        var selected = '';
        var selectat = false;
        for (i=0; i<24; i++) {
            selected = ((tmpmonth-1 == month) && (tmpyear == year))? 'selected': '';
            calendar_html += '<option value="1/'+tmpmonth+'/'+tmpyear+'" '+selected+'>' + months[tmpmonth-1] + ' ' + tmpyear + '</option>';
            tmpmonth++;
            if (tmpmonth == 13) {
                tmpmonth = 1;
                tmpyear++;
            }
            if (selected != '') {
                selectat = true;
            }
        }
        if (!selectat) {
            calendar_html += '<option value="1/'+(month+1)+'/'+year+'" selected>' + months[month] + ' ' + year + '</option>';
        }
        calendar_html += '</select>';
        calendar_html += '<input style="font-size:10px;width: 22px; height:22px;padding:0;margin:0;" type="button" value="&gt;" onclick="myCalendar.change(new Date('+year+','+ (month + 1)+', 1));"/>';
        calendar_html += '</nobr></td></tr>';
        //header zile
        calendar_html += '<tr>';
        var stilul = '';
        for (i=0; i<7; i++) {
            stilul = ((i == 5) || (i == 6)) ? stilWeekEnd : stilDay;
            calendar_html += '<td style="'+stilul+'color:#000;">'+zile[i]+'</td>';
        }
        calendar_html += '</tr>';
        var noRows = 0;
        if (first_week_day != 1){
            calendar_html += '<tr>';
            noRows++;
        }
        //Fill the first week of the month with the appropriate number of blanks.
        var week_day = 0;
        for (week_day = 1; week_day < first_week_day; week_day++) {
            stilul = (week_day == 6)? stilWeekEnd : stilDay;
            calendar_html += '<td style="'+stilul+'">&nbsp;</td>';
        }
        week_day = first_week_day-1;
        var day_counter = 1;
        var gata = false;
        for (day_counter = 1; day_counter <= days_in_this_month; day_counter++) {
            week_day %= 7;
            if (week_day == 0) {
                if ((first_week_day != 1) || gata) {
                    calendar_html += '</tr>';
                    gata = true;
                }
                calendar_html += '<tr>';
                noRows++;
            }
            stilul = ((week_day==6)||(week_day==5)) ? ((day == day_counter)? stilTheDayWeekEnd : stilWeekEnd) : ((day == day_counter) ? stilTheDay : stilDay);
            stilul = (selectedDay == day_counter) ? stilSelectedDay : stilul;
            calendar_html += '<td style="'+stilul+'" onmouseover="myCalendar.mouseOver(this);" onmouseout="myCalendar.mouseOut(this)" onclick="myCalendar.returnDate(\'' + year + '/' + (month + 1) + '/' + day_counter + '\');">' + day_counter + '</td>';
            week_day++;
        }
        for (i = week_day; i < 7; i++) {
            stilul = ((i == 5) || (i == 6))? stilWeekEnd : stilDay;
            calendar_html += '<td style="'+stilul+'">&nbsp;</td>';
        }

        calendar_html += '</tr>';
/*        if (noRows < 6) {
            calendar_html += '<tr><td colspan="7" style="'+stilBottom+';">&nbsp;</td></tr>';
          }
*/
        //ziua curenta
        calendar_html += '<tr><td colspan="7" style="'+stilBottom+';" onclick="myCalendar.returnDate(\'' + currentDate.getFullYear() + '/' + (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '\');">Astăzi, ' + currentDate.getDate() + ' ' + months[currentDate.getMonth()] + '</td></tr>';
        //goleste + inchide
        calendar_html += '<tr><td colspan="7" style="'+stilBottom+';"><input style="font-size:11px;height:22px;padding:0;margin:0;margin-right:20px;" type="button" value="Şterge" onclick="myCalendar.clearDate();"/><input style="font-size:11px;height:22px;padding:0;margin:0;" type="button" value="Închide" onclick="myCalendar.hide();"/></td></tr>';
        calendar_html += '</table>';
         
        //Display the calendar.
        document.getElementById(this.TargetDiv).innerHTML = calendar_html;
    }
});

var myCalendar = new MyCalendarEngine();

Event.observe(window, 'load', function() { myCalendar.init() });

