﻿/*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(timeout_hoistAds($(this)));
        },*/
        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");
        },
        getTags: function () {
            if (!pageScanned) {
                scanPage();
                history.sort(sortHistory);
                pageScanned = true;
            }
            return history;
        },
        getAdContent: function (id) {
            var tempTile = $("#temp" + id),
                src = tempTile.children("script:first").attr("src"),
                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;
        },
        hoist: function (id) {
                //$("#" + id).hide();
            /*setTimeout(function() {
            
            }, 20);*/
            $("#" + id).empty().append(MediaMotive.getAdContent(id)).removeClass('doubleclick-preload').hide().show();
        }
    };
} (jQuery));
