function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277&
    // inicializa
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}
/*###############################################################################################################################*/


function ConfDialog(largura)
{
	var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
	$('#dialog').css('width',largura);
	$('#dialog').css('margin-left','-'+(largura/2)+'px');
	$('#dialog').css('margin-top',50+scrollTop+'px');
}

function Mascara()
{
	var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
	document.body.style.overflow='hidden';
	$('#mascara').css('margin-top',scrollTop+'px');
	$('#mascara').show();
}

/**/

function limpaCampo(msg_padrao,elemento)
{
	if(msg_padrao==elemento.value){
		elemento.style.color="#2a2a2a";
		elemento.value="";
	}
}
function verificaCampo(msg_padrao,elemento)
{
	if(elemento.value.length==0)
	{
		elemento.style.color="#b1b1b1";
		elemento.value=msg_padrao;	
	}
}

/*
 *
 */

function addSWF(url, width, height, transparent)
{	
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ');
	document.write('codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" ');
	document.write('width="'+width+'" height="'+height+'">');
	document.write('<param name="movie" value="'+url+'" />');
	document.write('<param name="quality" value="high" />');
	
	if(transparent){
	  document.write('<param name="wmode" value="transparent" />');
	}
	
	document.write('<embed src="'+url+'" quality="high"');
	
	if(transparent) {
	document.write (' wmode="transparent"');
	}
	
	document.write ('pluginspage="http://www.macromedia.com/go/getflashplayer" ');
	document.write ('type="application/x-shockwave-flash" width="'+width+'" height="'+height+'" style="z-index:0;"></embed>');
	document.write ('</object>');
}

function carregaGrupos()
{	
	if(document.getElementById("menu_grupos").style.display=="none"){
		ajaxjQuery('conteudo','paginas/carrega_grupos.php');
		document.getElementById('img_seta').src='images/seta_up.png';
	}else{
		//$('#conteudo').html("&nbsp;");
		//ajaxjQuery('conteudo','paginas/inicial.php');
		document.getElementById('img_seta').src='images/seta_down.png';
	}
}

function is_email(email)
{
	er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
  
	if(er.exec(email))
	{
	  return true;
	} else {
	  return false;
	}
}

function validaForm(formulario,erro,erro2){
	switch(formulario)
	{
		case 'contato':
			var campos=new Array("nome","email","mensagem");
			var valida=true;
			
			for(var i=0; i<campos.length; i++)
			{
				if($('#'+campos[i]).val().length==0)
				{
					$('#'+campos[i]).css('background-color','#e84c4c');
					valida=false;
				}
			}
			
			if(valida)
			{
				if(is_email($('#email').val()))
				{
					document.forms['form_contato'].submit();
				}else{
					alert(erro2);
				}
			}else{
				alert(erro);
			}
		break;
		
		case 'carrinho':
			var campos=new Array("nome","email","contato","pais","tipo");
			var valida=true;
			
			for(var i=0; i<campos.length; i++)
			{
				if($('#'+campos[i]).val().length==0 || document.getElementById(campos[i]).value=="0")
				{
					$('#'+campos[i]).css('background-color','#e84c4c');
					valida=false;
				}
			}
			
			//verifica se o tipo "Outro" foi selecionado, e se tem algo escrito no campo
			if(document.getElementById("tipo_div").style.display=="block"){
				if($('#tipo_div').val().length==0){
					$('#tipo_div').css('background-color','#e84c4c');
					valida=false;
				}
			}
			
			// * //
			
			if(valida)
			{
				if(is_email($('#email').val()))
				{
					document.forms['form_carrinho'].submit();
				}else{
					alert(erro2);
				}
			}else{
				alert(erro);
			}
		break;
	}
	
	return false;
}

function showInfo(codigo)
{
	ConfDialog(800);
	Mascara();
	
	var retorno = $.ajax({
	  type: "GET",
	  url: "paginas/produtos_info.php?id="+codigo,
	  async: false,
	  success: function(retorno)
	  {
		$('#dialog').html('<table width="100%" border="0" cellpading="0" cellspacing="0" style="background-color:#9d2721;">'+
  						  '<tr>'+
    					  '<td width="50%" style="padding:5px;" align="left"><a href="?p=contato" style="color:#fff;">Gostou? Entre em Contato</a></td>'+
    					  '<td width="50%" style="padding:5px;" align="right"><a href="#" onclick="$(\'#dialog\').hide(); $(\'#mascara\').hide(); document.body.style.overflow=\'auto\';" style="color:#fff;">Fechar <img src="images/close.gif" alt="" border="0" /></a></td>'+
 						  '</tr>'+
						  '</table>'+
						  retorno);
		$('#dialog').fadeIn();
	  }
	}).responseText;
}

function trocaPr(pos)
{
	//variaveis temporarias
	var produto = new Array();	
	produto[0] = $('#produto_nome').html();
	produto[1] = $('#produto_codi').val();
	
	//altera produto principal
	var cod = $('#tb_'+pos+'_cod').val();
	
	$('#produto_codi').val(cod);
	$('#produto_nome').html($('#tb_'+pos+'_nome').val());
	$('#produto_link').html('<a href="#" onclick="showInfo('+cod+'); return false" style="color:#f0f0d5; font-size:13px;">Mais Detalhes</a>');
	document.getElementById('produto_foto').src='images/produtos/'+cod+'_media.png';
	
	
	//altera thumb
	$('#tb_'+pos+'_nome').val(produto[0]);
	$('#tb_'+pos+'_cod').val(produto[1]);
	document.getElementById('tb_'+pos+'_img').src='images/produtos/'+produto[1]+'_thumb.png';
	document.getElementById('nome'+pos).innerHTML = produto[0];
}

function carregaCliente(id)
{
	$('#cliente_swf').html('teste');
}

function scrollPr(tipo)
{	
	//$(document).ready(function(){
		switch(tipo)
		{
			case 'next':
				if(parseInt($('#thumbs').css('margin-left').replace('px','')) > ($('#largura').val()-($('#largura').val()*2)))
				$('#thumbs').css('margin-left',(parseInt($('#thumbs').css('margin-left').replace('px',''))-100)+'px');
				//$("#thumbs").animate({"left": "-=100px"}, "medium");
			break
			
			case 'prev':
				if(parseInt($('#thumbs').css('margin-left').replace('px','')) < 0)
				$('#thumbs').css('margin-left',(parseInt($('#thumbs').css('margin-left').replace('px',''))+100)+'px');
				//$("#thumbs").animate({"left": "+=100px"}, "medium");
			break;
		}
	//});
}

function scrollEvt(tipo)
{	
	//$(document).ready(function(){
		switch(tipo)
		{
			case 'next':
				if(parseInt($('#slide_int').css('margin-left').replace('px','')) > -300)
				$('#slide_int').css('margin-left',(parseInt($('#slide_int').css('margin-left').replace('px',''))-100)+'px');
				//$("#thumbs").animate({"left": "-=100px"}, "medium");
			break
			
			case 'prev':
				if(parseInt($('#slide_int').css('margin-left').replace('px','')) < 0)
				$('#slide_int').css('margin-left',(parseInt($('#slide_int').css('margin-left').replace('px',''))+100)+'px');
				//$("#thumbs").animate({"left": "+=100px"}, "medium");
			break;
		}
	//});
}

function samScroll(tipo, div, tamanho)
{
	switch(tipo)
	{
		case 'cima':
			if(parseInt(document.getElementById(div).style.top.replace('px','')) < 0)
			$("#"+div).animate({"top": "+="+tamanho+"px"}, "medium");
		break;
		
		case 'direita':
			$("#"+div).animate({"left": "-="+tamanho+"px"}, "medium");
		break;
		
		case 'baixo':
			$("#"+div).animate({"top": "-="+tamanho+"px"}, "medium");
		break;
		
		case 'esquerda':
			$("#"+div).animate({"left": "+="+tamanho+"px"}, "medium");
		break;
	}
}

/*
 *
 */

function ajaxjQuery(div, pagina){
	setTimeout("continua_jQuery('"+div+"','"+pagina+"');", 50);
}

function continua_jQuery(div,pagina){
	var divRetorno=document.getElementById(div);
	
	var html = $.ajax({
		url: pagina,
		async: false,
		dataType: "html"
	}).responseText;
	divRetorno.innerHTML=html;
	extraiScript(html);
}

function carregaProduto(valores){
	var indices = valores.split(',');
	tipo = indices[0];
	id = indices[1];
	
	$('#carrega_produto').load('paginas/carrega_produto.php?tipo='+tipo+'&id='+id);
	objSel = document.getElementById('dropProdutos');
    for (i=0; i < objSel.length; i++){
        if (objSel.options[i].value == id) {
            objSel.selectedIndex = i;
            break;
        }
    }
}


function trocafotocliente(id){
	  var ft = $("img#fotocliente");
	  ft.attr("src", './images/clientes/'+id+'.jpg');
}


function trocafotopromo(id){
	//window.alert(id);
	  var ft2 = $("img#fotopromo");
	  ft2.attr("src", './images/produtos/promo/'+id+'.jpg');
}

/*
 * INICIO DO SCROLLL DE CLIENTES
 */
var x;
var mover = 0;
var alturacontainer = 464;

function moveUp(){
    
	totalAltura = 986;

    x = window.setInterval(function goUp(){
            
            mover = mover + 2;
            
            if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
                 var ieversion=new Number(RegExp.$1);
                  if (ieversion>=6 && ieversion <9){
                      mover = mover + 7;   
                  }
            }           
            document.getElementById('cli_cont').style.marginTop = -(mover) +'px'; 
            
            
            if(mover > totalAltura){
                window.clearInterval(x);
            }
    },5);
}

//Iniciando a funcao que rola o slider para a direita...
function moveDown(){    
    x = window.setInterval(function goDown(){
            mover = mover - 2;
            
            if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
                 var ieversion=new Number(RegExp.$1);
                  if (ieversion>=6 && ieversion <9){
                      mover = mover - 7;   
                  }
            }          
            document.getElementById('cli_cont').style.marginTop = -(mover) +'px';
            if(mover < 1){
                   window.clearInterval(x);
                   document.getElementById('cli_cont').style.marginTop = '0px';
            }  
    },5);
}

// Iniciando a funcao que para a rolagem...
function stopMove(){
    window.clearInterval(x);
}

function slideshowclientes(lista){
	
	var myphotos = lista.split(':');
	var i = 0;
	var mover = 0;
	var intervalo = window.setInterval(mudafoto, 2600);
	function mudafoto() {
		
		
		j = i-1;
		$('#miniatura'+myphotos[j] ).css( 'border-color','#000');
		$('#miniatura'+myphotos[i] ).css( 'border-color','#fff');
		trocafotocliente(myphotos[i]);
		document.getElementById('cli_cont').style.marginTop = -(mover) +'px'
		i++;
		mover = mover + 67;
		if(i == myphotos.length){
			$('#miniatura'+myphotos[myphotos.length]).css('border-color','#000');
			clearInterval(intervalo);
			
		}
		
	}
}