﻿/*global jQuery */
/*jslint undef: true, browser: true */

var MediaMotive = (function ($) {
    "use strict";
    var history = [],
        pageScanned = false,
    // Private method to scan for ads that were written to the page without delay-loading
        scanPage = function () {
            $("div[id^=Tile]:has(script),div[id^=tempTile]:not([data-is-hoisted])").each(function () {
                var div = $(this), id = div.attr("id").replace("temp", ""), src = div.children("script:first").attr("src");
                history.push({ id: id, src: src, isHoisted: false });
            });
        },
        sortHistory = function (a, b) {
            // strip the ID of text just to get the number to compare
            var c = parseInt(a.id.replace(/\D+/, ""), 10),
                d = parseInt(b.id.replace(/\D+/, ""), 10);
            return c > d ? 1 : (c < d ? -1 : 0);
        };

    return {
        showHistory: function () {
            // this shows what ads have been generated on the page
            var i = 0, count = 0, s = [], m;

            if (!pageScanned) {
                scanPage();
                history.sort(sortHistory);
                pageScanned = true;
            }
            count = history.length;

            while (i < count) {
                m = history[i].src.match(/^(\S+)\/adj\/(\S+)$/);
                s.push("'" + history[i].id + "': tags='" + m[2] + "', hoisted='" + (history[i].isHoisted ? "yes" : "no") + "'");
                i += 1;
            }
            return s.join("\r\n");
        },
        getAds: function () {
            var i;
            if (!pageScanned) {
                scanPage();
                history.sort(sortHistory);
                pageScanned = true;
            }
            for (i = history.length - 1; i >= 0; i -= 1) {
                if (!history[i].container) {
                    history[i].container = $('#' + history[i].id);
                }
            }
            return history;
        },
        getAdContent: function (id) {
            var tempTile = $("#temp" + id),
                src = tempTile.children("script:first").attr("src"),
                elements;

            if (src.indexOf(";sz=1x1") === -1) {
                elements = tempTile.children(":not(script)").find("script").remove().end();
                tempTile.attr("data-is-hoisted", "true");
                history.push({ id: id, src: src, isHoisted: true });
                return elements;
            }
            return "";
        },
        hoist: function (id) {
            $("#" + id).empty().append(this.getAdContent(id)).removeClass('csn-doubleclick-preload');
        }
    };
} (jQuery));
