/********************************************************/
// File : minimonth.js                             
// Purposes : generate calendar
// Created : 
// Comments : 
// Modified : 15/2/2001 by Komsan Aunwaitaya 
//				  12/06/2007 by Kiattikhun Prathumma * fixed:	incompatible in firefox
/********************************************************/

var numDays = new Array();
var months = new Array();
var mNames = new Array();
var tNames = new Array();
var useHref = true;
var hrefType = 1;
var selectedDay = new Date();
var todayDay = new Date();
var viewType = "view"; // can be either "view" or "script"
var boxSize = "9";
var fromServer = false;
var fServerDate = new Date();
var origStartDateText = "";

numDays[0] = 31; numDays[1] = 28; numDays[2] = 31; numDays[3] = 30;
numDays[4] = 31; numDays[5] = 30; numDays[6] = 31; numDays[7] = 31;
numDays[8] = 30; numDays[9] = 31; numDays[10] = 30; numDays[11] = 31;

function getDayInMonths(month, day, year) {

    if (month == 2) {
        if ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) {
            return 29;
        } else {
            return 28;
        }
    }

    return numDays[month-1];
}

// send date to textbox 
function submitLink( month, day, year ) {
	var text = "";
	var language = document.csccalendar.__language.value.toLowerCase();
	
	//var language = document.csccalendar.__regional.value.toLowerCase();
	var txtObj = document.csccalendar.__temp.value.split(",");

	//return thai or eng year
	if((language == "thai")||(language == "tha")) { 
		text = getDateThaiFormat(month, day, year);
	} else {
		text = getDateFormat(month,day,year);
	}
	//	alert("window.opener.document.forms[0]." +  document.csccalendar.__temp.value + ".value= \"" + day + "/" + month + "/" + year + "\";");
	//	eval("window.opener.document.forms[0]." +  document.csccalendar.__temp.value + ".value= \"" + getDateFormat(month, day, year) + "\";");
	for(i = 0;i < txtObj.length;i++){
		eval("window.opener.document.forms[0]." +  txtObj[i] + ".value= '" + text + "';");
		eval("window.opener.document.forms[0]." + txtObj[i] + ".focus();");
		eval("window.opener.document.forms[0]." + txtObj[i] + ".select();");
	}
	with(window.opener){
		if (typeof postCalendar == 'function') { 
			postCalendar();
		}
	}

	with(window.opener){
		if (typeof postCalendarSTD == 'function') { 
			postCalendarSTD(txtObj);
		}
	}
	window.close();
}

// gen date format with object "__dataformat" value
function getDateFormat(month, day, year){
	var strFormat = document.csccalendar.__format.value;
	var strDay = day.toString();
	var strMonth = month.toString();
	var strYear = year.toString();

	if(strFormat.indexOf("DD") > -1){
		if(strDay.length == 1) strDay = "0" + strDay;
		strFormat = replace(strFormat,"DD",strDay);
	}
	if(strFormat.indexOf("MM") > -1){
		if(strMonth.length == 1) strMonth = "0" + strMonth;
		strFormat = replace(strFormat,"MM",strMonth);
	}
	if(strFormat.indexOf("YYYY") > -1){
		strFormat = replace(strFormat,"YYYY",strYear);
	}
	if(strFormat.indexOf("YY") > -1){
		strFormat = replace(strFormat,"YY",strYear.substring(2,strYear.length));
	}
	return strFormat;
}

// gen date format with object "__dataformat" value
function getDateThaiFormat(month, day, year){
	var strFormat = document.csccalendar.__format.value;
	var strDay = day.toString();
	var strMonth = month.toString();
//	var strYear = (year + 543).toString();
   var strYear = (year).toString();
	if(strFormat.indexOf("DD") > -1){
		if(strDay.length == 1) strDay = "0" + strDay;
		strFormat = replace(strFormat,"DD",strDay);
	}
	if(strFormat.indexOf("MM") > -1){
		if(strMonth.length == 1) strMonth = "0" + strMonth;
		strFormat = replace(strFormat,"MM",strMonth);
	}
	if(strFormat.indexOf("YYYY") > -1){
		strFormat = replace(strFormat,"YYYY",strYear);
	}
	if(strFormat.indexOf("YY") > -1){
		strFormat = replace(strFormat,"YY",strYear.substring(2,strYear.length));
	}
	return strFormat;
}

function replace(strSrc,strReplace,strWith)	{
	if(strSrc.indexOf(strReplace) == -1)
		return strSrc;
	var i = 0;
	var j = 0;
	while((i = strSrc.indexOf(strReplace, j)) != -1) {
		strSrc = strSrc.substring(0, i) + strWith + strSrc.substring(i + strReplace.length);
		j = i + strWith.length;
	}
	return strSrc; 
}

function setSelectedDay( month, day, year, serverVar ){
    if ((month*1) == -1) return;
    //alert('in setSelDay ' +month+'/'+day+'/'+year);
    //alert('setting the selected day');
    if (serverVar != null) {
        fromServer = serverVar;
    } else {
        fromServer = false;
    }

    if (year >= 100 && year < 500) {
        //alert('adding 2000 in setSelDay');
        year = (year % 100) + 2000;
    }

    if (year < 0) { // netscape treats year < 1900 as negative, so we need to make it positive
        year += 1900;
    }

    selectedDay = new Date( year, ((month*1)-1), day );
    fServerDate    = new Date( year, ((month*1)-1), day );
}

function setTodayDay( month, day, year ){
    //alert(month+'/'+day+'/'+year);
    if ((month*1) == -1) {
        todayDay = new Date();
    	return;
    }
    todayDay = new Date( year, ((month*1)-1), day );
	fServerDate    = new Date( year, ((month*1)-1), day );
}

//function check integer
function testInt(anum){
    numstr = "0123456789"
    for(var i=0;i<anum.length;i++){
    if(numstr.indexOf(anum.charAt(i)) == -1)return false
    }
    return true
}

//function check Date format 
function checkDate(dateString) {
	var errormsg = "Please enter a valid date in the mm/dd/yyyy format"
	if (dateString.indexOf("-")!=-1){
    	var sdate = dateString.split("-")
    }else {
    	var sdate = dateString.split("/")
    }
	//alert(sdate.length);
	if(sdate.length != 3){
    	alert(errormsg);
    	return false;
    }
    if(!testInt(sdate[0]) || !testInt(sdate[1]) || !testInt(sdate[2])){
    	alert(errormsg);
    	return false;
    }

    //complain if the year's length is not 1,2,or 4
    if (sdate[2].length != 1 && sdate[2].length != 2 && sdate[2].length != 4) {
        alert(errormsg);
        return false;
    }

    //alert(sdate[2].length);
    if (sdate[2].length == 2) {
        if(1*sdate[2]<30){
            if (1*sdate[2] < 10) {
                sdate[2] = "200"+(1*sdate[2]);
            } else {
                sdate[2] = "20"+sdate[2]
            }
        	dateString = sdate.join("/")
        } else if (1*sdate[2] < 100) {
            sdate[2] = "19" + sdate[2];
        }
    }

    // check for valid daysInMonth
    var numDays = getDayInMonths((1*sdate[0]), (1*sdate[1]), (1*sdate[2]));
    if ((1*sdate[1]) > numDays) {
        alert(errormsg);
        return false;
    }

    var chkDate=new Date(Date.parse(dateString))
    var cmpDate=(chkDate.getMonth()+1)+"/"+(chkDate.getDate())+"/"+(sdate[2])
    var newDate=(1*sdate[0])+"/"+(1*sdate[1])+"/"+(sdate[2])
    //alert(newDate)
    if ((""+newDate)!= (""+cmpDate) || isNaN(chkDate)){
    	alert(errormsg);
    	return false;
    }

//    if( document.all ){
//        document.gotoForm.StartDate.value = newDate;
//    }else{
//        document.layers['calLayer2'].document.gotoForm.StartDate.value = newDate;
//    }
//    return newDate;
}

mNames[0] = "January"
mNames[1] = "February"
mNames[2] = "March"
mNames[3] = "April"
mNames[4] = "May"
mNames[5] = "June"
mNames[6] = "July"
mNames[7] = "August"
mNames[8] = "September"
mNames[9] = "October"
mNames[10] = "November"
mNames[11] = "December"

tNames[0] = "มกราคม"
tNames[1] = "กุมภาพันธ์"
tNames[2] = "มีนาคม"
tNames[3] = "เมษายน"
tNames[4] = "พฤษภาคม"
tNames[5] = "มิถุนายน"
tNames[6] = "กรกฎาคม"
tNames[7] = "สิงหาคม"
tNames[8] = "กันยายน"
tNames[9] = "ตุลาคม"
tNames[10] = "พฤศจิกายน"
tNames[11] = "ธันวาคม"

function initMonths(year){
	var m = -1
	for (var x=0; x<7; x++) {
		m = x+1;
		months[x] = (m%2 == 0) ? (m==2 ? ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0)) ? 29 : 28) : 30) : 31
	}
	for (var x=7; x<12; x++) {
		m = x+1;
		months[x] = (m%2 == 0) ? 31 : 30
	}
}

function getSubmitLinkAnchor( curMonth, curDate, curYear, className, displayDay ){
	return "<A HREF='javascript:submitLink("+curMonth+","+ curDate+","+ curYear+")' class='"+className+"'>"+displayDay+"</A>"
}

function getCalHtml( month, day, year ){
	//set calendar language
	var language = document.csccalendar.__language.value.toLowerCase();
    
	//var language = document.csccalendar.__regional.value.toLowerCase();
	//alert('getCalHtml: month = '+month);
	if( month == null ){
        //alert('month is null, defaulting to today');
    	var todayDate = new Date()
		month = todayDate.getMonth()+1
		day = todayDate.getDate()
		year = todayDate.getYear()
	}
    year = selectedDay.getYear();
    if (year <= 500) {
        year += 1900;
    }
    var StartDateText = month + "/" + day + "/" + year;

    var selYear = selectedDay.getYear();
    if (selYear <= 500) {
        selYear += 1900;
    }

    if (selectedDay.getMonth() != -1) {
        StartDateText = selectedDay.getMonth()+1 + "/" + selectedDay.getDate() + "/" + selYear;
        //alert(StartDateText);
    }

	initMonths(year)
	month = month-1
	var dt = new Date(year,month,1)
	var dayOfWeek = dt.getDay()
	var i = 0
	var numDisplayCells = (dayOfWeek+months[month] > 35? 42 : 35 )
	var numcells = 42
	var cellArray = new Array()
	for( var j=0; j<numcells; j++){
		cellArray[j] = "<TD></TD>"
	}

	var nextMonth
	var prevMonth
	var nextYear = year
	var prevYear = year
	if(month+1 > 11){
		nextMonth = 1
		prevMonth = 11
		nextYear = year+1
	}else if(month-1 < 0){
		nextMonth = 2
		prevMonth = 12
		prevYear = year - 1
	}else{
		nextMonth = month+2
		prevMonth = month
	}
	//set up dynamic hrefs here
	var today = ""
    var curDate = 0;

	//prev month cells set to grey color
	var k = months[prevMonth-1]
	var l = dayOfWeek-1

	while( l>-1 ){
		today = k
		if( useHref ){
            curDate = today;
		    cellArray[l] = "<TD>" + getSubmitLinkAnchor( prevMonth, curDate, prevYear, "mini-monthday-grey", today ) + "</TD>"
		}else{
			cellArray[l] = "<TD align='center' class='mini-monthday-grey' >"+today+"</TD>"
		}
		k--
		l--
	}

	//paint days of current month
	while (i<months[month]){
		today = (i+1)
		if( useHref ){
            curDate = today;
            
			//set current date to blue color
			if( todayDay.getMonth() == month && todayDay.getDate() == (i+1) && todayDay.getYear() == year ){
				today = "<SPAN CLASS='mini-monthday-blue'>"+today+"</SPAN>"
			}
			
			if( (fromServer == true || (selectedDay.getYear() == todayDay.getYear() && selectedDay.getMonth() == todayDay.getMonth() )) && selectedDay.getMonth() == month && selectedDay.getDate() == (i+1) && selectedDay.getYear() == year ){
				if (viewType == "script") {
                    cellArray[i+dayOfWeek] = "<TD><TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD ALIGN=CENTER CLASS='mini-monthgrey-bkg'>"+today+"</TD></TR></TABLE></TD>"
                } else {
                    cellArray[i+dayOfWeek] = "<TD class='mini-month-bkg' align='center'>"+getSubmitLinkAnchor( (month+1), curDate, year, "mini-month-bkg", today ) +"</TD>"
                }
			}else{
			    cellArray[i+dayOfWeek] = "<TD>" + getSubmitLinkAnchor( (month+1), curDate, year, "mini-month-bkg", today ) + "</TD>"
			}
		}else{
			cellArray[i+dayOfWeek] = "<TD align='center'>"+today+"</TD>"
		}
		i++
	}

	//next month cells set to grey color
	var j = 1
	while( (i+dayOfWeek)<numDisplayCells ){
		today = j
		if( useHref ){
            curDate = today;
		    cellArray[i+dayOfWeek] = "<TD>" + getSubmitLinkAnchor( nextMonth, curDate, nextYear, "mini-monthday-grey", today ) + "</TD>"
		}else{
			cellArray[i+dayOfWeek] = "<TD align='center' class='mini-monthday-grey'>"+today+"</TD>"
		}
		j++
		i++
	}

    //alert(month);
	/*
	var retHtml = "<table width='250' border='1' cellpadding='10' cellspacing='0' ><tr><td><table width='100%' border='0' cellpadding='0' cellspacing='1' >"
	//month title control
	retHtml += "<TR align='center'><TD colspan='9' class='mini-year-bkg'></td></tr><TR><TD colspan='9' class='head-cal-bkg'><div align='center'><A HREF='javascript:paintCal("+prevMonth+",selectedDay.getDate(),"+prevYear+")'><img src='../IMAGES/BUTTON/MAIN/BACK20.gif' border='0'></a>&nbsp;";
	
	//set month for thai or eng 
	if((language == "thai")||(language == "tha"))  { 
		retHtml += tNames[month]
	} else {
		retHtml += mNames[month]
	}
	
	retHtml +="&nbsp;<A HREF='javascript:paintCal("+nextMonth+",selectedDay.getDate(),"+nextYear+")'><img src='../IMAGES/BUTTON/MAIN/NEXT20.gif' border='0'></a></div></TD></TR>"*/
	var month_desc = new Array();
	//	var thaiyear = selYear + 543;
	var thaiyear = selYear;
	if((language == "thai")||(language == "tha"))  { 
		month_desc = tNames;
	}else{
		month_desc = mNames;
	}
	var retHtml = "<table width='250' border='1' cellpadding='10' cellspacing='0' ><tr><td><table width='100%' border='0' cellpadding='0' cellspacing='1' >"


	//month title control
	retHtml += "<TR align='center'><TD colspan='9' class='mini-year-bkg'></td></tr><TR><TD colspan='9' class='head-cal-bkg'><div align='center'><A HREF='javascript:paintCal("+prevMonth+",selectedDay.getDate(),"+prevYear+")'><img src='../IMAGES/BUTTON/MAIN/BACK20.gif' border='0'></a>&nbsp;";
	retHtml += '<select onchange="paintCalForSelect(parseInt(this.value)+1,selectedDay.getDate(),'+year+')">';
		for(var i=0;i<12;i++){
			if(month==i){
				retHtml += '<option value="'+i+'" style="color:red;" selected>'+month_desc[i]+'</option>';
			}else{
				retHtml += '<option value="'+i+'">'+month_desc[i]+'</option>';
			}
		}
	retHtml +='</select>';
	retHtml +="&nbsp;<A HREF='javascript:paintCal("+nextMonth+",selectedDay.getDate(),"+nextYear+")'><img src='../IMAGES/BUTTON/MAIN/NEXT20.gif' border='0'></a></div></TD></TR>"

	//year title control
	retHtml += "<TR><TD colspan='9' class='mini-month-bkg'></td></tr><TR><TD colspan='9' class='head-year-bkg' align='center'><div align='center'><A HREF='javascript:paintCal("+(month+1)+",selectedDay.getDate(),"+(year-1)+")'><img src='../IMAGES/BUTTON/MAIN/BACK20.gif' border='0'></a>&nbsp;<span class='mini-year'>";
	
	retHtml += '<select onchange="paintCal('+(month+1)+',selectedDay.getDate(),this.value)">';
		for(var i=selYear-80;i<new Date().getFullYear()+100;i++){
			if(selYear==i){
				retHtml += '<option value="'+i+'" style="color:red;" selected>'+i+'</option>';
			}else if(new Date().getFullYear()==i){
				retHtml += '<option value="'+i+'" style="color:blue;">'+i+'</option>';
			}else{
				retHtml += '<option value="'+i+'">'+i+'</option>';
			}
		}
	retHtml +='</select>';	
	retHtml +="</span>&nbsp;<A HREF='javascript:paintCal("+(month+1)+",selectedDay.getDate(),"+(year+1)+")'><img src='../IMAGES/BUTTON/MAIN/NEXT20.gif' border='0'></a></div></TD></TR><TR><TD colspan='9' class='mini-month-bkg' align='center'></td></tr>"
	
	//set day title (sun - sat) or (อ - ส)
	if((language == "thai")||(language == "tha"))  { 
		retHtml += "<TR align='center'><TD class='thaimini-week-bkg'>อา</TD><TD class='thaimini-week-bkg'>จ</TD><TD class='thaimini-week-bkg'>อ</TD><TD class='thaimini-week-bkg'>พ</TD><TD class='thaimini-week-bkg'>พฤ</TD><TD class='thaimini-week-bkg'>ศ</TD><TD class='thaimini-week-bkg'>ส</TD></TR>"
	} else {
		retHtml += "<TR align='center'><TD class='mini-week-bkg'>SUN</TD><TD class='mini-week-bkg'>MON</TD><TD class='mini-week-bkg'>TUE</TD><TD class='mini-week-bkg'>WED</TD><TD class='mini-week-bkg'>THU</TD><TD class='mini-week-bkg'>FRI</TD><TD class='mini-week-bkg'>SAT</TD></TR>"
	}
	for(var j=0; j<numcells; j++){
		if( j % 7 == 0 ){
			retHtml += "<TR class='mini-month-bkg' align='center'>"
		}
		retHtml += cellArray[j]
		if((j+1) != 0 && (j+1) % 7 == 0 ){
			retHtml += "</TR>"
		}
	}

    origStartDateText = StartDateText;

// textbox display current time
//    retHtml += "<tr class=mini-month-bkg align=\"center\"><td align=center colspan=9><span class=\"mini-year\">Time </span><input size=\""+boxSize+"\" type=text name='__timer' class=\"inputBox\" maxlength=12><span class=\"mini-year\" id=\"__timeflag\">&nbsp;</span></td></tr>";

    retHtml += "</table></td></tr></table>"
	return retHtml
}

// rewrite time in textbox
function setClock(){
	var cur = new Date();
	var strHour = (cur.getHours() >= 12)? (cur.getHours()-12).toString():cur.getHours().toString();
	var strMinute = cur.getMinutes().toString();
	var strSecond = cur.getSeconds().toString();
	var time = " " + strHour + ":" + strMinute + ":" + ((strSecond.length == 1)?"0"+strSecond:strSecond);
	with(document.csccalendar){
		__timer.value = time;
	}
	var flag = (cur.getHours() >= 12) ? "&nbsp;PM" : "&nbsp;AM";
	__timeflag.innerHTML = flag;
	setTimeout("setClock()",1000);
}

// get current time
function getCurrentTime(){
	var cur = new Date();
	var time = cur.getHours() + ":" + cur.getMinutes() + ":" + cur.getSeconds();
	return time;
}

function paintCal( month, day, year ){
	if (year != null) {
    	if (year >= 100 && year < 500) {
            year = (year % 100) + 2000;
        }
        if (year < 0) { // netscape treats year < 1900 as negative, so we need to make it positive
            year += 1900;
        }
        setSelectedDay(month, day, year);
    } else {
        setSelectedDay(fServerDate.getMonth()+1, fServerDate.getDate(), fServerDate.getYear(), true);
        month = fServerDate.getMonth()+1;
        day   = fServerDate.getDay();
        year  = fServerDate.getYear();
    }
    var retHtml = getCalHtml( month, day, year );
	document.all.calLayer.innerHTML = retHtml;
}

//use for when change month by click in dropdown
function paintCalForSelect( month, day, year ){
	paintCal( month, day, year )
}