window.status  = "";
doc            = document.all;

var calendario = null;

MANDATORY      = true;
NOT_MANDATORY  = false;

/* Operações */
OPERACAO_INCLUIR                        = 1;
OPERACAO_ALTERAR                        = 2;
OPERACAO_EXCLUIR                        = 3;
OPERACAO_TABELA                         = 4;
OPERACAO_GRAVAR_INCLUSAO                = 5;
OPERACAO_GRAVAR_ALTERACAO               = 6;
OPERACAO_PESQUISAR                      = 7;
OPERACAO_SELECIONAR_MIDIA               = 8;
OPERACAO_ALTERACAO_EXTERNA              = 9;
OPERACAO_SELECIONAR_MIDIAS              = 10;
OPERACAO_APROVAR_CLIENTE                = 11;
OPERACAO_GRAVAR_APROVACAO_CLIENTE       = 12;
OPERACAO_SUSPENDER_ASSINATURA           = 13;
OPERACAO_REDIRECIONAR_SITE              = 14;
OPERACAO_GRAVAR_CADASTRO                = 15;
OPERACAO_TABELA_APROVACAO               = 16;
OPERACAO_INCLUIR_CADASTRO               = 17;
OPERACAO_REATIVAR_ASSINATURA            = 18;
OPERACAO_GRAVAR_SUSPENSAO_ASSINATURA    = 19;
OPERACAO_GRAVAR_REATIVAMENTO_ASSINATURA = 20;
OPERACAO_GRAVAR_EXCLUSAO                = 21;
OPERACAO_TABELA_MENSALIDADES            = 22;
OPERACAO_PAGAR_MENSALIDADE              = 23;
OPERACAO_GRAVAR_PAGAMENTO_MENSALIDADE   = 24;
OPERACAO_TABELA_MENSALIDADES_CLIENTE    = 25;
OPERACAO_ESTORNAR                       = 26;
OPERACAO_GRAVAR_REABERTURA              = 27;
OPERACAO_FOTOS_COLUNISTA                = 28;
OPERACAO_GRAVAR_FOTOS_COLUNISTA         = 29;
OPERACAO_IMPRIMIR_EXTRATO               = 30;
OPERACAO_RELOGAR_ADMINISTRADOR          = 31;
OPERACAO_OBTER_EXTRATO                  = 32;
OPERACAO_IMPRIMIR_EXTRATO_REFERENCIA    = 33;

OPERACAO_ALTERAR_CENTRAL_ASSINANTE          = 34;
OPERACAO_GRAVAR_ALTERACAO_CENTRAL_ASSINANTE = 35;

OPERACAO_SUSPENDER_ASSINATURA_CENTRAL_ASSINANTE = 36;
OPERACAO_GRAVAR_SUSPENSAO_ASSINATURA_CENTRAL_ASSINANTE = 37;
OPERACAO_OBTER_DESCRICAO					= 38;

OPERACAO_SELECIONAR						= 39;

OPERACAO_PREVIEW						= 42;

var OPERACAO_TABELA_FATURAS = 44;
var OPERACAO_PAGAR_FATURA              = 45;
var OPERACAO_CANCELAR_FATURA           = 46;
var OPERACAO_IMPRIMIR_FATURA           = 47;
var OPERACAO_REABRIR_FATURA            = 48;
var OPERACAO_ALTERAR_CREDITOS_CLIENTE  = 49;
var OPERACAO_REMOVER_INDICACOES_CLIENTE = 50;
// Tamanho dos códigos do sistema
CODE_MAX_LENGTH = 8;

// Tipos de Mídia
var TIPO_MIDIA_TODOS = 0;
var TIPO_MIDIA_FOTO   = 1;
var TIPO_MIDIA_VIDEO  = 2;
var TIPO_MIDIA_AUDIO  = 3;
var TIPO_MIDIA_TEXTO  = 4;
var TIPO_MIDIA_COLUNA = 5;
var TIPO_MIDIA_GALERIA = 6;

aTiposMidia = Array( "Foto", "Vídeo", "Áudio", "Texto", "Coluna" );
aOpcoes     = Array( "Agência Tempo", "Login", "Cadastro", "Assinante", "Quem Somos", "Galeria", "Outros Sites", "Contatos" );

// Tipos de acesso
TIPO_ACESSO_LIVRE      			= 1;
TIPO_ACESSO_VISUALIZAR 			= 2;
TIPO_ACESSO_PAGO       			= 3;
TIPO_ACESSO_RESERVADO  			= 4;
TIPO_ACESSO_DOWNLOAD_PAGO		= 5;

// Grupos
GRUPO_ADMINISTRADORES          	= 1;
GRUPO_COLABORADORES            	= 2;
GRUPO_COLUNISTAS               	= 5;
GRUPO_USUARIOS_ACESSO_COMPLETO 	= 3;
GRUPO_USUARIOS_COMUNS          	= 4;

// ParÃ¢metros
PARAMETRO_DIRETORIO_MIDIAS    	= 1;
PARAMETRO_CRIAR_THUMBNAIL_MPG 	= 2;

// ResoluÃ§Ãµes
ALTA_RESOLUCAO  				= 1;
MEDIA_RESOLUCAO 				= 2;
BAIXA_RESOLUCAO 				= 3;

FOTO_COLUNISTA_LARGURA			= 85;
FOTO_COLUNISTA_ALTURA			= 95;

FOTO_COLUNISTA_LATERAL_LARGURA  = 60;
FOTO_COLUNISTA_LATERAL_ALTURA   = 72;


ID_COLUNISTA_PRINCIPAL 		     = "colunistaPrincipal";
ID_COLUNISTA_COMUM     		     = "colunistas";
ID_DESCRICAO_COLUNISTA_PRINCIPAL = "descricaoColunistaPrincipal";

// Menus
OPCAO_CAD_MIDIAS_TABELA = 52;
OPCAO_PAUTA      		= 53;
OPCAO_PAUTA_EDITAR		= 531;
OPCAO_PAUTA_SELECIONAR	= 532;

CLICAR_PRIMEIRA_OPCAO   = 1;

//Some parameters can only be choosen from an existing list:
uploadPolicyList = ["", "DefaultUploadPolicy", "FileByFileUploadPolicy", "PictureUploadPolicy", "CoppermineUploadPolicy"];
langList = ["", "de", "en", "fr", "us"];
serverProtocolList = ["", "HTTP/0.9", "HTTP/1.0", "HTTP/1.1"];

function TableControl() {

	this.init = function() {
		this.keyField = "0";
		this.selectedRow = null;
	}

	this.init();

}

var controleTabela = new TableControl();

/* FunÃ§Ãµes */

function centralizar_janela( _width, _height ) {
	window.resizeTo( _width, _height );
	window.moveTo( ( window.screen.width - _width ) / 2, ( window.screen.height - _height ) / 2 );
}

function centralizarVertical( object ) {
    object.style.pixelTop = ( window.screen.availHeight - object.clientHeight ) / 2 - 100;
    object.style.position = "absolute";
}

function centralizarHorizontal( object ) {
    object.style.pixelLeft = ( window.screen.availWidth - object.clientWidth ) / 2;
    object.style.position  = "absolute";
}

function centralizar( object ) {
	centralizarVertical( object );
	centralizarHorizontal( object );
}

function voltar() {
	history.go(-1);
}

function onlyNumbers( keyPress ) {
	k = keyPress.keyCode;
	event.returnValue = ( k >= 48 && k <= 57 );
}

function onlyDecimalNumber( keyPress ) {
	k = keyPress.keyCode;
	rv = false;
	if ( k == 46 ) {
		k = 44;
		keyPress.keyCode = k;
	}
	if ( k == 44 /* , */ ) {
		if ( window.event.srcElement.value.indexOf( "," ) == -1 ) {
			rv = true;
		}
	}
	else if ( k >= 48 && k <= 57 ) {
		rv = true;
	}
	event.returnValue = rv;
}

function formatDecimal( campo ) {
	campo.value = formatValorDecimal(campo.value);
}


function formatValorDecimal( valor ) {
	if ( valor == "" ) {
		valor = "0,00";
	} else if ( valor.indexOf( "," ) == -1  ) {
		valor += ",00";
	} else {
		//valor += "00";
		//valor += valor.substr( 0, valor.indexOf( "," ) + 3 );
	}
	return valor;
}

function adicionarSeparadores(nStr)
{
	nStr += '';
	x = nStr.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '\.' + '$2');
	}
	return x1 + x2;
}

function FormataData(campo,teclapres) {

	var tecla = teclapres.keyCode;

	if ( tecla < 48 || tecla > 57 ) {
		teclapres.returnValue = false;
		return;
	}

    vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ) {
			// document.form[campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
            campo.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
        }
		if ( tam >= 5 && tam <= 10 ) {
			// document.form[campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
            campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
        }
	}
}

function errorField( expression, field, message ) {
	if ( ! expression ) {
		field.focus();
		alert( message );
		field.focus();
	}
	return ! expression;
}

function isDate( campo, obrigatorio  ) {
	if ( obrigatorio == "" ) { obrigatorio = false; }
	dataStr = campo.value;
	if ( dataStr == "" && ! obrigatorio ) { return true; }
	/*alert( "isDate" );
	alert( "campo.id: " + campo.id );
	alert( "dataStr: " + dataStr );
	alert( "dataStr.length: " + dataStr.length );*/
    if ( errorField( dataStr.length == 10, campo, "Data deve ter 10 dígitos (DD/MM/AAAA)" ) ) { return false; }
    try {
        dia = dataStr.substring( 0, 2 ) * 1;
        mes = dataStr.substring( 3, 5 ) * 1;
        ano = dataStr.substring( 6,10 ) * 1;
    } catch ( e ) {
        errorField( true, campo, "Data deve ser informada no formato DD/MM/AAAA" );
        return false;
    }
    /* verifica o dia valido para cada mes */
    if ( errorField( dia >= 1 && dia <= 31, campo, "Dia deve estar entre 1 e 31" ) ) {
        return false; }
    if ( errorField( mes >= 1 && mes <= 12, campo, "Mês deve estar entre 1 e 12" ) ) {
        return false; }
    if ( errorField( ano >= 1900 && ano <= 2050, campo, "Ano deve estar entre 1900 e 2050" ) ) {
        return false;
    }
    bissexto = ( parseInt( ano / 4 ) == ano / 4 ) ;
    if ( mes == 2 ) {
    	if ( errorField( dia <= 29, campo, "Dia inválido para Fevereiro " ) ) { return false; }
    	if ( ! bissexto ) {
    		if ( errorField( dia == 29, campo, "Dia inválido para Fevereiro de um ano não bissexto" ) ) { return false; }
    	}
    }
    if ( ( mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia == 31 ) {
    	campo.focus();
    	alert( "Dia inválido" );
    	campo.focus();
        return false;
    }
    return true;
}

function validaCNPJ( oInput ){

	var CNPJ = oInput.value

	if ( CNPJ.length < 14 ) {
	  alert( "CNPJ Inválido !!!" );
	  oInput.focus();
	  return false;
	}

	CNPJ1 = CNPJ.substr(0, 12);
	CNPJ2 = CNPJ.substr(12, 2);
	Mult = "543298765432";
	Controle = "";
	Digito = 0;

	for (j = 1; j <= 2; j++) {
		Soma = 0;
		for (i = 0; i <= 11; i++) {
			Soma = Soma + (parseInt(CNPJ1.substr(i, 1)) * parseInt(Mult.substr(i, 1)));
		}
		if (j == 2) {
			Soma = Soma + (2 * Digito);
		}
		Digito = (parseInt(Soma) * 10) % 11;
		if (Digito == 10) {
			Digito = 0;
		}
		Controle = Controle + Digito.toString();
		Mult = "654329876543";
	}
	if ( Controle != CNPJ2 ) {
		alert( "CNPJ Inválido !!!");
		oInput.focus();
		return false;
	}
	else {
	   return true;
	}
}
function validaCPF(oInput){

	if ( oInput.value.length != 11 ) {
	  oInput.focus();
	  alert("CPF Invalido");
	  return false;
	}
	
	var s = oInput.value;
	
	/* Verificar se todos os caracteres são iguais */
	caracter = s.charAt(0);
	bCaracteresIguais = true;
	for ( i = 0; i < 11; i++ ) {
	  if ( s.charAt( i ) != caracter ) {
	    bCaracteresIguais = false;
	    break;
	  }
	}
	if ( bCaracteresIguais == true ) {
	   oInput.focus();
	   alert( "CPF inválido" );
	   return false;
	}

	var i;
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++){
    	d1 += c.charAt(i)*(10-i);
   	}
	if (d1 == 0) {
	  alert("CPF Invalido");
	  oInput.focus();
	  return false;
	}
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1){
	  alert("CPF Invalido");
	  oInput.focus();
	  return false;
    }

    d1 *= 2;
    for (i = 0; i < 9; i++){
    	d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1){
		alert("CPF Invalido");
	  oInput.focus();
	  return false;
    }
    return true;
}

function isValidEMail( eMailField, requiredField ) {

  if ( requiredField == null ) {
    requiredField = false;
  }
  eMail = eMailField.value;
  eMail = eMail.replace( " ", "" );
  eMailField.value = eMail;
  if ( ( eMail == "" ) &&
       ( requiredField == true ) ) {
    eMailField.focus();
    alert( "É necessário informar um e-mail válido !!!" );
    eMailField.focus();
    return false;
  }
  if ( ( eMail == "" ) && ( requiredField == false ) ) {
    return true;
  }
  if ( eMail.indexOf( "@" ) == -1 ||
  		eMail.indexOf( "." ) == -1 ||
  		eMail.indexOf( ";" ) > -1 ||
  		eMail.indexOf( " " ) > -1 ||
  		eMail.indexOf( "\\" ) > -1 ||
  		eMail.indexOf( "\/" ) > -1 ||
  		eMail.indexOf( "\"" ) > -1 ||
  		eMail.indexOf( "[" ) > -1 ||
  		eMail.indexOf( "]" ) > -1 ||
  		eMail.indexOf( "{" ) > -1 ||
  		eMail.indexOf( "}" ) > -1 ||
  		eMail.indexOf( "'" ) > -1 ||
  		eMail.indexOf( "(" ) > -1 ||
  		eMail.indexOf( ")" ) > -1 ||
  		eMail.indexOf( "*" ) > -1 ||
  		eMail.indexOf( "&" ) > -1 ||
  		eMail.indexOf( "%" ) > -1 ||
  		eMail.indexOf( "$" ) > -1 ||
  		eMail.indexOf( "#" ) > -1 ||
  		eMail.indexOf( "!" ) > -1 ||
  		eMail.indexOf( "<" ) > -1 ||
  		eMail.indexOf( ">" ) > -1 ||
  		eMail.indexOf( ":" ) > -1 ||
  		eMail.indexOf( "?" ) > -1 ||
  		eMail.indexOf( "\"") > -1 ||
  		eMail.indexOf( "¨") > -1 ||
  		eMail.indexOf( "|" ) > -1 ||
  		eMail.charAt( 0 ) == "@" ) {
	eMailField.focus();
	alert( "E-Mail inválido !!!" );
	eMailField.focus();
    return false;
  }
  return true;
}

function CompareDate( dateValue, Operator, thenDate ) {

    if ( thenDate == null ) {
        todayDate = new Date();
        mes = todayDate.getMonth() + 1;
        if ( mes < 10 ) {
            mes = "0" + mes;
        }
        dia = todayDate.getDate();
        if ( dia < 10 ) {
            dia = "0" + dia;
        }
        thenDate = dia + "/" + mes + "/" + todayDate.getFullYear();
    }

    data1 = dateValue;
    data2 = thenDate;

    valor1 = data1.substring( 06, 10 ) + data1.substring( 03, 05 ) + data1.substring( 00, 02 );
    valor2 = data2.substring( 06, 10 ) + data2.substring( 03, 05 ) + data2.substring( 00, 02 );

    v = false;
    switch ( Operator ) {
        case ">"  : v = ( valor1 >  valor2 ); break;
        case "<"  : v = ( valor1 <  valor2 ); break;
        case ">=" : v = ( valor1 >= valor2 ); break;
        case "<=" : v = ( valor1 <= valor2 ); break;
        case "!=" : v = ( valor1 != valor2 ); break;
        case "==" : v = ( valor1 == valor2 ); break;
    }

    return v;

}

function AddDay(Day,Days) {

var strData = new String(Day);

var dia = new String(strData.substr(0,2));
var mes = new String(strData.substr(3,5));
var ano = new String(strData.substr(6,10));

	if (dia.substr(0,1) == "0"){ dia = dia.substr(1,1); }
	if (mes.substr(0,1) == "0"){ mes = mes.substr(1,1); }

	var d=new Date(parseInt(ano),parseInt(mes),parseInt(dia),00,00,00);

	d.setDate( d.getDate() + parseInt( Days ) );

	dia    = d.getDate();
	mes    = d.getMonth();
	ano    = d.getFullYear();

	strDia = new String();
	strDia = dia.toString();
	strMes = mes.toString();

	if (strDia.length == 1){ strDia = "0" + strDia; }
	if (strMes.length == 1){ strMes = "0" + strMes; }
	return strDia + '/' + strMes + '/' + ano;

}

function getToday() {
    dataHoje = new Date();
    mes = dataHoje.getMonth() + 1;
    if ( mes < 10 ) {
        mes = "0" + mes;
    }
    dia = dataHoje.getDate();
    if ( dia < 10 ) {
        dia = "0" + dia;
    }
    dataHoje = dia + "/" + mes + "/" + dataHoje.getFullYear();
    return dataHoje;
}

function getCaption( field, fieldName ) {
    var caption = fieldName;
    if ( field.titulo != null ) {
        caption = trimAll( field.titulo );
    }
    return caption;
}

function campoNumerico( field, fieldName, mandatory ) {
	if ( mandatory == "" ) {
		mandatory = false;
	};
    field.value = field.value.replace( " ", "" );
	if ( ! mandatory && field.value == "" ) {
		return true;
	}
    if ( field.value == "" ) {
        field.focus();
        caption = getCaption( field, fieldName );
        alert( "Campo [" + caption + "] não contém um número [" + field.value + "] válido !!!" );
        return false;
    }
    if ( isNaN( field.value ) ) {
        field.focus();
        caption = getCaption( field, fieldName );
        alert( "Campo [" + caption + "] não é um número [" + field.value + "] inteiro válido !!!" );
        return false;
    }
    return true;
}

function validField( expression, field, fieldName, errorMessage ) {
	if ( errorMessage == null ) {
		errorMessage = "";
	}
	if ( expression == false ) {
		field.focus();
		if ( errorMessage == "" ) {
			caption = getCaption( field, fieldName );
			alert( "Campo [" + caption + "] inválido" );
		}
		else {
			alert( errorMessage );
		}
	}
	return expression;
}

function mandatoryField( field, fieldName ) {
	if ( field.value == "" ) {
        try {
	    	field.focus();
        } catch ( e ) {
            alert( "Não foi possível colocar o foco no componente [" + fieldName + "]" );
            return false;
        }
		fieldCaption = getCaption( field, fieldName );
        field.focus();
        alert( "Campo [" + fieldCaption + "] obrigatório" );
		field.focus();
		return false;
	}
	return true;
}

function checkMandatoryFields( form ) {
	form = $(form);
	var elementos = form.getElements();
	var invalidado = 0;
	elementos.each(function(elemento) {
		if ( elemento.mandatory == "y" && invalidado == 0) {
			var fieldName = elemento.label;
			if ( fieldName == null || fieldName == "" ) {
				fieldName = elemento.name;
			}
			if ( fieldName == null || fieldName == "" ) {
				fieldName = elemento.id;
			}
			if ( fieldName == null || fieldName == "" ) {
				fieldName = "dados";
			}
			if ( ! mandatoryField( elemento, fieldName ) ) {
				invalidado = 1;
				return false;
			}
		}
	});
	if (invalidado != 0) {
		return false;
	}
	return true;
}

function trim2(str) {
  if (str!=null) {
    while (str.charAt(str.length - 1)==" ")
      str = str.substring(0, str.length - 1);
    while (str.charAt(0)==" ")
      str = str.substring(1, str.length);
  }
  return str;
}

function trim(str) {
  if (str!=null) {
    fv = "";
    first = true;
    for ( i = 0; i < str.length; i++ ) {
      if ( first ) {
        if ( str.substring( str, i, i + 1 ) != " " ) {
          break;
        }
      }
      fv = fv + substring( str, i, i + 1 );
    }
    while (str.charAt(0)==" ")
      str = str.substring(1, str.length);
  }
  return str;
}

/*The trimAll Function
The trim function works with the form's TEXT input element, but it does not work for elements that can accept carriage return characters, such as a TEXTAREA. The trimAll in Listing 24.5 extends the trim function to trim any leading or trailing blank space, carriage return character, new line character, or tab character.

The trimAll Function */
function trimAll(str) {
  if (str!=null) {
    while (str.length > 0 &&
      "\n\r\t ".indexOf(str.charAt(str.length - 1)) != -1)
      str = str.substring(0, str.length - 1);
    while (str.length > 0 &&
      "\n\r\t ".indexOf(str.charAt(0)) != -1)
      str = str.substring(1, str.length);
  }
  return str;
}
/*The first while loop first makes sure that the string str is not empty. It then creates a string "\n\r\t "and uses the indexOf function to check whether the last character of str matches any of the characters in the string "\n\r\t ".If there is a match, indexOf returns the matching character position in "\n\r\t "; otherwise, it returns -1. Note that in JavaScript \n represents a new line character, \r represents a carriage return, and \t is a tab character.
The second while loop does the same thing with the first character in str.
*/

function textAreaMaxLength( maxLength ) {
	window.event.returnValue = ( window.event.srcElement.value.length < maxLength );
}

function textAreaMaxLenghCut( maxLength ) {
	if (!window.event) {
		return;
	}
	if ( window.event.srcElement.value.length > maxLength ) {
		window.event.srcElement.value = window.event.srcElement.value.substring( 0, maxLength );
	}
}

function textAreaMaxLengthCritica( maxLength ) {
	f = window.event.srcElement;
	if ( f.value.length > maxLength ) {
		f.focus();
		alert( "Há " + f.value.length + " caracteres. Máximo: " + maxLength );
		f.value = f.value.substring( 0, maxLength );
		window.event.returnValue = false;
	}
}

function isPositiveInteger(str) {
  var pattern = "0123456789"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
        pos = 1;
        break;
      }
    i++;
  } while (pos==1 && i<str.length)
  if (pos==0)
    return false;
  return true;
}

function sair() {
	window.open( "nothing.htm", "_self" );
}

function generateRandomID() {
	d = new Date();
	id = d.getFullYear() + "" +
		( d.getMonth() + 1 ) + "" +
		d.getDate() + "" +
		d.getHours() + "" +
		d.getMinutes() + "" +
		d.getSeconds() + "" +
		d.getMilliseconds() + "" +
		parseInt( Math.random() * 10000 );
	return id;
}

function fecharJanela() {
	window.returnValue = false;
	window.close();
}

function writeParam (param, value) {
	if (value != "") {
		document.write('   <param name="');
		document.write(param);
		document.write('" VALUE="');
		document.write(value);
		document.writeln('" >');
	}
}

function paintCol( row, c, bc ) {
    for ( var i=0; i < row.cells.length; i++ ) {
        row.cells(i).style.color = c;
        row.cells(i).style.backgroundColor = bc;
    }
}

// Controlar barra de seleção de registro
function selecionarRegistro( rowKeyField, row ) {
    // Se a célula selecionada for do Header
    if ( row.rowIndex == 0 ) {
        return;
    }
	// Armazenar linha e valor da chave selecionada
    controleTabela.selectedRow = row;
    controleTabela.keyField    = rowKeyField;

    table = row.parentElement.parentElement;
    // se houver mais de uma linha
    if ( table.rows.length > 1 )
		for ( var i = 1; i < table.rows.length; i++ ) {
			tableRow = table.rows(i);
			tableRow.style.cursor = "pointer";
			if ( i == row.rowIndex ) {
				paintCol( tableRow, "White", "Navy" );
				row.style.cursor = "default";
			} else {
				if ( i % 2 == 0 ) {
					paintCol( tableRow, "Navy", "#DAE2F1" );
				} else {
					paintCol( tableRow, "Navy", "White" );
				}
			}
		}
}

function limparStatus() {
    window.status = "";
}
function initZoom() {
}

function deleteElements( elementName ) {
	if ( $( elementName ) == null ) return;
	var element;
	var tam = document.all.item( elementName ).length;
	if ( tam == null )
		//document.body.removeChild( document.body.item( elementName ) );
		try {
			document.all.item( elementName ).parentElement.removeChild( document.all.item( elementName ) );
		} catch ( e ) {
			try {
				document.body.removeChild( document.all.item( elementName ) );
			} catch ( e ) {
			}
		}
	else if ( document.all.item( elementName ).length > 0 ) {
		var parentElement = document.all.item( elementName ).item( 0 ).parentElement;
		for ( var i = tam - 1; i >= 0; i-- ) {
			try {
				parentElement.removeChild( document.all.item( elementName ).item( i ) );
			} catch ( e ) {
				try {
					document.all.body.removeChild( document.all.item( elementName ).item( i ) );
				} catch ( e ) {
				}
			}
		}
	}
}

function mesChange() {
}

function folha_ads_show( x, y, z ) {
}

function dateFormat_DD_MM_YYYY( dia, mes, ano ) {
	if ( dia < 10 ) dia = "0" + dia;
	if ( mes < 10 ) mes = "0" + mes;
	return dia + "/" + mes + "/" + ano;
}

function getFileExt( midiaTypeCode ) {
	switch ( midiaTypeCode ) {
		case TIPO_MIDIA_FOTO  :
		case TIPO_MIDIA_GALERIA  :
			return "jpg";
			break;
		case TIPO_MIDIA_VIDEO :
			return "mpg";
			break;
		case TIPO_MIDIA_AUDIO :
			return "mp3";
	}
	return "ERRO";
}

function checkDialogWindow() {
	if ( windowIsModal() ) {
		window.document.write( "<body bgcolor=#EEEEEE style='font-family:verdana,arial;font-size:14;color:#293A5C;overflow-y:hidden'>AgÃªncia Tempo<hr></body>" );
	}
}

function showWindowInformation() {
	with ( window.screen )
		if ( windowIsModal() )
			alert( "availHeight: " +		availHeight + "\n" +
					"availWidth: " +		availWidth + "\n" +
					"bufferDepth: " +		bufferDepth + "\n" +
					"colorDepth: " +		colorDepth + "\n" +
					"height: " +			height + "\n" +
					"updateInterval: " +	updateInterval + "\n" +
					"width: " + 			width + "\n" +
					"dialogArguments: " +	dialogArguments + "\n" +
					"dialogHeight: " +		dialogHeight + "\n" +
					"dialogLeft: " +		dialogLeft + "\n" +
					"dialogTop: " + 		dialogTop + "\n" +
					"dialogWidth: " +		dialogWidth
					);
		else
			alert( "availHeight: " +		availHeight + "\n" +
					"availWidth: " +		availWidth + "\n" +
					"bufferDepth: " +		bufferDepth + "\n" +
					"colorDepth: " +		colorDepth + "\n" +
					"height: " +			height + "\n" +
					"updateInterval: " +	updateInterval + "\n" +
					"width: " + 			width
					);
}

var WindowDialog = new Object();
WindowDialog.Show = function(pageUrl, dialogWidth, dialogHeight, parentWindow, resizable) {
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){// Checa o Browser
        if ( !parentWindow ) {
            parentWindow = window;
            }

		var features = "dialogWidth=" + dialogWidth + "px;dialogHeight=" + dialogHeight + "px;help=no;scroll=no;status=no;";
        var oReturn = parentWindow.showModalDialog(pageUrl, features );

    } else {
        var iTop  = (screen.height - dialogHeight)/2;
        var iLeft = (screen.width  - dialogWidth)/2;
// Obs.: O Fórum está mudando na linha abaixo a aspa dupla (") pelo (& #34;). é só mudar manualmente.
   var sOption  = "location=no;menubar=no;toolbar=no;dependent=yes;dialog=yes;minimizable=no;modal=yes;alwaysRaised=yes;" +
            ";resizable="  + ( resizable ? 'yes' : 'no' ) +
            ";width="  + dialogWidth +
            ";height=" + dialogHeight +
            ";top="  + iTop +
            ";left=" + iLeft;

        if ( !parentWindow )
            parentWindow = window;

        var oWindow = parentWindow.open('',"Caixa de Diálogo", sOption, true);

        oWindow.moveTo(iLeft, iTop); // Para navegadores que não aceitem os índices top e left;
        oWindow.resizeTo(dialogWidth, dialogHeight);
        oWindow.focus();// Mantém o foco na janela aberta
        oWindow.location.href = pageUrl;
}
}
WindowDialog.showSimulation = function( pageUrl, dialogWidth, dialogHeight, parentWindow ) {

	showPopWin( pageUrl, 400, 200, null);

}

function getCodigoTipoMidiaExtendido( codigo ) {
	if ( codigo == "F" ) return TIPO_MIDIA_FOTO;
	if ( codigo == "V" ) return TIPO_MIDIA_VIDEO;
	if ( codigo == "A" ) return TIPO_MIDIA_AUDIO;
	if ( codigo == "T" ) return TIPO_MIDIA_TEXTO;
	if ( codigo == "C" ) return TIPO_MIDIA_COLUNA;
	return "XXX";
}

function getCodigoTipoMidia( codigo ) {
	if ( codigo == "F" ) return TIPO_MIDIA_FOTO;
	if ( codigo == "V" ) return TIPO_MIDIA_VIDEO;
	if ( codigo == "A" ) return TIPO_MIDIA_AUDIO;
	if ( codigo == "T" ) return TIPO_MIDIA_TEXTO;
	if ( codigo == "C" ) return TIPO_MIDIA_COLUNA;
	return "XXX";
}

function windowIsModal() {
	return ( window.parent == window );
}

function showNavigatorInformation() {
	var navigatorInformation =
       "Informações do Navegador<hr>" +
       "<br>appCodeName		: " + window.navigator.appCodeName	 + "\n" +
	   "<br>appMinorVersion	: " + window.navigator.appMinorVersion + "\n" +
	   "<br>appName 		: " + window.navigator.appName 		 + "\n" +
	   "<br>appVersion 		: " + window.navigator.appVersion 	 + "\n" +
	   "<br>browserLanguage	: " + window.navigator.browserLanguage + "\n" +
	   // "<br>connectionSpeed	: " + window.navigator.connectionSpeed + "\n" +
	   "<br>cookieEnabled 	: " + window.navigator.cookieEnabled 	 + "\n" +
	   "<br>cpuClass 		: " + window.navigator.cpuClass 		 + "\n" +
	   "<br>onLine 			: " + window.navigator.onLine 		 + "\n" +
	   "<br>platform 		: " + window.navigator.platform 		 + "\n" +
	   "<br>systemLanguage 	: " + window.navigator.systemLanguage  + "\n" +
	   "<br>userAgent 		: " + window.navigator.userAgent 		 + "\n" +
	   "<br>userLanguage 	: " + window.navigator.userLanguage 	 + "\n" +
	   "<br>userProfile 	: " + window.navigator.userProfile ;

	var janela = window.open( "", null, "width=600px,height=400px,top=100px,left=200px;status=no,center=yes,location=no,resizable=no,directories=no,toolbar=no,menubar=no" );

	if ( janela ) {
		janela.document.body.innerHTML = "";
		janela.document.write( "<body style='font-family:arial,verdana;font-size:14;background-color:#FFFBF0'>" );
		janela.document.write( "\n" + navigatorInformation.replace( "<br>", "" ) );
		janela.document.write( "</body>" );
	} else {
		with ( window.navigator )
			alert( "appCodeName		" + appCodeName	 + "\n" +
				   "appMinorVersion	" + appMinorVersion + "\n" +
				   "appName 		" + appName 		 + "\n" +
				   "appVersion 		" + appVersion 	 + "\n" +
				   "browserLanguage	" + browserLanguage + "\n" +
				   // "connectionSpeed	" + connectionSpeed + "\n" +
				   "cookieEnabled 	" + cookieEnabled 	 + "\n" +
				   "cpuClass 		" + cpuClass 		 + "\n" +
				   "onLine 			" + onLine 		 + "\n" +
				   "platform 		" + platform 		 + "\n" +
				   "systemLanguage 	" + systemLanguage  + "\n" +
				   "userAgent 		" + userAgent 		 + "\n" +
				   "userLanguage 	" + userLanguage 	 + "\n" +
				   "userProfile 	" + userProfile );
	}
}

function wopen(url, name, w, h, debug, x, y)
{
  var wleft;
  var wtop;
  w += 32;
  h += 96;
  if (!x) {
  	wtop = (screen.height - h) / 2;
  } else {
  	wtop = x;
  }
  if (!y) {
  	wleft = (screen.width - w) / 2;
  } else {
  	wleft = y;
  }
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  if (debug) {
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=yes, toolbar=yes, scrollbars=yes, resizable=yes');
  } else {
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=yes, resizable=no');
  }
  win.resizeTo(w, h);
  win.moveTo(wleft, wtop);
  win.focus();
  return win;
}

function trocarCaracteresInputs(form) {
	form = $(form);
	var elementos;
	elementos = form.getInputs('text');
	elementos = elementos.concat(form.getElements('textarea'));
	elementos.each(function(elemento) {
		var deveTrocar;
		if (elemento.tagName.toLowerCase() == 'textarea') {
			deveTrocar = true;
		} else {
			try {
				deveTrocar = elemento.readAttribute('tratarChars');
			} catch (e) {
				deveTrocar = elemento.tratarChars;
			}
		}
		if (deveTrocar) {
			var valor = elemento.value;
			if (valor != "") {
				var invalido = [8211, 8212, 8213, 8216, 8217, 8219, 8220, 8221];
				var valido =   ['-' , '-' , '-' , '\'' , '\'','\'' , '"' , '"'];
				for (var i = 0; i < invalido.length; i++) {
					var letra = String.fromCharCode(invalido[i]);
					while(valor.indexOf(letra) != -1) {
						valor = valor.replace(letra, valido[i]);
					}
				}
				elemento.value = valor;
			}
		}
	});
}

function IsValidTime(timeStr) {
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];
	
	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }
	
	if (hour < 0  || hour > 23) {
		return false;
	}
	if  (hour > 12 && ampm != null) {
		return false;
	}
	if (minute<0 || minute > 59) {
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		return false;
	}
	return false;
}


function formataHora(campo,teclapres) {

	var tecla = teclapres.keyCode;

	if ( tecla < 48 || tecla > 57 ) {
		teclapres.returnValue = false;
		return;
	}

    vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ) {
            campo.value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
        }
	}
}