/**
 * spotlight.js
 * @name Spotlght
 * @fileoverview Provides Spotilght ad data for the Compare Tool
 * @requires Prototype version 1.6.0 or greater
*/

// TODO: Please, please, please make this go away
// is should be incorporated into the spotlight object, and reference the "this" pointer, bound to "this".
//
ATC.cs.research.ctr.globArrayCars = [];
ATC.cs.research.ctr.globArrayOwners = [];
ATC.cs.research.ctr.globArraySpecials = [];
/**
 * Compare Tool Spotlight class
 * @author AutoTrader.com
 */
var Spotlight = Class.create({

    cdList: "",
    cdZip: "",
    waitForSpotlights: 0,

    /**
     * Constructor.
     * @constructor
     * @throws exception if Prototype 1.6.0 or greater is not loaded.
     */
    initialize:function (options) {
        this.options = options || {};
        this.checkVersion();
        this.waitForSpotlights = 0;
    },

    checkVersion:function () {
        // Make sure Prototype is included.
        var exception = "SpotlightArray 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);
        }
    },

    /**
    * Query for Spotlight ads
    * If page has an OCID, return. You shall not pass
    * If modelIds on page < 2 fyc url is constructed and return
    * If modelIds >= 2 spotlights url is constructed and call is made for spotlight data
    * @param modelArray is an array of modelIds from cars currently populating the columns
    */
    queryAds:function(modelArray){
        var ns = ATC.cs.research.ctr;
        var target = 'spotlights';
        var url = ns.url;
        var zip = ns.model.getZIP();

        // clear the old spotlights
         $(target).update('');
        if((ns.model.isOEM()) || (modelArray.length<2)) {
            this.getSpotlightUrl('fyc');
            return;
        }
        else if (!modelArray) {
            this.getSpotlightUrl('fyc');
            $(target).update('');
            return;
        }
        else {
            this.getSpotlightUrl('spotlight');
        }

        // get the data, send to evaluateSpotlights
        var urlGetSpotlights = '/ac-servlets/research/compare/ctr/getSpotlightAds?zip='+zip+'&modelIds='+modelArray;
        var options = {method:'get', onComplete: function(responseText) { ns.spotlight.evaluateSpotlights(responseText)}};
        new Ajax.Request(urlGetSpotlights, options);
    },

    // Get spotlight url data
    getSpotlightUrl:function(type){
        var ns = ATC.cs.research.ctr;
        var zip = ns.model.getZIP();
        var distance = $('distance').value;
        var makeArray = ns.controller.getMakes();
        var modelArray = ns.controller.getModels();
        var modelIdArray = ns.controller.getModelIds();
        var yearArray = ns.controller.getYears();
        ns.spotlight.updateSpotlightUrl(type, zip, distance, makeArray, modelArray, modelIdArray, yearArray);
    },

    // Update View More Listings link according to data
    updateSpotlightUrl:function(type, zip, distance, makeArray, modelArray, modelIdArray, yearArray){
        var target = $('view-more-listings');
        var models = '';
        distance = '&distance='+distance;

        // process type of url, point to fyc or spotlights
        switch(type) {
            case 'fyc':
                viewAllPrefix = '/fyc/searchresults.jsp?num_records=25&search_type=both&default_sort=priceDESC&address=';
                viewAllTarget = 'fyc';
                viewAllText = 'View Local Listings';
                break;
            case 'spotlight':
                viewAllPrefix = '/research/compare/spotlights.jsp?page=1&address=';
                viewAllTarget = 'spotlights';
                viewAllText = 'View more listings';
                break;
        }

        var year = '&start_year='+((typeof(yearArray.min()) != 'undefined') ? yearArray.min():'')+'&end_year='+((typeof(yearArray.max()) != 'undefined') ? yearArray.max():'');
        for(var i=0; i<modelIdArray.length; i++) {
            models += '&model_id='+modelIdArray[i]+'&make'+(i+1)+'_desc='+makeArray[i]+'&model'+(i+1)+'_desc='+modelArray[i];
        }
        // construct the url
        var viewAllUrl = viewAllPrefix + zip + year + distance + models;
        target.writeAttribute('href', viewAllUrl);
        target.update(viewAllText);
    },

   spotlightLinkChecker:function(what) {
        if (what > 0) {
            if (this.waitForSpotlights == 0) {
                setTimeout("ATC.cs.research.ctr.spotlight.spotlightLinkChecker(-1)", 5000);
            }
            this.waitForSpotlights += what;
            if (this.waitForSpotlights > 3) { this.waitForSpotlights = 3; }
        } else if (what < 0) {
            this.waitForSpotlights += what;
            if (this.waitForSpotlights > 0) {
                setTimeout("ATC.cs.research.ctr.spotlight.spotlightLinkChecker(-1)", 5000);
            } else {
                this.waitForSpotlights = 0;
                // Check spotlight link
                var target = $('view-more-listings');
                var hf = target.href;
                var spotAds = $('spot-ads');
                if (spotAds.style.display == "none") { // Fire no events if spot ad hidden
                } else {
                    if (hf.indexOf("/fyc/searchresults.jsp") > 0) { // If link points to FYC then no spotlights
                        ATC.utils.BIUtils.getBIEvent('e10ax');
                    } else if (this.cdList != "") { // If link points to spotlight and there are sponsored vehicles
                        ATC.utils.BIUtils.getBIEvent("e2","cdlist:"+this.cdList,"zip:"+this.cdZip);
                    }
                }
            }
        }
    },

    formatPriceFunction:function(nStr){
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1)) {
           x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },

    // Evaluate queryAds response, send url to updateSpotlightUrl if no Spotlights
    evaluateSpotlights:function(spotlightObject){
        var spotlightArray = spotlightObject.responseText.evalJSON();
        var spotlightLength = spotlightArray.length;
        var zip = ATC.cs.research.ctr.model.getZIP();
        var cdL = "";
        var cIds = [];
        this.cdZip = zip;
        if(spotlightArray.length==0) {
            this.getSpotlightUrl('fyc');
            return;
        }
        else {
            this.getSpotlightUrl('spotlight');
        }
        var spotlightTemplate = new Template("<div id='#{tileId}' class='spotlight-tile column'><div class='top clearfix'><div class='photo'><a href='#{redirectUrl}/fyc/vdp.jsp?car_id=#{carId}'><img src='#{photoUrl}' width='118' height='88' alt='image' title='#{yearMakeModelTrim}'/></a></div><div class='car-info'><div class='dealer'>#{dealerName}</div><div class='ymm'><a href='#{redirectUrl}/fyc/vdp.jsp?car_id=#{carId}'>#{yearMakeModelTrim}</a></div><div class='certified'>#{certifiedTile}</div></div></div><div class='bottom clearfix'><div class='car-financial'><div class='price'>$#{price}</div>#{vehicleSpecial}#{privateSeller}#{newlyListed}#{reduced}</div><div class='car-info'><div class='mileage'>Mileage: #{mileage}</div><div class='selling-point'>#{customText}</div></div></div></div>");
        var target = $('spotlights');
        // clear target div again in case prior Ajax calls have tried to render
        target.update('');

        for(var x=0; x<spotlightLength; x++) {
            var el = spotlightArray[x];
            ATC.cs.research.ctr.globArrayCars.push( "&car_id="+el.carId ) ;
            ATC.cs.research.ctr.globArrayOwners.push( "dealer_id="+el.ownerid ) ;
            ATC.cs.research.ctr.globArraySpecials.push( "&special_id="+el.specialIds[0] ) ;
            cdL += "&c"+(x+1)+"="+el.carId+"&d"+(x+1)+"="+el.ownerid;
            var spotlightNVS = 'spotlight-nvs-'+x;
            if (!el.customText || (el.customText == null)) {
                el.customText = '<div class="selling-point">'+el.customText+'</div>';
            } else {
                el.customText = '';
            }
            if (!el.reduced || (el.reduced == null)) {
                el.reduced = '';
            } else {
                el.reduced = '<div class="pdvi">Reduced</div>';
            }
            if (!el.newlyListed || el.reduced) {
                el.newlyListed = '';
            } else {
                el.newlyListed = '<div class="newly-listed"><img src="/img/research/compare/newly-listed.jpg" alt="image" title="Newly Listed"/></div>';
            }
            if (!el.mileage || (el.mileage == null)) {
                el.mileage = 'Not listed';
            }

            el.price = (!el.price || (el.price == null))
                    ? '$ Unlisted' : this.formatPriceFunction(el.price);

            if (!el.privateSeller || (el.privateSeller == null)) {
                el.privateSeller = '';
            } else {
                el.privateSeller = '<div class="private-seller"><img src="/img/fyc/spotlight/forsale.jpg" alt="image" title="Private Seller"/></div>';
            }
            if (!el.vehicleSpecial) {
                vehicleSpecial = '';
            } else {
                vehicleSpecial = '<div id='+spotlightNVS+' class="specials"><img src="/img/research/compare/specials.jpg" alt="image" title="View Specials" /></div>';
            }

            // NVS related items used in the Prototip function below
            var seeDetailsOfSpecial = "";
            var seeAllSpecials = '/nvs/dealer_specials.jsp?dealer_id='+el.ownerid+'&special_id='+el.specialIds[0]+'&rdpage=FYC+Spotlight+Ads';

            var signUpForVS = '/myatc/my_alerts.xhtml?isNL=true&dealer_id='+el.ownerid+'&rdpage=FYC+Spotlight+Ads';
            var signUpForVSClick = 'return MIS.Redirect(this.href, \"GVSPPULNNS1065\", false);';

            //Setting values for template items
            var values = {
                iteration : x,
                tileId : 'spotlight-tile-'+x,
                nvsId : spotlightNVS,
                carId : el.carId,
                certifiedTile : el.certifiedTile,
                customText : el.customText,
                dealerName : el.dealerName,
                mileage : el.mileage,
                newlyListed : el.newlyListed,
                ownerid : el.ownerid,
                photoUrl: el.photoUrl,
                price : el.price,
                privateSeller : el.privateSeller,
                reduced : el.reduced,
                redirectUrl : '/redirect/redirector_link.jsp?to_url=',
                specialIds : el.specialIds,
                vehicleSpecial : vehicleSpecial,
                year : [el.year],
                yearMakeModelTrim : el.yearMakeModelTrim
            };

            var evaluatedTemplate = spotlightTemplate.evaluate(values);
            target.insert(evaluatedTemplate);

            // After inserting template, if we have a special attach new Prototip
            if (el.vehicleSpecial) {
                if (el.specialIds.size() > 1) {
                   $(spotlightNVS).observe('click',handleMultiSpecialSpotlightRedirect);
                }  else {
                  $(spotlightNVS).observe('click',handleSingleSpecialSpotlightRedirect);
                }
            }
        };
        this.cdList = cdL;
        this.spotlightLinkChecker(1);
    }
}) ;

function handleMultiSpecialSpotlightRedirect(e) {
   var tag = e.element().up().id;
   var index = parseInt(tag.split("-")[2]);
   MIS.Redirect('/fyc/view_vehicle_offers.jsp?'+ATC.cs.research.ctr.globArrayOwners[index]+ATC.cs.research.ctr.globArrayCars[index]+'&rdpage=FYC+Spotlight+Ads', "GVSPPULNNS972&rdpage=FYC+Spotlight+Ads"+ATC.cs.research.ctr.globArrayCars[index], true, Array("height=800", "width=800"));
}
function handleSingleSpecialSpotlightRedirect (e) {
  var tag = e.element().up().id;
  var index = parseInt(tag.split("-")[2]);
  MIS.Redirect('/nvs/nvs_detail.jsp?'+ATC.cs.research.ctr.globArrayOwners[index]+ATC.cs.research.ctr.globArraySpecials[index]+ATC.cs.research.ctr.globArrayCars[index]+'&rdpage=FYC+Spotlight+Ads', "GVSPPULNNS972&rdpage=FYC+Spotlight+Ads"+ATC.cs.research.ctr.globArrayCars[index], true, Array("height=800", "width=800"));
}

// Create an instance.
ATC.cs.research.ctr.spotlight = new Spotlight();
