// TRIM COMPLETO
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,"");
}
 
// TRIM A ESQUERDA
String.prototype.ltrim = function () {
    return this.replace(/^\s+/,"");
}
 
// TRIM A DIREITA
String.prototype.rtrim = function () {
    return this.replace(/\s+$/,"");
}

function verificarCampo(targetForm) {
	form = document.getElementById(targetForm);
	for (i=0; i<form.elements.length; i++) {
		if (form.elements.item(i).nodeName == 'INPUT') {
			if (form.elements.item(i).name == 'iERR') {
				return true;
			}
		}
	}
}


// CORREÇÃO DA TECLA ENTER PARA UTILIZAR NOS FORMULÁRIOS
function arrumaEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
			break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	}
	else
		return true;
}

// CODIFICA STRING PARA UTF-8
function utf8_encode ( string ) {
 
    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

// DECODIFICA STRING PARA UTF-8
function utf8_decode ( str_data ) {
 
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
 
    str_data += '';
 
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}

// CONFIRMAÇÃO DE EXCLUSÃO
function exclusao(id, titulo, pagina) {
	
	var str1 = "Deseja realmente excluir?\n";
	
		if (confirm(str1+titulo)) {
		location.href=pagina+".php?del="+id;}
}

// ABRIR PÁGINA EM DIV (NECESSÁRIO INCLUIR JQUERY.JS)

function abrePgDiv(pagina) {
	$("#content").load(pagina); 
};

function abrePgDiv_1(pagina, div) {
	$("#"+div+"").load(pagina); 
};

//TRANSIÇÃO DE IMAGENS
function roll(img_name, img_src) {
   document[img_name].src = img_src;
}

//RELÓGIO
function UR_Start() 
{
	UR_Nu = new Date;
	UR_Indhold = showFilled(UR_Nu.getHours()) + "<strong>:</strong>" + showFilled(UR_Nu.getMinutes());
	document.getElementById("ur").innerHTML = UR_Indhold;
	setTimeout("UR_Start()",1000);
}
function showFilled(Value) 
{
	return (Value > 9) ? "" + Value : "0" + Value;
}

//POSTAR PÁGINA
function post(pagina,form){
    with(document.getElementById(form)){
        method = 'POST';
        action = pagina;
		submit();
    }
    return;
}

//MASCARAS
function redireciona(caminho) {
	document.location = caminho;
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function dta(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function FormataMascara(e,src,mask) {
	if(window.event) { _TXT = e.keyCode; }
	else if(e.which) { _TXT = e.which; }
	if(_TXT > 47 && _TXT < 58) {
		var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
		if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); }
		return true; } else { if (_TXT != 8) { return false; }
	else { return true; }
	}
}

function leech(v){
	v=v.replace(/o/gi,"0")
	v=v.replace(/i/gi,"1")
	v=v.replace(/z/gi,"2")
	v=v.replace(/e/gi,"3")
	v=v.replace(/a/gi,"4")
	v=v.replace(/s/gi,"5")
	v=v.replace(/t/gi,"7")
	return v
}

function Formatadata(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	if (tecla != 8 && tecla != 8){
		if (tam > 0 && tam < 2)
		Campo.value = vr.substr(0, 2) ;
		if (tam > 2 && tam < 4)
		Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2);
		if (tam > 4 && tam < 7)
		Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4, 7);
	}
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

//PULAR CAMPOS COM ENTER
function autoTab(input, e)  {   
  var ind = 0;  
  var isNN = (navigator.appName.indexOf("Netscape")!=-1);  
  var keyCode = (isNN) ? e.which : e.keyCode;   
  var nKeyCode = e.keyCode;   
  if(keyCode == 13){   
    if (!isNN) {window.event.keyCode = 0;} // evitar o beep  
    ind = getIndex(input);  
    if (input.form[ind].type == 'textarea') {  
      return;  
    }  
    ind++;  
    input.form[ind].focus();   
    if (input.form[ind].type == 'text') {  
      input.form[ind].select();   
    }  
  }   
  
  function getIndex(input) {   
    var index = -1, i = 0, found = false;   
    while (i < input.form.length && index == -1)   
      if (input.form[i] == input) {  
        index = i;  
          if (i < (input.form.length -1)) {  
           if (input.form[i+1].type == 'hidden') {  
       index++;   
     }  
     if (input.form[i+1].type == 'button' && input.form[i+1].id == 'tabstopfalse') {  
       index++;   
     }  
   }  
      }  
      else   
   i++;   
    return index;   
  }  
}

//ALTERAR FUNDO DOS TITULOS DAS NOTÍCIAS (ESPECÍFICO)
function alterarBkg(id,acao) {
	if (acao == 1) { 
		document.getElementById('n1'+id).style.background="url('images/fundos/noticias_2/Noticias_2_2.png') no-repeat"; 
		document.getElementById('n2'+id).style.background="url('images/fundos/noticias_2/Noticias_3_2.png') repeat-x"; 
	} else if (acao == 2) {
		document.getElementById('n1'+id).style.background="url('images/fundos/noticias_2/Noticias_2.png') no-repeat"; 
		document.getElementById('n2'+id).style.background="url('images/fundos/noticias_2/Noticias_3.png') repeat-x";
	}
}
//POPUP
function PopupCenter(pageURL, title,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}

// REDIMENSIONA ALTURA DO IFRAME AUTOMATICAMENTE
function iframeAutoHeight(quem,heu){
    
    if(navigator.appName.indexOf("Internet Explorer")>-1){ 
        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)  
    }else{
        var val = quem.contentWindow.document.body.parentNode.offsetHeight + 5
        quem.style.height= val + "px";
    }    
}


// CURSO - ETAPAS - VALIDACÃO
function incluirEtapas() {

	var dataInicio	= document.getElementById('cursoPeriodoEtapaInicial').value.trim();
	var dataFim		= document.getElementById('cursoPeriodoEtapaFinal').value.trim();
	var etapa		= document.getElementById('cursoEtapas').value.trim();
	var ok 			= 1;
	
	if (etapa == '') { 
		alert('Selecione uma Etapa');
		ok = 0;
	}
	
	if ( dataInicio == '' && dataFim != ''  ) {
		alert('Preencha a Data Inicial'); 
		ok = 0;

	}
	
	if ( dataInicio != '' ) {
		if ( dataInicio.length < 10 ) {
			alert('Data Inicial Inválida');
			ok = 0;
		}
	}
	
	if (dataFim != '') {
		if ( dataFim.length < 10 ) {
			alert('Data Final Inválida');
			ok = 0;
		}

	};

	if ( dataInicio.length == 10 && dataFim.length == 10 ) {
		if ( parseInt( dataFim.split( "/" )[2].toString() + dataFim.split( "/" )[1].toString() + dataFim.split( "/" )[0].toString() ) < parseInt( dataInicio.split( "/" )[2].toString() + dataInicio.split( "/" )[1].toString() + dataInicio.split( "/" )[0].toString() ) ) {
				alert('Data Final não pode ser menor que a Data Inicial'); 
				ok = 0;
		}
	}
	
	if (ok == 1) {
	
		validarDados('addEtapas', document.getElementById('cursoEtapas').value, 'validacao.php', document.getElementById('cursoPeriodoEtapaInicial').value+' '+document.getElementById('cursoPeriodoEtapaFinal').value, '', document.getElementById('etapaDescricao').value, '1'); 
		
		document.getElementById('cursoEtapas').value = ''; 
		document.getElementById('cursoPeriodoEtapaInicial').value = '';
		document.getElementById('cursoPeriodoEtapaFinal').value = '';
		document.getElementById('etapaDescricao').value = '';
	
	};
};

// VALIDAR URL
function validarURL(url){
    var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}

// NOTÍCIAS - VÍDEOS - VALIDACÃO
function incluirVideos(idSession, tipo) {

	var linkVideo	= document.getElementById('LinkVideo').value.trim();
	var descricao	= document.getElementById('DescVideo').value.trim();
	var ok 			= 1;
	
	if (linkVideo == '') { 
		alert('Preencha o Link');
		ok = 0;
	} else if (validarURL(linkVideo) == false) { 
		alert(utf8_decode('Link Inválido'));
		ok = 0;
	} else {	
		
		var tipoVideos = new Object();
		tipoVideos[1] = 'youtube';
		tipoVideos[2] = 'rpc';

		for (var i in tipoVideos){
			
			var reg = eval('/'+tipoVideos[i]+'/i');
			var ar = reg.exec(linkVideo);
			
			if (ar != null) {
				ok = 1;
				break;
			} else ok = 0;
		}

		if (ok == 0) alert(utf8_decode('Link Inválido'));
	};
		
	if (ok == 1) {
		
	var linkVideo = document.getElementById('LinkVideo').value;
	while(linkVideo.indexOf("&") >= 0) {		
		linkVideo = linkVideo.replace("&","\\eE\\");
	}
				
		validarDados('addVideos', linkVideo, 'validacao.php', document.getElementById('DescVideo').value, '', idSession, '1', tipo);
				
		document.getElementById('LinkVideo').value = ''; 
		document.getElementById('DescVideo').value = '';
	
	};
};


//DEFINE VALOR PARA O CAMPO DE E-MAIL
function valorCampoEmail(campo, tipo) {
	
	valor = document.getElementById(campo).value;
	
	if (tipo == 1) {
		if (valor == 'e-mail') {
			document.getElementById(campo).value = '';
		}
	}
	
	if (tipo == 2) {
		if (valor == '') {
			document.getElementById(campo).value = 'e-mail';
		}
	}
}