if ( typeof(window.mb)=="undefined"){ mb={}; }

var ie6 = ($.browser.msie && $.browser.version == '6.0') ? true : false;
var ie7 = ($.browser.msie && $.browser.version == '7.0') ? true : false;
/**
 * MB vehicles js
 */
mb.vehicles = new ( function($) 
{
    var me = this;
    var cl_index = 0;
    
	mb.broadcaster.addListener( mb.events.INITED, function() { mb.vehicles.init(); });

	/**
	 * must be call by application
	 */
	me.init = function()
	{
		//mb.logger.info("vehicles.init()");
		mb.broadcaster.addListener( mb.events.PAGE_LOADED, function(e,args) {
            mb.vehicles.onPageLoaded(e);
        });
		
		mb.broadcaster.addListener( mb.events.FRAGMENT_LOADED, function(e,args) {
            mb.vehicles.onFragmentLoaded(e);
        });
	};

	/**
	 * handles the page load event to complete initializing/setup
	 */
	me.onPageLoaded = function( d ) {

		//mb.logger.info("vehicles.onPageLoaded("+typeof(d)+")");

		initPageStyles( d );
		
	};

	me.onFragmentLoaded = function( d ) {

        if(d.getProperty("subsection") == 'save-comparison') {
        	mb.global.wireSaveCompare();
        }

	};

	//Updates AMG link when the owner is logged in
	function updateAMGLink(elem)
	{
		if($.cookie("MBUSA_OWNERS_STATUS") != null && typeof($.cookie("MBUSA_OWNERS_STATUS")) !="undefined" &&  
	                $.cookie("MBUSA_OWNERS_STATUS") != '0' )
	    {
			var urlParams = "/custID-"+$.cookie('OWNERS_CUST_ID')+"/emailID-"+$.cookie('OWNERS_EMAIL_ID').replace(/"/g,'')+"/UUID-"+$.cookie('MBUSA_UUID').replace("-","+");
			var href = $(elem).attr("href");
			if(href != "undefined" && href.indexOf("/amg/build") != -1)
			{
				$(elem).attr("href",href+urlParams);
			}
			
	    }
	}
	
	/**
	 * initialize page styles
	 */
	var initPageStyles = function( d )
	{
		mb.logger.info("vehicles.initPageStyles()");
        
        var section = d.getProperty("section") 
            , subsection = d.getProperty("subsection")
            , contextPath = d.getProperty("contextPath")
        ; 

        if(typeof mb.siteshare != 'undefined' && $('.share-widget-container').length > 0 && typeof mb.socialMedia != 'undefined'){

	        mb.broadcaster.addListener( 
                mb.siteshare.events.WIDGET_CLICKED
                , function(e,args) {
                    mb.logger.log("vehicles.js heard mb.siteshare WIDGET_CLICK()");
                    
                    if ((ie6 || ie7) && section == 'vehicles' && subsection == 'class-landing'){

                        if($(args).hasClass("hover")){
                            $("#swf_container").css("z-index","0");    
                            $(args).css("z-index","9999");
                        } else {
                            $("#swf_container").css("z-index","9999");    
                            $(args).css("z-index","0");
                        }

                    }
                }
            );

            //social media defined on page
            mb.siteshare.setContent(mb.socialMedia);

        }

        $('.blue-arrow.maximized-window').click(mb.global.openMaximizedWindow);

        if(d.getProperty("subsection") == 'save-comparison'){
        	var touts = $('.comparison-tout');
        	touts.click(function(){
        		$('.vehicle-tout-list').hide();
        		$(this).siblings('.vehicle-tout-list').show();
        		$('.comparison-tout').removeClass('on');
        		$(this).addClass('on');
        	});
        }
        
        if(d.getProperty("subsection") == 'class-landing'){
        	$(".cta-content a").click(function(){
        		createGAEventTag('BrandHalo CTA', 'click', 'WHAT DRIVES US ('+$(this).attr("id")+')');
        	}); 
        }
        
		if ( section == "vehicles" || section == "european_delivery_program" ) {
			var node = d.getNode();
			var subsection = d.getProperty("subsection");
			$('.teaser a').click(function(e) {
                e.preventDefault();
                var expanded = $(this).parents('.expanded');
                if (expanded.size()) {
                    $(expanded).collapseTout(subsection);
                    return false;
                }
            });
			
					
			
			$('.vehicle-tout-body').click(function() {
				//$(this).expandTout(subsection);
			});
			
			$('#vehicle-selector .vehicle-tout').each(function() {
                var vehicleGroups = $('.link-list li:not(.overview)', this);
                var vehicleImages = $('.vehicle-tout-thumbnail', this);
                var vehicleLinks = $(vehicleGroups).children('a');
                $(vehicleImages).eq(0).show();
                $(vehicleLinks).hover(function(){
                    var index = $(vehicleLinks).index(this);
                    $(vehicleImages).hide().eq(index).show();
                    $(this).siblings('.details').stop(true, true).fadeIn('slow');
                },function(){
                    $(vehicleGroups).children('.details').stop(true, true).fadeOut('fast');
                    $(vehicleImages).hide().eq(0).show();
                });
            });
			
			$("#find-dealer-form").submit(function(){
                var loadUrl = $(this).attr("action") + '/modal';
                var data = $(this).serialize();
                var qs = loadUrl.indexOf("?") > -1 ? "&" : "?"; 
                var mapIcon = contextPath + '/images/icons/mbpushpin.png';
                var mapWidth = 320;
                var mapHeight = 125;
                
                $.ajax({
                    type: "GET"
                    ,url: loadUrl + qs + "nodecorator=true"
                    ,data : data
                    ,success:function(response, textStatus){
                        var responseHtml = $(response); 
                        if(responseHtml.find("#dealer-result").length > 0){
                            $("#dealer-result").remove();
                            $("#dealer-result-container").prepend( $('#dealer-result', responseHtml) ); 
                            var poiContainers = $('.poi');
                            var pois = me.getPois(poiContainers);
                            var myMap = new mb.Map(
                                'map-result'
                                ,6
                                ,mapIcon
                                ,mapWidth
                                ,mapHeight
                                ,false
                                ,pois
                            );
                        } else {
                            var errors = $("#dealer-result .error");
                            if (errors.length <= 0){
                                $("#dealer-result-container").html('');
                                $("#dealer-result-container").prepend(
                                    '<div id="dealer-result">'
                                    + '<p class="error">We\'re sorry, your search did not return any results.</p>'
                                    + '</div>'
                                ); 
                            }
                            
                        }
                    }
                    ,error:function(XMLHttpRequest, textStatus, errorThrown){
                        var errors = $("#dealer-result .error");
                        if (errors.length <= 0){
                            $("#dealer-result-container").html('');
                            $("#dealer-result-container").prepend(
                                '<div id="dealer-result">'
                                + '<p class="error">We\'re sorry, your search did not return any results.</p>'
                                + '</div>'
                            ); 
                        }
                    }
                });
                return false;
            });
			
            //move to global
			jQuery.each(jQuery.browser, function(i) {
                if($.browser.msie && $.browser.version <= 8){
                    $('.showroom .vehicle-tout li a').hoverIntent(
                        function(e){
                            $("#pop-"+$(this).attr("id")).show();
                        },
                        function(){
                            $("#pop-"+$(this).attr("id")).hide();
                    });
                }else{
                    var showroomLength = $('.showroom .vehicle-tout li a').length;
                    if(showroomLength > 0){
                        $('.showroom .vehicle-tout li a').hoverIntent(
                            function(e){
                                $("#pop-"+$(this).attr("id")).fadeIn();
                            },
                            function(){
                                $("#pop-"+$(this).attr("id")).fadeOut();
                        });
                    }
                }
            });
			
			var t = $('.subclass-content-container .model-tout:not(.right-links)');
			t.mouseenter(function(){
				if ($.browser.msie && parseInt($.browser.version)== 8 )
					$(this).children('.link-wrap').show();
				else
					$(this).children('.link-wrap').fadeIn();
				return false;
			});
			t.mouseleave(function(){
				if ($.browser.msie && parseInt($.browser.version)== 8 )
					$(this).children('.link-wrap').hide();
				else
					$(this).children('.link-wrap').fadeOut('fast');
				
				return false;
			});
			t.click(function(e){
				window.location = $('a:first-child', this).attr('href');
				e.stopPropagation();
				//tracking for model tout clicking
				mb.metrics.trackInteraction( $('p a:first', this).attr('rel') );
				return false;
			});

            // Prevent Bubble Up from anchor tags to trigger onclick on the model-tout
			$('.subclass-content-container .model-tout:not(.right-links) .link-wrap a').click(function(e){
				if(e.stopPropagation) e.stopPropagation();
				e.cancelBubble = true;
				return true;
            });
			
            $('.tabs li a:first-child').click(function(){
                var url = $(this).attr("href");
                var selector = url.substring(url.indexOf('#'));
                var touts = $(this).parent().parent().parent().parent().children(".full-tout:not(" + selector + ")");
                var lis = $(this).parent().parent().children();
                lis.removeClass("on");
                $(this).parent().addClass("on");
                if($(this).next().attr("href")){
                	try {
                		var app = mb.getFlash("swf");
    					app.setContent( $(this).next().attr("href") );
                	  }
                	catch(err) {
                		mb.logger.info('mb.getFlash failed because: ' + err);
                	}                	
                }
                touts.hide();
                $(selector).fadeIn();
                //$(window, 'body', 'html', '#main').scrollTop(-500);
                return false;
            });
            
            if (subsection == "build-landing") {
            	
            	$('.amg a').each(function(){
            		updateAMGLink($(this));
            	});
            	
            	$('li.amg').nextAll('li').each(function(){
            		updateAMGLink($(this).find("a"));
            	})
            	
            }

            if ( subsection == "class-landing" || subsection == "bodystyle-landing") {
            	$('<div id="blackout"/>').appendTo('.story').hide().css('opacity', 0);
            	
                $('.tabs li a').click(function(){                	
                    var url = $(this).attr("href"); 
                    var selector = url.substring(url.indexOf('#'));
                    var touts = $(this).parent().parent().parent().parent().children(".full-tout:not(" + selector + ")");
                    var lis = $(this).parent().parent().children();
                    
                    var ctaId = $(".cta-content a").attr("id");
                    if($(this).text().indexOf("OVERVIEW") == -1)
                    {
                    	//Replace the last section with Sedans/Coupes etc.
                    	var replaceStr = ctaId.substr(ctaId.lastIndexOf("-"));
                    	$(".cta-content a").attr("id",ctaId.replace(replaceStr,"-"+$(this).text()));
                    }
                    
                    lis.removeClass("on");
                    $(this).parent().addClass("on");
                    if(selector != '#subclasstout0'){
                        $("#landing-menu").fadeOut('fast');
                        $("#campaign-cta").fadeOut('fast');
                    } else {
                        $("#landing-menu").fadeIn('fast');
                        $("#campaign-cta").fadeIn('fast');
                    }

                    $('#blackout').stop(true, true).show()
	                    .animate({'opacity':'1'}, {duration: 250, complete: function() {
	                    	touts.hide();
	                    	$(selector).show();
	                    }})
	                    .animate({'opacity':'0'}, {duration: 500, complete: function() {
	                        	$(this).hide();
	                    }});
                    
                    $.cookie("tab-id", $(this).parent().attr('id'));
                    return false;
                });
                
                var lastTabClicked = $.cookie("tab-id");
            	
            	if(lastTabClicked)
            		$("#"+lastTabClicked + " a:first").trigger("click");
            }

            //add click events to overview touts
            $('#subclasstout0 .body-class').each(function(i){
            	$(this).click(function(){
                    $('.subclass-menu-container .tabs li a:first-child:not(:first):eq('+i+')').trigger('click');
                    return false;
                });
            });

            $('#subclasstout0 .body-class,.subclass-content-container .model-tout:not(.right-links)').each(function(i){
            	$(this).hover(
                    function(){
                        $(this).addClass('hover');
                    }
                    ,function(){
                        $(this).removeClass('hover');
                    }
                );
            });
            
            $('.subclass-consider-container .body-class ').each(function(i){
            	$(this).hover(
                    function(){
                        $(this).addClass('hover');
                    }
                    ,function(){
                        $(this).removeClass('hover');
                    }
                );
            });
            
            if ( subsection == "compare-vehicles" ) {
            	me.wireCompareTabs();
            	var form = $('#compare');
        		var url = form.attr('action');
        		var formVehicles = $('.vehicle', form);
        		var category = form.find('input[name="category"]').val();
        		$(form).append('<div class="loading" />');
        		if (category == 'PHOTOS') {
					me.wireComparePhotos();
				}
        		$(".save-compare-ga-track").click(function(){
        			createGAEventTag('Vehicle Comparison', 'save', 'Save Comparison');
                	return true;
        		});
        		
        		$(".print-compare-ga-track").click(function(){
        			createGAEventTag('Vehicle Comparison', 'print', 'Print Comparison');
        			var qsIndex = $(".print-compare-ga-track").attr("href").indexOf("?");
        			var qsFragment = $(".print-compare-ga-track").attr("href").substring(qsIndex+1);
        			createATForComparison(qsFragment);
                	return true;
        		});
        		
        		$('select', form).change(function(){
        			var _this = $(this);
    				if(!_this.val()){return;}
        			$('.vehicle-touts p.error').remove();
        			$('.loading', form).show();
        			//reset
        			_this.parents('.form-item').nextAll().children('select').not(':disabled').val('').attr('disabled', 'disabled');
            		var scope = _this.parents('.vehicle');
            		var index = $(formVehicles).index(scope);
        			$('ul.compare-tout', scope).remove();
            		var data = form.serialize();
            		data += "&t=" + new Date().getTime();
                    $.ajax({
                        type: "GET"
                        ,url: contextPath + "/json/vehiclesCompare"
                        ,data : data
                        ,dataType : "json"
                        ,success:function(response){
            				var ns = me.getNameSpacedVars(response);
                    		me.updateComparisonForm(ns, response.Response.value, index, _this, scope);
                        }
                    	,error: function(XMLHttpRequest, textStatus, errorThrown) {
                        	$('.vehicle-touts').append('<p class="error">We\'re sorry, we encountered an error, please select a different vehicle.</p>')
                        	_this.focus();
                        	$('.loading', form).hide();
                        }
                    });
            	});
    			
        		if ($('form#compare #year2 option:selected').attr("value") == "") {
	        		//set second car year to the same as first
	        		$('form#compare #year2 option').each(function(){
	        			if($(this).attr('value') == $('form#compare #year1 option:selected').html()) $(this).attr('selected','selected');
	        		});
	        		$('form#compare #year2').trigger('change');
        		}
            }
            
            if ( subsection == "class-landing" || subsection == "bodystyle-landing") {
                $('.landing-menu li').hover(
                    function(){
                        $(this).addClass('on');
                    }
                    , function(){
                        $(this).removeClass('on');
                    }
                );

				$("#landing-menu a:not(.mediaLink)").each( function() {
					$(this).parent().find("a:first").click( function() {
						var link = $(this).parent().find("a:last").attr("href");
						var temphtml = 
							'<div id="modal" class="modal-container class-e">'
						    +'<div class="modal-shield"></div>'
						    +'<div class="modal-content-wrapper">'
						    +'<a class="close-modal" href="javascript:void(0);"><span/>close</a>'
						    +'<div class="modal-content"><div id="modal-swf"></div></div>'
						    +'</div></div>'
						;
						mb.modal.show(temphtml, "type1");
						var params = { scale: "noScale" , bgcolor : "#000" , salign : "tl" , wmode : "transparent" , quality : "high" , menu : "false", allowfullscreen : "true" };
						var flashVars = {autoPlay:true, content: link,contextRoot:d.getProperty("contextPath")};
						swfobject.embedSWF(contextPath + "/swf/mbusa_actionscript_media_container.swf" , "modal-swf" , "980px" , "458px" , "9.0.45" , false , flashVars , params);
						mb.modal.positionModal( $(".modal-container") );
						return false;
					});
				});

                $("li#sound-on-off a").click(function(){
                	$(mb.getFlash("swf").toggleMute());
                    return false;
                });
                $("li#sound-on-off a").toggle(function(){
            		$(this).css("background-image","url('"+contextPath+"/images/icons/sprite_sound_off.png')");
            		$(this).attr("title","Turn Sound On");
            		}, function () {
            		$(this).css("background-image","url('"+contextPath+"/images/icons/sprite_sound_on.png')");
            		$(this).attr("title","Turn Sound Off");
            	});
                
            	
            	//IE fix for deep linking.
            	if(window.location.hash)
            	{
                    cl_index = getClassIndex(window.location.hash);            		
                    $('.subclass-menu-container .tabs li a:first-child:eq('+cl_index+')').trigger('click');
            	}

            }
            
          
            if ( subsection == "configure"){
            	   $(".byo-print").click(function(){
            		   var vehicle = $('.pp-vehicle-year').html() + " "+ $('.pp-vehicle-model').html();
            		   createGAEventTag('BYO', 'print', vehicle);

            		   return true;
                  });
            }
            
            if ( subsection.match(/^explore/) != null ) {
            	$(".apply-for-credit").click(function(){
            		$(".apply-credit").submit();
            		
            		createGAEventTag('outbound-apply-for-credit', 'Apply for Credit', 'Apply for Credit(Financing)');
            		return false;
            	});
            	
            	if($.cookie('embed') == "true")
            	{
	            	var changedUrl = $(".secondary-navigation .tagged").attr("href").replace(/actyp-MAIN_CD/, "actyp-DWS_MAIN_CD/dealerCode-" + $.cookie('dealerCode'));
					 				 $(".secondary-navigation .tagged").attr("href", changedUrl);  
            	}
            	
            }
          
            
            
            if ( subsection == "comparison-landing") {
                //set up accordion
                $('.generic .accordion-title')
                    .unbind("mouseover")
                    .unbind("mouseout")
                ;
            }
            
		}
		/** Create Atlas Tag for Print Comparison (Extended Data)**/
		function createATForComparison(qsFragment)
		{	
			if(typeof $.fn.querystring == 'undefined') return;
			//Get the Query string dictionary object from print url
			var qsDictionary = $.fn.querystring(qsFragment);
			var custId = $('.pp-cust-id').text() == '' ? '0':$('.pp-cust-id').text();
			var objParams = {'action':'NYC_MBUSAVehicle_Comparison_Print1','ato':custId,'atc1':qsDictionary['year1'],
						'atc2':qsDictionary['make1'],'atc3':$("select[name='model1'] option[value='"+qsDictionary['model1']+"']").text(),
						'atc4':$("select[name='trim1'] option[value='"+qsDictionary['trim1']+"']").text()};
			var p = 5;
			for(var v=2;v<=4;v++)
			{
				objParams['atc'+(p++)] = (qsDictionary['year'+v] != null && qsDictionary['trim'+v] != null)?qsDictionary['year'+v]:'0';
				objParams['atc'+(p++)] = qsDictionary['make'+v] != null ?qsDictionary['make'+v]:'0';
				objParams['atc'+(p++)] = qsDictionary['model'+v] != null ?$("select[name='model"+v+"'] option[value='"+qsDictionary['model'+v]+"']").text():'0';
				objParams['atc'+(p++)] = qsDictionary['trim'+v] != null ?$("select[name='trim"+v+"'] option[value='"+qsDictionary['trim'+v]+"']").text():'0';
				
			}
			mb.metrics.trackAtlasInteraction(objParams);
		}
		
		me.getNameSpacedVars = function(r){
			var ns = mb.getNamespace(r);

			ns.years = ns.page+':years';
			ns.vehicles = ns.page+':vehicles';
			
			ns.vehicleMakes = ns.entity+':vehicleMakes';
			ns.vehicleClasses = ns.entity+':vehicleClasses';
			ns.vehicleClass = ns.entity+':vehicleClass';
			ns.titles = ns.entity+':titles';
			ns.vehicleEntity = ns.entity+':vehicles';
			ns.polkId = ns.entity+':polkId';
			ns.name = ns.entity+':name';
			ns.msrp = ns.entity+':msrp';
			ns.media = ns.entity+':media';
			ns.currentModelYear = ns.entity+':currentModelYear';
			
			return ns;
		}

		me.updateComparisonForm = function(ns, response, index, trigger, scope){
			var selects = $('.select', scope);
			var selected = $(selects).index(trigger);
			var makeOptions = '<option value="">Select Make</option>';
			var modelOptions = '<option value="">Select Model</option>';
			var trimOptions = '<option value="">Select Trim</option>';
			var obj = (response[ns.years][index]) ? response[ns.years][index] : response[ns.years];
			
			var makesArray = new Array();
			if(obj[ns.vehicleMakes].length){
				makesArray = obj[ns.vehicleMakes];
			} else {
				makesArray.push(obj[ns.vehicleMakes]);
			}
			for(i=0; i<makesArray.length; i++){
				var hasModels = (makesArray[i][ns.vehicleClasses]) ? true: false;
				var selectedMake = (hasModels) ? ' selected="selected"' : '';
				makeOptions += '<option'+selectedMake+'>'+makesArray[i][ns.titles].description+'</option>';
				if(hasModels){
					var modelArray = new Array();
					if(makesArray[i][ns.vehicleClasses].length){
						modelArray = makesArray[i][ns.vehicleClasses];
					} else {
						modelArray.push(makesArray[i][ns.vehicleClasses]);
					}
					for(j=0; j<modelArray.length; j++){
						var hasTrims = (modelArray[j][ns.vehicleEntity]) ? true: false;
						var selectedModel = (hasTrims) ? ' selected="selected"' : '';
						modelOptions += '<option value="'+modelArray[j][ns.polkId]+'"'+selectedModel+'>'+modelArray[j][ns.titles].description+'</option>';
						if(hasTrims){
							var trimsArray = new Array();
							if(modelArray[j][ns.vehicleEntity].length){
								trimsArray = modelArray[j][ns.vehicleEntity];
							} else {
								trimsArray.push(modelArray[j][ns.vehicleEntity]);
							}
							for(k=0; k<trimsArray.length; k++){
								var trimName = trimsArray[k][ns.name].split('/').splice(2,2).join('/');
								trimOptions += '<option value="'+trimsArray[k][ns.polkId]+'">'+trimName+'</option>';
							}
						}
					}
				}
			}
			
			// Added the following to clear out the following elements when changing year, model and trim.
			// This makes the UI less confusing because the only time these elements should be shown is
			// after trim is selected. -pMa 8/16/10
			var tout = $('.vehicle-tout').eq(index);
			$('h2', tout).text('');
			$('.vehicle-tout-thumbnail img', tout).attr('src', contextPath+'/images/icons/grey_vehicle.jpg');
			$('.vehicle-tout-body', tout).html('<p></p>');
			
			var year = (response[ns.years][index]) ? response[ns.years][index] : response[ns.years];
			var vehicle = null;
    		
			if(response[ns.vehicles] != undefined) {
				vehicle = (response[ns.vehicles][index]) ? response[ns.vehicles][index] : response[ns.vehicles];
			}
			
			switch(selected){
				case 0:
					$('select[name^="make"]', scope).html(makeOptions).removeAttr('disabled');
					$('select[name^="year"] option:first', scope).attr('disabled','disabled');
					
					if(index == 0){
						$('select[name^="model"]', scope).html(modelOptions).removeAttr('disabled');
						$('select[name^="make"] option:first', scope).attr('disabled','disabled');
					}
					//me.updateComparisonResults(ns, vehicle, 0, year);
					$('div.vehicle.first ul.compare-tout li.single').remove();
					break;
				case 1:
					$('select[name^="model"]', scope).html(modelOptions).removeAttr('disabled');
					$('select[name^="make"] option:first', scope).attr('disabled','disabled');
					break;
				case 2:
					$('select[name^="trim"]', scope).html(trimOptions).removeAttr('disabled');
					$('select[name^="model"] option:first', scope).attr('disabled','disabled');
					break;
				case 3:
					$('select[name^="trim"] option:first', scope).attr('disabled','disabled');
		    		
		    		var next = $('select[name="year'+(index+2)+'"]');
		    		if(!next.val()){
		    			next.val(year["id"]).removeAttr('disabled').change();
						$('option:first', next).attr('disabled','disabled');
		    		}
		    		if(index == 0){
		    			var initialModel = (vehicle[ns.vehicleClass]) ? vehicle[ns.vehicleClass] : year[ns.vehicleMakes][ns.vehicleClasses];
		    			$('#initialModel').val(initialModel[ns.polkId]);
		    			$('#initialTrim').val(vehicle[ns.polkId]);
		    		} 
		    		me.updateSaveComparisonLink(index);
		    		me.updateComparisonResults(ns, vehicle, index, year);
					break;
			}
			
			$('#compare .loading').hide();
		}
		
		
		me.updateSaveComparisonLink = function(index){
			var params = $('#compare').serialize();
			
			var slink = $('#save-comparison');
			var surl = $("#save-comparison .save-compare-ga-track").attr("href");
			surl = surl.substring(0, surl.indexOf('?')) + "?" + params;
			slink.find('a').attr('href', surl);
			if (index > 0) {
				$(slink).show();
			}
			
			var link = $('.print');
			//remove category from print url
		    var prefix= encodeURIComponent('category')+'=';
		    var pars= params.split(/[&;]/g);
		    for (var i= pars.length; i-->0;)
		    if (pars[i].lastIndexOf(prefix, 0)!==-1){
		            pars.splice(i, 1);
		    }
		    params= pars.join('&');
			var url = $(link).attr("href");
			url = url.substring(0, url.indexOf('?')) + "?" + params+'&print=true';
			
			link.attr('href', url);			
		}

		me.updateComparisonResults = function(ns, vehicle, index, year){

        mb.logger.log("index = " + index);

			var tout = $('.vehicle-tout').eq(index);
			var nameSplit = vehicle[ns.name].split('/');
			var showLinks = (nameSplit[0].indexOf('Mercedes-Benz') != -1) ? ((nameSplit[1].indexOf('Sprinter') != -1) ? false : true) : false;
			var name = nameSplit[0] +' ' + nameSplit[1] + ' ' + nameSplit.splice(2,2).join('/');
			var msrp = mb.global.formatCurrency(vehicle[ns.msrp]);
			
			if(msrp == 'NaN') {
				msrp = 'TBA';
			} else {
				msrp = '$' + msrp;
			}
			
			if(name.length > 40) {
				name = name.substring(0,39) + '...';
			}

			$('h2', tout).text(name);
			$('.vehicle-tout-thumbnail img', tout).attr('src', vehicle[ns.media]["url"]);
			$('.vehicle-tout-body', tout).html('<p>Base MSRP: '+msrp+'</p>');
			
			if(showLinks && vehicle.id){
				var vClass = (vehicle[ns.vehicleClass]) ? vehicle[ns.vehicleClass].id : year[ns.vehicleMakes][ns.vehicleClasses][ns.polkId];
				var vModel = vehicle.id;
                
                var elem = $('#trim' + (index + 1) + ' option:selected');

                var type = elem.text().toUpperCase();
						
				if(type.match("SLK55")){

					var links = '<ul class="compare-tout"><li class="single"><a class="carat" href="http://www.mercedes-amg.com/#/'+
					vModel.toLowerCase()+'-overview" target="_new">Explore This Vehicle</a></li></ul>';
					mb.logger.info('SLK55 - no BYO');

				}
				else if(type.match("AMG")){
					var trimmedModel = vModel;
					if(vModel.match("SLSC")) {
						trimmedModel = "SLS";
					}
					
					if(vModel.match("G55K")) {
						trimmedModel = "G55";
					}
					
					if(vModel.match("C63C")) {
						trimmedModel = "C63-COUPE";
					}
					
					if(vModel.match("E63S")) {
						trimmedModel = "E63E";
					}
					if( vehicle[ns.currentModelYear] != undefined && !(year["id"] < vehicle[ns.currentModelYear])){
						var links = '<ul class="compare-tout"><li><a class="box-orange" href="http://www.mbusa.com/amg/build/#/model-'+
						vModel+'/" target="_blank">Build This Vehicle</a></li><li><a class="carat" href="http://www.mercedes-amg.com/#/'+
						trimmedModel.toLowerCase()+'-overview" target="_new">Explore This Vehicle</a></li></ul>';					
						$('.vehicle-tout-thumbnail a', tout).attr('href', 'http://www.mercedes-amg.com/#/'+ trimmedModel.toLowerCase()+'-overview');
						$('.vehicle-tout-thumbnail a', tout).attr('target', '_new');
					}
					mb.logger.info('AMG vehicle');

				} else if(vehicle[ns.currentModelYear] != undefined && !(year["id"] < vehicle[ns.currentModelYear])){					
						var links = '<ul class="compare-tout"><li><a class="box-orange" href="'+contextPath+'/vehicles/build/class-'+
						vClass+'/model-'+vModel+'">Build This Vehicle</a></li><li><a class="carat" href="'+contextPath+'/vehicles/explore/overview/class-'+
						vClass+'/model-'+vModel+'">Explore This Vehicle</a></li></ul>';
						$('.vehicle-tout-thumbnail a', tout).attr('href', contextPath + '/vehicles/explore/overview/class-' + vClass + '/model-' + vModel);
						$('.vehicle-tout-thumbnail a', tout).attr('target', '_self');
						mb.logger.info('M-B vehicle');

				}

				$(tout).parent().append(links);

			}
			
            var params = '/polk?'+$('#compare').serialize().replace(/&category=\w+/, '');

			$('.tabs li').each(function(){
				var _this = $('a', this);
				if($(this).hasClass('on')) {
		            var url = _this.attr('href').split('?')[0]+params;
		            me.updateComparisonData(_this, url);
				}
			});
		}
		
		me.updateComparisonData = function(trigger, url){
            var category = ($(trigger).attr('href').replace('/vehicles/compare/category-','').replace(/\?.*$/,''));
//            var newPrintLink = ($('ul.utilities a.print').attr('href').replace(/category=[^&]*/,'category='+category));
            var newPrintLink = ($('ul.utilities a.print').attr('href').replace(/category=[^&]*/,'category='+category));
            
//            $('ul.utilities a.print').attr('href', newPrintLink);
            $('ul.utilities a.print').attr('href', newPrintLink);
            
			$('#comparison-chart .loading').show();
            
	        $.ajax({
				url: url,
				dataType: "html",
				success: function(data) {
					$('#comparison-chart').replaceWith(data);
					$('.tabs li').removeClass('on');
		            trigger.parent().addClass('on');
		            if(data.indexOf('published-photos') != -1){
		            	me.wireComparePhotos();
		            }
				},
				error: function() {
	            	$('#compare').submit();
	            }
			});
	    }
		
		//Read tab location from url
		var loc = window.location.href;

        cl_index = getClassIndex(loc);
        
        //hijack the links from the nav on this page
        $('#overlay-nav .class-bodystyle a').click(function(){
        	$('#tabs-menu a[href='+$(this).attr('href')+']').trigger('click');        	
        });
        
        //Click Handler for top nav bodystyle links/background image
	    $('#overlay-nav ul.overlay-container li.overlay-item div.nav-gp-info-cont a.body-style-img-lnk, #overlay-nav .overlay-item.group .nav-gp-info-cont .gp-info-title-ch a').click(function(){
        	var vehicleClass = $(this).attr("id").replace("-img-link","");
        	var currentClass = $(".nav-body-group li.nav-body-gp-children a.active span").html();
        	//If in E class landing use tab menu click or use the href to navigate to bodystyle section 
        	if(vehicleClass == "E"){   
	        	$('#tabs-menu a[href='+$(this).attr('href')+']').trigger('click');
	        	}
        	
        	return true;
	        	
	        });
	};

    function getClassIndex(loc){
        	 var classIndex = 0; 
        	 if(loc.indexOf("#") > -1){
                 subsection = loc.substring(loc.indexOf("#") + 1);
             }else{
                 subsection = "subclasstout0";
             }
        	 classIndex = subsection;
        	 return classIndex;
    }

    /**
     * Gets the pois from dealers printed on the page
     *
     * @param {Object} poiContainers A jQuery object for poi containers found on the page.
     * @return {Array}	Returns list of pois as an Array of objects.
     */
    me.getPois = function(poiContainers){
        var pois = new Array();
        $.each(poiContainers, function(i,v){
            pois.push({
                key : $(v).find('.key').text()
                ,lat : $(v).find('.latitude').text()
                ,lng : $(v).find('.longitude').text()
                ,title : $(v).find('.title').text()
                ,infoContent : $(v).find('.info-content-html').html()
            });
        });           
        return pois;
    };
	
    /**
     * Wires up the different tabs for vehicle compare page
     * to load specific category
     */
    me.wireCompareTabs = function(){
    	var compareTabs = $('.tabs li a');
    	$(compareTabs).unbind('click').click(function(e){
    		var params = '/polk?'+$('#compare').serialize().replace(/&category=\w+/, '');
    		var _this = $(this);
    		if(_this.parent().hasClass('on')) {return false;}
            var url = _this[0].pathname+params+'&nodecorator=true';
            if($.browser.msie)
            	url = "/" + url;
            me.updateComparisonData(_this, url);
    		e.preventDefault();
            return false;
    	});
	};

    me.wireComparePhotos = function(){
        mb.logger.info('wireComparePhotos');
    	var scope = $('.photos');
    	var group = $('.published-photos');
    	var thumbnails = $('.thumbnail-area a');
    	$(group).each(function(){
    		$('img', this).hide().eq(0).show();
    	});
    	$('.thumbnail-area', scope).show();
    	$(thumbnails).mouseover(function(){
    		var x = $(thumbnails).index(this);
    		$(group).each(function(){
    			$(this).find('img').hide().eq(x).show();
    		});
    	}).click(function(e){
    		e.preventDefault();
    	});
    };
    
    me.lookupType = function(key){
		var map = new Array();
		
		map['SDN'] = 'Sedan';
		map['CPE'] = 'Coupe';
		map['SUV'] = 'SUV';
		map['GST'] = 'Crossover';
		map['RDS'] = 'Roadster';
		map['WGN'] = 'Wagon';
		map['CAB'] = 'Cabriolet';
		
		var newkey = map[key];

		return ( map[key] ? map[key] : key );
    };

})(jQuery);

