/*
/*	Dynamic design functions and onLoad events
/*	----------------------------------------------------------------------
/* 	Creates added dynamic functions and initializes loading.
*/


// ======================================================================
//
//	On document ready functions
//
// ======================================================================

$(document).ready(function() {
	
	var count = 0;
    $("#mercado-recentes #next").bind("click", function(e){
        e.preventDefault();
        if (!$(this).hasClass("inactive")) {
            count+=1;
            $("#mercado-recentes  #prev").removeClass("inactive");
            if ($("#mercado-recentes li:not(':visible')").eq(count).length < 1) {
                $(this).addClass("inactive");
            }
            $("#mercado-recentes li:visible").eq(0).hide();
            $("#mercado-recentes li:not(':visible')").eq(count).show();
            
        }
    });
     $("#mercado-recentes #prev").bind("click", function(e){
        e.preventDefault();
        if (!$(this).hasClass("inactive")) {
            $("#mercado-recentes #next").removeClass("inactive");
            count-=1;
            if (count < 1) {
                $(this).addClass("inactive");
            }
            $("#mercado-recentes li:visible").eq(3).hide();    
            $("#mercado-recentes li:not(':visible')").eq(count).show();
            
        }

    });
	 
	 $(".assano").click(function(){
		$(".assano").removeClass("selected");
		$(this).addClass("selected");
        $(".assano input").removeAttr("checked");
        $("#tipoAssinatura").val($(this).attr("title"));
		$("#precoAssinatura").val($(this).attr("alt"));
		$(this).find("input").attr("checked", "checked");
        $(".asstipo").find("input:checked").click();
	 });
	 $(".assano input").unbind('click').click(function(){
		$(".assano").removeClass("selected");
		$(this).parent().addClass("selected");
		$("#tipoAssinatura").val($(this).parent().attr("title"));
		$("#precoAssinatura").val($(this).parent().attr("alt"));
		$(this).attr("checked", "checked");
        $(".asstipo").find("input:checked").click();
	 });
	 
	  $(".asstipo input").click(function(){
		var choice = $("div.selected").attr("title") + $(this).attr("alt");
		$("#tipoAssinatura").val(choice);
	 });
	  $(".assano").eq(0).click();
	  $(".asstipo").find("input").eq(0).click();
	 
	 $("#archiveMercado > tbody > tr:even").css("background-color", "#f3e9d2");
	  $("body").mousedown(function(){
            $(".willFade").fadeOut();
			$("object").css("visibility", "visible");
        });
        $(".willFade").mousedown(function(e){
            e.stopPropagation();
        });
	 
	 $(".sobreAnimal .genealogia").bind("click", function(e){
		e.preventDefault();
		$("#layer_genealogia").fadeIn();
		$("object").css("visibility", "hidden");
	 });
	 $(".close").bind("click", function(e){
		e.preventDefault();
		if ($(this).closest(".willFade").length > 0){
			$("body").trigger("mousedown");
		}
	 });
	
	//$(".mercadoEquestreCapa a:has('img')").fancybox();
	
//	$("#linkcat-2").find("ul").prepend("<li style='height:120px'> <object width='260' height='100' type='application/x-shockwave-flash' data='http://www.mundoequestre.com.br/ads/colca.swf'><param value='http://www.mundoequestre.com.br/ads/colca.swf' name='movie'>  <param value='260' name='width'> <param value='100' name='height'> </object><a href='http://www.tradicioncolca.com/'>Clique aqui</a></li>");
	
    
    function nextLastNews(){
		clearInterval(timer);
		if (lastNewsDistance < 1040) {
			sliderVal = sliderVal+1;
			lastNewsDistance = lastNewsDistance + 260;
		} else {
			lastNewsDistance = 0;
			sliderVal = 1;
		}
		$("#lastnews-1").scrollTo(lastNewsDistance, 200);
		$("#SkinSlider").slider("value", sliderVal);
		timer = setInterval(nextLastNews, 6000);
	}
    
	var timer = setInterval(nextLastNews, 6000);
	var lastNewsDistance = 260;
	var sliderVal = 1;
	
	$("#SkinSlider").slider({
		value: 1,
		min: 1,
		max: 5,
		step: 1,
		slide: function (event, ui) {
			nextLastNews();
			sliderVal = $("#SkinSlider").slider("value");
			clearInterval(timer);
		}, stop: function(){
			clearInterval(timer);
			timer = setInterval(nextLastNews, 6000);
		}
	});
	
	function prevLastNews(){
		clearInterval(timer);
		if (lastNewsDistance > 0) {
			lastNewsDistance = lastNewsDistance - 260;
		} else {
			lastNewsDistance = 1040;
		}
		$("#lastnews-1").scrollTo(lastNewsDistance, 200);
		timer = setInterval(nextLastNews, 6000);
	}
	$(".controles a").click(function(e){
		e.preventDefault();
		destino = $(this).attr("href");
		if (destino == "prev") {
			prevLastNews();
		}
		if (destino == "next"){
			nextLastNews();
		}
	});
	$(".mercadoEquestre .tabela tbody:not('.except') tr:even").css("background-color", "#f9fffa");
//	$(".guia4_listaServicos a").click(function(e){
//		e.preventDefault();
//		newwindow=window.open($(this).attr('href'),'','height=300,width=450');
//        if (window.focus) {newwindow.focus()}
//        return false;
//	});
	
	$(".guia4Search").click(function(){
		var cidade = $("#guia4cidSelect").val();
		var servico = $("#guia4servSelect").val();
		document.location = "http://www.mundoequestre.com.br/guia/?categoria="+servico+"&cidade="+cidade;
	});
	$(".formRevstas").submit(function(e){
		e.preventDefault();
		data = $(this).serialize();
		esse = $(this);
		esse.empty().append("Adicionando ao carrinho...");
		$.post('http://www.mundoequestre.com.br/loja-virtual/carrinho', data, function(){
			esse.empty().append("<p>No carrinho.</p>");
		});
	});
	 $(".formPagSeguro").submit(function(e){
		nomereal = $(".produtonomeReal").val();
		nome = $(".formPagSeguro .produtonome").attr("value");
		if (nome == nomereal) {
			e.preventDefault();
			alert("Escolha um tamanho!");
		}
	});
	 
	$(".imgsMercadoEquestre a").click(function(e){
		e.preventDefault();
		$link = $(this);
		$img = $("#imgMain").find("img");
		$img.fadeOut(300, function(){
			$img.attr("src", $link.attr("href")).fadeIn(300);
		});
	});
	 
	 $(".formEnquete").submit(function(e){
		$form = $(this);
		e.preventDefault();
		$form.find("input[type=submit]").attr("disabled", "disabled");
		$.post($form.attr("action"), $form.serialize(), function(){
			$form.empty().append("<p>Voto computado - Obrigado por participar!</p>");
		});
	 });
	 
	$(".tamanho input[type='radio']").click(function(){
		nome = $(".formPagSeguro .produtonome").val();
		tamanho = $(this).val();
		if (tamanho == "outro") {
			$("#outroTamanho").removeAttr("disabled");
			tamanho = $("#outroTamanho").val();
		} else {
			$("#outroTamanho").attr("disabled", "true");
		}
		$(".formPagSeguro .produtonomeReal").attr("value", nome + " - "+ tamanho);
	});
	$(".tamanho input[type='text']").blur(function(){
		tamanho = $(this).val();
		nome = $(".formPagSeguro .produtonome").val();
		$(".formPagSeguro .produtonomeReal").attr("value", nome + " - "+ tamanho);
	})
	$(".gallery a[rel='grup']").not(".sendToMail").fancybox();
	$("#ulRevistas a").fancybox();
	$(".gallery-icon a").not(".sendToMail").fancybox();
	$(".blogPostText a:has(img)").fancybox();
	$(".sendToMail").click(function(e){
		e.preventDefault();
		$("#sendMail").fadeIn();
		$("#sendToMail .right img").attr("src", $(this).closest(".gallery-icon").find("a[rel='grup'] img").attr("src"));
		$("#sendToMail .fotoURL").attr("value", $(this).closest(".gallery-icon").find("a[rel='grup']").attr("href"));
	});
	$(".closeSendMail").live('click', function(e){
		e.preventDefault();
		$("#sendMail").fadeOut('fast', function(){
			$("#sendMail").find(".status").remove();
			$("#sendToMail").show();
		});		
	});
	$("#sendToMail").submit(function(e){
		e.preventDefault();
		form = $(this);
		data = form.serialize();
		url = form.attr("action");
		form.hide();
		form.parent().append("<p class='status'>Enviando..</p>");
		$.post(url, data, function(cb){
			if (cb == "1") {
				form.parent().find(".status").text("E-mail enviado com sucesso! ").append(" <a href='fechar esta janela' class='closeSendMail'>[fechar]</a>");
			} else {
				form.parent().find(".status").text(cb).append(" <a href='fechar esta janela' class='closeSendMail'>[fechar]</a>");
			}
		});
	});
	$(".hoverMail").hover(function(){
		$(this).find(".galOpt").fadeIn();
	}, function(){
		$(this).find(".galOpt").fadeOut();
		});
	
	$(".edOnline").fancybox({
		 'titleShow'     : false,
'modal' : true


		});
	
	// initialise main-menu (jQuery superfish plug-in)
	// -------------------------------------------------------------------
	
	if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7) {
		// IE 6 has problem with supersubs plugin so we don't use it here...
		$('ul.sf-menu').superfish({  		// initialize superfish
				delay:       400,			// one second delay on mouseout 
				animation: {				// fade-in and slide-down animation 
					height:	'show'
				},
				speed:		275
			});
	} else {
		// all other browsers, include supersubs plugin.
		$('ul.sf-menu').supersubs({ 
	            minWidth:    12,	// minimum width of sub-menus in em units 
	            maxWidth:    27,	// maximum width of sub-menus in em units 
	            extraWidth:  0		// extra width for slight rounding differences in fonts 
	        }).superfish({  		// initialize superfish
	            delay:       400,	// one second delay on mouseout 
	            animation: {		// fade-in and slide-down animation 
					height:	'show'
				},
	            speed:		275
	        });
	}
	
		
	// initialize modal (fancybox)
	// -------------------------------------------------------------------
	
	// Quickly setup some special references
	// fancybox doesn't like #name references at the end of links so we find
	// them and modify the link to use a class and remove the #name.
	$('a[href$="#popup"]').addClass('zoom').each( function() {
		theHref = $(this).attr('href');
		$(this).attr('href', theHref.replace('#popup',''))
	});
	$('a[href$="#login"]').addClass('login').each( function() {
		theHref = $(this).attr('href');
		$(this).attr('href', theHref.replace('#login',''))
	});

	
	var overlayColor = $('#fancy_overlay').css('background-color') || '#2c2c2c';
	
	$('a.zoom').fancybox({
		'padding': 12, 
		'overlayOpacity': 0.2,
		'overlayColor': overlayColor, 
		'zoomSpeedIn': 500, 
		'zoomSpeedOut': 500,
		'callbackOnShow': modalStart
	});

	// initialize login modal (fancybox)
	// -------------------------------------------------------------------
	$('a.login').fancybox({
		'padding': 12, 
		'overlayOpacity': 0.2,
		'overlayColor': overlayColor, 
		'showCloseButton': false,
		'frameWidth': 400,
		'frameHeight': 208,
		'hideOnContentClick': false,
		'callbackOnShow': modalStart		
	});
	
		

	// Slide down top content (topReveal) 
	// -------------------------------------------------------------------
	$('.topReveal, a[href$="#topReveal"]').click( function() {
		$('#ContentPanel').slideToggle(800,'easeOutQuart');	// show/hide the content area
		$.scrollTo('#ContentPanel');
		return false;
	});
	

	// image hover effects	
	// -------------------------------------------------------------------
	$("a.img").hover( function () {
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) <= 8) {
			$(this).stop(false, true).toggleClass('imgHover');
		} else {
			$(this).stop(false, true).toggleClass('imgHover', 200);
		}
	});
			
			
	// Text and password input styling
	// -------------------------------------------------------------------
	
	// This should be in the CSS file but IE 6 will ignore it.
	// If you have an input you don't want styles, add the class "noStyle"

	$("input[type='text']:not(.noStyle), input[type='password']:not(.noStyle)").each(function(){
		$(this).addClass('textInput');
	});

						   
	// input lable replacement
	// -------------------------------------------------------------------
	$("label.overlabel").overlabel();
	
	// apply custom search input functions
	// -------------------------------------------------------------------
	searchInputEffect();
		
	// apply custom button styles
	// -------------------------------------------------------------------
	buttonStyles();
	
	// CSS Rounded Corners (not for IE)
	// -------------------------------------------------------------------
	if (!jQuery.browser.msie) {
		$("a.img, div.img, .pagination a, .textInput, input[type='text'], input[type='password'], textarea").addClass('rounded');	// items to add rounded class
		roundCorners(); // execute it!
	}
	
});




// ======================================================================
//
//	Design functions
//
// ======================================================================


	
// Modal after load functions
// -------------------------------------------------------------------

function modalStart() {
	// apply font replacement
	Cufon.replace('.fancy_title > div');
	
	// updated styles
	$('#fancy_inner').addClass('rounded');
	roundCorners();
}



// Search input - custom effects for mouse over and focus.
// -------------------------------------------------------------------

// Search input - custom effects for mouse over and focus.
// -------------------------------------------------------------------

function searchInputEffect() {

	var	searchFocus = false,
		searchHover = false,
		searchCtnr = $('#Search'),
		searchInput = $('#SearchInput'),
		searchSubmit = $('#SearchSubmit');
	// Search input - mouse events
	if (searchCtnr.length > 0) {
		searchCtnr.hover(
			function () {	// mouseover
				if (!searchFocus) $(this).addClass('searchHover');
				searchHover = true; }, 
			function () {	// mouseout
				if (!searchFocus) $(this).removeClass('searchHover');
				searchHover = false;
		}).mousedown( function() {
			if (!searchFocus) $(this).removeClass('searchHover').addClass('searchActive');
		}).mouseup( function() {
			searchInput.focus();
			searchSubmit.show();
			searchFocus = true;
		});
		// set focus/blur events
		searchInput.blur( function() {
			if (!searchHover) {
				searchCtnr.removeClass('searchActive');
				searchSubmit.hide();
				searchFocus = false;
			}
		});
	}
}



// button styling function
// -------------------------------------------------------------------

function buttonStyles() {
	// Button styles
	
	// This will style buttons to match the theme. If you don't want a button
	// styled, give it the class "noStyle" and it will be skipped.
	$("button:not(:has(span),.noStyle), input[type='submit']:not(.noStyle), input[type='button']:not(.noStyle)").each(function(){
		var	b = $(this),
			tt = b.html() || b.val();
		
		// convert submit inputs into buttons
		if (!b.html()) {
			b = ($(this).attr('type') == 'submit') ? $('<button type="submit">') : $('<button>');
			b.insertAfter(this).addClass(this.className).attr('id',this.id);
			$(this).remove();	// remove input
		}
		b.text('').addClass('btn').append($('<span>').html(tt));	// rebuilds the button
	});
	
	// Get all styled buttons
	var styledButtons = $('.btn');
	
	// Fix minor problem with Mozilla and WebKit rendering (can also be done adding this to CSS, 
	// button::-moz-focus-inner {border: none;}
	// @media screen and (-webkit-min-device-pixel-ratio:0) { button span {margin-top: -1px;} }
	if (jQuery.browser.mozilla || jQuery.browser.webkit) {
		styledButtons.children("span").css("margin-top", "-1px");
	}
	
	// Button hover class (IE 6 needs this)
	styledButtons.hover(
		function(){ $(this).addClass('submitBtnHover'); },		// mouseover
		function(){ $(this).removeClass('submitBtnHover'); }	// mouseout
	);
}

// Rounded corner styles
// -------------------------------------------------------------------

function roundCorners() {
	$('.rounded, .ui-corner-all').css({
		'-moz-border-radius': '4px',
		'-webkit-border-radius': '4px',
		'border-radius': '4px'
	});
}
	


