/**
 * NMLModelSearchForm.js
 * @name NML
 * @fileoverview Provides NML entry point integration into MI for RCLP and MIDetail page search forms
 * @requires Prototype version 1.6.0 or greater
 */

/**
 * New Model Launch model search form class
 * @author AutoTrader.com
 */
// Create namespace for the class
ATC.createNamespace('ATC.cs.research.mi');

var NML = Class.create({
    initialize: function(newModelsJSON, options) {
        this.newModels = newModelsJSON.evalJSON().models;
        this.numModels = this.newModels.length;

        this.options = {
            ieElementToHide: 'rncMIZip',
            makeSelectId: 'rncMIMake',
            makeDivId: 'rncMIMakeDiv',
            modelSelectId: 'rncMIModel',
            modelDivId: 'rncMIModelDiv',
            popId: 'nml-entry',
            popInsertionPoint: 'rncMIFields',
            submitButton: 'rncMISubmit'
        }
        Object.extend(this.options, options || {});

        this.ieElementToHide = this.options.ieElementToHide;
        this.makeSelectId = this.options.makeSelectId;
        this.makeSelect = $(this.makeSelectId);
        this.makeDivId = this.options.makeDivId;
        this.makeDiv = $(this.makeDivId);
        this.modelSelectId = this.options.modelSelectId;
        this.modelSelect = $(this.modelSelectId);
        this.modelDivId = this.options.modelDivId;
        this.modelDiv = $(this.modelDivId);
        this.popInsertionPoint = this.options.popInsertionPoint;
        this.submitButton = this.options.submitButton;

        this.initializeEventHandlers();
    },

    initializeEventHandlers: function() {
        this.makeSelect.observe('change', function() {
            var make = $F(this.makeSelectId);
            var hasNmlData = ATC.cs.research.mi.nml.hasNmlData(make);
            if (hasNmlData) {
                var popId = $(this.options.popId);
                if (popId) {
                    ATC.cs.research.mi.nml.hidePopup();
                    $('rncMIMake').removeClassName('invisible');
                }
                ATC.cs.research.mi.nml.showPopup();
                $('rncMIMake').addClassName('invisible');
            } else {
                ATC.cs.research.mi.nml.hidePopup();
                $('rncMIMake').removeClassName('invisible');

            }
        }.bindAsEventListener(this));

        this.modelSelect.observe('change', function() {
            var model = $F(this.modelSelectId);
            if ((model != null) && (model != undefined)) {
                ATC.cs.research.mi.nml.hidePopup();
                $('rncMIMake').removeClassName('invisible');
            }
        }.bindAsEventListener(this));
    },

    toggleEventForExpand: function(value) {
        var expandLink = $('nmlExpand');
        switch (value) {
            case 'add':
                if (expandLink) {
                    expandLink.observe('click', this.showNewMakeModelsList.bindAsEventListener(this));
                }
                break;
            case 'remove':
                if (expandLink) {
                    expandLink.stopObserving('click');
                }
                break;
        }
    },

    hasNmlData: function(make) {
        this.make = make;
        for (var i = 0; i < this.numModels; i++) {
            if (this.newModels[i].make.toLowerCase() == this.make.toLowerCase()) {
                return true;
            }
        }
        return false;
    },

    getNewMakeModels: function() {
        this.showcase = new Array();
        this.numInShowcase = 0;
        for (var i = 0; i < this.numModels; i++) {
            if (this.newModels[i].make.toLowerCase() == this.make.toLowerCase()) {
                this.showcase.push(this.newModels[i]);
                this.numInShowcase++;
            }
        }
    },

    generateMakeLink: function() {
        return '/research/newmodel/index.jsp?sort_type=OEMFILTERED&make1=' + this.showcase[0].make;
    },

    showNewMakeModelsList: function() {
        var makeModelList = new Element("ul");
        this.showcase.each(function(car, i) {
            var ymm = car.year + ' ' + car.make + ' ' + car.model;
            //rdpage and ymm from java b/c we have no way here to determine if it is a flash only NMLSPNSR2CS or a carousel detail page NMLSPNSR1CS
            var linkurl = car.link; //+"?year="+car.year + "&make=" + car.make + "&model=" + car.model + "&rdpage="+(car.link.indexOf("newmodel/index.jsp")!=-1?"NMLSPNSR1CS":"");
            var tmpLink = new Element("a", {href: linkurl}).update(ymm);
            makeModelList.insert({bottom: new Element("li").update(tmpLink)});
        });
        var makeLink = this.generateMakeLink();
        var makeText = 'View all the new models coming soon from ' + this.showcase[0].make;
        var allLink = new Element('p').insert(new Element('a', {'class': 'link', href: makeLink}).update(makeText));
        $('nmlExpand').toggleClassName('link').update('Select a car from the New Model Showcase');
        this.toggleEventForExpand('remove');
        $('nmlOr').remove();
        $(this.options.popId).down('.content').insert(makeModelList);
        $(this.options.popId).down('.content').insert(allLink);
    },

    submitButtonStatus: function(value) {
        var submitButton = $(this.submitButton);
        if (!submitButton) {
            return;
        }
        switch (value) {
            case 'enable':
                submitButton.up(2).className = 'atc-button';
                submitButton.enable();
                submitButton.setStyle({cursor: 'pointer'});
                break;
            case 'disable':
                submitButton.up(2).className = 'atc-button-disabled';
                submitButton.disable();
                submitButton.setStyle({cursor: 'default'});
                break;
        }
    },

    formElementStatus: function(value) {
        var element = this.ieElementToHide;
        if (!element) {
            return;
        }
        switch (value) {
            case 'hide':
                $(element).setStyle({visibility: 'hidden'});
                break;
            case 'show':
                $(element).setStyle({visibility: 'visible'});
                break;
        }
    },

    showPopup: function() {
        this.formElementStatus('hide');
        this.submitButtonStatus('disable');
        this.getNewMakeModels();

        var orP = new Element("p", {id: 'nmlOr', 'class': 'or'}).update("or");
        var vehicles = (this.numInShowcase == 1) ? 'vehicle' : 'vehicles';
        var expandCopy = 'Expand to see ' + this.numInShowcase + ' ' + vehicles + ' coming soon from ' + this.make + ' in the New Model Showcase';
        var expandLink = new Element('p', {id: 'nmlExpand', 'class': 'heading link'}).insert(new Element('a', {'class': 'link', href: 'javascript:void(\'0\')'}).update(expandCopy));

        var popTop = new Element('div', {'class': 'corners top'});
        var popContent = new Element('div', {'class': 'content clearfix'}).insert(this.modelDiv.remove()).insert(orP).insert(expandLink);
        var popBottom = new Element('div', {'class': 'corners bottom'});
        var popupBox = new Element("div", {id: this.options.popId}).insert(popTop).insert(popContent).insert(popBottom);
        $(this.popInsertionPoint).insert({bottom: popupBox});
        popupBox.clonePosition($(this.popInsertionPoint), {setWidth: false, setHeight: false, setLeft: false});
        new Effect.Appear(popupBox, {duration: 0.2, fps: 50, from: 0.0, to: 1.0});
        this.toggleEventForExpand('add');
    },

    hidePopup: function() {
        this.formElementStatus('show');
        this.submitButtonStatus('enable');
        this.toggleEventForExpand('remove');
        this.makeDiv.insert({after: this.modelDiv.remove()});
        var popId = $(this.options.popId);
        if (popId) {
            popId.remove();
        }
    }

});