// car drop down
$(function(){
    var $resultsoutput = $('#results');
    $('#year').change(function getmakes(){
        var vehyear = $("#year").val();
        $("#model").html('<option value="">-- All Models --</option>');
        $.ajax({
               url: "car-makes.php",
               global: false,
               type: "POST",
               async: false,
               dataType: "html",
               data: "year="+vehyear, //the name of the $_POST variable and its value
               success: function (response) //'response' is the output provided
                           {
                        //counts the number of dynamically generated options
                        var dynamic_options = $("*").index( $('.dynamic')[0] );
                        //removes previously dynamically generated options if they exists (not equal to 0)
                        if (dynamic_options != (-1)) $(".dynamic").remove();
                        $("#make").html(response);
                        $(".first").attr({selected: ' selected'});
                        
                       }
              });
              return false
    });
    
    $('#make').change(function getmodels(){
        var vehyear = $("#year").val();
        var vehmake = $("#make").val();
        $.ajax({
               url: "car-models.php",
               global: false,
               type: "POST",
               async: false,
               dataType: "html",
               data: "year="+ vehyear+"&make="+vehmake, //the name of the $_POST variable and its value
               success: function (response) //'response' is the output provided
                           {
                         //counts the number of dynamically generated options
                        var dynamic_options = $("*").index( $('.dynamic')[0] );
                        //removes previously dynamically generated options if they exists (not equal to 0)
                        if (dynamic_options != (-1)) $(".dynamic").remove();
                        $("#model").html(response);
                        $(".first").attr({selected: ' selected'});                        
                       }
              });
              return false
    });
    $('#model').change(function getstyles(){
        var vehyear = $("#year").val();
        var vehmake = $("#make").val();
        var vehmodel = $("#model").val();
        $.ajax({
               url: "car-trims.php",
               global: false,
               type: "POST",
               async: false,
               dataType: "html",
               data: "year="+ vehyear+"&make="+vehmake+"&model="+ vehmodel, //the name of the $_POST variable and its value
               success: function (response) //'response' is the output provided
                           {
                        //counts the number of dynamically generated options
                        var dynamic_options = $("*").index( $('.dynamic')[0] );
                        //removes previously dynamically generated options if they exists (not equal to 0)
                        if (dynamic_options != (-1)) $(".dynamic").remove();
                        $("#trim").html(response);
                        $(".first").attr({selected: ' selected'});
                        
                       }
              });
              return false
    });               

    
    $('form#reviewForm select').change(function(){
        if (!$(this).val()){ 
            $resultsoutput.html(''); 
            return; 
        }
        var content = "<b>Selected vehicle:</b> " 
            + $('#year').val() + ' '
            + $('#make').val() + ' '
            + $('#model').val() + ' '
            + $('#trim').val();
        $resultsoutput.html(content);    
    });
});



/* GPS.jquery
//////Copyright © 2009 Bird Wing Productions, http://www.birdwingfx.com//////////
*/
// for pop up google map
(function($) {
    
    $.GoogleMapObjectDefaults = {        
        zoomLevel: 10,
	imagewidth: 50,
	imageheight: 50,
	center: '2000 Florida Ave NW Washington, DC 20009-1231',
	start: '#start',
        end: '#end',
	directions: 'directions',
        submit: '#getdirections',
	tooltip: 'false',
	image: 'false'
    };

    function GoogleMapObject(elementId, options) {
        /* private variables */
        this._inited = false;
        this._map = null;
        this._geocoder = null;
	
        /* Public properties */
        this.ElementId = elementId;
        this.Settings = $.extend({}, $.GoogleMapObjectDefaults, options || '');
    }

    $.extend(GoogleMapObject.prototype, {
        init: function() {
            if (!this._inited) {
                if (GBrowserIsCompatible()) {
                    this._map = new GMap2(document.getElementById(this.ElementId));
                    this._map.addControl(new GSmallMapControl());
                    this._geocoder = new GClientGeocoder();
                }
		
                this._inited = true;
            }
        },
        load: function() {
            //ensure existence
            this.init();
	    
            if (this._geocoder) {
                //"this" will be in the wrong context for the callback
                var zoom = this.Settings.zoomLevel;
                var center = this.Settings.center;
		var width = this.Settings.imagewidth;
		var height = this.Settings.imageheight;
                var map = this._map;
		
		if (this.Settings.tooltip != 'false') {
		    var customtooltip = true;
		    var tooltipinfo = this.Settings.tooltip;
		}
		
		if (this.Settings.image != 'false') {
		    var customimage = true;
		    var imageurl = this.Settings.image;
		}
		
                this._geocoder.getLatLng(center, function(point) {
                    if (!point) { alert(center + " not found"); }
                    else {
                        //set center on the map
                        map.setCenter(point, zoom);
			
			if (customimage == true) {
			    //add the marker
			    var customiconsize = new GSize(width, height);
			    var customicon = new GIcon(G_DEFAULT_ICON, imageurl);
			    customicon.iconSize = customiconsize;
			    var marker = new GMarker(point, { icon: customicon });
			    map.addOverlay(marker);
			} else {
			    var marker = new GMarker(point);
			    map.addOverlay(marker);
			}
			
			if(customtooltip == true) {
			    marker.openInfoWindowHtml(tooltipinfo);
			}
                    }
                });
            }
	    
	    
            //make this available to the click element
            $.data($(this.Settings.submit)[0], 'inst', this);
	    
            $(this.Settings.submit).click(function(e) {
                e.preventDefault();
                var obj = $.data(this, 'inst');
		var outputto = obj.Settings.directions;
                var from = $(obj.Settings.start).val();
                var to = $(obj.Settings.end).val();
		map.clearOverlays();
		var gdir = new GDirections(map, document.getElementById(outputto));
		gdir.load("from: " + from + " to: " + to);
		
                //open the google window
                //window.open("http://maps.google.com/maps?saddr=" + from + "&daddr=" + to, "GoogleWin", "menubar=1,resizable=1,scrollbars=1,width=750,height=500,left=10,top=10");
            });
	    
            return this;
        }
    });

    $.extend($.fn, {
        googleMap: function(options) {
            // check if a map was already created
            var mapInst = $.data(this[0], 'googleMap');
            if (mapInst) {
                return mapInst;
            }
	    
            //create a new map instance
            mapInst = new GoogleMapObject($(this).attr('id'), options);
            $.data(this[0], 'googleMap', mapInst);
            return mapInst;
        }
    });
})(jQuery);




//jquery metadata
(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);




// jquery clearfield plugin
/**
   http://www.donotfold.be
 * @example: $('selector').clearField();
 * @example: $('selector').clearField({ blurClass: 'myBlurredClass', activeClass: 'myActiveClass' }); 
*/

(function($) {
	
	$.fn.clearField = function(settings) {
		
		settings = jQuery.extend({
			blurClass: 'clearFieldBlurred',
			activeClass: 'clearFieldActive',
			attribute: 'rel',
			value: ''
		}, settings);
		
		return $(this).each(function() {
						
			var el = $(this);		
			settings.value = el.val();
		
			if(el.attr(settings.attribute) == undefined) {
				el.attr(settings.attribute, el.val()).addClass(settings.blurClass);
			} else {
				settings.value = el.attr(settings.attribute);
			}
			
			el.focus(function() {
				
				if(el.val() == el.attr(settings.attribute)) {
					el.val('').removeClass(settings.blurClass).addClass(settings.activeClass);
				}
				
			});
			
			
			el.blur(function() {
				
				if(el.val() == '') {
					el.val(el.attr(settings.attribute)).removeClass(settings.activeClass).addClass(settings.blurClass);
				}
				
			});
			
			
		});
		
	};
	
})(jQuery);



// tooltip
this.tooltip = function(){	
			
		xOffset = 90;
		yOffset = -30;		
		
   $("a.tooltip").hover(function(e){											  
	   this.t = this.title;
	   this.title = "";									  
	   $("body").append("<p id='tooltip'>"+ this.t +"</p>");
	   $("#tooltip")
		   .css("top",(e.pageY - xOffset) + "px")
		   .css("left",(e.pageX + yOffset) + "px")
		   .fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


$(document).ready(function() {
		
	// colorbox
	//$(".dealeradd-iframe").colorbox({width:725, height:480, opacity:0.30, iframe:true, onClosed:function(){ location.reload(true); }});
	$("a[rel='gal']").colorbox({opacity:0.30});
	$(".fancy-image").colorbox({opacity:0.30});
	$(".popup-page").colorbox({width:725, height:480, opacity:0.30, iframe:true});
	//$(".popup-login").colorbox({width:520, height:540, opacity:0.30, iframe:true});
	$(".login").colorbox({width:540, height:560, opacity:0.30, iframe:true, 
        onClosed:function(){ location.reload(true); } 
	 });

	
	// start equal height
    //equalHeight($(".equal-height"));
	
	// start the tooltip on page load
	tooltip();
						
	// jquery validation plugin
	$.metadata.setType("attr", "validate");
	$("#reviewForm").validate();
	$("#contactForm").validate();
	$("#srchForm").validate();
	$("#zipForm").validate();
	$("#carsearchForm").validate({
		rules: {
			postalcode: {
				postalcode: true
			}
		}
	});
	
	// clear form plugin
	$('.clearfield').clearField();

});	


/**
* hoverIntent r5 
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

// activate hoverintent for top menu 
// delay for megamenu with hoverIntent
//<![CDATA[
$(document).ready(function() { 
  
  function addMega(){
   $(this).addClass("onhover");
  }

  function removeMega(){
    $(this).removeClass("onhover");
  }

  var megaConfig = {
    interval: 200,
    sensitivity: 10,
    over: addMega,
    timeout: 200,
    out: removeMega
  };
  
   $("#topnav li").hoverIntent(megaConfig);
      
});
//]]>



/*
 * 	easyListSplitter 1.0.2 - jQuery Plugin
 *	written by Andrea Cima Serniotti	
 *	http://www.madeincima.eu
 */
var j=1; (function(a){a.fn.easyListSplitter=function(h){var k={colNumber:2,direction:"vertical"};this.each(function(){a(this);var b=a.extend(k,h),e=a(this).children("li").size(),g=Math.ceil(e/b.colNumber);e=a(this).attr("class");for(i=1;i<=b.colNumber;i++){if(i==1)a(this).addClass("listCol1").wrap('<div class="listContainer'+j+'"></div>');else a(this).is("ul")?a(this).parents(".listContainer"+j).append('<ul class="listCol'+i+'"></ul>'):a(this).parents(".listContainer"+j).append('<ol class="listCol'+i+'"></ol>'); a(".listContainer"+j+" > ul,.listContainer"+j+" > ol").addClass(e)}var f=0,c=1,d=0;if(b.direction=="vertical"){a(this).children("li").each(function(){f+=1;if(f>g*(b.colNumber-1))a(this).parents(".listContainer"+j).find(".listCol"+b.colNumber).append(this);else if(f<=g*c)a(this).parents(".listContainer"+j).find(".listCol"+c).append(this);else{a(this).parents(".listContainer"+j).find(".listCol"+(c+1)).append(this);c+=1}});a(".listContainer"+j).find("ol,ul").each(function(){a(this).children().size()== 0&&a(this).remove()})}else a(this).children("li").each(function(){d+=1;d<=b.colNumber||(d=1);a(this).parents(".listContainer"+j).find(".listCol"+d).append(this)});a(".listContainer"+j).find("ol:last,ul:last").addClass("last");j+=1})}})(jQuery);
// fireup easy list splitter
$(document).ready(function () {
	$('.splitlist2').easyListSplitter({ 
		colNumber: 2
	});
	$('.splitlist3').easyListSplitter({ 
		colNumber: 3
	});	
	$('.splitlist4').easyListSplitter({ 
		colNumber: 4 
	});
	$('.splitlist5').easyListSplitter({ 
		colNumber: 5 
	});
});


// more less
$(function () {

	$('.excerpt').each(function () {
		
		// number of words to display
		$(this).html(formatWords($(this).html(), 40));
		$(this).children('span').hide();
		
		}).click(function () {

		var more_text = $(this).children('span.more_text');
		var more_link = $(this).children('a.more_link');
				
		if (more_text.hasClass('hide')) {
			more_text.show();
			more_link.html(' &laquo; Read less');		
			more_text.removeClass('hide');
		} else {
			more_text.hide();
			more_link.html(' &raquo; Read more');			
			more_text.addClass('hide');
		}

		return false;
		
	});
	
});

// read more
function formatWords(sentence, show) {

	var words = sentence.split(' ');
	var new_sentence = '';

	for (i = 0; i < words.length; i++) {
		if (i <= show) {
			new_sentence += words[i] + ' ';				
		} else {
			if (i == (show + 1)) new_sentence += '... <span class="more_text hide">';		
			new_sentence += words[i] + ' ';
			if (words[i+1] == null) new_sentence += '</span><a href="#" class="more_link"> &raquo; Read more</a>';
		} 		
	} 	

	return new_sentence;

}



//Initialize animated divs:
ddaccordion.init({
	headerclass: "animated-button", //Shared CSS class name of headers group
	contentclass: "animated-content", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover"
	collapseprev: false, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: true, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["up", "down"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["prefix", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: "fast", "normal", or "slow"
	oninit:function(expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
});


//direct form based on selected radio button
function usePage(frm,nm){
for (var i_tem = 0, section=frm.elements; i_tem < section.length; i_tem++)
if(section[i_tem].name==nm&&section[i_tem].checked)
frm.action=section[i_tem].value;
}


//twitter widget
/*
(function(){
	var twitterWidgets = document.createElement('script');
	twitterWidgets.type = 'text/javascript';
	twitterWidgets.async = true;
	twitterWidgets.src = '//platform.twitter.com/widgets.js';
	document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
})();
*/


$(function(){
	
	var menu = $('#navbar-wrapper'),
		pos = menu.offset();
		
		$(window).scroll(function(){			
			
			if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){
				menu.fadeOut('fast', function(){
					$(this).removeClass('default').addClass('fixed').fadeIn('fast');
				});
			} else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
				menu.fadeOut('fast', function(){
					$(this).removeClass('fixed').addClass('default').fadeIn('normal');
				});
			}
		});

});
