/*
 * Designed for use with the R&C Impressions / CarZen
 * @author Chris Keen <chris . keen at autotrader>
 * @requires Prototype.js >= 1.6.0.2
 */
var AdHandler = Class.create({
    //TODO: cache or hold ads for 10 seconds - either show for time limit then iterate through, or each ad shows for time and then allows update.

    /**
     * constructor
     * @param iframeId - ID of the container
     * @param options - array of options to be applied to this object as properties
     */
    initialize: function(iframeId,options) {
        this.iframe = $(iframeId);
        this.adURI = this.getAdServingURI();
        this.adTagRequest = this.getAdTagRequest();
        this.options = this._extendOptions(options);
    },

    /**
     * getter for iframe's src attribute
     * @return String representing the URI of the iframe's src
     */
    getAdServingURI: function(){
        return this.iframe.getAttribute("src");
    },

    /**
     * getter for iframe's custom adtagrequest attribute
     * @return String representing the adtagrequest
     */
    getAdTagRequest: function(){
        return this.iframe.getAttribute("adtagrequest");
    },

    /**
     * refreshes the iframe by setting the src attribute - even if the src is the same, the iframe refreshes because it has received a change
     */
    refreshAd: function(){
        this.iframe.setAttribute("src",this.adURI);
    },

    /**
     * makes an AJAX request to the servlet specified in options and parses the raw data into a usable adtagrequest attribute for the iframe
     * @param serverParams - the value to pass for parameters in AJAX.Request - in the default case the JSON object from CarZen
     */
    getNewAdTagRequest: function(serverParams){
        new Ajax.Request(this.options.ajaxRequestURI,{
            parameters: serverParams,
            onSuccess: this.updateAdTagRequest.bind(this),
            onFailure:  this._updateFailed.bind(this)
        });
    },

    /**
     * CarZen specific method used to merge the existing adTagRequest into the JSON object
     * @param serverParams - the JSON data to send as a param to the servlet - in the default case the JSON object from CarZen
     */
    preprocessAdTagRequest: function(serverParams){
        var bodyStyles = "", adTagRequest = this.getAdTagRequest(), ATCParams = null;
        for (i=0, loopCounter = serverParams.segments.length; i<loopCounter; i++){
            bodyStyles += i == 0 ? "" : ",";
            bodyStyles += serverParams.segments[i];
        }
        ATCParams = $H(serverParams).merge({segments: bodyStyles, adtagrequest: adTagRequest});
        this.getNewAdTagRequest(ATCParams.toQueryString());
    },

    /**
     * writes out the new adtagrequest param and refreshes the ad
     * if the object is set to use AJAX, it will retreive the response text and use that, versus the string literal of adTagRequestString
     * @param adTagRequestString - the string value for the adtagrequest HTML attribute returned from the servlet
     */
    updateAdTagRequest: function(adTagRequestString){
        var adtagrequest = this.options.useAJAX ? adTagRequestString.responseText : adTagRequestString;
        if (adtagrequest != this.getAdTagRequest()){
            this.iframe.setAttribute("adtagrequest",adtagrequest);
            this.refreshAd();
        }
    },

    /**
     * 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({
            ajaxRequestURI: '/ac-servlets/CarZenTransform/',
            useAJAX: true
        }, options || {});
    },

    /**
     * helper method to handle AJAX failures - log the issue w/o alerting the EU
     */
    _updateFailed: function(){
        logCall("&AJAXError=There was an problem calling " + this.options.ajaxRequestURI + " on " + window.location.href);
        //TODO: possibly retry the request X# more times?
    }
});