
var status = '';
var statusMsg = '';
var onPageLoad = null;

function AGSystem()
{
    this.name = 'Alumni Gestum';
    this.version = '2.15';
    this.defaultStatusMessage = 'Alumni Gestum';
    this.status = '';
    this.statusMsg = '';
    this.onStatusReceived = null;
    this.onLoad = null;

    this.statusReceived = AGSystem_statusReceived;
    this.statusMessage = statusMessage;
    this.statusMessageError = statusMessageError;
    this.selectGridItem = selectGridItem;
    this.unselectGridItem = unselectGridItem;

    this.addLoadAction = AGSystem_addLoadAction;
    this.addUnloadAction = AGSystem_addUnloadAction;

    this.adjustSpecialChars = adjustSpecialChars;
    this.adjustFormFields = adjustFormFields;
    this.adjustFormFields2 = adjustFormFields2;
    this.checkEmptyFields = checkEmptyFields;
    this.checkFormats = checkFormats;
    this.checkAndSubmit = checkAndSubmit;
    this.checkDateTimeFields = checkDateTimeFields;
    this.checkCPF = checkCPF;
    this.checkCNPJ = checkCNPJ;
    this.disableAll = disableAll;
    this.scriptToHTML = scriptToHTML;
    this.scriptToHTML2 = scriptToHTML2;
    this.htmlToScript = htmlToScript;  
    this.cutString = cutString;
    this.getSeparator = getSeparator;
    this.adjustDate = adjustDate;
    this.adjustTime = adjustTime;
    this.adjustMoney = adjustMoney;
    this.getWidthResolution = getWidthResolution;
    this.getHeightResolution = getHeightResolution;
    this.getWidthVisibilityArea = getWidthVisibilityArea;
    this.getHeightVisibilityArea = getHeightVisibilityArea;
    this.getBrowser = getBrowser;
    this.getBrowserVersion = getBrowserVersion;
	this.moveObjHorizontal = moveObjHorizontal;
	this.moveObjVertical = moveObjVertical;

    this.loadActions = new Array();
    this.unloadActions = new Array();
    this.location = location.toString();
    this.location = this.location.substring(0, this.location.lastIndexOf("/")+1);

    this.showHelp = AGSystem_showHelp;

    this.checkFile = checkFile;
    this.lastIndexOf = lastIndexOf;

    this.getWaitHTML = AGSystem_getWaitHTML;
    this.limitText = AGSystem_limitText;
    this.modalDialogWindow = AGSystem_ModalDialogWindow; 
    
    this.checkDatePeriodIsValid = checkDatePeriodIsValid;
    this.breakLimitLineWithSeparator = breakLimitLineWithSeparator;
  //  this.loadHidden = loadHidden;
  //  this.loadShow = loadShow;
  
  	this.openWindowBaseForm = openWindowBaseForm;
}

agSystem = new AGSystem();


//#####################################################################################
//FUNÇÕES PARA CONTRUÇÃO DE JANELAS MODAIS CROSS BROWSER
//#####################################################################################

var ModalDialogWindow;
var ModalDialogInterval;

function AGSystem_ModalDialogWindow(file,nameWindow,args)
{
	//ex: args='width=350,height=125,left=325,top=300,toolbar=0,location=0,status=0,menubar=0,scrollbars=1,resizable=0';  

    ModalDialogWindow=window.open(file,nameWindow,args); 
    ModalDialogWindow.focus(); 

    ModalDialogInterval = window.setInterval("ModalDialogFocus()",5);
}

function ModalDialogFocus()
{
  try
  {
    if (ModalDialogWindow.closed)
    {
        window.clearInterval(ModalDialogInterval);
        return;
    }
    ModalDialogWindow.focus(); 
  }
  catch (everything) { }
}

//################################## FIM ###################################################

var speedMoveObj = new Array(50,36,26,21,18,14,11,8,5,1)
var objMoveHorizontal = null;
function moveObjHorizontal(startPointX, startPointY, limitPointX, obj, speed)
{	
	//x = horizontal
	//y = vertical
	if(objMoveHorizontal==null)
		objMoveHorizontal = obj;

	objMoveHorizontal.style.display = 'inline';
		
	objMoveHorizontal.style.left = parseInt(startPointX);		
	objMoveHorizontal.style.top = parseInt(startPointY);
	
    moveObject('horizontal',limitPointX,speed);
}

var objMoveVertical = null;
function moveObjVertical(startPointX, startPointY, limitPointY, obj, speed)
{
	//x = horizontal
	//y = vertical
	if(objMoveVertical==null)
		objMoveVertical = obj;

	objMoveVertical.style.display = 'inline';
		
	objMoveVertical.style.left = parseInt(startPointX);		
	objMoveVertical.style.top = parseInt(startPointY);
	
    moveObject('vertical',limitPointY,speed);
}

function moveObject(type,limitPoint,speed)
{
	if(type == 'vertical')
	{
		if(parseInt(objMoveVertical.style.top) < limitPoint)
		{
			objMoveVertical.style.top = parseInt(objMoveVertical.style.top) + 1;
			setTimeout("moveObject('vertical',"+limitPoint+","+speed+");", speedMoveObj[speed]);
		}		
	}
	
	if(type == 'horizontal')
	{
		if(parseInt(objMoveHorizontal.style.left) < limitPoint)
		{
			objMoveHorizontal.style.left = parseInt(objMoveHorizontal.style.left) + 1;
			setTimeout("moveObject('horizontal',"+limitPoint+","+speed+");", speedMoveObj[speed]);
		}		
	}
	
}

function getWidthResolution()
{
	return parseInt(getResolution("width"));
}

function getHeightResolution()
{
	return parseInt(getResolution("height"));
}

function getResolution(type)
{
	var myWidth = 0;
	var myHeight = 0;
	
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		myWidth = window.innerWidth;
	 	myHeight = window.innerHeight;
	 	var identNav = false;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
	 	//IE 6+ in 'standards compliant mode'
	 	myWidth = document.documentElement.clientWidth;
	 	myHeight = document.documentElement.clientHeight;
	 	var identNav = true;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		//IE 4 compatible
	  	myWidth = document.body.clientWidth;
	  	myHeight = document.body.clientHeight;
	}	

	if (navigator.platform.indexOf('Win') != -1)
	{
		if(myWidth != screen.width)
			myWidth = screen.width;
	
		if(myHeight	!= screen.height)
			myHeight = screen.height;
	}

	if(type == 'width')
		return myWidth;
	
	if(type == 'height')
		return myHeight;
}

function getWidthVisibilityArea()
{
	return parseInt(getVisibilityArea("width"));
}

function getHeightVisibilityArea()
{
	return parseInt(getVisibilityArea("height"));
}


function getVisibilityArea(type)
{
	var myWidth = 0;
	var myHeight = 0;
	
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
    if(agSystem.getBrowser() == 'NS')// firefox area visivel + diferença do scroll "window.scrollMaxX"
    {
    	//alert("02= "+myWidth)
    	myWidth = myWidth + window.scrollMaxX;
    	//alert("01= "+myWidth)
    }
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;

  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;

  }

	if(type == 'width')
		return myWidth;
	
	if(type == 'height')
		return myHeight;
}

function getBrowserVersion()
{
	var browserVersion = "";
	var b = navigator.appName;
	if (b == "Netscape") this.b = "NS";
	else if (b == "Microsoft Internet Explorer") this.b = "IE";
	else this.b = b;
	this.v = parseInt(navigator.appVersion);
	this.NS4 = (this.b == "NS" && this.v == 4);
	this.NS5 = (this.b == "NS" && this.v == 5);
	this.IE4 = (navigator.userAgent.indexOf('MSIE 4')>0);
	this.IE5 = (navigator.userAgent.indexOf('MSIE 5')>0);
	this.IE6 = (navigator.userAgent.indexOf('MSIE 6')>0);
	this.IE7 = (navigator.userAgent.indexOf('MSIE 7')>0);
	
	if(this.NS4)
		browserVersion = "NS4";
	else if(this.NS5)
		browserVersion = "NS5";
	else if(this.IE4)
		browserVersion = "IE4";
	else if(this.IE5)
		browserVersion = "IE5";
	else if(this.IE6)
		browserVersion = "IE6";
	else if(this.IE7)
		browserVersion = "IE7";
		
	return browserVersion;
}

function getBrowser()
{
	var browser = "";
	var b = navigator.appName;
	if (b == "Netscape") this.b = "NS";
	else if (b == "Microsoft Internet Explorer") this.b = "IE";
	else this.b = b;
	this.v = parseInt(navigator.appVersion);
	this.NS = (this.b == "NS" && this.v>=4);
	this.IE = (this.b == "IE" && this.v>=4);
	if(this.NS)
		browser = "NS";
	else if(this.IE)
		browser = "IE";
		
	return browser;
}

//############### Processo de loaging pages ##############
var loadTimer	= setInterval(loadShow,18);
var loadPos	= 0;
var loadDir	= 2;
var loadLen	= 0;

function loadShow()
{
	var elem = document.getElementById("progress_bar");
	if(elem != null)
	{
		if (loadPos==0) loadLen += loadDir;
		if (loadLen>32 || loadPos>79) loadPos += loadDir;
		if (loadPos>79) loadLen -= loadDir;
		if (loadPos>79 && loadLen==0) loadPos=0;
		elem.style.left		= loadPos;
		elem.style.width	= loadLen;
	}
}

function loadHidden()
{
	window.clearInterval(loadTimer);
	var objLoader				= document.getElementById("load_bar");
	objLoader.style.display		="none";
	objLoader.style.visibility	="hidden";
}
//############### FIM Processo de loaging pages ##############


function findObjectByIdOrName(pattern)
{
	// pattern = "fStatus";
	var child 	= this.top;
	var founded	= false;
	
	while(!founded){
		father = findFather(child);
		if(father){
			if((founded = father.document.getElementById(pattern))||
			   (founded = father.document.getElementsByName(pattern)[0]))
			   	break;
			else{
				child	= father;
				founded = false;
				if(father.name == "")break;
			}
		}
		else
			break;
	}
	return founded;
}

function findFather(child)
{
	if(child){
		var opener = child.top.opener;
	
		if(opener)
			return opener;
		else
			return child.parent;
	}
	else
		return -1;
}

function selectGridItem(itemName)
{
    if (itemName != '')
    {
        var itemElem = null;
        if (document.getElementById)
        {
            itemElem = document.getElementById(itemName);
        }
        else if (document.all)
        {
            itemElem = document.all[itemName];
        }
        if (itemElem)
        {
            itemElem.className = 'gridSelectedRow';
        }
    }
    if (document.selection)
        document.selection.empty();
}

function unselectGridItem(itemName)
{
    if (itemName != '')
    {
        var itemElem = null;
        if (document.getElementById)
        {
            itemElem = document.getElementById(itemName);
        }
        else if (document.all)
        {
            itemElem = document.all[itemName];
        }
        if (itemElem)
        {
            itemElem.className = 'gridRow';
        }
    }
    if (document.selection)
        document.selection.empty();
}

function statusMessage(msg, color)
{
    var statusBarElem = null;
    var doc = top.document;

    if (doc.getElementById)
    {
        statusBarElem = doc.getElementById('statusBar');
    }
    else if (doc.all)
    {
        statusBarElem = doc.all['statusBar'];
    }
    if (statusBarElem)
    {
        statusBarElem.innerHTML = msg;
/*        if (color)
        {
            statusBarElem.style.color = color;
        }
*/
    }
}

function statusMessageError(msg)
{
    statusMessage(msg);
    alert(msg);
}

function AGSystem_addLoadAction(script)
{
    this.loadActions[this.loadActions.length] = script;
}

function AGSystem_addUnloadAction(script)
{
    this.unloadActions[this.unloadActions.length] = script;
}

function _loadAction()
{
//    initializeForms(); // corrigir datas nos formulários

    var i;
    for (i=0; i<agSystem.loadActions.length; i++)
    {
        eval(agSystem.loadActions[i]);
    }

    initializeForms();

    if (onPageLoad != null)
    {
        onPageLoad();
    }
    if (status != '')
    {
        eval("on" + status + "('" + statusMsg + "');");
    }
}

function _unloadAction()
{
    var i;
    for (i=0; i<agSystem.unloadActions.length; i++)
    {
        eval(agSystem.unloadActions[i]);
    }
}

onload = _loadAction;
onunload = _unloadAction;

function showHint(evento)
{
	try { 
		if (evento && evento.target.title)
	    	statusMessage(evento.target.title);
		else if (window.event && event.srcElement.title)
	        statusMessage(event.srcElement.title);
	}catch(e){}
}

function hideHint()
{
	try { statusMessage(agSystem.defaultStatusMessage); }catch(e){}
}

function initializeForms()
{
    for (var f=0; f<document.forms.length; f++)
    {
        var form = document.forms[f];
        for (var e=0; e<form.elements.length; e++)
        {
            var elem = form.elements[e];
            if (elem.type == 'button')
            {
                elem.onmouseover = showHint;
                elem.onmouseout = hideHint;
            }
        }
    }
}

function disableAll()
{
    for (var f=0; f<document.forms.length; f++)
    {
        var form = document.forms[f];
        for (var e=0; e<form.elements.length; e++)
        {
            var elem = form.elements[e];
            if (elem.type=='button' && (elem.name=='bClose' || elem.name=='bBack' || elem.name=='bCancel'))
            {
                elem.disabled = false;
            }
            else
            {
                elem.disabled = true;
            }
        }
    }
}

function AGSystem_statusReceived(status, message)
{
    if (this.onStatusReceived)
        this.onStatusReceived(status, message);
}

function SelectUserDialog(params)
{
    params = params.split(',').join('&');
    var dialogWin = window.open('../commom/selectUserDialog.jsp?'+params, 'SelectUserDialog', 'width=500,height=300');
    dialogWin.focus();
    return dialogWin;
}

/*=============================================================
    FUNÇÔES PARA TRATAMENTO DE CARACTERES ESPECIAIS
=============================================================*/
var spChars = new Array();
spChars['"'] = '&#34;';
//spChars['"'] = '¨'; // usa trema como aspa
spChars["'"] = '&#39;';
//spChars["'"] = '`'; // usa acento de crase como apóstrofo
spChars['|'] = '&#124;';
spChars['&'] = '&#38;';
spChars['\\'] = '\\\\';
spChars['\u0001'] = '&#01;';
spChars['\u0002'] = '&#02;';
// converte aspas inglesas para aspas normais:
spChars['\u201C'] = '&#34;';
spChars['\u201D'] = '&#34;';
spChars['\u2018'] = '&#39;';
spChars['\u2019'] = '&#39;';

function convertChar(ch)
{
    if (spChars[ch])
    {
        return spChars[ch]
    }
    else
    {
        return ch
    }
}

/*
    Ajusta caracteres especiais na string.
    remove retorno de carro (\u000D, ou #13)
    preserva quebra de linha (\u000A, ou #10)
*/
function adjustSpecialChars(textToAdjust_)
{
    var textToAdjust = new String(textToAdjust_);
    var adjustedText = ''
    for (var i=0; i<textToAdjust.length; i++)
    {
        var ch = textToAdjust.charAt(i)
        adjustedText += convertChar(ch)
    }
    var tmp = adjustedText.split("\u000D")
    adjustedText = tmp.join('')
    return adjustedText
}

function adjustFormFields(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];
        if (!field.disabled && (field.type=='text' || field.type=='textarea' || field.type=='hidden'))
        {
            if (field.className == 'date')
                field.value = adjustDate(field.value);
            if (field.className == 'time')
                field.value = adjustTime(field.value);
            if (field.className == 'money')
                field.value = adjustMoney(field.value);
            if (field.className == 'number')
                field.value = adjustNumber(field.value);               
            else
                field.value = adjustSpecialChars(field.value);
        }
    }
}

function adjustFormFields2(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];
        if (!field.disabled && (field.type=='text' || field.type=='textarea' || field.type=='hidden'))
        {
            if (field.className == 'date')
            {
                field.value = adjustDate(field.value);
                if (field.name.indexOf('_date')!=-1) // este campo é parte de outro, do tipo DATETIME
                {
                	var dateFieldName = field.name.substring(0, field.name.indexOf('_date'));
                    var dateField = formToAdjust.elements[dateFieldName];
                    dateField.value = field.value + ' ' + dateField.value;
                }        
            }
            if (field.className == 'time')
            {
            	field.value = adjustTime(field.value);
                if (field.name.indexOf('_time')!=-1) // este campo é parte de outro, do tipo DATETIME
                {
                    var dateFieldName = field.name.substring(0, field.name.indexOf('_time'));
                    var dateField = formToAdjust.elements[dateFieldName];
                    dateField.value = dateField.value + field.value;
                }
            }
            if (field.className == 'money')
                field.value = adjustMoney(field.value);
            if (field.className == 'number')
                field.value = adjustNumber(field.value);               
            else
            {
                var re = new RegExp("'", "g");
                field.value = field.value.replace(re, "\\'");
                re = new RegExp('"', 'g');
                field.value = field.value.replace(re, '\\"');
            }
        }
    }
}

function checkEmptyFields(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];	   
        if (isVisible(field) && !field.disabled && (field.type=='text' || field.type=='password' || field.type=='textarea' || field.type=='select-one'))
        {
            var value = field.value;
            if(value)
            value = value.replace(/^\s*/, ''); // remove espaços antes
            value = value.replace(/\s*$/, ''); // remove espaços depois
            if (field.className != 'date')
            {
	            if (field.getAttribute('ifempty')!=null)
	            {
	                if (!value || value=='')
	                {
	                    field.value = field.getAttribute('ifempty');
	                }
	            }
	            else
	            {
	                if (!value || value=='')
	                {
	                    alert('O campo "'+field.title+'" deve ser preenchido.');
	                    field.focus();
	                    return false;
	                }
	            }
	         }
        }
    }
    return true;
}

function checkFormats(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];

        if (isVisible(field) && !field.disabled && (field.type=='text' || field.type=='password' || field.type=='textarea' || field.type=='select-one'))
        {
            if (field.mask && field.mask!='')
            {
                var re = new RegExp(field.mask);
                if (!field.value.match(re))
                {
                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.');
                    field.focus();
                    return false;
                }
            }
            else if (field.className=='date')
            {
            	if (field.ifempty!=null)
	            {
	                if (!field.value || field.value=='')
	                {
	                    field.value = field.ifempty;
	                }
	            }
	            else
	            {
	                if (field.id != 'pInstallDate' && (!field.value || field.value==''))
	                {
	                    alert('O campo "'+field.title+'" deve ser preenchido.');
	                    field.focus();
	                    return false;
	                }
	            }
            	if (field.value != 'null')
            	{
	                if ((field.id != 'pInstallDate' && field.value != '') && !field.value.match("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"))
	                {
	                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.\nAs datas devem ser informadas no formato dd/mm/aaaa\nPor exemplo: 30/12/2001');
	                    field.focus();
	                    return false;
	                }
	                else if (field.id == 'pInstallDate' && field.value == '')
	                {
	                	//se for o filtro de data de instalação dos relatorios stope, deixa ir valor vazio.
	                }
	                else // o formato está correto - testa os valores:
	                {
	               	    var msg = '';
	                    switch (isDate(field.value))
	                    {
	                        case 0 : /* ok */; break;
	                        case 1 : msg = 'A data indicada no campo "'+field.title+'" é inválida.\nO problema parece ser o formato digitado.'; break;
	                        case 2 : msg = 'A data indicada no campo "'+field.title+'" é inválida.\nO problema parece ser o valor do dia.'; break;
	                        case 3 : msg = 'A data indicada no campo "'+field.title+'" é inválida.\nO problema parece ser o valor do mês.'; break;
	                        case 4 : msg = 'A data indicada no campo "'+field.title+'" é inválida.\nO problema parece ser o valor do ano.'; break;
	                    }
	                    if (msg!='')
	                    {
	                        alert(msg);
	                        field.focus();
	                        return false;
	                    }
	                }
	            }
            }
            else if (field.className=='time')
            {
                var m = field.value.match("^([0-9]{2}):([0-9]{2})$");
                if (!m)
                {
                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.\nOs horários devem ser informadas no formato hh:mm\nPor exemplo: 17:45');
                    field.focus();
                    return false;
                }
                else
                {
                    if (m[1]<0 || m[1]>23)
                    {
                        alert('O horário indicado no campo "'+field.title+'" é inválido.\nO problema parece ser com a hora.');
                        field.focus();
                        return false;
                    }
                    else if (m[2]<0 || m[2]>59)
                    {
                        alert('O horário indicado no campo "'+field.title+'" é inválido.\nO problema parece ser com os minutos.');
                        field.focus();
                        return false;
                    }
                }
            }
            else if (field.className=='money')
            {
                if (field.value!='' && !field.value.match("^R?[\$]?[ ]*[0-9]{1,5}[,\.][0-9]{2}$"))
                {
                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.\nValores monetários devem ser informadas como números com duas casas depois da vírgula.\nPor exemplo: 1538,00');
                    field.focus();
                    return false;
                }
            }

            else if (field.className=='number')
            {
                if (field.value!='' && !field.value.match("^[0-9]*$"))
                {
                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.\nO campo deve conter apenas números.');
                    field.focus();
                    return false;
                }
            }
            else if (field.className=='email')
            {
                if (field.value!='' && !field.value.match(/^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}$/))
                {
                    alert('Os dados do campo "'+field.title+'" estão em formato incorreto.');
                    field.focus();
                    return false;
                }
            }
        }
    }
    return true;
}

function checkAndSubmit(formToSubmit)
{
    // testa se todos campos obrigatórios estão preenchidos e se algum não estiver, vai avisar o usuário.
    // campos preenchidos apenas com espaços são considerados vazios
    if (agSystem.checkEmptyFields(formToSubmit))
    {
        // depois de verificar as campos vazios, verifica os caracteres permitidos
        // se algum dados estiver em formato inválido, avisa o usuário
        if (agSystem.checkFormats(formToSubmit))
        { 
            // se tudo está ok, faz os ajustes necessários para deixar os valores no padrão
            agSystem.adjustFormFields2(formToSubmit);
            // envia o forumlário
         //  if(!formToSubmit.hasAttribute("onsubmit"))
	       if(formToSubmit.getAttribute("onsubmit") == null)
	            formToSubmit.submit();
            // depois de enviar, desabilita o conteúdo da janela, para o usuário saber que deve aguardar
           setTimeout('document.body.innerHTML = agSystem.getWaitHTML()', 5);
            return true;
        }
    }
    return false;
}

function checkDateTimeFields(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];
        if (isVisible(field) && !field.disabled && field.type=='text' && (field.className=='date' || field.className == 'time' || field.className == 'datetime'))
        {
            var value = field.value;
            value = value.replace(/^\s*/, ''); // remove espaços antes
            value = value.replace(/\s*$/, ''); // remove espaços depois

            var re = /./;
            if (field.className == 'date')
                re = /^\d{2}[/]\d{2}[/]\d{4}$/;
            else if (field.className == 'time')
                re = /^\d{2}[:]\d{2}$/;
            else if (field.className == 'datetime')
                re = /^\d{2}[/]\d{2}[/]\d{4}\s\d{2}[:]\d{2}$/;

            if (!re.test(value))
            {
                if (field.className == 'date')
                    alert('O campo "'+field.title+'" está em formato incorreto.\nPor favor, digite a data no formato "dd/mm/aaaa".');
                else if (field.className == 'time')
                    alert('O campo "'+field.title+'" está em formato incorreto.\nPor favor, digite a hora no formato "hh:mm".');
                else
                    alert('O campo "'+field.title+'" está em formato incorreto.\nPor favor, digite a data completa no formato "dd/mm/aaaa hh:mm".');
                field.focus();
                return false;
            }
        }
    }
    return true;
}

	function checkCPF(cpf) 
	{
		if (!cpf.match("^[0-9]*$"))
		{
			alert('O CPF deve conter somente números!');
			return false;
		}
		if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
			cpf == "22222222222" ||	cpf == "33333333333" || cpf == "44444444444" ||
			cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
			cpf == "88888888888" || cpf == "99999999999")
		return false;
		soma = 0;
		for (i=0; i < 9; i ++)
			soma += parseInt(cpf.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
		if (resto != parseInt(cpf.charAt(9)))
			return false;
		soma = 0;
		for (i = 0; i < 10; i ++)
			soma += parseInt(cpf.charAt(i)) * (11 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
		if (resto != parseInt(cpf.charAt(10)))
			return false;
		return true;
	}
	 
function checkCNPJ(cnpj)
{
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
      {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
      }
      else
            return false;
} 

function isVisible(element)
{
    if (element.style.visibility == 'hidden' || element.style.display == 'none' || element.readOnly)
        return false
    else if (element.parentElement != null)
        return isVisible(element.parentElement);
    return true;
}

function adjustDateTimeFields(formToAdjust)
{
    var i;
    var field;
    for (i=0; i<formToAdjust.elements.length; i++)
    {
        field = formToAdjust.elements[i];
        if (field.className == 'date')
            field.value = adjustDate(field.value);
        if (field.className == 'time')
            field.value = adjustTime(field.value);
    }
}

/*
    Troca \n por <br>
*/
function scriptToHTML(textToAdjust)
{
    textToAdjust = new String(textToAdjust);
    var tmp = textToAdjust.split("\n")
    var adjustedText = tmp.join("<br />")
    return adjustedText;
}

function scriptToHTML2(textToAdjust)
{
    textToAdjust = textToAdjust.replace(/\\"/g,'&#34;');
    textToAdjust = textToAdjust.replace(/\\'/g,'&#39;');
    textToAdjust = textToAdjust.replace(/</g,'&lt;');
    textToAdjust = textToAdjust.replace(/>/g,'&gt;');
    textToAdjust = new String(textToAdjust);   
    var tmp = textToAdjust.split("\n")
    var adjustedText = tmp.join("<br>")
    return adjustedText
}

function htmlToScript(textToAdjust)
{
    textToAdjust = textToAdjust.replace(/&#34;/g,'\"');
    textToAdjust = textToAdjust.replace(/&#39;/g,'\'');
    textToAdjust = textToAdjust.replace(/&lt;/g,'<');
    textToAdjust = textToAdjust.replace(/&gt;/g,'>');
    return textToAdjust;
}

function cutString(textToAdjust, maxLength)
{
    if (textToAdjust.length > maxLength)
    {
        return textToAdjust.substring(0, maxLength) + "...";
    }
    return textToAdjust;
}

/*
    Funções para padronizar separadores
*/
var separators = new Array();
separators[1] = "\u0000"; // não utilizado
separators[1] = "\u0001";
separators[2] = "\u0002";
separators[3] = "\u0003";
separators[4] = "\u0004";
separators[5] = "\u0005";

function getSeparator(sepIndex)
{
    return separators[sepIndex];
}
/*=============================================================
    FIM DAS FUNÇÔES PARA TRATAMENTO DE CARACTERES ESPECIAIS
=============================================================*/



/*=============================================================
    FUNÇÔES PARA TRATAMENTO DE DATAS EOUTROS FORMATOS
=============================================================*/
function adjustDate(dateToAdjust)
{
    return dateToAdjust;
}

function adjustTime(timeToAdjust)
{
    return timeToAdjust;
}

function adjustNumber(NumberToAdjust)
{
    return NumberToAdjust;
}

function adjustMoney(valueToAdjust)
{
    var m = valueToAdjust.match("^R?[\$]?[ ]*([0-9]{1,5}[,\.][0-9]{2})$");
    if (m)
    {
        valueToAdjust = m[1];
        valueToAdjust = valueToAdjust.replace(",", ".")
    }
    return valueToAdjust;
}

//ai-2004-07-17-la Adicionadas funções para conversão de datas
function dateUStoBR(d)
{
    var p = d.split("-");
    return p[2] + '/' + p[1] + '/' + p[0];
}

function dateBRtoUS(d)
{
    var p = d.split("/");
    return p[2] + '-' + p[1] + '-' + p[0];
}
///ai
/*=============================================================
    FIM DAS FUNÇÔES PARA TRATAMENTO DATAS
=============================================================*/

function AGSystem_showHelp(url, width)
{
    if (!width)
        width = 300;
    window.open(url, "_blank", "width="+width+",height="+(screen.height-150)+",left=0,top=0,resizable=no");
}


function lastIndexOf(string,char)
{
    var position = -1;
    var charpart = "";

    for ( var rx = 0; rx <= string.length; rx++ )
    {
        charpart = string.substring(rx,rx+1);
        if (  charpart == char )
            position = rx;
    }

    return position;
}


function checkFile(path)
{
    var names = new Array();
    var extensions = new Array();

    //Coloque aqui os nomes de arquivos que não podem ser aceitos.
    //###########################################################
        names[0] = "INDEX";

    //###########################################################

    //Coloque aqui as estensões de arquivos que não podem ser aceitos.
    //###########################################################
        extensions[0] = "CGI";
        extensions[1] = "BAT";
        extensions[2] = "EXE";
        extensions[3] = "COM";

    //###########################################################

    var permission = 0;
    var fileName = "";
    var bar = "/";

    if ( path.indexOf("\\") != -1 )
        bar = "\\";

    fileName = path.substring(lastIndexOf(path,bar)+1, path.length);
    fileName = fileName.toUpperCase( );

    for( var ry =0; ry <= names.length; ry++ )
    {
        if( fileName.substring(0,lastIndexOf(fileName,".")) == names[ry] )
        {
            permission = 1;
            break;
        }
    }

    var ext = fileName.substring(lastIndexOf(fileName,".")+1,fileName.length);

    for( var ry =0; ry <= extensions.length; ry++ )
    {
        if( ext == extensions[ry] )
        {
            permission = 1;
            break;
        }
    }


    if ( permission != 0 )
    {
        alert('Por motivo de segurança o tipo do arquivo indicado "(".'+ext+'")" não é aceito pelo sistema.\n\nÉ recomendado que você compacte o arquivo no formato ".ZIP"\ne envie o arquivo compactado.');
        return false;
    }
    else
        return true;

}

function AGSystem_getWaitHTML(iconPath)
{
    var img = '';
    if (iconPath)
        img = '<img src="'+iconPath+'" border="0" align="left">';
    return '<div class="waitBox" style="width:100%;height:100%;"><div style="height:10px;overflow:hidden;"></div>'+img+'Processando.<br>Por favor, aguarde.</div>';
}

function AGSystem_limitText(textarea, maxLength, counterId)
{
    textarea.maxLength = maxLength;
    textarea.counterId = counterId;
    if (!textarea.onkeyup)
    {
        textarea.onkeyup = onKeyUpLimitText;
        textarea.onkeyup();
    }
    else
    {
        doLimitText(textarea, maxLength, counterId);
    }
}

function onKeyUpLimitText()
{
    doLimitText(this, this.maxLength, this.counterId);
}

function doLimitText(textarea, maxLength, counterId)
{
    if (textarea.value.length > textarea.maxLength)
        textarea.value = textarea.value.substring(0, textarea.maxLength);
    else
    {
        var elem = document.getElementById(textarea.counterId);
        if (elem)
            elem.innerHTML = textarea.maxLength - textarea.value.length;
    }
}




/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   }
   return this
}

/*
    alessandro: modificada para retornar um código de erro:
    0 = Ok (sem erro)
    1 = formato inválido
    2 = dia inválido
    3 = mês inválido
    4 = ano inválido
*/
function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        return 1
    }
    if (strMonth.length<1 || month<1 || month>12){
        return 3
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        return 2
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        return 4
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        return 1
    }
return 0
}

// ai-2004-08-30-at adicionada funçao p/ selecionar um option de acordo com o seu valor
function selectOptionElement (combo, value)
{
    for (var i = 0; i < combo.options.length; i++)
    {
        if (combo.options[i].value == value)
        {
            combo.options[i].selected = true;
            break;
        }
    }
}
/// at
// ai-2004-08-30-at adicionada funçao p/ selecionar vários elementos option
// caso o select seje MULTIPLE
function selectOptionElements (combo, values)
{
    for (var i = 0; i < values.length; i++)
    {
        selectComboElement(combo, values[i]);
    }
}
/// at

// 2007-12-07 ajusta data se for menor que 10
//
function adjustDate(date)
{

	if (date != null && date != "null" && date.indexOf("/") != -1)
	{
		var newDate = date.split("/");
		if (newDate[0] < 10 && newDate[0].length == 1)
		{
			newDate[0] = "0"+newDate[0];
		}
		if (newDate[1] < 10 && newDate[1].length == 1)
		{
			newDate[1] = "0"+newDate[1];
		}
		return newDate[0]+"/"+newDate[1]+"/"+newDate[2];
	}
	else
		return date;
}

//2008-01-29 verifica se a data inicial é maior que a final
//
function checkDatePeriodIsValid(dateIni, dateFin)
{
	var dI = dateIni.split("/");
	var dF = dateFin.split("/");
	if (dI[2] < dF[2])
		return true;
	else if (dI[2] == dF[2])
	{
		if (dI[1] < dF[1])
			return true;
		else if (dI[1] == dF[1])
		{
			if (dI[0] < dF[0])
				return true;
			else if (dI[0] == dF[0])
				return true;
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;
}


//2008-02-11 verifica se foi digitado username com "-" traço
function checkUserId(UserId)
{
	if(UserId.indexOf("-") >= 0)
	{
		return true;
	}
	else
	{
		return false;
	} 
}

//2008-04-04 - Refatoração em 2008-05-22 
function breakLimitLineWithSeparator(msg, limit, separator)
{
	var size = msg.length;
	var msgFinal = "";
	
	if(size > limit && limit > 0)
	{
		var x = 0;
		for(var i = 1; i < size/limit; i++)
		{
			if(i == 1)
			{
				msgFinal += msg.substring(0, limit) + separator;
				x = limit;
			}
			else
			{
				msgFinal += msg.substring(x, i*limit) + separator;
				x = i*limit;
			}
		}
		if( (size%limit) <= limit)
		{
			msgFinal += msg.substring(x, size) + separator;			
		}		
		return msgFinal;	
	}
	else
		return msg;
}

function openWindowBaseForm(file, name, properties, _form_)
{
	var i = location.href.indexOf("tools");
	if(file == null || file == "")
	{
		if(i != -1)
		{
			file = location.href.substring(0,i+5) + "/commom/loading.html";
		}
		else
		{
			i = location.href.indexOf("localized/");
			file = location.href.substring(0,i) + "/tools/commom/loading.html";
		}
	}
	var w = window.open(file, name, properties);
	_form_.target = name;	
	setTimeout(function(){_form_.submit()},200);
	return w;
}