/*
 * TODO
 * * Add rounded corners
 * * Add arrows to link targets
 * * create deployment steps and documentation
 *
 * Requires the following libraries:
 * jQuery 1.2.6+ (should automatically be loaded on websites platform)
 *
 * Usage:
 * Load an array of car objects as defined in the imageList.js.
 * e.g.:
 * jQuery(document).ready(function() {
 *      displayRandomImage.init(arrAtlasImageList,'randomImage');
 * });

 */

/* Cookie Functions */
function irCookie(strCookieName,strCookieValue,oCookieExpiration,strCookieDomain) {
    this.strCookie = null;
    this.cookieName = strCookieName;
    this.cookieValue = strCookieValue;
    this.cookieExpiration = oCookieExpiration;
    this.cookieDomain = strCookieDomain;
}

irCookie.prototype.create = function(strCookieName,strCookieValue,oCookieExpiration,strCookieDomain) {
    //create cookie
    this.strCookie = strCookieName + "=" + encodeURIComponent(strCookieValue);
    if (oCookieExpiration) {
        this.strCookie += "; expires=" + oCookieExpiration.toGMTString();
    }
    if (strCookieDomain) {
        this.strCookie += "; domain=" + strCookieDomain;
    }
    document.cookie = this.strCookie;
}

irCookie.prototype.destroy = function(strCookieName) {
    //delete cookie
    this.create(strCookieName, "", new Date(Date.parse("September 3, 1981")));
}

irCookie.prototype.get = function(strCookieName) {
    //get cookie
    var sRE = "(?:; )?" + strCookieName + "=([^;]*);?";
    var oRE = new RegExp(sRE);

    if (oRE.test(document.cookie)) {
        return decodeURIComponent(RegExp["$1"]);
    } else {
        return null;
    }
}

/* A Single function, not designed to be instantiated into multiple objects */

var displayRandomImage = {
    // Default Configuration
    currentImageIndex       : 0,
    outputElement           : null,
    promoIndex              : null,
    imageList               : [],
    constructedMarkup       : null,

    promoOverride: function() {
        // Load cookie code
        var firstTimeVisitor = new irCookie('firstTimeAtlasVisitor'),
            promoOptOut = true,
            myDate = new Date(),
            self = this,
            promoTitles= jQuery.map(this.imageList, function(i){
                return (i.imageType === "promo") ? i.imageTitle : null;
            });

        // If no cookie && promo has been detected, set cookie and return true
        if ((firstTimeVisitor.get('firstTimeAtlasVisitor') !== 'no') && (this.promoIndex !== null)) {
            // set cookie to expire in 24 hours
            myDate.setDate(myDate.getDate() + 1);
            firstTimeVisitor.create('firstTimeAtlasVisitor', 'no', myDate);

            return true;
        } else {
            return false;
        }
    },
    setPromoIndex: function() {
        var self = this;

        // loop through array searching for the first promo
        jQuery.each(this.imageList, function(index, imageObj) {
            if (imageObj.imageType === 'promo') {
                self.promoIndex = index;
                return false;
            }
        });
    },
    setIndex: function() {
        if(this.promoOverride() === true) {
            // force promo display
            this.currentImageIndex = this.promoIndex;
        } else {
            // randomize Index
            this.currentImageIndex = Math.floor(Math.random() * this.imageList.length);
        }
    },
    constructMarkup: function() {

        // construct parent div
        var currImg = this.imageList[this.currentImageIndex],
            elImage = jQuery('<img/>')
//                .css({
//                  'position': 'absolute',
//                  'top': 0,
//                  'left': 0
//                })
                .attr('src', currImg.imageSrc)
                .attr('alt', currImg.imageName),
            elWrapper = jQuery('<div id="imageRandomizerWrapper"/>').append(elImage);

        // construct links
        jQuery.each(this.imageList[this.currentImageIndex].CTA, function(index, ctaObj) {
            var elSpan = jQuery('<span/>').addClass('link').css({
                    'top': ctaObj.ctaPositionY + 'px',
                    'left': ctaObj.ctaPositionX + 'px'
                }),
                elAnchor = jQuery('<a/>').html(ctaObj.ctaTitle)
                    .attr('href', ctaObj.ctaURL)
                    .attr('title', ctaObj.ctaTitle)
                    .css({
                        'width': ctaObj.ctaWidth + 'px',
                        'height': ctaObj.ctaHeight + 'px'
                    });

            if (ctaObj.ctaURLTarget !== undefined) {
                elAnchor.attr('target', ctaObj.ctaURLTarget);
            }

            if (ctaObj.pixelTagHook === true) {
                elAnchor.addClass('isTaggable');
            }

            // Attach Anchor to Span then to Div
            elWrapper.append(elSpan.append(elAnchor));
        });

        this.constructedMarkup = elWrapper;
    },
    displayImage: function() {
        // append new dom object to outputElement
        var outEl = jQuery('#'+this.outputElement).html('');

        if (typeof this.constructedMarkup === "string") {
            outEl.html(this.constructedMarkup);
        } else {
            outEl.append(this.constructedMarkup);
        }
    },
    init: function(arrImageList, targetElement) {
        // get current active OEM promotions
        var promos = jQuery.map(jQuery.makeArray(ContextManager.getPromotions()), function(promo, p){
            return promo.title;
        });

        // set object variables
        this.outputElement = targetElement;
        this.imageList = jQuery.map(jQuery.makeArray(arrImageList), function(image, i){
            if (image.imageType !== "promo") {
                // include all newModels
                return image;
            } else {
                // filter promos to only include opt-in (active) ones
                var include = false;
                jQuery.each(promos, function(p, promo){
                    if (image.imageTitle === promo) {
                        include = true;
                    }

                    return (include !== true); // break out of loop if active
                });

                return (include === true) ? image : null;
            }
        });

        // go
        this.setPromoIndex();
        this.setIndex();
        this.constructMarkup();
        this.displayImage();
    }
};
