///* Função de validação de formulário por Jquery */
function validaJqurey(){
	var sSubmit = true;
	// faz uma busca por todos elementos que especificam o atributo req=true
	$("[req=true]").each(
	function(){
		if($(this).val().length < 1){
			alert("O campo '" + $(this).attr("label") + "' é obrigatório.");
			$(this).focus();
			sSubmit = false;
			return false;
		}
	});
	
	return sSubmit;
}

// Funções gerais //
function toggleMe(a){
	var e=document.getElementById(a);
	if(!e) {
		return true;
	}
	if((e.style.display=="none")||(e.style.display=="")){
		e.style.display="block"
	}
	else{
		e.style.display="none"
	}
	return true;
}

// validação dos emails
function ValidacaoEmail(value) {
	return (value == "" || value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) != -1);
}

// tira determinado valor do campo no focus
function TiraValue(valor, obj){
	if(obj.value == valor){
		obj.value="";
	}
}

/// coloca determinado valor no campo no blur
function ColocaValue(valor, obj){
	if(obj.value == ''){
		obj.value=valor;
	}
}

function validaEnviaNoticia(){
	if(document.formEnviaNews.seunome.value==""){
		alert("Por favor, preencha o campo: 'Seu Nome'.");
		document.formEnviaNews.seunome.focus();
		return false;
	}
	if(document.formEnviaNews.seuemail.value==""){
		alert("Por favor, preencha o campo: 'Seu e-mail'.");
		document.formEnviaNews.seuemail.focus();
		return false;
	}
	if(ValidacaoEmail(document.formEnviaNews.seuemail.value)==""){
		alert("Por favor, preencha o campo: 'Seu e-mail' corretamente.");
		document.formEnviaNews.seuemail.focus();
		return false;
	}
	if(document.formEnviaNews.destinatario.value==""){
		alert("Por favor, preencha o campo: 'Destinatário'.");
		document.formEnviaNews.destinatario.focus();
		return false;
	}
	if(document.formEnviaNews.emaildestinatario.value==""){
		alert("Por favor, preencha o campo: 'E-mail'.");
		document.formEnviaNews.emaildestinatario.focus();
		return false;
	}
	if(ValidacaoEmail(document.formEnviaNews.emaildestinatario.value)==""){
		alert("Por favor, preencha o campo: 'E-mail' corretamente.");
		document.formEnviaNews.emaildestinatario.focus();
		return false;
	}
	return true;
}


/*
Funções para chamar AJAX
*****************************************************************************/

function ajaxEnviaNews(idobj, endereco){
	if(ValidacaoEmail(value))
	ajaxHTML(idobj, endereco);
}

/*
Funções da ENQUETE
*****************************************************************************/


function toggleMeEnquete(a,b){
	var e=document.getElementById(a);
	var f=document.getElementById(b);
	if((!e)||(!f)) {
		return true;
	}
	if(e.style.display=="none"){
		e.style.display="block"
		f.style.display="none"
	}
	else{
		e.style.display="none"
		f.style.display="block"
	}
	return true;
	//document.geElementById("verificaVoto").innerHTML="";
}

function envia_enquete(codenquete){
	form 			= document.forms[1];
	totRespostas 	= document.enquete.radiobutton.length;
	valorChecado	= false;
	for(i=0; i<totRespostas; i++){
		if(document.enquete.elements["radiobutton"][i].checked){
			valorChecado = true;
			break;
		}
	}//for
	if(!valorChecado){
		alert("Por favor, selecione uma das opções de resposta.");
	}
	else{
		cod = acharadio();

		ajaxHTML('pergEnquete', 'ajaxGravaEnquete.php?codresposta=' + cod + '&codenquete=' + codenquete + '&' + Math.ceil(Math.random()*1000));

		for(i=0; i<totRespostas; i++){
			document.enquete.elements["radiobutton"][i].checked = false;
		}//for
		//document.getElementById('resultEnquete').style.display = 'block';
		ajaxHTMLnoLoad('resultEnquete', 'ajaxResultadoEnquete.php?codenquete=' + codenquete + '&' + Math.ceil(Math.random()*1000));
	}
}

function acharadio(){
	for(i=0;i<7;i++){
		if(document.enquete.radiobutton[i].checked){
			return document.enquete.radiobutton[i].value;
		}
	}
}

function carregaGuia(value) {
	if (value != "") {
		window.location.href = "/artesanato/Portugues/lisGuias.php?cod=" + value;
	} else {
		return false;
	}
}

//jcarousel lite

(function($) {                                          // Compliant with jquery.noConflict()
	$.fn.jCarouselLite = function(o) {
		o = $.extend({
			btnPrev: null,
			btnNext: null,
			btnGo: null,
			mouseWheel: false,
			auto: null,

			speed: 200,
			easing: null,

			vertical: false,
			circular: true,
			visible: 1,
			start: 0,
			scroll: 1,

			beforeStart: null,
			afterEnd: null
		}, o || {});

		return this.each(function() {                           // Returns the element collection. Chainable.

			var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
			var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

			if(o.circular) {
				ul.prepend(tLi.slice(tl-v-1+1).clone())
				.append(tLi.slice(0,v).clone());
				o.start += v;
			}

			var li = $("li", ul), itemLength = li.size(), curr = o.start;
			div.css("visibility", "visible");

			li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
			ul.css({overflow: "hidden", margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
			div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

			var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
			var ulSize = liSize * itemLength * 1.2;                   // size of full ul(total length, not just for the visible items)
			var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

			li.css({width: li.width(), height: li.height()});
			ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

			div.css(sizeCss);                     // Width of the DIV. length of visible images

			if(o.btnPrev)
			$(o.btnPrev).click(function() {
				return go(curr-o.scroll);
			});

			if(o.btnNext)
			$(o.btnNext).click(function() {
				return go(curr+o.scroll);
			});

			if(o.btnGo)
			$.each(o.btnGo, function(i, val) {
				$(val).click(function() {
					return go(o.circular ? o.visible+i : i);
				});
			});

			if(o.mouseWheel && div.mousewheel)
			div.mousewheel(function(e, d) {
				return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
			});

			if(o.auto)
			setInterval(function() {
				go(curr+o.scroll);
			}, o.auto+o.speed);

			function vis() {
				return li.slice(curr).slice(0,v);
			};

			function go(to) {
				if(!running) {

					if(o.beforeStart)
					o.beforeStart.call(this, vis());

					if(o.circular) {            // If circular we are in first or last, then goto the other end
						if(to<=o.start-v-1) {           // If first, then goto last
							ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
							// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
							curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
						} else if(to>=itemLength-v+1) { // If last, then goto first
							ul.css(animCss, -( (v) * liSize ) + "px" );
							// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
							curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
						} else curr = to;
					} else {                    // If non-circular and to points to first or last, we just return.
						if(to<0 || to>itemLength-v) return;
						else curr = to;
					}                           // If neither overrides it, the curr will still be "to" and we can proceed.

					running = true;

					ul.animate(
					animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
					function() {
						if(o.afterEnd)
						o.afterEnd.call(this, vis());
						running = false;
					}
					);
					// Disable buttons when the carousel reaches the last/first, and enable when not
					if(!o.circular) {
						$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
						$( (curr-o.scroll<0 && o.btnPrev)
						||
						(curr+o.scroll > itemLength-v && o.btnNext)
						||
						[]
						).addClass("disabled");
					}

				}
				return false;
			};
		});
	};

	function css(el, prop) {
		return parseInt($.css(el[0], prop)) || 0;
	};
	function width(el) {
		return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
	};
	function height(el) {
		return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
	};

})(jQuery);


/*
Função Cadastro de Nwesletter
*****************************************************************************/
$(document).ready(function(){
	
	/* Trocando valores do cadastro de newsletter do rodapé */
	$('#emlEmail').focus( function () {
		if($('#emlEmail').val() == 'Cadastre-se agora!') $('#emlEmail').val("");
	}).blur( function () {
		if($('#emlEmail').val() == '') $('#emlEmail').val("Cadastre-se agora!");
	});

	/* Validação do cadastro de newsletter do rodapé */
	$("#btnOkNews").click( function (){
		if($('#emlEmail').val() == ""){
			alert("Preencha o campo email!");
			$('#emlEmail').focus();return false;
		}
		if(ValidacaoEmail($('#emlEmail').val()) == ""){
			alert("Preencha o campo email corretamente!");
			$('#emlEmail').focus();return false;
		}
		$("form#frmNewsletter").submit();
	});
		$("form#frmNewsletter").submit(function() {
			$.post( "action/phpNewsletter.php",{email:this.emlEmail.value},function(resposta){
				$('#emlEmail').val("E-MAIL CADASTRADO!");
			},"html");
		return false;
	});
	
	/* Função para abrir lightbox do vídeo da direita */
	$("#videoCast a.detVideo").prettyPhoto({animationSpeed:'slow',theme:'light_rounded',slideshow:2000});
	
});


//flash

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

//hoverfocus ie 6 ???

// Funções de :hover e :focus para ie6

function suckerfish(type, tag, parentId) {
	if (window.attachEvent) {
		window.attachEvent("onload", function() {
			var sfEls = (parentId==null)?document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
			type(sfEls);
		});
	}
}

sfHover = function(sfEls) {
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" over";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
	}
}

sfFocus = function(sfEls) {
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onfocus=function() {
			this.className+=" focus";
		}
		sfEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" focus\\b"), "");
		}
	}
}

suckerfish(sfHover, "LI", "sm", "ul");
//suckerfish(sfFocus, "INPUT");
suckerfish(sfFocus, "TEXTAREA" );
suckerfish(sfFocus, "SELECT" );

//ajax util

//Tenta criar o objeto xmlHTTP
try{
	xmlhttp = new XMLHttpRequest();
}catch(ee){
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			xmlhttp = false;
		}
	}
}

//Fila de conexões
fila=[]
ifila=0

//Carrega via XMLHTTP a url recebida e coloca seu valor
//no objeto com o id recebido
function ajaxHTML(id,url){
	//Carregando...
	document.getElementById(id).innerHTML='<img src="img/ajax-loader.gif" class="carregando" />'
	//Adiciona à fila
	fila[fila.length]=[id,url]
	//Se não há conexões pendentes, executa
	if((ifila+1)==fila.length)ajaxRun()
}

//Carrega via XMLHTTP a url recebida e coloca seu valor
//no objeto com o id recebido
function ajaxHTMLnoLoad(id,url){
	//Adiciona à fila
	fila[fila.length]=[id,url]
	//Se não há conexões pendentes, executa
	if((ifila+1)==fila.length)ajaxRun()
}

//Executa a próxima conexão da fila
function ajaxRun(){
	//Abre a conexão
	xmlhttp.open("GET",fila[ifila][1],true);
	//Função para tratamento do retorno
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			//Mostra o HTML recebido
			retorno=unescape(xmlhttp.responseText.replace(/\+/g," "))
            document.getElementById(fila[ifila][0]).innerHTML=retorno
            //Roda o próximo
            ifila++
            if(ifila<fila.length)setTimeout("ajaxRun()",20)
        }
    }
    //Executa
    xmlhttp.send(null)
}

//scripts


window.onerror=function(desc,page,line,chr){
/* alert('JavaScript error occurred! \n'
  +'\nError description: \t'+desc
  +'\nPage address:      \t'+page
  +'\nLine number:       \t'+line
 );*/
}

$(function(){
 $('a').focus(function(){this.blur();});
 SI.Files.stylizeAll();
 slider.init();

 $('input.text-default').each(function(){
  $(this).attr('default',$(this).val());
 }).focus(function(){
  if($(this).val()==$(this).attr('default'))
   $(this).val('');
 }).blur(function(){
  if($(this).val()=='')
   $(this).val($(this).attr('default'));
 });

 $('input.text,textarea.text').focus(function(){
  $(this).addClass('textfocus');
 }).blur(function(){
  $(this).removeClass('textfocus');
 });

 var popopenobj=0,popopenaobj=null;
 $('a.popup').click(function(){
  var pid=$(this).attr('rel').split('|')[0],_os=parseInt($(this).attr('rel').split('|')[1]);
  var pobj=$('#'+pid);
  if(!pobj.length)
   return false;
  if(typeof popopenobj=='object' && popopenobj.attr('id')!=pid){
   popopenobj.hide(50);
   $(popopenaobj).parent().removeClass(popopenobj.attr('id').split('-')[1]+'-open');
   popopenobj=null;
  }
  return false;
 });
 $('p.images img').click(function(){
  var newbg=$(this).attr('src').split('bg/bg')[1].split('-thumb')[0];
  $(document.body).css('backgroundImage','url('+_siteRoot+'img/bg/bg'+newbg+'.jpg)');
 
  $(this).parent().find('img').removeClass('on');
  $(this).addClass('on');
  return false;
 });
 $(window).load(function(){
 	if(!css_ims) var css_ims;
  $.each(css_ims,function(){(new Image()).src=_siteRoot+'img/'+this; });
  $.each(css_cims,function(){
   var css_im=this;
   $.each(['blue','purple','pink','red','grey','green','yellow','orange'],function(){
    (new Image()).src=_siteRoot+'css/'+this+'/'+css_im;
   });
  });
 }); 
 $('div.sc-large div.img:has(div.tml)').each(function(){
  $('div.tml',this).hide();
  $(this).append('<a href="#" class="tml_open">&nbsp;</a>').find('a').css({
			left:parseInt($(this).offset().left)+864,top:parseInt($(this).offset().top)+1
		}).click(function(){
			$(this).siblings('div.tml').slideToggle();
			return false;
		}).focus(function(){this.blur();});
	});
});
var slider={
	num:-1,
	cur:0,
	cr:[],
	al:null,
	at:10*1000,
	ar:true,
	init:function(){
		if(!slider.data || !slider.data.length)
		return false;

		var d=slider.data;
		slider.num=d.length;
		var pos=Math.floor(Math.random()*1);//slider.num);
		for(var i=0;i<slider.num;i++){
			$('#'+d[i].id).css({left:((i-pos)*1000)});
			$('#slide-nav').append('<a id="slide-link-'+i+'" href="#" onclick="slider.slide('+i+');return false;" onfocus="this.blur();">'+(i+1)+'</a>');
		}

		$('img,div#slide-controls',$('div#slide-holder')).fadeIn();
		slider.text(d[pos]);
		slider.on(pos);
		slider.cur=pos;
		window.setTimeout('slider.auto();',slider.at);
	},
	auto:function(){
		if(!slider.ar)
		return false;

		var next=slider.cur+1;
		if(next>=slider.num) next=0;
		slider.slide(next);
	},
	slide:function(pos){
		if(pos<0 || pos>=slider.num || pos==slider.cur)
		return;

		window.clearTimeout(slider.al);
		slider.al=window.setTimeout('slider.auto();',slider.at);

		var d=slider.data;
		for(var i=0;i<slider.num;i++)
		$('#'+d[i].id).stop().animate({left:((i-pos)*1000)},1000,'swing');

		slider.on(pos);
		slider.text(d[pos]);
		slider.cur=pos;
	},
	on:function(pos){
		$('#slide-nav a').removeClass('on');
		$('#slide-nav a#slide-link-'+pos).addClass('on');
	},
	text:function(di){
		slider.cr['a']=di.client;
		slider.cr['b']=di.desc;
		slider.cr['c']=di.texx;
		slider.ticker('#slide-client span',di.client,0,'a');
		slider.ticker('#slide-desc',di.desc,0,'b');
		slider.ticker('#slide-texx',di.texx,0,'c');
	},
	ticker:function(el,text,pos,unique){
		if(slider.cr[unique]!=text)
		return false;

		ctext=text.substring(0,pos)+(pos%2?'-':'_');
		$(el).html(ctext);

		if(pos==text.length)
		$(el).html(text);
		else
		window.setTimeout('slider.ticker("'+el+'","'+text+'",'+(pos+1)+',"'+unique+'");',30);
	}
};
// STYLING FILE INPUTS
if(!window.SI){var SI={};};
SI.Files={
	htmlClass:'SI-FILES-STYLIZED',
	fileClass:'file',
	wrapClass:'cabinet',

	fini:false,
	able:false,
	init:function(){
		this.fini=true;
	},
	stylize:function(elem){
		if(!this.fini){this.init();};
		if(!this.able){return;};

		elem.parentNode.file=elem;
		elem.parentNode.onmousemove=function(e){
			if(typeof e=='undefined') e=window.event;
			if(typeof e.pageY=='undefined' &&  typeof e.clientX=='number' && document.documentElement){
				e.pageX=e.clientX+document.documentElement.scrollLeft;
				e.pageY=e.clientY+document.documentElement.scrollTop;
			};
			var ox=oy=0;
			var elem=this;
			if(elem.offsetParent){
				ox=elem.offsetLeft;
				oy=elem.offsetTop;
				while(elem=elem.offsetParent){
					ox+=elem.offsetLeft;
					oy+=elem.offsetTop;
				};
			};
		};
	},
	stylizeAll:function(){
		if(!this.fini){this.init();};
		if(!this.able){return;};
	}
};

// jcarousel no head
$(function() {
	$(".slider").jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev"
	});
	$(".slider2").jCarouselLite({
		btnNext: ".next2",
		btnPrev: ".prev2"
	});
	$(".menuCarousel").jCarouselLite({
		btnNext: ".nextMenu",
		btnPrev: ".prevMenu"
	});
	$(".slider3").jCarouselLite({
		btnNext: ".next3",
		btnPrev: ".prev3"
	});
	$(".slider4").jCarouselLite({
		btnNext: ".next4",
		btnPrev: ".prev4",
		circular: false
	});
	$(".slider1").jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		visible: 4
	});
});

//busca limpa campo
function remBusca(a, b){
	if (a.value==b) {
		a.value='';
	} else if(a.value=='') {
		a.value=b;
	} else {
		a.value=a.value;
	}
}
function chkBusca(a, b){
	if (a.value=='') {
		a.value=b;
	} else {
		a.value=a.value;
	}
}

//contador

var contador = 10;
function conta() {
	document.getElementById('tempo').innerHTML=contador;
	if (contador == 0) {
		document.getElementById('link').style.display="none";
	}
	if (contador != 0) {
		contador = contador-1;
		setTimeout("conta()", 1000);
	}
}

//variavel site root index

var _siteRoot='index.php',_root='index.php';


