var inputDateField  = 0;
var divIdCalendar   = 0;
var bCalOpen        = 0;
var nCalTimeOut     = null;

var secondInput     = null;
var cssCustomLink   = "";
var agencyCustomCssLink = "";
var nSecondDateOffset = 7;

var futureLimit = 330;

// Get day, month year of current day
var now       = new Date();
var nSlcDay   = now.getDate();
var nSlcMonth = now.getMonth()+1;
var nSlcYear  = now.getFullYear();
var compare_with_second = false;
var check = new Date();
check.setDate(now.getDate() + futureLimit);

var CALENDAR_WIDTH = 140;

var POSITION_REL_DOWN_LEFT = 1;
var POSITION_REL_DOWN_RIGHT = 2;
var POSITION_REL_TOP_LEFT = 5;
var POSITION_REL_TOP_RIGHT = 6;

function OnKeyDownEventFunction(thisEvent, textInputID, calendarID)
{    
    if(thisEvent.keyCode)
    {
        var keyCode = thisEvent.keyCode;
        // info -> tab key == 9
        if(keyCode == 9)
        {
            var textBox = getElement(textInputID);
            if(textBox!=null)
                if(!isValidDateFormat(textBox.value, dateRegEx))//dateRegEx is defined in Util.js
                {
                    var cal = getElement(calendarID);
                    if(cal != null)
                        cal.click();
                }
        }
    }
}

function FormatDayToString(dDayIn)
{
	var strDay = dDayIn;
	if(dDayIn < 10)
		strDay = "0"+strDay;
	
	return strDay;
}

//function buildCalendar(bSlcOnlyFutureDays, csLangIn)
function buildCalendar(dDayIn, dMonthIn, dYearIn, bIsInputVal, bSlcOnlyFutureDaysIn, csLangIn, exportFocusToElemID)
{	

	// Constant declaration for month and day strings
	var calendarString = "";
	var days  = new Array (new Array("Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"),
						   new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday") );
	var month = new Array (new Array("janvier", "f&eacute;vrier", "mars", "avril", "mai", "juin", "juillet", "ao&ucirc;t", "septembre", "octobre", "novembre", "d&eacute;cembre" ),
	                       new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") );
	var title = new Array (new Array("Journ&eacute;e courante", "Journ&eacute;e s&eacute;lectionn&eacute;e"),
						   new Array("Current day", "Day selected"));
	var close = new Array ( new Array("Fermer"),
					    	new Array("Close"));

	// Toggle calendar language between english and french
	if(csLangIn.toUpperCase() == "FR")
		calendarLang=0;
	else
		calendarLang=1;
	
	// Get day, month year of current day
	var now  = new Date();
	var currentDay   = now.getDate();
	var currentMonth = now.getMonth();
	var currentYear  = now.getFullYear();

	// Reset nSlcDay Month and Year to current month
	nSlcDay   = 1;
	nSlcMonth = dMonthIn;
	nSlcYear  = dYearIn;
//	alert("Selected date "+nSlcDay+" "+nSlcMonth+" "+nSlcYear);
	
	// Calculate previous month
	var prevMonthDate = new Date(dYearIn, dMonthIn-1, 1);
	prevMonthDate.setMonth(prevMonthDate.getMonth()-1);

	// Calculate next month
	var nextMonthDate = new Date(dYearIn, dMonthIn-1, 1);
	nextMonthDate.setMonth(nextMonthDate.getMonth()+1);

	// Calculate next month +2
	var nextMonthDate2 = new Date(dYearIn, dMonthIn-1, 1);
	nextMonthDate2.setMonth(nextMonthDate2.getMonth()+2);
//	alert("Selected date "+nextMonthDate2.getDate()+" "+nextMonthDate2.getMonth()+" "+nextMonthDate2.getFullYear()+" monthIn "+dMonthIn);
		
	// Create links to navigate in the calendar
	var prevMonthLink = "#";//"pageAccueil.php?ddate=01-"+FormatDayToString( (prevMonthDate.getMonth()+1) )+"-"+FormatDayToString( (prevMonthDate.getFullYear()) );
	var prevMonth     = month[calendarLang][prevMonthDate.getMonth()]+" "+(prevMonthDate.getFullYear());
	var monthYear     = month[calendarLang][dMonthIn-1]+" "+dYearIn;
	var nextMonthLink = "#";//"pageAccueil.php?ddate=01-"+FormatDayToString( (nextMonthDate.getMonth()+1) )+"-"+FormatDayToString( (nextMonthDate.getFullYear()) );
	var nextMonth     = month[calendarLang][nextMonthDate.getMonth()]+" "+(nextMonthDate.getFullYear());

	// Starting the code that creates the first calendar
	calendarString += "<TABLE class=\"cadre\" bgcolor=\"#ffffff\" cellSpacing=\"0\" cellPadding=\"0\" border=\"0\">";
	calendarString += "<TBODY>";
	calendarString += "<tr><td colspan=\"7\" align=\"right\" class=\"cal_content\"><a href='javascript:void(0)' onclick='parent.hideCalendar();return false;'>"+close[calendarLang]+" X</a></td></tr>"
	calendarString += "  <TR>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\">";
	calendarString += "      <A class=\"cal_head\" title=\""+prevMonth+"\" onclick=\"javascript:parent.prevMonth('"+csLangIn+"', '"+bSlcOnlyFutureDaysIn+"','"+ exportFocusToElemID +"');\" href=\"javascript:void(0)\">&lt;</A>";
	calendarString += "    </TD>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\" colSpan=\"5\">"+monthYear+"</TD>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\">";
	calendarString += "      <A class=\"cal_head\" title=\""+nextMonth+"\" onclick=\"javascript:parent.nextMonth('"+csLangIn+"', '"+bSlcOnlyFutureDaysIn+"','"+ exportFocusToElemID +"');\" href=\"javascript:void(0)\">&gt;</A>";
	calendarString += "    </TD>";
	calendarString += "  </TR>";
	
	/* Calculating the first day of the week for the first day of the month selected*/
	var nbDaysInWeek = 0;
	var nDate  = new Date(dYearIn, dMonthIn-1, dDayIn);
	
	// set date to first day of month
	nDate.setDate(1);
	nbDaysInWeek = nDate.getDay();
	
	//set date to sunday date for
	nDate.setDate(nDate.getDate()-nbDaysInWeek-1); 
	
	// print days of week
	calendarString += "  <TR>";
	for(i=0; i<7; i++)
	{
		calendarString += "    <TD class=\"dayCellFormat\" width=\"20\" height=\"20\"><font class=\"smallBlue\">"+ days[calendarLang][i].substr(0, 2) +"</font></TD>";	
	}
	calendarString += "  </TR>";

    for(w=0; w<6; w++)
	{
		calendarString +="<tr>\n";
        for(wd=0; wd<7; wd++)
		{
			// calculates the date to put in the cell
			nDate.setDate( nDate.getDate() + 1 );
			nYear = nDate.getFullYear();
			
			var strDateCell = nYear+"-"+FormatDayToString(nDate.getMonth()+1)+"-"+FormatDayToString(nDate.getDate());//yyyy-mm-dd

			if(nDate.getMonth()==(dMonthIn-1))
			{
				if(bSlcOnlyFutureDaysIn)
				{
					if(isDateFutureDay(nDate) && isDateValid(nDate))
					{
						if(nDate.getMonth()==currentMonth && nDate.getDate()==currentDay && nDate.getFullYear()==currentYear)
						{
							calendarString +="<TD align=\"center\" bgcolor=\"#96B99F\" title=\""+title[calendarLang][0]+"\"><A class=\"smallBlueBold\" href=\"#\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate.getDate())+"</A></TD>";// parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
						else if((nDate.getMonth()+1)==dMonthIn && nDate.getDate()==dDayIn && nDate.getFullYear()==dYearIn && bIsInputVal)
						{
							calendarString +="<TD align=\"center\" title=\""+title[calendarLang][1]+"\"><A class=\"smallOrangeBold\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
						else
						{
							calendarString +="<TD align=\"center\"><A class=\"smallBlueNoUnder\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
					}
					else
					{
						calendarString +="<TD align=\"center\" class=\"smallGrayBold\">"+FormatDayToString(nDate.getDate())+"</TD>";
					}
				}
				else
				{
					calendarString +="<TD align=\"center\"><A class=\"smallBlueNoUnder\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
				}
			}
			else
			{
				calendarString +="<TD class=\"cal_content\">&nbsp;</TD>";
			}
		}
	
		calendarString +="</tr>\n";
	}

	/* Calculating the first day of the week for the first day of the month selected*/
	nbDaysInWeek = 0;
	var nDate2 = new Date(nextMonthDate2.getFullYear(), nextMonthDate2.getMonth()-1, nextMonthDate2.getDate());
	
	// set date to first day of month
	nDate2.setDate(1);
	nbDaysInWeek = nDate2.getDay();
	
	// get month string and year for this calendar
	monthYear     = month[calendarLang][nextMonthDate.getMonth()]+" "+nDate2.getFullYear();
	
	// set date to sunday date for
	nDate2.setDate(nDate2.getDate()-nbDaysInWeek-1);
	
	// Starting the code that creates the second calendar	
	calendarString += "<tr><td colspan=\"7\" align=\"right\" class=\"cal_content\"></td></tr>"
	calendarString += "  <TR>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\">";
	calendarString += "";
	calendarString += "    </TD>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\" colSpan=\"5\">"+monthYear+"</TD>";
	calendarString += "    <TD class=\"cal_head\" align=\"center\">";
	calendarString += "";
	calendarString += "    </TD>";
	calendarString += "  </TR>";

	// print days of week
	calendarString += "  <TR>";
	for(i=0; i<7; i++)
	{   
		calendarString += "    <TD class=\"dayCellFormat\" width=\"20\" height=\"20\"><font class=\"smallBlue\">"+ days[calendarLang][i].substr(0, 2) +"</font></TD>";	
	}
	calendarString += "  </TR>";
		
    for(w=0; w<6; w++)
	{	
		calendarString +="<tr>\n";
        for(wd=0; wd<7; wd++)
		{
			// calculates the date to put in the cell
			nDate2.setDate( nDate2.getDate() + 1 );
			nYear = nDate2.getFullYear();
			
			var strDateCell = nYear+"-"+FormatDayToString(nDate2.getMonth()+1)+"-"+FormatDayToString(nDate2.getDate());//yyyy-mm-dd

			if(nDate2.getMonth()==nextMonthDate.getMonth())
			{
				if(bSlcOnlyFutureDaysIn)
				{
					if(isDateFutureDay(nDate2) && isDateValid(nDate2))
					{
						if(nDate2.getMonth()==currentMonth && nDate2.getDate()==currentDay && nDate2.getFullYear()==currentYear)
						{
							calendarString +="<TD align=\"center\" bgcolor=\"#96B99F\" title=\""+title[calendarLang][0]+"\"><A class=\"smallBlueBold\" href=\"#\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate2.getDate())+"</A></TD>";// parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
						else if((nDate2.getMonth()+1)==dMonthIn && nDate2.getDate()==dDayIn && nDate2.getFullYear()==dYearIn && bIsInputVal)
						{
							calendarString +="<TD align=\"center\" title=\""+title[calendarLang][1]+"\"><A class=\"smallOrangeBold\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate2.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
						else
						{
							calendarString +="<TD align=\"center\"><A class=\"smallBlueNoUnder\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate2.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
						}
					}
					else
					{
						calendarString +="<TD align=\"center\" class=\"smallGrayBold\">"+FormatDayToString(nDate2.getDate())+"</TD>";
					}
				}
				else
				{
					calendarString +="<TD align=\"center\"><A class=\"smallBlueNoUnder\" href=\"javascript:void(0)\" onclick=\"javascript:parent.printDateAndSetFocus(event, '"+strDateCell+"','"+exportFocusToElemID+"');\">"+FormatDayToString(nDate2.getDate())+"</A></TD>";//parent.printDate('"+strDateCell+"');parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');
				}
			}
			else
			{
				calendarString +="<TD class=\"cal_content\">&nbsp;</TD>";
			}
			
		}
	
		calendarString +="</tr>\n";
	}	
//	calendarString += "<tr><td colspan=\"7\" align=\"center\" class=\"cal_content\"><a href='#' onclick='top.closeCal();return false;'>close</a></td></tr>"

	calendarString +="</TBODY>";
	calendarString +="</TABLE>";

	return calendarString;
}

// string: strDate => must be in YYYY-MM-DD format
function GetDateFromString(strDate)
{
	var reDateFormat = /^\d{4}-\d{2}-\d{2}$/;

	if (strDate.search(reDateFormat) == -1)
	{
		//if match failed
		return new Date();
	}
	else
	{
		var csDateTokens = strDate.split("-"); //split using minus char as delimiter
		return new Date(csDateTokens[0], (csDateTokens[1]-1), csDateTokens[2]);
	}
}

function hideFrame()
{
  /*if (ie) {
  if ( document.all['calFrame'].style.visibility == 'visible' )
  {
      document.all['calFrame'].style.visibility = 'hidden';
      document.all['calFrame'].style.display = 'none';
  }
  } else if (n6){
		if ( document.getElementById('calFrame').style.visibility == 'visible' )
      document.getElementById('calFrame').style.visibility = 'hidden';
      document.getElementById('calFrame').style.display = 'none';
  }*/
  var frame = getIFrame('calFrame');
  frame.style.visibility = 'hidden';
  frame.style.display = 'none';
}

function updateFrame( csCalendarHTML )
{

	if(ie){
    document.frames['calFrame'].document.open();
    document.frames['calFrame'].document.write(csCalendarHTML);
    document.frames['calFrame'].document.close();
	} else if(n6){
	  window['calFrame'].document.open();
    window['calFrame'].document.write(csCalendarHTML);
    window['calFrame'].document.close();
	}
	
	var frame = getIFrame('calFrame');
	frame.style.display = 'block';
	frame.style.visibility = 'visible';

  /*if (ie) 
  {
	if ( document.all['calFrame'].style.visibility == 'hidden' )
	{
      document.all['calFrame'].style.display = 'block';
      document.all['calFrame'].style.visibility = 'visible';
    }
  } 
  else if (n6)
  {
	if ( document.getElementById('calFrame').style.visibility == 'hidden' )
	{
      document.getElementById('calFrame').style.visibility = 'visible';
      document.getElementById('calFrame').style.display = 'block';
    }
  }*/
}

function printTSGCalendar( eventIn, editControlId, bAllowOnlyFuture, hostName, calAnchorObj, position_rel, secondTextField, nSecondTextOffset )
{
	var fullhostName = '';
	
	if ( hostName != null && hostName != '' )
		fullhostName = "http://" + hostName;

	printCalendar( eventIn, editControlId, bAllowOnlyFuture, 'EN', fullhostName + '/Shared/generic/default/styles/dualCalendar.css', calAnchorObj, position_rel, secondTextField, nSecondTextOffset );
}
  
// inputObj: string that represent's the clientID of the input text where the date will be print out
// startingDateField : string of the clientID of the input text where the stratign date will be taken to print the calendar strating month
// exportFocusToElemID : will export focus to the specified element on click or on tab key
function printCalendar(eventIn, inputObj, bSlcOnlyFutureDaysIn, csLanguage, cssLink, _agencyCustomCssLink, calAnchorObj, position_rel, secondTextField, nSecondTextOffset, startingDateField, exportFocusToElemID, compare_with_second ){

	inputDateField = getElement(inputObj);
	secondInput    = secondTextField;
	cssCustomLink  = cssLink;
	agencyCustomCssLink = _agencyCustomCssLink;
	
	nSecondDateOffset = nSecondTextOffset;
	
	var inputDate = "";
	// set calendar to the date of this date 
	if(startingDateField != null && startingDateField != "")
	{
		inputDate = GetDateFromString(getElement(startingDateField).value);
	}
	else
	{
		inputDate = GetDateFromString(inputDateField.value);
	}
	
	var CalendarAnchorObject = inputDateField;
	if ( calAnchorObj != null )
		CalendarAnchorObject = getElement(calAnchorObj);
	
	var inputObjposX = findPosX(CalendarAnchorObject);
	var inputObjposY = findPosY(CalendarAnchorObject);

	var newX = 0;
	var newY = 0;

	if( position_rel == POSITION_REL_DOWN_LEFT )
	{
		newX = inputObjposX + CalendarAnchorObject.offsetWidth - CALENDAR_WIDTH;
		newY = inputObjposY + CalendarAnchorObject.offsetHeight - 30;
	}
	else if ( position_rel == POSITION_REL_DOWN_RIGHT )
	{
	    newX = inputObjposX + CalendarAnchorObject.offsetWidth + 24;
	    newY = inputObjposY + CalendarAnchorObject.offsetHeight - 30;
	}
	else if( position_rel == POSITION_REL_TOP_LEFT )
	{
		newX = inputObjposX + CalendarAnchorObject.offsetWidth - CALENDAR_WIDTH;
		newY = inputObjposY + CalendarAnchorObject.offsetHeight - 70;
	}
	else if ( position_rel == POSITION_REL_TOP_RIGHT )
	{
	    newX = inputObjposX + CalendarAnchorObject.offsetWidth + 35;
	    newY = inputObjposY + CalendarAnchorObject.offsetHeight - 115;
	}
	if (compare_with_second && secondInput != '')
	{
		now = GetDateFromString(getElement(secondInput).value);
		secondInput = secondTextField = null;
	}

	
    var frame = getIFrame("calFrame");
    
	frame.style.position = "absolute";
	frame.style.top      = newY;
	frame.style.left     = newX;

	var csCalendar = HTMLheader(exportFocusToElemID) + buildCalendar(inputDate.getDate(), (inputDate.getMonth()+1), inputDate.getFullYear(), 1, bSlcOnlyFutureDaysIn, csLanguage, exportFocusToElemID) + HTMLfooter();
    //document.write(csCalendar); // this prints the html code into the page
	updateFrame( csCalendar );

  if (ie) {
	document.frames['calFrame'].focus(  );
  } else if (n6) {
	window['calFrame'].focus(  );
  }

	bCalOpen = 1;
}

function printDate(csDate){

	inputDateField.value = csDate;
	
	var laterDate = GetDateFromString(csDate);
	
	laterDate.setDate( laterDate.getDate() + nSecondDateOffset );
	
	if(secondInput != null)
	{
	    getElement(secondInput).value = laterDate.getFullYear()+"-"+FormatDayToString(laterDate.getMonth()+1)+"-"+FormatDayToString(laterDate.getDate());
	}
    //hideCalendar();
}



function prevMonth(csLangIn, bSlcOnlyFutureDaysIn, exportFocusToElemID){
	nSlcDay   = 1;
	nSlcMonth--;
	if(nSlcMonth < 1)
	{
		nSlcMonth = 12;
		nSlcYear--;
	}

	var csCalendar = HTMLheader(exportFocusToElemID) + buildCalendar(nSlcDay, nSlcMonth, nSlcYear, 0, bSlcOnlyFutureDaysIn, csLangIn, exportFocusToElemID) + HTMLfooter();

	updateFrame( csCalendar );

//	bCalOpen = 0;
//	clearTimeout(nCalTimeOut);
//	setTimeout("bCalOpen = 1", 2000);
}

function nextMonth(csLangIn, bSlcOnlyFutureDaysIn, exportFocusToElemID){
	nSlcDay   = 1;
	nSlcMonth++;
	if(nSlcMonth > 12)
	{
		nSlcMonth = 1;
		nSlcYear++;
	}

	var csCalendar = HTMLheader(exportFocusToElemID) + buildCalendar(nSlcDay, nSlcMonth, nSlcYear, 0, bSlcOnlyFutureDaysIn, csLangIn, exportFocusToElemID) + HTMLfooter();

	updateFrame( csCalendar );

	
// 	bCalOpen = 0;
// 	clearTimeout(nCalTimeOut);
// 	setTimeout("bCalOpen = 1", 2000);
}

function isDateFutureDay(nDateIn){
	if(nDateIn > now)
		return true;
	else
		return false;
}

function isDateValid(nDateIn){
	if(nDateIn < check)
		return true;
	else
		return false;
}

function printDateAndSetFocus( _event, csDate, elementIDToSetFocus)
{
    printDate(csDate);
    
    SetFocus(elementIDToSetFocus);
        
    hideCalendar();
}

function hideCalendar()
{
	hideFrame();
	now = new Date();
	bCalOpen = 0;
}

function closeCal(){
    
	if(/*divIdCalendar && */bCalOpen)
	{
		hideFrame();
	}
	
	now = new Date();
	bCalOpen = 0;
}

function HTMLheader(exportFocusToElemID){
    var toReturn = '<html><head><title>Calendar</title><LINK href=\"'+cssCustomLink+'\" type=\"text/css\" rel=\"stylesheet\" /><LINK href=\"'+agencyCustomCssLink+'\" type=\"text/css\" rel=\"stylesheet\" />\n\</head><body'
    
    if(exportFocusToElemID != null && exportFocusToElemID.length > 0)
      toReturn +=  " onkeydown=\"javascript:parent.closeCal();parent.changeFocusOnPressedKey(event, 9, '"+exportFocusToElemID+"');\""; // 9 is the tab key, this function is defined in SearchPanel.js
      
    toReturn += '>';
        
    return toReturn;
}

function HTMLfooter(){
  return '</body></html>';
}

