/* Carousel */
;(function($) {
	$.fn.carousel = function(settings) {
	    var options = $.extend({}, $.fn.carousel.defaults, settings);
	    return this.each(function() {
	    	/* Definições de variáveis */
			var context 				= this,
				running 				= false, 
				animCss 				= options.vertical ? "top" : "left", 
				sizeCss 				= options.vertical ? "height" : "width",
				initial					= 0,
				change;
				context.$this	 		= $(this),
	        	context.$ul 			= context.$this.children("ul"),
	        	context.$li 			= context.$ul.children("li"),
	        	context.$prev			= $(options.btnPrev),
	        	context.$next			= $(options.btnNext),
	        	context.$go				= $(options.btnGo),
	        	context.$slideshow		= $(options.btnSlideshow),
	        	context.liLength 		= context.$li.length,
	        	context.visible 		= options.visible,
	        	context.current			= options.current,
	        	context.scroll			= options.scroll,
	        	context.circular		= options.circular,
	        	context.activeClass		= "active",
	        	context.disableClass	= "disabled",
	        	context.slideshow		= false,
	        	context.$liCloned,
	        	context.liLengthCloned,
	        	context.direction,
	        	context.timer;
	        /* // Definições de variáveis */
	        /* Se for cicular clona a mesma quantidade de itens vísiveis em cada extremidade.  */
	        if (context.liLength < context.visible) {
				context.$prev.add(context.$next).addClass('noScroll');
	        	return;
	        }
	        
	        if(context.circular) {
	        	context.$ul
	            	.prepend(context.$li.slice(context.liLength - context.visible - 1 + 1).clone().addClass("cloned"))
	              	.append(context.$li.slice(0, context.visible).clone().addClass("cloned"));
	            options.start += context.visible;
	        };
	        /* // Se for cicular clona a mesma quantidade de itens vísiveis em cada extremidade. */
	        context.$liCloned 			= context.$ul.children("li"), 
	        context.liLengthCloned 		= context.$liCloned.length;
	        context.current 			= options.start;
	        /* Verificações inicias de posição */
	        if ( !options.start && !context.circular ) {
	        	context.$prev.addClass(context.disableClass);
	        } else if ( (options.start + context.visible) === context.liLength && !context.circular ) {
	        	context.$next.addClass(context.disableClass);
	        };
	        /* // Verificações inicias de posição */
	        /* Definições de estilo */
	        //context.$this.css("visibility", "visible");
	        context.$liCloned.css({
	        	//overflow: "hidden", 
	        	float: options.vertical ? "none" : "left"
	    	});
	        context.$ul.css({
	        	//position	: "relative",
	        	zIndex		: 1
	    	});
	        context.$this.css({
	        	//overflow	: "hidden", 
	        	//position	: "relative", 
	        	zIndex		: 99999
	        	//left		: 0
	    	});
	    	/* // Definições de estilo */
	        var liSize = options.vertical ? context.$liCloned.outerHeight(true) : context.$liCloned.outerWidth(true);
	        context.$ul
	        	.css(sizeCss, liSize * context.liLengthCloned)
	        	.css(animCss, -(context.current * liSize));
	        context.$this.css(sizeCss, liSize * context.visible);
	        context.clearInterval = function(){
	        	window.clearInterval(context.timer);
	        };
	        context.interval = function(){
	        	context.timer = window.setInterval(function () {
                	context.go(context.current + context.scroll);
                }, options.autoSlideshow || options.auto + options.speed);
	        };
	        context.resetInterval = function() {
	        	context.clearInterval();
	        	context.interval();
	        	context.slideshow = true;
	        };
	        context.visibleItens = function() {
	        	return context.$liCloned.slice(context.current, context.current + context.visible);
	        };
	        context.go = function (ir) {
	        	/* Define se a animação será p/ esquerda ou p/ cima. */
	        	var anim;
	        	if (!running) {
	        		if (options.beforeStart) {
	                	options.beforeStart.call(context);
	                };
	                // If circular we are in first or last, then goto the other end
	                if (context.circular) {
	                	// If first, then goto last
	                    if (ir <= options.start - context.visible - 1) {
	                    	context.$ul.css( animCss, -((context.liLengthCloned - (context.visible * 2)) * liSize) );
	                    	// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
	                        context.current = context.liLengthCloned - (context.visible * 2) - ((ir == options.start - context.visible - 1) ? - 1 : context.scroll);
	                    // If last, then goto first
	                    } else if (ir >= context.liLengthCloned - context.visible + 1) {
	                    	context.$ul.css( animCss, -(context.visible * liSize) );
	                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
	                        context.current = context.visible + ((ir == context.liLengthCloned - context.visible + 1) ? 1 : context.scroll);
	                    } else {
	                    	context.current = ir;
	                    };
	                /* Se não é circular */    
	                } else {
	                	/* Se a distância do início for menor que o passado como parâmetro define o item atual como zeroptions. */
	                	if (ir < 0) {
                			context.current = 0;
                		/* Se a distância do final for maior que o passado como parâmetro define o item atual como a diferença do total de itens menos a quantidade de itens vísiveis. */
                		} else if ( context.liLength < (ir + context.visible) ) {
                			context.current = context.liLength - context.visible;
                		} else if (context.liLength > context.visible) {
                			context.current = ir;
                		};
	                };                        
	                // If neither overrides it, the atual will still be "to" and we can proceed.
	                running 	= true;
	                anim 		= (animCss == "left") ? {left: -(context.current * liSize)} : {top: -(context.current * liSize)};
	                initial		= -(context.current * liSize);
	                change		= 0;
                	context.$ul.animate(
	                	anim,
	                    options.speed, 
	                    options.easing,
	                    function() {
	                        if (options.afterEnd) {
	                        	options.afterEnd.call(context);
	                        };
	                        running = false;
	                    }
	                );
	                /* Desabilita os botões somente quando não for circular; */
	                if(!context.circular) {
	                    context.$prev.removeClass(context.disableClass);
	                    context.$next.removeClass(context.disableClass);
	                    if ( !context.current ) {
	                    	context.$prev.addClass(context.disableClass);	
	                    } else if ( !(context.liLength - context.current - context.visible) ) {
	                    	context.$next.addClass(context.disableClass);
	                    	if (context.slideshow) {
	                    		context.$slideshow.click();
	                    	};
	                    };
	                };
	                /* // Desabilita os botões somente quando não for circular; */
	            };
	            return false;
	        };
	        /* Eventos em botões de anterior, próximo ou ir. */
	        if (context.$prev[0]) {
	        	context.$prev.click(function() {
	        		if (!context.$prev.hasClass(context.disableClass)) {
	        			if (options.auto || context.slideshow) {
		                    context.resetInterval();
		                };
		                context.direction = "prev";
		                return context.go(context.current - context.scroll);
	        		};
	            });	
	        };
	        if (context.$next[0]) {
	        	context.$next.click(function() {
	        		if (!context.$next.hasClass(context.disableClass)) {
	        			if (options.auto || context.slideshow) {
		                    context.resetInterval();
		                };
		                context.direction = "next";
		                return context.go(context.current + context.scroll);	
	        		};
	            });	
	        };
	        if (context.$go[0]) {
	        	$.each(context.$go, function(i, val) {
	                $(val).click(function() {
	                	if (options.auto || context.slideshow) {
		                    context.resetInterval();
		                };
		                $(this)
		                	.siblings()
		                	.removeClass(context.activeClass)
		                	.end()
		                	.addClass(context.activeClass);
		                context.direction = i;
		                return context.go( context.circular ? (context.visible + i) : (i * context.visible) );
	                });
	            });	
	        };
			if (context.$slideshow[0]) {
				context.$slideshow.click(function(){
					if (context.slideshow) {
						context.clearInterval();
						context.slideshow = false;
						if (options.stopSlideshow) {
							options.stopSlideshow.call(context);
		                };
					} else {
						context.interval();
		                context.slideshow = true;
		                context.direction = "next";
						if (options.startSlideshow) {
		                	options.startSlideshow.call(context);
		                };
					};
				});
			};
	        /* // Eventos em botões de anterior, próximo ou ir. */
	        if (options.mouseWheel && context.$this.mousewheel) {
				context.$this.mousewheel(function(e, d) {
					if (d > 0) {
						context.direction = "prev";
						return context.go(context.current - context.scroll);
					} else {
						context.direction = "next";
						return context.go(context.current + context.scroll);
					};
				});
	        };
	        if (options.auto) { context.interval(); };
	        if (options.load) { options.load.call(context); };
	    });
	};
	
	$.fn.carousel.defaults = {
		btnPrev			: ".carousel-prev",
        btnNext			: ".carousel-next",
        btnGo			: null,
        mouseWheel		: true,
        auto			: null,
        speed			: 200,
        easing			: null,
        vertical		: false,
        circular		: false,
        visible			: 3,
        start			: 0,
        scroll			: 1,
        beforeStart		: null,
        afterEnd		: null
	};
	
	if ($.fn.carousel) {
		$("#carousel-3 .carousel-overflow").carousel({
	        circular		: true,
	        visible			: 3,
	        start			: 0,
	        scroll			: 1
	    });
		$("#carousel-4 .carousel-overflow").carousel({
	        circular		: true,
	        visible			: 5,
	        start			: 0,
	        scroll			: 1
	    });
	};
})(jQuery)

/* Galeria de Imagens */
;(function($){
	$(function() {
		$(".gallery").each(function(){
			var $gallery 		= $(this),
				$image			= $gallery.find(".gallery-img"),
				//$thumbs			= $gallery.find(".gallery-thumb");
				$thumbs		= $gallery.find(".gallery-thumb li:not(.video)")
				$thumbs.find("a").click(function(event){
				var href	= $(this).attr("href"),
					img 	= new Image();
				event.preventDefault();		
				if (href === $image.children().attr("src")) {
					return;
				};
				$image.children().css("visibility", "hidden");
		        $(img)
			        .load(function () {
			        	$(this).hide();
			        	$image.children().remove();
			        	$image.removeClass("gallery-img-error").append(this);
			            $(this).fadeIn();
			        }).error(function () {
			        	$image.children().remove();
			        	$image.css("opacity", 0).addClass("gallery-img-error").animate({opacity	: 1});
			        }).attr("src", href);
			    $thumbs.find(".atv").removeClass("atv");
			    $(this).parents("li").addClass("atv");
			});
		});
    });
})(jQuery)

/* Abas */
;(function($){
	$.fn.tab = function(settings) {
	    var options = $.extend({}, $.fn.tab.defaults, settings);
	    return this.each(function() {
	    	var $list 			= $(this).find(options.list),
	    		$contents		= $(this).find(options.content);
			$list.find(options.trigger).click(function(event){
				event.preventDefault();
				var $this 		= $(this),
					$item		= $(this).parents(options.itemList),
					$content	= $( $this.attr(options.attrUrl) );
				if (!$item.hasClass(options.activeClass) && !$content.hasClass(options.activeClass)) {
					$list.find("." + options.activeClass).removeClass(options.activeClass);
					$contents.find("." + options.activeClass).hide().removeClass(options.activeClass);
					$item.addClass(options.activeClass);
					$content.addClass(options.activeClass).show();
				};
			});
			$(options.auxiliarList).find(options.trigger).click(function(event){
				var href	 = $(this).attr("href").match(/#[a-z0-9-_]*/gi)[0],
					$tab 	 = $( $list.find("[href='" + href + "']") ),
					$content = $(href),
					offset;
				if ($tab[0] && $content[0]) {
					event.preventDefault();
					offset = $tab.offset().top;
					$("html")
						.animate({
							scrollTop : offset
						}, offset * 2, function(){
							$tab.trigger("click");
						});
				};
			});
	    });
	};
	$.fn.tab.defaults = {
		activeClass	 : "atv",
		attrUrl		 : "href",
		auxiliarList : "#tab-rochedo",
		list		 : ".tab-list",
		itemList	 : "li",
		trigger		 : "a",
		content		 : ".tab-contents"
	};
	
	$(".tab").tab();
	$(function(){
		var hash	 = window.location.hash,
			$tab 	 = $("[href='" + hash + "']"),
			$content = $(hash),
			offset;
		if ($tab[0] && $content[0]){
			$tab.trigger("click");
		} else if ( window.location.href.indexOf("rochedo.aspx") !== -1 ) {
			_gaq.push(['_trackPageview', 'Quem_Somos']);
		};
	});
})(jQuery)

/* Expansivel */
;(function($){
	$.fn.expandable = function(settings) {
	    var options = $.extend({}, $.fn.expandable.defaults, settings);
	    return this.each(function() {
	    	var $dts 		= $(this).children("dt"),
	    		$dds		= $(this).children("dd");
	    	$dts.find("a").click(function(event){
	    		var $dt 	= $(this).parents("dt"),
	    			$dd		= $dt.next();
	    		event.preventDefault();
	    		if ( $dt.hasClass("atv") ) {
	    			$dd.slideUp(function(){
	    				$dt.removeClass("atv");
	    				$dd.removeClass("atv");
	    			});
	    		} else {
	    			if (options.unique) {
	    				$dts.removeClass("atv");
	    				$dds.removeClass("atv").slideUp("fast");	
	    			};
	    			$dt.addClass("atv");
	    			$dd.slideDown().addClass("atv");
	    		};
	    	});
	    });
	};
	$.fn.expandable.defaults = {
		unique : true
	};
	$(".expandable").expandable();
})(jQuery)

/* Placeholder */
;(function($){
	$.fn.placeholder = function() {
		if (!!("placeholder" in document.createElement("input"))) {
			return;
		};
		return this.each(function() {
			var $this = $(this),
				placeholder = $this.attr('placeholder'); // fallback p/ o placeholder
			$this
				.val(placeholder)
				.focus(function(){
					if ($this.val() === placeholder) {
						$this.val("");
					};
				}).blur(function(){
					if (!$this.val()) {
						$this.val(placeholder);
					};
				});
		});
	};
	if ($.fn.placeholder) {
		$("[placeholder]").placeholder();
	};
})(jQuery)

/* jqModal - Minimalist Modaling with jQuery * (http://dev.iceburg.net/jquery/jqModal/) * $Version: 03/01/2009 +r14 */
;(function($){
	$.fn.jqm = function (o) {
        var defaults = {
            overlay			: 60,
            overlayClass	: "jqmOverlay",
            closeClass		: "jqmClose",
            trigger			: ".jqModal",
            ajax			: null,
            ajaxText		: "",
            target			: null,
            modal			: null,
            toTop			: null,
            onShow			: null,
            onHide			: null,
            onLoad			: null
        };
        return this.each(function () {
            if (this._jqm) {
            	return $.jqm.hash[this._jqm].c = $.extend({}, $.jqm.hash[this._jqm].c, o);
            };
            s++;
            this._jqm = s;
            $.jqm.hash[s] = {
                c		: $.extend(defaults, $.jqm.params, o),
                a		: null,
                w		: $(this).addClass("jqmID" + s),
                s		: s
            };
            defaults.trigger && $(this).jqmAddTrigger(defaults.trigger);
        });
    };
    $.fn.jqmAddClose = function (e) {
        return hs(this, e, "jqmHide");
    };
    $.fn.jqmAddTrigger = function (e) {
        return hs(this, e, 'jqmShow');
    };
    $.fn.jqmShow = function (t) {
        return this.each(function () {
            t = t || window.event;
            $.jqm.open(this._jqm, t);
        });
    };
    $.fn.jqmHide = function (t) {
        return this.each(function () {
            t = t || window.event;
            $.jqm.close(this._jqm, t)
        });
    };
    $.jqm = {
        hash: {},
        open: function (s, t) {
        	var h 		= $.jqm.hash[s], 								// Hash
                c 		= h.c,											// Object config.
                cc 		= '.' + c.closeClass,							// Classe que fecha o modal
                z 		= h.w.css("z-index") !== "auto"? z : 3000,		// Caso tenha o z
                o 		= $("<div />").css({
	                	zIndex		: z - 1,
	                    opacity		: (c.overlay/100)
                });
            if (h.a) {
            	return false;
            };
            h.t = t; // Define o elemento que chamou o modal.
            h.a = true;
            h.w.css("z-index", z);
            if (c.modal) {
                if (!A[0]) L('bind');
                A.push(s);
            } else if (c.overlay > 0) {// Se tiver overlay
            	h.w.jqmAddClose(o);
            } else {// Deleta o overlay
            	o = false;
            };
			// Caso exista overlay adiciona no topo do body com sua respectiva classe.
            h.o = (o) && o.addClass(c.overlayClass).prependTo("form");
            // Caso for IE6 define o overlay como absoluto.
            if (ie6) {
                if (o) {
                    o = o.css({
                        position: "absolute"
                    })[0];
                    for (var y in {
                        Top		: 1,
                        Left	: 1
                    }) {
                    	//o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + "))+'px'");
                    };
                };
            };
			// Caso tenha ajax
            if (c.ajax) {
            	var r 		= c.target || h.w, // Local onde irá adicionar o html.
                    url 	= c.ajax, // URL do ajax.
                    r 		= (typeof r == 'string') ? $(r, h.w) : $(r), // Retorno um objeto jQuery com o elemento.
                    u 		= (url.substr(0, 1) == '@') ? $(t).attr(url.substring(1)) : url; // Usa o valor do atributo como URL
                r
                	.html(c.ajaxText) // Define o texto que irá aparecer enquanto carrega o conteúdo do ajax
                	.load(url, function() {
	                    c.onLoad && c.onLoad.call(this, h); // Chama o onload.
	                    cc && h.w.jqmAddClose($(cc, h.w)); // Seta a função que fecha o modal.
	                    e(h); // Adiciona o focus no primeiro input visível. Caso for o ie6 define o iframe.
                	});
            } else if (cc) {
            	h.w.jqmAddClose($(cc, h.w)); // Seta a função que fecha o modal.
            };
            if (c.toTop && h.o) h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
            (c.onShow) ? c.onShow(h) : h.w.show();
            e(h); // Insere o iframe caso for ie6.
            return false;
        },
        close: function (s) {
            var hash = $.jqm.hash[s];
            if (!hash.a) {
            	return false;
            };
            hash.a = false;
            if (A[0]) {
                A.pop();
                if (!A[0]) L('unbind');
            };
            if (hash.c.toTop && hash.o) {
            	$('#jqmP' + hash.w[0]._jqm).after(hash.w).remove();
            };
            if (hash.c.onHide) {
            	hash.c.onHide(hash);
            } else {
                hash.w.hide();
                hash.o && hash.o.remove();
            };
            return false;
        },
        params: {}
    };
    var s = 0,
        //H = $.jqm.hash,
        A = [],
        ie6 = $.browser.msie && ($.browser.version == "6.0"),
        //F = false,
        i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({
            opacity: 0
        }),
        e = function (h) {
            if (ie6) {
            	if (h.o) {
            		h.o.html('<p style="width:100%;height:100%"/>').prepend(i);
            	} else if (!$('iframe.jqm', h.w)[0]) {
            		h.w.prepend(i);
            	};
            };
            f(h);
        },
        f = function (h) {
            try {
                $(":input:visible", h.w)[0].focus();
            } catch (_) {}
        },
        L = function (t) {
            $()[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m);
        },
        m = function (e) {
            var h = $.jqm.hash[A[A.length - 1]],
                r = (!$(e.target).parents('.jqmID' + h.s)[0]);
            if (r) f(h);
            return !r;
        },
        hs = function (w, t, c) {
            return w.each(function () {
                var s = this._jqm;
                $(t).each(function () {
                    if (!this[c]) {
                        this[c] = [];
                        $(this).click(function () {
                            for (var i in {
                                jqmShow: 1,
                                jqmHide: 1
                            }) for (var s in this[i]) if ($.jqm.hash[this[i][s]]) $.jqm.hash[this[i][s]].w[i](this);
                            return false;
                        });
                    };
                    this[c].push(s);
                });
            });
        };
	
    /* Extras */
    $(".jqmWindow").jqm({
		onShow: initModal,
		onHide: exitModal
	});
	$("#sejaAssistencia").click(function(event){
		event.preventDefault();
		$("#modal-assistencia").jqmShow();
	});
	
	$(".video a").click(function(event){
		event.preventDefault();
		$("#modal-video").jqmShow();
		$(".videoFrame").attr('src', $(this).attr("href"));
		$(".ttlModalVideo").html($(".ttlProduto").html());
	});





    function initModal(hash){
		var winWidth 		= $(window).width(),
			winHeight 		= $(window).height(),
			modalWidth 		= hash.w.width(),
			modalHeight 	= hash.w.height(),
			winScroll 		= $(window).scrollTop(),
			left 			= (modalWidth > winWidth) ? 0 : ((winWidth - modalWidth) /2),
			top 			= winScroll + ((modalHeight > winHeight) ? 50 : ((winHeight - modalHeight) / 2));
			
		hash.w
			.css({
				top 		: top,
				left 		: left
			})
			.fadeIn();
	};
	// FUNÇÕES P/ FINALIZAR MODAL
	function exitModal(hash){
		hash.o.hide().remove();
		hash.w.hide();
	};
	/* // Extras */
})(jQuery)

/* FORMS */
;(function($){
	if( ( !("pointerEvents" in document.body.style) && /ie(7|8)/.test(document.documentElement.className) ) || ( !!("attachEvent" in document.body) && !!("pointerEvents" in document.body.style) ) ) {
		document.documentElement.className += " no-pointer-event";
		$(".form-select-custom").each(function(){
			var $button 		= $("<span class='button' />"),
				$text 			= $("<span class='text' />"),
				$select			= $(this).find("select");
			$(this).prepend(
				$button,
				$text
			);
			if ( $select.children(":selected")[0] ) {
				$text.text( $select.children(":selected").text() );
			} else {
				$text.text( $select.children(":first").text() );
			};
			$select.change(function(){
				$text.text( $(this).children("option:selected").text() );
			});
		});
	};
})(jQuery)

/* Border Radius Support */
;(function(){
	var borderRadius = "borderRadius WebkitBorderRadius MozBorderRadius".split(" "),
		support		 = false;
	for (var prop in borderRadius) {
		if (borderRadius[prop] in document.body.style) {
			support = true;
			break;
		};
	};
	if (!support) {
		document.documentElement.className += " no-border-radius";
	};
})()

$('document').ready(function () {
	//Links Externos
    $('a[rel="external"]').click(function () {
        window.open($(this).attr('href'));
        return false;
    });
    //retira icone separador do menu...
    $(".setFinal li:last-child").addClass('final');
});


