/* Author: 
	Tony oliveira
*/
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}



$(function(){
	
	EmailButtonHover();
	EmailButtonClick();
	LightSwitch();
	PreloadImages();

});

var msgInterval;



function EmailButtonHover(){
	
	$("span#emailButton").mouseenter(function(){

      $(this).fadeTo(0,0.5)

    }).mouseleave(function(){

      $(this).fadeTo(0,1)

    });

}

function EmailButtonClick(){

	$("span#emailButton").click(function(){

		var email = $("input#email").val();
		
		if($.trim(email) == ""){ShowMessage("Por favor preencha o campo de E-mail."); return;}

	    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	    
	    if (!filter.test(email)){ShowMessage("O E-mail é inválido."); return;}



	    $.ajax({
	    	type:'POST',          
	      	dataType:'json',
	      	data:{
	      		email: email
	      	},
	      	success:function(response){
	    
	    		if(response.duplicated){
	    		
	    			ShowMessage("O E-mail submetido já existe.")
	    			
	    		}else{
	    		
	    			ShowMessage("O E-mail foi submetido com sucesso!")
	    			
	    		}

	    		$("input#email").val("");
	    
	      	},
	      	url: "ajax/newsletter.php"     
	    });

	})	
}

function LightSwitch(n){

	if(n === undefined){

		window.setTimeout(function(){LightSwitch(1);},1000); 

		return;

	}

	var bulb = "img#bulbOn";

	var fadeSpeed = 400;

	fadeVal = n%2 == 0 ? 0.9 : 1; 

	n++;

	if(n > 12){

		$(bulb).fadeTo(200,0,LightSwitch);

		return
		
	}

	$(bulb).fadeTo(fadeSpeed,fadeVal,function(){LightSwitch(n)})

}

function ShowMessage(msg){

	if($("div#messageBox").length){
	
		$("div#messageBox").unbind("click").remove();

		clearTimeout(msgInterval);
		
	}

	msgBox = "<div id='messageBox'>"+msg+"</div>";

	$(msgBox).appendTo("div#main").fadeIn("fast").unbind("click").bind("click",function(){
		
		$(this).fadeOut("fast",function(){

			clearTimeout(msgInterval);
		
			$(this).remove();

			
		})

	});

	msgInterval = window.setTimeout(function(){

		$("div#messageBox").fadeOut("fast",function(){
			
			$(this).remove()

		})

	},5000)
	
}

function PreloadImages(){

	$.preloadImages("../img/box_alert_wide.png");

}


















