/**************************************************************************
 @CLASSTITLE:		jetFuncoes
 @CREATOR:			Jose Eduardo Vicentini
 @CREATEDON:		2008-03-12 Brazil
 @CDESCRIPTION:		Funcoes Padrao
 @VERSION:			0.1
****************************************************************************/


/**************************************************************************
 @TITLE:			String.Format
 @CDESCRIPTION:		prototype da função semelhante ao C# String.Format
 @EXAMPLE:			var str = String.format("This is a {0} string using the {1} method.","formatted","static");
 					var str = "This is a {0} string using the {1} method.".format("formatted","inline");
 ****************************************************************************/
function _StringFormatInline(){var txt = this;for(var i=0;i<arguments.length;i++){var exp = new RegExp('\\{' + (i) + '\\}','gm');txt = txt.replace(exp,arguments[i]);}return txt;}
function _StringFormatStatic(){for(var i=1;i<arguments.length;i++){var exp = new RegExp('\\{' + (i-1) + '\\}','gm');arguments[0] = arguments[0].replace(exp,arguments[i]);}return arguments[0];}
if(!String.prototype.format){String.prototype.format = _StringFormatInline;}
if(!String.format){String.format = _StringFormatStatic;}

/**************************************************************************
 @TITLE:			Prototype replaceAll
 @CDESCRIPTION:		
****************************************************************************/
String.prototype.replaceAll = function(de, para){var str = this;var pos = str.indexOf(de);while (pos > -1){str = str.replace(de, para);pos = str.indexOf(de);}return (str);}

/**************************************************************************
 @TITLE:			Prototype trim
 @CDESCRIPTION:		// Substitúi os espaços vazios no inicio e no fim da string por vazio.
****************************************************************************/
String.prototype.trim = function (){ var str = this; return str.replace(/^\s+|\s+$/g, '');}

/**************************************************************************
 @TITLE:			Prototype Currency
 @CDESCRIPTION:		// Substitúi os espaços vazios no inicio e no fim da string por vazio.
****************************************************************************/
String.prototype.StrToNumber = function (){ var str = this; var Reg = /^[-+]?\d*\.?\d*\,?\d*$/; if (Reg.test(str)) { return str.replaceAll(".","").replaceAll(",","."); } else { return 0; }}
String.prototype.ToVal = function () { return ConvertStrToValor(this, 2); }
String.prototype.ToCurrency = function () { return FormataNumberJsToBr(this, 2); }


/**************************************************************************
 KEY enter Like TAB()
 Necessita da lib. JQUERY
****************************************************************************/
var textboxes;
function EnterLikeTab()
{
    // get only input tags with class data-entry
    textboxes = $("input");
     // now we check to see which browser is being used
    if ($.browser.mozilla) {
        $(textboxes).keypress (checkForEnter);
    } else {
        $(textboxes).keydown (checkForEnter);
    }
}
//----------------------------//
function checkForEnter(event) {
    if (event.keyCode == 13) {
        currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 1];
            nextBox.focus();
            nextBox.select();
        }
        event.preventDefault();
        return false;
    }
}

/**************************************************************************
 @CDESCRIPTION:		retorna o objeto do componente html
 @PARAM:			name: Nome do componente
 @RETURN:			.obj, .style
 @EXAMPLE:			dv = new getObjStyle(div1); dv.obj.innerHtml = 'example'; img.style.font = "verdana";
****************************************************************************/
function getObjStyle(name)
{
	if (document.getElementById)
	{
		this.obj = document.getElementById(name);
		this.style = (this.obj != null) ? this.style = document.getElementById(name).style : null;
	}
	else if (document.all)
		{
			this.obj = document.all[name];
			if (this.obj != null) 	this.style = document.all[name].style;
		}
		else if (document.layers)
			{
				this.obj = document.layers[name];
				if (this.obj != null) 	this.style = document.layers[name];
			}
}

/**************************************************************************
 @CDESCRIPTION:		Funcao que Desabilita todos os Botaoes de Submit quando o Form é submetido
 @PARAM:			theform : document.form
 @EXAMPLE:			<form method="post" onsubmit="submitonce(this)">
****************************************************************************/
function submitonce(theform){
	if (document.all||document.getElementById){
		for (i=0;i<theform.length;i++){
			var a=theform.elements[i];
			if (a.tagName != 'FIELDSET')
				if(a.type.toLowerCase()=="submit"||a.type.toLowerCase()=="reset"||a.type.toLowerCase()=="button")
					a.disabled = true;
		}
	}
}

/**************************************************************************
 @CDESCRIPTION:		Formata o Campo <input>
 @PARAM:			src: Campo // sMask: Mascara // evtKeyPress: event do keypress
 @EXAMPLE:			 <INPUT name="txtCNPJ" onKeyPress="return txtBoxFormat(this, '99.999.999/9999-99', event);">
****************************************************************************/
function txtBoxFormat(src, sMask, evtKeyPress) { 

	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla; 
	
	if(document.all) {  nTecla = evtKeyPress.keyCode;  }
	   else if(document.layers) {  nTecla = evtKeyPress.which;  }
	else {  nTecla = evtKeyPress.which;   }
	
	sValue = src.value; 
	
	// Limpa todos os caracteres de formatação que já estiverem no campo.
	sValue = replace( sValue, "-", "" ); 
	sValue = replace( sValue, ".", "" ); 
	sValue = replace( sValue, "/", "" ); 
	sValue = replace( sValue, "(", "" ); 
	sValue = replace( sValue, ")", "" ); 
	sValue = replace( sValue, " ", "" ); 
	sValue = replace( sValue, ":", "" ); 
	fldLen = sValue.length; 
	mskLen = sMask.length; 
	
	i = 0; 
	nCount = 0; 
	sCod = ""; 
	mskLen = fldLen;
	
	while (i <= mskLen) { 
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/")) 
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ")) 
		bolMask = bolMask || ((sMask.charAt(i) == ":")) 		
		
		if (bolMask) 
		{ 
		  sCod += sMask.charAt(i); 
		  mskLen++;
		} 
		else 
		{ 
		  sCod += sValue.charAt(nCount); 
		  nCount++; 
		} 
		i++; 
	} 
	src.value = sCod; 

	if (nTecla != 8) { // backspace 
		if (sMask.charAt(i-1) == "9")  // apenas números...
		{ 
			return ((nTecla > 47) && (nTecla < 58));  // números de 0 a 9
		} 
		else 
		{ // qualquer caracter... 
			return true; 
		} 
	} 
	else 
	{ 
		return true; 
	} 
} 
/**************************************************************************
 @CDESCRIPTION:		Replace de variaveis - Replace all Old string on String Base to new string
 @PARAM:			S : string Base // strOld: String Old to replace // strNew: new string
 @RETURN:			string replaced
****************************************************************************/
function replace(strBase, strOld, strNew)
{
	var temp = "";
	var digito = "";
	for (var i=0; i<strBase.length; i++)
	{
		digito = strBase.charAt(i);
		if (strOld.indexOf(digito)>=0)
		   {temp=temp+strNew}
		else{temp=temp+digito}
	}
	return temp
}


/**************************************************************************
 @CDESCRIPTION:		ConvertStrToValor - Convert um text string em um Valor
 @PARAM:			valor: Valor // casas: Casas Decimais
 @RETURN:			Float: returna o valor arredondado
****************************************************************************/
function ConvertStrToValor(Numero, Decimals){
	var strNumero = ''+Numero;
	var dblNumero = 0;
	if (strNumero.indexOf(",") >= 0) 
		strNumero = replace(Numero,".","");
		
	strNumero = replace(strNumero,",",".");
	dblNumero = Arredonda(strNumero,Decimals)
	return dblNumero
}

/**************************************************************************
 @CDESCRIPTION:		funcao para arredondar campos x numero de casas decimais
 @PARAM:			valor: Valor // casas: Casas Decimais
 @RETURN:			Float: returna o valor arredondado
****************************************************************************/
function Arredonda( valor , casas ){
   return Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
}


/**************************************************************************
 @CDESCRIPTION:		Limpa a String Deixando somente Numeros
 @PARAM:			S: String
 @RETURN:			Float: returna o valor arredondado
****************************************************************************/
function limpa_string(S)
{
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
/**************************************************************************
 @CDESCRIPTION:		Verifica se a string tem somente valores iguais Ex: '11111', '222222'
 @PARAM:			S: String
 @RETURN:			Bolean - true se '111111' false se '12111111'
****************************************************************************/
function DigitosIguais(value)
{
	var cont = 1;
    s = limpa_string(value);
    for (var i = 1; i < s.length; i++){
	     if (s.charAt(i) == s.charAt((i-1))){
	        cont = cont + 1; 
         }
    }
    if (cont == s.length){
       return true;
    } 
    return false;
}

/**************************************************************************
 @CDESCRIPTION:		Funcao que valida CPF
 @PARAM:			S: String
 @RETURN:			Boolean: returna true ou false se CPF correto
****************************************************************************/
function valida_CPF(value)
{
	var i, s;
	s = limpa_string(value);
	if (DigitosIguais(s)) return false;
	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) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1) 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) return false;
    return true;
}

/**************************************************************************
 @CDESCRIPTION:		Funcao que valida CNPJ
 @PARAM:			S: String
 @RETURN:			Boolean: returna true ou false se CNPJ correto
****************************************************************************/
function valida_CNPJ(value)
{
	var i, s;
	s = limpa_string(value);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++) d1 += c.charAt(11-i)*(2+(i % 8));
	if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1) return false;
	d1 *= 2;
	for (i = 0; i < 12; i++) d1 += c.charAt(11-i)*(2+((i+1) % 8));
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) return false;
	return true;
}


/**************************************************************************
 @CDESCRIPTION:		Funcao que valida o email
 @PARAM:			S: String
 @RETURN:			Boolean: returna true ou false se e-mail correto
****************************************************************************/
function ValidaEmail(value)
{
	var filter=/^.+@.+\..{2,3}$/
	return (filter.test(value))
}

/**************************************************************************
 @CDESCRIPTION:		Limita a Quantidade de Caracteres de uma Textarea
 @DEPENDETS:		Dependente das Funcoes 'restrictinput' e 'countlimit'
 @PARAM:			theform: Form   // thelimit: Limite max de caracters
 @EXAMPLE:			<script>displaylimit("document.form.txtObservacao",500)</script>
****************************************************************************/
var ns6=document.getElementById&&!document.all
function restrictinput(maxlength,e,placeholder){
	if (window.event&&event.srcElement.value.length>=maxlength)
		return false
	else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
			var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
			if (pressedkey.test(String.fromCharCode(e.which)))
				e.stopPropagation()
			}
}

function countlimit(maxlength,e,placeholder){
	var theform=eval(placeholder)
	var lengthleft=maxlength-theform.value.length
	var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
	if (window.event||e.target&&e.target==eval(placeholder)){
		if (lengthleft<0)
			theform.value=theform.value.substring(0,maxlength)
			placeholderobj.innerHTML=lengthleft
	}
}

function displaylimit(theform,thelimit){
	var campo= eval(theform)
	var atual = campo.value.length;
	var limit_text='<b><span id="'+theform.toString()+'">'+(thelimit-atual)+'</span></b> caracteres'
	if (document.all||ns6)
		document.write(limit_text)
		if (document.all){
			eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
			eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
		}
	else if (ns6){
		document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
		document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
	}
}
// end of displaylimit functions

/**************************************************************************
 @CDESCRIPTION:		Monta o script que inclue um FLASH
 @PARAM:			SwfName 	: Url do Arquivo 
 					width		: width
					height		: height
					id 			: 
					bgcolor		: Background Color
					xmlDataPath	: flashvars = XML
					wmode		: opaque (default) or transparent 
					cache		: Chache flash
 @EXAMPLE:			
****************************************************************************/
function jetFlash(SwfName, width, height, id, bgcolor, xmlDataPath, wmode, cache)
{
	var noCache = cache || cache == undefined ? "" : "?" + new Date();
	var wmode = wmode || wmode == undefined ? "opaque" : "transparent";
	
	var strHttps = (document.location.protocol);

	if (id==null) id = 'flash';
	str = '';
	str += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
	str += 'codebase="'+strHttps+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" ';
	str += 'width="'+width+'" height="'+height+'">';
	
	if 	(xmlDataPath!=null) str += '<param name="FlashVars" value="xmlDataPath='+xmlDataPath+'" />';
	if (bgcolor!=null) str += '<param name="bgcolor" value="'+bgcolor+'" />';	
	
	str += '<param name="movie" value="'+SwfName+'" />';				  
	str += '<param name="scale" value="noscale" />';	
	str += '<param name="quality" value="high" />';				  
	str += '<param name="wmode" value="'+ wmode +'" />';
	str += '<embed src="'+SwfName+'" id="'+id+'" ';	
	str += '				quality="high"  ';
	str += '				scale="noscale"  ';
	str += '				type="application/x-shockwave-flash"  ';
	str += '				width="'+width+'" height="'+height+'"  ';
	str += '				wmode="'+wmode+'" ';
	if 	(xmlDataPath!=null) str += 'flashvars="xmlDataPath='+xmlDataPath+'"  ';
	if (bgcolor!=null) str += 'bgcolor="'+bgcolor+'"  ';
	str += '				pluginspage="http://www.macromedia.com/go/getflashplayer" /> ';	
	str += '</embed>';
	str += '</object>';	

	
  	document.write(str);
}