//Javascript name: My Date Time Picker
//Date created: 16-Nov-2003 23:19
//Scripter: TengYong Ng
//Website: http://www.rainforestnet.com
//Copyright (c) 2003 TengYong Ng
//FileName: DateTimePicker.js
//Version: 1.9
//Contact: contact@rainforestnet.com
// Note: Permission given to use and modify this script in ANY kind of applications if
//       header lines are left unchanged.
//Date changed: 24-Dec-2007 by Burgsoft (Holland)
//Changed: Year picker as drop down. Code optimised. Tables filled with blank fields as needed.
//Known (non fatal) issue: javascript remains running after month or year select

//detect whether the click is on panel or outside
var click_on_panel_state=false;
var panel_open_for_firsttime=false;

//Global variables
var winCal;
var dtToday=new Date();
var Cal;

// English
var MonthName=["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var MonthName_Short=["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var WeekDayName1=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var WeekDayName2=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
/*
// Dutch
var MonthName=["januari", "februari", "maart", "april", "mei", "juni","juli", 
	"augustus", "september", "oktober", "november", "december"];
var WeekDayName1=["zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"];	
var WeekDayName2=["maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag","zondag"];	
*/
var exDateTime;//Existing Date and Time
var selDate;//selected date. version 1.7


//Configurable parameters
var cnTop="200";//top coordinate of calendar window.
var cnLeft="500";//left coordinate of calendar window
var WindowTitle ="DateTime Picker";//Date Time Picker title.
var WeekChar=2;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed.
var CellWidth=30;//Width of day cell.
var DateSeparator="/";//Date Separator, you can change it to "/" if you want.
var TimeMode=24;//default TimeMode value. 12 or 24

var ShowLongMonth=true;//Show long month name in Calendar header. example: "January".
var ShowMonthYear=true;//Show Month and Year in Calendar header.
var MonthYearColor="#cc0033";//Font Color of Month and Year in Calendar header.
var WeekHeadColor="#DED6D1";//Background Color in Week header.
var SundayColor="white";//Background color of Sunday.
var SaturdayColor="white";//Background color of Saturday.
var WeekDayColor="white";//Background color of weekdays.
var FontColor="blue";//color of font in Calendar day cell.
var TodayColor="#white";//Background color of today.
var SelDateColor="#078FF5";//Backgrond color of selected date in textbox.
var YrSelColor="#ffffff";//color of font of Year selector.
var MthSelColor="#ffffff";//color of font of Month selector if "MonthSelector" is "arrow".
var ThemeBg="";//Background image of Calendar window.
var PrecedeZero=true;//Preceding zero [true|false]
var MondayFirstDay=false;//true:Use Monday as first day; false:Sunday as first day. [true|false]  //added in version 1.7
//end Configurable parameters
//end Global variable

function NewCal(pCtrl, pFormat, posXY) {

	Cal=new Calendar(dtToday);
	if (pCtrl!=null) Cal.Ctrl=pCtrl;
	if (pFormat!=null) Cal.Format=pFormat.toUpperCase();
	
	exDateTime=document.getElementById(pCtrl).value;
    
    //Parse existing Date String
	if (exDateTime!="")	{
		var Sp1;//Index of Date Separator 1
		var Sp2;//Index of Date Separator 2 
		var tSp1;//Index of Time Separator 1
		var tSp1;//Index of Time Separator 2
		var strMonth;
		var strDate;
		var strYear;
		var intMonth;
		var YearPattern;
		var winHeight;
		//parse month
		Sp1=exDateTime.indexOf(DateSeparator,0)
		Sp2=exDateTime.indexOf(DateSeparator,(parseInt(Sp1)+1));
		
		var offset=parseInt(Cal.Format.toUpperCase().lastIndexOf("M"))-parseInt(Cal.Format.toUpperCase().indexOf("M"))-1;
		if ((Cal.Format.toUpperCase()=="DDMMYYYY") || (Cal.Format.toUpperCase()=="DDMMMYYYY")) {
			if (DateSeparator==""){
				strMonth=exDateTime.substring(2,4+offset);
				strDate=exDateTime.substring(0,2);
				strYear=exDateTime.substring(4+offset,8+offset);
			}else{
				strMonth=exDateTime.substring(Sp1+1,Sp2);
				strDate=exDateTime.substring(0,Sp1);
				strYear=exDateTime.substring(Sp2+1,Sp2+5);
			}
		}else if ((Cal.Format.toUpperCase()=="MMDDYYYY") || (Cal.Format.toUpperCase()=="MMMDDYYYY")) {
			if (DateSeparator=="") {
				strMonth=exDateTime.substring(0,2+offset);
				strDate=exDateTime.substring(2+offset,4+offset);
				strYear=exDateTime.substring(4+offset,8+offset);
			}else{
				strMonth=exDateTime.substring(0,Sp1);
				strDate=exDateTime.substring(Sp1+1,Sp2);
				strYear=exDateTime.substring(Sp2+1,Sp2+5);
			}
		}else if ((Cal.Format.toUpperCase()=="YYYYMMDD") || (Cal.Format.toUpperCase()=="YYYYMMMDD")) {
			if (DateSeparator==""){
				strMonth=exDateTime.substring(4,6+offset);
				strDate=exDateTime.substring(6+offset,8+offset);
				strYear=exDateTime.substring(0,4);
			}else{
				strMonth=exDateTime.substring(Sp1+1,Sp2);
				strDate=exDateTime.substring(Sp2+1,Sp2+3);
				strYear=exDateTime.substring(0,Sp1);
			}
		}//endif

		if (isNaN(strMonth)) intMonth=Cal.GetMonthIndex(strMonth);
		else intMonth=parseInt(strMonth,10)-1;	
		if ((parseInt(intMonth,10)>=0) && (parseInt(intMonth,10)<12)) Cal.Month=intMonth;
		if ((parseInt(strDate,10)<=Cal.GetMonDays()) && (parseInt(strDate,10)>=1)) Cal.Date=strDate;

		YearPattern=/^\d{4}$/;
		if (YearPattern.test(strYear)) Cal.Year=parseInt(strYear,10);
	}//endif

	selDate=new Date(Cal.Year,Cal.Month,Cal.Date);//version 1.7
	
	//modified by Tuan    
    //remove the 'DIV' if it exists then re-create it again (at another position)
    if (document.getElementById('timepicker')) document.body.removeChild(document.getElementById('timepicker'));
	//create a DIV to hold the Calendar instead of popup window
    var panel=document.createElement('div');
    panel.style.zIndex='1';
    panel.style.width='auto';
    panel.style.height='auto';
    panel.style.position='absolute';
    panel.id='timepicker';
    panel.style.left=posXY[0]+'px'; //'600px';
    panel.style.top=posXY[1]+'px'; //'400px';
    panel.style.backgroundColor='#ffffff';
    panel.style.border='1px #000000 solid';
    panel.style.padding='1px';
    document.body.appendChild(panel);

    //this is fantastic coding by Tuan ***** (5 stars)
    //catch the click event on the panel
    //since this click is on panel, nothing should happen in the body event
    //otherwise, will close the panel
    set_panel_firsttime_open(true);
    document.body.onclick=function(e) {
        panel.onclick=function(e) {
            set_click_on_panel_state(true);
        };
        
        if (!get_click_on_panel_state() && !get_panel_firsttime_open()) {
            //there is a panel open and it is not first time
            if (document.getElementById('timepicker')) 
                document.body.removeChild(document.getElementById('timepicker'));
        }//endif
        set_click_on_panel_state(false);
        set_panel_firsttime_open(false);
    };
            
	RenderPanel();
}//func

//detect whether the panel is just initiated
function set_panel_firsttime_open(new_state) {
    panel_open_for_firsttime=new_state;
}//set_panel_firsttime_open

//return the state of panel first time open
function get_panel_firsttime_open() {
    return panel_open_for_firsttime;
}//get_panel_firsttime_open

//set the state of click
function set_click_on_panel_state(new_state) {
    click_on_panel_state=new_state;
}//set_click_on_panel_state

//return the current state
function get_click_on_panel_state() {
    return click_on_panel_state;
}//get_click_on_panel_state

//move prev or next month
function changeMonth(direction, num) {
    if (direction=="prev") DecMonth();
    else if (direction=="next") IncMonth();
    else if (direction=="jump") SwitchMth(num);
    else return;
    
    //re-render the panel
    RenderPanel();
}//changeMonth

//move prev or next year
function changeYear(direction, num) {
    if (direction=="prev") DecYear();
    else if (direction=="next") IncYear();
    //else if (direction=="jump") SwitchMth(num);
    else return;
    
    //re-render the panel
    RenderPanel();
}//changeYear


//return the selected date to the right text field
function returnDate(theDate) {
    //set value
    document.getElementById(Cal.Ctrl).value=theDate;
    //remove the panel and reset the object
    Cal=null;
    if (document.getElementById('timepicker')) document.body.removeChild(document.getElementById('timepicker'));
}//returnDate

//detect and return mouse X and Y positioning
function getMouseXY(e) {
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    } else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }//endif

    return new Array(posx, posy);
}//getMouseXY

//generate a table of month for user to go directly to a month
function buildMonthTable() {
    var output = '<link href="/assets/property_form/js/datetimepicker.css" rel="stylesheet" type="text/css" />';
    output += '<div id="datetimepicker_monthtable"><ul>';
    for (var i=0; i<MonthName_Short.length; i++) {
        output += '<li onclick="changeMonth(\'jump\', '+ i +');">'+ MonthName_Short[i] +'</li>';
    }
    output += '</ul></div>';
    
    return output;
}

//write data to the panel
function RenderPanel() {
    var vCalHeader;
    var vCalData;
    var vCalTime;
    var i;
    var j;
    var SelectStr;
    var vDayCount=0;
    var vFirstDay;
    
    //hold everything
    var panel=document.getElementById('timepicker');
    var paneContent="";
   
    //header
    paneContent="<table border='0' cellpadding='1' cellspacing='3' width='200px' style='background-color:#ffffff; font-family:Arial; font-size:12px; font-weight:bold'>";
  
    //put a month table to allow user directly click on
    paneContent += '<tr><td colspan="7" width="100%">'+ buildMonthTable() +'</td></tr>';
  
    //Calendar header shows Month and Year
    if ((ShowMonthYear)&&(Cal.Scroller=="DROPDOWN")) {
        //add prev and next month image
        paneContent+='<tr><td colspan="7" width="100%"><table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin:0; margin-bottom:3px">';
        paneContent+='<tr><td width="20%" valign="top"><p style="margin:0; margin-top:4px; margin-left:4px"><img onclick="changeYear(\'prev\');" style="cursor:pointer;" src="/assets/property_form/images/prev_year.png" border="0" vspace="0" hspace="4"><img onclick="changeMonth(\'prev\');" style="cursor:pointer;" src="/assets/property_form/images/cal_prevMonth.gif" border="0" vspace="0" hspace="4"></p></td>';
        paneContent+='<td width="60%" align="center" style="color:'+MonthYearColor+'">'+Cal.GetMonthName(ShowLongMonth)+' '+Cal.Year+'</td>';
        paneContent+='<td width="20%" valign="top"><p style="margin:0; margin-top:4px; margin-right:4px; text-align:right;"><img onclick="changeMonth(\'next\');" style="cursor:pointer;" src="/assets/property_form/images/cal_nextMonth.gif" border="0" vspace="0" hspace="4"><img src="/assets/property_form/images/next_year.png" border="0" onclick="changeYear(\'next\');" style="cursor:pointer;" vspace="0" hspace="4"></p></td></tr>';
        paneContent+='</table></td></tr>';
    }//endif
        
    //Week day header
    paneContent+='<tr style="background-color:'+WeekHeadColor+'">';
    
    var WeekDayName=new Array();//Added version 1.7
    if (MondayFirstDay==true) WeekDayName=WeekDayName2;
    else WeekDayName=WeekDayName1;
    
    for (i=0;i<7;i++) {
        paneContent+="<td width="+CellWidth+" align='center'>"+WeekDayName[i].substr(0,WeekChar)+"</td>";
    }//for
    
    paneContent+="</tr>";
    
    //Calendar detail
    CalDate=new Date(Cal.Year,Cal.Month);
    CalDate.setDate(1);
    vFirstDay=CalDate.getDay();
    
    //Added version 1.7
    if (MondayFirstDay==true) {
        vFirstDay-=1;
        if (vFirstDay==-1)
            vFirstDay=6;
    }//endif
        
    //Added version 1.7
    //place some empty TD to match with the month weekdays
    paneContent+="<tr>";
    for (var i=0;i<vFirstDay;i++) {
        paneContent+='<td align="center">&nbsp;</td>';
        vDayCount++;
    }//for

    //Added version 1.7
    for (var j=1;j<=Cal.GetMonDays();j++) {
        if((vDayCount%7==0)&&(j > 1)) paneContent+="<tr>\n";
                
        if ((j==dtToday.getDate())&&(Cal.Month==dtToday.getMonth())&&(Cal.Year==dtToday.getFullYear())) {
            //Highlight today's date
            paneContent+='<td align="center"><a style="color:crimson; font-weight:bold" href="javascript:returnDate(\''+Cal.FormatDate(j)+'\');">' + j + '</a></td>';
        }else{
            //Normal day
            paneContent+='<td align="center"><a style="color:#000000" href="javascript:returnDate(\''+Cal.FormatDate(j)+'\');">' + j + '</a></td>';
        }//endif
        
        //detect to end the row
        vDayCount=vDayCount+1;
        if((vDayCount%7==0)&&(j<Cal.GetMonDays())) {
            paneContent+='</tr>';
        }//endif
    }//for
    
    //finish the table proper
    if(!(vDayCount%7) == 0) {
        while(!(vDayCount % 7) == 0) {
            paneContent+='<td>&nbsp;</td>';
            vDayCount=vDayCount+1;
        }//while
        
        paneContent+='</tr>';
    }//endif
        
    //end time picker
    paneContent+="\n</table>\n";

    //assign to panel
    panel.innerHTML=paneContent;
    
    return true;
}//func

function GenCell(pValue,pHighLight,pColor)//Generate table cell with value
{
	var PValue;
	var PCellStr;
	var vColor;
	var vHLstr1;//HighLight string
	var vHlstr2;
	var vTimeStr;
	
	if (pValue==null)
		PValue="";
	else
		PValue=pValue;
	
	if (pColor!=null)
		vColor="bgcolor=\""+pColor+"\"";
	else
		vColor="";	
	if ((pHighLight!=null)&&(pHighLight))
		{vHLstr1="<font class='r'>";vHLstr2="</font>";}
	else
		{vHLstr1="";vHLstr2="";}	
	
	if (Cal.ShowTime)
	{
		vTimeStr=' '+Cal.Hours+':'+Cal.Minutes;
		if (Cal.ShowSeconds)
			vTimeStr+=':'+Cal.Seconds;
		if (TimeMode==12)
			vTimeStr+=' '+Cal.AMorPM;
	}	
	else
		vTimeStr="";		
	if (PValue!="")
		PCellStr="<td "+vColor+" onClick=\"javascript:callback('"+Cal.Ctrl+"','"+Cal.FormatDate(PValue)+"');\">"+vHLstr1+PValue+vHLstr2+"</td>\n";
	else
		PCellStr="<td "+vColor+">&nbsp;</td>\n";
	return PCellStr;
}

function Calendar(pDate,pCtrl)
{
	//Properties
	this.Date=pDate.getDate();//selected date
	this.Month=pDate.getMonth();//selected month number
	this.Year=pDate.getFullYear();//selected year in 4 digits
	this.Hours=pDate.getHours();	
	
	if (pDate.getMinutes()<10)
		this.Minutes="0"+pDate.getMinutes();
	else
		this.Minutes=pDate.getMinutes();
	
	if (pDate.getSeconds()<10)
		this.Seconds="0"+pDate.getSeconds();
	else		
		this.Seconds=pDate.getSeconds();
		
	this.MyWindow=winCal;
	this.Ctrl=pCtrl;
	this.Format="ddMMyyyy";
	this.Separator=DateSeparator;
	this.ShowTime=false;
	this.Scroller="DROPDOWN";
	if (pDate.getHours()<12)
		this.AMorPM="AM";
	else
		this.AMorPM="PM";
	this.ShowSeconds=true;		
}

function GetMonthIndex(shortMonthName)
{
	for (i=0;i<12;i++)
	{
		if (MonthName[i].substring(0,3).toUpperCase()==shortMonthName.toUpperCase())
		{	return i;}
	}
}
Calendar.prototype.GetMonthIndex=GetMonthIndex;

function IncYear()
{	Cal.Year++;}
Calendar.prototype.IncYear=IncYear;

function DecYear()
{	Cal.Year--;}
Calendar.prototype.DecYear=DecYear;

function IncMonth()
{	
	Cal.Month++;
	if (Cal.Month>=12)
	{
		Cal.Month=0;
		Cal.IncYear();
	}
}
Calendar.prototype.IncMonth=IncMonth;

function DecMonth()
{	
	Cal.Month--;
	if (Cal.Month<0)
	{
		Cal.Month=11;
		Cal.DecYear();
	}
}
Calendar.prototype.DecMonth=DecMonth;
	
function SwitchMth(intMth)
{	Cal.Month=intMth;}
Calendar.prototype.SwitchMth=SwitchMth;

function SwitchYear(intYear)
{	Cal.Year=intYear;}
Calendar.prototype.SwitchYear=SwitchYear;

function SetHour(intHour)
{	
	var MaxHour;
	var MinHour;
	if (TimeMode==24)
	{	MaxHour=23;MinHour=0}
	else if (TimeMode==12)
	{	MaxHour=12;MinHour=1}
	else
		alert("TimeMode can only be 12 or 24");		
	var HourExp=new RegExp("^\\d\\d");
	var SingleDigit=new RegExp("\\d");
	//alert(SingleDigit.test(intHour));
	if (SingleDigit.test(intHour))
	{
		intHour="0"+intHour+"";
		//alert(intHour);	
	}	
	if (HourExp.test(intHour) && (parseInt(intHour,10)<=MaxHour) && (parseInt(intHour,10)>=MinHour))
	{	
		if ((TimeMode==12) && (Cal.AMorPM=="PM"))
		{
			if (parseInt(intHour,10)==12)
				Cal.Hours=12;
			else	
				Cal.Hours=parseInt(intHour,10)+12;
		}	
		else if ((TimeMode==12) && (Cal.AMorPM=="AM"))
		{
			if (intHour==12)
				intHour-=12;
			Cal.Hours=parseInt(intHour,10);
		}
		else if (TimeMode==24)
			Cal.Hours=parseInt(intHour,10);	
	}
}
Calendar.prototype.SetHour=SetHour;

function SetMinute(intMin)
{
	var MinExp=new RegExp("^\\d\\d$");
	if (MinExp.test(intMin) && (intMin<60))
		Cal.Minutes=intMin;
}
Calendar.prototype.SetMinute=SetMinute;

function SetSecond(intSec)
{	
	var SecExp=new RegExp("^\\d\\d$");
	if (SecExp.test(intSec) && (intSec<60))
		Cal.Seconds=intSec;
}
Calendar.prototype.SetSecond=SetSecond;

function SetAmPm(pvalue)
{
	this.AMorPM=pvalue;
	if (pvalue=="PM")
	{
		this.Hours=(parseInt(this.Hours,10))+12;
		if (this.Hours==24)
			this.Hours=12;
	}	
	else if (pvalue=="AM")
		this.Hours-=12;	
}
Calendar.prototype.SetAmPm=SetAmPm;

function getShowHour()
{
	var finalHour;
    if (TimeMode==12)
    {
    	if (parseInt(this.Hours,10)==0)
		{
			this.AMorPM="AM";
			finalHour=parseInt(this.Hours,10)+12;	
		}
		else if (parseInt(this.Hours,10)==12)
		{
			this.AMorPM="PM";
			finalHour=12;
		}		
		else if (this.Hours>12)
		{
			this.AMorPM="PM";
			if ((this.Hours-12)<10)
				finalHour="0"+((parseInt(this.Hours,10))-12);
			else
				finalHour=parseInt(this.Hours,10)-12;	
		}
		else
		{
			this.AMorPM="AM";
			if (this.Hours<10)
				finalHour="0"+parseInt(this.Hours,10);
			else
				finalHour=this.Hours;	
		}
	}
	else if (TimeMode==24)
	{
		if (this.Hours<10)
			finalHour="0"+parseInt(this.Hours,10);
		else	
			finalHour=this.Hours;
	}	
	return finalHour;	
}				
Calendar.prototype.getShowHour=getShowHour;		

function getShowAMorPM()
{
	return this.AMorPM;	
}				
Calendar.prototype.getShowAMorPM=getShowAMorPM;		

function GetMonthName(IsLong)
{
	var Month=MonthName[this.Month];
	if (IsLong)
		return Month;
	else
		return Month.substr(0,3);
}
Calendar.prototype.GetMonthName=GetMonthName;

function GetMonDays()//Get number of days in a month
{
	var DaysInMonth=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	if (this.IsLeapYear())
	{
		DaysInMonth[1]=29;
	}	
	return DaysInMonth[this.Month];	
}
Calendar.prototype.GetMonDays=GetMonDays;

function IsLeapYear()
{
	if ((this.Year%4)==0)
	{
		if ((this.Year%100==0) && (this.Year%400)!=0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}
Calendar.prototype.IsLeapYear=IsLeapYear;

function FormatDate(pDate)
{
	var MonthDigit=this.Month+1;
	if (PrecedeZero==true)
	{
		if (pDate<10)
			pDate="0"+pDate;
		if (MonthDigit<10)
			MonthDigit="0"+MonthDigit;
	}

	if (this.Format.toUpperCase()=="DDMMYYYY")
		return (pDate+DateSeparator+MonthDigit+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="DDMMMYYYY")
		return (pDate+DateSeparator+this.GetMonthName(false)+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="MMDDYYYY")
		return (MonthDigit+DateSeparator+pDate+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="MMMDDYYYY")
		return (this.GetMonthName(false)+DateSeparator+pDate+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="YYYYMMDD")
		return (this.Year+DateSeparator+MonthDigit+DateSeparator+pDate);
	else if (this.Format.toUpperCase()=="YYYYMMMDD")
		return (this.Year+DateSeparator+this.GetMonthName(false)+DateSeparator+pDate);	
	else					
		return (pDate+DateSeparator+(this.Month+1)+DateSeparator+this.Year);
}
Calendar.prototype.FormatDate=FormatDate;	