
$.fn.infiniteCarousel = function () {
 
    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            
 
 
        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }
 
        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        $('.cloned', $slider).find('a').removeAttr('rel');
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 300, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 
 
                currentPage = page;
            });                
            
            return false;
        }
        
        $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
        
        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () {
            return gotoPage(currentPage - 1);                
        });
        
        $('a.forward', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
    });  
};
$(document).ready(function(){	
	
	$('.infiniteCarousel').infiniteCarousel();
	
	$('.minigaleria li a')
	.click(function(){
		var href = $(this).attr('href');
		
		$('.minigaleria a.img_principal')
		.attr('href', href.replace('/thumbs/', ''));
		
		$('.minigaleria img.img_principal')
		.attr('src', href.replace('/uploads/', '/uploads/thumbs/'));
		
		$('.minigaleria li a').removeClass('active');
		
		$(this).addClass('active');
		
		return false;
	});
	
	$("#s_form")
	.submit(function(){
		var input = $('input[name=q]', this);
		var q = input.val();
		if( q == '' || q == "digite um termo para pesquisa"){
			input.focus();
			return false;
		}else{
			return true;
		}
	});
	$("#s_form button")
	.hover(function(){
		$(this).css("color", "#777");
	}, function(){
		$(this).css("color", "#e6e6e6");
	});
	$("#s_form input")
	.focus(function(){
		$(this).val("");
	})
	.blur(function(){
		setTimeout(function(){
			$(this).val("digite um termo para pesquisa");
		}, 1500);
	});	
	$(".slider a.link span, .produto span")
	.fadeTo('fast', 0.6)
	.hide();
	
	$(".slider a.link")
	.hover(function(){
		$("span", this).slideDown();
	}, function(){
		$("span", this).slideUp();
	});
	
	$(".produto")
	.hover(function(){
		$("span.bottom", this).slideUp();
		$("span", this).slideDown();
	}, function(){
		$("span.bottom", this).slideDown();
		$("span", this).slideUp();
	});
	
	$('.slider .sliderWrap')
	.easySlider({
		auto: true, 
		continuous: true,
		prevId: 		'prevBtn',
		prevText: 		'',
		nextId: 		'nextBtn',	
		nextText: 		'',
		pause: 3000,
		speed: 1000
	});
	$("#nextSlide").live('click', function(){		
		$("#nextBtn a").click();
		return false;
	});
	$("#prevSlide").live('click', function(){		
		$("#prevBtn a").click();	
		return false;			
	});
	
	$('#content img')
	.each(function(){
		var h = $(this).height();
		var w = $(this).width();
		var s = parseFloat(new Number(h/w).toFixed(1) );
		
		var src = $(this).attr('src').replace('/thumbs/', '/');

		if($(this).attr('alt') == 'Calendar' || $(this).parent().hasClass('link') == true )
		return;
		if( w > 400 ){
			$(this).css({margin: '5px 0'});
			$(this).width('585px').removeAttr('width');
		}else{
			$(this).width( parseInt(w*s) ).height( parseInt(h*s) ).removeAttr('width').removeAttr('height');
		}
		
		if( w > 585 ){
			$(this).width('585px').removeAttr('width');
		}
		
		if($(this).parent().attr('href') != undefined){
			$(this).parent('a').attr('rel', 'colorbox').attr('href', src).attr('title', $(this).attr('title'));
			
		}else{
			$(this).wrap('<a href="'+src+'" class="floatl" title="'+$(this).attr('title')+'" rel="colorbox"></a>');
		}
		
	});
	
	$("a[rel='colorbox'], a[rel='colorbox2']")
	.colorbox({
		maxWidth: (screen.width * 0.8),
		maxHeight: (screen.height * 0.8),
		scalePhotos: true
	});
	
	$("#featureCarousel").featureCarousel({
		autoPlay:		1500,
		carouselSpeed:	1000
	});
	
	$('form[name=postComment]')
	.livequery(function(){
		$(this)
		.validate({
			submitHandler: function(form){
				var postUrl = '/painel/system/process/save.php';
				var _formData = 'tbl=comments&'+$('form[name=postComment]').serialize();
				
				var save = savePostData(postUrl, _formData); 
				
				var wrapComment = 	'	<div class="lista border-all padding margin highlight">'+ 
									'		<h5>'+$('input[name=nome]', form).val()+' <span style="font-size: 12px; font-weight: normal;">comentou:</span></h5>'+
									'		<div class="comentario margin-top margin-bottom">'+$('textarea[name=comentario]', form).val()+'</div>'+
									'		<h6 class="no-padding padding-top no-margin">em '+$('input[name=data_cadastro]', form).val()+'</h6>'+
									'	</div>';
				if(save){
					$('#commentWrap').prepend(wrapComment);
					$('input[type=reset]', form).click();
				}
			},
			rules:{
				nome: "required",
				email: {
					required: true,
					email: true
				},
				comentario: "required"
			}
		});
	});
	
	$('form[name=contactForm]')
	.livequery(function(){
		$(this)
		.validate({
			/*submitHandler: function(form){
				return true;
			},*/
			rules:{
				nome: "required",
				email: {
					required: true,
					email: true
				},
				assunto: "required",
				mensagem: "required"
			}
		});
	});
	
	var savePostData = function(postUrl, postData){
	
		var id = $.ajax({
			async: false,
			type: 'POST',
			url: postUrl,
			data: postData
		}).responseText;
		
		return id;
		
	}
	
	if($('.comentarios .pagina').get().length > 0){
		
		$('.comentarios .pagina').eq(0).show();
		$('.comentarios .menuPaginas a').eq(0).addClass('highlight');
		
		$('.comentarios .menuPaginas a')
		.click(function(){
			$('.comentarios .pagina').hide();
			$('.comentarios .menuPaginas a').removeClass('highlight');
			var id = '#'+$(this).attr('id');
			$(id, '.comentarios').show();
			$(this).addClass('highlight');
			return false;
		});
		
	}
			
});

