// convert all characters to lowercase to simplify testing
/* @ Akari this is at commons.js
var agt=navigator.userAgent.toLowerCase();

var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
            && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
            && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav6up = (is_nav && (is_major >= 5));
var is_gecko = (agt.indexOf('gecko') != -1);
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie7	  = (is_ie && (agt.indexOf("msie 7.")!=-1) || (agt.indexOf("msie 8.")!=-1)); // or 8
var is_ie5up  = is_ie6 || is_ie7;
var is_op = (agt.indexOf("opera") != -1);
var is_safari = (agt.indexOf("safari") != -1);
*/

function dropdias() { 
    qual = arguments[0] ? arguments[0] : 0;
    for (cont=1;cont<32;cont++) {
      document.write("<option value='" + cont + "'" + ( (qual) == cont ? " selected='selected'" : "" ) + ">" + (cont) + "</option>");
    }
    document.write("<option value='0'"+( qual == 0 ? " selected='selected'" : "")+"></option>");
  }
  
  function dropmes() { 

   qual = arguments[0] ? arguments[0] : 0;
  
    var mes = new Array();
    
    mes[1] = "Jan";
    mes[2] = "Fev";
    mes[3] = "Mar";
    mes[4] = "Abr";
    mes[5] = "Mai";
    mes[6] = "Jun";
    mes[7] = "Jul";
    mes[8] = "Ago";
    mes[9] = "Set";
    mes[10] = "Out";
    mes[11] = "Nov";
    mes[12] = "Dez";

    for (cont=1;cont<13;cont++) {
      document.write("<option value='" + cont + "'" + ( qual == cont ? " selected='selected'" : "" ) + ">" + mes[cont] + "</option>");
    }
    
    document.write("<option value='0'"+( qual == 0 ? " selected='selected'" : "")+"></option>");

  }

/**
* Global variables
*/
	dynCalendar_layers          = new Array();
	dynCalendar_mouseoverStatus = false;
  
/**
* The calendar constructor
*
* @access public
* @param string objName      Name of the object that you create
* @param string callbackFunc Name of the callback function
* @param string OPTIONAL     Optional images path
* @param string OPTIONAL     Optional layer name
*/
	function dynCalendar(objName, callbackFunc, imgPath)
	{
		// Todays date

		this.today          = new Date();
		this.date           = this.today.getDate();
		this.month          = this.today.getMonth();
		this.year           = this.today.getFullYear();

		this.objName        = objName;
		this.callbackFunc   = callbackFunc;
		this.imagesPath     = imgPath;
		this.layerID        = 'dynCalendar_layer_' + dynCalendar_layers.length;

		this.useMonthCombo  = true;
		this.useYearCombo   = true;
		this.yearComboRange = 90;

		this.currentMonth   = this.month;
		this.currentYear    = this.year;

		this.show              = dynCalendar_show;
		this.writeHTML         = dynCalendar_writeHTML;

		// Accessor methods
		this.setImagesPath     = dynCalendar_setImagesPath;
		this.setMonthCombo     = dynCalendar_setMonthCombo;
		this.setYearCombo      = dynCalendar_setYearCombo;
		this.setCurrentMonth   = dynCalendar_setCurrentMonth;
		this.setCurrentYear    = dynCalendar_setCurrentYear;
		this.setYearComboRange = dynCalendar_setYearComboRange;

		// Layer manipulation
		this._getLayer         = dynCalendar_getLayer;
		this._hideLayer        = dynCalendar_hideLayer;
		this._showLayer        = dynCalendar_showLayer;
		this._setLayerPosition = dynCalendar_setLayerPosition;
		this._setHTML          = dynCalendar_setHTML;

		// Miscellaneous
		this._getDaysInMonth   = dynCalendar_getDaysInMonth;
    	this._mouseover        = dynCalendar_mouseover;

		dynCalendar_layers[dynCalendar_layers.length] = this;
		this.writeHTML();
	}

/**
* Shows the calendar, or updates the layer if
* already visible.
*
* @access public
* @param integer month Optional month number (0-11)
* @param integer year  Optional year (YYYY format)
*/
	function dynCalendar_show(left)
	{
		// Variable declarations to prevent globalisation
		var month, year, monthnames, numdays, thisMonth, firstOfMonth;
		var ret, row, i, cssClass, linkHTML, previousMonth, previousYear;
		var nextMonth, nextYear, prevImgHTML, prevLinkHTML, nextImgHTML, nextLinkHTML;
		var monthComboOptions, monthCombo, yearComboOptions, yearCombo, html;

		this.currentMonth = month = arguments[0] ? arguments[0] : this.currentMonth;
		this.currentYear  = year  = arguments[1] ? arguments[1] : this.currentYear;

		monthnames = new Array(); // dont ask, IE6 crashes if I add the values here
		monthnames.push('Jan.');
		monthnames.push('Fev.');
		monthnames.push('Mar.');
		monthnames.push('Abr.');
		monthnames.push('Mai.');
		monthnames.push('Jun.');
		monthnames.push('Jul.');
		monthnames.push('Ago.');
		monthnames.push('Set.');
		monthnames.push('Out.');
		monthnames.push('Nov.');
		monthnames.push('Dez.');
		numdays    = this._getDaysInMonth(month, year);

		thisMonth    = new Date(year, month, 1);
		firstOfMonth = thisMonth.getDay();

		// First few blanks up to first day
		ret = new Array(new Array());
		for(i=0; i<firstOfMonth; i++){
			ret[0][ret[0].length] = '<td>&nbsp;</td>';
		}

		// Main body of calendar
		row = 0;
		i   = 1;
		while(i <= numdays){
			if(ret[row].length == 7){
				ret[++row] = new Array();
			}

			cssClass = (i == this.date && month == this.month && year == this.year) ? 'dynCalendar_today' : 'dynCalendar_day';
			linkHTML = '<a href="javascript: ' + this.callbackFunc + '(' + i + ', ' + (Number(month) + 1) + ', ' + year + '); ' + this.objName + '._hideLayer()">' + (i++) + '</a>';
			ret[row][ret[row].length] = '<td align="center" class="' + cssClass + '">' + linkHTML + '</td>';
		}

		// Format the HTML
		for(i=0; i<ret.length; i++){
			ret[i] = ret[i].join('\n') + '\n';
		}

		previousYear  = thisMonth.getFullYear();
		previousMonth = thisMonth.getMonth() - 1;
		if(previousMonth < 0){
			previousMonth = 11;
			previousYear--;
		}
		
		nextYear  = thisMonth.getFullYear();
		nextMonth = thisMonth.getMonth() + 1;
		if(nextMonth > 11){
			nextMonth = 0;
			nextYear++;
		}

		prevImgHTML  = '<img src="' + this.imagesPath + '/prev.gif" alt="<<" border="0" />';
		prevLinkHTML = '<a href="javascript: ' + this.objName + '.show(' + previousMonth + ', ' + previousYear + ')">' + prevImgHTML + '</a>';
		nextImgHTML  = '<img src="' + this.imagesPath + '/next.gif" alt="<<" border="0" />';
		nextLinkHTML = '<a href="javascript: ' + this.objName + '.show(' + nextMonth + ', ' + nextYear + ')">' + nextImgHTML + '</a>';

		if (this.useMonthCombo) {
			monthComboOptions = '';
			for (i=0; i<12; i++) {
				selected = (i == thisMonth.getMonth() ? 'selected="selected"' : '');
				monthComboOptions += '<option value="' + i + '" ' + selected + '>' + monthnames[i] + '</option>';
			}
			monthCombo = '<select id="dyn_ms'+this.objName+'" name="months" style="width:60px" onchange="' + this.objName + '.show(this.options[this.selectedIndex].value, ' + this.objName + '.currentYear)">' + monthComboOptions + '</select>';
		} else {
			monthCombo = monthnames[thisMonth.getMonth()];
		}
		
		if (this.useYearCombo) {
			yearComboOptions = '';
			for (i = thisMonth.getFullYear() - this.yearComboRange; i <= (thisMonth.getFullYear() + 5); i++) {
				selected = (i == thisMonth.getFullYear() ? 'selected="selected"' : '');
				yearComboOptions += '<option value="' + i + '" ' + selected + '>' + i + '</option>';
			}
			yearCombo = '<select id="dyn_ys'+this.objName+'" style="border: 1px groove;width:60px" name="years" onchange="' + this.objName + '.show(' + this.objName + '.currentMonth, this.options[this.selectedIndex].value)">' + yearComboOptions + '</select>';
		} else {
			yearCombo = thisMonth.getFullYear();
		}

		html = '<table border="0" bgcolor="#eeeeee">';
		html += '<tr><td class="dynCalendar_header">' + prevLinkHTML + '</td><td colspan="5" align="center" class="dynCalendar_header" nowrap><nobr>' + monthCombo + ' ' + yearCombo + '</nobr></td><td align="right" class="dynCalendar_header">' + nextLinkHTML + '</td></tr>';
		html += '<tr>';
		html += '<td class="dynCalendar_dayname">Dom</td>';
		html += '<td class="dynCalendar_dayname">Seg</td>';
		html += '<td class="dynCalendar_dayname">Ter</td>';
		html += '<td class="dynCalendar_dayname">Qua</td>';
		html += '<td class="dynCalendar_dayname">Qui</td>';
		html += '<td class="dynCalendar_dayname">Sex</td>';
		html += '<td class="dynCalendar_dayname">Sab</td></tr>';
		html += '<tr>' + ret.join('</tr>\n<tr>') + '</tr>';
		html += '</table>';

		this._setHTML(html);
		if (!arguments[0] && !arguments[1]) {
			this._showLayer();
			this._setLayerPosition();
		}

	}

/**
* Writes HTML to document for layer
*
* @access public
*/
	function dynCalendar_writeHTML()
	{

		if (is_ie5up || is_ie7 || is_nav6up || is_gecko) {
			document.write('<a href="javascript: ' + this.objName + '.show()"><img src="' + this.imagesPath + 'dyncalendar.gif" border="0" width="16" height="16" id="calimg_'+ this.layerID +'" style="position:relative;top:-2px" alt=""/></a>');
			// IE won't allow appends on body until it's loaded
			addEvent(window, 'load', new Function("var objOverlay = document.createElement('div');objOverlay.innerHTML = \"<div class='dynCalendar' style='z-index:100;' id='" + this.layerID + "' onmouseover='" + this.objName + "._mouseover(true)' onmouseout='" + this.objName + "._mouseover(false)'></div>\";document.body.appendChild(objOverlay);"));	
		}

	}

/**
* Sets the images path
*
* @access public
* @param string path Path to use for images
*/
	function dynCalendar_setImagesPath(path)
	{
		this.imagesPath = path;
	}

/**
* Turns on/off the month dropdown
*
* @access public
* @param boolean useMonthCombo Whether to use month dropdown or not
*/
	function dynCalendar_setMonthCombo(useMonthCombo)
	{
		this.useMonthCombo = useMonthCombo;
	}

/**
* Turns on/off the year dropdown
*
* @access public
* @param boolean useYearCombo Whether to use year dropdown or not
*/
	function dynCalendar_setYearCombo(useYearCombo)
	{
		this.useYearCombo = useYearCombo;
	}

/**
* Sets the current month being displayed
*
* @access public
* @param boolean month The month to set the current month to
*/
	function dynCalendar_setCurrentMonth(month)
	{
		this.currentMonth = month;
	}

/**
* Sets the current month being displayed
*
* @access public
* @param boolean year The year to set the current year to
*/
	function dynCalendar_setCurrentYear(year)
	{
		this.currentYear = year;
	}

/**
* Sets the range of the year combo. Displays this number of
* years either side of the year being displayed.
*
* @access public
* @param integer range The range to set
*/
	function dynCalendar_setYearComboRange(range)
	{
		this.yearComboRange = range;
	}

/**
* Returns the layer object
*
* @access private
*/
	function dynCalendar_getLayer()
	{
		var layerID = this.layerID;

		if (document.getElementById(layerID)) {

			return document.getElementById(layerID);

		} else if (document.all(layerID)) {
			return document.all(layerID);
		}
	}

/**
* Hides the calendar layer
*
* @access private
*/
	function dynCalendar_hideLayer()
	{    
		this._getLayer().style.visibility = 'hidden';
		if (is_ie6) {
			selects = document.getElementsByTagName("select");
			for (i = 0; i != selects.length; i++) {
				if (selects[i].id.substr(0,6) != 'dyn_ys' && selects[i].id.substr(0,6) != 'dyn_ms')
					selects[i].style.visibility = "visible";
			}
		}
	}

/**
* Shows the calendar layer
*
* @access private
*/
	function dynCalendar_showLayer()
	{
		if (is_ie6) {
		    selects = document.getElementsByTagName("select");
			for (i = 0; i != selects.length; i++) {
				if (selects[i].id.substr(0,6) != 'dyn_ys' && selects[i].id.substr(0,6) != 'dyn_ms')
					selects[i].style.visibility = "hidden";
			}
		}
	    this._getLayer().style.zIndex = 1;
	    this._getLayer().style.display = 'none';
	    this._getLayer().style.visibility = 'visible';
	    try {
	      Effect.toggle(this._getLayer(),'BLIND');
	    } catch (e) {
	      this._getLayer().style.display = '';
	    }
	    
	}

/**
* Sets the layers position
*
* @access private
*/
	function dynCalendar_setLayerPosition()
	{

		// all previous containers must have position relative
		_top = findPosY($('calimg_' + this.layerID)) + 5;
		_left = findPosX($('calimg_' + this.layerID)) + 8;
		this._getLayer().style.top  = _top + "px";
		this._getLayer().style.left = _left + "px";
	    this._getLayer().style.zIndex = 1;
	}

/**
* Sets the innerHTML attribute of the layer
*
* @access private
*/
	function dynCalendar_setHTML(html)
	{
		this._getLayer().innerHTML = html;
	}

/**
* Returns number of days in the supplied month
*
* @access private
* @param integer month The month to get number of days in
* @param integer year  The year of the month in question
*/
	function dynCalendar_getDaysInMonth(month, year)
	{
		monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if (month != 1) {
			return monthdays[month];
		} else {
			return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28);
		}
	}

/**
* Callbacks for document.onclick
*/
	dynCalendar_oldOnclick = document.onclick ? document.onclick : new Function;

	document.onclick = function ()
	{
		if (is_ie5up || is_nav6up || is_gecko) {
			if(!dynCalendar_mouseoverStatus){
				for(i=0; i<dynCalendar_layers.length; ++i){
					dynCalendar_layers[i]._hideLayer();
				}
			}
	
			dynCalendar_oldOnclick(arguments[0] ? arguments[0] : null);
		}
	}

/**
* onMouse(Over|Out) event handler
*
* @access private
* @param boolean status Whether the mouse is over the
*                       calendar or not
*/
	function dynCalendar_mouseover(status)
	{
		dynCalendar_mouseoverStatus = status;
		return true;
	}
    /**
    * When changed, the date fields in the forms are updated by this
    */
    function update_date(formulario, prefix, input)
    {
        if (eval('data_atualizada_' + prefix)) return true;

        yearElement  = $(prefix + '_year');
        monthElement = $(prefix + '_month');
        dayElement   = $(prefix + '_day');
        today = new Date();

        switch (input) {
            case 'year':
                if (monthElement.value != '' || dayElement.value != '') return true;
                monthElement.value = today.getMonth() + 1;
                dayElement.value = today.getDate();
                break;

            case 'month':
                if (yearElement.value != '' || dayElement.value != '') return true;
                yearElement.value = today.getFullYear();
                dayElement.value  = today.getDate();
                break;

            case 'day':
                if (yearElement.value != '' || monthElement.value != '') return true;
                yearElement.value  = today.getFullYear();
                monthElement.value = today.getMonth() + 1;
                break;
        }

        eval('data_atualizada_' + prefix + ' = true');
        return true;
    }

    /**
    * Callback functions for the calendar
    */

    function setDateFromCalendar(formulario, prefix, date, month, year)
    {
        if (eval(prefix + '_disabled') == true) {
            return;
        }
		yearElement  = $(prefix + '_year');
        monthElement = $(prefix + '_month');
        dayElement   = $(prefix + '_day');
        yearElement.value = year;
        monthElement.value = month;
        dayElement.value = date;
    }

  


