﻿//Retira caracteres HTML e altera o valor do campo.
//campo - campo a ser validado o valor.
//Exemplo: onblur="RetirarHtml(this);"
function RetirarHtml(campo) {
    valor = campo.value;
    valor = valor.replace(/<[^>]*>/g, "");
    campo.value = valor;
}



//FUNÇÃO DO MENU LATERAL  
$(function () {
    var niveis = location.pathname.toLowerCase().replace('_','-').split('/');
    var linksSuperior = $('#mainMenu ul li a');
    var linksLateral = $('#menuLateral ul li a');
    
     for (var i = 0; i < niveis.length; i++) {    
        for (var a = 0; a < linksSuperior.length; a++) {
            if (linksSuperior[a].id == niveis[i]) {
                $(linksSuperior[a]).addClass('marcadoTopo');
            }
            else if (niveis[i] == "index.aspx"){
                $(linksSuperior[0]).addClass('marcadoTopo');
            }
        }
    }    
    $(linksLateral).each(function(){
		var linkLateral = location.pathname.replace('/neogas/index/','');
        if($(this).attr("href") == linkLateral){
            $(this).addClass("latMarcado");
            return;
        }        
    });
   
});

//CARROSEL DE IMAGENS
$(function () {var indiceIndica = 0; var fotos = $("#trocaImgLadoDireito li, #trocaImgLadoEsquerdo li"); $("#trocaImgLadoDireito li:first, #trocaImgLadoEsquerdo li:first").css('display', 'block'); function trocaImagem(){ if (indiceIndica == (fotos.length - 1)) { $(fotos[fotos.length - 1]).hide(); indiceIndica = 0; $(fotos[indiceIndica]).show(); return; } $(fotos[indiceIndica]).hide(); indiceIndica++; $(fotos[indiceIndica]).show();} var timer = setInterval( trocaImagem, 5000); });

//CARROSEL DE IMAGENS BANNERS
$(function () {var indiceIndica = 0; var fotos = $("#trocaImgBanner li"); $("#trocaImgBanner li:first").css('display', 'block'); function trocaImagem(){ if (indiceIndica == (fotos.length - 1)) { $(fotos[fotos.length - 1]).hide(); indiceIndica = 0; $(fotos[indiceIndica]).show(); return; } $(fotos[indiceIndica]).hide(); indiceIndica++; $(fotos[indiceIndica]).show();} var timer = setInterval( trocaImagem, 5000); });

// EFEITO ZEBRA NA TABELA
$(document).ready(function(){$('table#tabelaInfo tbody tr:even').addClass('par');});

function showFlash(src, larg, alt, wmode) {
	
	var flash = '';
	flash += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+ larg +'" height="'+ alt +'">';
	flash += '<param name="movie" value="'+ src +'" />';
	flash += '<param name="allowScriptAccess" value="always" />';
	flash += '<param name="menu" value="false" />';	
	flash += '<param name="wmode" value="'+ wmode +'" />';	
	flash += '<embed src="'+ src +'" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" width="'+ larg +'" height="'+ alt +'" menu = "false" wmode = "'+ wmode +'"></embed>';
	flash += '</object>';	
	
	return flash;
	
}

/* SWFOBJECT
Versão alterada por Marlon Rogério (05/10)
- src, width e height são obrigatórios
- os demais parametros são opcionais
*/
function flash(src, id, width, height, flashVersion, flashVars, wmode, menu, scale) {
    var _flashVersion = (flashVersion == null) ? "8" : flashVersion;
    var _flashVars = (flashVars == null) ? "" : flashVars;
    var _wmode = (wmode == null) ? "transparent" : wmode;
    var _menu = (menu == null) ? "false" : menu;
    var _scale = (scale == null) ? "exactfit" : scale;

    var params = { menu: _menu, scale: _scale, wmode: _wmode };
    var attributes = { type: "application/x-shockwave-flash", quality: "high" };

    //chamada do flash arquivo swfobject.js
    swfobject.embedSWF(src, id, width, height, _flashVersion, _flashVars, "", params, attributes);
}

/* RESET PESQUISAR */
$(function(){
	$('#campoBusca').resetDefaultValue();
	$('#txtNovaBusca').resetDefaultValue();
});

jQuery.fn.resetDefaultValue = function() {
	function _clearDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == this.defaultValue ) { _$.val(''); }
	};
	function _resetDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == '' ) { _$.val(this.defaultValue); }
	};
	return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
}

// Pega o value do select
function trocaValText(sel){
    if (sel.selectedIndex == 0){
        sel.value = 0;
    } else {
		sel.options[sel.selectedIndex].value;
		window.open(sel.value);
    }
}

// highslide
/*
function openYouTube(opener) {
   return hs.htmlExpand(opener, { 
        objectType: 'iframe',
			width: 480,
			height: 385,
			allowSizeReduction: false,
			wrapperClassName: 'draggable-header no-footer', 
			preserveContent: false,
			objectLoadTime: 'after',
    });
}  

function slideShow()
{
	hs.addSlideshow({
		// slideshowGroup: 'group1',
		interval: 5000,
		repeat: false,
		useControls: true,
		fixedControls: true,
		overlayOptions: {
			opacity: .7,
			position: 'top center',
			hideOnMouseOut: true
		}
	});
	// Optional: a crossfade transition looks good with the slideshow
	hs.transitions = ['expand', 'crossfade'];
}
*/
$(document).ready(function(){
	if(jQuery().prettyPhoto) {
		//run plugin dependent code
		$("a[rel^='prettyPhoto']").prettyPhoto({
			animationSpeed:'slow',
			/* opacity: 0.80,  Value between 0 and 1 */
			/* show_title: true,  true/false */
			/* allow_resize: true,  Resize the photos bigger than viewport. true/false */
			/* default_width: 700, */
			/* default_height: 600, */
			/* counter_separator_label: '/',  The separator for the gallery counter 1 "of" 2 */
		    /* horizontal_padding: 20, The padding on each side of the picture */
			/* hideflash: false,  Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			/* wmode: 'opaque',  Set the flash wmode attribute */
			/* autoplay: true,  Automatically start videos: True/False */
			/* modal: false,  If set to true, only the close button will close the window */
			/* deeplinking: true,  Allow prettyPhoto to update the url to enable deeplinking. */
			/* overlay_gallery: true,  If set to true, a gallery will overlay the fullscreen image on mouse over */
			/* keyboard_shortcuts: true,  Set to false if you open forms inside prettyPhoto */
			/* changepicturecallback: function(){},  Called everytime an item is shown/changed */
			/* callback: function(){},  Called when prettyPhoto is closed */
			/* ie6_fallback: true, */

			theme:'facebook', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			slideshow:2000, 
			autoplay_slideshow: false
		});		
	}
});


function isVisible(obj){  //verifica se o elemento está visivel
	if(!obj.parentNode){return false;}
	while(obj.parentNode!=null){
		if(obj.style.display.toLowerCase()=='none' || obj.style.visibility.toLowerCase()=='hidden'){return false;}
		obj=obj.parentNode;
	}
	return true;
}

function checkEmail(valor){
	if(valor==''){return true;}
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){return (true);}
	return (false);
}

function checkdate(d,m,y)
{
	if(!IsNumeric(d) || !IsNumeric(m) || !IsNumeric(y) || d.length<2 || m.length<2 || y.length<4){return false;}
	var yl=1900; // least year to consider
	var ym=2500; // most year to consider
	if (m<1 || m>12) return(false);
	if (d<1 || d>31) return(false);
	if (y<yl || y>ym) return(false);
	if (m==4 || m==6 || m==9 || m==11)
	if (d==31) return(false);
	if (m==2)
	{
		var b=parseInt(y/4);
		if (isNaN(b)) return(false);
		if (d>29) return(false);
		if (d==29 && ((y/4)!=parseInt(y/4))) return(false);
	}
	return(true);
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

function isHour(value){
	if(value==''){alert('Favor digite uma hora válida.');return false;}
	var splitted=value.split(':');
	var hora=splitted[0];
	var minuto=splitted[1];
	if(!IsNumeric(hora) || !IsNumeric(minuto) || (hora==0 || hora>=24) || (minuto==0 || minuto>=60)){return false;}
	return true;
}

function hideValidateError() {
	if ($("#validateFormError")) {
		$("#validateFormError").hide("fast");
	}
}
function returnValidateError(element)
{
	if (document.getElementById('validateFormError')!=null)
	{
		$("#validateFormError").html("<p style=\"text-align:center; color:#990000; font-weight:bold;\">"+element.title+"</p>");
		$("#validateFormError").show('normal');
		element.focus();
	} else {
		$("#validateFormError").html("<p style=\"text-align:center; color:#990000; font-weight:bold;\">Atenção - Há campos necessarios em branco ou inválidos.</p>");
		element.focus();
	}
}

function validateForm(form){
	if(!form)
	{
		return false;
		}
	hideValidateError();
	var element,enviar=true;
	 for(var i=0;i<form.elements.length;i++){
		element=form.elements[i];
		if(element.className.indexOf('required')>=0){  //campo requerido
		  if(!isVisible(element)){continue;}
			if(element.type.toUpperCase()=='CHECKBOX'){  //se for um checkbox
				checkboxes=document.getElementsByName(element.name);
				for(var c=0;c<checkboxes.length;c++){
					if(checkboxes[c].checked){break;}
				}
				if(c<checkboxes.length){continue;}
				returnValidateError(element);
				return false;
			}
			if(element.value.length<=0){  //nao preenchido
				if(element.type.toUpperCase().indexOf('SELECT')>=0){
					returnValidateError(element);
				}else{
					if(!isVisible(element)){continue;}
					returnValidateError(element);
				}
				enviar=false;
				break;
			}
			if(element.type.toUpperCase()=='RADIO'){  //se for um checkbox
				radios=document.getElementsByName(element.name);
				for(var c=0;c<radios.length;c++){
					if(radios[c].checked){break;}
				}
				if(c<radios.length){continue;}
				returnValidateError(element);
				return false;
			}
		}
		if(element.className.indexOf('email')>=0){  //campo tipo email
			if(!checkEmail(element.value.trim())){
				returnValidateError(element);
				enviar=false;
				break;
				
			}
		}
		if(element.className.indexOf('hour')>=0){  //campo tipo hora HH:mm:ss
			if(!isHour(element.value.trim())){
				returnValidateError(element);
				enviar=false;
				break;
			}
		}
		if(element.className.indexOf('number')>=0){  //campo tipo numero
			if(!IsNumeric(element.value.trim())){
				returnValidateError(element);
				enviar=false;
				break;
			}
		}
		if(element.className.indexOf('cpf')>=0){  //campo tipo cpf
			if(!validarCPF(element.value.trim())){
				returnValidateError(element);
				enviar=false;
				break;
			}
		}
		if(element.className.indexOf('day')>=0){  //campo tipo dia
			if(!IsNumeric(element.value.trim())&&!isDay(element.value.trim())){
				returnValidateError(element);

				enviar=false;
				break;
			}
		}
		if(element.className.indexOf('senha')>=0){  //campo tipo senha
			if(form.pwd1.value!=form.pwd2.value){
			alert('Senhas não conferem, favor digite-as novamente.');
			form.pwd1.value='';
			form.pwd2.value='';
			form.pwd1.focus();
			returnValidateError(element);
			enviar=false;
			break;
			}
		}
	}
	return enviar;
}
function sendSuccess(msg)
{
	 $("#send-error").html('<p style=\"text-align:center; color:#990000; font-weight:bold;\">' + msg + '</p>');
	 $("#send-error").show('normal');
}
function creatFields(form,arr)
{
	$.each(arr, function(key, val){ 										
		//alert(key+' '+val[0]+' '+val[1])
		$('#creat_fields_'+form).append('<div class="field" >'+
								'<label for="'+key+'">'+val[1]+'</label><br/>'+
								'<input type="text" name="'+key+'" id="'+key+'"  value="" rel="" />'+ //onBlur="clearform(\''+form+'\');"
							 '</div>');
	});
}

var id_blur;
var valor_blur =0;
var factor =0;
var firstvalue = 0;	
$(document).ready(function(){
	$('input').blur(function(){
		id_blur = $(this).attr('id');
		valor_blur = this.value;	
	});
});
function convertform(form,arr)
{
	$.each(arr, function(key, val){ 										
		if(id_blur==key)
		{	
			if (valor_blur != 0) 
			{			
				factor = val[0];
				firstvalue = parseFloat(valor_blur / factor);
			}
		} 
	});
	if (firstvalue == 0) {
		clearform(form);
		return false;
	} 
	$('#'+form+' input[type=text]').each(function() 
	{
		var id = $(this).attr('id');
		var valor = this.value;
		$.each(arr, function(key, val){ 
			if(id==key)
			{
			  $("#"+id).val(formatvalue((firstvalue * val[0]), 7));
			}
		});
	});
}
function formatvalue(input, rsize) {
   var invalid = "Err";
   var nines = "999999999999999999999999";
   var strin = "" + input;
   var fltin = parseFloat(strin);
   if (strin.length <= rsize) return strin;
   if (strin.indexOf("e") != -1 ||
	   fltin > parseFloat(nines.substring(0,rsize)+".4"))
	  return invalid.substring(0, rsize);
   var rounded = "" + (fltin + (fltin - parseFloat(strin.substring(0, rsize))));
   return rounded.substring(0, rsize);
}
function resetform(form) {
	clearform(form);
	//convertform(form);
	return true;
}
function clearform(form) {
	$('#'+form+' input[type=text]').each(function() 
	{
		this.value = "";
	});
	return true;
}
function widthText(form)
{	
	if(form)
	{
		var str_limpar = $('#'+form+' .btn_bg_reset').text().length;
		var str_converter = $('#'+form+' .btn_bg').text().length;
		if(str_limpar>str_converter)
		{
			var width = str_converter+15(str_limptar-str_converter);			
		}else{
			var width = str_limpar+str_converter+5;
		}
		$('#'+form+' .reset').css('width',width+'%');
	}
}
function alignCenter()
{
	$(".align").attr("align","center");
	$('.container_fields').attr('align','center');
}
