/////////////// COMPARE 4 functionality ///////////////////    
/**
 * CompareBuffer.js
 * @name CompareBuffer
 * @fileoverview Provides compare buffer functionality and interaction for MI tiles pages and model-selection-set.jsp
 * @requires ATC.js, prototype.js version 1.6.0 or greater
*/

//---------------------------------------------------------------------------------------------------------------------
/**
 * Compare Buffer data population
 * @class CB
 * @author Dennis Sarvis, extended from initial version
 * @example
 * Usage examples:
 * === Initialize
 * var micb = new CB();
 * === Examples of how to lookup the styleId returning a style object that will call the populate a column function:
 * var a = micb.addToCompare(null, 0, style.styleId, style.year, style.make, style.model, img);
 *
 *
 */
//var CB = Class.create();
    var compareList = new Array();
    var tempCompareList = null;
var CB;
    function initCompareBuffer() {
        CB = new ATC.cs.research.mi.CompareBuffer();
    }
//---------------------------------------------------------------------------------------------------------------------
// Create namespace for the class
ATC.createNamespace('ATC.cs.research.mi');
//---------------------------------------------------------------------------------------------------------------------
// Class CompareBuffer
ATC.cs.research.mi.CompareBuffer = function() {
    this.initialize();
    this.initEventHandlers();
};
    /**
     * initializes event handlers.
     */
ATC.cs.research.mi.CompareBuffer.prototype.initEventHandlers = function() {
    
}

//---------------------------------------------------------------------------------------------------------------------
    /**
     * Constructor.
     * @throws exception if Prototype 1.6.0 or greater is not loaded.
     */
ATC.cs.research.mi.CompareBuffer.prototype.initialize = function () {
        // Make sure Prototype is included.
        var exception = "CB requires Prototype version 1.6.0 or greater.";
        if(typeof Prototype == "undefined")
        {
            throw(exception);
        }
        // Make sure it is version 1.6.0 or greater.
        var ver = Prototype.Version.split(".");
        var major = ver[0];
        var minor = ver[1];
        if(major < 1)
        {
            throw(exception);
        }
        if(minor < 6)
        {
            throw(exception);
        }
    //class variables
    //this.compareList = new Array();
    //this.tempCompareList = null;
};


//TODO, see if wrapper function is needed to add car to buffer from compare tool
ATC.cs.research.mi.CompareBuffer.prototype.addStyleToCompare = function(style) {
        if (style.pictures != null && style.pictures[0] != null) {
            var img =  style.pictures[0].fileName;
        } else {
            var img = '';
        }
    //addToCompare(null, null, style.styleId, style.year, style.make, style.model, img);
    ATC.cs.research.mi.CompareBuffer.prototype.addToCompare(null, 0, style.styleId, style.year, style.make, style.model, img);
};

ATC.cs.research.mi.CompareBuffer.prototype.addToCompare = function(element, tileId, styleId, year, make, model, imgUrl) {
        var cb = $("checkbox_" + tileId);
        //changed to 4 cars
        //run buffer validator
        if (ATC.cs.research.mi.CompareBuffer.prototype.validateCompareList(tileId)) {
            if (element == null || element.checked) {
                //add car to compare4
                compareList.push({'tileId':tileId,'styleId':styleId,'year':year,'make':make,'model':model,'imgUrl':imgUrl});
            } else {
                //remove car from compare4
                tempCompareList = Array();
                compareList.each( function(car) {
                    if (car['tileId'] != tileId) {
                        tempCompareList.push(car);
                    }
                });

                compareList = tempCompareList;
                tempCompareList = null;
            }
            ATC.cs.research.mi.CompareBuffer.prototype.buildCompareList(compareList);
            //callback?
            ATC.cs.research.mi.CompareBuffer.prototype.toggleCompareButton();

        //TODO find out why highlight is not firing
        if (compareList.length > 0) {
            var theOne = compareList.length - 1;
        } else {
            var theOne = compareList.length;
        }
        $('compare_' + theOne).highlight({startcolor:'#ff6600', endcolor:'#ffffff', duration: 1.5});

        }
    };

ATC.cs.research.mi.CompareBuffer.prototype.removeFromCompare = function(id) {
        var checkbox_id = compareList[id]['tileId']
        var cb = $("checkbox_" + checkbox_id);
        if(cb != undefined && cb!=null){
            $("checkbox_" + checkbox_id).checked = false;
        }
        compareList.splice(id, 1);
        ATC.cs.research.mi.CompareBuffer.prototype.buildCompareList(compareList);
        ATC.cs.research.mi.CompareBuffer.prototype.toggleCompareButton();
    };

ATC.cs.research.mi.CompareBuffer.prototype.removeAllStyles = function() {
    for(var i = compareList.length-1; i>=0; i--){
        ATC.cs.research.mi.CompareBuffer.prototype.removeFromCompare(i);
    }
};

ATC.cs.research.mi.CompareBuffer.prototype.toggleCompareButton = function() {
        var submitButton = $("compare-button");
/*keeping logic in case this requirement changes back
        //enable button IF more than 2 cars in buffer
        if( compareList.length > 1) {//$("compareStyles").getElementsByClassName("inUse").length
            //enable button
            submitButton.disabled= false;
            submitButton.removeClassName('disabled');
        } else {
            //disable button
            submitButton.disabled= true;
            submitButton.addClassName('disabled');
        }*/

        var removeAllLink = $("remove-all");
        if( compareList.length > 0) {            //enable link
            removeAllLink.removeClassName('hidden');
        } else {            //disable link
            removeAllLink.addClassName('hidden');
        }
    };

ATC.cs.research.mi.CompareBuffer.prototype.validateCompareList = function(tileId) {
        var cb = $("checkbox_" + tileId);
        //limit selection to 4 vehicles
        if (compareList.length == 4 && cb != null && cb.checked) {
            alert("You cannot select more than 4 vehicles to compare at once.");
            $("checkbox_" + tileId).checked = false;
            //invalid
            return false;

        } else {
            //valid
            return true;
        }
    };

ATC.cs.research.mi.CompareBuffer.prototype.buildCompareList = function(compareList) {
        compareList.each( function(car, i)  {
            $("year_compare_" + i).update( car['year'] );
            $("make_compare_" + i).update( car['make'] );
            $("model_compare_" + i).update( car['model'] );
            if(car['imgUrl'] != '' && car['imgUrl'] != 'null'){
                $("imgurl_compare_" + i).src = "http://images.autotrader.com/scaler/50/32/" + car['imgUrl'];
                $("imgurl_compare_" + i).alt = car['year'] + ' ' + car['make'] + ' ' + car['model'];
                $("imgurl_compare_" + i).title = car['year'] + ' ' + car['make'] + ' ' + car['model'];
            }else{
                $("imgurl_compare_" + i).src = "/img/research/shared/image_not_available_50x32.gif";
                $("imgurl_compare_" + i).alt = 'No Image Available';
                $("imgurl_compare_" + i).title = 'No Image Available';
            }
            $("vn_compare_" + i).value = car['styleId'];
            $("compare_" + i).style.display = "block";
            //TODO CTR remove link in MI and MI selection set
            $("compare_close_" + i).style.display = "block";

            $("empty_compare_" + i).style.display = "none";
        });
        for (var i = (compareList.length) ; i < 4; i++) {
            $("year_compare_" + i).update();
            $("make_compare_" + i).update();
            $("model_compare_" + i).update();
            $("imgurl_compare_" + i).src = "/img/research/mir/no_photo_50x32.gif";
                $("imgurl_compare_" + i).alt = 'Select a vehicle on the left to add here.';
                $("imgurl_compare_" + i).title = 'Select a vehicle on the left to add here.';
            $("vn_compare_" + i).value = "";
            $("compare_" + i).style.display = "none";
            //TODO CTR remove link in MI and MI selection set
            $("compare_close_" + i).style.display = "none";

            $("empty_compare_" + i).style.display = "block";
        }

        //update text
        $('number_compared').innerHTML = (compareList.length > 0?"1-":"0-") + compareList.length + " of 4";

        ATC.cs.research.mi.CompareBuffer.prototype.rememberCar(compareList);
    };

    /*
     * this stores currently selected comparable cars to cookie for
     */
ATC.cs.research.mi.CompareBuffer.prototype.rememberCar = function(compareList) {
        compareList.each( function(car, i) {
            var values = car['tileId'] + "|";
            values += car['styleId'] + "|";
            values += car['year'] + "|";
            values += car['make'] + "|";
            values += car['model'] + "|";
            values += car['imgUrl'];

            setCookie("mi_compare_" + i, values, null, null, null, null);
        });
        for (var i = (compareList.length) ; i < 4; i++) {
           setCookie("mi_compare_" + i,'',null,null,null,null);
        }
    };

    /**
     * Rebuilds compare3 box from cookie
     * (useful when user arrives at search result page by hitting back button)
     */
ATC.cs.research.mi.CompareBuffer.prototype.rebuildCompareListFromCookie = function(){
        var memory = Array();
        var limit = 0;

        for (var i = 0; i < 4; i++) {
            memory.push(getCookie("mi_compare_"+i))
        }


        for (var i = 0; i < (memory.length - limit); i++) {
            //var values = getCookie("modelinfo_compare_"+i);
            if(memory[i] != null && memory[i]!=''){
                var value = memory[i].split("|");

                    ATC.cs.research.mi.CompareBuffer.prototype.addToCompare(null, value[0], value[1], value[2], value[3], value[4], value[5]);
            }
        }

    };

ATC.cs.research.mi.CompareBuffer.prototype.validateCompare = function(){
            if(compareList.length == 0){
                alert("Please select at least one car to add to your compare list.");
                return false;
            } else {
                ATC.utils.BIUtils.getBIEvent(ATC.cs.research.mi.CompareBuffer.prototype.whichBIEvent(),CB.getVehicleNumber(1),CB.getVehicleNumber(2),CB.getVehicleNumber(3),CB.getVehicleNumber(4),CB.getVehicleYear(1),CB.getVehicleYear(2),CB.getVehicleYear(3),CB.getVehicleYear(4));
                return true;
            }
    };

ATC.cs.research.mi.CompareBuffer.prototype.validateCompareDefer = function(what){
            if(compareList.length == 0){
               //alert("Please select at least one car to add to your compare list.");
                location.href="/research/compare/index.jsp?rdpage=SUBNAV";
                return false;
            } else {
                ATC.utils.BIUtils.getBIEvent(ATC.cs.research.mi.CompareBuffer.prototype.whichBIEvent(),CB.getVehicleNumber(1),CB.getVehicleNumber(2),CB.getVehicleNumber(3),CB.getVehicleNumber(4),CB.getVehicleYear(1),CB.getVehicleYear(2),CB.getVehicleYear(3),CB.getVehicleYear(4));
                setTimeout("document.getElementById('"+what.id+"').submit()",1000);
                return false;
            }
    };
    
ATC.cs.research.mi.CompareBuffer.prototype.getYMM = function(which){
    var nameValue = "ymm"+which+":";
    if ((which >= 1) && (which <= 4)) {
        if ((compareList[which-1] != null) && (compareList[which-1] != undefined)) {
            nameValue += compareList[which-1]["year"]+"-"+compareList[which-1]["make"]+"-"+compareList[which-1]["model"];
        }
    }
    return nameValue;
};

ATC.cs.research.mi.CompareBuffer.prototype.getVehicleNumber = function(which){
    var nameValue = "vn"+which+":";
    if ((which >= 1) && (which <= 4)) {
        if ((compareList[which-1] != null) && (compareList[which-1] != undefined)) {
            nameValue += compareList[which-1]["styleId"];
        }
    }
    return nameValue;
};

ATC.cs.research.mi.CompareBuffer.prototype.getVehicleYear = function(which){
    var nameValue = "vy"+which+":";
    if ((which >= 1) && (which <= 4)) {
        if ((compareList[which-1] != null) && (compareList[which-1] != undefined)) {
            nameValue += compareList[which-1]["year"];
        }
    }
    return nameValue;
};


ATC.cs.research.mi.CompareBuffer.prototype.whichBIEvent = function(){
    var bID = document.getElementsByTagName("body")[0].id;
    if (bID == "model-selection-set") return "e10k";
    if (bID == "model-information-results-page") return "e10l";
};
