//Insert Flash Function
function insert_flash(file,div,width,height,transparent)
{
	var flashvars = {};
	if(transparent==1)
	{
		var params = {
		  wmode: "transparent",quality: "high"
		};
	}
	else
	{
	var params = {
	  quality: "high"
	  };
	}
		
	var attributes = {};
	swfobject.embedSWF(""+file+"", ""+div+"", ""+width+"", ""+height+"", "9.0.0","flash/expressInstall.swf", flashvars, params, attributes);
}
/*Tooltips*/
function initTooltips(){ $('a.hasTooltip[title!=""], span.hasTooltip[title!=""], div.hasTooltip[title!=""]').tipsy({gravity: $.fn.tipsy.autoNS}); $('a.hasTooltip.horizontalTipsy').tipsy({gravity: $.fn.tipsy.autoWE});/*, input[title]*//* $('a.horizTip').tipsy({gravity: "e"});*/ }
//External Links
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}

function share_click(type, url, title)
{
	var share_link;
	switch(type)
	{
		case "stumble":
			share_link = "http://www.stumbleupon.com/submit?url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "twitter":
			share_link = "http://twitter.com/home?status="+encodeURIComponent((url==""?location.href:url))+"+"+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "friend":
			share_link = "http://www.friendfeed.com/share?url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "delicious":
			share_link = "http://del.icio.us/post?url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"&notes=";
		break;
		case "facebook":
			share_link = "http://www.facebook.com/share.php?u="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "digg":
			share_link = "http://www.digg.com/submit?phase=2&url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "linkedin":
			share_link = "http://www.linkedin.com/shareArticle?mini=true&url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"&summary=&source=";
		break;
		case "gbuzz":
			share_link = "http://www.google.com/buzz/post?url="+encodeURIComponent((url==""?location.href:url))+"&title="+encodeURIComponent((title==""?document.title:title))+"";
		break;
		case "technorati":
			share_link = "http://technorati.com/signup/?f=favorites&amp;Url="+encodeURIComponent((url==""?location.href:url))+"";
		break;
		case "myspace":
			share_link = "http://www.myspace.com/index.cfm?fuseaction=postto&t=" + encodeURIComponent((title==""?document.title:title))+"&c=&u=" + encodeURIComponent((url==""?location.href:url))+"";
		break;
		case "blogger":
			share_link = "http://www.blogger.com/blog_this.pyra?t=" + encodeURIComponent((title==""?document.title:title))+"&u=" + encodeURIComponent((url==""?location.href:url))+"";
		break;
	}
	window.open(share_link, 'sharer', 'toolbar=0,status=0,width=640,height=436');
}
var api, api2; 
$(window).load(function(){
	
	//ACTIVATE POPEYE GALLERY
	$('img.youtube_video').each(function(){
		if($(this).attr("alt") != ''){
			var url = $.jYoutube($(this).attr("alt"),"small");
			$(this).attr("src", url);
			$(this).attr("alt", "");
		}
	});
	$('.ppy3').popeye({slideshow: 10000, navigation:'hover',duration:1000});
	$('.ppy2').popeye(); 	
	
	
	$('.scrollPane').css("overflow","auto");
	var scrollPane = $('.scrollPane');
	scrollPane.jScrollPane({verticalDragMinHeight:89, verticalDragMaxHeight:240,  autoReinitialise:true, animateTo:true});
	
	$('.scrollPane2').css("overflow","hidden");
	var scrollPane2 = $('.scrollPane2');
	scrollPane2.jScrollPane({verticalDragMinHeight:57, verticalDragMaxHeight:237,  autoReinitialise:true, animateTo:true});
	
	api = scrollPane.data('jsp');
	api2 = scrollPane2.data('jsp');
	
	initTooltips();
	
	/*Scroll-Pane*/
	//$('#paneagenda').jScrollPane({dragMinHeight:83, dragMaxHeight:83});
	
	$.watermarker.setDefaults({ color: '#D7D7D7', left: 5, top:7 });
	$(".jq_watermark").watermark();
	
	var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 40, "firstpos2": 15};			
	$.pnotify.defaults.pnotify_insert_brs = false;
	$.pnotify.defaults.pnotify_width = "350px";
	$.pnotify.defaults.pnotify_title = '';
	$.pnotify.defaults.pnotify_hide = true;
	$.pnotify.defaults.pnotify_mouse_reset = true;
	$.pnotify.defaults.pnotify_before_close = function(pnotify){};
	$.pnotify.defaults.pnotify_opacity = 0.9;
	$.pnotify.defaults.pnotify_shadow = false;
	$.pnotify.defaults.pnotify_min_height = "30px";
	$.pnotify.defaults.pnotify_animation = {effect_in: 'fade', effect_out: 'fade'};//function(status, callback, pnotify){ }
	$.pnotify.defaults.pnotify_animate_speed = 1000;
	$.pnotify.defaults.pnotify_delay = 25000;
	$.pnotify.defaults.pnotify_history = false;
	$.pnotify.defaults.pnotify_stack = stack_bottomright;
			
	/*Load External Links*/
	externalLinks();
	var slideEffect = "easeInOutExpo";
		
	/*SIGNATURE CONTAINER*/
	$("#signatureContainer").mouseover(function(){
		$(this).stop().animate({'right':'0'},{queue:false, duration:500});										
	}).mouseout(function(){
		$(this).stop().animate({'right':'-176px'},{queue:false, duration:500});	
	});
		
	/*$('img.youtube_video').each(function(){
		if($(this).attr("alt") != ''){
			var url = $.jYoutube($(this).attr("alt"));
			$(this).attr("src", url);
			$(this).attr("alt", "");
		}
	});*/
	
	//VERTICALLY ALIGN
	$(".carDescription").vAlign();
	
	
	/*DESIGN JQTRANSFORM*/
	$('form').jqTransform({imgPath:'design/jqtransformplugin/'});
	//After Load jqtransform - remove Loader
	$('#search').removeClass('loader');
	$('#newsletterBox').removeClass('loader');
	$('#advancedSearchBox').css('display','none');
	
	//Define Width of inputs in Newsletter With jqtransform
	var myW = 292;
	var myWrapper = myW+18;
	$(".input1").css("width", myW);
	$(".input1").parents(".jqTransformInputWrapper").css("width", myWrapper);
	
	//Make Forms Visible
	$('form').css("visibility","visible");
	
	var advancedSearchBox = 0;	
	function toggleAdvancedSearch()
	{
		if($('#advancedSearch:checked').val())
		{
			$('.radiovalue').removeClass('active');
			$('#advancedSearch').parent('.jqTransformRadioWrapper').next('.radiovalue').addClass('active');
			
			//$("#sentenceTitle").addClass("active");
			//$("#sentenceText").addClass("active");
			
			$('#searchBtnSmall')/*.stop()*/.hide();
			
			//$("#pvpContainer").jqTransSelect();
			$("#pvpContainer .jqTransformSelectWrapper, #pvpContainer .jqTransformSelectWrapper div span")/*.stop()*/.animate({width:'305px'},500);
			$("#pvpContainer .jqTransformSelectWrapper ul")/*.stop()*/.animate({width:'303px'},500);
			//See if NewsletterBox is open and close it
			if(showNewsletterForm==1){
				$('#newsletterBox').fadeToggle();
				$('#removeNewsletterBox').fadeToggle();
				$('#newsletter').removeClass("active");
				showNewsletterForm =0;
			}
			//$('#advancedSearchBox').show('fast');
			$('#advancedSearchBox').css({"display":"block"}).animate({opacity:1},200);
			
			advancedSearchBox = 1;
			$("#handMadeCar").addClass("active").hide();
			$("#advancedSearchBox").css("height",$(window).height()-((308-$(window).scrollTop())+36) +"px");
			$("#handMadeCar2").vAlign2();
		}
		else{
			
			$('.radiovalue').addClass('active');
			$('#advancedSearch').parent('.jqTransformRadioWrapper').next('.radiovalue').removeClass('active');
			
			$("#handMadeCar").removeClass("active").show();
			//$("#sentenceTitle").removeClass("active");
			//$("#sentenceText").removeClass("active");
			//$('#advancedSearchBox').hide('fast');
			$('#advancedSearchBox').animate({opacity:0},200).css({"display":"none"});
			$("#pvpContainer .jqTransformSelectWrapper, #pvpContainer .jqTransformSelectWrapper div span")/*.stop()*/.animate({width:'148px'},500, function(){ $('#searchBtnSmall')/*.stop()*/.show(); });
			$("#pvpContainer .jqTransformSelectWrapper ul")/*.stop()*/.animate({width:'146px'},500);
			
			advancedSearchBox = 0;
		}
	}
	
	/*ONCLICK LABEL OF RADIO BUTTON CHANGE CLASS*/
	$('.radiovalue, .jqTransformRadio').click(function(){
		$('.radiovalue').removeClass('active');
		$(this).addClass('active');
		
		$(this).parent().parent().parent().find('.radiovalue').removeClass('active');
		$(this).parent().parent().find('.radiovalue').addClass('active');
		
		toggleAdvancedSearch();		
	});
	/*SHOW ADVANCED SEARCH BOX IF CHECKED*/
	toggleAdvancedSearch();
	
	//START SLIDER
	function slideRangeUpdate(event, ui)
	{
		var marginMax = $("#sliderRange").slider("option","max");//Get Min value
		var marginMin = $("#sliderRange").slider("option","min");//Get Max value
		var factor = marginMax-marginMin;//Get difference
		var widthSlider = $("#sliderRange").width();//Get Slider Width
		var multipleFactor = widthSlider/factor; 
		var beginFactor = 30;
		var margin1 = ((ui.values[0]-marginMin)*multipleFactor)-beginFactor;
		var margin2 = (((ui.values[1]-marginMax)*multipleFactor)-beginFactor)+widthSlider;
		$("#amount1").html( "" + ui.values[0] + "");
		$("#amount2").html( "" + ui.values[1] + "");
		$("#valueSlider_1").val( "" + ui.values[0] + "");
		$("#valueSlider_2").val( "" + ui.values[1] + "");
		$("#amount1").css("margin-left",margin1+"px");
		$("#amount2").css("margin-left",margin2+"px");
	}
	$("#sliderRange").slider({
		range: true,
		min: ((new Date()).getFullYear()-31),
		max: (new Date()).getFullYear(),
		values: [ ((new Date()).getFullYear()-31), (new Date()).getFullYear() ],
		slide: slideRangeUpdate,
		change: slideRangeUpdate
	});
	
	function slideRangeUpdate2(event, ui)
	{
		var marginMax = $("#sliderRange2").slider("option","max");//Get Min value
		var marginMin = $("#sliderRange2").slider("option","min");//Get Max value
		var factor = marginMax-marginMin;//Get difference
		var widthSlider = $( "#sliderRange2").width();//Get Slider Width
		var multipleFactor = widthSlider/factor; 
		var beginFactor = 30;
		var margin1 = ((ui.values[0]-marginMin)*multipleFactor)-beginFactor;
		var margin2 = (((ui.values[1]-marginMax)*multipleFactor)-beginFactor)+widthSlider-10;
		$("#amount3").html( "" + ui.values[0] + "");
		$("#amount4").html( "" + ui.values[1] + "");
		$("#valueSlider_3").val( "" + ui.values[0] + "");
		$("#valueSlider_4").val( "" + ui.values[1] + "");
		$("#amount3").css("margin-left",margin1+"px");
		$("#amount4").css("margin-left",margin2+"px");
	}
	$("#sliderRange2").slider({
		range: true,
		min: 0,
		max: 300000,
		step: 10000,
		values: [ 0, 300000 ],
		slide: slideRangeUpdate2,
		change: slideRangeUpdate2
	});
	
	function slideRangeUpdate3(event, ui)
	{
		var marginMax = $("#sliderRange3").slider("option","max");//Get Min value
		var marginMin = $("#sliderRange3").slider("option","min");//Get Max value
		var factor = marginMax-marginMin;//Get difference
		var widthSlider = $( "#sliderRange2").width();//Get Slider Width
		var multipleFactor = widthSlider/factor; 
		var beginFactor = 20;
		var margin1 = ((ui.values[0]-marginMin)*multipleFactor)-beginFactor-10;
		var margin2 = (((ui.values[1]-marginMax)*multipleFactor)-beginFactor)+widthSlider-10;
		$("#amount5").html( "" + ui.values[0] + "");
		$("#amount6").html( "" + ui.values[1] + "");
		$("#valueSlider_5").val( "" + ui.values[0] + "");
		$("#valueSlider_6").val( "" + ui.values[1] + "");
		$("#amount5").css("margin-left",margin1+"px");
		$("#amount6").css("margin-left",margin2+"px");
	}
	$("#sliderRange3").slider({
		range: true,
		min: 10,
		max: 1300,
		step: 10,
		values: [ 10, 1300 ],
		slide: slideRangeUpdate3,
		change: slideRangeUpdate3
	});
	
	$("#amount1").html( "" + $("#sliderRange").slider( "values", 0 ));
	$("#amount2").html( "" + $("#sliderRange").slider( "values", 1 ));
	$("#amount3").html( "" + $("#sliderRange2").slider( "values", 0 ));
	$("#amount4").html( "" + $("#sliderRange2").slider( "values", 1 ));
	$("#amount5").html( "" + $("#sliderRange3").slider( "values", 0 ));
	$("#amount6").html( "" + $("#sliderRange3").slider( "values", 1 ));
	
	/*$("#valueSlider_1").val( "" + $("#sliderRange").slider( "values", 0 ));
	$("#valueSlider_2").val( "" + $("#sliderRange").slider( "values", 1 ));
	$("#valueSlider_3").val( "" + $("#sliderRange2").slider( "values", 0 ));
	$("#valueSlider_4").val( "" + $("#sliderRange2").slider( "values", 1 ));
	$("#valueSlider_5").val( "" + $("#sliderRange3").slider( "values", 0 ));
	$("#valueSlider_6").val( "" + $("#sliderRange3").slider( "values", 1 ));*/
	
	//Vertical Ticker of Testimonials
	$('.vtickerClass').vTicker({
	   speed: 500,
	   pause: 10000,
	   showItems: 1,
	   animation: 'fade',
	   mousePause: false,
	   height: 100,
	   direction: 'up'
	});
	$('.vtickerClass').css("visibility","visible");
	
	//Show Newsletter - buttons to open and close and change class of newsletter button
	var showNewsletterForm = 0;

	/*$('#showNewsletterForm').click(function(){
		if(showNewsletterForm==0){
			$('#newsletterBox').fadeToggle();
			$('#newsletter').addClass("active");
			showNewsletterForm=1;
		}
	});*/
	/*$('#closeButtonNewsletter').click(function(){
		if(showNewsletterForm==1){
			$('#newsletterBox').fadeToggle();
			$('#newsletter').removeClass("active");
			showNewsletterForm =0;
		}
	});*/
	
	/*$("#carHighlight .carContent, #carsArchive .carContent").click(function(event) {
		event.preventDefault();
		var str = $(this).find("a").attr("href");
		if(str.length > 0){
			window.location = $(this).find("a").attr("href");
		}
	});*/
	
	$("#newsletterList .newsletterLine").click(function(event) {
		event.preventDefault();
		var str = $(this).find("a").attr("href");
		if(str.length > 0){
			window.open($(this).find("a").attr("href"), '_blank');
		}
	});
	
	//SHOW UPPER DIV WHEN SIDE PANEL BUTTONS ARE PRESSED
	$(".newsletter_Button, .newsletter_remove_Button").live('click',function(event){
		var $aux = $(this).attr("class").split("_");
		var $href = $aux[0];
		if($aux.length>2){var $action = $aux[1]; $href=$href+"/"+$action;}
		var $this = $(this);
		var container = $this.attr("rev");
		$(".formContent").not(container).fadeOut(500,slideEffect);
			
		var timeoutID = window.setTimeout(function(){
			var shown = false;
			if($(container).is(':visible')) { shown = true; }
			$(container).addClass("loader").html("");
			$this.parent("section").addClass("active");
			$(container).fadeToggle(500,slideEffect, function(){
				if(!shown)
				{
					$this.parent("section").addClass("active");
					$.ajax({
						type: "POST",
						url: "/ajax/action/"+$href,
						cache: false,
						success: function(html){
							$(container).removeClass("loader").html(html);//.fadeOut("fast",function(){ $(this).html(html); $(this).fadeIn(500); });
							initTooltips(); 
							$(container+" a.closeDivButton").live('click',function(){
								/*$(container).slideUp(1000,slideEffect);
								$(container+" .contentHiddenContainer").html("");
								$this.parent("div").removeClass("active");
								$this.parent().parent("div").removeClass("current");*/
								$this.first().click();
							});							
						}
					});
				}
				else
				{
					$(container).removeClass("loader");	
					$this.parent("section").removeClass("active");
				}
			});
			window.clearTimeout(timeoutID);
		}, 500);
		event.preventDefault();
	});
	
	function submitSearch()
	{
		var semantic = 1;
		var form = this;
		var els = semantic ? form.getElementsByTagName('*') : form.elements;
		var i,j,n,v,el,max,jmax,a=[];
		for(i=0, max=els.length; i < max; i++) {
			el = els[i];
			n = el.name;
			if (!n) {
				continue;
			}
			v = $.fieldValue(el, true);
			if (v && v.constructor == Array) {
				for(j=0, jmax=v.length; j < jmax; j++) {
					a.push({name: n, value: v[j]});
				}
			}
			else if (v !== null && typeof v != 'undefined' && v != "") {
				a.push({name: n, value: v});
			}
		}
		var params = $.param(a);
		//var params = form.serializeAnything();
		window.location = "/pt/pesquisa/?"+params;
		//event.preventDefault();
		return false;
	}
	//$('#search_form').attr("onsubmit","javascript:submitSearch()");
	$('#search_form').submit(submitSearch);
	
	$('#equipmentButton a').click(function(){
		if($('#equipmentButton a').hasClass('active')){}else{
			
			$("#commentButton a").removeClass('active');
			$(this).addClass('active');
			
			$('#commentContent').hide();
			$('#equipmentContent').show();
		}
	});
	
	$('#commentButton a').click(function(){
		if($('#commentButton a').hasClass('active')){}else{
			
			$("#equipmentButton a").removeClass('active');
			$(this).addClass('active');
			
			$('#equipmentContent').hide();
			$('#commentContent').show();
		}
	});
	
	$("div#carContentLeft div#carInfo").css("height",$(window).height()-412 +"px");
});
//ACTIVATE STYLE FOR DROPDOWN
function styleSelectBox(element){
	$(element).jqTransform({imgPath:'design/jqtransformplugin/'});
}
function getCarModels(form,product,brand)
{
	$(form + " #carModel").parent().find("div").find("span").html("Aguarde...");
	$(form + " #carModel").parent().find("ul").remove();
	$.ajax({
		type: "POST",
		url: "/ajax/action/search/get-models",
		data: "product="+product+"&brand="+brand+"&form="+form, 
		cache: false,
		success: function(html){
			//$("#modelsContainer").html(html);
			$(form + ' #carModel').html(html);
			var sty = $(form + " #carModel").parent().attr("style");
			var sels = $(form + " #carModel").removeClass("jqTransformHidden"); 
			var $par = $(form + " #carModel");
			$par.parent().replaceWith($par);
			sels.jqTransSelect();
			$(form + " #carModel").parent().attr("style",sty);
			initTooltips(); 
			//styleSelectBox("#carModel");
		}
	});
}
//On resize, format height of advancedSearchBox
$(window).bind('resize', function(){
	$("#advancedSearchBox").css("height",$(window).height()-((308-$(window).scrollTop())+36) +"px");
	$("#handMadeCar2").vAlign2();
	
	var min_h = ($(window).height()-((412-$(window).scrollTop())) < 328 ? 328 : $(window).height()-((414-$(window).scrollTop())));
	$("div#carContentLeft div#carInfo").css("height",min_h +"px");
});
$(window).bind('scroll', function(){
	$("#advancedSearchBox").css("height",$(window).height()-((308-$(window).scrollTop())+36) +"px");
	$("#handMadeCar2").vAlign2();
	
	var max_h = ($(window).height()-((412-$(window).scrollTop())) > 328 ? 328 : $(window).height()-((414-$(window).scrollTop())));
	$("div#carContentLeft div#carInfo").css("height",max_h +"px");
});

$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
			continue;
		}
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (successful === undefined) {
		successful = true;
	}
	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1)) {
			return null;
	}
	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) {
			return null;
		}
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) { // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				}
				if (one) {
					return v;
				}
				a.push(v);
			}
		}
		return a;
	}
	return $(el).val();
};
(function($) {
    $.fn.serializeAnything = function() {
        var toReturn    = [];
        var els         = $(this).find(':input').get();
        $.each(els, function() {
            if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
                var val = $(this).val();
                toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
            }
        });   
        return toReturn.join("&").replace(/%20/g, "+");
    }
})(jQuery);
