﻿
<!-- Bloqueio de menu Contextual nas imagens -->
//inicio das funções em serches.js

/*
IMGonmousedown();
clearInterval(msD);
*/

//var msD = setInterval("IMGonmousedown()",100);
        var msg="© Espaço e Dimensão - Todos os direitos reservados"
        function md(e) 
        {   
          try 
          { 
            if (navigator.appName == 'Microsoft Internet Explorer' && (event.button==2||event.button==3||event.button==4)) 
            {
                alert(msg);
                return false; 
            }
            else
            { 
                if (navigator.appName == 'Netscape' && (e.button == 3 || e.button == 2))
                {
                    document.oncontextmenu = function() { return false; }//aqui certifico-me que não ha hipotese de ele poder usar o right-click
                    alert(msg);
                    document.oncontextmenu = function() { return false; } //ver acima /^\
	                e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                else
                    return true;
             }
          }  
          catch (ex) 
          { 
            if (e.which == 3 || e.which == 2 || e.which == 1) 
            {
                document.oncontextmenu = function() { return false; }
            }
          } 
        }
        
        function DisableIMG()
        {
           // alert("disabling...");
            document.oncontextmenu = function() { return false; }
			document.onmousedown  = md;

        }
        
        function EnableIMG()
        {
            // alert("enabling...");
            //document.oncontextmenu = function() { return true; }
            
        }
        
        function canceldefault(){dragged='true'; return false}
        
        /*
		function IMGonmousedown()
        {
            document.ondragstart   = function() { return false; }
        
            var imgs = document.getElementsByTagName('img');
            for(i=0; i<imgs.length; i++)
            {
                document.ondragstart = canceldefault; //disable image drag
                //imgs[i].onmouseover = DisableIMG;
                imgs[i].onmousemove = DisableIMG;
                imgs[i].onmouseout = EnableIMG;
                imgs[i].onmousedown  = md;
                //imgs[i].click  = md;
                //imgs[i].onmouseup  = md; //No caso do FF, ele iria repetir a mensagem de erro 2x.
            }
            var noclick = document.getElementById('noClickImages');
            if(noclick != null)
            {
                document.ondragstart = canceldefault; //disable image drag
                //noclick.onmouseover = DisableIMG;
                noclick.onmousemove = DisableIMG;
                noclick.onmouseout = EnableIMG;
                noclick.onmousedown  = md;
                //noclick.click  = md;
                //noclick.onmouseup  = md; //No caso do FF, ele iria repetir a mensagem de erro 2x.
            }
        }
		*/

<!-- Favoritos do browser -->

var bookmarkurl="http://www.edimensao.com/"
var bookmarktitle="Espaço e Dimensão"

function addbookmark(){
	if(window.sidebar){
		window.sidebar.addPanel(bookmarktitle,bookmarkurl ,'');
		//alert("firefox");	
	}else if(window.external){
	window.external.AddFavorite(bookmarkurl,bookmarktitle);
		//alert("IE");
	}else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

<!-- Validação Recomendar -->

function validateForm_recom(form1,iframe)
{
	//var form1 = document.getElementById("recom_form");
	 var sErr = '';

	if( form1.mailfromname.value == "" )
	{
		sErr = "Tem de preencher o seu Nome" ;
		
	}
	else if( form1.mailfrom.value == "" )
	{
		sErr = "Tem de preencher o seu Email";
		
	}
	else if( form1.mailto.value == "" )
	{
		sErr = "Tem de preencher o Email de destino";
		
	}
	
	 if(sErr != '')

            {
                        alert(sErr)
                        //document.getElementById("validation").innerHTML = sErr;
            } else
            {
                       document.getElementById(iframe).style.display = "block";
					   form1.submit()
            }	
}
<!-- Validação Geral de Formulários -->

function validateForm_forms(oForm)
{
	var sErr = '';
	if(oForm.NAM.value == 'Nome')
		sErr = "Tem de preencher o seu Nome";
	else if(oForm.NAM.value == '')
		sErr = "Tem de preencher o seu Nome";
	else if(!oForm.PHO.value.match(/^\d{9,}$/ig))
		sErr = "Tem de preencher o seu Telefone";	
	else if(oForm.EML.value != '' &&  !oForm.EML.value.match(/^([+_.A-Za-z0-9\-]+@([A-Za-z\-]+\.)+[A-Za-z\-]{2,}){1}$/ig))
		sErr = "Tem de introduzir correctamente o seu email";
	
		if(sErr != '')
	{
		alert(sErr)
		//document.getElementById("validation").innerHTML = sErr;
		return false;
	}
	else
	{
		return true;
	}
	


}

<!-- Validação de Formulários de detalhes/listagem -->

function validateForm_detalhes(oForm,iframe)

{
            var sErr = '';

            if(oForm.NAM.value == '')

                        sErr = "Tem de preencher o seu Nome";

            else if(!oForm.PHO.value.match(/^\d{9,}$/ig))

                        sErr = "Tem de preencher o seu Telefone"; 
						
		     else if(oForm.EML.value == '')

                        sErr = "Tem de introduzir correctamente o seu email";
         

            else if(oForm.EML.value != '' &&  !oForm.EML.value.match(/^([+_.A-Za-z0-9\-]+@([A-Za-z\-]+\.)+[A-Za-z\-]{2,}){1}$/ig))

                        sErr = "Tem de introduzir correctamente o seu email";

            if(sErr != '')

            {
                        alert(sErr)
                        //document.getElementById("validation").innerHTML = sErr;       
            }
            else
            {
						oForm.submit();
						document.getElementById(iframe).style.display = "block";
            }
}

function reset(iframe)

{
	document.getElementById(iframe).style.display = "none";
}

function validateForm_sugestoes(oForm)

{
            var sErr = '';

            if(oForm.NAM.value == '')

                        sErr = "Tem de preencher o seu Nome";
						
			else if(oForm.NAM.value == 'Nome')

                        sErr = "Tem de preencher o seu Nome"; 

            else if(!oForm.PHO.value.match(/^\d{9,}$/ig))

                        sErr = "Tem de preencher o seu Telefone"; 
			
			else if(oForm.OBS.value == 'Os seus comentários/sugestões...')

                        sErr = "Deve preencher o campo comentários"; 
						
			else if(oForm.OBS.value == '')

                        sErr = "Deve preencher o campo comentários"; 
						
		     else if(oForm.EML.value == '')

                        sErr = "Tem de introduzir correctamente o seu email";
         

            else if(oForm.EML.value != '' &&  !oForm.EML.value.match(/^([+_.A-Za-z0-9\-]+@([A-Za-z\-]+\.)+[A-Za-z\-]{2,}){1}$/ig))

                        sErr = "Tem de introduzir correctamente o seu email";

            if(sErr != '')

            {
                        alert(sErr)
                        //document.getElementById("validation").innerHTML = sErr;       
            }
            else
            {
						show_hide('aviso');
						oForm.submit();
            }
}

function validateForm_newsletter(oForm)

{
            var sErr = '';

            if(oForm.NAM.value == '')

                        sErr = "Tem de preencher o seu Nome";
						
			else if(oForm.NAM.value == 'Nome')

                        sErr = "Tem de preencher o seu Nome"; 
						
		     else if(oForm.EML.value == '')

                        sErr = "Tem de introduzir correctamente o seu email";
         

            else if(oForm.EML.value != '' &&  !oForm.EML.value.match(/^([+_.A-Za-z0-9\-]+@([A-Za-z\-]+\.)+[A-Za-z\-]{2,}){1}$/ig))

                        sErr = "Tem de introduzir correctamente o seu email";

            if(sErr != '')

            {
                        alert(sErr)
                        //document.getElementById("validation").innerHTML = sErr;       
            }
            else
            {
						show_hide('aviso_news');
						oForm.submit();
            }
}

function validateForm_comprar(oForm)

{
            var sErr = '';

            if(oForm.NAM.value == '')

                        sErr = "Tem de preencher o seu Nome";
						
			else if(oForm.NAM.value == 'Nome')

                        sErr = "Tem de preencher o seu Nome"; 

            else if(!oForm.PHO.value.match(/^\d{9,}$/ig))

                        sErr = "Tem de preencher o seu Telefone"; 
						
		     else if(oForm.EML.value == '')

                        sErr = "Tem de introduzir correctamente o seu email";
         

            else if(oForm.EML.value != '' &&  !oForm.EML.value.match(/^([+_.A-Za-z0-9\-]+@([A-Za-z\-]+\.)+[A-Za-z\-]{2,}){1}$/ig))

                        sErr = "Tem de introduzir correctamente o seu email";

            if(sErr != '')

            {
                        alert(sErr)
                        //document.getElementById("validation").innerHTML = sErr;       
            }
            else
            {
						oForm.submit();
            }
}

<!-- Validação do Formulário de Recrutamento -->

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function checkFile( _target )
{
	var acceptable = _target.getAttribute("accept");
	if( _target.value != '' )
	{
		var docTypes = acceptable.split(",");
		for(var i = 0; i <docTypes.length; i++){var r = new RegExp( docTypes[i] , "gi");
			if( _target.value.substr( _target.value.lastIndexOf('.') ).match(r) ){
				return true;
			}
		}
	}
	return false;
}

function validateForm_rec(oForm)
{


	var todayDate = new Date();
	if( String(todayDate.getMonth()).length == 1 )
		dayDate = "0"+(todayDate.getMonth()+1)
	else
		dayDate = todayDate.getMonth()+1;
		
	var stringDate = todayDate.getDate() +"-"+ dayDate  +"-"+ todayDate.getYear();

	var sErr = '';
	var radio_choice = false;
	var check_box = false;
   
   	for (counter = 0; counter < oForm.habli.length; counter++)
	{
		if (oForm.habli[counter].checked)
			radio_choice = true; 
	}
	for (counter = 0; counter < oForm.trabalho.length; counter++)
	{
		if (oForm.trabalho[counter].checked)
			check_box = true; 
	}
	
	if(oForm.nome.value == 'nome*')
		sErr = "Por favor introduza um nome válido!";
	else if(oForm.nome.value == '')
		sErr = "Por favor introduza um nome válido!";
	else if(oForm.morada.value == '')
		sErr = "Por favor, introduza a sua morada."; 
	else if(!radio_choice)
		sErr = "Por favor, introduza as suas habilitações.";
	else if(!check_box)
		sErr = "Por favor, introduza o sector em que preferia trabalhar.";
	else
		if( oForm.fileToUpload.value != '' )
		{
			var docTypes = oForm.fileToUpload.getAttribute("accept").split(",");
			var validFile = false;
			for( var i = 0; i < docTypes.length ; i++ )
			{
				var r = new RegExp( docTypes[i] , "gi");
				if( oForm.fileToUpload.value.substr( oForm.fileToUpload.value.lastIndexOf('.') ).match(r) )
				{
					validFile = true;
					break;
				}
			}
			if( !validFile )
			{
				valid = false;
				sErr = "Por favor introduza um ficheiro válido. ('"+oForm.fileToUpload.getAttribute("accept")+"') ";
			}
		}


	if(sErr != "")
	{
		alert(sErr)
		return false;
	}
	else
	{
		return true;
	}

}
function ObrigaIntroducaoNumeros(ponto,formulario,elemento)
{
	var key=window.event.keyCode;
	var valor=document.forms[formulario].elements[elemento].value;
	
	if(key!=0)
	{
		if(key<48 || key>57)
		{
			if(key==44)
			{
				if(ponto)
				{
					if(valor!='')
					{
						if(valor.match(/,/)!=null)
						{
							window.event.returnValue=false;
						}
					}
					else
					{
						window.event.returnValue=false;
					}
				}
				else
				{
					window.event.returnValue=false;
				}
			}
			else
			{
				window.event.returnValue=false;
			}
		}
	}
}


<!-- Chamada do Lightbox -->

        function GroupDelegate(id) {
        var objLink = document.getElementById(id);
        Lightbox.start(objLink);
         }
		 
<!-- Simulador de Crédito -->

function loadContent(place)
{
	var frm=place.contentWindow.document.all['form'];
	if(frm)
	{
		if(document.getElementById('response').style.display=="none")
		{
			document.getElementById('response').style.display="block";
		}
		if(document.getElementById('aplAmount').value)
		{
			oMensal.style.display = 'block'	
			oTotal.style.display = 'none'	
		}
		else
		{
			oMensal.style.display = 'none'	
			oTotal.style.display = 'block'	
		}
		for(var i=0; i<frm.length; i++)
		{
			if(frm[i].value != '0')
				document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value;	
		}
	}
}

<!-- Chamadas de Impressão -->

function impressao(rid) {
link = window.open("printex.htm?RID="+rid,"_blank","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=620");
}

function impressao_emp(ent) {
link = window.open("printex2.htm?ENT="+ent,"_blank","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=620");
} 


<!-- Format Number -->

// Abbreviations: LODP = Left Of Decimal Point, RODP = Right Of Decimal Point
Number.formatFunctions = {count:0};

// Constants useful for controlling the format of numbers in special cases.
Number.prototype.NaN         = 'NaN';
Number.prototype.posInfinity = 'Infinity';
Number.prototype.negInfinity = '-Infinity';

Number.prototype.numberFormat = function(format, context) {
    if (isNaN(this) ) {
        return Number.prototype.NaNstring;
    }
    else if (this == +Infinity ) {
        return Number.prototype.posInfinity;
    }
    else if ( this == -Infinity) {
        return Number.prototype.negInfinity;
    }
    else if (Number.formatFunctions[format] == null) {
        Number.createNewFormat(format);
    }
    return this[Number.formatFunctions[format]](context);
}

Number.createNewFormat = function(format) {
    var funcName = "format" + Number.formatFunctions.count++;
    Number.formatFunctions[format] = funcName;
    var code = "Number.prototype." + funcName + " = function(context){\n";

    // Decide whether the function is a terminal or a pos/neg/zero function
    var formats = format.split(";");
    switch (formats.length) {
        case 1:
            code += Number.createTerminalFormat(format);
            break;
        case 2:
            code += "return (this < 0) ? this.numberFormat(\""
                + String.escape(formats[1])
                + "\", 1) : this.numberFormat(\""
                + String.escape(formats[0])
                + "\", 2);";
            break;
        case 3:
            code += "return (this < 0) ? this.numberFormat(\""
                + String.escape(formats[1])
                + "\", 1) : ((this == 0) ? this.numberFormat(\""
                + String.escape(formats[2])
                + "\", 2) : this.numberFormat(\""
                + String.escape(formats[0])
                + "\", 3));";
            break;
        default:
            code += "throw 'Too many semicolons in format string';";
            break;
    }
    eval(code + "}");
}

Number.createTerminalFormat = function(format) {
    // If there is no work to do, just return the literal value
    if (format.length > 0 && format.search(/[0#?]/) == -1) {
        return "return '" + String.escape(format) + "';\n";
    }
    // Negative values are always displayed without a minus sign when section separators are used.
    var code = "var val = (context == null) ? new Number(this) : Math.abs(this);\n";
    var thousands = false;
    var lodp = format;
    var rodp = "";
    var ldigits = 0;
    var rdigits = 0;
    var scidigits = 0;
    var scishowsign = false;
    var sciletter = "";
    // Look for (and remove) scientific notation instructions, which can be anywhere
    m = format.match(/\..*(e)([+-]?)(0+)/i);
    if (m) {
        sciletter = m[1];
        scishowsign = (m[2] == "+");
        scidigits = m[3].length;
        format = format.replace(/(e)([+-]?)(0+)/i, "");
    }
    // Split around the decimal point
    var m = format.match(/^([^.]*)\.(.*)$/);
    if (m) {
        lodp = m[1].replace(/\./g, "");
        rodp = m[2].replace(/\./g, "");
    }
    // Look for %
    if (format.indexOf('%') >= 0) {
        code += "val *= 100;\n";
    }
    // Look for comma-scaling to the left of the decimal point
    m = lodp.match(/(,+)(?:$|[^0#?,])/);
    if (m) {
        code += "val /= " + Math.pow(1000, m[1].length) + "\n;";
    }
    // Look for comma-separators


    if (lodp.search(/[0#?],[0#?]/) >= 0) {
        thousands = true;
    }
    // Nuke any extraneous commas
    if ((m) || thousands) {
        lodp = lodp.replace(/,/g, "");
    }
    // Figure out how many digits to the l/r of the decimal place
    m = lodp.match(/0[0#?]*/);
    if (m) {
        ldigits = m[0].length;
    }
    m = rodp.match(/[0#?]*/);
    if (m) {
        rdigits = m[0].length;
    }
    // Scientific notation takes precedence over rounding etc
    if (scidigits > 0) {
        code += "var sci = Number.toScientific(val,"
            + ldigits + ", " + rdigits + ", " + scidigits + ", " + scishowsign + ");\n"
            + "var arr = [sci.l, sci.r];\n";
    }
    else {
        // If there is no decimal point, round to nearest integer, AWAY from zero
        if (format.indexOf('.') < 0) {
            code += "val = (val > 0) ? Math.ceil(val) : Math.floor(val);\n";
        }
        // Numbers are rounded to the correct number of digits to the right of the decimal
        code += "var arr = val.round(" + rdigits + ").toFixed(" + rdigits + ").split('.');\n";
        // There are at least "ldigits" digits to the left of the decimal, so add zeros if needed.
        code += "arr[0] = (val < 0 ? '-' : '') + String.leftPad((val < 0 ? arr[0].substring(1) : arr[0]), "
            + ldigits + ", '0');\n";
    }
    // Add thousands separators
    if (thousands) {
        code += "arr[0] = Number.addSeparators(arr[0]);\n";
    }
    // Insert the digits into the formatting string.  On the LHS, extra digits are copied
    // into the result.  On the RHS, rounding has chopped them off.
    code += "arr[0] = Number.injectIntoFormat(arr[0].reverse(), '"
        + String.escape(lodp.reverse()) + "', true).reverse();\n";
    if (rdigits > 0) {
        code += "arr[1] = Number.injectIntoFormat(arr[1], '" + String.escape(rodp) + "', false);\n";
    }
    if (scidigits > 0) {
        code += "arr[1] = arr[1].replace(/(\\d{" + rdigits + "})/, '$1" + sciletter + "' + sci.s);\n";
    }
    return code + "return arr.join('.');\n";
}

Number.toScientific = function(val, ldigits, rdigits, scidigits, showsign) {
    var result = {l:"", r:"", s:""};
    var ex = "";
    // Make ldigits + rdigits significant figures
    var before = Math.abs(val).toFixed(ldigits + rdigits + 1).trim('0');
    // Move the decimal point to the right of all digits we want to keep,
    // and round the resulting value off
    var after = Math.round(new Number(before.replace(".", "").replace(
        new RegExp("(\\d{" + (ldigits + rdigits) + "})(.*)"), "$1.$2"))).toFixed(0);
    // Place the decimal point in the new string
    if (after.length >= ldigits) {
        after = after.substring(0, ldigits) + "." + after.substring(ldigits);
    }
    else {
        after += '.';
    }
    // Find how much the decimal point moved.  This is #places to LODP in the original
    // number, minus the #places in the new number.  There are no left-padded zeroes in
    // the new number, so the calculation for it is simpler than for the old number.
    result.s = (before.indexOf(".") - before.search(/[1-9]/)) - after.indexOf(".");
    // The exponent is off by 1 when it gets moved to the left.
    if (result.s < 0) {
        result.s++;
    }
    // Split the value around the decimal point and pad the parts appropriately.
    result.l = (val < 0 ? '-' : '') + String.leftPad(after.substring(0, after.indexOf(".")), ldigits, "0");
    result.r = after.substring(after.indexOf(".") + 1);
    if (result.s < 0) {
        ex = "-";
    }
    else if (showsign) {
        ex = "+";
    }
    result.s = ex + String.leftPad(Math.abs(result.s).toFixed(0), scidigits, "0");
    return result;
}

Number.prototype.round = function(decimals) {
    if (decimals > 0) {
        var m = this.toFixed(decimals + 1).match(
            new RegExp("(-?\\d*)\.(\\d{" + decimals + "})(\\d)\\d*$"));
        if (m && m.length) {
            return new Number(m[1] + "." + String.leftPad(Math.round(m[2] + "." + m[3]), decimals, "0"));
        }
    }
    return this;
}

Number.injectIntoFormat = function(val, format, stuffExtras) {
    var i = 0;
    var j = 0;
    var result = "";
    var revneg = val.charAt(val.length - 1) == '-';
    if ( revneg ) {
       val = val.substring(0, val.length - 1);
    }
    while (i < format.length && j < val.length && format.substring(i).search(/[0#?]/) >= 0) {
        if (format.charAt(i).match(/[0#?]/)) {
            // It's a formatting character; copy the corresponding character
            // in the value to the result
            if (val.charAt(j) != '-') {
                result += val.charAt(j);
            }
            else {
                result += "0";
            }
            j++;
        }
        else {
            result += format.charAt(i);
        }
        ++i;
    }
    if ( revneg && j == val.length ) {
        result += '-';
    }
    if (j < val.length) {
        if (stuffExtras) {
            result += val.substring(j);
        }
        if ( revneg ) {
             result += '-';
        }
    }
    if (i < format.length) {
        result += format.substring(i);
    }
    return result.replace(/#/g, "").replace(/\?/g, " ");
}

Number.addSeparators = function(val) {
    return val.reverse().replace(/(\d{3})/g, "$1,").reverse().replace(/^(-)?,/, "$1");
}

String.prototype.reverse = function() {
    var res = "";
    for (var i = this.length; i > 0; --i) {
        res += this.charAt(i - 1);
    }
    return res;
}

String.prototype.trim = function(ch) {
    if (!ch) ch = ' ';
    return this.replace(new RegExp("^" + ch + "+|" + ch + "+$", "g"), "");
}

String.leftPad = function (val, size, ch) {
    var result = new String(val);
    if (ch == null) {
        ch = " ";
    }
    while (result.length < size) {
        result = ch + result;
    }
    return result;
}

String.escape = function(string) {
    return string.replace(/('|\\)/g, "\\$1");
}

<!-- Draggble -->

// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 5000;


function dragStart(event, id) {

//alert(event);

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 300;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 200;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Clear the drag element global.

  dragObj.elNode = null;

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
};

<!-- Fade in/out  -->

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
			
			
			
        } 
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
			
			
	
        } 
		
    } 
	
	 
	
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 


function shiftOpacity(id, millisec) { 
    //if an element is invisible, make it visible, else make it ivisible 
    if(document.getElementById(id).style.opacity == 0) { 
        opacity(id, 0, 100, millisec); 
    } else { 
        opacity(id, 100, 0, millisec); 
    } 
} 



<!-- Esconder/Mostrar -->

function HideLayer(layName)
{
	
	//shiftOpacity(layName, 1000);
	document.getElementById(layName).style.visibility='hidden';
	//document.getElementById(layName).style.display='none';
	
	
}

function ShowLayer(layName)
{
      
	
	//document.getElementById(layName).style.opacity = 0
	//document.getElementById(layName).style.display='block';
	document.getElementById(layName).style.visibility='visible';
	link = window.open("#topo","_self"); 
	//shiftOpacity(layName, 1000);
   
	
}

function esconder(layName)
{
	
	document.getElementById(layName).style.display='none';
	
}

function mostrar(layName)
{
    
	document.getElementById(layName).style.display='block';
	
}

<!-- Simulação de crédito Format Number -->

function valor(context){
var val = (context == null) ? new Number(this) : Math.abs(this);
val = (val > 0) ? Math.ceil(val) : Math.floor(val);
var arr = val.round(0).toFixed(0).split('.');
arr[0] = (val < 0 ? '-' : '') + String.leftPad((val < 0 ? arr[0].substring(1) : arr[0]), 0, '0');
arr[0] = Number.addSeparators(arr[0]);
arr[0] = Number.injectIntoFormat(arr[0].reverse(), '######', true).reverse();
return arr.join('.');
}


function setPrice(cbo){
	var str = cbo.value.split(';');
	//alert(cbo.value);
	document.getElementById('LPR').value=str[0];
	document.getElementById('MPR').value=str[1];
}

function loadContent(place)
{
	var frm=place.contentWindow.document.all['form'];
	if(frm)
	{
		if(document.getElementById('response').style.display=="none")
		{
			document.getElementById('response').style.display="block";
		}
		if(document.getElementById('aplAmount').value)
		{
			oMensal.style.display = 'block'	
			oTotal.style.display = 'block'	
		}
		else
		{
			oMensal.style.display = 'block'	
			oTotal.style.display = 'block'
			
		}
		for(var i=0; i<frm.length; i++)
		{
			if(frm[i].value != '0') {
				
				document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value;
				
			}
			if( i == 0) {
				//document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value;
				var nun = document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value * 1;
				document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value = nun.numberFormat("###,###,###.00");
				//alert( nun.numberFormat("###,###,###.00 euros") );
				//alert( nun );
				
			}
			if( i == 4) {
				//document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value;
				var nun = document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value * 1;
				document.getElementById(frm[i].getAttribute('id')).innerHTML=frm[i].value = nun.numberFormat("###,###,###.00");
				//alert( nun.numberFormat("###,###,###.00 euros") );
				//alert( nun );
				
			}
			
		}
		
	}
	
	
}


<!-- Sliders Controllers -->

function slide_caract(obj)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			//document.getElementById(obj).style.display = "block";
			document.getElementById("slide_"+obj).src= "../images/menos2_btn.png";
			
			effect_1 = Effect.SlideDown(obj,{duration:0.5});
			
		}

		else{
			//document.getElementById(obj).style.display = "none";
			document.getElementById("slide_"+obj).src= "../images/mais2_btn.png";
			
			effect_1 = Effect.SlideUp(obj,{duration:0.5});
			
			}
		
	}
	
function slide_forms(obj)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			//document.getElementById(obj).style.display = "block";
			document.getElementById("slide_"+obj).src= "../images/menos1_btn.png";
			
			effect_1 = Effect.SlideDown(obj,{duration:0.5});
			
		}

		else{
			//document.getElementById(obj).style.display = "none";
			document.getElementById("slide_"+obj).src= "../images/mais1_btn.png";
			
			effect_1 = Effect.SlideUp(obj,{duration:0.5});
			
			}
		
	}

var maximized = null ; //Se fossem para iniciar todos minimizados
	
	
	function max(obj)
	{

		if(maximized && maximized!=obj)
			min(maximized);
		else if(maximized==obj)
			return false;
				
		effect_1 = Effect.SlideDown(obj,{duration:0.5});
		maximized=obj;
			
		return false;
	}
	
	function min(obj)
	{
		if(maximized==obj || document.getElementById(obj).style.display == "block")
			maximized=null;
		else
			return false;			
			
		effect_1 = Effect.SlideUp(obj,{duration:0.5}); return false;	
	}
	
	function slide(obj,obj2,obj3,obj4,obj5)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			//document.getElementById(obj).style.display = "block";
			effect_1 = Effect.SlideDown(obj,{duration:0.5});
			document.getElementById(obj2).style.display = "none";
			document.getElementById(obj3).style.display = "none";
			document.getElementById(obj4).style.display = "none";
			document.getElementById(obj5).style.display = "none";
		}

		else{
			//document.getElementById(obj).style.display = "none";
			effect_1 = Effect.SlideUp(obj,{duration:0.5});
			document.getElementById(obj2).style.display = "none";
			document.getElementById(obj3).style.display = "none";
			document.getElementById(obj4).style.display = "none";
			document.getElementById(obj5).style.display = "none";
			}
		
	}
	
	function slide2(obj, hide1, hide2)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			//document.getElementById(obj).style.display = "block";
			document.getElementById(obj+"_pic").src= "../images/cima.png";
			document.getElementById(hide1+"_pic").src= "../images/baixo.png";
			document.getElementById(hide2+"_pic").src= "../images/baixo.png";
			effect_1 = Effect.SlideDown(obj,{duration:0.5});
			effect_2 = Effect.SlideUp(hide1,{duration:0.5});
			effect_3 = Effect.SlideUp(hide2,{duration:0.5});
			
			
		}

		else{
			//document.getElementById(obj).style.display = "none";
			document.getElementById(obj+"_pic").src= "../images/baixo.png";
			effect_1 = Effect.SlideUp(obj,{duration:0.5});
			
			}
		
	}
	
	function slide_detalhe(obj, hide1, hide2, hide3, hide4)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			//document.getElementById(obj).style.display = "block";
			document.getElementById(obj+"_pic").src= "../images/cima.png";
			document.getElementById(hide1+"_pic").src= "../images/baixo.png";
			document.getElementById(hide2+"_pic").src= "../images/baixo.png";
			document.getElementById(hide3+"_pic").src= "../images/baixo.png";
			document.getElementById(hide4+"_pic").src= "../images/baixo.png";
			effect_1 = Effect.SlideDown(obj,{duration:0.5});
			effect_2 = Effect.SlideUp(hide1,{duration:0.5});
			effect_3 = Effect.SlideUp(hide2,{duration:0.5});
			effect_4 = Effect.SlideUp(hide3,{duration:0.5});
			effect_5 = Effect.SlideUp(hide4,{duration:0.5});
			
			
		}

		else{
			//document.getElementById(obj).style.display = "none";
			document.getElementById(obj+"_pic").src= "../images/baixo.png";
			effect_1 = Effect.SlideUp(obj,{duration:0.5});
			
			}
		
	}
	
	function separador(obj, hide1, hide2)
	{
		
			link = window.open("#tabs","_self"); 
					
		if( document.getElementById('bottom_separadores_'+obj).style.display == 'none')
		{
			
			document.getElementById('bottom_separadores_btns_'+obj).style.display = 'block';
			
			
				if( document.getElementById('bottom_separadores_btns_'+hide1).style.display == 'block')
					{
						document.getElementById('bottom_separadores_btns_'+hide1).style.display = 'none';
						
					}
				
				if( document.getElementById('bottom_separadores_btns_'+hide2).style.display == 'block')
					{
						document.getElementById('bottom_separadores_btns_'+hide2).style.display = 'none';
						
					}
			
			
			document.getElementById('bottom_separadores_'+obj).style.display = 'block';
			
			
			
				if( document.getElementById('bottom_separadores_'+hide1).style.display == 'block')
					{
						document.getElementById('bottom_separadores_'+hide1).style.display = 'none';
						
					}
				
				if( document.getElementById('bottom_separadores_'+hide2).style.display == 'block')
					{
						document.getElementById('bottom_separadores_'+hide2).style.display = 'none';
						
					}
			
		}
		
	}
	
	
	function show_hide(obj)
	{
		
					
		if( document.getElementById(obj).style.display == "none")
		{
			
			document.getElementById(obj).style.display = "block";
			
		} else {
			
			document.getElementById(obj).style.display = "none";
			
			}
		
	}
	

<!-- Calendar Input -->

// Customizable variables
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 3; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = '../images/calendar.jpg';
var NextURL = '../images/next.gif';
var PrevURL = '../images/prev.gif';


var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightblue';


// Global variables
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('D','S','T','Q','Q','S','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('Janeiro','Fevreiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');

// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}

// Only allows certain keys to be used in the date field
function YearDigitsOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}

// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j<document.forms.length;j++) {
         for (var i=0;i<document.forms[j].elements.length;i++) {
            if (typeof document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  i += 3; // 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
                  if (document.forms[j].elements[i].type.substr(0,6) == 'select') {
                     ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
                     if (ListTopY < CalBottomY) {
                        if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)) {
                           document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
                        }
                     }
                     else break formLoop;
                  }
               }
            }
         }
      }
   }
}

// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   if (Over) {
      if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}

// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   this.show();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
   var YearField = this.getYearField();
   FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
   // Select the month and day in the lists
   for (var i=0;i<MonthList.length;i++) {
      if (MonthList.options[i].value == this.displayed.monthIndex) MonthList.options[i].selected = true;
   }
   for (var j=1;j<=DayList.length;j++) {
      if (j == ClickedDay) DayList.options[j-1].selected = true;
   }
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;
}

// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:white;font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) TextStyle += 'border:1px solid blue;padding:0px;';
            HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}

// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}

// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}

// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.selectedIndex + 1;
   if (NewDays != DayList.length) {
      var OldSize = DayList.length;
      for (var k=Math.min(NewDays,OldSize);k<Math.max(NewDays,OldSize);k++) {
         (k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
      }
      DayPick = Math.min(DayPick, NewDays);
      DayList.options[DayPick-1].selected = true;
   }
   return DayPick;
}

// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
   if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}

// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}

// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}

// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}

// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
      var StopTimer = true;
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
   }
   else {
      var StopTimer = false;
      this.fixSelects(true);
      this.getCalendar().style.zIndex = ++ZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleTimer(StopTimer);
   self.status = '';
}

// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}

// Sets the date, based on the month selected
function CheckMonthChange(MonthList) {
   var DayList = this.getDayList();

   if (MonthList.options[MonthList.selectedIndex].value == '') {
      DayList.selectedIndex = 0;
      this.hideElements(true);
      this.setHidden('');
   }
   else {
      this.hideElements(false);
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-selected month
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
      this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
   }
}

// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}

// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
      YearField.defaultValue = YearField.value;
   }
}

// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}

// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}

// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}

// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}

// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
   this.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}

// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {

   /* Properties */
   this.hiddenFieldName = DateName;
   this.monthListID = DateName + '_Month_ID';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;

   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');

   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   // Main part of the constructor
   if (DefaultDate != '') {
      if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
      else {
         // Get the year
         if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate))) { // Year is at the beginning
            var YearPart = GetGoodYear(RegExp.$1);
            // Determine the order of the months and days
            if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate)) {
               var MidPart = RegExp.$2;
               var EndPart = RegExp.$4;
               if (/D$/.test(this.format)) { // Ends with days
                  var DayPart = EndPart;
                  var MonthPart = MidPart;
               }
               else {
                  var DayPart = MidPart;
                  var MonthPart = EndPart;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/(-|\/)(\d{2,4})$/.test(DefaultDate)) { // Year is at the end
            var YearPart = GetGoodYear(RegExp.$2);
            // Determine the order of the months and days
            if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'D') { // Starts with days
                  var DayPart = RegExp.$1;
                  var MonthPart = RegExp.$3;
               }
               else { // Starts with months
                  var MonthPart = RegExp.$1;
                  var DayPart = RegExp.$3;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else SetGoodDate(this, true);
      }
   }
}

// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat, DefaultDate) {
   if (arguments.length == 0) document.writeln('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      // Handle DateFormat
      if (arguments.length < 3) { // The format wasn't passed in, so use default
         DateFormat = DefaultDateFormat;
         if (arguments.length < 2) Required = false;
      }
      else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
      else { // Passed-in DateFormat was invalid, use default format instead
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         DateFormat = DefaultDateFormat;
         if (arguments.length == 4) { // DefaultDate was passed in with an invalid date format
            var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
            AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
            DefaultDate = CurrentDate.formatted;
         }
         alert(AlertMessage);
      }
      // Define the current date if it wasn't set already
      if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
      // Handle DefaultDate
      if (arguments.length < 4) { // The date wasn't passed in
         DefaultDate = (Required) ? CurrentDate.formatted : ''; // If required, use today's date
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      // Determine initial viewable state of day, year, and calendar icon
      if ((Required) || (arguments.length == 4)) {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      else {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
         eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDate() + ')');
      }
      // Create the form elements
      with (document) {
         writeln('<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">');
         // Find this form number
         for (var f=0;f<forms.length;f++) {
            for (var e=0;e<forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         writeln('<table cellpadding="0" cellspacing="2"><tr>' + String.fromCharCode(13) + '<td valign="middle">');
         writeln('<select class="calendarDateInput" id="' + DateName + '_Month_ID" onChange="' + DateName + '_Object.changeMonth(this)">');
         if (!Required) {
            var NoneSelected = (DefaultDate == '') ? ' selected' : '';
            writeln('<option value=""' + NoneSelected + '>' + UnselectedMonthText + '</option>');
         }
         for (var i=0;i<12;i++) {
            MonthSelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.monthIndex') == i)) ? ' selected' : '';
            writeln('<option value="' + i + '"' + MonthSelected + '>' + MonthNames[i].substr(0,3) + '</option>');
         }
         writeln('</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');
         writeln('<select' + InitialStatus + ' class="calendarDateInput" id="' + DateName + '_Day_ID" onChange="' + DateName + '_Object.changeDay(this)">');
         for (var j=1;j<=eval(DateName + '_Object.picked.dayCount');j++) {
            DaySelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.day') == j)) ? ' selected' : '';
            writeln('<option' + DaySelected + '>' + j + '</option>');
         }
         writeln('</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');
         writeln('<input' + InitialStatus + ' class="calendarDateInput" type="text" id="' + DateName + '_Year_ID" size="' + eval(DateName + '_Object.picked.yearPad.length') + '" maxlength="' + eval(DateName + '_Object.picked.yearPad.length') + '" title="Year" value="' + eval(DateName + '_Object.picked.yearPad') + '" onKeyPress="return YearDigitsOnly(window.event)" onKeyUp="' + DateName + '_Object.checkYear(this)" onBlur="' + DateName + '_Object.fixYear(this)">');
         write('<td valign="middle">' + String.fromCharCode(13) + '<a' + InitialStatus + ' id="' + DateName + '_ID_Link" href="javascript:' + DateName + '_Object.show()" onMouseOver="return ' + DateName + '_Object.iconHover(true)" onMouseOut="return ' + DateName + '_Object.iconHover(false)"><img src="' + ImageURL + '" align="baseline" title="Calendar" border="0"></a>&nbsp;');
         writeln('<span id="' + DateName + '_ID" style="position:absolute;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;" onMouseOver="' + DateName + '_Object.handleTimer(true)" onMouseOut="' + DateName + '_Object.handleTimer(false)">');
         writeln('<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
         writeln('<td id="' + DateName + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return ' + DateName + '_Object.previous.hover(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '"></td>');
         writeln('<td id="' + DateName + '_Current_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" colspan="5" onClick="' + DateName + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + CurrentDate.fullName + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month">' + eval(DateName + '_Object.displayed.fullName') + '</td>');
         writeln('<td id="' + DateName + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.next.hover(this,true)" onMouseOut="return ' + DateName + '_Object.next.hover(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>');
         for (var w=0;w<7;w++) writeln('<td width="' + CellWidth + '" align="center" class="calendarDateInput" style="height:' + CellHeight + ';width:' + CellWidth + ';font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;">' + WeekDays[w] + '</td>');
         writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval(DateName + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '</tr>' + String.fromCharCode(13) + '</table>');
      }
   }
}








