

$(document).ready(function(){
    
	init();
	
		
});

// Pre-loader plugin
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

function init(){

	
	/*initSplash();*/

	initToday();
	
	initMenu();
	
	initMultimidia();
	
	formComentario();
	
	formAssinatura();
	
	formAmigo();
	
	fotos();
	
	albuns();

        //jQuery('#viewport').carousel('#simplePrevious', '#simpleNext');
        $("#viewport").accordion({ header: "h3",autoHeight: false });

        $(".imgtitle").css("color","#0066cc");
        $(".imgtitle").css("margin","1px");
        $(".imgtitle").css("margin-left","4px");
        $(".imgtitle").css("margin-right","4px");
        $(".imgtitle").css("padding","1px");

        //margin:0px; padding:0px; margin-left:0px;margin-right:

}

/*
 * Today Splash Home
 */

var timerToday;
var cardZ = 1;

function initToday(){
	
	if( $(".today").html() == null )
		return;
		
	$(".tab").mouseover( function(){
		timerTodayStop();
		var i = $(this).attr("lang");
		goToCard( i );
		//cardZ = i;
	} );
	
	$(".tab").mouseout( function(){
		timerTodayStart();
	} );
	
	goToCard( 0 );
	timerTodayStart();
	
}

function timerTodayStop(){
	timerToday.stop();
}

function timerTodayStart(){
	timerToday = $.timer( 5000, function(){ goToCard( cardZ++ ); } );
}

function goToCard( i ){
	if( i > 2 ) i = 0;
	cardZ = i+1;
	$(".card").css( "visibility", "hidden" );
	$(".card:eq(" + i + ")").css( "visibility", "visible" );
	$(".tab > a").attr( "class", "" );
	$(".tab:eq(" + i + ") > a").attr( "class", "ativo" );
}

/*
 * ==================================================================================== MULTIMIDIA
 */
function initMultimidia(){
	
	$('#nuvem').html( $('#nuvem').html() ).cloudinizr({ loPerc: 110, hiPerc: 200 });
	$('#nuvem span').css({backgroundColor: '#fff',color: '#FF7500'});
	$('#nuvem span').hover(
	        function() { $(this).css({backgroundColor: '#FF7500',color: '#fff'}) },
	        function() { $(this).css({backgroundColor: '#fff',color: '#FF7500'}) });
	
	 $('#nuvem span').click(function(){
		 	
		 //$(this).css({fontWeight: 'bold',color: '#888'});
		 document.location.href = "http://www.revistamissoes.org.br/multimidia/filtrar/tag/" + $(this).html();
	 	
	 });
	
}
/*
 * 
 * */
function fotos(){
	
	
        $('#fotos a').lightBox({
        	overlayBgColor: '#E5EFFB',
        	overlayOpacity: 0.6,                    
        	imageLoading: 'http://www.revistamissoes.org.br/public/images/ajax-loader.gif', 
        	imageBtnPrev: 'http://www.revistamissoes.org.br/public/images/lightbox-btn-prev.gif',			
    		imageBtnNext: 'http://www.revistamissoes.org.br/public/images/lightbox-btn-next.gif',	
    		imageBtnClose:'http://www.revistamissoes.org.br/public/images/lightbox-btn-close.gif',	
    		imageBlank:   'http://www.revistamissoes.org.br/public/images/lightbox-blank.gif',
    		txtImage: 'Imagem',
    		txtOf: 'de'    	    			
            });
    
	
}


/*
 * ==================================================================================== COMENTARIOS
 */
function formComentario(){
	
	$("#boxComenteForm").validate({
		   submitHandler: function(form) {
		    //$(form).ajaxSubmit();
		    enviarComentario();
		   }
		});
	
}
function formAmigo(){
	
	$("#boxAmigoForm").validate({
		   submitHandler: function(form) {
		    //$(form).ajaxSubmit();
		    enviarAmigo();
		   }
		});
	
}
function formAssinatura(){
	
	$("#formAss").validate({
		errorElement: "div",
		errorClass: "error",
		   submitHandler: function(form) {
		    $(form).ajaxSubmit();
		      
		   }
		});
	
}
function formNewsletter(){
	var valor = $("#email").val();
	var reg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	
	if( valor.match(reg) ){
		
		
		$.ajax({
			  type: "POST",
			  url: "http://www.revistamissoes.org.br/newsletter/process/format/json",
			  data: "email="+valor,
			  dataType: "text",
			  cache: false,
			  success: function(msg){
			     //alert( "Data Saved: " + msg +"\n\nEnvia com sucesso.");
				alert( "E-mail cadastrado com sucesso.");
		
			   }
			});
			
		
		
	}else{
		alert("Informe um E-mail válido");
		
	}
	
}
function qtdeAssinaturas(varejo,atacado,atacadoqtde ){
	//alert(qtde);
	var qtde = parseInt( $("#quantidade").val());
	//alert(qtde+ "   " +atacadoqtde);
	var decimais = 2;
	if (isNaN(qtde)) {  $("#thisval").html("0"); return ""; }; 
	
	var valor = 0;
	if( qtde >= parseInt(atacadoqtde) ){
		valor = qtde * atacado;
		//$("#thisval").html(valor);		
	}else{		
		valor = qtde * varejo;
		//$("#thisval").html(valor);		
	}
	numero = valor;
	
	  if(isNaN(numero)){ $("#thisval").html("-"); return ""; }
	  if( numero == '' ){ $("#thisval").html("-"); return ""; }
	 
	  var IsNegative=(parseInt(numero)<0);
	  if(IsNegative)numero=-numero;

	  var snum = new String(numero);
	  var sec = snum.split('.');
	  var whole = parseInt(sec[0]);
	  var result = '';
	  if(sec.length > 1){
	    var dec = new String(sec[1]);
	    dec = parseInt(dec)/Math.pow(10,parseInt(dec.length-decimais-1));
	Math.round(dec);
	dec = parseInt(dec)/10;

	if(IsNegative)
	{
	  var x = 0-dec;
	      x = Math.round(x);
	  dec = - x;
	}
	else
	{
	      dec = Math.round(dec);
	}

	/*
	  * If the number was rounded up from 9 to 10, and it was for 1 'decimal'
	  * then we need to add 1 to the 'whole' and set the dec to 0.
	  */
	if(decimais==1 && dec==10)
	{
	  whole+=1;
	  dec="0";
	}

	    dec = String(whole) + "." + String(dec);
	    var dot = dec.indexOf('.');
	    if(dot == -1){
	      dec += '.';
	      dot = dec.indexOf('.');
	    }
	var l=parseInt(dot)+parseInt(decimais);
	    while(dec.length <= l) { dec += '0'; }
	    result = dec;
	  } else{
	    var dot;
	    var dec = new String(whole);
	    dec += '.';
	    dot = dec.indexOf('.');
	var l=parseInt(dot)+parseInt(decimais);
	    while(dec.length <= l) { dec += '0'; }
	    result = dec;
	  }
	  if(IsNegative)result="-"+result;
	  
	  $("#thisval").html("<b>Total:</b> R$ "+result);
	  
	  if( qtde == 0 ){
		  $("#quantidade").val("");
		  $("#thisval").html("<b>Total:</b> R$ 0,00");
	  }
	  
	
}


var test = "";
var numCount = 0;


function avulsoQnt( varejo, atacado, atacadoqtde ){
	
	var edicaoC = $("#edicao").val();
	test = edicaoC; 
	numCount = 0;
	$("input[name=edicaoavulso][type=checkbox]").each(
			function(){
				if(this.checked){
				test = test +" , "+ this.value;
				numCount++;
				}
				});
	
	$("#quantidade").val(numCount);
	$("#pedido").val(test);
	
	
	
	qtdeAssinaturas( varejo, atacado, atacadoqtde );
	
	
	
	
	
	numCount = 0;
	test = "";
	//alert(test);
	
}


function mesmaEdicao(val){
	
	if(val){
		
		$("#edicaoMaster").attr("checked","checked");
		$("#mesmoCheck").attr("checked","checked");
		
	}else{
		
		$("#edicaoMaster").attr("checked","");
		$("#mesmoCheck").attr("checked","");
		
	}
	
}


function enviarComentario(){
	
	var autorizo = 1;
	

	if( $("[name='autorizo']").attr("checked") ){
		autorizo = 1;		 
	}else{
		autorizo = 0;		
	}
	
	
	$.ajax({
	  type: "POST",
	  url: "http://www.revistamissoes.org.br/comentarios/process/format/json",
	  data: "comentario="+$("[name='comentario']").val()+
	        "&titulo="+$("[name='titulo']").val()+
	        "&email="+$("[name='email']").val()+
	        "&autor="+$("[name='autor']").val()+
	        "&modulo_name="+$("[name='modulo_name']").val()+
	        "&modulo_id="+$("[name='modulo_id']").val()+
	        "&data="+$("[name='data']").val()+
	        "&autorizo="+autorizo+
	        "&moderado=0",
	  dataType: "text",
	  cache: false,
	  success: function(msg){
	     //alert( "Data Saved: " + msg +"\n\nEnvia com sucesso.");
		alert( "Envia com sucesso.");
	     $("[name='comentario']").val("");
	     $("[name='titulo']").val("");
	     $("[name='email']").val("");
	     $("[name='autor']").val(""); 	     
	     mHide('#boxComente');
	   }
	});
	
}
function enviarAmigo(){
	
	$.ajax({
	  type: "POST",
	  url: "http://www.revistamissoes.org.br/contato/amigo/format/json",
	  data: "nome="+$("[name='seunome']").val()+
	        "&email="+$("[name='seuemail']").val()+
	        "&para="+$("[name='amigopara']").val()+
	        "&comentario="+$("[name='amigocomentario']").val()+
	        "&end="+$("[name='end']").val(),
	  dataType: "text",
	  cache: false,
	  success: function(msg){
	     //alert( "Data Saved: " + msg +"\n\nEnvia com sucesso.");
		 alert( "Envia com sucesso.");
	     $("[name='seunome']").val("");
	     $("[name='seuemail']").val("");
	     $("[name='amigopara']").val("");
	     $("[name='amigocomentario']").val(""); 	     
	     
	     mHide('#boxAmigo');
	   }
	});
	
}

/*
 * ==================================================================================== MENU
 */

/*
 * Inicia o menu, adicionando o drop down nos itens corretos
 */

var timerMenu;

function initMenu(){
	
	var menus = $(".drop");
	
	jQuery.each( menus , function( index, value ) {
		
		var obj = $(".drop:eq("+index+")");
		
		obj.mouseover( function(){
			
			mShow( ".submenu" );
			mShow( "#"+obj.attr("rel") );
			
		} );
		
		$("#"+obj.attr("rel")+" > li > a").mouseover( function(){ timerMenuStop(); } );
		$("#"+obj.attr("rel")+" > li > a").mouseout( function(){ timerMenuStart(); } );
		
	});
	
	// nao drop
	$(".no-drop").mouseover( function(){ mHideAll(); mHide(".submenu"); timerMenuStop(); } );
	
	
}


function albuns(){
	
	var imgSpan = $(".load_img");
	
	jQuery.each( imgSpan , function( index, value ) {
		
		//alert(value.lang);
		
		
		$.ajax({
			  type: "POST",
			  url: "http://www.revistamissoes.org.br/fotos/capa/id/"+value.lang,
			  data: "",
			  dataType: "text",
			  cache: false,
			  success: function(msg){
			     //alert( "Data Saved: " + msg +"\n\nEnvia com sucesso.");
				$("#img_"+value.lang).html('<img src="'+msg+'" style="float: left; margin: 6px; " />');
		
			   }
			});
		
		
		
	});
	
}


function mHideAll(){
	
	var menus = $(".drop");
	
	jQuery.each( menus , function( index, value ) {
		var obj = $(".drop:eq("+index+")");
		mHide( "#"+obj.attr("rel") );
	});
	
}

function mHide( selector ){
	
	$( selector ).css("display","none");
	$( selector ).css("visibility","hidden");
	
}

function mShow( selector ){
	
	mHideAll();
	
	$( selector ).css("display","block");
	$( selector ).css("visibility","visible");
	
}

function timerMenuStop(){
	if( timerMenu != null )
		timerMenu.stop();
}

function timerMenuStart(){
	timerMenu = $.timer( 1500, function(){ mHideAll(); mHide(".submenu"); timerMenuStop(); } );
}

/*
 * 
 * */
function proximo(atual , total){

    var divComenBtns = "";  
    var i = parseInt(atual) + 1;
    mHide(".com_"+atual);
    mShow(".com_"+i);

    if( atual > 0  ) divComenBtns += "<a href=\"javascript:void(0);\" onclick=\"voltar('"+i+"','"+total+"')\" >anteriores</a>";
    if( atual > 0 && i < parseInt( total ) ) divComenBtns += "|";
    if( i < parseInt( total ) ) divComenBtns += "<a href=\"javascript:void(0);\" onclick=\"proximo('"+i+"','"+total+"' )\" >próximos</a>";

    $("#divComenBtns").html(divComenBtns);

}
function voltar( atual , total ){

	var divComenBtns = "";  
   var i = parseInt(atual) - 1;           
   mHide(".com_"+atual);          
   mShow(".com_"+i);

   if( i > 1  ) divComenBtns += "<a href=\"javascript:void(0);\" onclick=\"voltar('"+i+"','"+total+"')\" >anteriores</a>";
   if( i > 1 && i < parseInt( total ) && i > 0  ) divComenBtns += "|";
   if( i < parseInt( total ) && i > 0 ) divComenBtns += "<a href=\"javascript:void(0);\" onclick=\"proximo('"+i+"','"+total+"' )\" >próximos</a>";

   $("#divComenBtns").html(divComenBtns);
  
}

/*
 * ===================================================================================
 */

jQuery.validator.addMethod("verificaCPF", function(value, element) {  
	     value = value.replace('.','');  
	     value = value.replace('.','');  
	     cpf = value.replace('-','');  
	     while(cpf.length < 11) cpf = "0"+ cpf;  
	     var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;  
	     var a = [];  
	     var b = new Number;  
	     var c = 11;  
	     for (i=0; i<11; i++){  
	         a[i] = cpf.charAt(i);  
	         if (i < 9) b += (a[i] * --c);  
	     }  
	     if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }  
	     b = 0;  
	     c = 11;  
	     for (y=0; y<10; y++) b += (a[y] * c--);  
	     if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }  
	     if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;  
	     return true;  
	 }, "Informe um CPF válido."); 

jQuery.validator.addMethod("dateBR", function(value, element) {  
	         //contando chars  
	        if(value.length!=10) return false;  
	        // verificando data  
	        var data        = value;  
	        var dia         = data.substr(0,2);  
	        var barra1      = data.substr(2,1);  
	        var mes         = data.substr(3,2);  
	        var barra2      = data.substr(5,1);  
	       var ano         = data.substr(6,4);  
	       if(data.length!=10||barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||isNaN(ano)||dia>31||mes>12)return false;  
	       if((mes==4||mes==6||mes==9||mes==11)&&dia==31)return false;  
	       if(mes==2 && (dia>29||(dia==29&&ano%4!=0)))return false;  
	       if(ano < 1900)return false;  
	       return true;  
	  }, "Informe uma data válida");  // Mensagem padrão   

jQuery.validator.addMethod('phone', function(value) {
	return value.match(/^[0-9()+ -]{5,}$/);
	//var numbers = value.split(/\d/).length - 1;
	//return (10 <= numbers && numbers <= 20 && value.match(/^(\+){0,1}(\d|\s|\(|\)){10,20}$/));
	}, 	'Informe um telefone válido');


//---------data
jQuery(function(a){a.datepicker.regional["pt-BR"]={closeText:"Fechar",prevText:"&#x3c;Anterior",nextText:"Pr&oacute;ximo&#x3e;",currentText:"Hoje",monthNames:["Janeiro","Fevereiro","Mar&ccedil;o","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthNamesShort:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],dayNames:["Domingo","Segunda-feira","Ter&ccedil;a-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sabado"],dayNamesShort:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"],dateFormat:"dd/mm/yy",firstDay:0,isRTL:false};a.datepicker.setDefaults(a.datepicker.regional["pt-BR"])});