// window.madvertise_ad_params = {
//   site:'token',
//   format:'html'
// }

// temporary AdTruth JSC
adtruth = new function () {
    this.e = (new Date(2005, 0, 15)).getTimezoneOffset();
    this.f = (new Date(2005, 6, 15)).getTimezoneOffset();
    this.plugins = [];
    this.d = {
        Flash: ["ShockwaveFlash.ShockwaveFlash", function (b) {
            return b.getVariable("$version")
        }],
        Director: ["SWCtl.SWCtl", function (b) {
            return b.ShockwaveVersion("")
        }]
    };
    this.p = function (b) {
        var c;
        try {
            c = document.getElementById(b)
        } catch (d) {}
        if (c === null || typeof c === "undefined") try {
            c = document.getElementsByName(b)[0]
        } catch (e) {}
        if (c === null || typeof c === "undefined") for (var f = 0; f < document.forms.length; f++) for (var g = document.forms[f], h = 0; h < g.elements.length; h++) {
            var a = g[h];
            if (a.name === b || a.id === b) return a
        }
        return c
    };
    this.b = function (b) {
        var c = "";
        try {
            if (typeof this.c.getComponentVersion !== "undefined") c = this.c.getComponentVersion(b, "ComponentID")
        } catch (d) {
            b = d.message.length;
            b = b > 40 ? 40 : b;
            c = escape(d.message.substr(0, b))
        }
        return c
    };
    this.exec = function (b) {
        for (var c = 0; c < b.length; c++) try {
            var d = eval(b[c]);
            if (d) return d
        } catch (e) {}
        return ""
    };
    this.n = function (b) {
        var c = "";
        try {
            if (navigator.plugins && navigator.plugins.length) {
                var d = RegExp(b + ".* ([0-9._]+)");
                for (b = 0; b < navigator.plugins.length; b++) {
                    var e = d.exec(navigator.plugins[b].name);
                    if (e === null) e = d.exec(navigator.plugins[b].description);
                    if (e) c = e[1]
                }
            } else if (window.ActiveXObject && this.d[b]) try {
                var f = new ActiveXObject(this.d[b][0]);
                c = this.d[b][1](f)
            } catch (g) {
                c = ""
            }
        } catch (h) {
            c = h.message
        }
        return c
    };
    this.o = function () {
        for (var b = ["Acrobat", "Flash", "QuickTime", "Java Plug-in", "Director", "Office"], c = 0; c < b.length; c++) {
            var d = b[c];
            this.plugins[d] = this.n(d)
        }
    };
    this.g = function () {
        return Math.abs(this.e - this.f)
    };
    this.h = function () {
        return this.g() !== 0
    };
    this.i = function (b) {
        var c = Math.min(this.e, this.f);
        return this.h() && b.getTimezoneOffset() === c
    };
    this.l = function (b) {
        var c = 0;
        c = 0;
        if (this.i(b)) c = this.g();
        return c = -(b.getTimezoneOffset() + c) / 60
    };
    this.j = function (b, c, d, e) {
        if (typeof e !== "boolean") e = false;
        for (var f = true, g;
        (g = b.indexOf(c)) >= 0 && (e || f);) {
            b = b.substr(0, g) + d + b.substr(g + c.length);
            f = false
        }
        return b
    };
    this.k = function () {
        return (new Date(2005, 5, 7, 21, 33, 44, 888)).toLocaleString()
    };
    this.q = function (b) {
        var c = new Date,
            d = [function () {
                return "TF1"
            }, function () {
                return "015"
            }, function () {
                return ScriptEngineMajorVersion()
            }, function () {
                return ScriptEngineMinorVersion()
            }, function () {
                return ScriptEngineBuildVersion()
            }, function (a) {
                return a.b("{7790769C-0471-11D2-AF11-00C04FA35D02}")
            }, function (a) {
                return a.b("{89820200-ECBD-11CF-8B85-00AA005B4340}")
            }, function (a) {
                return a.b("{283807B5-2C60-11D0-A31D-00AA00B92C03}")
            }, function (a) {
                return a.b("{4F216970-C90C-11D1-B5C7-0000F8051515}")
            }, function (a) {
                return a.b("{44BBA848-CC51-11CF-AAFA-00AA00B6015C}")
            }, function (a) {
                return a.b("{9381D8F2-0288-11D0-9501-00AA00B911A5}")
            }, function (a) {
                return a.b("{4F216970-C90C-11D1-B5C7-0000F8051515}")
            }, function (a) {
                return a.b("{5A8D6EE0-3E18-11D0-821E-444553540000}")
            }, function (a) {
                return a.b("{89820200-ECBD-11CF-8B85-00AA005B4383}")
            }, function (a) {
                return a.b("{08B0E5C0-4FCB-11CF-AAA5-00401C608555}")
            }, function (a) {
                return a.b("{45EA75A0-A269-11D1-B5BF-0000F8051515}")
            }, function (a) {
                return a.b("{DE5AED00-A4BF-11D1-9948-00C04F98BBC9}")
            }, function (a) {
                return a.b("{22D6F312-B0F6-11D0-94AB-0080C74C7E95}")
            }, function (a) {
                return a.b("{44BBA842-CC51-11CF-AAFA-00AA00B6015B}")
            }, function (a) {
                return a.b("{3AF36230-A269-11D1-B5BF-0000F8051515}")
            }, function (a) {
                return a.b("{44BBA840-CC51-11CF-AAFA-00AA00B6015C}")
            }, function (a) {
                return a.b("{CC2A9BA0-3BDD-11D0-821E-444553540000}")
            }, function (a) {
                return a.b("{08B0E5C0-4FCB-11CF-AAA5-00401C608500}")
            }, function () {
                return eval("navigator.appCodeName")
            }, function () {
                return eval("navigator.appName")
            }, function () {
                return eval("navigator.appVersion")
            }, function (a) {
                return a.exec(["navigator.productSub", "navigator.appMinorVersion"])
            }, function () {
                return eval("navigator.browserLanguage")
            }, function () {
                return eval("navigator.cookieEnabled")
            }, function (a) {
                return a.exec(["navigator.oscpu", "navigator.cpuClass"])
            }, function () {
                return eval("navigator.onLine")
            }, function () {
                return eval("navigator.platform")
            }, function () {
                return eval("navigator.systemLanguage")
            }, function () {
                return eval("navigator.userAgent")
            }, function (a) {
                return a.exec(["navigator.language", "navigator.userLanguage"])
            }, function () {
                return eval("document.defaultCharset")
            }, function () {
                return eval("document.domain")
            }, function () {
                return eval("screen.deviceXDPI")
            }, function () {
                return eval("screen.deviceYDPI")
            }, function () {
                return eval("screen.fontSmoothingEnabled")
            }, function () {
                return eval("screen.updateInterval")
            }, function (a) {
                return a.h()
            }, function (a) {
                return a.i(c)
            }, function () {
                return "@UTC@"
            }, function (a) {
                return a.l(c)
            }, function (a) {
                return a.k()
            }, function () {
                return eval("screen.width")
            }, function () {
                return eval("screen.height")
            }, function (a) {
                return a.plugins.Acrobat
            }, function (a) {
                return a.plugins.Flash
            }, function (a) {
                return a.plugins.QuickTime
            }, function (a) {
                return a.plugins["Java Plug-in"]
            }, function (a) {
                return a.plugins.Director
            }, function (a) {
                return a.plugins.Office
            }, function () {
                return (new Date).getTime() - c.getTime()
            }, function (a) {
                return a.e
            }, function (a) {
                return a.f
            }, function () {
                return c.toLocaleString()
            }, function () {
                return eval("screen.colorDepth")
            }, function () {
                return eval("window.screen.availWidth")
            }, function () {
                return eval("window.screen.availHeight")
            }, function () {
                return eval("window.screen.availLeft")
            }, function () {
                return eval("window.screen.availTop")
            }, function (a) {
                return a.a("Acrobat")
            }, function (a) {
                return a.a("Adobe SVG")
            }, function (a) {
                return a.a("Authorware")
            }, function (a) {
                return a.a("Citrix ICA")
            }, function (a) {
                return a.a("Director")
            }, function (a) {
                return a.a("Flash")
            }, function (a) {
                return a.a("MapGuide")
            }, function (a) {
                return a.a("MetaStream")
            }, function (a) {
                return a.a("PDFViewer")
            }, function (a) {
                return a.a("QuickTime")
            }, function (a) {
                return a.a("RealOne")
            }, function (a) {
                return a.a("RealPlayer Enterprise")
            }, function (a) {
                return a.a("RealPlayer Plugin")
            }, function (a) {
                return a.a("Seagate Software Report")
            }, function (a) {
                return a.a("Silverlight")
            }, function (a) {
                return a.a("Windows Media")
            }, function (a) {
                return a.a("iPIX")
            }, function (a) {
                return a.a("nppdf.so")
            }, function (a) {
                return a.m()
            }];
        this.o();
        for (var e = "", f = 0; f < d.length; f++) {
            if (b) {
                e += this.j(d[f].toString(), '"', "'", true);
                e += "="
            }
            var g;
            try {
                g = d[f](this)
            } catch (h) {
                g = ""
            }
            e += b ? g : escape(g);
            e += ";";
            if (b) e += "\\n"
        }
        return e = this.j(e, escape("@UTC@"), (new Date).getTime())
    };
    this.r = function (b) {
        try {
            var c;
            c = this.p(b);
            if (c !== null) try {
                c.value = this.q()
            } catch (d) {
                c.value = escape(d.message)
            }
        } catch (e) {}
    };
    this.a = function (b) {
        try {
            if (navigator.plugins && navigator.plugins.length) for (var c = 0; c < navigator.plugins.length; c++) {
                var d = navigator.plugins[c];
                if (d.name.indexOf(b) >= 0) return d.name + (d.description ? "|" + d.description : "")
            }
        } catch (e) {}
        return ""
    };
    this.m = function () {
        var b = document.createElement("span");
        b.innerHTML = "&nbsp;";
        b.style.position = "absolute";
        b.style.left = "-9999px";
        document.body.appendChild(b);
        var c = b.offsetHeight;
        document.body.removeChild(b);
        return c
    }
};
try {
    adtruth.c = document.createElement("span");
    typeof adtruth.c.addBehavior !== "undefined" && adtruth.c.addBehavior("#default#clientCaps")
} catch (i) {}
window.adtruth = adtruth;
window.adtruth.validator = adtruth.r;


// madvertise stuff starts here
(function() {
  function MadStorage(origin, path) {
      this.origin = origin;
      this.path = path;
      this._iframe = null;
      this._iframeReady = false;
      this._queue = [];
      this._requests = {};
      this._id = 0;
  }

  MadStorage.prototype = {
    constructor: MadStorage,

    init: function() {
      if (!this._iframe) {
        // create iframe
        this._iframe = document.createElement("iframe");
        this._iframe.style.cssText = "position:absolute;width:1px;height:1px;left:-9999px;";
        document.body.appendChild(this._iframe);

        // register event-handler
        var that = this;
        if (window.addEventListener) {
          this._iframe.addEventListener("load", function(){ that._iframeLoaded(); }, false);
          window.addEventListener("message", function(event){ that._handleMessage(event); }, false);
        }
        else if (this._iframe.attachEvent) {
          this._iframe.attachEvent("onload", function(){ that._iframeLoaded(); }, false);
          window.attachEvent("onmessage", function(event){ that._handleMessage(event); });
        }
      }
      this._iframe.src = this.origin + this.path;
    },

    set: function(key, value) {
      this._postRequest({ request: { key: key, value: value, type: 'set', id: ++this._id } });
    },

    get: function(key, callback) {
      this._postRequest({ request: { key: key, type: 'get', id: ++this._id }, callback: callback });
    },

    _postRequest: function(data) {
      if (this._iframeReady) {
        this._sendRequest(data);
      }
      else {
        this._queue.push(data);
      }

      if (!this._iframe) {
        this.init();
      }
    },

    _sendRequest: function(data) {
      this._requests[data.request.id] = data;
      this._iframe.contentWindow.postMessage(JSON.stringify(data.request), this.origin);
    },

    _iframeLoaded: function() {
      this._iframeReady = true;

      if (this._queue.length){
        for (var i=0, len=this._queue.length; i < len; i++) {
          this._sendRequest(this._queue[i]);
        }
        this._queue = [];
      }
    },

    _handleMessage: function(event) {
      if (event.origin == this.origin) {
        var data = JSON.parse(event.data);
        if (this._requests[data.id].callback) {
          this._requests[data.id].callback(data.key, data.value);
        }
        delete this._requests[data.id];
      }
    }

  };

  to_param_string = function(hash) {
    var result = [];
    for(var k in hash) {
      result.push(k+"="+encodeURIComponent(hash[k]));
    }
    return result.join('&');
  };

  merge = function(src_array, dest_array) {
    for (attr in src_array) { dest_array[attr] = src_array[attr]; }

    return dest_array
  }

  get_ad = function(conf, base_url) {
    var ad_tag = null;
    var src = base_url + to_param_string(conf);
    // banner sizes
    var sizes_hash = {
      mma: { w: 320, h: 53 },
      medium_rectangle: { w: 300, h: 250 },
      leaderboard:  { w : 728, h: 90  },
      portrait:     { w : 766, h: 66  },
      landscape:    { w: 1024, h: 66  },
      fullscreen:   { w: 768,  h: 768 },
      rich_media:   { w: 320,  h: 480 }
    };

    var dim = sizes_hash[conf.banner_type] || { w: 320, h: 53 };
    if(screen.availWidth < dim.w) dim.w = screen.availWidth;
    if(screen.availHeight < dim.h) dim.h = screen.availHeight;

    if(conf.format == 'html-js') {
      ad_tag = "<ins id='" + conf.token + "'></ins><script type='text/javascript' src=\"" + src + '"></script>';
    } else {
      ad_tag = '<div><iframe name="madvertise_ad" src="' + src + '" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" frameborder="0" width="' + dim.w + '" height="' + dim.h + '"></iframe></div>';
    }

    document.write(ad_tag);
  }


  // what do we need
  conf = window.madvertise_ad_params;

  // override html for now, as several old browsers do not like it
  if(!conf.format || conf.format == 'html')
    conf.format = 'html-js'

  now = (new Date).getTime();
  var base_url = (conf.base || "http://ad.madvertise.de/site/") + conf.site + "?";

  var today = new Date();
  var jan = new Date(today.getFullYear(), 0, 1);
  var jul = new Date(today.getFullYear(), 6, 1);

  conf = merge({
    requester: 'js',
    version  : 'js-9',
    ref      : document.referrer,
    ua       : navigator.userAgent,
    token    : "JST-" + Math.floor(Math.random()*10000000).toString(36),
    timezone : -(new Date).getTimezoneOffset(),
    timestamp: now,
    color    : screen ? screen.colorDepth: "",
    history  : window.history ? window.history.length: ""
  }, conf);

  if( window.adtruth) conf.dip = adtruth.q();
  if( window.innerWidth) conf.iw = window.innerWidth;
  if( window.innerHeight) conf.ih = window.innerHeight;
  if( window.outerWidth) conf.ow =   window.outerWidth;
  if( window.outerHeight) conf.oh =  window.outerHeight;
  if( window.scrollX) conf.scx =  window.scrollX;
  if( window.scrollY) conf.scy =  window.scrollY;
  if( window.screenX) conf.sx =  window.screenX;
  if( window.screenY) conf.sy =  window.screenY;
  if( screen.colorDepth) conf.cd =  screen.colorDepth;
  if( screen.height) conf.h =  screen.height;
  if( screen.width) conf.w =  screen.width;
  if( screen.availTop) conf.at =  screen.availTop;
  if( screen.availHeight) conf.ah =  screen.availHeight;
  if( screen.availWidth) conf.aw =  screen.availWidth;
  if( screen.availLeft) conf.al =  screen.availLeft;
  if( -today.getTimezoneOffset()) conf.today =  -today.getTimezoneOffset();
  if( -jan.getTimezoneOffset()) conf.jan =  -jan.getTimezoneOffset();
  if( -jul.getTimezoneOffset()) conf.jul =  -jul.getTimezoneOffset();
  if( window.navigator.language) conf.lang =  window.navigator.language;
  if( window.navigator.cpuClass) conf.cpu =  window.navigator.cpuClass;
  if( window.navigator.platform) conf.pf =  window.navigator.platform;

  if ('localStorage' in window && window['localStorage'] !== null && window.postMessage && window.JSON) {
    var uuls = localStorage.getItem("madvertise");
    if (uuls)
      conf.uuls = uuls;

    get_ad(conf, base_url);

    var storage = new MadStorage("http://ad.madvertise.de", "/mad_storage.html");
    storage.get("madvertise", function(key, value) {
      if (value) {
        localStorage.setItem(key, value);
      }
      else if (localStorage.getItem("madvertise")) {
        storage.set("madvertise", localStorage.getItem("madvertise"));
      }
    });
  }
  else {
    get_ad(conf, base_url);
  }
})();

