﻿
Type.registerNamespace('DTG.Dollar.Web.Consumer.Common.Ajax.CarType');

/// <summary>
/// CarType
///    Extender that populates controls two functions of the Car Type.
///     1. Controls the population of the Car Type DropDown List control based on the location code and pickup date
///     2. Controls the image settings for Car Type images based on the selected value in the list
/// </summary>
/// <remarks>
///    properties: 
///      {name: 'TargetControlID', type: String} : Default value for extenders identifing the DDL control
///      {name: 'LocationCode', type: String} : Location code
///      {name: 'PickupDate', type: String) : string of date of pickup
///      {name: 'SelectedValue', type: String} : value to select in drop down list (ex:car type...CDAR..)
///      {name: 'CarImageId', type: String} : Id of image element that displays the car type car
///      {name: 'PassengerImageId', type: String} : Id of image element that displays the car type passenager
///      {name: 'LuggageImageId', type: String} : Id of image element that displays the car type luggage
///      {name: 'MPGImageId', type: String} : Id of image element that displays the car type gas mpg
///      {name: 'StatsContainerId', type: String} : Id of element that contains the vehicle stat images
///      {name: 'TitleContainerId', type: String} : Id of element that contains the vehicle image title
///      {name: 'TitleId', type: String} : Id of text element that displays the car type title (Dodge Neon (or similiar))
///                 this element should reside in the element defined by the TitleContainerId
///      {name: 'SelectedCodeId', type: String} : id of element that holds the valid car type
///                 code value. element must have value property (eg. input type=hidden)
///      {name: 'SelectedTextId', type: String} : id of element that holds the selected car type
///                 description text. element must have value property (eg. input type=hidden)
///      {name: 'VehicleList', type: String} : JSON Serialize string of VehicleBasicInfo objects
///      {name: 'DefaultVehicleList', type: string) : JSON Serialize string of default VehicleBasicInfo objects
/// </remarks>
/// <history>
///     <change date="01/25/2007 12:18:00" ticket="">
///         <author>Steven Berenbrock</author>
///         <description>Initial version.</description>
///     </change>
///     <change date="09/04/2007" ticket="CR 1167">
///         <author>Steven Berenbrock</author>
///         <description>Change to Vehicle Availability Check in Res Panel
///             Pickup Location Provided/Changed : If the pickup date is the default date (i.e., tomorrow), use the existing
///              a fixed date in the future; use this in combination with the pickup location for the availability call
///              If the pickup date is NOT the default date, use the specified pickup date along with the pickup location 
///              for the availability call
///             Pickup Date Changed : If a pickup location is specified, use it along with the pickup date to determine availability
///              If a pickup location is NOT specified, do not make the availability call
///         </description>
///     </change>
///     <change date="09/25/2007" ticket="Issue 1358">
///         <author>Steven Berenbrock</author>
///         <description>changed order of search for vehicle basic info object.  search first by selected value, then by selected
///             text.
///         </description>
///     </change>
///     <change date="01/16/2008">
///         <author>Jscott1 - SiteDynamics</author>
///         <description>Added filterB2B property.
///         </description>
///     </change>
///     <change date="10/29/2008">
///         <author>Jscott1 - SiteDynamics</author>
///         <description>Updated _callCarTypeWebService method params to inlcude filterB2b.  
///                         Updated calls to this method to pass this._filterB2b.
///         </description>
///     </change>
/// </history>

DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior = function(element) {
    DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior.initializeBase(this, [element]);
    ///<summary>CarTypeBehavior Extender</summary>
    ///<param name="element">Associated element</param>

    //Properties
    this._locationCode = null;
    this._pickupDate = null;
    this._selectedValue = null;
    this._selectedText = null;
    this._carImageId = null;
    this._passengerImageId = null;
    this._luggageImageId = null;
    this._mpgImageId = null;
    this._statsContainerId = null;
    this._titleContainerId = null;
    this._titleId = null;
    this._selectedCodeId = null;
    this._selectedTextId = null;
    this._vehicleList = null;
    this._defaultVehicleList = null;
    this._filterB2b = false;

    // Member variables
    this._carTypeList = null;
    this._defaultCarTypeList = null;
    this._previousLocationCode = null;
    this._previousPickupDate = null;
    
    // Event delegates
    this._changeHandler = null;
    
    // Constants
    this._metroName = "Metro";
    this._countryName = "Country";
    this._stateName = "State";
}

DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior.prototype = {
    //*****************************************************************
    //Override methods
    //
    initialize : function() {
        DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior.callBaseMethod(this, 'initialize');
        this._previousLocationCode = "";
        this._previousPickupDate = "";
        var targetElement = this.get_element();
        
        //current cartype list preloaded at server
        if (this._vehicleList && this._vehicleList.length > 0) {
            var list = Sys.Serialization.JavaScriptSerializer.deserialize(this._vehicleList)
            if (list) {
                this._carTypeList = list;
            }
            //list initialized...clear variable
            this._vehicleList = null;  
        }
        
        //default car type list pre loaded at server
        if (this._defaultVehicleList && this._defaultVehicleList.length > 0) {
            var dlist = Sys.Serialization.JavaScriptSerializer.deserialize(this._defaultVehicleList)
            if (dlist) {
                this._defaultCarTypeList = dlist;
            }
            //list initialized...clear variable
            this._defaultVehicleList = null;  
        }

        // Attach change handler
        this._changeHandler = Function.createDelegate(this, this._onChange);
        $addHandler(targetElement, "change", this._changeHandler);
    },

    dispose : function() {
        var targetElement = this.get_element();

        // Detach change handler for self
        if (this._changeHandler) {            
            $removeHandler(targetElement, "change", this._changeHandler);
            this._changeHandler = null;
        }
        
        DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior.callBaseMethod(this, 'dispose');
    },

    //*****************************************************************
    // Property get/set methods
    //
    get_LocationCode : function() {
        return this._locationCode;
    },

    set_LocationCode : function(value) {
        this._locationCode = value;
    },
    
    get_PickupDate : function() {
        return this._pickupDate;
    },

    set_PickupDate : function(value) {
        this._pickupDate = value;
    },

    get_SelectedValue : function() {
        return this._selectedValue;
    },

    set_SelectedValue : function(value) {
        this._selectedValue = value;
    },

    get_SelectedText : function() {
        return this._selectedText;
    },

    set_SelectedText : function(value) {
        this._selectedText = value;
    },

    get_CarImageId : function() {
        return this._carImageId;
    },

    set_CarImageId : function(value) {
        this._carImageId = value;
    },
    
    get_PassengerImageId : function() {
        return this._passengerImageId;
    },

    set_PassengerImageId : function(value) {
        this._passengerImageId = value;
    },
    
    get_LuggageImageId : function() {
        return this._luggageImageId;
    },

    set_LuggageImageId : function(value) {
        this._luggageImageId = value;
    },
    
    get_MPGImageId : function() {
        return this._mpgImageId;
    },

    set_MPGImageId : function(value) {
        this._mpgImageId = value;
    }, 
    
    get_StatsContainerId : function() {
        return this._statsContainerId;
    },

    set_StatsContainerId : function(value) {
        this._statsContainerId = value;
    }, 
    
    get_TitleContainerId : function() {
        return this._titleContainerId;
    },

    set_TitleContainerId : function(value) {
        this._titleContainerId = value;
    }, 
    
    get_TitleId : function() {
        return this._titleId;
    },

    set_TitleId : function(value) {
        this._titleId = value;
    }, 
    
    get_SelectedCodeId : function() {
        return this._selectedCodeId;
    },

    set_SelectedCodeId : function(value) {
        this._selectedCodeId = value;
    }, 

    get_SelectedTextId : function() {
        return this._selectedTextId;
    },

    set_SelectedTextId : function(value) {
        this._selectedTextId = value;
    }, 
    
    get_VehicleList : function() {
        return this._vehicleList;
    },
        
    set_VehicleList : function(value) {
        this._vehicleList = value;
    },    
    
    get_DefaultVehicleList : function() {
        return this._defaultVehicleList;
    },
        
    set_DefaultVehicleList : function(value) {
        this._defaultVehicleList = value;
    },    
    
    get_FilterB2B : function() {
        return this._filterB2b;
    },
    
    set_FilterB2B : function(value) {
        this._filterB2b = value;
    },
    
    //*****************************************************************
    // Custom methods
    //
    _getImageElement : function(imageElementId) {
        ///<summary>Private method _getImageElement</summary>
        ///<remarks>get the element value from pickup location element id</remarks>   
        var imageElement = null;
        if (imageElementId) {
            imageElement = $get(imageElementId);
        }    
        return imageElement;
    },
    
    _setImageElement : function(imageElement, imageSrc) {
        ///<summary>Private method _setImageElement</summary>
        ///<param name="imageElement" type="DOM Object">DOM image element</param>
        ///<param name="imageSrc" elementType="Object">url to image</param>
        ///<remarks>set the src attribute to the image element</remarks>   
        if (imageElement) {
            imageElement.src = imageSrc;  
        }
    },
    
    _hideStats : function() {
        ///<summary>Private method _hideStats</summary>
        ///<remarks>hide the stats container</remarks>   
        if (this._statsContainerId) {
            var statElement = $get(this._statsContainerId);
            if (statElement) {
      	        statElement.style.visibility = "hidden";
      	        statElement.style.display = "none";
            }
        }
    },
    
    _hideTitle : function() {
        ///<summary>Private method _hideTitle</summary>
        ///<remarks>hide the vehicle image title container</remarks>   
        if (this._titleContainerId) {
            var titleElement = $get(this._titleContainerId);
            if (titleElement) {
      	        titleElement.style.visibility = "hidden";
      	        titleElement.style.display = "none";
            }
        }
    },
    
    _showStats : function() {
        ///<summary>Private method _showStats</summary>
        ///<remarks>show the stats container</remarks>   
        if (this._statsContainerId) {
            var statElement = $get(this._statsContainerId);
            if (statElement) {
          	    statElement.style.visibility = "visible";
      	        statElement.style.display = "inline";
      	    }
        }
    },
    
    _showTitle : function() {
        ///<summary>Private method _showTitle</summary>
        ///<remarks>show the vehicle image title container</remarks>   
        if (this._titleContainerId) {
            var titleElement = $get(this._titleContainerId);
            if (titleElement) {
      	        titleElement.style.visibility = "visible";
      	        titleElement.style.display = "inline";
            }
        }
    },

    _setCarTypeImages : function(vehicleBasicInfo) {
        ///<summary>Private method _setCarTypeImages</summary>
        ///<param name="vehicleBasicInfo" type="DOM bject">vehicle info object</param>
        ///<remarks>set the car type images....vehicle image, passenger, luggage, and mpg images</remarks>   
        if (vehicleBasicInfo) {
            this._setImageElement(this._getImageElement(this._carImageId), vehicleBasicInfo.Image);
            this._setImageElement(this._getImageElement(this._passengerImageId), vehicleBasicInfo.PassengerImage);
            this._setImageElement(this._getImageElement(this._luggageImageId), vehicleBasicInfo.LuggageImage);
            this._setImageElement(this._getImageElement(this._mpgImageId), vehicleBasicInfo.MilesPerGallonImage);
        }
    },
    
    _setCarTypeTitle : function(vehicleBasicInfo) {
        ///<summary>Private method _setCarTypeTitle</summary>
        ///<param name="vehicleBasicInfo" type="DOM bject">vehicle info object</param>
        ///<remarks>set the car type title</remarks>   
        var titleElement = $get(this._titleId);
        if (titleElement) {
            if (vehicleBasicInfo) {
                titleElement.innerHTML = vehicleBasicInfo.ImageTitle;
            }
            else {
                titleElement.innerHTML = "";
            }
        }    
    },
        
    _hasVehicleStats : function(vehicleBasicInfo) {
        ///<summary>Private method _hasVehicleStats</summary>
        ///<param name="vehicleBasicInfo" type="DOM bject">vehicle info object</param>
        /// <returns type="Boolean">Whether vehicle object has stat data</returns>
        ///<remarks>checks if vehicle object has stat data...if no type, no stats</remarks>   
        var hasStats = false;
        if (vehicleBasicInfo) {
            hasStats = (vehicleBasicInfo.Type.length > 0);
        }
        return hasStats;
    }, 

    _hasTitle : function(vehicleBasicInfo) {
        ///<summary>Private method _hasTitle</summary>
        ///<param name="vehicleBasicInfo" type="DOM bject">vehicle info object</param>
        /// <returns type="Boolean">Whether vehicle object has title data</returns>
        ///<remarks>checks if vehicle object has title data...if no type and title empty, no title</remarks>   
        var hasVehTitle = false;
        if (vehicleBasicInfo) {
            hasVehTitle = ((vehicleBasicInfo.Type.length > 0) && (vehicleBasicInfo.ImageTitle.length > 0));
        }
        return hasVehTitle;
    }, 
        
    _callCarTypeWebService : function(locCode, selected, pkDate, filterB2b) {
        ///<summary>Private method _callCarTypeWebService</summary>
        ///<param name="locCode">location code</param>
        ///<param name="selected">selected value</param>
        ///<param name="pkDate">pickup date</param>
        ///<remarks>this method calls the web service CustomerWebService to get vehicle types and images
        ///proxy for CustomerWebService.asmx GetVehiclesByDate(code, select, pickup, complete handler, error handler, user context)</remarks>
        DTG.Dollar.Web.Consumer.Services.CustomerWebService.GetVehiclesByDate(
            locCode,
            selected,
            pkDate,
            filterB2b,
            this._onCarTypeComplete, 
            this._onMethodError, 
            [this, locCode]);
    },
    
    _clearItems : function() {
        /// <summary>Clear the items from the drop down</summary>
        var targetElement = this.get_element();
        while (0 < targetElement.options.length) {
            targetElement.remove(0);
        }
    },
    
    _isPopulated : function() {
        /// <summary>Determine whether the drop down has any items</summary>
        /// <returns type="Boolean">Whether the drop down has any items</returns>
        var items = this.get_element().options.length;
        return items > 0;
    },
    
    _setOptions : function(list) {
        /// <summary>Set the contents of the DropDownList to the specified list</summary>
        /// <param name="list" mayBeNull="true" elementType="Object">Array of options</param>

        //save off result list
        this._carTypeList = list;
        
        var targetElement = this.get_element();
        // Remove existing contents
        this._clearItems();

        if (list) {
            for (i = 0 ; i < list.length ; i++) {
                var listItemName = list[i].Name;
                var listItemValue = list[i].Type;
                
                var isSelected = (listItemName == this._selectedText) ? (listItemName == this._selectedText) : (listItemValue == this._selectedValue);
                
                var optionElement = new Option(listItemName, listItemValue, false, isSelected);

                targetElement.options[targetElement.options.length] = optionElement;
            }
        }
    },

    _setCarTypeFields : function() {
        /// <summary>private method _setCarTypeFields : process the car type based on selected value in ddl
        ///     call to set images and set vehicle type title</summary>
        //get the vehicle basic info object from car Type List object
        //get vehicle info based on the selected value....else get if from selected text
        var vehicleTypeInfo = this._getVehicleInfoByValue(this._selectedValue);
        if (!vehicleTypeInfo) {
            vehicleTypeInfo = this._getVehicleInfoByText(this._selectedText);        
        }
        if (vehicleTypeInfo) {
            this._setCarTypeImages(vehicleTypeInfo);
            this._setCarTypeTitle(vehicleTypeInfo);
            if (this._hasVehicleStats(vehicleTypeInfo)) {
                this._showStats();
            }
            else {
                this._hideStats();
            }
            if (this._hasTitle(vehicleTypeInfo)) {
                this._showTitle();
            }
            else {
                this._hideTitle();
            }
        }
        else {
            if (this._isPopulated()) {
                var targetElement = this.get_element();
                //did not find selected value in list....default to first (0) item in list
                targetElement.selectedIndex = 0;
                this._selectedValue = targetElement.options[targetElement.selectedIndex].value;
                this._selectedText = targetElement.options[targetElement.selectedIndex].text;
                this._setSelectedCarTypeCode(this._selectedValue);
                this._setSelectedCarTypeText(this._selectedText);
                vehicleTypeInfo = this._carTypeList[targetElement.selectedIndex];
                if (vehicleTypeInfo) {
                    this._setCarTypeImages(vehicleTypeInfo);
                    this._setCarTypeTitle(vehicleTypeInfo);
                    if (this._hasVehicleStats(vehicleTypeInfo)) {
                        this._showStats();
                    }
                    else {
                        this._hideStats();
                    }
                    if (this._hasTitle(vehicleTypeInfo)) {
                        this._showTitle();
                    }
                    else {
                        this._hideTitle();
                    }
                }
                else {
                    this._hideStats();
                    this._hideTitle();
                }
            }
            else {
                this._hideStats();
                this._hideTitle();
            }
        }
    },
    
    _getVehicleInfoByValue : function(value) {
        /// <summary>private method _getVehicleInfoByValue : get the vehicle object Type from the list based on the value param</summary>
        /// <param name="value" elementType="string">vehicle type string</param>
        var vehicleInfo = null;
        if (this._carTypeList && this._carTypeList.length > 0) {
            for (i = 0 ; i < this._carTypeList.length ; i++) {
                if (value == this._carTypeList[i].Type) {
                    vehicleInfo = this._carTypeList[i];
                    break;
                }
            }
        }
        return vehicleInfo;
    },

    _getVehicleInfoByText : function(text) {
        /// <summary>private method _getVehicleInfoByText : get the vehicle object Name from the list based on the text param</summary>
        /// <param name="text" elementType="string">vehicle text string</param>
        var vehicleInfo = null;
        if (this._carTypeList && this._carTypeList.length > 0) {
            if (text) {
                for (i = 0 ; i < this._carTypeList.length ; i++) {
                    if (text == this._carTypeList[i].Name) {
                        vehicleInfo = this._carTypeList[i];
                        break;
                    }
                }
            }
        }
        return vehicleInfo;
    },    
    
    _setSelectedCarTypeCode : function(carTypeCode) {
        ///<summary>Private method _setSelectedCarTypeCode</summary>
        ///<param name="carTypeCode">car type code string</param>
        ///<remarks>Sets the value attribute of element identified by the _selectedCodeId</remarks>
        if (this._selectedCodeId) {
            var selectedCodeElement = $get(this._selectedCodeId);
            if (selectedCodeElement) {
                selectedCodeElement.value = carTypeCode;
            }
        }    
    },
    
    _setSelectedCarTypeText : function(carTypeText) {
        ///<summary>Private method _setSelectedCarTypeText</summary>
        ///<param name="carTypeText">car type text string</param>
        ///<remarks>Sets the value attribute of element identified by the _selectedTextId</remarks>
        if (this._selectedTextId) {
            var selectedTextElement = $get(this._selectedTextId);
            if (selectedTextElement) {
                selectedTextElement.value = carTypeText;
            }
        }    
    },
    
    _loadDefault : function() {
        /// <summary>private method loadDefault : load the default car type list</summary>
        /// <remarks>use preloaded default list if exist...else get it from web service call</remarks> 
        if (this._defaultCarTypeList && this._defaultCarTypeList.length > 0) {
            this._setOptions(this._defaultCarTypeList);
            this._setCarTypeFields();
        }
        else {
            this._callCarTypeWebService("", this._selectedValue, "", this._filterB2b);   
        }
    },
    
    load : function() {
        /// <summary>public method load : load the ddl by calling the web service.  if locationCode matches
        ///     previous locationCode, leave the current list options</summary>
        if (this._previousLocationCode != this._locationCode || this._previousPickupDate != this._pickupDate) {
            this._previousLocationCode = this._locationCode;
            this._previousPickupDate = this._pickupDate;
            if (!this._locationCode.startsWith(this._countryName) && !this._locationCode.startsWith(this._stateName) &&
                !this._locationCode.startsWith(this._metroName)) {
                this._callCarTypeWebService(this._locationCode, this._selectedValue, this._pickupDate, this._filterB2b);   
            }
            else {
                //metro/state/country location code....load default cartype list
                this._loadDefault();   
            }
        }
    },

    //*****************************************************************
    // Event handler methods
    //
    _onChange : function(evnt) {
        /// <summary>Handler for the drop down's change event</summary>
        /// <param name="evt" type="Object">Set by the browser when called as an event handler</param>
        var targetElement = this.get_element();
        if (targetElement.selectedIndex != -1) {
            this._selectedValue = targetElement.options[targetElement.selectedIndex].value;
            this._selectedText =  targetElement.options[targetElement.selectedIndex].text;
            this._setCarTypeFields();
            this._setSelectedCarTypeCode(this._selectedValue);
            this._setSelectedCarTypeText(this._selectedText);
        } 
    },
        
    _onCarTypeComplete : function(result, userContext, methodName) {
        ///<summary>Private event method onLocationReturnComplete</summary>
        ///<param name="result">Result of web service call</param>
        ///<param name="userContext">value passed to web service call for user context</param>
        ///<param name="methodName">name of method that called the web service</param>
        ///<remarks>this is the completed method call from web service call.  it processes
        ///  the results of the Location Return Search web service call.</remarks>
        var acBehavior = userContext[0];
        //var code = userContext[1];
        
        if (result && result.length > 0) {
            acBehavior._setOptions(result);
            acBehavior._setCarTypeFields();
        }
        else {
            //did not receive any cartypes for code/pickup date....load default list
            acBehavior._loadDefault();
        }
    },

    _onMethodError : function(error, userContext, methodName) {
        ///<summary>Private event method _onMethodError</summary>
        ///<param name="error">error object from web service call</param>
        ///<param name="userContext">value passed to web service call for user context</param>
        ///<param name="methodName">name of method that called the web service</param>
        ///<remarks>this method is called when an error has been received from the 
        /// web service call</remarks>
        Sys.Debug.trace(error.get_message());
    }
}

DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior.registerClass('DTG.Dollar.Web.Consumer.Common.Ajax.CarType.CarTypeBehavior', AjaxControlToolkit.BehaviorBase);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();