/* Copyright Dealer.com 2007
* Written by Scott Gale

carbuilder.init - called when page loads to initialize everything
detailsVehicle.init - called when details page and trim page load, case exists for each

*/

var carbuilder = {
    year : "All Years",
	make : Config.InitialMake,
	style : "All Styles",
	minPrice: 1000000,
	maxPrice: 0,
	minMPG: 1000,
	maxMPG: 0,
	intro : Config.Opener, //logos-sm, logos-med, logos-lrg, bodystyle, null, logos-txt-[size]
	modelPage : Config.ModelPage, //settings for model splash: model, curve, bodystyles, fourstyles, acura
	introLoaded : false,
	priceSlider : null,
	mpgSlider : null,
	poped : false, //for alpha
	color : "white",
	inTransition: null, //holds for transition to finish before going to next photo
    configurable : Config.configurable, //allows changes to config on fly
	defaultMake : Config.DefaultMake,

    makes : new UniqueList(),
	years : new UniqueList(),
	styles : new UniqueList(),

	setMake : function(makeToSet){
		this.make = makeToSet;
		$("#makes option").each(function(count){
				if (this.value == makeToSet)	{
					$("#makes")[0].selectedIndex = count;
				}
		});
	},

	matches : function (row) {
		var res = true,
			criteria = {
				modelyear: !!(row.getAttribute("modelyear") == this.year || this.year == "ALL"),
				make: !!(row.getAttribute("make") == this.make || this.make == "ALL"),
				bodystyle: !!(row.getAttribute("bodystyle") == this.style || this.style == "ALL"),
				price: !!(row.getAttribute("minprice") >= (carbuilder.priceSlider.getLowValue() * 1000) &&
						   row.getAttribute("maxprice") <= (carbuilder.priceSlider.getHighValue() * 1000)),
				mpg: !!(carbuilder.mpgSlider && row.getAttribute("mincmpg") >= carbuilder.mpgSlider.getLowValue() &&
						row.getAttribute("maxhmpg") <= carbuilder.mpgSlider.getHighValue())
			},
			tests = ['modelyear', 'make', 'bodystyle', 'price'];
		if (Config.ModelFilterType == "more") // inclusive filtering for price, includes if rules a vehicle's max price is above the min, and minprice is below the max
			criteria.price = !!(row.getAttribute("maxprice") >= (carbuilder.priceSlider.getLowValue() * 1000) && row.getAttribute("minprice") <= (carbuilder.priceSlider.getHighValue() * 1000));
		if (carbuilder.mpgSlider)
			tests.push('mpg');
		for (var i = 0; i < tests.length; i++) {
			if (criteria[tests[i]] != true) {
				res = false;
				break;
			}
		}
		return res;
    },

	// init gets called on page load by Config.execute()
	init : function() {
		//init carbuilder
		if (Config.InitialModel) { //load model if the initial model is passed in
			carbuilder.load.details(Config.InitialModel.year, Config.InitialModel.make, Config.InitialModel.model, Config.InitialModel.bodystyle);
		} else if (Config.InitialMake) {
            carbuilder.load.models(carbuilder.make, 'models_target');
        } else {
			carbuilder.load.makes('makeItems'); //load make listing
		}
	},

	initIntro : function() {
		if (carbuilder.intro == "model") return;
		var html = "",
			start = 15000,
			end = 85000,
			increment = 10000,
			compliantMakeString = "acura,audi,bmw,bentley,honda,lexus,mercedes,mini,porsche,rolls-royce,scion,toyota,volkswagen",
			useTextLogos = (carbuilder.intro.indexOf("txt") !=- 1);

		if (carbuilder.intro == "bodystyle") {
			$("#makes option").each(function() {
				var val = $(this).val();
				if (val && val != "Select Make") html += "<div><a href='javascript:carbuilder.postIntro(\"" + val + "\");'>" + val + "</a></div>";
			});
			$("#byMake .content").html(html);
			for (var i = start; i <= end; i = i + increment) {
				if (i == start) {
					html = "<div>Under $" + i + "</div>";
				}
				if (i == end) {
					html += "<div>Over $" + i + "</div>";
				} else {
					html += "<div>$" + i + " - $" + (i + increment) + "</div>";
				}
			}
			$("#byPriceRange .content").html(html);
		} else if (carbuilder.intro.indexOf("logos") != -1) {
			detailsVehicle.updateBreadCrumb("make");
			$("#logos").addClass(carbuilder.intro.replace("logos-", ""));
			carbuilder.intro = carbuilder.intro.replace("-txt", "");
			$("#makes option").each(function() {
				var logoType = "";
				//setup for non-compliant text logos for only certain makes
				if (useTextLogos && compliantMakeString.indexOf(this.value.toLowerCase()) != -1) {
					logoType = "txt-" + carbuilder.intro.replace("logos-", "");
				} else {
					if (this.value == "BMW") { //special case for BMW, they can never have their logo used as a click through
						logoType = "txt-" + carbuilder.intro.replace("logos-", "");
					} else {
						logoType = carbuilder.intro.replace("logos-", "");
					}
				}

				//render logos page
				if (this.value && this.value.indexOf("Select Make") == -1) {
					html += [
						"<div><img alt='",
						this.value,
						"' src='http://static.dealer.com/v8/global/images/franchise/",
						Config.Shade,
						"/",
						Config.isCanada ? "en_CA" : "en_US",
						"/logo-",
						this.value.toLowerCase().replace(" ","-"),
						"-",
						logoType,
						".jpg'",
						" onClick='carbuilder.postIntro(\"",
						this.value,
						"\");'></div>"
					].join('');
				}
			});
			$("#logos .content").html(html);
		}
	},

	postIntro : function(make) {
		carbuilder.make = make;
		carbuilder.init();
	},

//	clearSelector: function(select) {
//		if (select.options.length == 1) return;
//		var numopt = select.options.length;
//		for (var i = (numopt - 1); i >= 1; i--)
//			select.options[i] = null;
//	},

	loadSliders: function() {
		//initialize sliders
		if (!this.priceSlider) {
			this.priceSlider = new Slider($("#slider-1")[0], this.minPrice, this.maxPrice);
			//format pricing, $ and , are part of index.vm so only change thousands place and beyond
			this.maxPrice = Math.round(this.maxPrice/1000);
			this.minPrice = Math.round(this.minPrice/1000);
			//set limits
			this.priceSlider.setMinimum(this.minPrice);
			this.priceSlider.setLowValue(this.minPrice);
			this.priceSlider.setMaximum(this.maxPrice);
			this.priceSlider.setHighValue(this.maxPrice);
			this.priceSlider.setUnitIncrement(1);
			//update display
			document.getElementById("slideMinPrice").innerHTML = this.priceSlider.getLowValue();
			document.getElementById("slideMaxPrice").innerHTML = this.priceSlider.getHighValue();
			// Price Slider's onchange
			this.priceSlider.onchange = function() {
				//PriceChange();
				document.getElementById("slideMinPrice").innerHTML = carbuilder.priceSlider.getLowValue();
				document.getElementById("slideMaxPrice").innerHTML = carbuilder.priceSlider.getHighValue();
				filter();
				if (calc) {
					document.forms["indexCalcForm"].elements["minPrice"].value = carbuilder.priceSlider.getLowValue() * 1000;
					document.forms["indexCalcForm"].elements["maxPrice"].value = carbuilder.priceSlider.getHighValue() * 1000;
					calc.exec();
				}
			};
		}
		if (this.maxMPG != 0) {
			this.mpgSlider = new Slider($("#slider-2")[0], this.minMPG, this.maxMPG);
			//set limits
			this.mpgSlider.setMinimum(parseInt(this.minMPG, 10));
			this.mpgSlider.setLowValue(parseInt(this.minMPG, 10));
			this.mpgSlider.setMaximum(parseInt(this.maxMPG, 10));
			this.mpgSlider.setHighValue(parseInt(this.maxMPG, 10));
			this.mpgSlider.setUnitIncrement(1);
			//update display
			document.getElementById("slideMinMpg").innerHTML = this.mpgSlider.getLowValue();
			document.getElementById("slideMaxMpg").innerHTML = this.mpgSlider.getHighValue();
			// MPG Slider's onchange
			this.mpgSlider.onchange = function () {
				//MPGChange();
				document.getElementById("slideMinMpg").innerHTML = carbuilder.mpgSlider.getLowValue();
				document.getElementById("slideMaxMpg").innerHTML = carbuilder.mpgSlider.getHighValue();
				filter();
			};
		}
	},

	changeColor : function(obj, media, onmouseover) {
		if (media) {
			if (onmouseover) return;
			$("#exteriorStills").css("background-image","url(" + $("#mediaColorPhoto").attr("src") + ")");
			$("#mediaColors .colorSwatch").css("border","solid 1px #fff");
			$(obj).css("border","1px solid #EA5100");
			clearTimeout(carbuilder.inTransition);
			carbuilder.inTransition = setTimeout(function(){
				if(obj.getAttribute("colorPhotoLrg") != "") setTimeout(function(){document.images["mediaColorPhoto"].src = obj.getAttribute("colorPhotoLrg")},10);
				detailsVehicle.mediaShow("mediaColorPhoto","exteriorStills img",function(){$("#exteriorStills").css("background-image","none");});
			});
			detailsVehicle.endSlideShow();
			$("#mediaColors "+obj.getAttribute("display")).html(obj.getAttribute("name"));
		} else {
			if (obj.getAttribute("colorphoto") != "") {
				if ($("#detailImageViewer").size() > 0 && $("#detailImageViewer").css("display") == "none") { //if slideshowing vehicle
					if (onmouseover) return; //don't mouse over if slideshow is running, requires clicking
					$("#detailSlideShow").fadeOut("fast",function() {
						$("#detailSlideShow").html("&nbsp;");
						$("#detailImageViewer").fadeIn("fast");
						$("#detailDisplayContainer").animate({height: 135}, "normal", function(){
							carbuilder.changeColor(obj,media);
							$("#detailZoom").fadeIn();
						});
					});
				} else {
					$("#detailImageView1").css("background-image","url(" + $("#detailsVehiclePhoto1").attr("src") + ")");
					$("#detailColors #" + obj.parentNode.id + " .colorSwatch").css("border","solid 1px #fff");
					$(obj).css("border","1px solid #EA5100");
					if (obj.getAttribute("colorPhoto") != null) {
						clearTimeout(carbuilder.inTransition);
						carbuilder.inTransition = setTimeout(function(){ //apply cross fade when user settles on a vehicle
							setTimeout(function(){
								document.images["detailsVehiclePhoto1"].src = obj.getAttribute("colorPhoto");
							},1);
							$("#detailsVehiclePhoto1").fadeIn("normal", function(){
								$("#exteriorStills").css("background-image","none");
							});
						}, 200);
					}
				}
			}
			$(obj.getAttribute("display")).html(obj.getAttribute("name"));
		}
	},

	toggleFlash : function() {
		$("#detailSlideShow").toggle();
	},

    print : function(stage) {
		if (!stage) {
			$("#print").hide();
			$("#menuContainer").hide();
			window.print();
			$("#print").show();
			$("#menuContainer").show();
		} else if (stage == 'setup') {
			$("#globalPrint").attr("href","javascript:window.print();");
		} else if (stage == 'detailsetup') {
			$("#globalPrint").attr("href","javascript:carbuilder.print('detail');");
		} else if (stage == 'detail') {
			window.print();
			//var docprint = window.open('/apps/builder/print.vm?year='+detailsVehicle.year+'&make='+detailsVehicle.make+'&model='+detailsVehicle.model+"&bodystyle="+detailsVehicle.style,'printWin','toolbar=yes,location=no,directories=yes,menubar=yes,resizable=yes,scrollbars=yes,width=760,height=420,left=75,top=50');
			/*
			var docprint = window.open("/apps/builder/blank.vm",'printWin','toolbar=yes,location=no,directories=yes,menubar=yes,resizable=yes,scrollbars=yes,width=760,height=420,left=75,top=50');
			$(docprint).load(function(){
				$(docprint.document.body).html(Account.getHeader() + $("#carBuilderContainer").html());
				$(docprint.document.body).find("#detailView").show();
				$(docprint.document.body).find("#detailList").show();
				$(docprint.document.body).find("#detailList div").show();
			});
			docprint.focus();
			setTimeout(function(){docprint.print();},1000);
			*/
		} else if (stage == 'trimsetup') {
			$("#globalPrint").attr("href","javascript:carbuilder.print('trim');");
		} else if (stage == 'trim') {
			window.print();
			/*
			var docprint = window.open("/apps/builder/blank.vm",'printWin','toolbar=yes,location=no,directories=yes,menubar=yes,resizable=yes,scrollbars=yes,width=760,height=420,left=75,top=50');
			$(docprint).load(function(){
				$(docprint.document.body).html(Account.getHeader() + $("#carBuilderContainer").html());
				$(docprint.document.body).find('#buildCarousel').removeClass("jcarousel-scope");
				$(docprint.document.body).find('#buildCarousel').css("float","left");
				$(docprint.document.body).find('#buildCarousel').html("<ul style='width:400px;'>" + $('#buildCarousel .jcarousel-clip li').html() + "</ul>");
				var html = "";
				$('#buildCarousel .jcarousel-clip li').each(function(count){if(count > 0){html += $(this).html()}});
				$(docprint.document.body).find('#buildCarousel').css("float","left");
				$(docprint.document.body).find('#detailWrapper').append("<ul id='ulPrint'>" + html + "</ul>");
			});
			docprint.focus();
			*/
		}
	},

    load : {
        intro : function (target) {
			carbuilder.debug("load intro");
            $("#menuWrapper").hide();
            $("#models_target").fadeOut("fast");
            $("#details_target").hide();
            detailsVehicle.updateBreadCrumb("intro");
            var url = (carbuilder.intro.indexOf("logos") != -1) ? "logos" : carbuilder.intro;
            carbuilder.load.ajax('/builder/views/' + url, target, "Loading Selector...", function() {
				carbuilder.initIntro(); //load intro if there is one, intro peforms check to be sure
				carbuilder.introLoaded = true;
				carbuilder.load.track( 10, "CARBUILDER_LOGOS_INTRO" );
				carbuilder.debug("load makes");
				//carbuilder.fadeIn($('#models_target'));
				$('#models_target').fadeIn();
			});
        },

        makes : function (target) {
			if (Config.Makes === "Honda" ) { // DNA1087902: flag for honda compliancy hacks
				Config.hondaCompliancy = true;
			}
			if (Config.Makes == "") {
                carbuilder.load.ajax('/builder/views/makes', null, "Loading Makes...", function() {
					if ($('#makes')[0].length < 2) {	//check if makes haven't been loaded yet
						carbuilder.makes.addToSelectBox(document.getElementById("makes"));
					}
					carbuilder.setMake(carbuilder.make);
					if (carbuilder.intro != "model" && !carbuilder.introLoaded) {
						carbuilder.load.intro('models_target');
						return;
					} else {
						if (carbuilder.make=="All Makes") {
							carbuilder.load.models('Acura', 'models_target'); //load models
						} else {
							carbuilder.load.models(carbuilder.make, 'models_target'); //load models
						}
					}
                });
            } else {
                var makes = Config.Makes.split(",");
                for (var i = 0; i < makes.length; i++) {
					carbuilder.makes.add(makes[i]);
                }

                if ($('#makes')[0] && $('#makes')[0].length < 2) {//check if makes haven't been loaded yet
                    carbuilder.makes.addToSelectBox( $('#makes')[0] );
				}
				carbuilder.setMake(carbuilder.make); //on initial glance, this seems partially redundant since this.make is set at the beginning of carbuilder.setMake

                if (makes.length == 1) {
					carbuilder.load.models(makes[0], 'models_target');
					return;
				}

                if (carbuilder.intro != "model" && !carbuilder.introLoaded) {
                    carbuilder.load.intro('models_target');
                } else {
                    if (carbuilder.make=="") {  //set make based on default make
                        if (carbuilder.defaultMake != "default") {
                            carbuilder.setMake(carbuilder.defaultMake);
						} else {
                            carbuilder.setMake(makes[0]);
						}
					}
                    if (carbuilder.make == "All Makes") {
						carbuilder.load.models('Acura', 'models_target'); //load models
					} else {
						carbuilder.load.models(carbuilder.make, 'models_target'); //load models
					}
                }
            }
        },

        models : function (make, target) {
			carbuilder.year = "ALL";
			carbuilder.style = "ALL";
			carbuilder.setMake(make);
			$('option:gt(0)', $('#years, #styles')).remove();  // clear menu options dropdown

            detailsVehicle.updateBreadCrumb("model");
            $("#carBuilderContainer").removeClass("carBuilderContainerDetails");
            $("#models_target").fadeOut("fast", function(){
				$("#details_target").hide();
				$("#menuOpts, #indexAfford").show();
			});

//            $("#gridCtrls").show();
//            $("#indexAfford").show();


            var loadingMessage = ["Loading ",
					make,
					(make.charAt(make.length - 1) == 's' ? "" : "s"),
					"..."
				].join(''),
				ajaxUrl = ["/builder/views/models?style=",
					carbuilder.modelPage,
					"&make=",
					make,
					"&excludedModels=",
					Config.ExcludedModels
				].join('');
			carbuilder.load.ajax(ajaxUrl, target, loadingMessage, function() {
				carbuilder.load.track(10, "CARBUILDER_MODELS" );
				if (carbuilder.modelPage == "model") {
					carbuilder.styles = new UniqueList(); //refresh on make change
					$('div.model').each( function() {
						var $this = $(this);
						if (parseFloat($this.attr("maxprice"), 10) < 999999) { //check for bad data
							carbuilder.years.add( $this.attr("modelyear") );
							carbuilder.styles.add( $this.attr("bodystyle") );

							//find lowest/highest MPG
							if (carbuilder.minMPG > $this.attr("mincmpg")) {
								carbuilder.minMPG = $this.attr("mincmpg");
							}
							if (carbuilder.maxMPG < $this.attr("maxhmpg")) {
								carbuilder.maxMPG = $this.attr("maxhmpg");
							}

							//find lowest/highest MSRP
							if (carbuilder.minPrice > parseFloat($this.attr("minprice"), 10)) {
								carbuilder.minPrice = $this.attr("minprice");
							}
							if (carbuilder.maxPrice < parseFloat($this.attr("maxprice"), 10)) {
								carbuilder.maxPrice = parseFloat($this.attr("maxprice"), 10);
							}
						}
					});

					//round to thousands
					carbuilder.maxPrice = Math.ceil(carbuilder.maxPrice/1000) * 1000;
					carbuilder.minPrice = Math.floor(carbuilder.minPrice/1000) * 1000;

					carbuilder.years.addToSelectBox($('#years')[0]);
					carbuilder.styles.addToSelectBox($('#styles')[0]);

					//create sliders based on the above values that you found
					carbuilder.loadSliders();

					calc.moPayDiv = "indexPaymentAmount";
					detailsVehicle.priceCalc((carbuilder.minPrice * 1000) + "-" + (carbuilder.maxPrice * 1000), "indexCalcForm");

					//register events for selection menu
					$("#years").change(function() {
						carbuilder.year = this.value;
						filter();
					});
					$("#styles").change(function() {
						carbuilder.style = this.value;
						filter();
					});
					$("#menuWrapper").show();
					carbuilder.setMake(carbuilder.make);
					var _acuraHack = 0;
					if (Config.Makes.indexOf("Acura") != -1) { //temporary fix for acura
						_acuraHack = 670;
					}
					$(".model").each(function() {
						var html = $(this).find(".mnStarting").html();
						html = html.split(': ');
						html[1] = calc.format(parseFloat($(this).attr("minprice")) + _acuraHack, true);
						html = html.join(': $');
						$(this).find(".mnStarting").html(html);
					});

					if (Config.hondaCompliancy) { 	// DNA1087902: honda compliancy hacks
						$('#models_target .mi .mnStarting').add('#menuOpts .gridCtrls').css('display','none');
					}
					//carbuilder.fadeIn($('#models_target'));
					$('#models_target').fadeIn();
				} else if (carbuilder.modelPage == "curve") {
					curve.init();
				} else if (carbuilder.modelPage == "fourstyles") {
					fourStyles.init();
				} else if (carbuilder.modelPage == "bodystyles") {
					bodyStyles.init();
				} else if (carbuilder.modelPage == "acura") {
					acura.init();
				}
			});
        },

        mediaGallery : function() {
			var url = '/builder/views/media?vehicleId=' + detailsVehicle.vehicleId,
				target = "tb_target",
				loadingMsg = "Loading " + detailsVehicle.year + " " + detailsVehicle.make + " " + detailsVehicle.model + " Details...";
			carbuilder.load.ajax(url, target, loadingMsg, function(){detailsVehicle.initMediaGallery()});
        },

        //reload function for testing
        reloadDetails : function() {
            $("#models_target").hide();
            $("#details_target").fadeOut("fast");
            detailsVehicle.updateBreadCrumb("trim");
			var url = ['/builder/views/details?year=', detailsVehicle.year, '&make=', detailsVehicle.make, '&model=', detailsVehicle.model, '&bodystyle=', detailsVehicle.style].join(''),
				target = "details_target",
				msg = ['Loading', detailsVehicle.make, detailsVehicle.model, 'Details...'].join(' ');
			carbuilder.load.ajax(url, target, msg, function(){detailsVehicle.init()});
        },
        //end reloading

        details : function( year, make, model, bodystyle ) {
			detailsVehicle.year = year;
			detailsVehicle.make = make;
			detailsVehicle.model = model;
			detailsVehicle.style = bodystyle; //for reloading
            carbuilder.model = model;
			$("#models_target").hide();
            detailsVehicle.updateBreadCrumb("trim");
            $("#details_target").html("").show().fadeOut("fast");
            $("#menuWrapper").hide();
            $("#carBuilderContainer").addClass("carBuilderContainerDetails");
            var extraConfig = ((Config.ShowIncentives == "true") ? "&showIncentives=true" : "") + ((Config.ShowReviews) ? "&showReviews=1" : "");
			var url = ['/builder/views/details?year=', year, '&make=', encodeURIComponent(make), '&model=', encodeURIComponent(model), '&bodystyle=', encodeURIComponent(bodystyle), extraConfig].join('');
			var target = "details_target";
			var msg = ['Loading', make, model, 'Details...'].join(' ');
			carbuilder.load.ajax(url, target, msg, function(){detailsVehicle.init()});
        },

        trims : function (el) { //carbuilder.load.trims
			el = $(el)
			var selected = $(':selected', el),
				vehicleId = selected.val() || el[0].getAttribute('value'),
				trim = (selected.size() ? selected : el).attr("trim"),
				url,
				target,
				msg;

			//ie6 hides
            $('#detailQuickSubmit, #exteriorColors, #trims, #buildCarousel, #models_target, #gridCtrls, #details_target #detailColors').hide();
			$('#details_target').fadeOut('fast');
//            $("#exteriorColors").hide();
//            $("#trims").hide();
//            $("#buildCarousel").hide();

			if ($("#trims").attr('selectedIndex') == 0 && selected.size()) {
				carbuilder.load.reloadDetails();
				return;
			}
			detailsVehicle.vehicleId = vehicleId;
			//trim = (selected.size() ? selected : el).attr("trim");

//            $("#models_target").hide();
//            $("#gridCtrls").hide();
//            $("#details_target").fadeOut("fast");
//            $("#details_target #detailColors").hide();
            detailsVehicle.updateBreadCrumb("details");
			url = '/builder/views/trim?vehicleId=' + vehicleId + (Config.ShowAdditionalOptions ? '&showAdditionalOptions=true' : '&showAdditionalOptions=false');
			target = "details_target";
			msg = ["Loading", detailsVehicle.make, detailsVehicle.model, trim, "Details..."].join(' ');
			carbuilder.load.ajax(url, target, msg, function() {
				detailsVehicle.init(true);
				detailsVehicle.configure.init();
				//alert("load scripts");
				//carbuilder.load.scripts("/apps/builder/js/dump1.js");
				//carbuilder.load.scripts("/apps/builder/js/dump2.js");
				if (Config.EnableOptionLogic) {
					carbuilder.load.scripts("/api/logic?provider=jato&vehicleId=" + detailsVehicle.vehicleId);
					carbuilder.load.scripts("/api/logic?provider=jato&options=true&vehicleId=" + detailsVehicle.vehicleId);
				}
			});
        },

        graphic: function (msg) {$("#loaderTemplate").find(".message").html(msg).end().show();},	//show loading graphic

        ajax : function (url, target, msg, handler) { //root loader for all ajax calls, adds color and carbuilder id
            //RG: cbId is appended to every request and color
            if( url.indexOf("?") > -1 )
                url += "&cbId="+cbId + "&color=" + Config.Shade;
            else
                url += "?cbId="+cbId + "&color=" + Config.Shade;

            $.ajax( {
                type : "GET",
                url: url,
                beforeSend: function() {
                    if(target != null && target!="TB_ajaxContent") {
                        carbuilder.load.graphic(msg);
                    }
                },
                success: function(req){
                    $("#loaderTemplate").fadeOut(1);
                    eval( req );
                    if( target != null )
                        document.getElementById(target).innerHTML = __result.join("");
                    if( handler ) handler();
                }
            });
        },

        scripts: function( url, handler ) {  //carbuilder.load.scripts
            $.ajax( {
                type : "GET",
                url: url,
                beforeSend:function() {
                },
                success:function(req){
                    eval(req);
                    if (handler) handler();
                }
            });
        },

        track: function(viewType, viewExtra) {DDC.Tracker.track(viewType, viewExtra);}
    },

    fadeIn: function ($el) {
		if (!$.browser.msie) {
			$el.fadeIn(1000);
		} else {
			$el.show(.1, function () {
				$(this)[0].filters[0].enabled = false;
			});
			_el = $el;
		}
	},

    formatPrice : function (str, hideDecimal, showDollarSign) {
		var res = "Call",
			decimal = null;
		if (parseInt(str, 10) > 0) {
			res = '';
			str = str.split('.');
			if (str.length > 1 && parseInt(str[1], 10) > 0) {
				decimal = str[1];
			}
			str = str[0];
			// this loop adds commas every three characters for price formatting, starting from the ones place by factors of a thousand (ie, will correctly display a price with commas)
			for (var sliceEnd = str.length; sliceEnd > 0; sliceEnd = sliceEnd - 3 ) {
				var sliceStart = sliceEnd - 3;
				res = str.slice(sliceStart > 0 ? sliceStart : 0, sliceEnd) + (sliceEnd != str.length ? ',' : '') + res;
			}
			if (!hideDecimal) {
				res += (decimal == null) ? ".00" : decimal;
			}
			res = !!(showDollarSign) ? ('$' + res) : res;
		}
		return res;

	},

	debug: !Config.debug ? function () {} : function () {	// pass multiple arguments into carbuiler.debug to mimic console.log
		if (typeof window.console != 'undefined' && arguments.length) {
			console.log.apply(console, ['[carbuilder]'].concat([].splice.call(arguments, 0)));
		}
	}
}

var detailsVehicle = {
	year : 0,
	make : "none",
	model: "model",
	style : "style",
	vehicleId : "",
	mediaGalleryImg : null,
	slideShowCount : 1,
	slideShowPlay : true,
	slideShowInterval : 0,
	categories : new UniqueList(),
	vehiclePrice : 0,
	trims : "",
	form : "",
	optionTotal : 0,
	packageTotal: 0,
	formSend : false,
	inTransition: false, //holds for transition to finish before going to next photo
	step : 1, //current step for configurator

	toDigits: function (a) {return parseInt(a.replace(/\D/g,""), 10)},
	stripToDigits: function(o) {
		if (o.constructor == Array) {
			for (var i = 0; i < o.length; i++) {
				o[i] = this.toDigits(o[i]);
			}
		} else if (o.constructor == String) {
			o = this.toDigits(o);
		}
		return o;
	},

	init : function (trim) { //called when details page loads
		//reset option and package totals
		this.optionTotal = 0;
		this.packageTotal = 0;
		this.updateTotal();
		this.year = parseFloat($("#vehicleYear").text(), 10);
		var thumbsHtml = [],
			retail = '',
			$retail = $('#retailValue'),
			$quickSubmit = $('#detailQuickSubmit'),
			$next = $('#next'),
			$prev = $('#previous');
		carbuilder.load.track( 10, (trim) ? "CARBUILDER_CONFIGURE_VEHICLE" : "CARBUILDER_SUMMARY" );			//page tracking for webstats
		carbuilder.print("detailsetup");		//setup printing
		calc.moPayDiv = "detailsMonthlyPayment";	//setup montly payment range
		selectedOptions = new Array()

		$("#detailImageViewer img").slice(0, 8).each(function(){  //TODO: start debugging here!
			thumbsHtml.push("<img src='" + this.getAttribute("smallpicture") + "' />");
		});
		$("#detailMultiplePhotos").html(thumbsHtml.join('')).click(function(){detailsVehicle.showMediaGallery(true);})
		detailsVehicle.initCategorySelect();

		//initialize validation, submits, accountId
		$quickSubmit.find('input').click(function(){detailsVehicle.validate()}).end()
			.find('.detailSubmit').html('<img src="/apps/builder/images/' + Config.Shade + '/submit.gif" onClick="detailsVehicle.submitForm();">').end()
			.find('input[name=accountId]').val(Account.Id);

		//check for incentives
		if (!$("#detailList div[select=detailIncentives] li").size()) $("#detailIncentives").hide();
		else $("#detailIncentives").show();
		//calculate total
		if ($retail.size()) {
			var msrps = this.stripToDigits(($retail.text().indexOf("-") != -1 ? $retail : $("#msrpValue")).text().split("-")),
				destinations = this.stripToDigits($("#destinationValue").text().split('-'));
			retail = ["$",
					calc.format(msrps[0] + destinations[0], true),
					(msrps.length > 1) ? " - $" + calc.format(msrps[1] + destinations[destinations.length - 1], true) : ''
				].join('');
			$retail.text(retail);
		}
		this.priceCalc(retail);

		if (trim) {
			//if the Accessories resource is unchecked, then remove the Accessories page
			if ($("#jatoAccessoriesModule").size() && !Config.ShowAccessories) {
				$("#jatoAccessoriesModule").remove();
			}

			//update printer link
			carbuilder.print("trimsetup");

			//load trims
			$("#detailCtrlTrimWrapper").html(this.trims.replace("Select Trim", "Back to Model Summary").replace(this.vehicleId + "\"", this.vehicleId + "\" selected"));
		} else {
			//load trims
			this.trims = document.getElementById("detailCtrlTrimWrapper").innerHTML;

			//init tabs
			tab.init();

			//init trim comparison tool
			trimCompare.init();

			//init flash slideshow
			if ($("#detailSlideShow").size() > 0) {
				if (Config.Shade == "white")
					var so = new SWFObject("/apps/builder/swf/monoslideshow.swf", "SOmonoSlideshow", "278", "260", "7", "#FFFFFF");
				else if(Config.Shade ==  "black")
					var so = new SWFObject("/apps/builder/swf/monoslideshow.swf", "SOmonoSlideshow", "278", "260", "7", "#000000");
				so.addVariable("dataFile","/builder/views/slideshow?year="+this.year+"%26make="+encodeURIComponent(this.make)+"%26model="+encodeURIComponent(this.model).replace("%26","%2526")+"%26bodystyle="+encodeURIComponent(this.style)+"%26cbId="+Config.cbId);//Town and Country replacement %2526
				so.addVariable("showLogo", "false");
				so.addParam("wmode", "transparent"); // DNA726907
				so.write("detailSlideShow"); //accepts parameter for div to write to
			}

			//disable links for colors without photos
			$("#exteriorColors .colorSwatch").each(function() {
					if (this.getAttribute("colorPhoto") == "") {
						$(this).click(function(){});
						$(this).mouseover(function(){});
					}
				}
			);

		}
		//preload images
		try {
			imgs.preload("#detailColors .colorSwatch", "colorPhoto");//color photos
		} catch (e) {}//catch for preloading images inside frameset this sometimes causes problems

		if (navigator.userAgent.indexOf("Mac") != -1) {
			$("#detailCtrlTabs .tabSpacer").css("padding","22px 8px 0 8px");
		}
		
		if (Config.ShowDestinationCharge == "false") {
			$('#destinationValue').text('0').parent().hide();
		}

		//carbuilder.fadeIn($('#details_target'));
		$('#details_target').fadeIn('fast', function(){
			if (trim) {
				$('#buildCarousel').css({
					display: 'block'
				}).jcarousel({
					itemVisible: 1,
					itemScroll: 1,
					itemHeight: 450,
					nextButtonStateHandler : function(param1, param2, enabled) {
						if (!enabled) {
							$next.fadeOut();
							detailsVehicle.expandForm($("#detailsQuickAction").get(0),true);
							detailsVehicle.configure.summary();
						}
						else if ($next.css("display") != "block") $next.fadeIn();
					},
					prevButtonStateHandler : function(param1, param2, enabled) {
						if (!enabled)
							$prev.fadeOut();
						else if ($prev.css("display") != "block")
							$prev.fadeIn();
					},
					itemVisibleInHandler : {
						onAfterAnimation: function(carousel, li, index, state) {
							if (!$("#summaryList", li).size()) detailsVehicle.configure.adjustCarouselSize(li);
						}
					}
				});
				if (Config.isCanada) $("#carBuilderContainer #detailTrimMPG").hide();
				$next.fadeIn();
			}
		});
	},

	//submit form, show confirmation
	submitForm: function (stage, sendDiv, formType) {
		var form = $('#fullDetailsForm')[0],
			selectedVehicle = $("#trims option:selected").attr('index') > 0 ? $("#trims option:selected") : $("#trims option:eq(1)"),
			errorMsg = 'Please enter your',
			errors = $('[name=contact.firstName], [name=contact.lastName], [name=contact.email], [name=contact.phone]', form).filter(':not([value])'),
			queryString = '';
		$("input[name='vehicleId']", form).val(selectedVehicle.attr("vehicleId"));
		queryString = $("#fullDetailsForm .formFieldInclude").fieldSerialize();
		errors.each(function(i, el){
			var txt = ' ' + $('[required=' + $(this).attr('name') + '] span', form).text();
			if (i == errors.size() - 1 && errors.size() > 1 ) txt = ' and' + txt;
			if (i && errors.size() > 2 ) txt = ',' + txt;
			errorMsg += txt;
		});
		if (errors.size()) {
			alert(errorMsg + '.');
		} else {
			//queryString += $("#fullDetailsForm " + $("#fullDetailsForm #detailsQuickAction").fieldValue() + " input").fieldSerialize();
			carbuilder.debug('querystring: ', queryString);
			$.post($("#fullDetailsForm").attr("action"), queryString, function() {
				$("#detailQuickSubmit").html("").append("<div style='display:none;'>Your information has been sent.</div>").find('div').fadeIn("slow");
			});
		}
	},

	showSpins : function(url) {
		carbuilder.toggleFlash();
		TB_show('360 Spins', '/builder/views/spins?width=330&height=260&movieurl=' + url + '&doLoad=void()&doUnload=carbuilder.toggleFlash()');
	},

	validate : function(form) {
		if(!form) this.form = document.forms[0];
		var source = new String($("#detailQuickSubmit .detailSubmit img").attr('src'));
		if(source.indexOf("_F2.gif")==-1) $("#detailQuickSubmit .detailSubmit img").attr('src',source.replace(".gif","_F2.gif"));
	},

	showMediaGallery : function(initImage) {
		if (initImage) detailsVehicle.mediaGalleryImg = document.images['detailsVehiclePhoto1'].src.replace("200","400");
		carbuilder.toggleFlash();
		TB_show(this.year + " " + this.make + " " + this.model, '/builder/views/media?vehicleId='+detailsVehicle.vehicleId+'&width=640&height=500&doLoad=detailsVehicle.initMediaGallery()&doUnload=detailsVehicle.closeMediaGallery()');
	},

	showData : function(caption, load, unload, width, height) {
		if(caption == true) {
			$("#tb_target").html(eval(load));
		} else {
			carbuilder.toggleFlash();
			if(!width) width = 640;
			if(!height) height = 480;
			TB_show(caption, '/builder/views/tb_load?width='+width+'&height='+height+'&doLoad=detailsVehicle.showData(true,"'+load+'");&doUnload='+unload);
		}
	},

	closeMediaGallery : function() {
		carbuilder.toggleFlash();
		detailsVehicle.mediaGalleryImg = null;
		this.endSlideShow();
	},

	showCalc : function(id) {
		var target = $('#' + id);
		if (target[0]) {
			if (target.css('display') == 'block') {
				if (id == 'indexAdvancedContainer') {
					if (carbuilder.maxMPG != 0) {
						carbuilder.mpgSlider.setMaximum(parseInt(carbuilder.maxMPG));
						$('#indexAdvancedContainer .gridCtrls').fadeOut();
					}
				}
				target.slideUp('fast', function() {
					if (id == 'indexAdvancedContainer') {
						var anchor = $('#indexAdvanced a');
						anchor.text(anchor.text().replace('Simple', 'Advanced'));
					}
				});
			} else {
				target.slideDown('fast', function() {
					if (id == 'indexAdvancedContainer') {
						if (carbuilder.maxMPG != 0) {
							$('#indexAdvancedContainer .gridCtrls').fadeIn();
							carbuilder.mpgSlider.setHighValue(parseInt(carbuilder.maxMPG) - 1);  //fix slider bar displaying 0px long
							carbuilder.mpgSlider.setHighValue(parseInt(carbuilder.maxMPG));
						}
						var anchor = $('#indexAdvanced a');
						anchor.text(anchor.text().replace('Advanced', 'Simple'));
					}
				});
			}
		}
	},

	showPayment : function() {
		carbuilder.toggleFlash();
		$("#detailsMonthlyPayment").html(document.getElementById("monthlyPayment").innerHTML);
	},

	toggle : function(num) {
		if(num == 1) {
			$("#detailFeatures").hide();
			$("#detailSpecs").show();
		} else {
			$("#detailSpecs").hide();
			$("#detailFeatures").show();
		}
	},

	initCategorySelect : function() {
		//initialize category select box
		var select = document.getElementById("detailCategories");
		if(!select) return;

		//attach onChange event
		$(".detailsSelectBox").change (
			function() {
				//toggle all uls off
				$('#detailList div[select='+this.id+'] ul').hide();
				//toggle categories requested from select box on, assumes unique category names
				var values = this.value.split(",");
				for(i=0;i<values.length;i++) $('#detailList ul[category='+values[i]+']').show();
			}
		);
	},

	expandForm : function (select, noanimation) {
		select = $(select);
		var toExpand = select.val();
		if (select.size()) {
			select.parents('form').find('input[name=source]').val($(':selected', select).attr('source'));
		}

		//expands the data entry forms on the details and trim pages
		$("#detailsQuickAction option").each(function() {
			var target = $(this.value).hide();
			if (toExpand == this.value) {
				$('.formFieldInclude', $('#detailGetAQuote, #detailEmailIt, #detailRequestInfo')).removeClass('formFieldInclude');
				$('input, textarea', $('.detailQuickInput', target)).addClass('formFieldInclude');
				if (!noanimation) { //noanimation for last page on configure section, no slide
					target.slideDown("normal",function() {
						//check for summary page resizing in IE6
						if ($("#summaryList").size()) {detailsVehicle.configure.adjustCarouselSize($("#summaryList").parent().get(0));}
					});
				} else {
					target.show();
				}
			}
		});
    },

	initMediaGallery : function() {
		//initalize colors
		var html = $("#exteriorColors").html(),
			_imgs = {
				exterior: {thumb: [], med: [], lrg: []},
				interior: {thumb: [], med: [], lrg: []},
				addImg: function (img, i) {
					var dest = (img.attr("type") == "exterior") ? 'exterior' : 'interior';
					this[dest].thumb.push('<img show="evoxStill' + i + '" group="' + dest + 'Stills img" id="evoxStillThumb' + i + '" src="' + img.attr("smallpicture") + '">');
					this[dest].med.push('<img class="medEvox" show="evoxStillLarge' + i + '" group="mediaDisplayLarge img" id="evoxStill' + i + '" src="' + img.attr("mediumpicture") + '">');
					this[dest].lrg.push('<img id="evoxStillLarge' + i + '" src="' + img.attr("largepicture") + '">')
				},
				asHtml: function (path) {
					if (path) {
						var res = this;
						path = path.split('.');
						for (var i = 0; i < path.length; i++) {
							res = res[path[i]];
						}
						return res.join('');
					}
				}
			};
		_imgs.exterior.med.push('<img id="mediaColorPhoto" />');
		_imgs.exterior.lrg.push('<div id="closeZoom">Close</div>');
		$("#mediaCarTitle").html(detailsVehicle.model);
		html = html.replace(/carbuilder\.changeColor\(this\)/g, "carbuilder.changeColor(this,true)").replace(/carbuilder\.changeColor\(this,false,true\)/g, "carbuilder.changeColor(this,true,true)");
		$("#mediaDisplayContainer #mediaColors").html(html);
		$("#mediaColors .colorName, #mediaColors h2").remove();

		//initializes the media gallery and attaches necessary events
		$("#mediaHeader").html("<img src='" + $("#detailsVehiclePhoto1").attr("mediumpicture") + "'>");
		$(($("#detailImageViewer").size() ? "#detailImageViewer" : "#trimImageViewer") + " img").each(function(i){_imgs.addImg($(this), i)});
		$("#exteriorStillThumbs").html(_imgs.asHtml('exterior.thumb'));
		$("#exteriorStills").html(_imgs.asHtml('exterior.med'));
		$("#mediaDisplayLarge").html(_imgs.asHtml('exterior.lrg'));
		$("#interiorStillThumbs").html(_imgs.asHtml('interior.thumb'));
		$("#interiorStills").html(_imgs.asHtml('interior.med'));

		//attach events for main menu
		$("#mediaHeaderMenu li").click(function() {
			$("#mediaHeaderMenu li").removeClass("mediaHeaderSelected");
			$(this).addClass("mediaHeaderSelected");
			detailsVehicle.endSlideShow();
			$("#mediaDisplay div").hide();
			var shw = this.getAttribute("show").split(",");
			detailsVehicle.mediaShow(shw[0], this.getAttribute("group"));
			for (var i = 0; i < shw.length; i++) {
				$("#" + shw[i]).show();		//show divs that are in 'show' property
			}
			$("#mediaWrapper #mediaSelectionTitle").html($(this).attr("title"));
		});

		//attach events for photo displaying from thumbnail
		$("#mediaListing img").click(function() {
			detailsVehicle.endSlideShow();
			detailsVehicle.mediaShow($(this).attr("show"), $(this).attr("group"));
		});

		//attach events for zooming to large photo
		$("#mediaDisplay img").bind('click', function() {
			detailsVehicle.endSlideShow();
			$("#mediaDisplayLarge").show();
			$("#" + this.getAttribute("show")).show();
			detailsVehicle.mediaShow(this.getAttribute("show"), this.getAttribute("group"));
		});
		if (detailsVehicle.mediaGalleryImg == null) {
			$("#mediaDisplay img:eq(1)").load(function(){detailsVehicle.slideShow(true)});  //start slideshow after 2nd medium size photo has loaded
		}

		//if somone has clicked zoom from the details page, display that picture instead of the slideshow
		if (detailsVehicle.mediaGalleryImg != null) {
			document.images["mediaColorPhoto"].src = detailsVehicle.mediaGalleryImg;
			detailsVehicle.mediaShow("mediaColorPhoto","exteriorStills img");
		}
		//360 spins
		if ($('#detailMediaSelector').attr('exteriorSpin').indexOf("$Arrays")!=-1) {
			$("#spinThumbs").html("Interior and exterior spins are not available for this model.");
		}
		//preload images
		imgs.preload("#detailColors .colorSwatch","colorPhotoLrg");//color photos
	},

	priceCalc : function(msrp, form) {
		form = $('#' + (form || 'calcForm'));
		if (form.size()) {
			var price = (msrp || $("#msrpValue").text()).split('-');
			if (form.attr('id') != 'calcForm' && price.length < 2) {}
			else {price = this.stripToDigits(price);}
			$('input[name=minPrice]', form).val(price[0]);
			$('input[name=maxPrice]', form).val(price[price.length - 1])
			calc.initialize(form.attr('id'));			//initializes the price calculator
		}
	},

	updateOptions : function(chkbox) {  //needs work for DNA DNA546525
		var chkbox = $(chkbox),
			price = parseFloat(chkbox.attr("msrprice"), 10);
		if (chkbox.attr("category") == "option") {
			this.optionTotal += (chkbox.is(':checked') ? 1 : -1 ) * price;
			$("#optionValue").html("$" + this.optionTotal);
		} else {
			this.packageTotal += (chkbox.is(':checked') ? 1 : -1 ) * price;
			$("#packageValue").html("$" + this.packageTotal);
		}
		this.updateTotal();
	},

	updateTotal : function() {
		var totalPrice = 0;
		if ($("#msrpValue").text().indexOf("-") != -1) return;
		totalPrice += parseFloat(document.getElementById("msrpValue").innerHTML.replace(/[$,]/g,""), 10);
		totalPrice += parseFloat(document.getElementById("destinationValue").innerHTML.replace(/[$,]/g,""), 10);
		totalPrice += this.packageTotal;
		totalPrice += this.optionTotal;
		$("#retailValue").html("$"+calc.format(totalPrice, true));
		detailsVehicle.priceCalc(new String(totalPrice));
	},

	mediaShow : function(show, group, callback) {
		if (group) { //group is the group of objects that obj is associated with
			$("#" + group).hide();
		}
		if (!detailsVehicle.inTransition) {
			detailsVehicle.inTransition = true;
			$("#" + show).fadeIn("normal",function(){detailsVehicle.inTransition=false;if(callback){callback()}});
		}
	},

	slideShow : function(play) {
		if (play) this.slideShowPlay = true; //initialize slideshow
		this.slideShowCount++;
		detailsVehicle.mediaShow("evoxStill" + this.slideShowCount, "exteriorStills img");
		if (this.slideShowPlay) {
			this.slideShowInterval = setTimeout(function(){
				detailsVehicle.slideShow()
			}, 2000);
		}
		if ($("#exteriorStills img").size() <= this.slideShowCount) this.slideShowCount = 0;
	},

	endSlideShow : function() {
		this.slideShowPlay = false;
		clearInterval(this.slideShowInterval);
	},

	/*checkInput : function() {
		//checks input values to see if everything has been entered then changes the color
		//of the submit button to orange
		$("#detailQuickSubmit .required").each(
			function() {
				if(this.value != "" && this.innerHTML.indexOf("*") != -1) {
					$(this).removeClass("detailRequired");
				} else if(this.value == "" && this.innerHTML.indexOf("*") != -1) {
					$(this).addClass("detailRequired");
				}
			}
		);
	},*/

    configure : {
        init : function() {//initializes configuration section
            //carousel
            this.step = 1;
            $("#buildCarousel .itemDescriptionExpand").click(function() {
				var item = $("#"+this.getAttribute("description"));
				if (item.css("display") == "block") {
					this.src = "/apps/builder/images/" + Config.Shade + "/show.gif";
					item.slideUp("fast");
				} else {
					this.src = "/apps/builder/images/" + Config.Shade + "/hide.gif";
					item.slideDown("fast");
				}
			});
        },

        summary : function(link) { //loads info from the summary page
            //get info and post to summary page
            var html = "<tr><td><h2>Summary</h2></td><td class='price'>Nothing Selected</td></tr>",
            	formData = "";//used to update form information with the vehicle information
			$("#buildCarousel input").each(function() {
				$this = $(this);
				if ($this.is(':checked')) {
					html += "<tr><td>" + $this.attr("optionName") + "</td><td class='price'>" + carbuilder.formatPrice($this.attr("msrprice"), false, true);
                    if ($this.attr("id") != "") {
                        formData += '<input type="hidden" name="selectedOption" value="'+ $this.attr("id") + '" class="formFieldInclude"/>';
                    }
                    if (Config.ShowInvoice == "true") {
                        html += " / " +
                            carbuilder.formatPrice($this.attr("invoiceprice"), true, true) + "</td></tr>";
                    }
                    if ($this.attr("description") && $this.attr("description").indexOf("Package") != -1) {
                        html += "<tr><td class='summaryDescription' colspan='2'>" + $("#" + $this.attr("description")).html()+"</td></tr>";
                    }
                }
            });
            var summaryHeader = (Config.ShowInvoice=="true")?"MSRP / Invoice":"MSRP";
            if (html.length > 59) html = html.replace("Nothing Selected", summaryHeader);
            $("#summaryList").html(html);
            detailsVehicle.configure.adjustCarouselSize($("#summaryList").parent().get(0));

            //update form information with the vehicle information
            $("#fullDetailsForm").append(formData);
        },

		//updates the jcarousel frame size from the height of the carousel pane passed in (li)
		adjustCarouselSize : function(li/*, clipOffset*/) {
            if (li.scrollHeight > 410) {
				var sizeOf = {
					offset: {
						top: parseFloat($(li).css("padding-top")),
						bottom: parseFloat($(li).css("padding-bottom"))
					}
				};
				sizeOf.li = li.scrollHeight - sizeOf.offset.top - sizeOf.offset.bottom;
				/*if(clipOffset && typeof clipOffset == 'number'){
					sizeOf.clip = sizeOf.li + clipOffset;
				} else {*/
				sizeOf.clip = sizeOf.li + 2;
				/*}*/
				$(li).css("height", sizeOf.li + "px");
                $('#buildCarousel .jcarousel-clip').css("height", sizeOf.clip + "px");
            } else {
                $(li).css("height", "400px");
                $('#buildCarousel .jcarousel-clip').css("height", "400px");
            }
        }

    },

	//update top bread crumb navigation
	updateBreadCrumb : function(crumb) {
		var html = "";
		var title = "";
        var clickEvent = "";

        switch(crumb) {
			case "details":
				html = ' &gt; <a href="javascript:carbuilder.load.reloadDetails()">Trim</a>' + html;
				title = "<h2>Configure Vehicle</h2>";
			case "trim":
				if (Config.InitialModel != null) {
					Config.InitialModel = null;
                    if (Config.Makes.indexOf(",") != -1) {
                        clickEvent = "$('#menuWrapper').hide();carbuilder.intro='model';carbuilder.init();carbuilder.intro=Config.Opener;detailsVehicle.updateBreadCrumb('model');";
                    } else {
                        clickEvent = "$('#menuWrapper').hide();carbuilder.init();";
                    }
                }
				if (carbuilder.modelPage == "model") {
					html = ' &gt; <a href="javascript:void(0);" onClick="$(\'#details_target\').hide();$(\'#menuWrapper, #models_target\').show();detailsVehicle.updateBreadCrumb(\'model\');'+clickEvent+'">Model</a>' + html;
				} else {
					html = ' &gt; <a href="javascript:void(0);" onClick="$(\'#details_target\').hide();$(\'#models_target\').fadeIn(\'fast\');detailsVehicle.updateBreadCrumb(\'model\');'+clickEvent+'">Model</a>' + html;
				}
				if (title == "") title = '<h2>Browse / Select Vehicle Trim</h2>';
			case "model" :
                if ((clickEvent && clickEvent.length != 0) || Config.InitialMake != "") { //logic for an InitialModel entry
                    carbuilder.debug("breadcrumb:initial model entry");
                    html = (carbuilder.intro!="model") ? '<span>Go back to: <a href="#" onClick="carbuilder.load.makes(\'models_target\');">Make</a>' + html : (html.length > 0) ? '<span>Select: ' + html : '';
                } else {
                    carbuilder.debug("breadcrumb:standard model entry");
                    html = (carbuilder.intro!="model") ? '<span>Go back to: <a href="#" onClick="carbuilder.load.intro(\'models_target\');">Make</a>' + html : (html.length > 0) ? '<span>Select: ' + html : '';
                }
                if (title == "") {
					title = '<h2>Select Model</h2>';
				}
				break;
			case "make":
				title = "<h2>Select Make</h2>";
		}
		html = (html.length > 0) ? title + html + "</span>" : html = title;
		$("#breadCrumb").html(html);
	},

	compare : function(selectObj) {
		var trims = $("#trims"),
			attributeHeadings = trims.attr("header").split(","),
			attributes = trims.attr("header").toLowerCase().replace(/[\s\!]/g,"").split(","),
			html = "";
		$("option:gt(0)", trims).each(function() {
			html += '<div class="carCompare">';
			for (var i = 0; i < attributes.length; i++) {
				var heading = (attributeHeadings[i].charAt(0) == '!') ? "" : (attributeHeadings[i] + ": ");
				html += "<div>" + heading + $(this).attr(attributes[i]) + "</div>";
			}
			html += '</div>';
		});
		return html;
	}
};

function UniqueList() {
	this.items = "";
	this.add = function( item ) {
		if (this.items.indexOf(item) < 0 ) {
			if (this.items != "" ) {
				this.items += ",";
			}
			this.items += item;
		}
	}

	this.toArray = function() {
		return this.items.split(",");
	}

	this.addToSelectBox = function( select ) {
		var list = this.toArray();
		for (var i = 0; i < list.length; i++ )
			select.options[select.length] = new Option(list[i],list[i]);

		if (select.length <= 2) { //if only 1 item in select box, select it
		 	select.selectedIndex = 1;
		}
	}
}

function filter() {
	$('div.model').each(function() {
		if (carbuilder.matches(this)) {
			this.style.display = "block";
		} else {
			this.style.display = "none";
		}
	});
}

function submitConfirmation() {
	detailsVehicle.submitForm(3);
}

function boxLoaded() {
	$("#menuWrapper").html($("#menuWrapper").html().replace("bb","bb-tab"));
}

var tab = {
	tabDiv : "#detailCtrlTabs",
	init : function() {
		$(this.tabDiv + " a").click(function(){tab.select(this);})
	},
	select : function(tab) {
		if (tab.className == "tabSelected") return;//check to see if tab is already selected
		$(this.tabDiv + " a").each(function() {
			$($(this).attr("hide")).hide();
			$(this).removeClass("tabSelected");
		});
		$($(tab).attr("show")).fadeIn();
		$(tab).addClass('tabSelected');
		if($(tab).html().indexOf("Build") != -1) trimCompare.select();
	}
}

var imgs = {
	preload : function (jref, attrib) { //takes jquery reference and the attribute that the image name resides in
		$(jref).each(function(){
			var img = new Image();
			img.src = this.getAttribute(attrib);
		});
	}
}

var curve = {
	scrollInterval : null,
	scrollHeight : 1,
	overTimeout : null,
	containerHeight : 0,

	init : function() {
        carbuilder.load.track( 10, "CARBUILDER_CURVE_INTRO" );
        if (Config.Makes.indexOf(",") == -1) {
            $("#carBuilderHeader").hide(); //hide breadcrumb if there are no other makes because there is no 'back'
        } else { //if there is a back, that means there are multiple makes, put them across the top

        }
        //$("body").addClass("curve"); moved this to execution statement for logos page
		this.scrollHeight = $("#curveScroll").height();
		$("#menuWrapper").hide();

        var hoverImage = curve.firstImage();
        curve.over(hoverImage);
		curve.out(hoverImage);
		//carbuilder.fadeIn($('#models_target'));
		$('#models_target').fadeIn();

		curve.containerHeight = $("#curveScrollContainer").height();

		//hide scroller buttons if they are not needed
		if ($("#curveScrollContainer").height() > $("#curveScroll").height()) {
			$("#curveScroller").hide();
		}
		$("#curveScroll").height($("#curveScroll").get(0).offsetHeight);
	},

    firstImage : function() {
        //if initial vehicle is set for curve
        var img = "";
        if (Config.Curve.initialVehicle != "" && Config.Curve.initialVehicle.split(",").length > 3) {
            var args = Config.Curve.initialVehicle.split(",");
            $("#curveScroll .modelCurve").each(function(){
                if (this.getAttribute("modelyear") == args[0] && this.getAttribute("make") == args[1] && this.getAttribute("modelname") == args[2] && this.getAttribute("bodystyle") == args[3] ) {
                    img = this;
                }
            });
        }
        if (img == "") { //if initial vehicle is not set for curve, get the first vehicle that has a photo
            $("#curveScroll .modelCurve").each(function(){
                if (this.getAttribute("picture").indexOf("missing-photo") == -1 && img == "") {
                    img = this;
                }
            });
        }
        if (img == "") {
            img = $("#curveScroll .modelCurve").get(0);
		}
		return img;
    },

    go : function(model) {  // follow link to inventory
		model = $(model);
		document.location = [Config.Links.research,
			"?SByear=",
			encodeURIComponent(model.attr("modelyear")),
			"&SBmake=",
			encodeURIComponent(model.attr("make")),
			"&SBmodel=",
			encodeURIComponent(model.attr("modelname")),
			"&SBbodystyle=",
			encodeURIComponent(model.attr("bodystyle"))].join('');
	},

	imgLoaded : function(img) {
		var modelDiv = $("#" + $(img).attr("modelDiv"));
		modelDiv.attr("imgLoaded","true");
		document.images["modelPicture"].src = modelDiv.attr("picture");
	},

	over : function(model) {
		var modelPicture = $('#modelPicture');
		model = $(model);
		model.addClass("over");
		if (model.attr("imgLoaded") != "true") {
			modelPicture.attr("src","/apps/builder/images/" + Config.Shade + "/curve_loading.gif");
			clearTimeout(curve.overTimeout);
			curve.overTimeout = setTimeout(function() {
				var image = new Image();
				image.src = model.attr("picture");
				//image.onload = setTimeout(function(){curve.imgLoaded(image)},100);
				$(image).attr("modelDiv", model.attr('id'));
				if ($.browser.msie) {
					setTimeout(function(){curve.imgLoaded(image)},500);
				} else {
					$(image).load(function(){curve.imgLoaded(image)});
				}
			}, 100);
		} else {
			modelPicture.attr("src", model.attr("picture"));
		}

		$("#curveModelName").html([model.attr("modelyear"), model.attr("make"), model.attr("modelname")].join(' '));

        var inStockVerbiage = (model.attr("modelname").charAt(model.attr("modelname") - 1) == 's') ? "s in stock" : " in stock";

        //build html, check for page defs
        var curveHtml = "<div class='actionPrices'>$" + calc.format(model.attr("minprice"), true) + " - $" + calc.format(model.attr("maxprice"), true) + "</div>";
        if (Config.Links.newInventory.indexOf("404") == -1 )
            curveHtml += "<div class='actionNewInv' onClick='document.location = \"" + curve.link("newInventory", model) + "\" '><a href='" + curve.link("newInventory", model) + "'>New " + model.attr("modelname") + inStockVerbiage + "</a></div>";
        if (Config.Links.ultimateInventory.indexOf("404") == -1 && Config.Links.newInventory.indexOf("404") != -1)
            curveHtml += "<div class='actionNewInv' onClick='document.location = \"" + curve.link("ultimateInventory", model) + "\" '><a href='" + curve.link("ultimateInventory", model) + "'>New " + model.attr("modelname") + inStockVerbiage + "</a></div>";
        if (Config.Links.usedInventory.indexOf("404") == -1 )
            curveHtml += "<div class='actionUsedInv' onClick='document.location = \"" + curve.link("usedInventory", model)+"\" '><a href='" + curve.link("usedInventory", model) + "'>Used " + model.attr("modelname") + inStockVerbiage + "</a></div>";

        curveHtml += "<div class='actionBuild' onClick='curve.go(document.getElementById(\"" + model.attr('id') + "\"));'><a href='javascript:" + curve.link("build", model)+"'>Build & Research a new " + model.attr("modelname") + "</a></div>";

        $("#curveActions").html(curveHtml);
	},

	//build links for new inventory, used inventory, and build research
	link : function(type, model) {
		model = $(model);
		var page = Config.Links[type],
			separator = '&',
			params = ['?reset=InventoryListing',
				'make=' + encodeURIComponent(model.attr("make")),
				'model=' + encodeURIComponent(model.attr('modelname'))];

		if (type != 'ultimateInventory') {
			var bodystyle = (model.attr('bodystyle') == "Sport Utility Vehicle") ? "SUV" : encodeURIComponent(model.attr('bodystyle'));
			separator += 'SB';
			params.push('bodystyle=' + bodystyle);
		}
		return (type == "build") ? ("") : (page + params.join(separator));
	},
	out : function(model) {
		$(model).removeClass("over");
	},
	scrollDown : function() {
		curve.scroll(-curve.containerHeight);
	},
	scrollUp : function() {
		curve.scroll(curve.containerHeight);
	},
	scroll : function(direction) {
		var start = parseFloat($("#curveScroll").css("top"), 10);
		start += direction;
		if (start < -curve.scrollHeight || start > 0) {
			clearInterval(curve.scrollInterval);
			return;
		}
		$("#curveScroll").animate({top: start},"normal");
	},
	stopScroll : function() {
		clearInterval(curve.scrollInterval);
	}
}

var trimCompare = {
    trim : {
        invoice : "",
        msrp : 0,
        trim : "",
        transmission : "",
        horsePower : "",
        mpg : "",
        engine : ""
    },

    trims : new Array(),

    init : function() {
		var html = "";
        var rows = new Array();

		//build header table
		html = "<table cellpadding=0 cellspacing=0>";
		$($("#detailTrimList .trimSummary").get(0)).find("div").each(function(count){
            html += "<tr class='"+((count%2==0)?"bgAlt":"")+"'>";
           	html += "<td>" + this.getAttribute("rowName") + "</td>";
            html += "</tr>";
        	rows.push(this.className);
		});
        html += "</table>";
		$("#tmHeader").html(html);

		//build table
		html = "<table cellpadding=0 cellspacing=0 align='left'>";
        for(var i=0;i<rows.length;i++) {
            html += "<tr class='"+((i%2==0)?"bgAlt":"")+"'>";
            $("."+rows[i]).each(function(count){
                html += "<td>" + this.getAttribute("value") + "</td>";
            });
            html += "</tr>";
        }
        html += "</table>";
        $("#tmPopulate").html(html);
	},

	select : function() { //set table height for browsing
		var tmWidth = $("#detailCtrls").width() - $("#tmHeader").width() - 2;
		$("#tmPopulate").css("width",tmWidth+"px");
		$("#tmPopulate tr").each(function(count) {$($("#tmHeader tr").get(count)).height(this.clientHeight+"px");});
	}
}

var bodyStyles = {
	models : new UniqueList(),
	styles : new UniqueList(),
	previousSelection : null,

	init : function() {
		var styles = carbuilder.styles.toArray();
		$("#introModelList a").each(function(count){
			bodyStyles.styles.add( this.getAttribute("bodystyle") );
			if(count == 0) {$("#intro_pic").attr("src",this.getAttribute("picture"));}
		});

		var bodyStyleArray = this.styles.toArray();
		html = "<ul>";
		for(var i=0;i<bodyStyleArray.length;i++) {
			html += "<li class='bodyStyleLi'><a class='bodyStyleLink' href='javascript:void(0);' onMouseOver='bodyStyles.show(this);' type="+bodyStyleArray[i]+" div='introBody"+bodyStyleArray[i].replace(/\s/g,"")+"'>" + bodyStyleArray[i] + "</a><ul id='introBody"+bodyStyleArray[i].replace(/\s/g,"")+"'></ul>";
		}
		$("#intro_bodystyles").html(html+"</ul>");

		$("#intro_bodystyles a").each(function(){
			var div = $("#"+$(this).attr("div"));
			div.css("position","absolute");
			div.css("top",(this.offsetTop+$(this).height())+"px");
			div.css("left",this.offsetLeft+"px");
		});

		$("#introModelList a").each(function(){
			var ul = $("#introBody"+this.getAttribute("bodystyle").replace(/\s/g,""));
			ul.append("<li>");
			ul.append(this);
			ul.append("</li>");
		});

		$("#introModelList").hide();
	},

	show : function(link) {
		bodyStyles.hide(bodyStyles.previousSelection);
		var div = $("#"+$(link).attr("div"));
		div.slideDown("fast");
		bodyStyles.previousSelection = link;
	},
	hide : function(link) {
		if(link == null) return;
		div = $("#"+$(link).attr("div"));
		div.slideUp("fast");
	},

	showStyle : function(styleObj) {
		//alert(styleObj.getAttribute("type"));
		$("#introModelMenu a").each(function(){
			//alert(this.getAttribute("bodystyle"));
			if(this.getAttribute("bodystyle") == styleObj.getAttribute("type")) {
				//$(this).slideDown("fast");
				$(this).parent().show();
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	}
}

var bodyStyles2 = {
	models : new UniqueList(),
	styles : new UniqueList(),

	init : function() {
		var styles = carbuilder.styles.toArray();
		$("#introModelList a").each(function(count){
			bodyStyles.styles.add( this.getAttribute("bodystyle") );
			bodyStyles.models.add( this.getAttribute("modelname") );
			if(count == 0) {$("#intro_pic").attr("src",this.getAttribute("picture"));}
		});

		var modelArray = this.models.toArray();
		var html = "";
		for(var i=0;i<modelArray.length;i++) {
			html += "<a href='javascript:void(0);' onClick='bodyStyles.show(this);' div='introModelSelector"+i+"'><span>+</span>"+modelArray[i]+"</a><div id='introModelSelector"+i+"' style='display:none;'></div>";
		}
		$("#introModelMenu").html(html);

		var bodyStyleArray = this.styles.toArray();
		html = "";
		for(var i=0;i<bodyStyleArray.length;i++) {
			html += "<a href='javascript:void(0);' onClick='bodyStyles.showStyle(this);' type="+bodyStyleArray[i]+"><img src='/apps/builder/images/"+bodyStyleArray[i].toLowerCase()+".jpg'/></a>";
		}
		$("#intro_bodystyles").html(html);

		html = "";
		for(var i=0;i<modelArray.length;i++) {
			var model = modelArray[i];
			var div = $("#introModelSelector"+i);
			$("#introModelList a").each(function(){
				if($(this).attr("modelname").indexOf(model) != -1) {
					div.append(this);
				} else {

				}
			});
		}
		$("#introModelList").hide();
	},

	show : function(link) {
		if(link.getAttribute("type") != null) {
			alert("show:"+link.getAttribute("type"));
		} else {
			var div = $(link).find("span");
			if(div.html() == "+") {
				$("#"+$(link).attr("div")).slideDown();
				div.html("-");
			} else {
				$("#"+$(link).attr("div")).slideUp();
				div.html("+");
			}
		}
	},

	showStyle : function(styleObj) {
		$("#introModelMenu a").each(function(){
			if(this.getAttribute("bodystyle") == styleObj.getAttribute("type")) {
				$(this).parent().show();
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	}
}

var fourStyles = {
		interval : null,

		init : function() {
			this.populate("Cars");this.populate("SUVs");this.populate("Trucks");this.populate("Vans");
		},

		getCategory : function(type) {
			switch(type) {
				case "Cars":
					return $("#fourStyleModels div[bodystyle=Sedan]").add("#fourStyleModels div[bodystyle=Coupe]").add("#fourStyleModels div[bodystyle=Hatchback]").add("#fourStyleModels div[bodystyle=Wagon]");
					break;
				case "SUVs":
					return $("#fourStyleModels div[bodystyle=Sport Utility Vehicle]");
					break;
				case "Vans":
					return $("#fourStyleModels div[bodystyle*=Van]").add("#fourStyleModels div[bodystyle=Minivan]");
					break;
				case "Trucks":
					return $("#fourStyleModels div[bodystyle=Pick-Up]").add("#fourStyleModels div[bodystyle*= Cab]");
					break;
			}
		},

		populate : function(column) {
			//$("#fourStyle"+column).append(column+":");
			fourStyles.getCategory(column).each(function(count){
				$("#fourStyle"+column).append(this);
				var preloadImg = new Image();
				preloadImg.src = this.getAttribute("picture");
				if(count == 0) {fourStyles.over(this);fourStyles.out(this);}
			});
		},

		over : function(obj) {
			$(obj).addClass("over");
			$(obj).parent().find("img").attr("src",$(obj).attr("picture"));
		},

		out : function(obj) {
	    	$(obj).removeClass("over");
		}
}

var acura = {
		init : function() {
			$("#carBuilderHeader").hide();
			//carbuilder.fadeIn($('#models_target'));
			$('#models_target').fadeIn();
        },

		go : function(year,make,model,bodyStyle) {
			$("#carBuilderHeader").show();
			carbuilder.load.details(year,make,model,bodyStyle);
		}
}

$.fn.attachQuickTimeMovie = function(movieUrl) {
	this.each(function() {
		if(navigator.userAgent.indexOf("MSIE")!=-1) {
			this.innerHTML = '<OBJECT CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" WIDTH="320" HEIGHT="240" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab"><PARAM name="src" VALUE="'+movieUrl+'"><PARAM name="autoplay" VALUE="true"><PARAM name="controller" VALUE="false"></OBJECT>';
		} else {
			this.innerHTML = '';
			var movie = document.createElement("embed");
			movie.type = "video/quicktime";
			movie.src = movieUrl;
			movie.width = "320";
			movie.height = "240";
			movie.autoplay = "true";
			movie.controller = "false";
			this.appendChild(movie);
		}
	});
}

//ie7 fix for option logic
var exteriorColors;
var packages;
var options;
var interiorColors;

