/**
 *	If the YAHOO.Edmunds object is undefined, define it
 *	@access	public
 *	@Singleton
 *	@static
 */
if(typeof YAHOO.Edmunds == 'undefined') {
    YAHOO.Edmunds = {};
}


/**
 *	VehicleInfo class can be used as a helper to create different variation of Year Make Model drop down boxes.
 *	@requires	YAHOO, YAHOO.Edmunds, YAHOO.util.Event, YAHOO.lang
 *	@class		YAHOO.Edmunds.VehicleInfo
 *	@param		string	divId				The HTMLElement ID design value of the Div Tag
 *	@param		string  configurationId 	The Id which represents particular DropDown box combination (example: YearMakeModel)
 *	@param		string	submitButtonLabel	The Submit button label
 *	@param		string  confSet             Conf Set helps to build appropriate Data set (JSON object) (example: un- used and new vehicles)
 *	@param		string	tid				    TID design value
 *	@param		string  formActionURL		URL design value for Action attribute of the FORM html tag.
 *  @param      string  zipcookie           Zip code Value from the cookie.
 *  @param      string  imgSRC              URL value for the SRC atribute of the IMG TAg
 *  @param      string  currentPage         Current page whith VehicleDropDownBox component (this value will be added to the Globing)
 *	@return		void
 *	@constructor
 */
YAHOO.Edmunds.VehicleInfo = function(divId, confId, submitButtonLabel, confSet, tid, formActionURL, zipcookie, imgSRC,
                                     currentPage) {
    this.divId = divId;
    this.confId = confId;
    this.submitButtonLabel = submitButtonLabel;
    this.confSet = confSet;
    this.tid = tid;
    this.formActionURL = formActionURL;
    this.zipcookie = zipcookie;
    this.imgSRC = imgSRC;
    this.currentPage = currentPage;
    // Selector which helps to separate various AJAX response calls.
    this.dropDownSelector = "";
    // Helps to refresh DropDown boxes values based on configuration settings.
    this.dropdownRefreshMap = {};
    this.proxyAjaxHelper = new AjaxHelperListener();
    //Separate Select Tag HTMLElement Id values.
    this.yearselect = "yearselect" + confId;
    this.makeselect = "makeselect" + confId;
    this.modelselect = "modelselect" + confId;
};

/**
 * @property string Class version 
 * @static
 */
YAHOO.Edmunds.VehicleInfo.VERSION = '0.0.1';

/**
 *	Defining public methods for the VehicleInfo class
 *	@access	public
 *	@class	YAHOO.Edmunds.VehicleInfo
 */
YAHOO.Edmunds.VehicleInfo.prototype = {

/**
 *	Builds particular DropDown Boxes based on confId value (example: 1 for YearMakeModel drop down box)
 *	@method renderConfiguration
 *	@param	void
 *	@return	void
 */
    renderConfiguration: function() {

        var formTag = this.buildForm(this.confId);

        switch(this.confId) {
            case 1: //YearMakeModel Submit Button combination
            //Year DropDown Box
                var yearTextLabel = document.createTextNode("Vehicle Model Year:");
                var yearLabelTag = document.createElement("label");
                yearLabelTag.htmlFor = this.yearselect;
                yearLabelTag.appendChild(yearTextLabel)
                formTag.appendChild(yearLabelTag);
                this.buildSelect(this.yearselect, "", "vehicleInfo" + this.confId + ".getMakes();", "Select Year");

            //Make DropDown Box
                var makeTextLabel = document.createTextNode("Vehicle Make:");
                var makeLabelTag = document.createElement("label");
                makeLabelTag.htmlFor = this.makeselect;
                makeLabelTag.appendChild(makeTextLabel)
                formTag.appendChild(makeLabelTag);
                this.buildSelect(this.makeselect, "", "vehicleInfo" + this.confId + ".getModels();", "Select Make");

            //Model DropDown Box
                var modelTextLabel = document.createTextNode("Vehicle Model:");
                var modelLabelTag = document.createElement("label");
                modelLabelTag.htmlFor = this.modelselect;
                modelLabelTag.appendChild(modelTextLabel)
                formTag.appendChild(modelLabelTag);
                this.buildSelect(this.modelselect, "", "", "Select Model");

                this.buildSubmitButton("continue");
                this.setAjaxCall("year", {});
                this.dropdownRefreshMap = {"modelselect":this.modelselect};
                break;
            case 3: //Make ZipCode and  Submit Button combination
                this.buildSelect(this.makeselect, "make", "", "Select Make");
                var zipCodeTextLabel = document.createTextNode("Zip Code:");
                var zipLabelTag = document.createElement("label");
                zipLabelTag.htmlFor = "setzip" + this.confId;
                zipLabelTag.appendChild(zipCodeTextLabel)
                formTag.appendChild(zipLabelTag);

                var oKStr = " if (vehicleInfo" + this.confId + ".infoCheckEnter(event)){ vehicleInfo" + this.confId
                    + ".submitForm(); return false;} ";

                var zipCodeTag = this.proxyAjaxHelper.createElement("input", "setzip"
                    + this.confId, {"value":this.zipcookie, "size":"5", "class":"input-zip", "maxlength":"5","name":"zip","type":"text","onkeypress":oKStr});

                var moduleInputTag = this.proxyAjaxHelper.createElement("input", false + this.confId,
                {"name":"module","type":"hidden","value":"dealerships"});

                formTag.appendChild(moduleInputTag);
                formTag.appendChild(zipCodeTag);
                this.buildSubmitButton("rate-dealer");
                this.setAjaxCall("make", {});
                break;

        }
    },
/**
 *	Makes AJAX call in order to build JSON Data set based on ConfId (example:1) and confSet (example: un)
 *	@method setAjaxCall
 *	@param	string		itemName	 helps to build particular JSON Data set (example: year)
 *	@param	map  		selectedItemsMap map of selected values from DropDown box
 *	@return	void
 */
    setAjaxCall: function(itemName, selectedItemsMap) {
        var postUrl = this.currentPage + '.' + itemName + '.vehiclejsondataset.html';
        var postData = "confSet=" + this.confSet + "&confId=" + this.confId;
        for(var key in selectedItemsMap) {
            postData = postData + "&" + key + "=" + selectedItemsMap[key]
        }
        this.dropDownSelector = itemName;
        var request = YAHOO.util.Connect.asyncRequest('POST', postUrl, {success:this.handleSuccessOnDropdown,
            failure:this.handleFailureOnDropdown, scope:this}, postData);
    },
/**
 *	Failure callback AJAX handler.
 *	@method handleFailureOnDropdown
 *	@param	object o  object which represents AJASX response
 *	@return	void
 */
    handleFailureOnDropdown: function(o) {

    },
/**
 *	Success callback AJAX handler. Based on the selector's value (example:year) builds particular option Tag.
 *	@method handleSuccessOnDropdown
 *	@param	object o  object which represents AJASX response
 *	@return	void
 */
    handleSuccessOnDropdown: function(o) {
        if(o.responseText != undefined) {

            switch(this.dropDownSelector) {
                case 'year':
                //Builds year option tags
                    var years = eval(o.responseText);
                    this.buildOptions(years.sort(this.compareDes), this.yearselect);
                    break;
                case 'make':
                //Builds make option tags
                    var makes = eval(o.responseText);
                    this.buildOptions(makes, this.makeselect);
                    break;
                case 'model':
                //Builds model option tags
                    var models = eval(o.responseText);
                    this.buildOptions(models, this.modelselect);
                    break;
                case 'zip':
                //Validates zipcode value
                    var isZipCodeFromAJAXValid = eval(o.responseText);
                    if(isZipCodeFromAJAXValid) {
                        this.setActionAttributeOftheForm(this.formActionURL);
                    } else {
                        var zipTag = document.getElementById("setzip" + this.confId)
                        alert("Please enter a valid 5-digit ZIP code");
                        zipTag.focus();
                    }
                    break;

                default:
                    break;
            }
        }
    },
/**
 *	Helps to build FORM HTMLelement Tag.
 *	@method buildForm
 *	@param	void
 *	@return	object formTag FORM HTMLelement object
 */
    buildForm: function() {
        var mainDivTag = document.getElementById(this.divId);
        // The form tag needs to support the target attribute to support popups.
        // This is accomplished by passing in the target attribute in the request parameter of
        // the formActionURL. The parameter is stripped after processing. Do not modify
        // or group the regex patterns unless you have a thorough understanding of javascript regex.
        var formTarget = "_self";
        if(this.formActionURL.match(/\?.*target.*/) != null) {
            var urlstr = this.formActionURL.split(/\?/);
            var targetValue = urlstr[1].match(/target=\w*/);
            if(targetValue != null) {
                formTarget = targetValue[0].replace(/target=/,'');
                var repstr = urlstr[1].replace(/&amp;target=\w*|&target=\w*|^target=\w*&amp;|^target=\w*&?/,'');
                if(repstr.length > 0) {
                    this.formActionURL = urlstr[0] + '?' + repstr;
                } else {
                    this.formActionURL = urlstr[0];
                }
            }
        }        
        var formTag = this.proxyAjaxHelper.createElement("form", "configurationForm"
            + this.confId, {"action":"", "name":"configurationForm" + this.confId,"method":"POST", "target":formTarget});
        mainDivTag.appendChild(formTag);
        return formTag;
    },
/**
 *	Helps to build Select HTMLelement Tag.
 *	@method buildSelect
 *	@param	string  selectedId        Value for ID attribute of the Select HTMLelement tag
 *	@param	string  name              Value for Name attribute of the Select HTMLelement tag
 *	@param	string  functionName      Value for onchange js event attribute of the Select HTMLelement tag
 *	@param	string  firstOptionValue  Text Value for first Option HTMLelement tag
 *	@return	void
 */
    buildSelect: function(selectId, name, functionName, firstOptionValue) {
        var formTag = document.getElementById("configurationForm" + this.confId);
        var selectTag = document.createElement("select");
        selectTag.id = selectId
        selectTag.name = name;
        if(functionName) {
            YAHOO.util.Event.addListener(selectTag, "change", new Function(functionName));
        }
        var firstDefaultOoptionTag = document.createElement("option");
        firstDefaultOoptionTag.value = "";
        firstDefaultOoptionTag.name = name;
        firstDefaultOoptionTag.appendChild(document.createTextNode(firstOptionValue));
        selectTag.appendChild(firstDefaultOoptionTag);
        formTag.appendChild(selectTag);

    },
/**
 *	Helps to build Options HTMLelement Tags.
 *	@method buildOptions
 *	@param	array  items       List of items (example: years, makes, models)
 *	@param	string  selectId   Id value of the Select HTMLelement tag
 *	@return	void
 */
    buildOptions: function(items, selectId) {
        var numberOfItems = items.length;
        var selectTag = document.getElementById(selectId);
        this.removeOptions(selectTag, selectId);
        for(var i = 0; i < numberOfItems; i++) {
            var item = items[i];
            var optionTag = this.proxyAjaxHelper.createElement("option", false, {"value":item}, item);
            selectTag.appendChild(optionTag);
        }

    },
/**
 *	Helps to build Submit Button.
 *	@method buildSubmitButton
 *	@param	string  classValue Value for the class atribute ot the IMG Tag.
 *	@return	void
 */
    buildSubmitButton: function(classValue) {
        var formTag = document.getElementById("configurationForm" + this.confId);
        var oCStr = "s_objectID='" + this.tid + "'; setTID('" + this.tid + "'); " + "vehicleInfo" + this.confId
            + ".submitForm(); return false;";
        var inputTag = this.proxyAjaxHelper.createElement("input", false, {"type":"image","name":this.getNiceName(this.submitButtonLabel),"class":classValue, "src":this.imgSRC,"onclick":oCStr});
        formTag.appendChild(inputTag);
    },
/**
 *	Helps to remove current Options HTMLelement Tags.
 *	@method removeOptions
 *	@param	string  selectTag Select HtHMLelement tag
 *	@param	string  selectId  Id value of the Select HTMLelement tag
 *	@return	void
 */
    removeOptions: function(selectTag, selectId) {

        var totalopts = selectTag.length;
        if(totalopts > 1) {

            var defaultOptionText = selectTag.options[0].text;
            selectTag.options.length = 0;
            var defaultOptionTag = this.proxyAjaxHelper.createElement("option", false, {"value":""}, defaultOptionText);
            selectTag.appendChild(defaultOptionTag);
        }
        // Helps to remove options of all Select HTMLelements tags based on value from dropdownRefreshMap
        for(var key in this.dropdownRefreshMap) {
            if(this.dropdownRefreshMap[key] != selectId) {
                var optionalSelectTag = document.getElementById(this.dropdownRefreshMap[key]);
                var optionalTotalopts = optionalSelectTag.length;
                if(optionalTotalopts > 1) {

                    var optionalDefaultOptionText = optionalSelectTag.options[0].text;
                    optionalSelectTag.options.length = 0;
                    var optionalDefaultOptionTag = this.proxyAjaxHelper.createElement("option", false, {"value":""}, optionalDefaultOptionText);
                    optionalSelectTag.appendChild(optionalDefaultOptionTag);
                }
            }
        }
    },
/**
 *	Helps to make AJAX call to get Make list after onclick event on a particular DropDown box.
 *	@method getMakes
 *	@param	void
 *	@return	void
 */
    getMakes: function() {
        var yearSelectTag = document.getElementById(this.yearselect);
        if(yearSelectTag.selectedIndex > 0) {
            var selectedYear = yearSelectTag.options[yearSelectTag.selectedIndex].text;
            var attributeMap = {"selectedYear":selectedYear};
            this.setAjaxCall("make", attributeMap);
        }
    },
/**
 *	Helps to make AJAX call to get Model list after onclick event on a particular DropDown box.
 *	@method getModels
 *	@param	void
 *	@return	void
 */
    getModels: function() {
        var makeSelecteTag = document.getElementById(this.makeselect);
        var attributeMap = {};

        if(makeSelecteTag.selectedIndex > 0) {
            var selectedMake = makeSelecteTag.options[makeSelecteTag.selectedIndex].text;
            var yearSelecteTag = document.getElementById(this.yearselect);
            // Get Models for particular Year and Make else only for particular Make
            if(yearSelecteTag) {
                var selectedYear = yearSelecteTag.options[yearSelecteTag.selectedIndex].text;
                attributeMap = {"selectedYear":selectedYear,"selectedMake":selectedMake};
            } else {
                attributeMap = {"selectedMake":selectedMake};
            }
            this.setAjaxCall("model", attributeMap);
        }
    },
/**
 *	Submits particular FORM basede on confId value (exapmple: 1 - YearMakeModel)
 *	@method submitForm
 *	@param	void
 *	@return	void
 */
    submitForm: function() {
        var crrURL = this.formActionURL ;
        switch(this.confId) {
            case 1:
            //YearMakeModel Submit Button combination
                if(this.validateDropDownBoxSelect({"yearselect":"Please Select Year","makeselect":"Please Select Make","modelselect":"Please Select Model"})) {
                    var yearSelectTag = document.getElementById(this.yearselect);
                    var selectedYear = yearSelectTag.options[yearSelectTag.selectedIndex].text
                    var makeSelectTag = document.getElementById(this.makeselect);
                    var selectedMake = makeSelectTag.options[makeSelectTag.selectedIndex].text
                    var modelSelectTag = document.getElementById(this.modelselect);
                    var selectedModel = modelSelectTag.options[modelSelectTag.selectedIndex].text

                    crrURL = crrURL.replace('year', selectedYear);
                    crrURL = crrURL.replace('make', this.getNiceName(selectedMake));
                    crrURL = crrURL.replace('model', this.getNiceName(selectedModel));

                    this.setActionAttributeOftheForm(crrURL);
                }
                break;
            case 3:
            //Make ZipCode and  Submit Button combination
                if(this.validateDropDownBoxSelect({"makeselect":"Please Select Make"}) && this.isZipCodeValid()) {
                    var selectedZipValue = document.getElementById("setzip" + this.confId).value;
                    this.setAjaxCall("zip", {"setzip":selectedZipValue});
                }
                break;
        }

    },
/**
 *	Convert provided string to NiceName value (example:Mercedes Benz to mercedesbenz).
 *	@method getNiceName
 *	@param	string text String value to be converted to NiceName value.
 *	@return	string	The updated NiceName string
 */
    getNiceName: function(text) {

        var retText;
        retText = "";
        var usedtext = ("" + text).toLowerCase();
        for(var i = 0; i < usedtext.length; i++)
        {
            var charValue = usedtext.charAt(i);
            if((charValue >= 'a' && charValue <= 'z') || (charValue >= '0' && charValue <= '9'))
            {
                retText += charValue;
            }
        }
        return retText;
    },
/**
 *	Validates DropDown Box selections.
 *	@method validateDropDownBoxSelect
 *	@param	map messagesMap Map of Validation Messages.
 *	@return	boolean  True if valid
 */
    validateDropDownBoxSelect: function(messagesMap) {

        var isValid = true;
        for(var key in messagesMap) {

            var itemSelectTag = document.getElementById(key + this.confId);
            if(itemSelectTag.selectedIndex == 0) {
                itemSelectTag.focus();
                alert(messagesMap[key]);
                isValid = false;
                break;
            }
        }
        return isValid;
    },
/**
 *	Sets Action Attribute of FORM HTMLelement tag.
 *	@method setActionAttributeOftheForm
 *	@param	string  crrURL URL design value.
 *	@return	void
 */
    setActionAttributeOftheForm: function(crrURL) {
        var formObject = eval("document.configurationForm" + this.confId);
        formObject.action = crrURL;
        formObject.submit();
    },
/**
 *	Validates ZipCode value.
 *	@method isZipCodeValid
 *	@param	void
 *	@return	boolean True if zipcode valid
 */
    isZipCodeValid: function()
    {
        var selectObject = eval("document.configurationForm" + this.confId + ".zip");
        if(selectObject)
        {
            if(selectObject.value)
            {
                if(selectObject.value.length != 5)
                {
                    alert("Please enter a valid 5-digit ZIP code");
                    selectObject.focus();
                    return false;
                }
                else
                {
                    if(isNaN(selectObject.value))
                    {
                        alert("Please enter a valid 5-digit ZIP code");
                        selectObject.focus();
                        return false;
                    }
                    return true;
                }
            }
        }
        alert("Please enter a valid 5-digit ZIP code");
        selectObject.focus();
        return false;
    },
/**
 *	Provides sorting in Des order.
 *	@method compareDes
 *	@param	array a,b Object to be sorted
 *	@return	array Sorted object
 */
    compareDes:function(a, b) {
        return -1 * ((a - 0) - (b - 0));
    },
/**
 *	Validates status of JS onkeypress event. If valid will trigger onclick event in order to submit FORM.
 *	@method infoCheckEnter
 *	@param	object event     Onkeypress Event object
 *	@param	string  formName Value of the name attribute of HTMLelement FORM tag.
 *	@return	boolean if true will trigger onlcick event in order to submit FORM
 */
    infoCheckEnter:function(event)
    {
        var code = 0;
        var formObject = eval("document.configurationForm" + this.confId);

        if(event.which)
        {
            code = event.which;
        }
        else
        {
            code = event.keyCode;
        }

        if(code == 13)
        {
            return true;
        }
        return false;

    }

}



