//
// NAVIGATION
//

$(document).ready(function(){
	if(!$.browser.msie)
	{
		$('.menuhover').removeClass('menuhover');
		
		$('#navigation ul').find('ul').css("opacity", "0").hide();
		
		$('#navigation').find('li').hover(
			function() {
				$(this).find('ul:first').stop().show().animate({
				opacity: '1'
				}, 350); },
			function() {
				$(this).find('ul:first').stop().animate({
				opacity: '0'
				}, 350, function(){ $(this).hide(); });
			$(this).find('ul:first').find('ul').hide();
		});
	}
});

$(document).ready(function(){


	check =  Math.floor($('#page_espetaculos_hist_list li').size());
	if (check==0) {
		$('#page_espetaculos_hist_list').hide();
		$('.page_espetaculo_hist_title').hide();
	}
});

//
// AGENDA ACCORDION
//
$(document).ready(function(){
	$('.page_agenda_accordion_title').click(function() {
		check_rel = $(this).attr("rel");
		class_open = '.page_agenda_accordion_list[rel="'.concat(check_rel,'"]');
		
		check_class = $(class_open).hasClass("open");
		
		if (check_class) {
			$(class_open).removeClass("open");
		} else {
			$(class_open).addClass("open");
		}
	})
});



$(document).ready(function(){
	$('.footer_parceiro_imagem a img').each(function() { 
		var altura = $(this).height();
		var padding = Math.floor((115-altura)/2);
		$(this).height(altura);
		$(this).css({'padding-top': padding,'padding-bottom': padding })
	})
	
	function fadeParceiros(lastParceiro) {
		actualParceiro=lastParceiro-1;
		if (actualParceiro==1) {
			$(".footer_parceiro_imagem[rel='"+ qtdParceiros +"']").delay(6000).show().fadeTo(1000,1,function() {$(".footer_parceiro_imagem[rel!='"+ qtdParceiros +"']").show().fadeTo(0,1,function(){ fadeParceiros(qtdParceiros+1); }); });
		} else {
			$(".footer_parceiro_imagem[rel='"+ actualParceiro +"']").delay(6000).fadeTo(1000,0.00001,function() { $(this).hide(); fadeParceiros(actualParceiro); });
		}
	}
	qtdParceiros = $('.footer_parceiro_imagem').size();
	fadeParceiros(qtdParceiros+1);
});


//
// NEWS SLIDER
//
$(document).ready(function(){
	$('#news .news_item:first a').addClass('news_active');
	$('#news .news_link').css({ color: "#7b2727"})
	$('#news .news_last').hide();
	n = $('#news .news_link').size()
	
	$('#news .news_last').click(function () { 
		if (ativo!=n) { $('#news .news_next').show(); }
		ativo = Math.floor($('.news_active').attr('rel'))-1;
		next = '.news_link[rel="'.concat(ativo,'"]')
		
		if (ativo != 0) {
			$('.news_active').removeClass('news_active');
			$(next).addClass('news_active');
			if(ativo-1 == 0) { $(this).hide() }
		} else {
			$(this).hide()
		}

	});
	$('#news .news_next').click(function () {
		ativo = Math.floor($('.news_active').attr('rel'))+1;
		if (ativo>1) { $('#news .news_last').show(); }
		next = '.news_link[rel="'.concat(ativo,'"]')
		
		if (ativo != n) {
			$('.news_active').removeClass('news_active');
			$(next).addClass('news_active');
			if(ativo+1 == n) { $(this).hide() }
		} else {
			$(this).hide()
		}
	});
});

//
// Custom Form 
//
$(document).ready(function(){
	i=0;
	y=0;
	max_altura = 0;
	itens_total = $('.newsBox').size();
	$('.newsBox').each(function(){ 
		
		i++;
		altura = $(this).height();
		if (altura>max_altura) {
			max_altura = altura;			
		}
		if((i%3)==0) {
			y++;
			$(this).addClass('get_3');
			$(this).height(max_altura).prevUntil('.get_3').height(max_altura);
			
			max_altura=0;
		}

	})
});

//
// Custom Form 
//
$(document).ready(function(){
	$('.gform_fields .gfield').each(function() {
		j_gfield_label = $(this).find('.gfield_label');
		texto = j_gfield_label.text();
		$(this).find('.ginput_container input,.ginput_container textarea').attr('title',texto)
	})
	$('label',this).remove();
	
	$('.wpcf7 input,.ginput_container input').each (function() { 
		if($(this).hasClass('wpcf7-submit')) { } else {
			title = $(this).attr('title');
			$(this).val(title)
		}
	});
	
	$('.wpcf7 input,.ginput_container input').click(function(){ 
		if($(this).hasClass('wpcf7-submit')) { } else {
			title = $(this).attr('title');
			if ($(this).val()==title) {
				$(this).val("")
				$(this).css({'color': '#666666'})
			}
		}
	 });
	 
	 $('.wpcf7 input,.ginput_container input').blur(function(){ 
	 	if($(this).hasClass('wpcf7-submit')) { } else {
	 		if ($(this).val()=="") {
		 		title = $(this).attr('title');
		 		$(this).val(title)
		 		$(this).css({'color': '#cccccc'})
	 		}
	 	}
	  });
	  
	  $('.wpcf7 textarea,.ginput_container textarea').each (function() { 
	  	if($(this).hasClass('wpcf7-submit')) { } else {
	  		title = $(this).attr('title');
	  		$(this).val(title)
	  	}
	  });
	  
	  $('.wpcf7 textarea,.ginput_container textarea').click(function(){ 
	  	if($(this).hasClass('wpcf7-submit')) { } else {
	  		title = $(this).attr('title');
	  		if ($(this).val()==title) {
	  			$(this).val("")
	  			$(this).css({'color': '#666666'})
	  		}
	  	}
	   });
	   
	   $('.wpcf7 textarea,.ginput_container textarea').blur(function(){ 
	   	if($(this).hasClass('wpcf7-submit')) { } else {
	   		if ($(this).val()=="") {
	  	 		title = $(this).attr('title');
	  	 		$(this).val(title)
	  	 		$(this).css({'color': '#cccccc'})
	   		}
	   	}
	    });
	    
	   $('#gform_submit_button_1').val('Enviar')
	  
});


// 
// IMAGE LOADER
//

function gallery_img_hover(id) {
	$(".rollover").css( {backgroundPosition: "276px 103px"} );

	$(id).hover(
		function() {
				$(this).find('.hover_fade').stop().animate({opacity:0.4},400);
				$(this).find('.rollover').stop().animate( {backgroundPosition:"228px 103px"}, 500);
			},
			function() {
				$(this).find('.hover_fade').stop().animate({opacity:1},400);
				$(this).find('.rollover').stop().animate({backgroundPosition:"276px 103px"}, 500);
			}
	);	
}

$("<img>").attr("src", "../images/loader.gif");
$("<img>").attr("src", "../images/zoom.png");
$("<img>").attr("src", "../images/play.png");
$("<img>").attr("src", "../images/link.png");

$(document).ready(function() {
	
	// change this to get a different effect
	var waitForAnimBeforeLoad = false;
	
	var images = $("span.image_holder_span img", "div[id^='image_holder_']");
	images.remove();
	$("span.image_holder_loading", "div[id^='image_holder_']").css({ 'display': 'inline' });
	
	// we start the loading loop
	if(images.length > 0)
		loadNextImage(0, images.length);
		
	function loadNextImage(index, count)
	{
		if($(images[index]).attr('src') == "")
		{
			// if image src is empty, we remove the loading image and move on
			$("span.image_holder_loading", "#image_holder_" + index).remove();
			
			if(index < count - 1)
				loadNextImage(index + 1, count);
		}
		else
		{
			var img = new Image();

			$(img).load(function () {
				// on load, we remove the loading image and fade in the real image
				$("span.image_holder_loading", "#image_holder_" + index).remove();
				$(this).css('display','none');
				
				$("span.image_holder_span", "#image_holder_" + index).append(this);
				
				if($(this).parents(".galleryItem3").length == 0)
				{
					$(this).width($("#image_holder_" + index).width());
					$(this).height($("#image_holder_" + index).height());
				}
				
				$(this).fadeIn(500, function()
										{ 											
											setup_hover('#image_holder_' + index);											
											if(waitForAnimBeforeLoad)
											{
												if(index < count - 1)
													loadNextImage(index + 1, count);
											}
										});
				if(!waitForAnimBeforeLoad)
				{
					if(index < count - 1)
						loadNextImage(index + 1, count);
				}
			}).error(function () {
				// if there's an error, we remove the loading image and move on			
				$("span.image_holder_loading", "#image_holder_" + index).remove();
	
				if(index < count - 1)
					loadNextImage(index + 1, count);					
			}).attr('src', $(images[index]).attr('src'));			
		}
	}
	
	function setup_hover(id) {
		var obj = $(id);
		if(obj.hasClass("tmp_rollover_zoom"))
			obj.toggleClass("tmp_rollover_zoom rollover_zoom").find("img").addClass('hover_fade');
		if(obj.hasClass("tmp_rollover_play"))
			obj.toggleClass("tmp_rollover_play rollover_play").find("img").addClass('hover_fade');
		if(obj.hasClass("tmp_rollover_link"))
			obj.toggleClass("tmp_rollover_link rollover_link").find("img").addClass('hover_fade');

		var hcenter = (obj.width() - 64)/2;
		var vcenter = (obj.height() - 64)/2;		

		$(id).hover(
			function() {
					$(this).stop().css({backgroundPosition: (hcenter - 30) + "px " + vcenter + "px" }).animate({backgroundPosition: (hcenter) + "px " + vcenter + "px" }, 400);
					$(this).find('.hover_fade').stop().animate({opacity: 0.4}, 400);
				},
				function() {
					$(this).stop().animate({backgroundPosition: (hcenter + 30) + "px " + vcenter + "px" }, 400);
					$(this).find('.hover_fade').stop().animate({opacity: 1}, 400);
				});
	}

});


//
// SLIDE DOWN
//

$(document).ready(function()
{
	$(".hiddenContent div").hide();    
    $('.hiddenContent a, .visibleContent a').click(function () {
		if($("div", $(this).parent()).is(":visible"))
			$("span", $(this)).html("+");
		else
			$("span", $(this)).html("-");
		slideToggle("div", $(this).parent());
    });
	
	function slideToggle(el, context){
		var $el = $(el, context), height = $el.data("originalHeight"), visible = $el.is(":visible");
		var ptop = $el.data("originalPTop"), pbot = $el.data("originalPBot");
		bShow = !visible;
		
		if( !height || !ptop || !pbot){
			height = $el.show().height();
			$el.data("originalHeight", height);
			
			ptop = $el.css("padding-top");
			$el.data("originalPTop", ptop);
			
			pbot = $el.css("padding-bottom");
			$el.data("originalPBot", pbot);			

			if( !visible ) 
				$el.hide().css({height: 0});
		}
		
		// expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
		if( bShow ){
			$el.show().animate({height: height, "padding-top": ptop, "padding-bottom": pbot}, {duration: 250});
		} else {
			$el.animate({height: 0, "padding-top": 0, "padding-bottom": 0}, {duration: 250, complete:function (){
				$el.hide();
			}});
		}
	}
});

//
// INPUT BLUR
//

$(document).ready(function()
{
    $(".defaultText").focus(function(srcc)
    {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});

//
// IMAGE SLIDE
// 

$(function() {
	$('ul.galleryItem3 li').hover(function(){
		$(this).find('img').animate({top:'170px'},{queue:false,duration:500});
	}, function(){
		$(this).find('img').animate({top:'0px'},{queue:false,duration:500});
	});
});

//
// VALIDATE FORMS
//

$(document).ready(function(){
	var items = $('#imageList li');
	if(items.length != 0)
	{
		var w = items.width() + parseInt(items.css("padding-left").replace("px", "")) + parseInt(items.css("padding-right").replace("px", ""));
		var m = (960/items.length - w)/2;
		if(m > 0)
			$('#imageList li').css("margin", "0px " +  m + "px");
	}
	$(".validate_button_comment").attr('onclick', '').click(function(e) {
		var valid = true;
		
		$(this).parent().find('.validate_entry input, .validate_entry textarea').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim())
			{
				highlightInputField($(this));
				//$(this).stop().focus();//animate({ backgroundColor: "#FC1959", color: "#FFFFFF"}, 300);
				valid = false;
			}
		});
		
		$(this).parent().find('.validate_email input').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim() || !emailCheck($(this).val().trim()))
			{
				highlightInputField($(this));
				//$(this).stop().focus();//.animate({ backgroundColor: "#FC1959", color: "#FFFFFF"}, 300);
				valid = false;
			}
		});
		
		if(valid)
		{
			$('input, textarea').each( function () { 
				if($(this).val().trim() == $(this).attr('title').trim())
					$(this).val('');
			});				
		
			this.parentNode.submit();
		}
	});
	
	var def_sumbit_action = $(".validate_button_contact").attr('onclick');
	$(".validate_button_contact").attr('onclick', '').click(function(e) {
		var valid = true;
		
		$(this).parent().find('.validate_entry input, .validate_entry textarea').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim())
			{
				highlightInputField($(this));
				valid = false;
			}
		});
		
		$(this).parent().find('.validate_email input').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim() || !emailCheck($(this).val().trim()))
			{
				highlightInputField($(this));
				valid = false;
			}
		});
		
		if(valid)
		{
			$('input, textarea').each( function () {  
				if($(this).val().trim() == $(this).attr('title').trim())
					$(this).val('');
			});				
		
			def_sumbit_action();
		}
	});	
	
});

function sendContactRequest(submitformid, url, toemail, buttonid, loadingid, successid)
{	
	var params = 'toemail=' + toemail;
	$("#" + submitformid).find("input, textarea").each( function() { if($(this).val() != $(this).attr('title')) params += '&' + $(this).attr('name') + '=' + $(this).val(); });
	
	xmlhttp = GetXmlHttpObject();
	xmlhttp.onreadystatechange = function() {if (xmlhttp.readyState == 4)
											{
												if(xmlhttp.responseText.indexOf('mailsentok') >= 0)
												{
													$(loadingid).hide();
													$(successid).show();
												}
												else
												{
													$(loadingid).hide();
													$(buttonid).show();
												}
											}
										};
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	$(buttonid).hide();
	$(loadingid).show();
}

function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject)
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function emailCheck (emailStr) {

var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return false;
   }
}

// Make sure there's a host name preceding the domain.

if (len<2) {
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

