
if (typeof YAHOO.Edmunds == 'undefined') {
    YAHOO.Edmunds = {};
}

// creates a namespace for this "YAHOO.Edmunds.Inventory"
YAHOO.namespace("YAHOO.Edmunds.Inventory");

/** Traps the enter key **/
YAHOO.Edmunds.Inventory.trapEnterKey = function(evt) {
    var evt = (evt) ? evt : ((event) ? event : null); 
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
    var char_code = YAHOO.util.Event.getCharCode(evt);
    if( (char_code == 9 || char_code == 13) && (node.type=="text"))  {   
        YAHOO.util.Event.preventDefault(evt);  
    }
};

/**
 * By instantiating an Image object, the browser will immediately fire off a request for
 */
YAHOO.Edmunds.Inventory.Impression = function(impression_data){
    var timestamped_impression_data = impression_data + '&impression_ts=' + new Date().getTime();
    
    var cache = new Image(0, 0);
    cache.src = timestamped_impression_data;
    YAHOO.Edmunds.Inventory.delay(200);
};

/**
 * Function to pause the current javascript execution.
 *
 * @namespace   YAHOO.Edmunds.Inventory
 * @method      delay
 * @param {Object} mseconds   time in milliseconds to spend looping and doing nothing.
 * @return      void
 * @public
 */
YAHOO.Edmunds.Inventory.delay = function(mseconds){
    if (mseconds) {
        var currentTime = new Date();
        var endTime = currentTime.getTime() + mseconds;
        while (currentTime.getTime() < endTime) {
            currentTime = new Date();
        }
    }
};

/**
 * Look for a specific value from the current URL. If it exists pass the value back after it has been
 * decoded.
 * 
 * @namespace    YAHOO.Edmunds.Inventory
 * @method       getQueryStringValue
 * @param {Object} prevalue    key for the value in the URL
 * @return       decoded value of passed in key from URL  
 * @public       
 */
YAHOO.Edmunds.Inventory.getQueryStringValue = function(prevalue){
    var prevalue = YAHOO.Edmunds.Util.getQueryString(prevalue);
    if (prevalue) {
        prevalue = decodeURI(prevalue);
    }
    
    return prevalue;
};


/**
 * Rounds number down to nearest 10. If number is below 10 returns 10. 
 * 
 * @namespace    YAHOO.Edmunds.Inventory
 * @method       getRoundedValue
 * @param {Object} count    number that needs to get rounded
 * @return       rounded Number
 * @public       
 */
YAHOO.Edmunds.Inventory.getRoundedValue = function(count){
    return count < 10 ? 10 : (Math.floor(count / 10) * 10);
};

/**
 * Search the current window location for a value in it's param list.
 * 
 * @namespace   YAHOO.Edmunds.Inventory
 * @method      containsQueryString 
 * @param {Object} prevalue value to look for in current window.location string
 * @return      true if value is in window.location string, false otherwise
 * @public
 */
YAHOO.Edmunds.Inventory.containsQueryString = function(prevalue){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == prevalue) {
            return true;
        }
    }  
    return false;
};

/**
 * Set value(s) in a cookie, with override for cookie name.
 * 
 * @namespace    YAHOO.Edmunds.Inventory
 * @method       setCookieSub
 * @param {Object} cookie_name     name of the cookie in which values are to be stored.
 * @param {Object} cookie_value    value to be stored in the cookie
 * @param {Object} alt_cookie_name (optional parameter) alternate cookie name used to change where the values are stored.
 * @return       void
 * @public
 */
YAHOO.Edmunds.Inventory.setCookieSub = function(cookie_name, cookie_value, alt_cookie_name){
    var main_cookie_name = "edmunds3";
    if (cookie_name) {
        if (YAHOO.Edmunds.Inventory.getQueryStringValue("conquest") == "true" || alt_cookie_name == "conquest") {
            switch (cookie_name) {
                case "nci_is_edmunds":
                case "nci_dealer_id":
                case "ncalId":
                case "carId":
                    main_cookie_name = "conquest";
                    break;
                default:
                    break;
            }
        }
        if (!cookie_value) {
            cookie_value = "";
        }
        
        YAHOO.util.Cookie.setSub(main_cookie_name, cookie_name, cookie_value, {
            path: "/"
        });
    }
};

/**
 * Get the value from the correct cookie based on the passed in name and the 'conquest' value set/not set in the 
 * current URL.
 * Conquested pages are flagged by having the 'conquest' parameter in the URL set to 'true'.
 * From a conquest flagged page certain values should be retrieved from the conquest cookie not the standard nci cookie.
 * 
 * @namespace   YAHOO.Edmunds.Inventory
 * @method      getCookieSub
 * @param {Object} cookie_key_name key used to look up value from the cookie.
 * @return      null if key has no corresponding value, value in appropriate cookie otherwise. 
 * @public
 */
YAHOO.Edmunds.Inventory.getCookieSub = function(cookie_key_name){
    var main_cookie_name = "edmunds3";
    if (YAHOO.Edmunds.Inventory.getQueryStringValue("conquest") == "true") {
        switch (cookie_key_name) {
            case "nci_is_edmunds":
            case "nci_dealer_id":
            case "ncalId":
            case "carId":
                main_cookie_name = "conquest";
                break;
            default:
                break;
        }
    }
    if (cookie_key_name) {
        return YAHOO.util.Cookie.getSub(main_cookie_name, cookie_key_name);
    } else {
        return null;
    }
    
};

/**
 * Remove the cookie specified by the passed in value.
 * 
 * @namespace    YAHOO.Edmunds.Inventory
 * @method       removeCookie
 * @param {Object} cookie_name name of the cookie to be removed.
 * @return       void
 * @public
 */
YAHOO.Edmunds.Inventory.removeCookie = function(cookie_name){
    if (cookie_name) {
        YAHOO.util.Cookie.remove(cookie_name, {
            path: "/"
        });
    }
};

/**
 * Forwards user to DPP page, with the SRL Detailed Pidget after properly setting all prerequisite values
 * 
 * @namespace   YAHOO.Edmunds.Inventory
 * @method      jumpToDDP
 * @param       String dealerId
 * @public       
 */
YAHOO.Edmunds.Inventory.jumpToDDP = function(dealerId, windowPopup, zipcode){
    var url = "/inventory/ddp.html?ddp_tab=tab_inventory&dealerId="+dealerId;
    YAHOO.Edmunds.Inventory.removeCookie('edmunds3');
    YAHOO.Edmunds.Inventory.setCookieSub('nci_dealer_id', dealerId);
    YAHOO.Edmunds.Inventory.setCookieSub('ddp_active_search', 'SRLDetailed');
    YAHOO.Edmunds.Inventory.setCookieSub('nci_is_edmunds', 'true');

    if (zipcode) {
        YAHOO.Edmunds.UserTrack.setZipCookie(zipcode);
    } 
       
    if (windowPopup) {
        YAHOO.Edmunds.Inventory.popupWindow(url);
    } else {
        window.location=url;
    }
};

/**
 * Forwards user to SRP page, after properly setting all prerequisite values
 * 
 * @namespace    YAHOO.Edmunds.Inventory
 * @method       jumpToSRP
 * @param Object {make,model,year} 
 * @public       
 */
YAHOO.Edmunds.Inventory.jumpToSRP = function(make, model, bodytype){
    var url = '/inventory/srp.html?'
    if(make){
        url = url + 'make='+make+"&";
    }
    if(model){
        url = url + 'model='+model+"&";
    }
    if(bodyType){
        url = url + 'bodytype='+bodytype;        
    }
    YAHOO.Edmunds.Inventory.removeCookie('edmunds3');
    window.location=url;
};

/**
 * Utility function to convert the NCI tab names to the ATC equivalent name. Calling this function
 * with no arguments or an empty/undefined argument will return empty string.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method    getATCTabValue
 * @param {Object} nci_pidget_name Name of the pidget from which to get the ATC tab value.
 * @return ATC tab value.
 * @public
 */
YAHOO.Edmunds.Inventory.getATCTabValue = function (nci_pidget_name, override_tab_value) {
    if(!nci_pidget_name) {
      return "ignore";
    }
    var atc_tab_value = "ignore";

    if(!YAHOO.Edmunds.Inventory.IsNullOrEmpty(override_tab_value)) {
      atc_tab_value = override_tab_value;
    } else {
        switch(nci_pidget_name) {
            case "SRP":
              atc_tab_value = "srl";
            break;
          case "SRLDetailed":
              atc_tab_value = "dealer_inventory_srl";
            break;
          case "NCAL":
              atc_tab_value = "dealer_inventory_ncal";
            break;
          case "Vehicle":
              atc_tab_value = "vehicle";
              break;
          case "Specials":
              atc_tab_value = "dealer_specials";
              break;
          case "DealerDetails":
              atc_tab_value = "dealer_detail";
              break;
          case "DealerInfo":
          case "ConquestSRL":
          case "SRLLite":
          case "SRL":
              atc_tab_value = "ignore";
            break;
          default:
              atc_tab_value = "ignore"; // fall through is 'ignore' value.
              break;
        }
    }

    return atc_tab_value;
};

/**
 * The timeoutmanager class provides a centralized resource for NCI timeouts based on response times from the pidgets.
 * 
 * The timeoutmanager is used any time an operation involving a pidget either being loaded or an action is started on a pidget
 * in which the user is not taken to a new page. These timers are used to handle one of two possible issues:
 * 1) The pidgets fail to load due to the ATC site being down and the javascript files being unavailable.
 * 2) The pidget starts an operation but takes beyond our specified time frame.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @class     TimeoutManager
 * @return    void
 * @constructor
 */
YAHOO.Edmunds.Inventory.TimeoutManager = function(){
    this.registered_pidget_configs = [];
    this.main_timeout = null;
};

YAHOO.Edmunds.Inventory.TimeoutManager.prototype = {
    /**
     * Start a global timer. There should only be a single global timer per page containing a pidget.
     * The global timer should be started just before the first pidget on the page is loaded.
     * 
     * @class    TimeoutManager
     * @method   startGlobalPidgetTimeout
     * @param {Object} curr_page Identifier to mark the name of the page on which this timer was started
     * @param {Object} millis    Length in milliseconds before the timer expires
     * @return   void
     * @public
     */
    startGlobalPidgetTimeout: function(curr_page, millis){
        var timeoutManager = YAHOO.Edmunds.Inventory.getTimeoutManager();
        this.main_timeout = timeoutManager.startPidgetTimeout(this.registered_pidget_configs, millis, { errorCode : '000;Pidget loading timeout;Global timeout threshold of [' + millis + '] millisec exceeded' });
    },
    
    /**
     * Associate a pidget_config with the timeoutmanager. This gives the manager an associated pidget_config for each pidget
     * so it can independently evaluate if a given pidget has issued a timeout error. The value for the error/success is 
     * stored in the pidget_config on a per-pidget basis.
     * 
     * @class    TimeoutManager
     * @method   registerPidgetTimeout
     * @param {Object} pidget_config pidget_config to add to the timeoutmananger
     * @return void
     * @public
     */
    registerPidgetTimeout: function(pidget_config){
        if (pidget_config) {
            this.registered_pidget_configs.push(pidget_config);
        }
    },
    
    /**
     * Start a timer for a given pidget.
     * 
     * @class    TimeoutManager
     * @method startPidgetTimeout
     * @param {Object} pidget_configs Pidget configuration array to which the timeout success/failure is associated
     * @param {Object} millis         time in milliseconds until timeout will trigger
     * @param {Object} error_message  Error message to to be used in logging
     * @return   void
     * @public
     */
    startPidgetTimeout: function(pidget_configs, millis, values){
        var timeout = new YAHOO.Edmunds.Inventory.Timeout(pidget_configs, values);
        var pt = setTimeout(function() {
            timeout.onPidgetTimeout(pidget_configs, values)
        }, millis);
        return pt;
    },
    
    /**
     * Cancel the passed in timer. Clear the global timer if the passed in flag is truel.
     * 
     * @class TimeoutManager
     * @method restePidgetTimeout
     * @param {Object} tm timer to cancel
     * @param {Object} clear_global_timer boolean flag to indicate if the global timer should be canceled
     * @return void
     * @public
     */
    resetPidgetTimeout: function(tm, clear_global_timer){
        if (clear_global_timer && this.main_timeout) {
            clearTimeout(this.main_timeout);
            this.main_timeout = null;
            
            if (window.wait) {
                window.wait.hide();
            }
            var loading_graphic = document.getElementById('loading-graphic');
            if (loading_graphic) {
                loading_graphic.style.visibility = 'hidden';
            }
        }
        
        if (tm) {
            clearTimeout(tm);
        }
    }
};

/**
 * Lazy loading getter for retrieveing a TimeoutManager object. This is a global per-page object.
 * The TimeoutManager is associated with the current page and is created if it does not already exist.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method    getTimeoutManager
 * @return (Object) Singleton TimeoutManager for this page.
 * @public
 */
YAHOO.Edmunds.Inventory.getTimeoutManager = function(){
    if (!window._timeout_manager) {
        window._timeout_manager = new YAHOO.Edmunds.Inventory.TimeoutManager();
    }
    
    return window._timeout_manager;
};

/**
 * Regenerate a PidgetConfig object from the current parameter set.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method    reloadPidgetConfig
 * @param {Object} pidget_config PidgetConfig with values to be regenerated.
 * @return void
 * @public
 */
YAHOO.Edmunds.Inventory.reloadPidgetConfig = function(pidget_config){
    //Search Info (Advanced Search Widget/Search Dealer's Lot Widget)
    pidget_config._atc_models = ["", "", "", "", ""];
    pidget_config._make = YAHOO.Edmunds.Inventory.getCookieSub("make") || "";
    pidget_config._model = YAHOO.Edmunds.Inventory.getCookieSub("model") || "";
    pidget_config._multiModels = YAHOO.Edmunds.Inventory.getCookieSub("model") || "";
    pidget_config._bodytype = YAHOO.Edmunds.Inventory.getCookieSub("bodytype") || "";
    pidget_config._transYear = YAHOO.Edmunds.Inventory.getCookieSub("nci_transYear") || new Date().getFullYear();
    pidget_config._year = YAHOO.Edmunds.Inventory.getCookieSub("yearFrom") || "";
    pidget_config._yearFrom = YAHOO.Edmunds.Inventory.getCookieSub("yearFrom") || new Date().getFullYear() - 1;
    pidget_config._yearTo = YAHOO.Edmunds.Inventory.getCookieSub("yearTo") || "";
    pidget_config._sortOrd = YAHOO.Edmunds.Inventory.getCookieSub("sortOrd") || "distanceASC";
    pidget_config._priceFrom = YAHOO.Edmunds.Inventory.getCookieSub("priceFrom") || "";
    pidget_config._priceTo = YAHOO.Edmunds.Inventory.getCookieSub("priceTo") || "";
    pidget_config._radius = YAHOO.Edmunds.Inventory.getCookieSub("radius") || 50;
    
    var zipcode = YAHOO.Edmunds.Util.getQueryString("setzip");
    if(YAHOO.Edmunds.Inventory.IsNullOrEmpty(zipcode)) {
        zipcode = YAHOO.Edmunds.Util.getQueryString("zip");
    }
    if(YAHOO.Edmunds.Inventory.IsNullOrEmpty(zipcode)) {
        zipcode = YAHOO.Edmunds.UserTrack.getZipCookie();
    }
    pidget_config._zip = zipcode;
    
    // Edmunds facet information for Send To A Friend
    pidget_config._engine = YAHOO.Edmunds.Inventory.getCookieSub("engine") || "";
    pidget_config._drive = YAHOO.Edmunds.Inventory.getCookieSub("drive") || "";
    pidget_config._transmission = YAHOO.Edmunds.Inventory.getCookieSub("transmission") || "";
    pidget_config._fuel = YAHOO.Edmunds.Inventory.getCookieSub("fuel") || "";
    pidget_config._color = YAHOO.Edmunds.Inventory.getCookieSub("color") || "";
    
    
    //General Edmunds Info
    pidget_config._modelId = YAHOO.Edmunds.Util.getQueryString("modelId") || "";
    pidget_config._styleId = YAHOO.Edmunds.Util.getQueryString("styleId") || "";
    pidget_config._ddp_tab = YAHOO.Edmunds.Inventory.getCookieSub("ddp_tab") || "tab_inventory";
    pidget_config._ddp_active_search = YAHOO.Edmunds.Inventory.getCookieSub("ddp_active_search") || "";
    
    //ATC data
    pidget_config._perPage = YAHOO.Edmunds.Inventory.getCookieSub("perPage") || 10;
    pidget_config._startRecord = YAHOO.Edmunds.Inventory.getCookieSub("startRecord") || 1;
    pidget_config._pgNum = 1;
    pidget_config._carId = YAHOO.Edmunds.Inventory.getCookieSub("carId") || "";
    pidget_config._ncalId = YAHOO.Edmunds.Inventory.getCookieSub("ncalId") || "";
    pidget_config._loadState = "error";
    pidget_config._dealerId = YAHOO.Edmunds.Util.getQueryString("dealerId") || YAHOO.Edmunds.Inventory.getCookieSub("nci_dealer_id") || "";
    pidget_config._isEnhanced = YAHOO.Edmunds.Inventory.getCookieSub("nci_is_edmunds") || "";
    pidget_config._only_photo = YAHOO.Edmunds.Inventory.getCookieSub("only_photo") || "";
    pidget_config._only_special = YAHOO.Edmunds.Inventory.getCookieSub("only_special") || "";
    pidget_config._atc_make = YAHOO.Edmunds.Inventory.getCookieSub("atc_make") || "";
    pidget_config._atc_model = YAHOO.Edmunds.Inventory.getCookieSub("atc_model") || "";
    pidget_config._atc_body = YAHOO.Edmunds.Inventory.getCookieSub("atc_body") || "";
    pidget_config._atc_color = YAHOO.Edmunds.Inventory.getCookieSub("atc_color") || "";
    pidget_config._atc_engine = YAHOO.Edmunds.Inventory.getCookieSub("atc_engine") || "";
    pidget_config._atc_transmission = YAHOO.Edmunds.Inventory.getCookieSub("atc_transmission") || "";
    pidget_config._atc_fuel = YAHOO.Edmunds.Inventory.getCookieSub("atc_fuel") || "";
    pidget_config._atc_drive = YAHOO.Edmunds.Inventory.getCookieSub("atc_drive") || "";
    
    
    pidget_config._special_id = YAHOO.Edmunds.Inventory.getCookieSub("special_id") || "";
    
    // create atc model array with either blanks or the model as it's values for use in writing out pixel information.
    // NOTE: this list is separated by the ';' character.
    //
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_model)) {
        if (pidget_config._atc_model.length > 5) {
            pidget_config._atc_model.length = 5;
        }
        var model_list = pidget_config._atc_model.split('|');
        for (var i = 0; i < model_list.length; i++) {
            pidget_config._atc_models[i] = model_list[i];
        }
    }
    
    if (pidget_config._make) {
        pidget_config._make = YAHOO.Edmunds.Inventory.URLDecode(pidget_config._make);
    }
    
    if (pidget_config._model) {
        pidget_config._model = YAHOO.Edmunds.Inventory.URLDecode(pidget_config._model);
    }
    
    if (pidget_config._yearFrom && pidget_config._yearTo && pidget_config._yearFrom > pidget_config._yearTo) {
        pidget_config._yearTo = pidget_config._yearFrom;
    }    
};

/**
 * Clear certain parameters from the cookie which in turn will cause the next retrieval of data to have
 * the fields in this function cleared.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method clearPidgetConfig
 * @return void
 * @public
 */
YAHOO.Edmunds.Inventory.clearPidgetConfig = function(){
    YAHOO.Edmunds.Inventory.setCookieSub('model', "");
    YAHOO.Edmunds.Inventory.setCookieSub('make', "");
    YAHOO.Edmunds.Inventory.setCookieSub('bodytype', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_transmission', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_engine', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_drive', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_fuel', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_body', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_model', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_make', "");
    YAHOO.Edmunds.Inventory.setCookieSub('yearFrom', "");
    YAHOO.Edmunds.Inventory.setCookieSub('yearTo', "");
    YAHOO.Edmunds.Inventory.setCookieSub('atc_color', "");
    YAHOO.Edmunds.Inventory.setCookieSub('engine', "");
    YAHOO.Edmunds.Inventory.setCookieSub('drive', "");
    YAHOO.Edmunds.Inventory.setCookieSub('fuel', "");
    YAHOO.Edmunds.Inventory.setCookieSub('transmission', "");
    YAHOO.Edmunds.Inventory.setCookieSub('color', "");
    YAHOO.Edmunds.Inventory.setCookieSub('priceFrom', "");
    YAHOO.Edmunds.Inventory.setCookieSub('priceTo', "");
    YAHOO.Edmunds.Inventory.setCookieSub('perPage', "10");
    YAHOO.Edmunds.Inventory.setCookieSub('startRecord', "1");
    YAHOO.Edmunds.Inventory.setCookieSub('pgNum', "1");
    YAHOO.Edmunds.Inventory.setCookieSub('only_special', "");
    YAHOO.Edmunds.Inventory.setCookieSub('only_photo', "");
    YAHOO.Edmunds.Inventory.setCookieSub('sortOrd', "priceDESC");
};

/**
 * Constructor for a PidgetConfig. 
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @class PidgetConfig
 * @param {Object} transient_flag 
 * @return (Object) a PidgetConfig containing all the current values used for a given pidget.
 * @public
 */
YAHOO.Edmunds.Inventory.PidgetConfig = function(transient_flag){

    if (!transient_flag) {
        YAHOO.Edmunds.Inventory.getTimeoutManager().registerPidgetTimeout(this);
    }
    
    this._error = false;
    
    this._tm = null;
    this._gomez_timers = [];
    YAHOO.Edmunds.Inventory.reloadPidgetConfig(this);
};

/**
 * Construct a modified string with no whitespace and all '+' values replaced with 'plus'.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method getNiceName
 * @param {Object} altered string 
 * @return void
 * @public
 */
YAHOO.Edmunds.Inventory.getNiceName = function(value){
    var niceName = "";
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(value)) {
        value = value.toLowerCase();
        for (i = 0; i < value.length; i++) {
            // Check that current character isn't whitespace.
            var c = value.charAt(i);
            if (YAHOO.Edmunds.Inventory.isLetterOrDigit(c)) {
                niceName += c;
            } else 
                if (c == "+") {
                    niceName += "plus";
                }
        }
    }
    return niceName;
}

/**
 * Utility function to determine if a character is in the range of a-z, A-Z, or 0-9.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method isLetterOrDigit
 * @param {Object} pword character to check
 * @return true if character is in the specified range, false otherwise
 * @public
 */
YAHOO.Edmunds.Inventory.isLetterOrDigit = function(pword){
    return (((pword >= "a") && (pword <= "z")) || ((pword >= "A") && (pword <= "Z"))) || ((pword >= "0") && (pword <= "9"));
}

/**
 * Retrieve the NCI page code from the edwpg array based on the passed in pgcode value.
 * 
 * @namespace YAHOO.Edmunds.Inventory
 * @method getNCIPageCode 
 * @param {Object} pgcode
 * @return (Object) pageCode based on an indexed value from edwpg global array
 * @public
 */
YAHOO.Edmunds.Inventory.getNCIPageCode = function(pgcode){
    var noresult = "none";
    for (i = 0; i < pgcode.length; i++) {
        if (edwpg.indexOf(pgcode[i]) > 0) {
            return pgcode[i];
        }
    }
    return noresult;
}

YAHOO.Edmunds.Inventory.nciSetEdwPg = function(){
    var cur_pgcode = "";
    var pgcode = ["DDP", "SRP", "VIN"];
    var edw_pgcode = [];
    
    //Set up VIN pagecodes
    edw_pgcode.vinModel = "New_Car_Inventory_VIN_Detail";
    edw_pgcode.vinMake = "New_Car_Inventory_VIN_Detail_Make";
    edw_pgcode.vinBody = "New_Car_Inventory_VIN_Detail_Body";
    edw_pgcode.vinGeneric = "New_Car_Inventory_VIN_Detail_Generic";
    
    //Set up DDP pagecodes
    edw_pgcode.ddpListingsModel = "New_Car_Inventory_DDP_Listings";
    edw_pgcode.ddpListingsMake = "New_Car_Inventory_DDP_Listings_Make";
    edw_pgcode.ddpListingsBody = "New_Car_Inventory_DDP_Listings_Body";
    edw_pgcode.ddpListingsGeneric = "New_Car_Inventory_DDP_Listings_Generic";
    
    edw_pgcode.ddpDetailsModel = "New_Car_Inventory_DDP_Details";
    edw_pgcode.ddpDetailsMake = "New_Car_Inventory_DDP_Details_Make";
    edw_pgcode.ddpDetailsBody = "New_Car_Inventory_DDP_Details_Body";
    edw_pgcode.ddpDetailsGeneric = "New_Car_Inventory_DDP_Details_Generic";
    
    edw_pgcode.ddpSpecialsModel = "New_Car_Inventory_DDP_Specials";
    edw_pgcode.ddpSpecialsMake = "New_Car_Inventory_DDP_Specials_Make";
    edw_pgcode.ddpSpecialsBody = "New_Car_Inventory_DDP_Specials_Body";
    edw_pgcode.ddpSpecialsGeneric = "New_Car_Inventory_DDP_Specials_Generic";
    
    edw_pgcode.ddpContactModel = "New_Car_Inventory_DDP_Contact";
    edw_pgcode.ddpContactMake = "New_Car_Inventory_DDP_Contact_Make";
    edw_pgcode.ddpContactBody = "New_Car_Inventory_DDP_Contact_Body";
    edw_pgcode.ddpContactGeneric = "New_Car_Inventory_DDP_Contact_Generic";
    
    //Set up SRP pagecodes
    edw_pgcode.srpModel = "New_Car_Inventory_SRP";
    edw_pgcode.srpMake = "New_Car_Inventory_SRP_Make";
    edw_pgcode.srpBody = "New_Car_Inventory_SRP_Body";
    edw_pgcode.srpGeneric = "New_Car_Inventory_SRP_Generic";
    
    var _make = YAHOO.util.Cookie.getSub("edmunds3", "make") || YAHOO.Edmunds.Util.getQueryString("make") || "";
    var _model = YAHOO.util.Cookie.getSub("edmunds3", "model") || YAHOO.Edmunds.Util.getQueryString("model") || "";
    var _bodytype = YAHOO.util.Cookie.getSub("edmunds3", "bodytype") || YAHOO.Edmunds.Util.getQueryString("bodytype") || "";
    var _ddpTab = YAHOO.util.Cookie.getSub("edmunds3", "ddp_tab") || YAHOO.Edmunds.Util.getQueryString("ddp_tab") || "";
    
    //Get current page
    cur_pgcode = YAHOO.Edmunds.Inventory.getNCIPageCode(pgcode);
    switch (cur_pgcode) {
        case "VIN":
            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                edwpg = edw_pgcode.vinModel;
            } else 
                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                        edwpg = edw_pgcode.vinMake;
                    } else {
                        edwpg = edw_pgcode.vinBody;
                    }
                } else 
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                        edwpg = edw_pgcode.vinMake;
                    } else {
                        edwpg = edw_pgcode.vinGeneric;
                    }
            break;
        case "SRP":
            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                edwpg = edw_pgcode.srpModel;
            } else 
                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                        edwpg = edw_pgcode.srpMake;
                    } else {
                        edwpg = edw_pgcode.srpBody;
                    }
                } else 
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                        edwpg = edw_pgcode.srpMake;
                    } else {
                        edwpg = edw_pgcode.srpGeneric;
                    }
            break;
        case "DDP":
            if (_ddpTab == "tab_inventory") {
                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                    edwpg = edw_pgcode.ddpListingsModel;
                } else 
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                            edwpg = edw_pgcode.ddpListingsMake;
                        } else {
                            edwpg = edw_pgcode.ddpListingsBody;
                        }
                    } else 
                        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                            edwpg = edw_pgcode.ddpListingsMake;
                        } else {
                            edwpg = edw_pgcode.ddpListingsGeneric;
                        }
                break;
            } else 
                if (_ddpTab == "tab_details") {
                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                        edwpg = edw_pgcode.ddpDetailsModel;
                    } else 
                        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                edwpg = edw_pgcode.ddpDetailsMake;
                            } else {
                                edwpg = edw_pgcode.ddpDetailsBody;
                            }
                        } else 
                            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                edwpg = edw_pgcode.ddpDetailsMake;
                            } else {
                                edwpg = edw_pgcode.ddpDetailsGeneric;
                            }
                    break;
                } else 
                    if (_ddpTab == "tab_specials") {
                        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                            edwpg = edw_pgcode.ddpSpecialsModel;
                        } else 
                            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                    edwpg = edw_pgcode.ddpSpecialsMake;
                                } else {
                                    edwpg = edw_pgcode.ddpSpecialsBody;
                                }
                            } else 
                                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                    edwpg = edw_pgcode.ddpSpecialsMake;
                                } else {
                                    edwpg = edw_pgcode.ddpSpecialsGeneric;
                                }
                        break;
                    } else 
                        if (_ddpTab == "tab_contact") {
                            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
                                edwpg = edw_pgcode.ddpContactModel;
                            } else 
                                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_bodytype)) {
                                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                        edwpg = edw_pgcode.ddpContactMake;
                                    } else {
                                        edwpg = edw_pgcode.ddpContactBody;
                                    }
                                } else 
                                    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
                                        edwpg = edw_pgcode.ddpContactMake;
                                    } else {
                                        edwpg = edw_pgcode.ddpContactGeneric;
                                    }
                            break;
                        }
    }
    //Explicitly set Omniture pixel with new pgcode (NOTE:  This is for the Omniture 1 pixel only)
    s.pageName = edwpg;
}


YAHOO.Edmunds.Inventory.PidgetConfig.prototype = {

    reload: function(){
        YAHOO.Edmunds.Inventory.reloadPidgetConfig(this);
    },
    
    _startTimer: function(pidget_config, timeout){
        if (pidget_config._tm) {
            var timeoutManager = YAHOO.Edmunds.Inventory.getTimeoutManager();
            timeoutManager.resetPidgetTimeout(pidget_config._tm, true);
        }
        if (timeout && timeout > 0) {
            var timeoutManager = YAHOO.Edmunds.Inventory.getTimeoutManager();
            var pidget_config_arg = [pidget_config];
            pidget_config._tm = timeoutManager.startPidgetTimeout(pidget_config_arg, timeout, { errorCode :'001;Pidget loading timeout;User action timeout threshold of [' + timeout + '] millisec exceeded' });
        }
    },
    
    subscribe: function(pidget_config, containerID, event_object, event_name, event_callback, timeout, skip_reload){
        if (event_name && event_callback && event_object && event_object.subscribe) {
            event_object.subscribe(event_name, function(data){
            
                if (pidget_config) {
                    pidget_config._containerID = containerID;
                    if (event_name == 'init') {
                        pidget_config._endTimer(pidget_config, false);
                    } else {
                        pidget_config._endTimer(pidget_config, true);
                    }
                    
                    if (!skip_reload) {
                        pidget_config.reload();
                    }
                } else {
                    YAHOO.Edmunds.Inventory.logDebug('pidget_config undefined! in PidgetConfig.prototype.subscribe');
                }
                
                try {
                    event_callback.call(this, data);
                } 
                catch (e) {
                    throw e;
                }
                
                if (timeout && timeout > 0) {
                    if (pidget_config) {
                        pidget_config._startTimer(pidget_config, timeout);
                    }
                }
            });
        }
    },
    
    _endTimer: function(pidget_config, stop_global_timer){
        var timeoutManager = YAHOO.Edmunds.Inventory.getTimeoutManager();
        timeoutManager.resetPidgetTimeout(pidget_config._tm, stop_global_timer);
    }
};

/** Static functions **/
YAHOO.Edmunds.Inventory.getElementsById = function(element_id, single) {
    if(single) {
        var return_value = [];

        var found_elements = YAHOO.util.Dom.getElementsBy( function(el) { return(el.id == element_id); } );
        if(found_elements && found_elements.length > 0) {
            return_value.push(found_elements[0]);
        }

        return return_value;
    } else {
        return YAHOO.util.Dom.getElementsBy( function(el) { return(el.id == element_id); } );
    }
};

YAHOO.Edmunds.Inventory.showElement = function(element_id, includeSpan){
    var targets = YAHOO.Edmunds.Inventory.getElementsById(element_id, true);
    
    for(var target_count = 0; target_count < targets.length; target_count++) {
        var target = targets[target_count];
        if (target != null) {
            if (includeSpan && target.nodeName != 'SCRIPT') {
                if(target.style.visibility == 'hidden') {
                    target.style.display = 'none';
                } else {
                    target.style.display = 'block';
                }
            } else 
                if (target.nodeName != 'SPAN' && target.nodeName != 'SCRIPT') {
                    if(target.style.visibility == 'hidden') {
                        target.style.display = 'none';
                    } else {
                        target.style.display = 'block';
                    }
                }
            
            var children = target.childNodes;
            for (var count = 0; count < children.length; count++) {
                if (children[count].style != null) {
                    if (includeSpan && children[count].nodeName != 'SCRIPT') {
                        if(children[count].style.visibility == 'hidden') {
                            children[count].style.display = 'none';
                        } else {
                            children[count].style.display = 'block';
                        }
                    } else 
                        if (children[count].nodeName != 'SPAN' && children[count].nodeName != 'SCRIPT') {
                            if(children[count].style.visibility == 'hidden') {
                                children[count].style.display = 'none';
                            } else {
                                children[count].style.display = 'block';
                            }
                        }
                }
            }
        }
    }
};

YAHOO.Edmunds.Inventory.hideElement = function(element_id, includeSpan){
    var targets = YAHOO.Edmunds.Inventory.getElementsById(element_id, true);
    
    for(var target_count = 0; target_count < targets.length; target_count++) {
        var target = targets[target_count];
        if (target != null) {
            if (includeSpan && target.nodeName != 'SCRIPT') {
                target.style.display = 'none';
            } else 
                if (target.nodeName != 'SPAN' && target.nodeName != 'SCRIPT') {
                    target.style.display = 'none';
                }
            
            var children = target.childNodes;
            for (var count = 0; count < children.length; count++) {
                if (children[count].style != null) {
                    if (includeSpan && children[count].nodeName != 'SCRIPT') {
                        children[count].style.display = 'none';
                    } else 
                        if (children[count].nodeName != 'SPAN' && children[count].nodeName != 'SCRIPT') {
                            children[count].style.display = 'none';
                        }
                }
            }
        }
    }
};

YAHOO.Edmunds.Inventory.IsPidgetError = function(data, pidget_config){
    if (pidget_config && pidget_config._error) {
        return true;
    } else 
        if (data) {
            return (data.errorCode && data.errorCode != 501);
        } else {
            return false;
        }
};

YAHOO.Edmunds.Inventory.IsNullOrEmpty = function(value){
    return (!value || value == null || value.length < 1);
};

YAHOO.Edmunds.Inventory.IsTrue = function(value){
    return (value == true || value == 'true' || value == 'TRUE');
};

YAHOO.Edmunds.Inventory.logDebug = function(message){
    try {
        if (window.console && window.console.log && YAHOO.Edmunds.Inventory.isPidgetDebug() && message) {
            window.console.log(message);
        }
    } catch(e) {
    }
};

YAHOO.Edmunds.Inventory.URLDecode = function(encodedString){
    var output = encodedString;
    var binVal, thisString;
    var myregexp = /(%[^%]{2})/;
    while ((match = myregexp.exec(output)) != null &&
    match.length > 1 &&
    match[1] != '') {
        binVal = parseInt(match[1].substr(1), 16);
        thisString = String.fromCharCode(binVal);
        output = output.replace(match[1], thisString);
    }
    
    return output;
};

YAHOO.Edmunds.Inventory.URLEncode = function(clearString){
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ') 
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    
    return output;
};

YAHOO.Edmunds.Inventory.startGomezTracking = function(pidget_config, timer_names){
    if (window.gomez) {
        if (timer_names && timer_names.length) {
            for (var i = 0; i < timer_names.length; i++) {
                window.gomez.startInterval(timer_names[i]);
                pidget_config._gomez_timers[timer_names[i]] = {
                    value: true
                };
            }
        }
    } else {
        YAHOO.Edmunds.Inventory.logDebug("Gomez is not registered for starting!");
    }
};

YAHOO.Edmunds.Inventory.stopGomezTracking = function(pidget_config, timer_names){
    if (window.gomez) {
        if (timer_names && timer_names.length) {
            for (var i = 0; i < timer_names.length; i++) {
                window.gomez.endInterval(timer_names[i]);
                pidget_config._gomez_timers[timer_names[i]] = {
                    value: false
                };
            }
        }
    } else {
        YAHOO.Edmunds.Inventory.logDebug("Gomez is not registered for stopping!");
    }
};

YAHOO.Edmunds.Inventory.resetGomezTracking = function(pidget_config){
    if (window.gomez && pidget_config._gomez_timers) {
        for (var key in pidget_config._gomez_timers) {
            if (pidget_config._gomez_timers[key].value) {
                window.gomez.endInterval(key);
            }
        }
    } else {
        YAHOO.Edmunds.Inventory.logDebug("Gomez is not registered for resetting!");
    }
    
    pidget_config._gomez_timers = [];
};

YAHOO.Edmunds.Inventory.generate_nci_inventory_impression = function(parameter_array){
    var inventory_pixel = new edd().toString().replace(/edw.edmunds.com/, 'inventory.edmunds.com');
    
    for (key in parameter_array) {
        if (!parameter_array[key] || typeof parameter_array[key] != 'function') {
            inventory_pixel = inventory_pixel + '&' + key + '=' + escape(parameter_array[key]);
        }
    }
    var impression = new YAHOO.Edmunds.Inventory.Impression(inventory_pixel);
};


YAHOO.Edmunds.Inventory.isPidgetDebug = function(){
    // Debug setup. Pidget debugging is turned on/off through the URL parameter list. The value passed
    // in is then stored in the Pidget cookie value set and retained until either cookies are cleared or 
    // a new URL value is passed.
    // NOTE: no value/clearing cookies turns debugging messages OFF
    // 
    // OPTIMIZATION NOTE: remove/disable this code
    //
    var PIDGET_DEBUG = YAHOO.Edmunds.Util.getQueryString("PIDGET_DEBUG") || YAHOO.Edmunds.Inventory.getCookieSub("PIDGET_DEBUG") || false;
    YAHOO.Edmunds.Inventory.setCookieSub("PIDGET_DEBUG", PIDGET_DEBUG);
    
    // Translate debug value to boolean since the pidget seems to require a boolean value and not any other form of true/false.
    //
    if (PIDGET_DEBUG == "true") {
        PIDGET_DEBUG = true;
    } else {
        PIDGET_DEBUG = false;
    }
    
    return PIDGET_DEBUG;
};

// Utility function to return back an array of all nci model information (split)
YAHOO.Edmunds.Inventory.parseMultipleModels = function(pidget_config) {
    var return_value = ["", "", "", "", ""];
    
    // create nci model array with either blanks or the model as it's values for use in writing out pixel information.
    // NOTE: this list is separated by the ';' character.
    if (pidget_config && !YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._multiModels)) {
        if (pidget_config._multiModels.length > 5) {
            pidget_config._multiModels.length = 5;
        }
        var model_list = pidget_config._multiModels.split(';');
        for (var i = 0; i < model_list.length; i++) {
            return_value[i] = model_list[i];
        }
    }
    
    return return_value;
}

// Utility function to set all the values in the 'user action' pixel which tracks all user interactions
// with the Pidgets (pagination, vehicle selection, etc...)
//
YAHOO.Edmunds.Inventory.setUserActionVars = function(values, pidget_config, pidget_name){
    var inv_ua = [];
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_name)) {
        inv_ua.nci_pidget_name = pidget_name;
    }
    inv_ua.nci_userevent = values.event || "";
    if (pidget_config) {
        inv_ua.nci_sum_dealerId = pidget_config._dealerId ? pidget_config._dealerId : "";
        inv_ua.nci_sum_ncalId = pidget_config._ncalId ? pidget_config._ncalId : "";
    }
    // If the data object from ATC contains the dealer_id this dealer corresponds to this action, regardless
    // of what is in the pidget_config.
    if (values.dealer_id) {
        inv_ua.nci_sum_dealerId = values.dealer_id || "";
    }    
    inv_ua.nci_sum_vehicleId = values.car_id || values.vehicle_id || "";
    inv_ua.nci_sum_isEnhanced = pidget_config._isEnhanced || "";
    inv_ua.nci_user_event_ts = new Date().getTime() || "";
    inv_ua.nci_sum_dma = YAHOO.Edmunds.UserTrack.getDmaCookie() || "";
    var nci_models = YAHOO.Edmunds.Inventory.parseMultipleModels(pidget_config);
    inv_ua.nci_edwmdl1 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[0] || "");
    inv_ua.nci_edwmdl2 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[1] || "");
    inv_ua.nci_edwmdl3 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[2] || "");
    inv_ua.nci_edwmdl4 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[3] || "");
    inv_ua.nci_edwmdl5 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[4] || "");
    inv_ua.nci_price_min = pidget_config._priceFrom || "";
    inv_ua.nci_price_max = pidget_config._priceTo || "";
    inv_ua.nci_distance = pidget_config._radius || "";
    inv_ua.nci_pidgetType = values.nci_pidgetType || "Standard";
    inv_ua.nci_wgt_bodystyle = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._bodytype || "");
    inv_ua.nci_wgt_engine = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._engine || "");
    inv_ua.nci_wgt_transmission = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._transmission || "");
    inv_ua.nci_wgt_drive = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._drive || "");
    inv_ua.nci_wgt_fuel = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._fuel || "");
    inv_ua.nci_wgt_color = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._color || "");
    inv_ua.nci_ddp_tab = values.ddp_tab || "";
    inv_ua.nci_wgt_onlyphotos = pidget_config._only_photo || "";
    inv_ua.nci_wgt_onlyspecials = pidget_config._only_special || "";
    inv_ua.nci_event_type = "useraction";
    YAHOO.Edmunds.Inventory.nciSetEdwPg();
    YAHOO.Edmunds.Inventory.generate_nci_inventory_impression(inv_ua);
};

// Utility function to set up all the values for the summary pixel which records the current state of the current pidget.
YAHOO.Edmunds.Inventory.setInventorySummaryVars = function(values, pidget_config, pidget_name){
    var inv_sum = [];
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_name)) {
        inv_sum.nci_pidget_name = pidget_name;
    }
    inv_sum.nci_sum_dma = YAHOO.Edmunds.UserTrack.getDmaCookie() || "";
    inv_sum.nci_sum_loadState = values.loadState || "";
    inv_sum.nci_sum_errorCode = values.errorCode || "";
    inv_sum.nci_sum_totalVehicles = values.totalVehicles || "";
    inv_sum.nci_sum_totalListings = values.totalListings || "";
    inv_sum.nci_sum_basicListings = values.standardListings || "";
    inv_sum.nci_sum_enhancedListings = values.premiumListings || "";
    inv_sum.nci_sum_listingsPhotos = values.listingsPhotos || "";
    inv_sum.nci_sum_listingsSpecials = values.listingsSpecials || "";
    inv_sum.nci_sum_isEnhanced = pidget_config._isEnhanced || "";
    inv_sum.nci_sum_dealerId = values.dealerId || pidget_config._dealerId || "";
    inv_sum.nci_sum_vehicleId = values.vehicleId || "";
    inv_sum.nci_sum_ncalId = values.ncalId || "";
    inv_sum.nci_pidgetType = values.nci_pidgetType || "Standard";
    inv_sum.nci_sum_exactMatches = values.exactMatches || "";
    inv_sum.nci_sum_closeMatches = values.closeMatches || "";
    var nci_models = YAHOO.Edmunds.Inventory.parseMultipleModels(pidget_config);
    inv_sum.nci_edwmdl1 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[0] || "");
    inv_sum.nci_edwmdl2 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[1] || "");
    inv_sum.nci_edwmdl3 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[2] || "");
    inv_sum.nci_edwmdl4 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[3] || "");
    inv_sum.nci_edwmdl5 = YAHOO.Edmunds.Inventory.getNiceName(nci_models[4] || "");
    inv_sum.nci_price_min = pidget_config._priceFrom || "";
    inv_sum.nci_price_max = pidget_config._priceTo || "";
    inv_sum.nci_distance = pidget_config._radius || "";
    inv_sum.nci_wgt_bodystyle = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._bodytype || "");
    inv_sum.nci_wgt_engine = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._engine || "");
    inv_sum.nci_wgt_transmission = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._transmission || "");
    inv_sum.nci_wgt_drive = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._drive || "");
    inv_sum.nci_wgt_fuel = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._fuel || "");
    inv_sum.nci_wgt_color = YAHOO.Edmunds.Inventory.getNiceName(pidget_config._color || "");
    inv_sum.nci_ddp_tab = values.ddp_tab || "";
    inv_sum.nci_wgt_onlyphotos = pidget_config._only_photo || "";
    inv_sum.nci_wgt_onlyspecials = pidget_config._only_special || "";
    inv_sum.nci_event_type = "summary";
    YAHOO.Edmunds.Inventory.nciSetEdwPg();
    YAHOO.Edmunds.Inventory.generate_nci_inventory_impression(inv_sum);
};

/**
 * Write out the omniture2 pixel. The values needed are all passed in and then mapped to their
 * corresponding value in the pixel to be written out.
 *
 * @param    Array    values    array of values to be sent to the Omniture2 pixel, missing values are set to empty string ("").
 * @return   void
 */
YAHOO.Edmunds.Inventory.writeOmni2Pixel = function(values){
    var nci_omni2 = [];
    nci_omni2.nci_sum_dma = YAHOO.Edmunds.UserTrack.getDmaCookie() || "";
    nci_omni2.nci_sum_loadState = values.loadState || "";
    nci_omni2.nci_sum_errorCode = values.errorCode || "";
    nci_omni2.nci_sum_totalVehicles = values.totalVehicles || "";
    nci_omni2.nci_sum_totalListings = values.totalListings || "";
    nci_omni2.nci_sum_standardListings = values.standardListings || "";
    nci_omni2.nci_sum_premiumListings = values.premiumListings || "";
    nci_omni2.nci_sum_listingsPhotos = values.listingsPhotos || "";
    nci_omni2.nci_sum_listingsSpecials = values.listingsSpecials || "";
    nci_omni2.nci_sum_pageNum = values.pageNum || "";
    nci_omni2.nci_sum_totalPages = values.totalPages || "";
    nci_omni2.nci_sum_isPremium = values.isPremium || "";
    nci_omni2.nci_sum_dealerId = values.dealerId || "";
    nci_omni2.nci_sum_vehicleId = values.vehicleId || "";
    nci_omni2.nci_sum_ncalId = values.ncalId || "";
    nci_omni2.nci_sum_ddp_tab = values.ddp_tab || "";
    nci_omni2.nci_ua_event = "";
    nci_omni2.nci_pidgetType = values.nci_pidgetType;
    nci_omni2.nci_pidgetName = values.nci_pidget_name;
    
    /************* Set values to be recorded in OMNITURE2 pixel ****************/
    YAHOO.Edmunds.Inventory.nciSetEdwPg();
    nci_set_values(nci_omni2);
    
    /************* Write out OMNITURE2 pixel**************/
    if(s_s2) {
        s_s2.pageName = edwpg;
        var s_code = s_s2.t();
        if (s_code) {
            document.write(s_code);
        }
    }
};

/**
 * Set values need (if available) in a cookie specific to the pidget pages so that the URL on passes YMM values.
 *
 * Create the relative URL for navigating throughout the 'inventory' section of the site.
 * Cookie values needed for other pages are set here as well so that the generated url can then be used immediately to
 * forward to the next page.
 *
 * OPTIMIZATION NOTE: rather than attempting to set values each time, only set values needed by the next page.
 *
 * @param     string    pageName    abbreviated page name of the inventory page for the URL to be generated. (ex: vdp, srl...)
 * @return    string    relative forwarding url to go to the correct inventory page.
 */
YAHOO.Edmunds.Inventory.generateURL = function(pageName, pidget_config, isConquest){
    //Maintain conquest state except when travelling to srp page. 
    if ((YAHOO.Edmunds.Inventory.getQueryStringValue("conquest") == "true")) {
        if (pageName != "srp") {
            isConquest = true;
        }
    }
    
    var url = "/inventory/" + pageName + ".html?year=" + pidget_config._year + "&yearTo=" + pidget_config._yearTo;
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._make)) {
        url = url + "&make=" + pidget_config._make;
    }

    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._model)) {
        url = url + "&model=" + pidget_config._model;
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._bodytype)) {
        url = url + "&bodytype=" + pidget_config._bodytype;
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._ddp_tab)) {
        url = url + "&ddp_tab=" + pidget_config._ddp_tab;
    }
    
    // Needed in URL for reporting.
    if (isConquest) {
        url = url + "&conquest=true";
    }
    
    return url;
};

YAHOO.Edmunds.Inventory.generateSendToAFriendURL = function(pageName){
    var pidget_config = new YAHOO.Edmunds.Inventory.PidgetConfig(true);
    
    YAHOO.Edmunds.Inventory.setCookieSub("make", pidget_config._make);
    YAHOO.Edmunds.Inventory.setCookieSub("model", pidget_config._model);
    var redirURL = pageName + ".html?year=" + pidget_config._year + "&yearTo=" + pidget_config._yearTo;
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._make)) {
        redirURL = redirURL + "&make=" + pidget_config._make;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._model)) {
        redirURL = redirURL + "&model=" + pidget_config._model;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._bodytype)) {
        redirURL = redirURL + "&bodytype=" + pidget_config._bodytype;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._ddp_tab)) {
        redirURL = redirURL + "&ddp_tab=" + pidget_config._ddp_tab;
    } // Needed in URL for reporting.
    redirURL = YAHOO.Edmunds.Inventory.URLEncode(redirURL);
    
    var url = "http://www.edmunds.com/inventory/ddp.forward.html?redirectURL=" + redirURL + "&yearTo=" + pidget_config._yearTo;
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._make)) {
        url = url + "&make=" + pidget_config._make;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._model)) {
        url = url + "&model=" + pidget_config._model;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._bodytype)) {
        url = url + "&bodytype=" + pidget_config._bodytype;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._modelId)) {
        url = url + "&modelId=" + pidget_config._modelId;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._styleId)) {
        url = url + "&styleId=" + pidget_config._styleId;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._radius)) {
        url = url + "&radius=" + pidget_config._radius;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._zip)) {
        url = url + "&zip=" + pidget_config._zip;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._sortOrd)) {
        url = url + "&sortOrd=" + pidget_config._sortOrd;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceFrom)) {
        url = url + "&priceFrom=" + pidget_config._priceFrom;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceTo)) {
        url = url + "&priceTo=" + pidget_config._priceTo;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._ncalId)) {
        url = url + "&ncalId=" + pidget_config._ncalId;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._dealerId)) {
        url = url + "&nci_dealer_id=" + pidget_config._dealerId;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._carId)) {
        url = url + "&carId=" + pidget_config._carId;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._transYear)) {
        url = url + "&nci_transYear=" + pidget_config._transYear;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._perPage)) {
        url = url + "&perPage=" + pidget_config._perPage;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._startRecord)) {
        url = url + "&startRecord=" + pidget_config._startRecord;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._isEnhanced)) {
        url = url + "&nci_is_edmunds=" + pidget_config._isEnhanced;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._color)) {
        url = url + "&color=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._color);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._engine)) {
        url = url + "&engine=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._engine);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._transmission)) {
        url = url + "&transmission=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._transmission);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._fuel)) {
        url = url + "&fuel=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._fuel);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._drive)) {
        url = url + "&drive=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._drive);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_make)) {
        url = url + "&atc_make=" + pidget_config._atc_make;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_model)) {
        url = url + "&atc_model=" + pidget_config._atc_model;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_body)) {
        url = url + "&atc_body=" + pidget_config._atc_body;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_color)) {
        url = url + "&atc_color=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._atc_color);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_engine)) {
        url = url + "&atc_engine=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._atc_engine);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_transmission)) {
        url = url + "&atc_transmission=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._atc_transmission);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_fuel)) {
        url = url + "&atc_fuel=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._atc_fuel);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._atc_drive)) {
        url = url + "&atc_drive=" + YAHOO.Edmunds.Inventory.URLEncode(pidget_config._atc_drive);
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._only_photo)) {
        url = url + "&only_photo=" + pidget_config._only_photo;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._only_special)) {
        url = url + "&only_special=" + pidget_config._only_special;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._ddp_tab)) {
        url = url + "&ddp_tab=" + pidget_config._ddp_tab;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._ddp_active_search)) {
        url = url + "&ddp_active_search=" + pidget_config._ddp_active_search;
    }
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._special_id)) {
            url = url + "&special_id=" + pidget_config._special_id;
    }
    
    var startRecordURL = 1 + ((pidget_config._pgNum - 1) * pidget_config._perPage);
    url = url + "&startRecord=" + startRecordURL;
    url = url + "&perPage=" + pidget_config._perPage;
    
    return url;
};

// Update the current timestamp and generate a new edd pixel. The timestamp is reset in order to get around a
// bug in the global_ajax.refreshAds() in which if the timestamp is not updated a pixel will not be written.
// This is needed so that both and edw and omniture pixel are written each time an action is taken which
// causes and ad refresh.
//
YAHOO.Edmunds.Inventory.refreshAds = function(){
    YAHOO.Edmunds.Inventory.nciSetEdwPg();
    YAHOO.Edmunds.Core.timestamp = new Date().getTime();
    window.ts = YAHOO.Edmunds.Core.timestamp;
    var tmp = new Image();
    tmp.src = new edd().toString();
    
    if (window.g_AJAXHelper) {
        window.g_AJAXHelper.refreshAds();
    } else {
        var adframes = document.getElementsByName('adframe');
        for (var i = 0; i < adframes.length; i++) {
            adframes[i].src = adframes[i].src.replace(/ord=\d*/, 'ord=' + window.ts);
        }
    }
};

// Utility function to pop up a window based on a passed in URL. Focus is switched to the new window as well.
//
YAHOO.Edmunds.Inventory.popupWindow = function(url, absoluteURL){
    if (url) {
        var popup_location = null;
        if (YAHOO.Edmunds.Inventory.IsNullOrEmpty(absoluteURL)) {
            popup_location = "/inventory/" + url;
        } else 
            if (absoluteURL == false) {
                popup_location = "/inventory/" + url;
            } else {
                popup_location = url;
            }
        newwindow = window.open(popup_location);
        if (window.focus) {
            newwindow.focus();
        }
    }
    return false;
};

YAHOO.Edmunds.Inventory.popupLightbox = function(url, absoluteURL, opts){
    if (url) {
        var popup_location = null;
        if (YAHOO.Edmunds.Inventory.IsNullOrEmpty(absoluteURL) || absoluteURL) {
            popup_location = "/inventory/" + url;
        } else {
            popup_location = url;
        }
        
        var apply = function(o, e){
            for (var p in e) 
                o[p] = e[p];
            return o;
        };
        
        var whiteout_function = function(gallery_item){
            var shadowbox_body_inner = document.getElementById("shadowbox_body_inner");
            if (shadowbox_body_inner) {
                shadowbox_body_inner.style.background = 'white';
                shadowbox_body_inner.style.backgroundColor = 'white';
            }
        };
        
        if (!opts) {
            opts = {};
        }
        
        opts.onOpen = whiteout_function;
        
        var o = {
            title: opts.title,
            type: 'iframe',
            options: apply({}, opts ||
            {}), // break the reference
            content: popup_location
        };
        
        // remove link-level options from top-level options
        var opt, l_opts = ['title', 'type', 'height', 'width', 'gallery'];
        for (var i = 0, len = l_opts.length; i < len; ++i) {
            opt = l_opts[i];
            if (typeof o.options[opt] != 'undefined') {
                o[opt] = o.options[opt];
                delete o.options[opt];
            }
        }
        
        YAHOO.Edmunds.LightBoxMedia.open(o);
    }
    
    return false;
};

/**
 * This method construct the error message for no data return from the ATC pidgets.
 *
 * @namespace YAHOO.Edmunds.Inventory
 * @method _noResultMessage
 * @param {Object} pidget_config, (String) pidgetName
 * @return String by joining all the array elements together
 * @public
 */
YAHOO.Edmunds.Inventory._noResultMessage = function(pidget_config, pidgetName){
    var a_message = [];
    a_message.push('Try modifying your search to get more results: <ul class="modify-criteria">');
    if (pidgetName == 'SRP') {
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._radius)) {
            a_message.push('<li>Expand your search radius beyond <b>' + pidget_config._radius + '</b> miles</li>');
        }
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._year)) {
        a_message.push('<li>Select a different year</li>');
    }
    
    if (YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceFrom) && !YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceTo)) {
        a_message.push('<li>Modify your price range of <b>less than ' + '$' + pidget_config._priceTo + '</b></li>');
    } else 
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceFrom) && YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceTo)) {
            a_message.push('<li>Modify your price range of <b>' + '$' + pidget_config._priceFrom + ' - $' + 'Maximum</b></li>');
        } else 
            if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceFrom) && !YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._priceTo)) {
                a_message.push('<li>Modify your price range of <b>' + '$' + pidget_config._priceFrom + ' - $' + pidget_config._priceTo + '</b></li>');
            }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._engine)) {
        a_message.push('<li>Clear your filter for only <b>' + pidget_config._engine + ' Cylinder</b> engines</li>');
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._fuel)) {
        if (pidget_config._fuel == 'A') {
            var fuel = 'Alternative';
        } else 
            if (pidget_config._fuel == 'D') {
                var fuel = 'Diesel';
            } else 
                if (pidget_config._fuel == 'G') {
                    var fuel = 'Gasoline';
                }
        a_message.push('<li>Clear your filter for only <b>' + fuel + '</b> engines</li>');
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._drive)) {
        YAHOO.Edmunds.Inventory.logDebug("dirve: *" + pidget_config._drive + "*");
        if (pidget_config._drive == '2WD') {
            var drive = '2 wheel';
        } else 
            if (pidget_config._drive == 'AWD') {
                var drive = 'All wheel';
            } else 
                if (pidget_config._drive == '4WD') {
                    var drive = '4 wheel';
                }
        a_message.push('<li>Clear your filter for only <b>' + drive + '</b> drive</li>');
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._transmission)) {
        a_message.push('<li>Clear your filter for only <b>' + pidget_config._transmission + '</b> transmissions</li>');
    }
    
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._color)) {
        a_message.push('<li>Clear your filter for only <b>' + pidget_config._color + '</b> vehicles</li>');
    }
    if (pidgetName == 'SRP') {
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._only_photo)) {
            a_message.push('<li>Clear your filter for only listings with <b>photos</b></li>');
        }
        
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._only_special)) {
            a_message.push('<li>Clear your filter for only listings with <b>dealer specials</b></li>');
        }
        
    }
    a_message.push('</ul>');
    
    var s_message = a_message.join(" ");
    return s_message;
}

/**
 * This method construct the error message for loading error with "a make and model" available
 *
 * @namespace YAHOO.Edmunds.Inventory
 * @method _withMakeModelLoadErrMsg
 * @param {Object} vehicle_data, (Object) pidget_config
 * @return String by joining all the array elements together
 * @public
 */
YAHOO.Edmunds.Inventory._withMakeModelLoadErrMsg = function(vehicle_data, pidget_config){
    var myip_url = '/' + YAHOO.Edmunds.Inventory.getNiceName(vehicle_data[0].edmundsMake) + '/' + YAHOO.Edmunds.Inventory.getNiceName(vehicle_data[0].edmundsModel) + '/' + vehicle_data[0].year + '/index.html';
    var vdp_url = '/new/' + vehicle_data[0].year + '/' + YAHOO.Edmunds.Inventory.getNiceName(vehicle_data[0].edmundsMake) + '/' + YAHOO.Edmunds.Inventory.getNiceName(vehicle_data[0].edmundsModel) + '/' + vehicle_data[0].edmundsTrimId + '/dealerpricing.html';
    
    var a_err_msg = [];
    a_err_msg.push("<br>We're sorry, we were unable to load the information you requested. ");
    a_err_msg.push("Please check back in a few minutes and hopefully we will have resolved the issue.");
    a_err_msg.push("<br /><br />In the meantime, feel free to <a href='");
    a_err_msg.push(myip_uri);
    a_err_msg.push("'>browse through more research</a> for ");
    a_err_msg.push(pidget_config._yearFrom);
    a_err_msg.push(" ");
    a_err_msg.push(YAHOO.Edmunds.Inventory.URLDecode(pidget_config._make));
    a_err_msg.push(" ");
    a_err_msg.push(YAHOO.Edmunds.Inventory.URLDecode(pidget_config._model));
    a_err_msg.push(" or <a href='");
    a_err_msg.push(vdp_uri);
    a_err_msg.push("'>get a quick quote</a> from dealers in your area");
    
    var s_err_msg = a_err_msg.join("");
    return s_err_msg;
}

/**
 * This method construct the error message for loading error with "no make and model" available
 *
 * @namespace YAHOO.Edmunds.Inventory
 * @method _withNoMakeModelLoadErrMsg
 * @param no parameter required
 * @return String by joining all the array elements together
 * @public
 */
YAHOO.Edmunds.Inventory._withNoMakeModelLoadErrMsg = function(){
    var a_err_msg = [];
    a_err_msg.push("<br>We're sorry, we were unable to load the information you requested. ");
    a_err_msg.push("Please check back in a few minutes and hopefully we will have resolved the issue.");
    a_err_msg.push("<br /><br />In the meantime, feel free to ");
    a_err_msg.push("<a href='http://www.edmunds.com/new/index.html'>browse through more research</a>");
    a_err_msg.push(" for new cars or ");
    a_err_msg.push("<a href='http://www.edmunds.com/futuremodels/2009/index.html'>look through the newest models</a>");
    a_err_msg.push(" coming out this year.");
    
    var s_err_msg = a_err_msg.join("");
    return s_err_msg;
}

/**
 * This method construct the error message for no vehicle found on the inventory tab
 *
 * @namespace YAHOO.Edmunds.Inventory
 * @method _inventoryTabNoVehiclesFoundErrMsg
 * @param (Object) pidget_config
 * @return String by joining all the array elements together
 * @public
 */
YAHOO.Edmunds.Inventory._inventoryTabNoVehiclesFoundErrMsg = function(pidget_config){
    var a_err_msg = [];
    var _make = '';
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._make)) {
        _make = '?make=' + pidget_config._make;
    }
    a_err_msg.push('Try visiting our <a href="http://www.edmunds.com/inventory/srp.html' + _make + '">inventory search page</a> where you can: ');
    a_err_msg.push('<ul class="modify-criteria">');
    var rad = YAHOO.Edmunds.Inventory.IsNullOrEmpty(pidget_config._radius) ? 50 : pidget_config._radius;
    a_err_msg.push('<li>Expand your search radius beyond <b>' + rad + '</b> miles</li>');
    a_err_msg.push('<li>Select a different year, make, or model</li>');
    a_err_msg.push('<li>Search by minimum / maximum price</li>');
    a_err_msg.push('<li>Narrow your search results by color, engine, transmission, and more!</li>');
    a_err_msg.push('</ul>');
    
    var s_err_msg = a_err_msg.join("");
    return s_err_msg;
}

/**
 * This method construct the error message translation error
 *
 * @namespace YAHOO.Edmunds.Inventory
 * @method _translationLoadErrMsg
 * @param no parameter is required
 * @return String by joining all the array elements together
 * @public
 */
YAHOO.Edmunds.Inventory._translationLoadErrMsg = function(){
    var make = YAHOO.Edmunds.Inventory.getCookieSub('make');
    
    var a_err_msg = [];
    a_err_msg.push('<p>This particular model year may be new and dealers may not have inventory on their lots yet. ');
    a_err_msg.push('A notification has been sent to our team to check its status. ');
    a_err_msg.push('Check back later for inventory on this vehicle.</p><p><br/></p>');
    a_err_msg.push('<p>In the meantime, try searching dealer inventory for ');
    a_err_msg.push('<a href="srp.html');
    if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(make)) {
        a_err_msg.push('?make=' + make + '">other ' + make + ' vehicles in your area.</a></p>');
    } else {
        a_err_msg.push('">Other vehicles in your area.</a></p>');
    }
    
    var s_err_msg = a_err_msg.join("");
    return s_err_msg;
}

YAHOO.Edmunds.Inventory._genEdmundsErrorCode = function(data) {
    var sEdmundsErrorCode = '';
    if (data) {
        if(data.errorCode || (data.errorCode && data.errorCause)) {
            sEdmundsErrorCode = '<p><br/></p><p style="font-size:x-small; color:gray; text-align:right;"> Error type (';
            if (data.errorCode && data.errorCause) {
                var aSubErrorCodes = data.errorCause.split(":");
                sEdmundsErrorCode =  sEdmundsErrorCode + data.errorCode + ';' + aSubErrorCodes[1] + ')</p>';
            } else if (data.errorCode) {
                var aErrorCodes = data.errorCode.split(";");
                sEdmundsErrorCode = sEdmundsErrorCode + aErrorCodes[0] + ')</p>';
            }
        }
    } 
    
    return sEdmundsErrorCode;
}

YAHOO.Edmunds.Inventory.showPidget = function(pidgetVar, pidgetName, pidget_config, data){
    if (pidgetVar == "hide") {
        throw "Passed in a 'hide' parameter, please use YAHOO.Edmunds.Inventory.hidePidget instead!";
    } else {
        var kill_timers = false;
        if (pidgetVar == "no_results") {
            kill_timers = true;
        } else {
        
            if (pidgetVar == "error") {
                kill_timers = true;
            } else {
                if (pidgetVar == "fatal_error") {
                    kill_timers = true;
                }
            }
        }
        
        if (kill_timers && pidget_config) {
            pidget_config._endTimer(pidget_config, true);
        }
        return YAHOO.Edmunds.Inventory._displayPidget(pidgetVar, pidgetName, pidget_config, data);
    }
}

YAHOO.Edmunds.Inventory.hidePidget = function(pidgetName, pidget_config){
    return YAHOO.Edmunds.Inventory._displayPidget("hide", pidgetName, pidget_config);
}

// Controller function which toggles the appropriate 'div' sections on the display pages in order to make
// either the pidget or an appropriate error message display.
//
YAHOO.Edmunds.Inventory._displayPidget = function(pidgetVar, pidgetName, pidget_config, data){

    var pidgetDiv = document.getElementById("edmui-pidget" + pidgetName);
    var pidgetMatchError = document.getElementById("pidget-match-error");
    var pidgetLoadError = document.getElementById("pidget-load-error");
    var pidgetMatchErrorText = document.getElementById("match-error-text");
    
    // Turn all pidgets off by default. Activate the correct div only for simplicity
    YAHOO.Edmunds.Inventory.hideElement("pidget-match-error");
    YAHOO.Edmunds.Inventory.hideElement("pidget-load-error");
    YAHOO.Edmunds.Inventory.hideElement("edmui-pidget" + pidgetName);
    
    if (pidgetVar == "hide") {
    } else 
        if (pidgetVar == "valid") {
            //No loading error and there are results in the pidget
            YAHOO.Edmunds.Inventory.showElement("edmui-pidget" + pidgetName);
            YAHOO.Edmunds.Inventory.showElement("ddp_tabs");
        } else 
            if (pidgetVar == "no_results") {
                //No loading error, but there is no result in the pidget
                if (pidgetName == 'DealerInfo') {
                    YAHOO.Edmunds.Inventory.hideElement("ddp_tabs");
                }
                var noResultMsgText = YAHOO.Edmunds.Inventory._noResultMessage(pidget_config, pidgetName);
                pidgetMatchErrorText.innerHTML = noResultMsgText;
                YAHOO.Edmunds.Inventory.showElement("pidget-match-error");
            } else 
                if (pidgetVar == "vdp_inventory_no_results") {
                    var noResultMsgText = YAHOO.Edmunds.Inventory._inventoryTabNoVehiclesFoundErrMsg(pidget_config);
                    pidgetLoadError.innerHTML = noResultMsgText;
                    YAHOO.Edmunds.Inventory.showElement("pidget-load-error");
                } else {
                    //Loading error
                    if (pidgetName == 'DealerInfo') {
                        YAHOO.Edmunds.Inventory.hideElement("ddp_tabs");
                    }
                    YAHOO.Edmunds.Inventory.showElement("pidget-load-error");
                    
                    var vehicle_translation_found_callback = function(o){
                        var pidgetLoadErrorText = document.getElementById("load-error-text");
                        var sEdmundsErrorCode = YAHOO.Edmunds.Inventory._genEdmundsErrorCode(data);
                        if (pidgetLoadErrorText) {
                            try {
                                var vehicle_data = YAHOO.lang.JSON.parse(o.responseText);
                                if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(vehicle_data[0].edmundsMake) && !YAHOO.Edmunds.Inventory.IsNullOrEmpty(vehicle_data[0].edmundsModel)) {
                                    pidgetLoadErrorText.innerHTML = YAHOO.Edmunds.Inventory._withMakeModelLoadErrMsg(vehicle_data, pidget_config) + sEdmundsErrorCode;
                                } else {
                                    pidgetLoadErrorText.innerHTML = YAHOO.Edmunds.Inventory._withNoMakeModelLoadErrMsg() + sEdmundsErrorCode;
                                }
                            } 
                            catch (e) {
                                pidgetLoadErrorText.innerHTML = YAHOO.Edmunds.Inventory._withNoMakeModelLoadErrMsg() + sEdmundsErrorCode;
                            }
                        }
                    };
                    
                    var no_vehicle_translation_found_callback = function(o){
                        var sEdmundsErrorCode = YAHOO.Edmunds.Inventory._genEdmundsErrorCode(data);                    
                        var pidgetLoadErrorTitle = document.getElementById("load-error-title");
                        var pidgetLoadErrorText = document.getElementById("load-error-text");
                        if (pidgetLoadErrorText) {
                            pidgetLoadErrorTitle.innerHTML = "New or Updated Model";
                            pidgetLoadErrorText.innerHTML = YAHOO.Edmunds.Inventory._translationLoadErrMsg() + sEdmundsErrorCode;
                            YAHOO.Edmunds.Inventory.clearPidgetConfig();
                        }
                    };
                    
                    var vehicle_translation = new YAHOO.Edmunds.Inventory.VehicleTranslation();
                    vehicle_translation.addCallback('translation_found', vehicle_translation_found_callback);
                    vehicle_translation.addCallback('no_translation_found', no_vehicle_translation_found_callback);
                    vehicle_translation.addCallback('translation_error', no_vehicle_translation_found_callback);
                    vehicle_translation.addCallback('translation_failure', no_vehicle_translation_found_callback);
                    
                    if (!pidget_config) {
                        pidget_config = new YAHOO.Edmunds.Inventory.PidgetConfig(true);
                    }
                    // Use the _nci_transYear if it is available. If it is not, use the greater of the current year
                    // and _yearFrom.
                    var current_year = new Date().getFullYear();
                    var tYear = null;
                    if (pidget_config._transYear && pidget_config._transYear.length > 0) {
                        tYear = pidget_config._transYear;
                    } else 
                        if (pidget_config._yearFrom && pidget_config._yearFrom.length > 0) {
                            if (pidget_config._yearFrom > current_year) {
                                tYear = pidget_config._yearFrom;
                            } else {
                                tYear = current_year;
                            }
                        }
                    
                    vehicle_translation.run(tYear, pidget_config._make, pidget_config._model, pidget_config._modelId, pidget_config._styleId);
                }
};

// Timeout functions
YAHOO.Edmunds.Inventory.Timeout = function(pidget_configs, data){
};

YAHOO.Edmunds.Inventory.Timeout.prototype = {

    onPidgetTimeout: function(pidget_configs, data){
        for (var i = 0; i < pidget_configs.length; i++) {
            var pidget_config = pidget_configs[i];
            if (pidget_config) {
                pidget_config._error = true;

            if(!data || !(data && data.hideTimeoutError)) {
                    YAHOO.Edmunds.Inventory.showPidget("timeout", pidget_config._containerID, pidget_config, data);                                        
                }
            }            
            
            var values = [];            
            values.loadState = "error";
            
            if (data) {
                for (var i in data) {
                    values[i] = data[i];
                }
            }
                        
            YAHOO.Edmunds.Core.timestamp = new Date().getTime();
            ts = YAHOO.Edmunds.Core.timestamp;
            YAHOO.Edmunds.Inventory.setInventorySummaryVars(values, pidget_config);
            YAHOO.Edmunds.Inventory.writeOmni2Pixel(values);
        }
        
        if (window.wait) {
            window.wait.hide();
        }
        var loading_graphic = document.getElementById('loading-graphic');
        if (loading_graphic) {
            loading_graphic.style.visibility = 'hidden';
        }
        
    }
};

YAHOO.Edmunds.Inventory.setGlobalPidgetTimeout = function(curr_page, millis){
    YAHOO.Edmunds.Inventory.getTimeoutManager().startGlobalPidgetTimeout(curr_page, millis);
};

YAHOO.Edmunds.Inventory.resetGlobalPidgetTimeout = function(){
    YAHOO.Edmunds.Inventory.getTimeoutManager().resetPidgetTimeout(null, true);
};

// Set up call to vehicle translation service.
//

YAHOO.Edmunds.Inventory.VehicleTranslation = function(scope){
    this.scope = scope;
};

YAHOO.Edmunds.Inventory.VehicleTranslation.prototype = {

    addCallback: function(callback_type, callback){
        if (callback_type) {
            if (callback_type == 'translation_init') {
                this.translation_init_callback = callback;
            } else 
                if (callback_type == 'translation_destroy') {
                    this.translation_destroy_callback = callback;
                } else 
                    if (callback_type == 'translation_found') {
                        this.translation_found_callback = callback;
                    } else 
                        if (callback_type == 'no_translation_found') {
                            this.no_translation_found_callback = callback;
                        } else 
                            if (callback_type == 'translation_error') {
                                this.translation_error_callback = callback;
                            } else 
                                if (callback_type == 'translation_failure') {
                                    this.translation_failure_callback = callback;
                                } else {
                                    YAHOO.Edmunds.Inventory.logDebug("Callback " + callback + " is not recognized!");
                                }
        } else {
            YAHOO.Edmunds.Inventory.logDebug("Callback " + callback + " is not recognized!");
        }
    },
    
    handleVehicleTranslationFailure: function(o){
        try {
            if (this.translation_failure_callback) {
                this.translation_failure_callback(o);
            }
        }
        finally {
            if (this.translation_destroy_callback) {
                this.translation_destroy_callback();
            }
        }
    },
    
    handleVehicleTranslationSuccess: function(o){
        if (o.responseText !== 'undefined') {
            // Reset global timeout so that the pidget has a full 8 seconds to load after init has been
            // called.
            
            try {
                var partnerdata = YAHOO.lang.JSON.parse(o.responseText);
                
                if (partnerdata && partnerdata.length > 0) {
                    if (this.translation_found_callback) {
                        this.translation_found_callback(o, partnerdata);
                    }
                } else {
                    if (this.no_translation_found_callback) {
                        this.no_translation_found_callback(o);
                    }
                }
            } 
            catch (err) {
                if (this.translation_error_callback) {
                    this.translation_error_callback(o);
                }
            }
            finally {
                if (this.translation_destroy_callback) {
                    this.translation_destroy_callback();
                }
            }
        }
    },
    
    run: function(_tYear, _make, _model, _modelId, _styleId){
        var callback = {
            cache: false,
            argument: [ this.scope ],
            success: this.handleVehicleTranslationSuccess,
            failure: this.handleVehicleTranslationFailure,
            scope: this
        };
        
        var requestBase = '/inventory/ATC_Vehicle_Translation_Service.html';
        var requestData = 'timestamp=' + new Date().getTime() + '&partner=AUTOTRADER';
        
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_tYear)) {
            requestData = requestData + "&year=" + _tYear;
        }
        
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_make)) {
            requestData = requestData + "&make=" + _make;
        }
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_model)) {
            requestData = requestData + "&model=" + _model;
        }
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_modelId)) {
            requestData = requestData + "&modelId=" + _modelId;
        }
        if (!YAHOO.Edmunds.Inventory.IsNullOrEmpty(_styleId)) {
            requestData = requestData + "&styleId=" + _styleId;
        }
        
        if (this.translation_init_callback) {
            this.translation_init_callback();
        }

        YAHOO.util.Connect.setDefaultPostHeader(false);
        YAHOO.util.Connect.initHeader('Content-Type', 'application/x-www-form-urlencoded-ajax');
        YAHOO.util.Connect.asyncRequest('POST', requestBase, callback, requestData);
    }
};
