function selecionar_tudo(){
   for (i=0;i<$('df2').elements.length;i++)
      if($('df2').elements[i].className == 'cb_excluir' && $('df2').elements[i].type == "checkbox")
         $('df2').elements[i].checked=1
} 


function deselecionar_tudo(){
   for (i=0;i<$('df2').elements.length;i++)
      if($('df2').elements[i].className == 'cb_excluir' && $('df2').elements[i].type == "checkbox")
         $('df2').elements[i].checked=0
} 


function validaSearch(form){

	var busca = form.busca.value;

	if(busca == ''){

		alert('Digite um termo a ser buscado');

		form.busca.focus();

		return false;

	}

	return true;

}

function submitSearch(form){

	var busca = form.busca.value;

	window.location.href=base_url + 'busca/' + escape(busca);

}

function sumbitFrmAgenda(form){

	var url = 'agenda/';

	url += form.ano.options[form.ano.selectedIndex].value;

	url += '/'+form.mes.options[form.mes.selectedIndex].value;

	window.location.href = url;

	return false;

}

function AbrePagina(Foto, tamx, tamy) {

	window.open(Foto,"","resizable=no,toolbar=no,status=no,menubar=no,scrollbars=no,width=" + tamx + ",height=" + tamy)

}

function addFoto(galeria_id, id){

	var w = 400;

	var h = 300;

	var url = (id) ? "admin/galerias/fotos_crud/"+galeria_id+"/exibir/"+id : "admin/galerias/fotos_crud/"+galeria_id+"/criar/";

	var win = new Window({className: "alphacube",

						  width:w,

						  height:h,

						  zIndex: 100,

						  resizable: true,

						  title: "Editar/Inserir Foto",

						  draggable:true,

						  wiredDrag: true,

						  url: url,

						  destroyOnClose: true

						  })

	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});

	win.showCenter();

	return false;

}



function reloadIframe(galeria_id){

	//parent.fotos.location.href = "admin/galerias/fotos/"+galeria_id;

	parent.fotos.location.reload();

}



function checkAll(obj, form){

	var inputs = form.getElementsByTagName('input');

	var status = (obj.checked) ? 'checked' : false ;

	for(i=0; i<inputs.length; i++){

		if(inputs[i].type == 'checkbox' && inputs[i].name != obj.name){

			inputs[i].checked = status;

		}

	}

}


function showPage(id){

	var w = window.screen.availWidth-100;
	var h = window.screen.availHeight-250;
	var url = (id) ? "admin/conteudo/page/exibir/"+id : "admin/conteudo/page/criar/" ;
	var win = new Window({className: "alphacube",

						  width:w,

						  height:h,

						  zIndex: 100,

						  resizable: true,

						  title: "Editar conte&uacute;do",

						  draggable:true,

						  wiredDrag: true,

						  url: url,

						  destroyOnClose: true

						  })

	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});

	win.showCenter();

	return false;

}

function showFoto(){

	var w = 400;

	var h = 70;

	var url =  "perfil/add_foto/";

	var win = new Window({className: "alphacube",

						  width:w,
						  height:h,
						  zIndex: 100,
						  resizable: true,
						  title: "Adicionar foto",
						  draggable:true,
						  wiredDrag: true,
						  url: url,
						  destroyOnClose: true

						  })

	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});

	win.showCenter();

	return false;

}



function showText(id){

	var w = window.screen.availWidth-100;

	var h = window.screen.availHeight-250;

	var url = (id) ? "admin/texto/carrega/"+id : "admin/conteudo/page/criar/" ;

	var win = new Window({className: "alphacube",

						  width:w,

						  height:h,

						  zIndex: 100,

						  resizable: true,

						  title: "Editar conte&uacute;do",

						  draggable:true,

						  wiredDrag: true,

						  url: url,

						  destroyOnClose: true

						  })

	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});

	win.showCenter();

	return false;

}



/* Popula o combo de cidades de acordo com o combo de estado */

function ckbSubSecoes(id){

	if(id > 0 && !isNaN(id)){

		var url = 'admin/functions/populaSubSecoes/'+id;

		var pars = '';

		var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: montaCkbSubSecoes });

	} else {

		$('subsecao_id').options.length = 0;

		$('subsecao_id').selectedIndex = 0;

		$('subsecao_id').options[0] = new Option('Selecione a seo', '');

	}

}

function montaCkbSubSecoes(request){

	itens = request.responseXML.getElementsByTagName("subsecoes");

	itens = request.responseXML.getElementsByTagName("item");

	if(itens.length > 0){

		$('subsecao_id').options.length = 0;

	    $('subsecao_id').selectedIndex = 0;

		for(i=0; i<itens.length; i++){

			var nome = pegaValor(itens[i].getElementsByTagName('titulo')[0]);

			var id = pegaValor(itens[i].getElementsByTagName('id')[0]);

			if(id == '' || id == null || id == 'null'){

				id = '';

			}

			$('subsecao_id').options[i] = new Option(nome, id);

		}

	} else {

		$('subsecao_id').options.length = 0;

	    $('subsecao_id').selectedIndex = 0;

		$('subsecao_id').options[0] = new Option('Esta secao possui subsecoes', '');

	}

}



function pegaValor(no){

    if(no.childNodes.length>0){

            return no.firstChild.nodeValue; //Tem filho

      } else {

            try{

                  return no.nodeValue;

            } catch (e) {

            return "";

        }

      }

}





/**

 * Funo que formata um campo do formulrio de

 * acordo com a mscara informada...

 *

 * Parmetros:

 *  => objForm (o Objeto Form);

 *  => strField (string contendo o nome do textbox);

 *  => sMask (mascara que define o formato que o dado ser apresentado,

 *            usando o algarismo "9" para definir nmeros e o smbolo "!" para

 *            qualquer caracter...

 *  => evtKeyPress (evento);

 *

 * Uso..: <input type="textbox" name="xxx"

 * onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">

 *

 * Observao: As mscaras podem ser representadas como os exemplos abaixo:

 * CEP -> 99.999-999

 * CPF -> 999.999.999-99

 * RG -> 99.999.999-9

 * CNPJ -> 99.999.999/9999-99

 * Data -> 99/99/9999

 * Tel Resid -> (99) 999-9999

 * Tel Cel -> (99) 9999-9999

 * Processo -> 99.999999999/999-99

 * Inscrio Estadual -> 999.999.999-9999

 * C/C -> 999999-!

 * E por a vai...

 **/

function format(field, sMask, evtKeyPress) {



   var i;

   var nCount;

   var sValue;

   var fldLen;

   var mskLen;

   var bolMask;

   var sCod;

   var nTecla;



   if(document.all) { // Internet Explorer

      nTecla = evtKeyPress.keyCode;

   }

   else

   if(document.layers) { // Nestcape

      nTecla = evtKeyPress.which;

   }



   sValue = field.value;



   // Limpa todos os caracteres de formatao que

   // j estiverem no campo.

   sValue = sValue.toString().replace( "-", "" );

   sValue = sValue.toString().replace( "-", "" );

   sValue = sValue.toString().replace( ".", "" );

   sValue = sValue.toString().replace( ".", "" );

   sValue = sValue.toString().replace( "/", "" );

   sValue = sValue.toString().replace( "/", "" );

   sValue = sValue.toString().replace( "(", "" );

   sValue = sValue.toString().replace( "(", "" );

   sValue = sValue.toString().replace( ")", "" );

   sValue = sValue.toString().replace( ")", "" );

   sValue = sValue.toString().replace( " ", "" );

   sValue = sValue.toString().replace( " ", "" );



   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) == " "))



       if (bolMask)

	   {  sCod += sMask.charAt(i);

          mskLen++;

	   }

       else {

         sCod += sValue.charAt(nCount);

         nCount++;

       }

       i++;

   }



   field.value = sCod;

   if (nTecla != 9 && nTecla != 8 && nTecla != 46)  {

       if (sMask.charAt(i-1) == "9")  // apenas nmeros...

	   {   return ((nTecla > 47) && (nTecla < 58)); // nmeros de 0 a 9

	   }

       else { // qualquer caracter...

         return true;

       }

   }

   else {

       return true;

   }

}



/**

 *

 */

function soNumero(event){

	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	var caract = new RegExp(/^[0-9]+$/i);

	var caract = caract.test(String.fromCharCode(keyCode));



    if (keyCode != 9 && keyCode != 8 && keyCode != 46) // backspace

	if(!caract){

		keyCode=0;

		return false;

	}

}



/**

 *

 */

function mascaraMoeda(cur,len) {

	n='__0123456789';

	d=cur.value;

	l=d.length;

	r='';



	if (l > 0)

	{   z = d.substr(0,l-1);

		s = '';

		a = 2;



		for (i=0; i < l; i++)

		{

			c = d.charAt(i);

			if (n.indexOf(c) > a)

			{   a=1;

				s+=c;

			}

		}



		l = s.length;

		t = len-1;



		if (l > t)

		{   l = t;

			s = s.substr(0,t);

		}



		if (l > 2)

		{   r = s.substr(0,l-2)+','+s.substr(l-2,2);

		}

		else

		{   if (l == 2)

			{	 r='0, '+s;

			}

			else

			{  if (l == 1)

				{   r = '0,0'+s;

				}

			}

		}



		if (r == '')

		{   r = '0,00';

		}

		else

		{   l = r.length;

			if (l > 6)

			{   j  = l%3;

				w  = r.substr(0,j);

				wa = r.substr(j,l-j-6);

				wb = r.substr(l-6,6);

				if (j > 0)

				{   w += '.';

				}

				k = (l-j)/3-2;



				for (i=0; i < k; i++)

				{	w += wa.substr(i*3,3)+'.';

				}



				r = w+wb;

			}

		}

	}



	if (r.length <= len)

	{   cur.value=r;

	}

	else

	{   cur.value=z;

	}



	return 'ok';

}


/*	-------------------------------------------------
	VALIDACAO DE CPNJ
	-------------------------------------------------*/
function validacnpj( c ) {

     var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj = c.value.replace(/\D+/g, '');
     digitos_iguais = 1;
    if (cnpj.length != 14)
            {
                 alert('CNPJ invalido');
                 c.focus();
                 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))
{
                 alert('CNPJ invalido');
                 c.focus();
                 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)){
                 alert('CNPJ invalido');
                 c.focus();
                 return false;
                 }
           else {
     // alert('CNPJ  OK !');
            return true;
            }
           }
     else{
           alert('CNPJ invalido');
           c.focus();
           return false;
           }
     } 


/*	-------------------------------------------------
	VALIDACAO DE CPF
	-------------------------------------------------*/
	
function validacpf(campo) {
var cpf = campo.value.replace(/\D/g, "");
if(cpf == "")
return true;
dig1 = 0; dig2 = 0; som1 = 0; som2 = 0; resto = 0;
calc = 0;
for (i = 1, k = 10; i < cpf.length -1; i++, k--) {
som1 += k * parseInt(cpf.substring(i - 1, i));
som2 += ((k + 1) * parseInt(cpf.substring(i - 1, i)));
}
resto = som1 % 11;
if (resto < 2)
dig1 = 0;
else
dig1 = 11 - resto;
som2 += 2 * dig1;
resto = som2 % 11;
if (resto < 2)
dig2 = 0;
else
dig2 = 11 - resto;
digCpf = cpf.substr(cpf.length - 2);
digCal = String(dig1).concat(String(dig2));
if(digCal != digCpf) {
alert('Numero de CPF invalido!');
campo.focus();
return false;
}
return true;
} 



function iframeAutoHeight(quem,heu){

    //by Micox - elmicox.blogspot.com - elmicox.com - webly.com.br

    if(navigator.appName.indexOf("Internet Explorer")>-1){ //ie sucks

        var func_temp = function(){

            var val_temp = quem.contentWindow.document.body.scrollHeight + 5

            quem.style.height = val_temp + "px";

            //alert(val_temp)

	}

        setTimeout(function() { func_temp() },100) //ie sucks

    }else{

        var val = quem.contentWindow.document.body.parentNode.offsetHeight + 5

        quem.style.height= val + "px";

    }

}
// Incio do cdigo de Aumentar/ Diminuir a letra
 
// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar
 
var tagAlvo = new Array('p'); //pega todas as tags p//
 
// Especificando os possveis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px','16px' );
var tamanhoInicial = 2;
 
function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) tamanho = 0;
  if ( tamanho > 6 ) tamanho = 6;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
  
  selecionados.style.fontSize = tamanhos[ tamanho ];
  
  for ( i = 0; i < tagAlvo.length; i++ ){
    tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
    for ( j = 0; j < tagsAlvo.length; j++ ) tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
  }
}
// Fim do cdigo de Aumentar/ Diminuir a letra
 function number_format( number, decimals, dec_point, thousands_sep ) {
    // %        nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

function str_replace(chars,repls,str) {
	if (chars instanceof Array) {
		var arrString = new Array();
		for (i=0; i<chars.length; i++) {
			 var count = i-1;
			 if (i>0) {
				 arrString.push(arrString[count].replace(chars[i],repls[i]));
			 } else {
				 arrString.push(str.replace(chars[i],repls[i]));
			 }
		}
		string = arrString.pop();
	} else {
		string = str.replace(chars,repls);
	}
	return string;
}
documentall = document.all;   
/*  
* função para formatação de valores monetários retirada de  
* [url]http://jonasgalvez.com/br/blog/2003-08/egocentrismo[/url]  
*/  
function formataValor(campo) {
	campo.value = filtraCampo(campo);
	vr = campo.value;
	tam = vr.length;

	if ( tam <= 2 ){ 
 		campo.value = vr ; }
 	if ( (tam > 2) && (tam <= 5) ){
 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 6) && (tam <= 8) ){
 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 9) && (tam <= 11) ){
 		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 12) && (tam <= 14) ){
 		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 	if ( (tam >= 15) && (tam <= 18) ){
 		campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
 		
}
function filtraCampo(campo){
	var s = "";
	var cp = "";
	vr = campo.value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {  
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	campo.value = s;
	return cp = campo.value
}


function validaremail(email) {
    var arroba = email.indexOf("@");
    var arrobaprimeiro = email.lastIndexOf(".");
    var space = email.indexOf(" ");

    if ((arroba != -1) && (arroba != 0) && (arrobaprimeiro != -1) && (arrobaprimeiro > arroba + 1) && (arrobaprimeiro < email.length -1) && (space == -1) ) {
        alert ("E-mail foi digitado correto.");
        return true;
    } else {
        alert("E-mail inválido.")
        return false;
    }
}