/*
script desenvolvido por Luis Carlos de Brito - luis@pevermelho.art.br

caso venha adquirir este script por outro meio senao atraves do autor, favor manter o credito do criadore
este script pode ser utilizado, modificado, publicado, utilizado sem restricoes desde que mantido os credidos dos criadores

##########------- tive muito trabalho para fazer este funcionar, respeite meu trabalho e conhecimento -------##########
*/
var ie=ie6=ie7=ie8=false;
var obj_flash;
var YouTubePlayer=null;

function init() {	
	if(window.navigator.appVersion.indexOf('MSIE 6.')!=-1) ie6=true;
	if(window.navigator.appVersion.indexOf('MSIE 7.')!=-1) ie7=true;
	if(window.navigator.appVersion.indexOf('MSIE 8.')!=-1) ie8=true;
	window.navigator.appName=='Microsoft Internet Explorer' ? ie=true : ie=false;
	$('#contato').click(function(){ showModalDiv('dv_contato')});	
	$('#contatos').click(function(){ showModalDiv('dv_contatos')});
	$('#slide_fotos').cycle({fx:'fade'});
	obj_flash=insertSWF('imagens/loading.swf', 60, 60, '');
	$('.telefone').mask('(99) 9999-9999');
	swfobject.embedSWF("banda.swf","ss_banda", 480, 282, "8", null, null, { allowScriptAccess: "always", wmode:"transparent" });
}



function setCookie(nome, valor) { document.cookie=nome+'='+valor; }

function getCookie(nome) {
	var start=document.cookie.lastIndexOf(nome+'=');
	if(start==-1) return false;
    var end=document.cookie.indexOf(';',start);
    if(end!=-1) 
    	return document.cookie.substring(start + nome.length+1, end);
    else 
    	return document.cookie.substring(start + nome.length+1, document.cookie.length);
}

function loadData(form) {
  form = get(form);
  var n_fields = form.length;
  var dados = '';
  var types1 = 'text hidden select-one textarea password';
  var types2 = 'checkbox radio';
  var types3 = 'button submit';
  
  for(var n=0; n < n_fields; n++) {
     if(types3.indexOf(form.elements[n].type)==-1) {
     	if(form.elements[n].getAttribute('obrigatorio')=='sim' && form.elements[n].value=='') {
     		$.growlUI('',form.elements[n].getAttribute('msg'));
     		form.elements[n].focus();
     		return false;
     	}
	  	else {
		  	if(types1.indexOf(form.elements[n].type)!=-1)
		     	dados+=form.elements[n].name+'='+ encodeURIComponent(form.elements[n].value) +'&';
		  	else{
		  		if(types2.indexOf(form.elements[n].type)!=-1) {
		  			if(form.elements[n].checked)
		  				dados+= form.elements[n].name+'='+ encodeURIComponent(form.elements[n].value)+'&';
		  		}
	  		}
	  	}
   	}
  } 
  dados = dados.substr(0, dados.length-1);
  return dados;
}

function showModalDiv(id) { 
	$.blockUI({ message: $('#'+id) }); 	
	$('.blockOverlay').click($.unblockUI); 
	$('.blockUI.blockPage').css('position','absolute'); 
}

function showModalContent(content, _w) {
	$.blockUI({ message: content, css: { width: _w, border:'5px solid #666', left: ((screen.width - parseInt(_w))/2)+'px' ,top:$('html').scrollTop()+50} });
	$('.blockOverlay').click($.unblockUI); 
	$('.blockUI.blockPage').css({'position':'absolute'}); 
}

function block() {
	 $.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } });
}

function insertSWF(file, w, h, params) {
	insert = new Flash(file, '', w, h,'');
	insert.addParameter('wmode', 'transparent'); 
	insert.addParameter('showMenu', 'false'); 
	
	if(params.length>2) {
		tmp=params.split(',');
		for(i in tmp) {
			param_value = tmp[i].split('=');
			insert.addVariable(param_value[0]+'', param_value[1]+'');
		}
	}
	return insert.toString();
}

function addListener(el, event, func) {
	try { el.addEventListener(event, func, false); } 
	catch (e) {
		try {
			el.detachEvent('on'+ event, func);
			el.attachEvent('on'+ event, func);
		} catch (e) {}
	}
}

function showImgUploaded(msg, campo) {get('retorno'+campo).innerHTML=''+msg;}

function loadVideo(idVideo, content, w, h){
	if(YouTubePlayer==null) {
		var params = { allowScriptAccess: "always", wmode:"transparent" };
		var atts = { id: "YTPlayer" };
		swfobject.embedSWF("http://www.youtube.com/v/" + idVideo + "&enablejsapi=1&playerapiid=YTPlayer",content, w, h, "8", null, null, params, atts);
		
	}else YouTubePlayer.cueVideoById(idVideo);
}

function onYouTubePlayerReady(playerId) {
	YouTubePlayer = document.getElementById(playerId);
	YouTubePlayer.addEventListener("onStateChange", "onYTPlayerStateChange");
	//console.info("player id ->"+playerId);
}

function onYTPlayerStateChange(newState) {
  //console.info("novo estado -> "+newState);
  switch(newState) {
  	case -1: //não iniciou a reprodução
  	case 0:  /*encerrou a reprodução*/
  		var tmp = YouTubePlayer.getVideoUrl();
  		tmp=tmp.split('v='); tmp=tmp[1];
  		tmp=tmp.substring(0, tmp.indexOf('&'));
  		//console.info("idVideo -> "+tmp);
  		setTimeout(function(){ YouTubePlayer.cueVideoById(tmp); },1000);
  		break;
  	case 2: /*pausado*/
  	case 3: /*armazenando em buffer*/
  	//case 5: /*video indicado*/
  	case 1: break;/*em reprodução*/
  		
  }
}

function manageSlideShow(id,dir) {
	var width=$('#'+id).css('width').replace('px','');
	var elemWidth=parseFloat(width / 5).toFixed(1);
	width=elemWidth*$('#'+id+' div').size();
	var max=-(width-(elemWidth*5));
	
	if($('#wrap'+id).html()==null) {
		$('#'+id+' div').css('width',elemWidth-1);
		$('#'+id+' div').wrapAll('<div id="wrap'+id+'" style="float:left;width:'+width+'px;position:relative;"/>');
	}
	if(dir=='e')
		if(parseFloat($('#wrap'+id).css('marginLeft').replace('px',''))<0) {
			$('#wrap'+id).animate({marginLeft:'+='+elemWidth},1500);}
	if(dir=='d')
		if(parseFloat($('#wrap'+id).css('marginLeft').replace('px',''))>max) {
			$('#wrap'+id).animate({marginLeft:'-='+elemWidth},1500);}
}

function doZoom() {
	setTimeout(function(){$('img.doZoom').animate({width:'-=15'});},2000);
	$('img.doZoom').hover(
	function(){ $(this).animate({width:'+=15'},200); },
	function(){ $(this).animate({width:'-=15'},200); }
	);
}

addListener(window, 'load', init);

function initjscep(cepOptions){
	$.fn.defaults = {
		urlCep: "http://cep.republicavirtual.com.br/web_cep.php",	
		target: "cep",												
		format:	"javascript",
		campos: Array()
	}
	jQuery.extend($().defaults, cepOptions);
}

$(function(){ 
    if (!$().defaults) return false;
    var _o=$().defaults;
   // FunÃ§Ã£o Ãºnica que farÃ¡ a transaÃ§Ã£o  
    $("[name="+_o.target+"]").blur(function() { 
		// Se o campo CEP nÃ£o estiver vazio  
		if($.trim($("[name="+_o.target+"]").val()) != ""){  
			/* 
				Para conectar no serviÃ§o e executar o json, precisamos usar a funÃ§Ã£o 
				getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros 
				dataTypes nÃ£o possibilitam esta interaÃ§Ã£o entre domÃ­nios diferentes 
				Estou chamando a url do serviÃ§o passando o parÃ¢metro "formato=javascript" e o CEP digitado no formulÃ¡rio 
				http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("[name=cep]").val() 
		   */  
		   $.getScript(_o.urlCep+"?formato="+_o.format+"&cep="+$("[name="+_o.target+"]").val(), function(){  
			   // o getScript dÃ¡ um eval no script, entÃ£o Ã© sÃ³ ler!  
			   //Se o resultado for igual a 1  
			   if(resultadoCEP["resultado"]){  
				   // troca o valor dos elementos  
				   $("[name="+_o.campos['rua']+"]").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));  
				   $("[name="+_o.campos['bairro']+"]").val(unescape(resultadoCEP["bairro"]));  
				   $("[name="+_o.campos['cidade']+"]").val(unescape(resultadoCEP["cidade"]));  
				   $("[name="+_o.campos['estado']+"]").val(unescape(resultadoCEP["uf"]));  
			   }else{  
				   alert("Endereço não encontrado");  
			   }  
		   });  
	   }  
   });      
});

function cadastrarCliente(){
	var erro='';
	if(document.frm_cadastro.nome.value.length<7) {
		erro='Seu nome deve conter no mínimo 7 caracteres'; document.frm_cadastro.nome.focus(); $.growlUI('',erro); return false;}
	if(document.frm_cadastro.curso.value.length<0) {
		erro='informe seu curso'; document.frm_cadastro.curso.focus(); $.growlUI('',erro); return false;}
	if(document.frm_cadastro.email.value.length<8) {
		erro='Seu email deve conter no minimo 8 caracteres'; document.frm_cadastro.email.focus(); $.growlUI('',erro); return false;}
	if(document.frm_cadastro.cidade.value.length<3) {
		erro='Informe sua Cidade'; document.frm_cadastro.cidade.focus(); $.growlUI('',erro); return false;}
	if(document.frm_cadastro.telefone.value.length<2){
		erro='Informe seu telefone'; document.frm_cadastro.telefone.focus(); $.growlUI('',erro); return false;}
	if(document.frm_cadastro.senha.value.length<1){
		erro='Informe sua senha'; document.frm_cadastro.senha.focus(); $.growlUI('',erro); return false;}
	
	if(erro.length<1) {		
		if(getv('resenha')!=getv('senha')){ 
			$.growlUI('','A confirmação de senha deve ser igual a senha!'); 
			get('resenha').focus();
		}else { 
			if(get('termo_uso').checked) 
				loadDataAndSend('alert','frm_cadastro'); 
			else $.growlUI('','Você deve aceitar os termos de uso para prosseguir.');
		}
	}
}
