if(!this.JSON){JSON={};}(function(){function f(n){return n<10?'0'+n:n;}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};(function(jQuery){
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	function getRGB(color) {
		var result;

		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);
;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip-settings",settings);this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).hover(save,hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip-settings");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;part=parts[i];i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;helper.parent.show();update();}function update(event){if($.tooltip.blocked)return;if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;helper.parent.css({left:left+'px',top:top+'px'});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;helper.parent.hide().removeClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.unfixPNG();}$.fn.Tooltip=$.fn.tooltip;})(jQuery);jQuery(document).ready(function() {
	jQuery('.sort').find('li:not(:last)').after('<li>|</li>');

	jQuery('.tooltip')
		.tooltip({ showURL: false })
		.click(function() { return false; })
		.find('a')
		.click(function() { return false; });
	
	populate_select(jQuery('#f_models_make'), makes);
	jQuery('#f_models_make').change(function() {
		o = jQuery('#f_models_model');
		o.find('option:not(.first)').remove();
		populate_select(o, makes[this.value]);
		jQuery('#f_models_year option:not(.first)').remove();
	});
	
	jQuery('#f_models_model').change(function() {
		o = jQuery('#f_models_year');
		o.find('option:not(.first)').remove();
		years = makes[jQuery('#f_models_make').val()][this.value]['y'];
		for (key in years.sort().reverse())
			o.append('<option value="'+ years[key] +'">'+ years[key] +'</option>');
	});
	
	jQuery('#f_models .submit').click(function() {
		try {
			make  = jQuery('#f_models_make  :selected').val();
			model = jQuery('#f_models_model :selected').val();
			year  = jQuery('#f_models_year  :selected').val();
			
			conds = new Array();
			if (make)  conds.push('make=' + make );
			if (model) conds.push('model='+ model);
			if (year)  conds.push('year=' + year );
			
			if (conds.length < 3)
				window.location = site_w_path +'new_cars/?'+ conds.join('&');
			else {
				window.location = site_w_path +'specifications/'+ make +'/'+ model +'/'+ year +'/';
			}
		}
		catch(e) {}
	});

	jQuery('#compare_list .entry a')
		.live('click', function() {
			li = jQuery(this).parents('li');
			id = li.attr('id').replace(/.+_/, '');
			
			li.remove();
			jQuery('#compare_add_'+ id).removeAttr('checked');
			
			delete _compare[id];
			_update_selected_count();
			
			jQuery.cookie('compare', JSON.stringify(_compare), { path : '/' });
			
			return false;
		});
	
	jQuery('.compare_add')
		.live('click', function() {
			id = jQuery(this).attr('id').replace(/.+_/, '');
			
			if (jQuery(this).filter(':checked').length) {
				if (_get_selected_count() >= compare_max_cars) {
					jQuery(this).removeAttr('checked');
					alert('You can compare a maximum of '+ compare_max_cars +' vehicles.');
					return;
				}
				
				jQuery('#compare_list ul').append('<li class="entry" id="compare_list_'+ id +'"><img src="" alt="" class="thumb" /><p class="title"><\/p><a href="#">remove<\/a><\/li>');
				
				jQuery('#compare_list_'+ id).find('.title').html(jQuery(this).parents('.details').find('.title:first').html());
				jQuery('#compare_list_'+ id).find('.thumb').attr('src', jQuery(this).parents('.details').siblings().find('img.thumb:first').attr('src'));
				
				_compare[id] = -1;
				_update_selected_count();
				
				jQuery.cookie('compare', JSON.stringify(_compare), { path : '/' });

				jQuery(this).parents('.details').css({backgroundColor:'#FFA'}).animate({backgroundColor:'#FAFAFA'}, 1000);
				jQuery('#compare_list').css({backgroundColor:'#FFA'}).animate({backgroundColor:'#FAFAFA'}, 1000);
			}
			else {
				jQuery('#compare_list #compare_list_'+ id).remove();
				
				delete _compare[id];
				_update_selected_count();
				
				jQuery.cookie('compare', JSON.stringify(_compare), { path : '/' });
			}
		});
	
	jQuery('.compare')
		.live('click', function() {
			window.location = _get_slug();
			
			return false;
		});
	
	populate_price_high = function() {
		from = parseInt(jQuery('#f_price_low option:selected').val() + 0);
		sel  = jQuery('#f_price_high option:selected').val();
		
		jQuery('#f_price_high option:not(:last)').remove()
		
		jQuery('#f_price_low option').each(function() {
			val = parseInt(jQuery(this).val() + 0)
			if (val > from)
				jQuery('#f_price_high option:last').before(jQuery(this).clone());
		});
		
		jQuery('#f_price_high option[value='+ sel +']').attr('selected', 'selected');
		
		if (!jQuery('#f_price_high option[value='+ sel +']').length)
			jQuery('#f_price_high option:first').attr('selected', 'selected');
	}
	jQuery('#f_price_low')
		.bind('change', populate_price_high);

	jQuery('#prices_custom .submit')
		.bind('click', function() {
			window.location = '?price='+ jQuery('#f_price_low option:selected').val() +'-'+ jQuery('#f_price_high option:selected').val();
		});
	
	populate_payment_high = function() {
		from = parseInt(jQuery('#f_payment_low option:selected').val() + 0);
		sel  = jQuery('#f_payment_high option:selected').val();
		
		jQuery('#f_payment_high option:not(:last)').remove()
		
		jQuery('#f_payment_low option').each(function() {
			val = parseInt(jQuery(this).val() + 0)
			if (val > from)
				jQuery('#f_payment_high option:last').before(jQuery(this).clone());
		});
		
		jQuery('#f_payment_high option[value='+ sel +']').attr('selected', 'selected');
		
		if (!jQuery('#f_payment_high option[value='+ sel +']').length)
			jQuery('#f_payment_high option:first').attr('selected', 'selected');
	}
	jQuery('#f_payment_low')
		.bind('change', populate_payment_high);

	jQuery('#payments_custom .submit')
		.bind('click', function() {
			window.location = '?payments='+ jQuery('#f_payment_low option:selected').val() +'-'+ jQuery('#f_payment_high option:selected').val();
		});
	
	jQuery('a.more_years')
		.live('click', function() {
			qs = jQuery(this).attr('href');
			
			jQuery(this)
				.parents('.entry')
				.css({opacity:.3})
				.load(
					site_w_path + 'async/newcars.php'+ qs,
					{},
					function() { jQuery(this).css({opacity:1}) }
				);
			
			return false;
		});
	
	_get_selected_count = function() {
		count = 0;
		for (k in _compare)
			if (_compare.hasOwnProperty(k))
				count++;
		
		return count;
	}

	_get_slug = function() {
		slug = new Array();
		for (k in _compare) {
			if (_compare[k] > 0)
				slug.push(k +'-'+ _compare[k]);
			else
				slug.push(k);
		}
		
		return '/new_cars/compare/'+ slug.join(',') +'/';
	}
	
	_update_selected_count = function() {
		count = _get_selected_count();
		jQuery('#compare_list .count').html((count ? count : 'no') +' vehicle'+ (count > 1 ? 's' : '') +' selected');

		if (count > 1)
			jQuery('.compare').show();
		else
			jQuery('.compare').hide();
	}
	
	_compare = JSON.parse(jQuery.cookie('compare') || '{}');
});
