var reSpaces			= /^\s+$/
var reLetra 			= /^[a-zA-Z]$/
var reAlfabetico 		= /^[a-zA-Z]+$/
var reAlfanumerico 		= /^[a-zA-Z0-9]+$/
var reAlfaSpaces		= /^[a-zA-Z0-9\s]+$/
var reDigito 			= /^\d/
var reLetraOuDigito 	= /^([a-zA-Z]|\d)$/
var reInteiro 			= /^\d+$/
var reSinalInteiro 		= /^(\+|\-)?\d+$/
var reDecimais 			= /((^\d*),?$)|((^\d*),(\d*)$)/
var reSinalDecimais     = /^(\+|\-)?((\d*,?$)|(\d*,\d*$))/
var re2Decimais			= /(^\d*,?$)|(^\d*,\d{1,2}$)/
var reSinal2Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,2}$))/
var re4Decimais			= /(^\d*,?$)|(^\d*,\d{1,4}$)/
var reSinal4Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,4}$))/
var re7Decimais			= /(^\d*,?$)|(^\d*,\d{1,7}$)/
var reSinal7Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,7}$))/
var reEmail 			= /^.+\@.+\..+$/
var reSN				= /^[SNsn]$/
var reCPFCGC            = /(^(\d{3})\W?(\d{3})\W?(\d{3})\W?(\d{2})$)|(^(\d{8})\W?(\d{4})\W?(\d{2})$)/ 
var feCPFCGC			= "$2$3$4$5$7$8$9"
var fsCPFCGC			= "$2$3$4$5$7$8$9"
var reCPF               = /^(\d{3})\W?(\d{3})\W?(\d{3})\W?(\d{2})$/ 
var fsCPF				= "$1.$2.$3-$4"
var feCPF				= "$1$2$3$4"
var reCGCMF             = /^(\d{8})\W?(\d{4})\W?(\d{2})$/
var fsCGCMF				= "$1/$2-$3"
var feCGCMF				= "$1$2$3"
var reCEP				=/^(\d{5})\W?(\d{3})$/
var feCEP				="$1$2"
var fsCEP				="$1$-2"
var reIERS              = /^(\d{3})\W?(\d{3})\W?(\d{4})$/
var fsIERS				= "$1/$2$3"
var feIERS				= "$1$2$3"
var reData		    	= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{1,3})$/
var fsData				= "$1/$5/$8"
var feData				= "$1$5$8"
var reMMAAAA		    = /^(([0]?[1-9])|([1][0-2]))\W?([1-9]\d{3})$/
var fsMMAAAA			= "$1/$4"
var feMMAAAA			= "$1$4"
var reDDMMAAAA			= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{3})$/
var fsDDMMAAAA			= "$1/$5/$8"
var feDDMMAAAA			= "$1$5$8"
var reDDMMAA			= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([0-9][0-9]{1})$/
var fsDDMMAA			= "$1/$5/$8"
var feDDMMAA			= "$1$5$8"
var reDDMM				=/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))$/
var feDDMM              = "$1$5"
var fsDDMM              = "$1/$5"
var reDia				=/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))$/ 
var reMes				=/^(([0]?[1-9])|([1][0-2]))$/ 
var reAno4				=/^[1-9][0-9]{3}$/
var reAno2				=/^[0-9][0-9]{1}$/
var reCtaCtb			=/^(\d{1})\W?(\d{2})\W?(\d{2})\W?(\d{4})$/
var feCtaCtb			="$1$2$3$4"
var fsCtaCtb			="$1.$2.$3.$4"
var reRubrica           =/^(\d{4})$/
var reProjSub	   		=/^(\d{4})\W?(\d{3})$/
var feProjSub			="$1$2"
var fsProjSub			="$1.$2"
var reProcesso			=/^(\d{6})\W?(\d{4})\W?(\d{2})\W?(\d)$/
var feProcesso			="$1$2$3$4"
var fsProcesso			="$1.$2.$3-$4"
var reUO				=/^(\d{2})\W?(\d{2})$/
var feUO				="$1$2"
var fsUO				="$1.$2"
var reClassRec			=/^(\d{4})\W?(\d{2})\W?(\d{3})$/
var feClassRec			="$1$2$3$"
var fsClassRec			="$1.$2.$3"
var reCurrency			= /^(R\$\s*)?(([0-9]{1,3})+(\,([0-9]{2}$)))/;
var feCurrency			="$2"
var fsCurrency			="R$ $2"

if (!self.g_IS)g_IS= new Is()
function getStyle(obj){
	if (g_IS.w3c) return obj.style
	else return obj
}
function Is() {
    var agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);
    this.ns  = ((agent.indexOf('mozilla')!=-1) && ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
    this.ns2 = (this.ns && (this.major == 2));
    this.ns3 = (this.ns && (this.major == 3));
    this.ns4b = (this.ns && (this.minor < 4.04));
    this.ns4 = ((this.ns && (this.major >= 4))&&!(agent.indexOf('netscape6')!=-1));
	this.gek = (agent.indexOf('gecko')!=-1);
	this.ns6 = (agent.indexOf('netscape6')!=-1);
    this.ie   = (agent.indexOf("msie") != -1);
    this.ie3  = (this.ie && (this.major == 2));
    this.ie4  = (this.ie && (this.major == 4));
    this.ie5  = (this.ie && (this.major >= 4));
    this.op  =  (agent.indexOf("opera") != -1);
	this.w3c = ((agent.indexOf('netscape6')!=-1)||(this.ie && (this.major >= 4)));
}
if (g_IS.ns4){
   g_sSTYLE_REF 			= "";
   g_sDOC_REF 				= "document.layers";
   g_sDOC					="document."		// Netscape aceita visibility igual ao Explorer:
   g_sVISIBLE_REF 			= "show"			// setar style visibility como 'visible' ou 'hidden' 
   g_sHIDE_REF				="hide"				// buscar eh que tem diferenca 'show' e 'hide'g_sSTYLE_REF 			= ".style";
}
else{
   g_sSTYLE_REF				= ".style"
   g_sDOC_REF 				= "document.all";
   g_sDOC					=""
   g_sVISIBLE_REF 			= "visible" 	
   g_sHIDE_REF 				= "hidden"		   
}										

function pegaObjeto(sObj,oOrigem){
	if(!oOrigem) 
	{oOrigem=self 
	}
	if(!isObject(oOrigem))
	{ oOrigem=frames[oOrigem]
	  if (!oOrigem)
	     {var sOrigem=oOrigem ;
	     oOrigem=pegaObjeto(sOrigem,self.parent)}
	  if (!oOrigem)
	     {oOrigem=pegaObjeto(sOrigem,self.top);}
	  if (!oOrigem)
	    {alert('erro - frame não localizado:'+sOrigem);return}
	}
	if (g_IS.ns4) // netscape 4
	{   if  (oOrigem.document.forms[sObj])
		{   return oOrigem.document.forms[sObj]
		}
		for (var f=0;f<oOrigem.document.forms.length;f++)
		{   if (oOrigem.document.forms[f].elements[sObj])
			{   return oOrigem.document.forms[f].elements[sObj]
			}
		}
		if (oOrigem.document.images[sObj])
		{	return oOrigem.document.images[sObj]
		}
		if (oOrigem.document.links[sObj])
		{	return oOrigem.document.links[sObj]
		}
		if (oOrigem.document.anchors[sObj])
		{	return oOrigem.document.anchors[sObj]
		}
		if (oOrigem.document.applets[sObj])
		{	return oOrigem.document.applets[sObj]
		}
		if (oOrigem.document.layers[sObj])
		{	return oOrigem.document.layers[sObj]
		}
		var obj=null
		for (var l=0;l<oOrigem.document.layers.length;l++)
		{	obj=pegaObjeto(sObj,oOrigem.document.layers[l])
			if(obj)	return obj
		}
	}
	else 
	{	if (g_IS.ie4) //explorer 4 ou superior
			{if (oOrigem.document.all[sObj]) 
				{return oOrigem.document.all[sObj]}
			}
		else 
		{ 	if (g_IS.w3c) //netscape 6 e explorer 5 (w3c)
			{   var col=oOrigem.document.getElementsByName(sObj)
				if (col.length==1) return col[0]
				if (col.length>1) return col
				if (oOrigem.document.getElementById(sObj))
			 	return oOrigem.document.getElementById(sObj)
			}
	 	}
	}
	if(oOrigem.frames)
	{ 	if (oOrigem.frames[sObj]) return oOrigem.frames[sObj]
		for (var fr=0;fr<oOrigem.frames.length;fr++)
		{	obj=pegaObjeto(sObj,oOrigem.frames[fr])
			if(obj)	return obj
		}
	}
	return
}


function isObject(obj){var stobj= typeof obj;return (stobj.indexOf("object")>=0)}
function isString(obj){var stobj= typeof obj;return (stobj.indexOf("string")>=0)}
function isDate(obj) {	return (obj&&obj.year)?true:false;}
function isArray(obj){return (obj&&obj.sort)?true:false}

function dw(div,stexto,frame){

	if (!isObject(frame)){ 
		if (frame){
			frame = frames[frame];
		}
		else{
			frame = self;
		}
	}
	
	sframe = (frame.name)?frame.name:((frame.title)?frame.title:frame.id);
	
	if (!isObject(div)){
		oDiv = pegaObjeto(div,frame)
		if (!oDiv){
			if (top.debug)
				alert(div+", em "+sframe+" não encontrada");
		return false
		}
	}
	else oDiv = div;

	if (g_IS.ns4){
		oDiv.document.open(); 
		oDiv.document.write(stexto);
		oDiv.document.close();
	}
	else
		oDiv.innerHTML = stexto;
}

function goToLink(pagina){
	if (pagina != ''){
		this.location.href = pagina; 
	}
}


function formatoData(data){
	if  (bMMAAAA=reMMAAAA.test(data)) return 4	
	if  (reDDMMAA.test(data))  return 1
	if  (reDDMMAAAA.test(data)) return 2
	if  (bDDMM=reDDMM.test(data)) return 3
	return false
}


function formatDMA(sStr,numZeros){	//Completa Zeros - para impFormatCampo
	var  i, sRes;
	if (sStr.length < numZeros && sStr.length > 0)
		for (i=sStr.length;i < numZeros; i++)
			sStr = "0" + sStr;
			
	return sStr;	
}


function impFormatCampo(campo, reBusca, sTroca,umavez,ignorecase){
	// - Completa Zeros em Dia e Mês
	var arrDMA
	arrDMA = campo.value.split("/");
	if (arrDMA.length>2)
	campo.value = formatDMA(arrDMA[0],2)+"/"+formatDMA(arrDMA[1],2)+"/"+arrDMA[2];	// DD/MM/AAAA
	// - - - 
	
    campo.value=impFormat(campo.value, reBusca, sTroca,umavez,ignorecase) 
	campo.select()
}


function impAutoTab(input,tam, e,reBusca,fsSaida) { //netscape nao tem .maxLength o que exige reinformar 'len'
	var keyCode = (g_IS.ns4) ? e.which : e.keyCode; 
	var filter = (g_IS.ns4) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(reBusca!=null&&fsSaida!=null) {
			input.value=input.value.replace(reBusca,fsSaida)
	}
	if(input.value.length >= tam && impContainsElement(filter,keyCode)==-1) {
		input.value = input.value.slice(0, tam);
		impAvancaCampo(input);
	}
	return true;
}

function impAvancaCampo(input){	
	input.form[(impGetProxIndex(input))].focus();
	return		
}


var impPararNoUltimo = true;  				 // Usado para fazer ciclo : false= retorna ao primeiro - true = trava no ultimo campo 

function impGetProxIndex(input){
	var ind=impGetIndex(input)
	var indpx=ind;
	var flag =impPararNoUltimo // Evita loop infinito em forms com camo hidden
	do {//ignorar campos hidden
		if( ++indpx==input.form.length){ //rodar no form (do ultimo para o primeiro)
			if (flag){
				indpx=ind;
				break
			}
			indpx= 0;     
			flag=true;
		}
	} while(input.form[indpx].type=='hidden');
	return indpx
}

//obtem posicao atual do campo no forms
function impGetIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
}

// verifica existencia de 'ele' no array 'arr'
function impContainsElement(arr, ele) {
	var found = -1, index = 0;
	while(found==-1 && index < arr.length){
		if(arr[index] == ele){
			found = index;
		}
		else {
			index++;
		}
	}
	return found;
}


//substitui todas as ocorrencias de uma string expressão regular por outra
function impFormat(instr, reBusca, sTroca,umavez,ignorecase) {
    if (isString(reBusca)){ 
	  	reBusca = new RegExp(reBusca,((ignorecase)?"i":"")+((umavez)?"":"g"))
	}
    return instr.replace(reBusca,sTroca);
}


function impValCPFCGC(field,bmsg,itipo) {
    var atipo=["CPF/CNPJ","CPF","CNPJ"]
    itipo=(itipo)?itipo:0 //0=qualquer, 1=cpf,2=cgc   
	var cpf='', cgc='', digito='',dg='', dgc='', digitoc='', k=0; i=0, j=0, soma=0, mt=0;
	if (field.value=='') return 0
	var cpfcgc = field.value;
	var bcpf=false
	var bcgc=false
	if (itipo==0||itipo==1) bcpf= reCPF.test(cpfcgc)	// valida tamanho e formato do CPF
	if (itipo==0||itipo==2) bcgc= reCGCMF.test(cpfcgc)	// valida tamanho e formato do CCG
	if ((!bcpf)&&(!bcgc)){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
if (bcpf){cpfcgc=cpfcgc.replace(reCPF,feCPF) }
else     {cpfcgc=cpfcgc.replace(reCGCMF,feCGCMF)} 
var cpferr = "0000000000011111111111222222222223333333333344444444444"+
             "5555555555566666666666777777777778888888888899999999999"
if ( cpferr.indexOf(cpfcgc)>=0){// informado campo de facil entrada
	 	 if(bmsg) alert ("Conteúdo não é aceito como "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
mult = [2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9]; // tabela de pesos para colunas 
if (bcgc)
	{  	cgc = cpfcgc.substring(0,12);
		digito = cpfcgc.substring(12,14);
		for (j = 1; j <= 2; j++) {
		    digitoc = impCalcDig11(cgc)
		    if (digitoc == 10){digitoc = 0}
		    dgc +=digitoc;
			cgc+=digitoc;
		}
  }
  else {
	  cpf = cpfcgc.substring(0,9);
	  digito = cpfcgc.substring(9,11);
	  for (j = 1; j <= 2; j++) {
	    soma = 0;
	    mt = 2;
	    for (i = 8 + j; i >= 1; i--) {
	      soma += parseInt(cpf.charAt(i-1),10) * mt;
	      mt++;
	    }
	    dg = 11 - (soma % 11);
	    if (dg > 9) {dg = 0};
	    cpf += dg;
		dgc+=dg
	  }
  } 
  if (dgc != digito) {// digito inválido
	 	 if(bmsg) alert (((bcgc)?"CNPJ":"CPF")+" com dígitos inválidos\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
  else {
   field.value=impFormat(field.value,((bcgc)?reCGCMF:reCPF),((bcgc)?fsCGCMF:fsCPF))
   return true }
 
  }

function impValIERS(field,bmsg) {
var dg='',ie='',IERS='',dgc=''
if (field.value=='') return 0
var IERS = field.value;
bIERS= reIERS.test(IERS)	// valida tamanho e formato do CPF
if (!bIERS){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como Inscrição Estadual -RS\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
IERS=impFormat(IERS,reIERS,feIERS)
ie=IERS.substring(0,9)
dg=IERS.substring(9)
dgc=impCalcDig11(ie)
if (dgc==10) dgc=0
if (dg!=dgc) {// Dígito inválido
	 	 if(bmsg) alert ("Inscrição Estadual com dígitos inválidos\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
else  {
   field.value=impFormat(field.value,reIERS,fsIERS)
   return true }
 
}


//digito módulo 11 - pode retornar digito 10  para verificação de aproveitamento
// 					 
function impCalcDig11(numero)
{var pesos=[2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9]
 var calc= 0 , x=''
 var numero=String(numero).split("")
 var limite=numero.length -1
 var result = 0
 var pso=0
 for (var i=limite; i>=0; i--)
 { x+="\npso:"+pesos[pso]+" * "+ numero[i] + " = " + (pesos[pso] * parseInt(numero[i]))
   calc += (pesos[pso++] * parseInt(numero[i]))
 } 
 result = 11 - ((calc)%11)
  if (result == 11){result = 0}
  return result	 
  
}

function impValData(field,bmsg,itipo) {
  	if (field.value==""){return 0};
    var atipo=["data","dd/mm/aa","dd/mm/aaaa","dd/mm","mm/aaaa"]
    itipo=(itipo)?itipo:0 //0=qualquer, 1=dmaa,2=dmaaaa,3=ddmm,4=mmaaaa   
    var bformatoData = formatoData(field.value)
	var bDDMMAA 	=((bformatoData==1)&&(itipo==0||itipo==1))
	var bDDMMAAAA	=((bformatoData==2)&&(itipo==0||itipo==2))
	var bDDMM 		=((bformatoData==3)&&(itipo==0||itipo==3))
	var bMMAAAA		=((bformatoData==4)&&(itipo==0||itipo==4))

	if ((!bDDMMAA)&&(!bDDMMAAAA)&&(!bDDMM)&&(!bMMAAAA)){// formato não reconhecido
	 	 //if(bmsg) alert ("Conteúdo informado não reconhecido como sendo "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
  	var dia0,mes0,ano0
  	var auxData;
  	var dData=""
	var dHoje=new Date()
	
	if (bDDMMAAAA) dData = impFormat(field.value,reDDMMAAAA,fsDDMMAAAA);
  	else if (bDDMMAA) dData = impFormat(field.value,reDDMMAA,fsDDMMAA);
		 else dData=impFormat(field.value+"/"+dHoje.getFullYear(),reDDMMAAAA,fsDDMMAAAA)
		 	  if (bMMAAAA) dData=impFormat(field.value,reMMAAAA,fsMMAAAA) //MMAAAA

  	dma=dData.split("/")
	
	if (bDDMMAA){dma[2]= (dma[2]<20)?parseInt(dma[2])+2000:parseInt(dma[2])+1900} // janelamento de data
	
	if (bMMAAAA){dma[2]= dma[1];  dma[1]= dma[0];} //ajusta array comparativo para MMAAAA
		
	var obj = new Date(dma[2], dma[1]-1, dma[0])//cria data no browser


	dma[0]= "00" + dma[0]
	dma[1]= "00" + dma[1]
	dma[2]= "0000" + dma[2]
  	dma[0] = dma[0].substr(dma[0].length-2) 
  	dma[1] = dma[1].substr(dma[1].length-2)
  	dma[2] = dma[2].substr(dma[2].length-4)
  	dData=dma.join("/")
	
	dia0 = "00" + obj.getDate()
  	mes0 = "00" + (obj.getMonth()+1)
  	ano0 = "0000" + obj.getFullYear()
  	dia0 = dia0.substr(dia0.length-2) 
  	mes0 = mes0.substr(mes0.length-2)
  	ano0 = ano0.substr(ano0.length-4)
	if (bMMAAAA)
		{ auxData =  mes0 + "/"+ ano0
		  dData = dma[1] + "/"+ dma[2]}
	else{ auxData = dia0 + "/"+  mes0 + "/"+ ano0}

	if ((auxData != dData)) { 
		if (bmsg) alert("Data incorreta\nVerifique sua Digitação")
		field.select();field.focus()
		return false     
	}
  	else {  if (bMMAAAA){field.value=mes0+"/"+ano0}
			else 		{field.value=dia0+"/"+mes0+((itipo==3)?"":("/"+((itipo==1)?ano0.substring(ano0,2):ano0)))}
			return true}
}


function impVal
(obj,str) {
	if (!obj || obj != '[object]') {
		alert("Erro, obj não declarado ou não é objeto.\nLocal: PRInputs.js # impValNumerico.")
		return false
	}
	if (isNaN(obj.value)) {
		if (str) {
			alert("O conteúdo informado para " + str + " deve ser numérico.")
		} else {
			alert("O conteúdo informado deve ser numérico.")
		}
		obj.focus()
		obj.select()
		return false;
	}
	return true
}


function InsertLink() {
	var URL = window.prompt("Digite a URL!","http://");
	if (URL == "" || URL == null || URL == "http://") {
		alert("Você não digitou a URL");
	}else {
			if((URL.indexOf('http://') == -1)){//SE NÃO FOR DIGITADO 'HTTP://', COMPLEMENTA COM 'HTTP://'
				tmpStartTag = "<a HREF='http://" + URL + "' target='_blank'>";
				tmpEndTag = "</a>";
				GetSelection(tmpStartTag, tmpEndTag, null);
			}else{
				tmpStartTag = "<a HREF='" + URL + "' target='_blank'>";
				tmpEndTag = "</a>";
				GetSelection(tmpStartTag, tmpEndTag, null);
			}
	}
}

function InsertEmail() {
	var Email = window.prompt("Digite o e-mail!","");
	if (Email == "" || Email == null) {
		alert("Você não digitou o e-mail!");
	} else {
		if (Verifica_Email(Email)) {
			tmpStartTag = "<a HREF='mailto:" + Email + "'>";
			tmpEndTag = "</a>";
			GetSelection(tmpStartTag, tmpEndTag, null);
		} else {
			alert("Você digitou um e-mail inválido!");
		}
	}
}

function InsertImage(ImageFile) {
	if (ImageFile == "NoFile") {
		ImageFile = window.prompt("Digite a url da imagem + o nome da imagem!","");
	}
	if (ImageFile == "" || ImageFile == null) {
		alert("Você não digitou a url da imagem!");
	} else {
		FileName = ImageFile.toLowerCase();
		if (FileName.indexOf(".jpg") <= 0 && FileName.indexOf(".gif") <= 0 && FileName.indexOf(".png") <= 0) {
			alert("Você não específicou a estensão. use somente JPGs, GIFs e PNGs!")
		} else {	
			document.News.Text.value = document.News.Text.value + "<IMG src='" + ImageFile + "' border='0'>";
		}
	}
}

function InsertQuote() {
	GetSelection("<BR><hr><small><B>Citação:</B></small><BR><i>","</i><BR><hr>","Inserir citação aqui");
}

function InsertSpoiler() {
	GetSelection("<BR><BR><div class='SpoilerTitle'>Highlight to read:</div><div class='SpoilerText'>","</div><BR>","INSERT SPOILER TEXT HERE");
}

function InsertAmazon() {
	var ID = window.prompt("Enter your Amazon-PartnerID!","");
	var Lang = window.confirm("Press OK if '" + ID + "' is an amazon.de PartnerID!");
	if (Lang == false) {
		Lang = window.confirm("Press OK if '" + ID + "' is an amazon.com PartnerID!");
		if (Lang == false) {
			Lang = "co.uk";
		} else {
			Lang = "com";
		}
	} else {
		Lang = "de";
	}
	if (ID == "" || ID == null) {
		alert("You didn't enter your ID");
	} else {
		var ASIN = window.prompt("Enter ASIN of Amazon product!","");
		if (ASIN || null) {
			while (ASIN.length != 10) {
				ASIN = window.prompt("The ASIN has 10 digits. Please enter correct one!","");
			}
			var ProductName = window.prompt("Enter name or description of product!","");
			if (ProductName == "" || ProductName == null) {
				alert("You didn't enter a description for the product");
			} else {
				document.News.Text.value = document.News.Text.value + "<a HREF='http://www.amazon." + Lang + "/exec/obidos/ASIN/" + ASIN + "/" + ID + "' target='_blank'>" + ProductName + "</a>";
			}
		}
	}
}

function InsertList() {
	var List = "<ul>"
	var ListText = "";
	var ListItem = "";
	var ListCount = 1;
	do {
		List = List + ListItem;
		ListText = window.prompt("Digite o ítem #" + ListCount + "! Leave blank if no more items should be added!","");
		ListItem = "<li>" + ListText + "</li>";
		ListCount++;
	}
	while (ListText != "" && ListText != null);
	var List = List + "</ul>";
	if (List == "<ul></ul>") {
		alert("You didn't enter at least one item");
	} else {
		document.News.Text.value = document.News.Text.value + List;
	}
}

function InsertSmilie(SmilieCode) {
	document.News.Text.value = document.News.Text.value + SmilieCode;
}

function Preview() {
	var PreviewCookie = "PreviewHeadline=" + escape(document.News.Headline.value);
	document.cookie = PreviewCookie;
	var PreviewCookie = "PreviewNews=" + escape(document.News.Text.value);
	document.cookie = PreviewCookie;
	PreviewWin = window.open('preview.asp', 'Preview', 'dependent=yes,resizable=yes,scrollbars=yes')
}


function FormatText(Tag) {
	tmpStartTag = "<" + Tag + ">";
	tmpEndTag = "</" + Tag + ">";
	GetSelection(tmpStartTag, tmpEndTag, null);
}

function GetSelection(strBefore, strAfter, strContent) {
	var Selection = document.selection.createRange();
	if (Selection.text != "" && Selection.text != null) {
		Selection.text = strBefore + Selection.text + strAfter;
	} else {
		alert('Texto não foi selecionado.\nSelecione o texto, logo após clique sobre a TAG desejada.');
	}
}

function ExibeDiv(oDiv,vtop,vleft,vpos){
	if (g_IS.ns4){
		oDiv.visibility = 'visible'
	}else{
		if (vtop == ''){
			oDiv.style.visibility = 'visible'
		}else{
			oDiv.style.visibility = 'visible'; oDiv.style.position = vpos; left = vleft; oDiv.style.top = vtop
		}
	}
}

function EscondeDiv(oDiv){
	if (g_IS.ns4) oDiv.visibility = 'hide'; else oDiv.style.visibility='hidden'; 
}


// Limita a digitação em um textarea
// ex.: <textarea name="exemplo" id="exemplo" onChange="checkTamTextarea(this,'5');" onKeyDown="checkTamTextarea(this,'5');" onKeyUp="checkTamTextarea(this,'5');"></textarea>
function checkTamTextarea(campo,valor){
	StrLen = campo.value.length;
	if (StrLen == 1 && campo.value.substring(0,1) == " "){
	  	campo.value = "";
        StrLen = 0;
	}
	else if (StrLen > valor){
       campo.value = campo.value.substring(0,campo.value.length-1);
    }
}


// Example: obj = findObj("image1");
function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(t1eObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}


function Numerico(Bflag){
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;

  if (Bflag){ // Somente numeros, virgula, espaço, barra ou ífem, backspace e parenteses
	if ((Tecla > 47 && Tecla < 58) || Tecla == 44 || Tecla == 32 || Tecla == 45 || Tecla == 47 || Tecla == 8 || Tecla == 40 || Tecla == 41)
    	event.returnValue = true;
    else
    	event.returnValue = false;
  }
  else { // Somente letras
	  if (Tecla < 48 && Tecla > 57)
		event.returnValue = true;
	  else
		event.returnValue = false;   
   }
}

function NumericoPreco(){
	var Tecla = window.event.keyCode;
	event.cancelBubble = true;

	// Somente numeros, ponto e virgula
	if ((Tecla > 47 && Tecla < 58) || Tecla == 44 || Tecla == 8 || Tecla == 46)
		event.returnValue = true;
	else
		event.returnValue = false;
}

function SomenteNumerico(){
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;

  if (Tecla > 47 && Tecla < 58)
  	event.returnValue = true;
  else
  	event.returnValue = false;
}

function CapturaEventoNetscape(){
	if (navigator.appName == "Netscape"){
		document.captureEvents(Event.KEYPRESS);
		document.onkeypress = Resto;
		return true;
	}
}

function DesligaCapturaNetscape(){
	if (navigator.appName == "Netscape")
		document.releaseEvents(Event.KEYPRESS);
	return true;
}

function comparaCampos(campo1,campo2,bmsg,msg){
	if ((campo1.value) == campo2.value){
		return true;
	}
	else {
		if(bmsg) alert(msg);
		campo2.focus();
		return false;
	}	
}

function Radio(objeto){
	var radio = objeto;
	cont = objeto.length;
	vx = 0;

	if (!isNaN(cont)){
		for (i=0; i<cont; i++){                        
			if (radio[i].checked){
				vx = vx + 1;
				break;  	
			}
		}
		if (vx == 0){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		if(radio.checked){
			return false;
		}
		else{
			return true;
		}
	}
}

// 0 - qualquer
// 1 - numerico
// 2 - email
// 3 - CheckBox
// 4 - data Tipo dd/mm/aaaa
// 5 - radio
// 6 - CPF
// 7 - CNPJ
// 8 - CPF/CNPJ
// 9 - inscrição estadual
function RecordForm(Vcampo,Vobrigatorio,Vtipo,VnomeCampo,vNomeCampoHidden,vTamanhoCampo){
	this.campo = Vcampo;
	this.obrigatorio = Vobrigatorio;
	this.tipo = Vtipo;
	this.nomeCampo = VnomeCampo;
	this.nomeCampoHidden = vNomeCampoHidden;
	this.tamanhoCampo = vTamanhoCampo;
}


function formataHidden(campo1,campo2){
	var campoNormal = pegaObjeto(campo1);
	var campoHidden = pegaObjeto(campo2);
	var tamOjeto = campoNormal.length;
	var vString = '';

	if (!isNaN(tamOjeto)){
		for (i=0; i<tamOjeto; i++){
			if (campoNormal[i].checked){
				vString += campoNormal[i].value + ',';
			}
		}
		campoHidden.value = vString.substr(0,(vString.length - 1));
	}
	else{
		vString = campoNormal.value
		campoHidden.value = vString;
	}
}


function resetaCheck(obj){
	var vResetaCheck = findObj(obj);

	for (var i=0;i<vResetaCheck.length;i++){
		vResetaCheck[i].checked = false;
	}
}

function Verifica_Email(emailStr){
	var checkTLD=0;
	var knownDomsPat=/ ^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null){
		return false; 
	} 
	var user=matchArray[1]; 
	var domain=matchArray[2]; 
	for(i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			return false; 
		} 
	} 
	for(i=0; i<domain.length; i++){
		if (domain.charCodeAt(i)>127){
			return false; 
		}
	} 
	if (user.match(userPat)==null){
		return false; 
	} 
	var IPArray=domain.match(ipDomainPat); 
	if (IPArray!=null){
		for(var i=1;i<=4;i++){
			if (IPArray>255){
				return false; 
			} 
		} 
		return true; 
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for(i=0;i<len;i++){
		if (domArr[i].search(atomPat)==-1){
			return false;
		} 
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		return false; 

	if (len<2){
		return false; 
	}

	return true;
}

function validaForm(arrayForm,theForm,campo1,campo2,bmsg,msg){
	if (isObject(campo1) || isObject(campo2)){
		if (campo1.value != '' && campo2.value != ''){
			return comparaCampos(campo1,campo2,bmsg,msg);
		}
	}

	var obj;
	var errMsg = 'Os seguintes erros foram detectados:\n\n';
	var err = 0;
	var tip = -1;
	var objErr = '';

	for(var i=0;i<arrayForm.length;i++){

	  if (arrayForm[i].campo != ''){
		if (isObject(theForm))
			obj = document[theForm.name][arrayForm[i].campo];
		else
			obj = findObj(arrayForm[i].campo);

		if (arrayForm[i].obrigatorio == 1){
			if ((arrayForm[i].tipo != 3 && arrayForm[i].tipo != 5) && (obj.value == '')){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' é um campo obrigatório.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if ((arrayForm[i].tipo != 3 && arrayForm[i].tipo != 5) && (((obj.value.indexOf('<div') != -1) || (obj.value.indexOf('<DIV') != -1)) || ((obj.value.indexOf('<LAYER') != -1) || (obj.value.indexOf('<layer') != -1)))){
				errMsg = errMsg + '- Conteúdo do campo ' + arrayForm[i].nomeCampo + ' é impróprio.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if ((arrayForm[i].tipo != 3 && arrayForm[i].tipo != 5) && obj.value.length < arrayForm[i].tamanhoCampo){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa ter ' + arrayForm[i].tamanhoCampo + ' caracteres ou mais.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 1 && isNaN(obj.value)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor numérico válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 2 && !Verifica_Email(obj.value)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 3 && Radio(obj)){
				errMsg = errMsg + '- precisa escolher um(a) ' + arrayForm[i].nomeCampo + '.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 4 && !impValData(obj, 2)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter uma data válida.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 5 && Radio(obj)){
				errMsg = errMsg + '- precisa escolher um(a) ' + arrayForm[i].nomeCampo + '.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 6 && !impValCPFCGC(obj,false,1)){ // CPF				
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 7 && !impValCPFCGC(obj,false,2)){ // CNPJ
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 8 && !impValCPFCGC(obj,false,0)){ // CPF/CNPJ
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == '') tip = arrayForm[i].tipo
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 9 && !impValIERS(obj,false)){ // Inscrição Estadual
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}
		}
	  	else if (obj.value != '' && obj.value != null){
			if (((obj.value.indexOf('<div') != -1) || (obj.value.indexOf('<DIV') != -1)) || ((obj.value.indexOf('<LAYER') != -1) || (obj.value.indexOf('<layer') != -1))){
				errMsg = errMsg + '- Conteúdo do campo ' + arrayForm[i].nomeCampo + ' é impróprio.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}
		
			if (arrayForm[i].tipo == 1 && isNaN(obj.value)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor numérico válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if ((arrayForm[i].tipo != 3 && arrayForm[i].tipo != 5) && obj.value.length < arrayForm[i].tamanhoCampo){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa ter ' + arrayForm[i].tamanhoCampo + ' caracteres ou mais.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 2 && !Verifica_Email(obj.value)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 3 && Radio(obj)){
				errMsg = errMsg + '- precisa escolher um(a) ' + arrayForm[i].nomeCampo + '.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 4 && !impValData(obj, 2)){
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter uma data válida.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}
			
			else if (arrayForm[i].tipo == 5 && Radio(obj)){
				errMsg = errMsg + '- precisa escolher um(a) ' + arrayForm[i].nomeCampo + '.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 6 && !impValCPFCGC(obj,false,1)){ // CPF				
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 7 && !impValCPFCGC(obj,false,2)){ // CNPJ
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 8 && !impValCPFCGC(obj,false,0)){ // CPF/CNPJ
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}

			else if (arrayForm[i].tipo == 9 && !impValIERS(obj,false)){ // Inscrição Estadual
				errMsg = errMsg + '- ' + arrayForm[i].nomeCampo + ' precisa conter um valor válido.\n';
				err = 1;
				if (tip == -1) tip = arrayForm[i].tipo;
				if (objErr == '') objErr = obj;
			}		
	  	}		
	  }	
	  // arrayForm[i].campo sem campo definido
	  else {
		  alert('Erro desconhecido!\n');
		  return false;
	  }
	}
	
	if (err == 1){
		alert(errMsg);
 		if((tip != -1) && (tip != 3) && (tip != 5)) objErr.focus();
		return false;
	}
	else {
		// Passa os campos de checkBox para hiddenFields
		for(var i=0; i<arrayForm.length; i++){
			if (arrayForm[i].tipo == 3 && (arrayForm[i].nomeCampoHidden != '' && arrayForm[i].nomeCampoHidden != null)){
				formataHidden(arrayForm[i].campo,arrayForm[i].nomeCampoHidden);
				//resetaCheck(arrayForm[i].campo);
			}
		}
		return true;
	}
}
