/**
 * @fileoverview Compare Tool Redesign (controller).
 * @name Controller
 * Requires Prototype version 1.6.0 or greater.
 */

/**
 * Compare Tool Redesign Controller class.
 * @author Ed Jenkins
 */
var Controller = Class.create();

/**
 * Compare Tool Redesign Controller prototype.
 * @scope Controller.prototype
 */
Controller.prototype =
{
    /**
     * BI Event.
     */
    bi_event: "",

    /**
     * Last Inline Ad info
     */
    bi_last_inline_ad: "",

    /**
     * Prior to page initilizing, holds the car data persisted in cookies
     */
    cookieStatePrePageInitialization: null,

    /**
     * Has Key Differences been initialized?
     */
    isKeyDifferencesInitialized: false,

    /**
     * Constructor.
     * @constructor
     * @throws exception if Prototype 1.6.0 or greater is not loaded.
     */
    initialize: function()
    {
        // Make sure Prototype is included.
        var exception = "Prototype version 1.6.0 or greater is required.";
        if (typeof Prototype == "undefined")
        {
            throw(exception);
        }
        // Make sure it is version 1.6.0 or greater.
        var ver = Prototype.Version.split(".");
        var major = ver[0];
        var minor = ver[1];
        if (major < 1  || minor < 6)
        {
            throw(exception);
        }
        this.isKeyDifferencesInitialized = false;
        //we have to wait for the namespace to load before executing this - these methods have dependencies on other CTR objects.
        document.observe('dom:loaded', function() {
            ATC.cs.research.ctr.controller.loadSpotlightAds();
        });
    },

    /**
     * Gets the ZIP code.
     * @return {string} the ZIP code.
     */
    getZIP: function()
    {
        return ATC.cs.research.ctr.model.getZIP();
    },

    /**
     * Refreshes car data.
     * Will reload all cars currently displayed except the inline ad.
     * You can also add an additional car by styleId or by YMM.
     */
    updateCars: function()
    {
        var model = ATC.cs.research.ctr.model;
        var x = 1;
        var y = 5;
        var z = 0;
        var styles = new Array();
        for (x = 1; x < y; x++)
        {
            var car = model.getCar(x);
            if (car == null)
            {
                continue;
            }
            if (car.ctr.adType == 1)
            {
                continue;
            }
            var styleId = car.ctr.styleId;
            styles[z++] = styleId;
        }
        var styleIds = styles.join(",");
        //console.debug("controller.updateCars - styleIds=" + styleIds);
        var zip = model.getZIP();
        ATC.cs.research.ctr.controller.loadCarsForStyleIds(styleIds, zip, true);
    },

    /**
     * Reloads all cars and adds another car by styleId or by year, make, and model.
     * @param {string} year the year.
     * @param {string} make the make.
     * @param {string} model the model.
     * @param {string} styleId the styleId of the car to add.
     * @param {number} column the column where the new car should appear.  May be zero if not applicable.
     * If a column is not specified, the new car will appear in the last available slot.
     */
    getCars: function(year, make, model, styleId, column)
    {
//console.debug("controller.getCars - year=%s | make=%s | model= %s | styleId=%s | column=%s",year,make,model,styleId,column);
        // Determine mode.
        var isYMM = false;
        if( (year != null) && (make != null) && (model != null) )
        {
            isYMM = true;
        }
        if( (styleId == null) && (isYMM == false) )
        {
//console.debug("controller.getCars - return because no ymm and no styleId");
            return;
        }
//console.debug("controller.getCars - isYMM=" + isYMM);
        // Create temp variables.
        var x = 1;
        var y = 5;
        var z = 0;
        var car = null;
        var arrCars = new Array();
        var s = null;
        var a = null;
        var b = 0;
        // Escape values.
        var _make = make;
        var _model = model;
        if(_make != null)
        {
            _make = window.escape(make);
            _make = _make.replace("&", "%26");
        }
        if(_model != null)
        {
            _model = window.escape(model);
            _model = _model.replace("&", "%26");
        }
        // Loop over columns.
        for(x = 1; x < y; x++)
        {
            if( (column != null) && (column == x) )
            {
                if(isYMM)
                {
                    a = new Array();
                    b = 0;
                    a[b++] = "year:" + year;
                    a[b++] = "make:" + _make;
                    a[b++] = "model:" + _model;
                    s = a.join("|");
                }
                else
                {
                    s = "styleId:" + styleId;
                }
                arrCars[z++] = s;
                continue;
            }
            car = ATC.cs.research.ctr.model.getCar(x);
            if(car == null)
            {
                s = "";
                arrCars[z++] = s;
                continue;
            }
            if(car.ctr.adType == 1)
            {
                s = "";
                arrCars[z++] = s;
                continue;
            }
            s = "styleId:" + car.ctr.styleId;
            arrCars[z++] = s;
        }
        if(column == null)
        {
            if(isYMM)
            {
                a = new Array();
                b = 0;
                a[b++] = "year:" + year;
                a[b++] = "make:" + _make;
                a[b++] = "model:" + _model;
                s = a.join("|");
            }
            else
            {
                s = "styleId:" + styleId;
            }
            arrCars[z++] = s;
        }
        if(isYMM)
        {
            ATC.utils.BIUtils.fireBIQ("ymm:" + year + "+" + _make + "+" + _model);
        }
        var cars = arrCars.join(",");
        var ad = arrCars.size == 4 ? false : true;
        var zip = ATC.cs.research.ctr.model.getZIP();
        var ajaxServiceMethod = "getCars";
        var parms = "zip=" + zip + "&column=" + column + "&ad=" + ad + "&cars=" + cars;
//console.debug(parms);
        var options = { method: "get", onSuccess: this.gotCars };
        this.loadCarsAjaxRequest(ajaxServiceMethod, parms, options);
    },

    /**
     * Saves Car Data Session Cookie State Pre Page Initialization
     * necessary due to cookie state race condition implicit in the fucntion of the compare tool
     */
    saveCarDataSessionCookieStatePrePageInitialization: function()
    {
        this.cookieStatePrePageInitialization = ATC.cs.research.ctr.model.getStyleIdsFromCookie();
        //set oem cookie to null initial state (resets it for standard comparison)
        if (ATC.cs.research.ctr.model.isOEM())
        {
            ATC.cs.research.ctr.model.setOEMdetailsCookie(null);
        }
    },

    /**
     * Clears cars from cookies only in un-occupied columns when an OEM is viewed after a competing OEM with potential
     * user entered cars that should not appear in current OEM
     */
    removeCarFromCookiePastLastFilledColumn: function(lastFilledColumn)
    {
        // lastFilledColumn is the last ocupied column, so we're going to fill the
        // remaining columns if the car data is available from a session cookie
        var currentColumn = lastFilledColumn + 1;
        while (currentColumn <= 4)
        {
            ATC.cs.research.ctr.model.removeCar(currentColumn);
            currentColumn++;
        }
    },

    getStyleIdsFromSeoUrl: function()
    {
        var seoUrlBase = '/research/compare/compare-cars/';
        var url = window.location.href;

        if (url.indexOf(seoUrlBase) != -1)
        {
            var seoString = url.split(seoUrlBase)[1];

            var seoStringSplitOnSlash = seoString.split("/");

            var carParamArray = seoStringSplitOnSlash[0].split("-");

            if (carParamArray.length >= 2)
            {
                var styleIds = [];

                carParamArray.each(function(param, i)
                {
                    styleIds.push(param);
                });
                return styleIds.join(",");
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    },

    /**
     * Returns car styleIds found in the URL
     */
    getStyleIdsFromUrl: function()
    {
        var url = ATC.cs.research.ctr.url;
        var styles = url.getParameter("styles");

        if (styles == null)
        {
            var vehicles =
                    [
                        url.getParameter("vehicle_number1"),
                        url.getParameter("vehicle_number2"),
                        url.getParameter("vehicle_number3"),
                        url.getParameter("vehicle_number4")
                    ];

            var validatedStyleIds = [];
            var validStyleIdIndex = 0;

            vehicles.each(function(styleId, i)
            {
                if (ATC.cs.research.ctr.controller.isValidStyleIdFormat(styleId))
                {
                    validatedStyleIds[validStyleIdIndex] = styleId;
                    validStyleIdIndex++;
                }
            });

            if (validatedStyleIds[0] != null)
            {
                styles = validatedStyleIds.join(",");
            }
        }
        return styles;
    },

    /**
     * Valiates that the style id is a valid format
     * as best it can without going back to the server
     */
    isValidStyleIdFormat: function(styleId)
    {
        var styleId = styleId * 1; // type casting

        return ((styleId > 0) && (styleId < 10000000)); // Edited to minimum of 0, the min styleID we have is 1
    },

    /**
     * Makes the AJAX request that loads cars by styleIds
     */
    loadCarsForStyleIds: function(styleIds, zip, ad)
    {
        var ajaxServiceMethod = "getCars";
        var params = "styleIds=" + styleIds + "&zip=" + zip + "&ad=" + ad;
        var options = { method: "get", onSuccess: this.gotCars };
        this.loadCarsAjaxRequest(ajaxServiceMethod, params, options);
    },

    /**
     * Makes the AJAX request that loads cars
     */
    loadCarsAjaxRequest: function(ajaxServiceMethod, params, options)
    {
        var baseAjaxRequestUrl = "/ac-servlets/research/compare/ctr/";
        var url = baseAjaxRequestUrl + ajaxServiceMethod + "?" + params;
        new Ajax.Request(url, options);
        window.setTimeout(ATC.cs.research.ctr.controller.loadSpotlightAds, 5000);
    },

    /**
     * Determine if this is an SEO URL
     * Note: this could have been written this in one line, but this expanded form is far more expressive
     * and easier to maintain
     */
    isSeoUrl: function()
    {
        var url = document.location.href;
        if ((url.indexOf(".jsp") == -1) && (url.indexOf("?") == -1) && (url.indexOf("&") == -1) && (url.indexOf("=") == -1))
        {
            // Did not find ".jsp" or "?" or "&" or "=", so it must be an SEO friendly URL
            return true;
        }
        else
        {
            return false;
        }
    },

    /**
     * Processes the business rules for a car.
     * The car may have come fresh from the server
     * or it may have come from the cache.
     * @param car the car to process.
     */
    addCar: function(car)
    {
        //console.debug("controller.addCar");
        var ns = ATC.cs.research.ctr;
        // Verify parameters.
        if (car == null)
        {
            return;
        }
        if (typeof car != "object")
        {
            return;
        }
        // Show it on the screen.
        var column = car.ctr.column;
        ns.model.setCar(column, car);
        ns.view.showColumn(car, false);
        if (ns.model.isAdbyColumn(column))
        {
            //setAd
            ns.model.setAd(car);
        }
    },

    /**
     * We got a list of cars.
     * Callback function for AJAX request.
     * @param tx the AJAX transport.
     */
    gotCars: function(tx)
    {
        // Verify parameters.
        if (tx == null)
        {
            return;
        }
        if (typeof tx != "object")
        {
            return;
        }
        // Create a flag to make sure we only show the add button once.
        var showedAddButton = false;
        // Get the cars.
        var txtCars = tx.responseText;
        var data = txtCars.evalJSON();
        var arrCars = data.cars;
        // Preserve inline ad status.
        var oldCar = null;
        arrCars.each(function(car, i)
        {
            if(car == null)
            {
                return;
            }
            if(car.ctr.column == 4)
            {
                oldCar = ATC.cs.research.ctr.model.getCar(4);
                if(oldCar != null)
                {
                    if(oldCar.ctr.adType == 1)
                    {
                        car.ctr.adType = 1;
                        car.ctr.sponsoredVehicleClass = "";
                        car.ctr.changeButtonClass = "hide";
                    }
                }
            }
        });
        // Preserve OEM ad status.
        arrCars.each(function(car, i)
        {
            if(car == null)
            {
                return;
            }
            var column = car.ctr.column;
            oldCar = ATC.cs.research.ctr.model.getCar(column);
            if (oldCar != null)
            {
                if (oldCar.ctr.oemSponsored)
                {
                    car.ctr.adType = oldCar.ctr.adType;
                    car.ctr.oemSponsored = oldCar.ctr.oemSponsored;
                    car.ctr.sponsoredVehicleClass = oldCar.ctr.sponsoredVehicleClass;
                    car.ctr.changeButtonClass = "hide";
                    car.ctr.removeButtonClass = "hide";
                    car.ctr.brandingStripeClass = "";
                    car.ctr.brandingStripeUrl = oldCar.ctr.brandingStripeUrl;
                    car.ctr.brandingStripeTrackingUrl = oldCar.ctr.brandingStripeTrackingUrl;
                    car.ctr.headerTrackingUrl = oldCar.ctr.headerTrackingUrl;
                    car.ctr.logoTrackingUrl = oldCar.ctr.logoTrackingUrl;
                    if(oldCar.ctr.adType != 2)
                    {
                        car.ctr.localListingsLinkClass = "hide";
                        car.ctr.localListingsTextClass = "hidden";
                    }
                }
            }
        });
        // rollup
        var rollup = data.rollup;
        ATC.cs.research.ctr.view.rollup(rollup);
        arrCars.each(function(car, i)
        {
            var column = i + 1;
            if (car == null)
            {
                if (column < 5)
                {
                    ATC.cs.research.ctr.view.removeColumnView(column);
                    ATC.cs.research.ctr.model.removeCar(column);
                }
                return;
            }
            //console.debug("controller.gotCars - column=" + column + ", year=" + car.ctr.year + ", make=" + car.ctr.make + ", model=" + car.ctr.model + ", adType=" + car.ctr.adType);
            //set car column
            car.ctr.column = column;
            // Show the car.
            ATC.cs.research.ctr.controller.addCar(car);
        });
        ATC.cs.research.ctr.view.updateComparingCounts();
        ATC.cs.research.ctr.view.enableNewComparisonButton();
        ATC.cs.research.ctr.view.displayPrintAndEmail();
        var col = ATC.cs.research.ctr.model.getFirstEmptyColumn();
        if (col == 1)
        {
            ATC.cs.research.ctr.view.showAddChangeColumn(1, true);
        }
        if (col > 1)
        {
            if(showedAddButton == false)
            {
                ATC.cs.research.ctr.view.showNextColumnAddButton(col);
                // Do this only once.
                showedAddButton = true;
            }
        }
        // Rollup photos.
        var arrPhotos = [ "fm_118", "fm_46", "fm_37", "fm_119", "fm_48", "fm_41", "fm_51", "fm_55", "fm_52" ];
        var xPhotos = 0;
        var yPhotos = arrPhotos.length;
        var zPhotos = 0;
        var iPhotos = "";
        var sPhotos = "";
        var bPhotos = false;
        for(xPhotos = 0; xPhotos < yPhotos; xPhotos++)
        {
            iPhotos = arrPhotos[xPhotos];
            sPhotos = rollup[iPhotos];
            bPhotos = (sPhotos == "") ? true : false;
            if(bPhotos == true)
            {
                zPhotos++;
            }
        }
        ATC.cs.research.ctr.view.rollupPhotos(zPhotos);
        ATC.cs.research.ctr.view.resetKeyDifferences();
        var biStyleId = new Array();
        var biYear = new Array();
        for (var x = 0; x < 4; x++) {
            var thisCar = arrCars[x];
            if (!thisCar) {
                biStyleId[x] = '';
                biYear[x] = '';
                continue;
            }
            biStyleId[x] = thisCar.ctr.styleId;
            biYear[x] = thisCar.ctr.year;
            // Fire e7 when inline ad (but don't fire again unless style ID and/or year change)
            if (x == 3) {
                if ((thisCar.ctr.adType == 1) && (thisCar.ctr.column == 4)) {
                    if (biStyleId[3] + "-" + biYear[3] != this.bi_last_inline_ad) {
                        ATC.utils.BIUtils.getBIEvent("e7","advn1:" + biStyleId[3], "advy1:" + biYear[3], "adzip:" + ATC.cs.research.ctr.model.getZIP());
                        this.bi_last_inline_ad = biStyleId[3] + "-" + biYear[3];
                    }
                }
            }
        }
        // This will also fire any events with vn# and vy# in the event
        // string provided the event added to the queue has event:column
        ATC.utils.BIUtils.fireBIQ("vn1:" + biStyleId[0], "vy1:" + biYear[0], "vn2:" + biStyleId[1], "vy2:" + biYear[1], "vn3:" + biStyleId[2], "vy3:" + biYear[2], "vn4:" + biStyleId[3], "vy4:" + biYear[3]);
    },

    /**
     * Removes a column.
     * @param column the column to remove.
     */
    removeColumn: function(column)
    {
        // Verify parameters.
        if (column == null)
        {
            return;
        }
        if (column < 1)
        {
            return;
        }
        if (column > 4)
        {
            return;
        }
        // Create temp variables.
        var x = 1;
        var y = 4;
        var z = 0;
        var car = null;
        var ad = true;
        var count = 0;
        var a = new Array();
        // Determine whether to include column 4 or not.
        // If it has a regular car, then we do want to shift left.
        // If it has an inline ad, the we don't want to shift it.
        var car4 = ATC.cs.research.ctr.model.getCar(4);
        if(car4 != null)
        {
            if(car4.ctr.adType == 0)
            {
                y = 5;
            }
        }
        // Loop over columns.
        for(x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if(car == null)
            {
                continue;
            }
            if(column == x)
            {
                continue;
            }
            // If there is a car and it's not the one we want to exclude
            // then add it to the list of cars to be requested.
            count++;
//console.debug("controller.removeColumn - added " + car.ctr.styleId);
            a[z++] = "styleId:" + car.ctr.styleId;
        }
        y = 3;
        z = count + 1;
        while(z < y)
        {
            a[z++] = null;
        }
        if(count == 0)
        {
            car = ATC.cs.research.ctr.model.getCar(4);
            if(car != null)
            {
                if(car.ctr.adType == 1)
                {
                    count++;
//console.debug("controller.removeColumn - special added " + car.ctr.styleId);
                    a[z++] = "styleId:" + car.ctr.styleId;
                    ad = false;
                }
            }
        }
        var cars = a.join(",");
//console.debug("controller.removeColumn - count=" + count);
        if(count == 4)
        {
            ad = false;
        }
        if(column == 4)
        {
            ad = false;
        }
        var zip = ATC.cs.research.ctr.model.getZIP();
        var ajaxServiceMethod = "getCars";
        var parms = "zip=" + zip + "&column=" + column + "&ad=" + ad + "&cars=" + cars;
//console.debug("controller.removeColumn - parms=" + parms);
        var options = { method: "get", onSuccess: this.gotCars };
        this.loadCarsAjaxRequest(ajaxServiceMethod, parms, options);
    },

    removeAllCars: function()
    {
        var model = ATC.cs.research.ctr.model;
        for (var i = 4; i > 0; i--)
        {
            model.removeCar(i);
        }
    },

    /**
     * Gets an array of vehicleType for all cars currently displayed.
     * @return an array of modelIds.
     */
    getBodyStyles: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its vehicleType to the array.
            r[z++] = car.ctr.vehicleType;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of modelIds for all cars currently displayed.
     * @return an array of modelIds.
     */
    getModelIds: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its modelId to the array.
            r[z++] = car.ctr.modelId;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of styleIds for all cars currently displayed.
     * @return an array of styleIds.
     */
    getStyleIds: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its styleId to the array.
            r[z++] = car.ctr.styleId;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of styleIds for all cars currently displayed.
     * @return an array of styleIds.
     */
    getStyleIdsExcludingInlineAd: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            if (car.ctr.adType == 1)
            {
                continue;
            }
            // Add its styleId to the array.
            r[z++] = car.ctr.styleId;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of years for all cars currently displayed.
     * @return an array of years.
     */
    getYears: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its year to the array.
            r[z++] = car.ctr.year;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of makes for all cars currently displayed.
     * @return an array of makes.
     */
    getMakes: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its make to the array.
            r[z++] = car.ctr.make;
        }
        // Return result.
        return r;
    },

    /**
     * Gets an array of models for all cars currently displayed.
     * @return an array of models.
     */
    getModels: function()
    {
        // Create return variable.
        var r = new Array();
        // Create temp variables.
        var car = null;
        var x = 1;
        var y = 5;
        var z = 0;
        // Loop through all of the cars.
        for (x = 1; x < y; x++)
        {
            // Get a car.
            car = ATC.cs.research.ctr.model.getCar(x);
            if (car == null)
            {
                continue;
            }
            // Add its model to the array.
            r[z++] = car.ctr.model;
        }
        // Return result.
        return r;
    },

    /**
     * Gets a suggestion list.
     * @param listName which list to get
     * @para column where to put it
     */
    getSuggestionList: function(listName, column)
    {
        ATC.cs.research.ctr.view.clearSuggestionList(column);
        ATC.cs.research.ctr.view.setSuggestionListLoading('show', column);
        var suggestionLists =
        {
            "SIMILAR"           : "getSimilarVehicles",
            "OTHERS_CONSIDERED" : "getVehiclesOthersConsidered",
            "PREVIOUSLY_VIEWED" : "getRecentlyViewedVehicles"
        }
        var baseUrl = "/ac-servlets/research/compare/ctr/";
        var columnParam = "column=" + column;
        var styleIdsParam = "styleIds=" + this.getStyleIds();
        var listNameParam = "listName=" + listName;
        var url = baseUrl + suggestionLists[listName] + "?" + columnParam + "&" + listNameParam + "&" + styleIdsParam;
        var options =
        {
            method: "get",
            onSuccess: ATC.cs.research.ctr.view.loadSuggestionList
        };
        new Ajax.Request(url, options);
    },

    /**
     * Initiates the Change process.
     * @param column the column to change.
     */
    changeColumn: function(column)
    {
        window.setTimeout(function() {
            ATC.cs.research.ctr.view.changeColumn(column);
        }, 10);
    },

    /**
     * Cancels the Change process.
     */
    cancelChange: function(column)
    {
        var car = ATC.cs.research.ctr.model.getCar(column);
        //getCar(column)
        //        var checkInlineAd = false;
        window.setTimeout(function() {
            //            ATC.cs.research.ctr.controller.addCar(car, checkInlineAd);
            ATC.cs.research.ctr.controller.addCar(car);
        }, 10);
    },

    /**
     * Sets the active tab.
     * If switching from tab 1 (Details) to tab 2 (Differences) for the first time,
     * it will also get Key Differences data and give it to the view to render.
     * @param {number} tab the tab to switch to
     */
    setActiveTab: function(tab)
    {
        ATC.cs.research.ctr.model.setActiveTab(tab);
        if (tab == 2)
        {
            if (this.isKeyDifferencesInitialized == false)
            {
                ATC.cs.research.ctr.view.resetKeyDifferences();
                var divBox = $("difference1-box");
                if(divBox != null)
                {
                    divBox.setStyle({backgroundImage:'url(/img/research/compare/bg-th.toggler-on.gif)'});
                    ATC.cs.research.ctr.controller.getKeyDifferences(1);
                }
                this.isKeyDifferencesInitialized = true;
            }
        }
    },

    getActiveTab: function()
    {
        return ATC.cs.research.ctr.model.getActiveTab();
    },

    /**
     * Gets key differences data.
     * @param {number} column the column to display.
     */
    getKeyDifferences: function(column)
    {
        var arrIDs = ATC.cs.research.ctr.model.getStyleIdsForKeyDifferences(column);
        if (arrIDs.length < 2)
        {
            ATC.cs.research.ctr.view.addNoKeyDifferences("Please select at least two vehicles to see Key Differences information.");
            //ATC.cs.research.ctr.view.displayKeyDifferences(null);
            return;
        }
        // Show loading indicator.
        var arrLoadingIndicatorID = ["difference", column, "-loading-indicator"];
        var attLoadingIndicatorID = arrLoadingIndicatorID.join("");
        ATC.cs.research.ctr.view.setLoadingIndicator(attLoadingIndicatorID, 'show');
        // Make AJAX call.
        var IDs = arrIDs.join(",");
        var url = "/ac-servlets/research/compare/ctr/getKeyDifferences?column=" + column + "&styleIds=" + IDs;
        //console.debug = "Getting Key Differences...";
        var options = {method: "get", onSuccess: this.gotKeyDifferences};
        new Ajax.Request(url, options);
    },

    /**
     * We got key differences data.
     * Callback function for AJAX request.
     * @param tx the AJAX transport.
     */
    gotKeyDifferences: function(tx)
    {
        // Verify parameters.
        if (tx == null)
        {
            return;
        }
        if (typeof tx != "object")
        {
            return;
        }
        // Get the data.
        var txt = tx.responseText;
        // Compile the data.
        var kd = txt.evalJSON();
        //window.status = "";
        // Hide loading indicator.
        var column = kd.column;
        var arrLoadingIndicatorID = ["difference", column, "-loading-indicator"];
        var attLoadingIndicatorID = arrLoadingIndicatorID.join("");
        ATC.cs.research.ctr.view.setLoadingIndicator(attLoadingIndicatorID, 'hide');
        // Display data.
        ATC.cs.research.ctr.view.displayKeyDifferences(kd);
    },

    /**
     * Gets a car.
     * @param {number} column which car to get.  Must be between 1 and 4.
     * @return {object} a Car object or null if there is no car in the specified column.
     */
    getCar: function(column)
    {
        return ATC.cs.research.ctr.model.getCar(column);
    },

    /**
     * Loads spotlight ads.
     */
    loadSpotlightAds: function()
    {
        //console.debug("controller.loadSpotlightAds");
        // Query Spotlight ads and set Spotlight url
        var modelIds = ATC.cs.research.ctr.controller.getModelIds();
        ATC.cs.research.ctr.spotlight.queryAds(modelIds);
    }

}

// Create an instance.
ATC.cs.research.ctr.controller = new Controller();
