// Usage:  Adicione as seguintes linhas de c&oacute;digo 
//         // Carrega o componente na p&aacute;gina
//
//         <SCRIPT LANGUAGE="JavaScript" SRC="PRCalendbr.js"><\/SCRIPT>
//
//
//
//         // Esta linha &eacute; usada em conjunto com um campo do formulario (myDateField) em um form (myForm)
//         // Substitua "myForm" e "myDateField" com os nomes do campo e do forms respectivamente
//         // Opcoes da janela ajusta tamanho, posicao, etc.
//         //
//         <A HREF="javascript:calSetDateField(document.myForm.myDateField);parent.newWin = window.open('calendar.html','cal','dependent=yes,width=210,height=230,screenX=200,screenY=300,titlebar=yes');void(0)">
//         <IMG SRC="calendar.gif" BORDER=0></A><font size=1>Popup Calendar</font>
//      ou 
//		(Recomendada)
//		   <A HREF="javascript:calShowCalendar(document.myForm.myDateField,myDateFormat);void(0)">
//         <IMG SRC="calendar.gif" BORDER=0></A><font size=1>Popup Calendar</font>
//      
//      
//		Sintaxe geral:
//
//	calShowCalendar([*datainteira],[ dateformat],[*campodia],[*campomes],[*campoano]) 
//
//  Parametros omitidos, informar 'null'
//  Se Forem informados campodia, mes e ano, estes serao usados para montar dia inicial do calendario
//		e receberao valor.
//
//  *informar ao menos um destes = referencia a campo do forms onde depositar os valores.
// 
//        
// Arquivos necessarios:
//
//         PRCalendbr.js - Contem as funcoes JS para a construcao da tela de calendario
//
//		   calendar.html - frameset para abrir calendario. Desnecessario se utilizada calShowCalendar()
//
// 
// Arquivos acessorios:
//
//         calendar.gif  - Imagem para o link ao calendario
// 
//         yourPage.html - Pagina que fara uso do componente
// 
// Especificacao de formatos para o calendario
// (usados como macrosubstituicao em texto)
//
// dd      = Dia de  1 ou 2-digit 
// DD      = Dia de  2-digit
// mm      = Mes de  1 ou 2-digitos
// MM      = Mes 2-digit Month
// aa/AA   = Ano 2-digitos
// aaaa/AAAA= Ano 4-digitos
// mes     = Mes em minusculas
// Mes     = Mes com inicial maiuscula
// MES     = Mes em maiusculas
// mon     = Mes com 3-letras em minusculas
// Mon     = Mes com 3-letras com inicial maiuscula
// MON     = Mes com 3-letras em maiusculas
// semana  = dia da semana em minusculas
// Semana  = dia da semana com inicial maiuscula
// SEMANA  = dia da semana em maiusculas
// smna    = dia da semana 3-letras em minusculas 
// Smna    = dia da semana 3-letras com inicial maiuscula
// SMNA    = dia da semana 3-letras em maiusculas
//
// Exemplos:
//
// calDateFormat = "mm/dd/aa";
// calDateFormat = "Semana,  dd de Mes de aaaa";
// calDateFormat = "smna, mon dd, aaaa";
// ou qualquer outro formato que tenha strings como as definidas acima.
// leiaute default para formato de data 

if (!self.dw&&parent.dw)
	var dw = function (sdiv,stexto,frame){frame=(frame)?frame:self;return parent.dw(sdiv,stexto,frame)}
if (!self.pegaObjeto&&parent.pegaObjeto)
	var pegaObjeto = function (sObj,oOrigem){oOrigem=(oOrigem)?oOrigem:self;return parent.pegaObjeto(sObj,oOrigem)}
if (!self.isArray&&parent.isArray)
	var isArray = parent.isArray
if (!self.isObject&&parent.isObject)
	var isObject = parent.isObject
if (!self.isDate&&parent.isDate)
	var isDate = parent.isDate
if (!self.isString&&parent.isString)
	var isString = parent.isString
//- DEFINICOES DE USUARIO (ESTILOS E FORMATOS)---------------------------------------------------
calDateFormat    = "dd/mm/aaaa";

// leiaute default para window chamada por calShowCalendar(campo,formato)
calWinPrefs='width=190px,height=195px,screenX=200,screenY=300,titlebar=yes'

// defaults de estilo 
calBodyBackground 		= "#B9E7FD"; 				// BG COLOR OF THE TOP FRAME
calBottomBackground 		= "#B9E7FF"; 				// BG COLOR OF THE BOTTOM FRAME
calTableBGColor 			= "#c2c2c2"; 				// BG COLOR OF THE BOTTOM FRAME'S TABLE
calCellColor 				= "#eeeeee"; 				// TABLE CELL BG COLOR OF THE DATE CELLS IN THE BOTTOM FRAME
calFocusCellColor 		= "#ffffff"; 				// TABLE CELL BG COLOR OF THE fOCUS DAY
calBlankCellColor 		= "#c2c2c2"; 				// TABLE CELL BG COLOR OF THE blank cells - off month days
calHeadingcalCellColor 	= "white"; 					// TABLE CELL BG COLOR OF THE WEEKDAY ABBREVIATIONS
calHeadingTextColor 		= "#006595"					// TEXT COLOR OF THE WEEKDAY ABBREVIATIONS
calDateColor 				= "#006595"; 				// TEXT COLOR OF THE LISTED DATES (1-28+)
calFocusColor 				= "#A00505"; 				// TEXT COLOR OF THE SELECTED DATE (OR CURRENT DATE)
calHoverColor 				= "darkred"; 				// TEXT COLOR OF A LINK WHEN YOU HOVER OVER IT
calFontStyle 				= "10pt arial, helvetica"; 			// TEXT STYLE FOR DATES
calHeadingFontStyle 		= "bold 10pt arial, helvetica"; 	// TEXT STYLE FOR WEEKDAY ABBREVIATIONS
calFocusFontStyle 		= "normal 10pt arial, helvetica"; 	// TEXT STYLE FOR WEEKDAY ABBREVIATIONS

// Referencias para formatacao
calBottomBorder  = false;        // TRUE/FALSE (WHETHER TO DISPLAY BOTTOM CALENDAR BORDER)
calTableBorder   = 0;            // SIZE OF CALENDAR TABLE BORDER (BOTTOM FRAME) 0=none

//-------------------------------------------------------------------------------------------------

// Constroi os elementos do calendario para uso
calBuildCalParts();

/**
 * Ajusta data global
 */
function calSetDateField(dateField,dayField,monthField,yearField)
{
	// inicializar variaveis de retorno
	inDate=new Date()
	inDay=inDate.getDate()
	inMonth=inDate.getMonth()
	inYear=inDate.getFullYear()
	VF=0;
	//ASSIGN THE INCOMING FIELD TO RECEIVE DAY BACK
	
	if (dayField&&dayField!=null)
	{
		calDayField = dayField;
		inDay=dayField.value;
		VF=1;
	}
	
	//ASSIGN THE INCOMING FIELD TO RECEIVE DAY BACK
	if (monthField&&monthField!=null)
	{
		calMonthField = monthField;
		inMonth=monthField.value;
		VF+=2;
	}
	
	//ASSIGN THE INCOMING FIELD TO RECEIVE DAY BACK
	if (yearField&&yearField!=null)
	{
		calYearField = yearField;
		inYear=yearField.value;
		VF+=4;
	}
	
	// ASSIGN THE INCOMING FIELD OBJECT TO A GLOBAL VARIABLE
	// GET THE VALUE OF THE INCOMING FIELD
	// ELSE, BUILD A NEW DATE FROM EACH PART
	if (dateField!=null)
	{
		calDateField = dateField;
		VF+=8;
	}
	else
	{
		if (VF>0)
		{
			inDate=inMonth+'/'+inDay+"/"+inYear;
		}
		else
		{
			return false;
		}
	}
	
	// SET calDate TO THE DATE IN THE INCOMING FIELD OR DEFAULT TO Hoje'S DATE
	calSetInitialDate();
	
	// THE CALENDAR FRAMESET DOCUMENTS ARE CREATED BY JAVASCRIPT FUNCTIONS
	calDocTop    = calBuildTopCalFrame();
	calDocBottom = calBuildBottomCalFrame();
}

/**
 * Ajusta a data inicial para hoje ou para o dia/m?s/ano se informados em separado
 */
function calSetInitialDate()
{
	// CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN "." IS USED AS A DELIMITER)
	// (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)
	calDate = new Date(inDate);
	
	// IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE
	if (isNaN(calDate))
	{
		// ADD CUSTOM DATE PARSING HERE
		// IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE
		calDate = new Date();
	}
	
	// KEEP TRACK OF THE CURRENT DAY VALUE
	calDay = calDate.getDate();
	
	// SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES
	// (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH
	//  AND THE DAY WOULD CHANGE TO 2.  SETTING THE DAY TO 1 WILL PREVENT THAT)
	calDate.setDate(1);
}


/**
 * Abre o calend?rio
 */
function calShowCalendar(dateField,dateFormat,dayField,monthField,yearField)
{
	// Verifica se j? n?o existe uma janela aberta. Se existir, primeira fecha.
	try
	{
		parent.newWin.close();
	}
	catch(e){}

	//dateFormat eh opcional
	calSetDateField(dateField,dayField,monthField,yearField);
	if (dateFormat != null)
	{
		calDateFormat=dateFormat;
	}
	// USE THE JAVASCRIPT-GENERATED DOCUMENTS (calDocTop, calDocBottom) IN THE FRAMESET
	calDocFrameset = 
		"<html>\n"+
		"<head>\n"+
		"<title>Calend&aacute;rio&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</title>\n"+
		"<style type='text/css'>\n" +
		"BODY {MARGIN-LEFT: 7px; WIDTH: 300px; COLOR: black; FONT-FAMILY: Arial, Helvetica, sans-serif; BACKGROUND-COLOR: #a1b8cf}\n" +
		"TD {PADDING-RIGHT: 2px; PADDING-LEFT: 2px; FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"TH {BORDER-RIGHT: white 1px; PADDING-RIGHT: 3px; BORDER-TOP: white 1px; PADDING-LEFT: 3px; FONT-WEIGHT: normal; FONT-SIZE: 11px; BORDER-LEFT: white 1px; COLOR: white; BORDER-BOTTOM: white 1px; FONT-FAMILY: Arial, Helvetica, sans-serif; BACKGROUND-COLOR: #7f9dbc; TEXT-ALIGN: center}\n" +
		"FORM {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"input {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"TEXTAREA {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"SELECT {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"UL {LIST-STYLE-POSITION: outside; FONT-SIZE: 12px; FONT-FAMILY: Arial, Helvetica, sans-serif; LIST-STYLE-TYPE: square}\n" +
		"LI {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"OL {LIST-STYLE-POSITION: outside; FONT-SIZE: 12px; FONT-FAMILY: Arial, Helvetica, sans-serif; LIST-STYLE-TYPE: decimal}\n" +
		"input {BORDER-RIGHT: #cccccc 1px solid; BORDER-TOP: #cccccc 1px solid; FONT-SIZE: 12px; BORDER-LEFT: #cccccc 1px solid; BORDER-BOTTOM: #cccccc 1px solid; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: none}\n" +
		"TABLE {FONT-WEIGHT: normal; FONT-SIZE: 12px; COLOR: black; FONT-FAMILY: Arial, Helvetica, sans-serif; BACKGROUND-COLOR: #a1b8cf}\n" +
		"A:link {FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #ffffff; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: none}\n" +
		"A:visited {FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #666666; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: none}\n" +
		"A:hover {FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: underline}\n" +
		"A:active {FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: underline}\n" +
		"THEAD {FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: white; FONT-FAMILY: Arial, Helvetica, sans-serif; BACKGROUND-COLOR: #7f9dbc; TEXT-DECORATION: none}\n" +
		"TFOOT {FONT-WEIGHT: bolder; FONT-SIZE: 10px; COLOR: #000000; FONT-FAMILY: Arial, Helvetica, sans-serif}\n" +
		"TABLE.thead {BORDER-TOP: blue thin; BORDER-COLLAPSE: collapse}\n" +
		"HR {BORDER-RIGHT: #333333 thin solid; BORDER-TOP: #333333 thin solid; BORDER-LEFT: #333333 thin solid; BORDER-BOTTOM: #333333 thin solid; HEIGHT: 1px}\n" +
		"TD.calHeading { text-decoration: none; color:" + calHeadingTextColor + "; font: " + calHeadingFontStyle + "; }\n" +
		"A.focusDay:link { color: " + calFocusColor + "; text-decoration: none; font: " + calFocusFontStyle + "; }\n" +
		"A.focusDay:hover { color: " + calFocusColor + "; text-decoration: none; font: " + calFontStyle + "; }\n" +
		"A.weekday:link { color: " + calDateColor + "; text-decoration: none; font: " + calFontStyle + "; }\n" +
		"A.weekday:hover { color: " + calHoverColor + "; font: " + calFontStyle + "; }\n" +
		".cBottom {position:absolute;top:61px;left:0;}\n"+
		".cTop{position:absolute;top:0;left:0;}\n"+
		"</style>\n" +
		"</head>\n" +
		"<body>\n"+
		"<div id='topCalFrame' align=\"center\" class=cTop>\n"+calDocTop+"\n</div>\n"+	
		"<div id='bottomCalFrame' class=cBottom>\n"+calDocBottom+"\n</div>\n"+	
		"</body>\n"+
		"</html>\n";
	
	/*
	"<FRAMESET ROWS='60,*' FRAMEBORDER='0'>\n" +
	"  <FRAME name='topCalFrame' SRC='javascript:parent.opener.calDocTop' SCROLLING='no' marginheight='0' marginwidth='0'>\n" +
	"  <FRAME name='bottomCalFrame' SRC='javascript:parent.opener.calDocBottom' SCROLLING='no' marginheight='0' marginwidth='0'>\n" +
	"</FRAMESET>\n";
	*/
	
	// DISPLAY THE CALENDAR IN A NEW POPUP WINDOW
	parent.newWin = window.open("javascript:parent.opener.calDocFrameset", "calWin", calWinPrefs);
	parent.newWin.focus();
}


/**
 * Cria o frame superior
 */
function calBuildTopCalFrame()
{
	var calDoc =
		"<form name='calControl' onSubmit='return false;'>\n" +
		"<center>\n" +
		"<table width=100% align=\"center\" border=0>\n" +
		"<tr>\n" +
		"<tr colspan=7>\n" +
		"<center>\n" +
		calGetMonthSelect() +
		"<input name='year' value='" + calDate.getFullYear() + "'type='text' size='4' maxlength='4' onChange='parent.opener.calSetYear()' >\n" +
		"</center>\n" +
		"</td>\n" +
		"</tr>\n" +
		"<tr>\n" +
		"<td colspan=7 align=center>\n" +
		"<input type='button' name='previousYear' value='<<' title='Ano anterior' onClick='parent.opener.calSetPreviousYear()'>\n" +
		"<input type='button' name='previousMonth' value=' <' title='Mes anterior' onClick='parent.opener.calSetPreviousMonth()'>\n" +
		"<input type='button' name='Hoje' value='Hoje' title='Dia de Hoje' onClick='parent.opener.calSetHoje()'>\n" + 
		"<input type='button' name='nextMonth' value='> ' title ='Mes seguinte' onClick='parent.opener.calSetNextMonth()'>\n" + 
		"<input type='button' name='nextYear' value='>>'  title='Ano seguinte' onClick='parent.opener.calSetNextYear()'>\n" +
		"</td>\n" +
		"</tr>\n" +
		"</table>\n" +
		"</center>\n" +
		"</form>\n" 
	return calDoc;
}


/**
 * Cria o frame inferior
 */
function calBuildBottomCalFrame()
{
	// START CALENDAR DOCUMENT
	var calDoc = calendarBegin;
	
	// GET MONTH, AND YEAR FROM GLOBAL CALENDAR DATE
	month = calDate.getMonth();
	year = calDate.getFullYear();
	
	// GET GLOBALLY-TRACKED DAY VALUE (PREVENTS JAVASCRIPT DATE ANOMALIES)
	day = calDay; 
	
	var i = 0;
	
	// DETERMINE THE NUMBER OF DAYS IN THE CURRENT MONTH
	var days = calGetDaysInMonth();
	
	// IF GLOBAL DAY VALUE IS > THAN DAYS IN MONTH, HIGHLIGHT LAST DAY IN MONTH
	if (day > days)
	{
		day = days;
	}
	
	// DETERMINE WHAT DAY OF THE WEEK THE CALENDAR STARTS ON
	var firstOfMonth = new Date (year, month, 1);
	
	// GET THE DAY OF THE WEEK THE FIRST DAY OF THE MONTH FALLS ON
	var startingPos = firstOfMonth.getDay();
	days += startingPos;
	
	// KEEP TRACK OF THE COLUMNS, START A NEW ROW AFTER EVERY 7 COLUMNS
	var columnCount = 0;
	
	// MAKE BEGINNING NON-DATE CELLS BLANK
	for (i = 0; i < startingPos; i++)
	{
		calDoc += blankCell;
		columnCount++;
	}
	
	// SET VALUES FOR DAYS OF THE MONTH
	var currentDay = 0;
	var dayType = "semana";
	
	// DATE CELLS CONTAIN A NUMBER
	for (i = startingPos; i < days; i++)
	{
		var paddingChar = "&nbsp;";
		
		// ADJUST SPACING SO THAT ALL LINKS HAVE RELATIVELY EQUAL WIDTHS
		if (i-startingPos+1 < 10)
		{
			padding = "&nbsp;&nbsp;";
		}
		else
		{
			padding = "&nbsp;";
		}
		
		// GET THE DAY CURRENTLY BEING WRITTEN
		currentDay = i-startingPos+1;
		
		// SET THE type OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR
		if (currentDay == day)
		{
			dayType = "focusDay";
		}
		else
		{
			dayType = "weekday";
		}
		
		// ADD THE DAY TO THE CALENDAR STRING
		// Adicionado o script de window.close(), pois n?o guarda referencia do window.open para
		// janelas modais do netscape, by Glauber Rodrigues da Silva
		calDoc += "<td align=center bgcolor='" +((dayType=="focusDay")?calFocusCellColor:calCellColor) + "'>" +
		"<a class='" + dayType + "'  href='javascript: parent.opener.calReturnDate(" + 
		currentDay + "); window.close();'>" + padding + currentDay + paddingChar + "</a></td>\n";
		
		columnCount++;
		
		// START A NEW ROW WHEN NECESSARY
		if (columnCount % 7 == 0)
		{
			calDoc += "</tr>\n<tr>\n";
		}
	}
	
	// MAKE REMAINING NON-DATE CELLS BLANK
	for (i=days; i<42; i++)
	{
		calDoc += blankCell;
		columnCount++;
		
		// START A NEW ROW WHEN NECESSARY
		if (columnCount % 7 == 0)
		{
			calDoc += "</tr>\n";
			if (i<41)
			{
				calDoc += "<tr>\n";
			}
		}
	}
	
	// FINISH THE NEW CALENDAR PAGE
	calDoc += calendarEnd;
	
	// RETURN THE COMPLETED CALENDAR PAGE
	return calDoc;
}


// WRITE THE MONTHLY CALENDAR TO THE BOTTOM CALENDAR FRAME
function calWriteCalendar() {
	
	// CREATE THE NEW CALENDAR FOR THE SELECTED MONTH & YEAR
	calDocBottom = calBuildBottomCalFrame();
	
	// WRITE THE NEW CALENDAR TO THE BOTTOM FRAME
	dw('bottomCalFrame',calDocBottom,parent.newWin);
	/*
	parent.newWin.frames.bottomCalFrame.document.open();
	parent.newWin.frames.bottomCalFrame.document.write(calDocBottom);
	parent.newWin.frames.bottomCalFrame.document.close();
	*/
}


// SET THE CALENDAR TO Hoje'S DATE AND DISPLAY THE NEW CALENDAR
function calSetHoje()
{
	// SET GLOBAL DATE TO Hoje'S DATE
	calDate = new Date();
	// SET DAY MONTH AND YEAR TO Hoje'S DATE
	var month = calDate.getMonth();
	var year  = calDate.getFullYear();
	calDay  =  calDate.getDate();
	// SET MONTH IN DROP-DOWN LIST
	omonth=pegaObjeto('month',parent.newWin)
	omonth.selectedIndex = month;
	
	// SET YEAR VALUE
	oyear=pegaObjeto('year',parent.newWin)
	oyear.value = year;
	
	// DISPLAY THE NEW CALENDAR
	calWriteCalendar();
}


// SET THE GLOBAL DATE TO THE NEWLY ENTERED YEAR AND REDRAW THE CALENDAR
function calSetYear()
{
	// GET THE NEW YEAR VALUE
	var oyear  = pegaObjeto('year',parent.newWin)
	var year =oyear.value
	// IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR
	if (calIsFourDigitYear(year))
	{
		calDate.setFullYear(year);
		calWriteCalendar();
	}
	else
	{
		// HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH
		oyear.focus();
		oyear.select();
	}
}


// SET THE GLOBAL DATE TO THE SELECTED MONTH AND REDRAW THE CALENDAR
function calSetCurrentMonth()
{
	// GET THE NEWLY SELECTED MONTH AND CHANGE THE CALENDAR ACCORDINGLY
	var omonth = pegaObjeto('month',parent.newWin)
	var month= omonth.selectedIndex;
	
	calDate.setMonth(month);
	calWriteCalendar();
}


// SET THE GLOBAL DATE TO THE PREVIOUS YEAR AND REDRAW THE CALENDAR
function calSetPreviousYear()
{
	var oyear  = pegaObjeto('year',parent.newWin)
	var year =oyear.value
	
	if (calIsFourDigitYear(year) && year > 1000)
	{
		year--;
		calDate.setFullYear(year);
		oyear.value = year;
		calWriteCalendar();
	}
}


// SET THE GLOBAL DATE TO THE PREVIOUS MONTH AND REDRAW THE CALENDAR
function calSetPreviousMonth()
{
	var oyear  = pegaObjeto('year',parent.newWin)
	var year =oyear.value
	
	if (calIsFourDigitYear(year))
	{
		var omonth = pegaObjeto('month',parent.newWin)
		var month= omonth.selectedIndex;
		// IF MONTH IS JANUARY, SET MONTH TO DECEMBER AND DECREMENT THE YEAR
		if (month == 0)
		{
			month = 11;
			if (year > 1000)
			{
				year--;
				calDate.setFullYear(year);
				oyear.value = year;
			}
		}
		else
		{
			month--;
		}
		calDate.setMonth(month);
		omonth.selectedIndex= month;
		calWriteCalendar();
	}
}


// SET THE GLOBAL DATE TO THE NEXT MONTH AND REDRAW THE CALENDAR
function calSetNextMonth()
{
	var oyear = pegaObjeto('year',parent.newWin)
	var year= oyear.value;
	
	if (calIsFourDigitYear(year))
	{
		var omonth = pegaObjeto('month',parent.newWin)
		var month= omonth.selectedIndex;
		// IF MONTH IS DECEMBER, SET MONTH TO JANUARY AND INCREMENT THE YEAR
		if (month == 11)
		{
			month = 0;
			year++;
			calDate.setFullYear(year);
			oyear.value = year;
		}
		else
		{
			month++;
		}
		calDate.setMonth(month);
		omonth.selectedIndex= month;
		calWriteCalendar();
	}
}


// SET THE GLOBAL DATE TO THE NEXT YEAR AND REDRAW THE CALENDAR
function calSetNextYear()
{
	var oyear = pegaObjeto('year',parent.newWin)
	var year= oyear.value;
	if (calIsFourDigitYear(year))
	{
		year++;
		calDate.setFullYear(year);
		oyear.value = year;
		calWriteCalendar();
	}
}


/**
 * Retorna o n?mero de dias no m?s
 */
function calGetDaysInMonth()
{
	var days;
	var month = calDate.getMonth()+1;
	var year  = calDate.getFullYear();
	
	// RETURN 31 DAYS
	if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
	{
		days=31;
	}
	// RETURN 30 DAYS
	else if (month==4 || month==6 || month==9 || month==11)
	{
		days=30;
	}
	// RETURN 29 DAYS
	else if (month==2)
	{
		if (isLeapYear(year))
		{
			days=29;
		}
		// RETURN 28 DAYS
		else
		{
			days=28;
		}
	}
	return (days);
}


/**
 * Verifica se o ano ? bissexto
 */
function isLeapYear (Year)
{
	if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0))
	{
		return (true);
	}
	else
	{
		return (false);
	}
}


// ENSURE THAT THE YEAR IS FOUR DIGITS IN LENGTH
function calIsFourDigitYear(year)
{
	var oyear = pegaObjeto('year',parent.newWin)
	var year= oyear.value;
	
	if (year.length != 4)
	{
		oyear.value = calDate.getFullYear();
		oyear.select();
		oyear.focus();
	}
	else
	{
		return true;
	}
}

// BUILD THE MONTH SELECT LIST
function calGetMonthSelect()
{
	monthArray = new Array('Janeiro', 'Fevereiro', 'Mar?o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
	
	// DETERMINE MONTH TO SET AS DEFAULT
	var activeMonth = calDate.getMonth();
	
	// START HTML SELECT LIST ELEMENT
	monthSelect = "<select name='month' onChange='parent.opener.calSetCurrentMonth()'>\n";
	
	// LOOP THROUGH MONTH ARRAY
	for (i in monthArray)
	{
		// SHOW THE CORRECT MONTH IN THE SELECT LIST
		if (i == activeMonth)
		{
			monthSelect += "<option selected>" + monthArray[i] + "\n";
		}
		else
		{
			monthSelect += "<option>" + monthArray[i] + "\n";
		}
	}
	monthSelect += "</select>\n";
	
	// RETURN A STRING VALUE WHICH CONTAINS A SELECT LIST OF ALL 12 MONTHS
	return monthSelect;
}


// SET DAYS OF THE WEEK DEPENDING ON LANGUAGE
function calCreateWeekdayList()
{
	weekdayList  = new Array('Domingo','Segunda-feira', 'Ter?a-feira', 'Quarta-feira', 'Quarta-feira', 'Quinta-Feira', 'Sexta-feira', 'S?bado');
	weekdayArray = new Array('Do','Sg','Tr','Qu','Qt','Sx','Sb');
	
	// START HTML TO HOLD WEEKDAY NAMES IN TABLE FORMAT
	var weekdays = "<tr bgcolor='" + calHeadingcalCellColor + "'>\n";
	
	// LOOP THROUGH WEEKDAY ARRAY
	for (i in weekdayArray)
	{
		weekdays += "<td class='calHeading' align=center>" + weekdayArray[i] + "</td>\n";
	}
	weekdays += "</tr>\n";
	
	// RETURN TABLE ROW OF WEEKDAY ABBREVIATIONS TO DISPLAY ABOVE THE CALENDAR
	return weekdays;
}


// PRE-BUILD PORTIONS OF THE CALENDAR (FOR PERFORMANCE REASONS)
function calBuildCalParts()
{
	// GENERATE WEEKDAY HEADERS FOR THE CALENDAR
	weekdays = calCreateWeekdayList();
	
	// BUILD THE BLANK CELL ROWS
	blankCell = "<td align=center bgcolor='" + calBlankCellColor + "'>&nbsp;&nbsp;&nbsp;</td>\n";
	
	// BUILD THE TOP PORTION OF THE CALENDAR PAGE USING CSS TO CONTROL SOME DISPLAY ELEMENTS
	calendarBegin = "<center>\n";
	
	// NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE TABLE OUTLINES PROPERLY
	if (document.layers)
	{
		calendarBegin += "<table cellpadding=0 cellspacing=1 border=" + calTableBorder + " align='center' bgcolor='" + calTableBGColor + "'>\n<tr>\n<tr>\n";
	}
	
	// BUILD WEEKDAY calHeadingS
	calendarBegin += "<table cellpadding=0 cellspacing=1 border=" + calTableBorder + " align='center' bgcolor='" + calTableBGColor + "'>\n" +	weekdays + "<tr>\n";
	
	// BUILD THE BOTTOM PORTION OF THE CALENDAR PAGE
	calendarEnd = "";
	
	// WHETHER OR NOT TO DISPLAY A THICK LINE BELOW THE CALENDAR
	if (calBottomBorder)
	{
		calendarEnd += "<tr></tr>\n";
	}
	
	// NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE BORDERS PROPERLY
	if (document.layers)
	{
		calendarEnd += "</td>\n</tr>\n</table>\n";
	}
	
	// END THE TABLE AND HTML DOCUMENT
	calendarEnd +=	"</table>\n</center>\n" 
}


// REPLACE ALL INSTANCES OF find WITH replace
// inString: the string you want to convert
// find:     the value to search for
// replace:  the value to substitute
//
// usage:    calJsReplace(inString, find, replace);
// example:  calJsReplace("To be or not to be", "be", "ski");
//           result: "To ski or not to ski"
//
function calJsReplace(inString, find, replace)
{
	var outString = "";
	
	if (!inString)
	{
		return "";
	}
	
	// REPLACE ALL INSTANCES OF find WITH replace
	if (inString.indexOf(find) != -1)
	{
		// SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find
		t = inString.split(find);
		
		// JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace
		return (t.join(replace));
	}
	else
	{
		return inString;
	}
}

// ENSURE THAT VALUE IS TWO DIGITS IN LENGTH
function calMakeTwoDigit(inValue)
{
	var numVal = parseInt(inValue, 10);
	
	// VALUE IS LESS THAN TWO DIGITS IN LENGTH
	if (numVal < 10)
	{
		// ADD A LEADING ZERO TO THE VALUE AND RETURN IT
		return("0" + numVal);
	}
	else
	{
		return numVal;
	}
}


// SET FIELD VALUE TO THE DATE SELECTED AND CLOSE THE CALENDAR WINDOW
function calReturnDate(inDay)
{
	// inDay = THE DAY THE USER CLICKED ON
	calDate.setDate(inDay);
	// SET THE DATE RETURNED TO THE USER
	var day           = calDate.getDate();
	var month         = calDate.getMonth()+1;
	var year          = calDate.getFullYear();
	var monthString   = monthArray[calDate.getMonth()];
	var monthAbbrev   = monthString.substring(0,3);
	var weekday       = weekdayList[calDate.getDay()];
	var weekdayAbbrev = weekday.substring(0,3);
	
	outDate = calDateFormat;
	
	// RETURN TWO DIGIT DAY
	outDay=day;
	outMonth = month;
	outYear = year;

	if (calDateFormat.indexOf("DD") != -1)
	{
		day = calMakeTwoDigit(day);
		outDate = calJsReplace(outDate, "DD", day);
	}
	// RETURN ONE OR TWO DIGIT DAY
	else if (calDateFormat.indexOf("dd") != -1)
	{
		outDate = calJsReplace(outDate, "dd", day);
	}
	
	// RETURN TWO DIGIT MONTH
	if (calDateFormat.indexOf("MM") != -1)
	{
		month = calMakeTwoDigit(month);
		outMonth=month;
		outDate = calJsReplace(outDate, "MM", month);
	}
	// RETURN ONE OR TWO DIGIT MONTH
	else if (calDateFormat.indexOf("mm") != -1)
	{
		outMonth=month;
		outDate = calJsReplace(outDate, "mm", month);
	}
	
	// RETURN FOUR-DIGIT YEAR
	if (calDateFormat.indexOf("aaaa") != -1)
	{
		outDate = calJsReplace(outDate, "aaaa", year);
	} 
	else if (calDateFormat.indexOf("AAAA") != -1)
	{
		outDate = calJsReplace(outDate, "AAAA", year);
	} 
	// RETURN TWO-DIGIT YEAR
	else if (calDateFormat.indexOf("aa") != -1)
	{
		var yearString = "" + year;
		var yearString = yearString.substring(2,4);
		outDate = calJsReplace(outDate, "aa", yearString);
	}
	else if (calDateFormat.indexOf("AA") != -1)
	{
		var yearString = "" + year;
		var yearString = yearString.substring(2,4);
		outDate = calJsReplace(outDate, "AA", yearString);
	}
	
	// RETURN DAY OF MONTH (Initial Caps)
	if (calDateFormat.indexOf("Mes") != -1)
	{
		outDate = calJsReplace(outDate, "Mes", monthString);
	}
	// RETURN DAY OF MONTH (lowercase letters)
	else if (calDateFormat.indexOf("mes") != -1)
	{
		outDate = calJsReplace(outDate, "mes", monthString.toLowerCase());
	}
	// RETURN DAY OF MONTH (UPPERCASE LETTERS)
	else if (calDateFormat.indexOf("MES") != -1)
	{
		outDate = calJsReplace(outDate, "MES", monthString.toUpperCase());
	}
	
	// RETURN DAY OF MONTH 3-DAY ABBREVIATION (Initial Caps)
	if (calDateFormat.indexOf("Mon") != -1)
	{
		outDate = calJsReplace(outDate, "Mon", monthAbbrev);
	}
	// RETURN DAY OF MONTH 3-DAY ABBREVIATION (lowercase letters)
	else if (calDateFormat.indexOf("mon") != -1)
	{
		outDate = calJsReplace(outDate, "mon", monthAbbrev.toLowerCase());
	}
	// RETURN DAY OF MONTH 3-DAY ABBREVIATION (UPPERCASE LETTERS)
	else if (calDateFormat.indexOf("MON") != -1)
	{
		outDate = calJsReplace(outDate, "MON", monthAbbrev.toUpperCase());
	}
	
	// RETURN WEEKDAY (Initial Caps)
	if (calDateFormat.indexOf("Semana") != -1)
	{
		outDate = calJsReplace(outDate, "Semana", weekday);
	}
	// RETURN WEEKDAY (lowercase letters)
	else if (calDateFormat.indexOf("semana") != -1)
	{
		outDate = calJsReplace(outDate, "semana", weekday.toLowerCase());
	}
	// RETURN WEEKDAY (UPPERCASE LETTERS)
	else if (calDateFormat.indexOf("SEMANA") != -1)
	{
		outDate = calJsReplace(outDate, "SEMANA", weekday.toUpperCase());
	}
	
	// RETURN WEEKDAY 3-DAY ABBREVIATION (Initial Caps)
	if (calDateFormat.indexOf("Smna") != -1)
	{
		outDate = calJsReplace(outDate, "Smna", weekdayAbbrev);
	}
	// RETURN WEEKDAY 3-DAY ABBREVIATION (lowercase letters)
	else if (calDateFormat.indexOf("smna") != -1)
	{
		outDate = calJsReplace(outDate, "smna", weekdayAbbrev.toLowerCase());
	}
	// RETURN WEEKDAY 3-DAY ABBREVIATION (UPPERCASE LETTERS)
	else if (calDateFormat.indexOf("SMNA") != -1)
	{
		outDate = calJsReplace(outDate, "SMNA", weekdayAbbrev.toUpperCase());
	}
	
	// SET THE VALUE OF THE FIELDS THAT WAS PASSED TO THE CALENDAR
	if (4&VF)
	{
		calYearField.value=outYear;calYearField.focus();
	}
	if (2&VF)
	{
		calMonthField.value=outMonth;calMonthField.focus();
	}
	if (1&VF)
	{
		calDayField.value=outDay; calDayField.focus();
	}
	// SET THE VALUE OF THE FIELD THAT WAS PASSED TO THE CALENDAR
	if (8&VF)
	{
		calDateField.value = outDate;calDateField.focus();
	}
	
	// CLOSE THE CALENDAR WINDOW
	// parent.newWin.close();
	// N?o fecha mais via referencia e sim no pr?prio script, pois esta ocorrendo erro no netscape
	// porque as janelas auxiliares s?o modais e n?o retornam referencia no window.open();
	// by Glauber Rodrigues da Silva
}

/**
 * Atualiza a data final mostrada em um campo, de acordo com uma data inicial e uma quantidade de dias.
 *
 * @param dataInicial    O campo de formul?rio com a data inicial
 * @param dataFinal      O campo de formul?rio com a data final
 * @param quantidadeDias O campo de formul?rio com a quantidade de dias
 */
function atualizarDataFinal(dataInicial, dataFinal, quantidadeDias)
{
   if (dataInicial.value && parseInt(quantidadeDias.value))
   {
      var dia = dataInicial.value.substring(0, 2);
      var mes = dataInicial.value.substring(3, 5);
      var ano = dataInicial.value.substring(6, 10);

      var date = new Date(Date.UTC(ano, mes - 1, dia));
      date.setTime(date.getTime() + quantidadeDias.value * (3600 * 24 * 1000));

      dataFinal.value = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
   }
}

/**
 * Atualiza a quantidade de dias mostrada em um campo, de acordo com uma data inicial e uma data final
 *
 * @param dataInicial    O campo de formul?rio com a data inicial
 * @param dataFinal      O campo de formul?rio com a data final
 * @param quantidadeDias O campo de formul?rio com a quantidade de dias
 */
function atualizarQuantidadeDias(dataInicial, dataFinal, quantidadeDias)
{
   if (dataInicial.value && dataFinal.value)
   {
      var diaInicial = dataInicial.value.substring(0, 2);
      var mesInicial = dataInicial.value.substring(3, 5);
      var anoInicial = dataInicial.value.substring(6, 10);

      var diaFinal = dataFinal.value.substring(0, 2);
      var mesFinal = dataFinal.value.substring(3, 5);
      var anoFinal = dataFinal.value.substring(6, 10);

      dateInicial = new Date(Date.UTC(anoInicial, mesInicial - 1, diaInicial));
      dateFinal   = new Date(Date.UTC(anoFinal, mesFinal - 1, diaFinal));

      quantidadeDias.value = ((dateFinal.getTime() - dateInicial.getTime()) / (3600 * 24 * 1000)) + 1;
   }
}
