function getDaysInMonth(year, month) {
return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
}

function getDayOfWeek(year, month, day) {
var date = new Date(year,month-1,day)
return date.getDay();
}
function getCurrentYear() {
var year = new Date().getYear();
if(year < 1900) year += 1900;
return year;
}
function getCurrentMonth() { return new Date().getMonth() + 1;} 
function getCurrentDay() { return new Date().getDate();}

function CalendarControl() {

	var calendarId = 'CalendarControl';
	var currentYear = 0;
	var currentMonth = 0;
	var currentDay = 0;
	
	var selectedYear = 0;
	var selectedMonth = 0;
	var selectedDay = 0;
	
	var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	this.crtDateField = null;
	
	this.startTimer = function(){	
		this.timerID = setInterval('calendarControl.checkHide()',200);
	}
	this.checkHide=function(){	
		if(window.focusElement !== this.crtDateField) this.hide()			
	}	
	
	this.clearDate = function() {
	this.crtDateField.value = '';
	this.hide();
	}

  this.setDate = function (year, month, day) {
    if (this.crtDateField) {
		xd=new xDate();
		xd.day=day
		xd.month=month
		xd.year=year		
		this.crtDateField.focus();
		this.crtDateField.value = xd.toString();		
		if(this.crtDateField.onchange)this.crtDateField.onchange()
		this.hide();		
    }
    return;
  }

  this.changeMonth = function (change) {
  	currentYear = xval(currentYear)
    currentMonth += change;
    currentDay = 0;
    if(currentMonth > 12) {
      currentMonth = 1;
      currentYear++;
    } else if(currentMonth < 1) {
      currentMonth = 12;
      currentYear--;
    }

    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  this.changeYear = function (change) {
  	currentYear = xval(currentYear)
    currentYear += change;
    currentDay = 0;
    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }


  function calendarDrawTable() {

    var dayOfMonth = 1;
    var validDay = 0;
    var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
    var daysInMonth = getDaysInMonth(currentYear, currentMonth);
    var css_class = null; //CSS class for each day

    var table = "<table style='border-collapse:separate' cellspacing='0' cellpadding='0' border='0'>";
    table = table + "<tr class='cc_header'>";

	table = table + "  <td colspan='1' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'>&lt;</a> <a href='javascript:changeCalendarControlYear(-1);'>&laquo;</a></td>";
    table = table + "  <td colspan='5' class='cc_title'>" + months[currentMonth-1] + "&nbsp;" + currentYear + "</td>";
    table = table + "  <td colspan='1' class='next'><a href='javascript:changeCalendarControlYear(1);'>&raquo;</a> <a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";


    table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

    for(var week=0; week < 6; week++) {
      table = table + "<tr>";
      for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
        if(week == 0 && startDayOfWeek == dayOfWeek) {
          validDay = 1;
        } else if (validDay == 1 && dayOfMonth > daysInMonth) {
          validDay = 0;
        }

        if(validDay) {
          if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
            css_class = 'current';
          } else if (dayOfWeek == 0 || dayOfWeek == 6) {
            css_class = 'weekend';
          } else {
            css_class = 'weekday';
          }

          table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
//"          
          dayOfMonth++;
        } else {
          table = table + "<td class='empty'>&nbsp;</td>";
        }
      }
      table = table + "</tr>";
    }
    table = table + "<tr class='cc_header'><th colspan='7' style='padding: 1px;text-align:center;'><a href='javascript:setCalendarControlDate("+getCurrentYear()+","+getCurrentMonth()+","+getCurrentDay()+");'>Today</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
//    table = table + "<tr class='cc_header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
    table = table + "</table>";

    return table;
  }
  
  this.show = function (field) {
    can_hide = 0;  
    // If the calendar is visible and associated with this field do not do anything.
    if (this.crtDateField == field) {
      return;
    } else {
      this.crtDateField = field;
    }
    
	if(this.crtDateField._calendarOpen==undefined)linkEventPreserve(this.crtDateField,"keypress","if(event.keyCode==27) calendarControl.hide();	")
	this.crtDateField._calendarOpen=true
	
	this.startTimer();

    if(this.crtDateField) {
      try {        
        d= new xDate(this.crtDateField.value)
        d.parse();
        selectedDay = d.day;
        selectedMonth = d.month;
        selectedYear = d.year;
      } catch(e) {}
    }

    if (!(selectedYear && selectedMonth && selectedDay)) {
      selectedMonth = getCurrentMonth();
      selectedDay = getCurrentDay();
      selectedYear = getCurrentYear();
    }

    currentMonth = selectedMonth;
    currentDay = selectedDay;
    currentYear = selectedYear;

    if(document.getElementById){

      calendar = document.getElementById(calendarId);
      calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

      $(calendarId).style.display='inline';

	ap = absolutePosition(this.crtDateField);
	
      $(calendarId).style.left= ap.x ;
      $(calendarId).style.top= (ap.y+this.crtDateField.offsetHeight) ;
 
    }
    setTimeout( "if(calendarControl.crtDateField)calendarControl.crtDateField.focus()",500);
    window.focusElement = this.crtDateField
  }
  this.hide = function () {
    if(this.crtDateField) {
      $(calendarId).style.display ='none';
      this.crtDateField._calendarOpen=false
      this.crtDateField = null;
      clearInterval(this.timerID);
    }
  }

  this.visible = function () {
    return this.crtDateField
  }

  this.can_hide = can_hide;
  var can_hide = 0;
  document.write("<div id='CalendarControl' ></div>");
}


var calendarControl = new CalendarControl();

function showCalendarControl(textField) { calendarControl.show(textField);}
function clearCalendarControl() { calendarControl.clearDate();}
function hideCalendarControl() {
  if (calendarControl.visible())  calendarControl.hide();  
}
function setCalendarControlDate(year, month, day) {  calendarControl.setDate(year, month, day);}
function changeCalendarControlYear(change) {  calendarControl.changeYear(change);}
function changeCalendarControlMonth(change) {  calendarControl.changeMonth(change);}

function xDate(dateStr,fmt){
	if(fmt==undefined) fmt = xDateFormat;
	this.fmt=fmt;
	this.dateStr=dateStr;	

	var monthsEn = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	var monthsRo = ['ian','feb','mar','apr','mai','iun','iul','aug','sep','oct','nov','dec'];
	this.months = monthsEn;

	this.fmtSep= this.fmt.replace(/[\dqwertyuiopasdfghjklzxcvbnm]/gi,'').substr(0,1);
	if(this.fmtSep== undefined) _isDate=false
	if(this.fmtSep.replace(/[./-]/g,'')!=='') _isDate=false
	this.fmts =fmt.split(this.fmtSep)
	
	this.parse = function(){
		var _isDate=true
		
		var seps= this.dateStr.replace(/[\dqwertyuiopasdfghjklzxcvbnm]/gi,'');
		if(seps.length!==2) _isDate=false
		
		var sep = seps.substr(0,1);	
		var grps =this.dateStr.split(sep);		
		
		for (var i = 0; i < 3; i++){
			switch(this.fmts[i].toLowerCase()){
			case 'd':
				var day= grps[i]
				break;
			case 'm':
				var month= grps[i]
				break;
			case 'y':
				var year= grps[i];
				break;
			}	 
		} 
		
		if(day.match(/\D/)) _isDate=false		
		if(year.match(/\D/)) _isDate=false
		if(month.match(/\D/)) {
			var found = false;
			for (var i = 0; i < this.months.length; i++){
				if(month.toLowerCase()==this.months[i].toLowerCase()) { found=true ; month=i+1; break;}
			}
			if(!found)  _isDate=false
		}else{
			month=month*1;	
			if(month>12) _isDate=false
		}
		day=day*1; 
		year=year*1;
		
		if(day>getDaysInMonth(year, month)) _isDate=false
	
		this.day=day;
		this.month=month;
		this.year=year;
		
		if(this.year<70) this.year=2000+this.year
		
		return _isDate;
		
	}
	
	this.toString = function(){
		if(this.dateStr) 
			if(!this.parse()) return '';
				
		_day 	= (this.day < 10) ? "0" + this.day : this.day;
		_month = (this.month < 10)?"0" + this.month : this.month;
		
		var _date=''; 
		var fmtSep=this.fmtSep;
		for (var i = 0; i < 3; i++){
			if(i==2) fmtSep='';
			if(this.fmts[i].toLowerCase()=='d') _date+= _day+ fmtSep;
			if(this.fmts[i]=='m') _date+= _month + fmtSep;
			if(this.fmts[i]=='M') _date+= this.months[_month-1] + fmtSep;
			if(this.fmts[i].toLowerCase()=='y') _date+= this.year + fmtSep;
		} 
		
		return _date;
	}

}
function cDate(dateStr){
	if(!window._xDate) window._xDate= new xDate();
	window._xDate.dateStr=dateStr;
	return window._xDate.toString();
}
function numDate(dateStr){
	if(!window._xDate) window._xDate= new xDate();
	window._xDate.dateStr=dateStr;
	window._xDate.parse()
	return window._xDate.year+''+(window._xDate.month<10?'0'+window._xDate.month:window._xDate.month)+''+(window._xDate.day<10?'0'+window._xDate.day:window._xDate.day);
}
function dateNow(){
	var d = new Date()
	if(!window._xDate) window._xDate= new xDate();
	window._xDate.day =d.getDate();
	window._xDate.month =d.getMonth()+1;
	window._xDate.year =d.getFullYear();
	return window._xDate.toString();
}
function date_old ( format, timestamp ) {
    // http://kevin.vanzonneveld.net
    // *     example 2: date('F j, Y, g:i a', 1062462400);
    // *     returns 2: 'September 2, 2003, 2:26 am'
 
    var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];
 
    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                t = f.l(); return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },
 
        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
 
                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{
 
                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },
 
        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },
 
        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            //o not supported yet
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },
 
        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            //u not supported yet
 
        // Timezone
            //e not supported yet
            //I not supported yet
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            //Z not supported yet
 
        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            //r not supported yet
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };
 
    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }
 
        return ret;
    });
}