/*
 * Designed for use with the R&C Impressions / CarZen
 * @author Chris Keen <chris . keen at autotrader>
 * @requires Prototype.js >= 1.6.0.2
 */

//temporary fix until we update the Ads namesapce in global.js, with the backend changes to get Iframes by ID
function expandSuperLinerContainer(index){
    Ads.expandAd(index);
}

var ad = null,
    carzenBI = null,
    initCarZen = function(){
        ad = new AdHandler('carAdvisorMain');
        ad2 = new AdHandler('carAdvisorExtra');
        ad3 = new AdHandler('footer1x1');
        carzenBI = new CarZenBI();
        zipHandler = new cookieZipHandler();
    };

    document.observe("dom:loaded",initCarZen);

/**
 * method for CarZen's state change.  This is how we know when to update the ad, and with what data.
 * @param CarZenJSON - the JSON object from CarZen that needs to be sent to our server to translate
 */
function autotraderStateChange(CarZenJSON){
    ad.preprocessAdTagRequest(CarZenJSON);
    ad2.preprocessAdTagRequest(CarZenJSON);
    ad3.preprocessAdTagRequest(CarZenJSON);
    carzenBI.logStateChange(CarZenJSON);
    zipHandler.updateZip(CarZenJSON.zip_code);
}

var cookieZipHandler = Class.create({
    initialize: function(){
        this.cookieName = "USER";
        this.cookieKey = "zip";
        this.prependChar = "&";
        this.pairSeperator = "=";
    },

    /**
    * updates the cookie associated with this class with a new zipcode= value.
    * @param zip - int - the new zip to store in the cookie.
    */
    updateZip: function(zip){
        //console.log("new zip: ",this.zipChanged(zip));
        if (this.zipChanged(zip)){
            var keyString = this.prependChar + this.cookieKey + this.pairSeperator + zip;
            setCookie(this.cookieName,keyString);
            //console.log("getting cookie val after update: ",getCookieKey(this.cookieName,this.cookieKey));
        }
    },

    /**
    * checks if the zip passed by carzen is the same at the one we have stored in the User cookie...
    * @param newZip - int - number representing the new zip code from carzen
    * @return boolean - true if the new zip does not match
    */
    zipChanged: function(newZip){
        return getCookieKey(this.cookieName,this.cookieKey) != newZip;
    }
});

var CarZenBI = Class.create({
    /**
     * constructor
     */
    initialize: function(options){
        this.options = this._extendOptions(options);
        //this.checkCarZenDown();
    },

    /**
     * sets defaults and extends them for use with Prototype
     * @param options - the object literal of properties to set defaults for / override
     */
    _extendOptions: function(options){
        return Object.extend({
            requestURI: 'http://staging.carzen.com/flash/img/thumbs/sedan.jpg',
            carZenDownAsis: '/no_cache/ac/carzen_notavailable.asis',
            stateChangeAsis: '/no_cache/ac/carzen_impress.asis'
        }, options || {});
    },

    /**
     * helper creates and returns BI QueryString
     * @param JSON - JSON Object from CarZen to parse through for BI values
     * @return queryString the GET parameters to be written to the log
     */
    getBIQueryString: function(JSON){
        var queryString  = "?rdpage=" + JSON.location;
        queryString += "&foundcar="   + JSON.visibleVehicles;
        queryString += "&address="    + JSON.zip_code;
        queryString += "&min_price="  + this.formatATCPrice(JSON.min_price_cents);
        queryString += "&max_price="  + this.formatATCPrice(JSON.max_price_cents);
        queryString += "&styleId="    + JSON.chrome_style_id;

        return queryString;
    },

    /**
     * helper returns the price in dollars, or returns the empty string;
     * @param priceInCents - integer representation of currency in cents
     * @return priceInDollars - integer representation of currency in dollars
     */
    formatATCPrice: function(priceInCents){
        return null == priceInCents ? "" : priceInCents.substring(0,priceInCents.length-2);
    },

    /**
     * makes a request to carzen's server using the img JS object and checks to see if we get a 200 (OK) response.  If not, log a BI tag.
     */
    checkCarZenDown: function(){
        //TODO: this and AJAX are not working yet.  Possibly because of XSS.  We need to revise this strategy with the product owner.
        var img = new Image();
        //img.onerror = this.sendCarZenDownTag();
        img.src = this.options.requestURI;
    },

    /**
     * sends a message to the server logs when CarZen's servers are down.
     */
    sendCarZenDownTag: function(){
        asis(this.options.carZenDownAsis);
    },

    /**
     * writes the state changes to the server logs for BI reporting
     * @param JSON - JSON Object from CarZen to parse through for BI values
     */
    logStateChange: function(JSON){
        asis(this.options.stateChangeAsis + this.getBIQueryString(JSON));
    }

});