/**
* @author GDI, Universal Music Group
* @version 1.0
* @description Akamai QuickTime Player and External Ad Loader
*
* PlayerDisp dynamically constructs player with preroll inserted playlist.
* AdDisplay class to insert external banner. Usage:
*
*    <script type="text/javascript">
*        var config = new Array();
*        config["adEnabled"] = true;
*        config["videoURL"] = [INSERT VIDEO URL];
*        config["playerName"] = [INSERT DOUBLECLICK NAME]; // example: umg.gdi.gdi/video.avp.ak.wm 
*        config["expandedBannerId"] = "customDiv"; // manually set target div, default is AkamaiPlayerDiv
*        // can also set: width, height, autoStart, showControls
*        createPlayer(config);
*    </script>
*    <div id="expandedBanner" class="companionad"><!-- 300x250 is inserted here --></div>   
*/

function PlayerDisp(config) {
    // Browser Detection
    var agt = navigator.userAgent.toLowerCase();
    this.isIe = (agt.indexOf("msie") != -1);
    this.videoURL = checkVal(config["videoURL"], null);
    this.playerName = checkVal(config["playerName"], null);
    if (this.videoURL == null || this.playerName == null) {
        // required parameters not set
        return;
    }
    else {
        this.adEnabled = checkVal(config["adEnabled"], false);        
        this.targetAdDiv = checkVal(config["expandedBannerId"], "expandedBanner");
        this.adDisplay = new AdDisplay(this.targetAdDiv);
        this.width = checkVal(config["width"], 390);
        this.height = checkVal(config["height"], 358);
        this.autoStart = checkVal(config["autoStart"], true);
        this.showControls = checkVal(config["showControls"], true);
        this.enableTracking = false;
        this.isrc = checkVal(config["isrc"], null);
    }
}

PlayerDisp.prototype.adServerUrlPrefix = "http://ad.doubleclick.net/pfadx/";
PlayerDisp.prototype.playlistProxy = "http://assets.gdi.umusic.com/adops/akamai/qt/SmilProxy.ashx";
PlayerDisp.prototype.metaServerUrl = "http://assets.gdi.umusic.com/adops/tools/GetIsrcKeyValues.ashx";
PlayerDisp.prototype.preloaderIconUrl = "http://cache.assets.gdi.umusic.com/adops/akamai/ajax-loader.gif";

PlayerDisp.prototype.constructPlayer = function(url, adURL, adClickURL) {
    var vidUrl = this.playlistProxy + "?";
    vidUrl += "v=" + escape(url); // Video;
    vidUrl += "&h=" + this.height + "&w=" + this.width; // Dimensions
    if (adURL != null && adClickURL != null) {
        vidUrl += "&pr=" + escape(adURL); // Preroll
        vidUrl += "&l=" + escape(adClickURL); // Preroll Link
    }
    
    var objectTag = "";
    objectTag += '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" id="gdiQtVideoPlayer" ';
    objectTag += ' codebase="http://www.apple.com/qtactivex/qtplugin.cab" ';
    objectTag += ' width="' + this.width + '" height="' + this.height + '" >';
    objectTag += ' <param name="autoplay" value="' + this.autoStart + '" />';
    objectTag += ' <param name="src" value="' + vidUrl + '" />';
    objectTag += ' <param name="controller" value="' + this.showControls + '" />';
    objectTag += ' <embed src="http://cache.assets.gdi.umusic.com/adops/akamai/qt/qtHolder.mov" ';
    objectTag += ' qtsrc="' + vidUrl + '" width="' + this.width + '" height="' + this.height + '" name="gdiQtVideoPlayer" ';
    objectTag += ' autoplay="' + this.autoStart + '" controller="' + this.showControls + '" ';
    objectTag += ' pluginspace="www.apple.com/quicktime/download" type="video/quicktime" />';
    objectTag += '</object>';

    var playerDiv = document.getElementById("quickTimePlayerDiv");
    playerDiv.innerHTML = objectTag;
}

PlayerDisp.prototype.track = function(URLs) {
    var arr = URLs.split(",");
    for (var i=0; i<arr.length; i++) {
        var url = unescape(arr[i]);
        this.insertImpressionImage(url);
    }
}

PlayerDisp.prototype.insertImpressionImage = function(url) {
    if (url.substr(0,7) == "http://") {
        var newImg = document.createElement("img");
        newImg.src = url;
        document.body.appendChild(newImg);
    }
}

PlayerDisp.prototype.init = function() {
    if (this.adEnabled) {
        if (this.isrc == null)
            this.getPrefetchAd();
        else 
            this.getMetaData();
    }
    else
        this.constructPlayer(this.videoURL, null, null);
}


PlayerDisp.prototype.getMetaData = function() {
    this.metaLoaded = false;
    var head = document.getElementsByTagName("head")[0];

    var metaScript = document.createElement("script");
    metaScript.type = "text/javascript";
    metaScript.src = this.metaServerUrl + "?v=" + this.isrc;
    
    // Handlers for script load:
    if (this.isIe) { // IE:
        metaScript.onreadystatechange = function() {
            if (this.readyState == "complete" || this.readyState == "loaded") playerDisp.onloadMetaData();
        }
    }
    else { // Mozilla, Opera:
        metaScript.onload = this.onloadMetaData;
    }

    head.appendChild(metaScript);
}

PlayerDisp.prototype.onloadMetaData = function() {
    if (!playerDisp.metaLoaded) {
        playerDisp.metaLoaded = true;
        playerDisp.getPrefetchAd();
    }
}

PlayerDisp.prototype.getPrefetchAd = function() {
    this.prefetchLoaded = false;
    var head = document.getElementsByTagName("head")[0];
    
    if (typeof(keyValues) == "undefined") keyValues = "";

    var adScript = document.createElement("script");
    adScript.type = "text/javascript";
    adScript.src = this.adServerUrlPrefix + this.playerName + ";sz=10x3;" + keyValues; // 10x3 is UMG's ad size for QuickTime
    
    // Handlers for script load:
    if (this.isIe) { // IE:
        adScript.onreadystatechange = function() {
            if (this.readyState == "complete" || this.readyState == "loaded") playerDisp.onloadPrefetchAd();
        }
    }
    else { // Mozilla, Opera:
        adScript.onload = this.onloadPrefetchAd;
    }
    
    head.appendChild(adScript);
}

// This is called as a handler, so we lose object context.
// We call playerDisp.processJsonAdModule() to retrieve context.
PlayerDisp.prototype.onloadPrefetchAd = function() {
    if (!playerDisp.prefetchLoaded) { // flag to prevent IE from calling twice
        playerDisp.prefetchLoaded = true;
        playerDisp.processJsonAdModule();
    }
}


PlayerDisp.prototype.processJsonAdModule = function() {
    if (typeof(jsonAdModule) == "undefined") {
        this.constructPlayer(this.videoURL, null, null);        
    }
    else {
        if (jsonAdModule.type == "PrerollAndCompanion300x250") {                
            this.constructPlayer(this.videoURL, jsonAdModule.video.videoURL, jsonAdModule.video.videoClickURL);
            this.enableTracking = true;
            this.insertImpressionImage(jsonAdModule.video.impressionURL);
            this.adDisplay.loadExternalBanner(jsonAdModule.banner.expandedBannerURL, jsonAdModule.banner.expandedBannerClickURL, 300, 250, 1);
        }
        else if (jsonAdModule.type == "Standalone300x250") {
            this.constructPlayer(this.videoURL, null, null);        
            this.adDisplay.loadExternalBanner(jsonAdModule.banner.expandedBannerURL, jsonAdModule.banner.expandedBannerClickURL, 300, 250, 0);
        }
        else {
            this.constructPlayer(this.videoURL, null, null);
        }
    }
}

/// Helper Functions
function checkVal(param, def) {
    return (typeof(param) == "undefined") ? def : param;
}
function getBit(bool) {
    return (bool) ? "1" : "0";
}

// Entry Point
var playerDisp = null;
function createPlayer(config) {
    playerDisp = new PlayerDisp(config);
    // This is where the player will get inserted
    document.write("<div id='quickTimePlayerDiv' style='background-color: #ffffff; background-repeat: no-repeat; background-position: center center; background-image: url(" + playerDisp.preloaderIconUrl + "); height:" + playerDisp.height + "px; width:" + playerDisp.width + "px;'></div>"); 
	window.onload = function() {
	    playerDisp.init();
	}
}

function AdDisplay(targetDiv) {
    this.targetDiv = targetDiv;
    this.adPriority = 0;
}

//--- RENDERS EXTERNAL BANNER---
AdDisplay.prototype.loadExternalBanner = function(bannerURL, clickURL, width, height, priority) {
    if (priority >= this.adPriority) {
        this.adPriority = priority;
       
        var expandedBanner = document.getElementById(this.targetDiv);            
        
        // INSERTS FLASH MOVIE (ends with "SWF")
        if(bannerURL.substr(-3, 3).toLowerCase() == "swf")
        {
            var objectTag = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + width + '" height="' + height + '" id="expandedBanner" align="middle">';
            objectTag += '<param name="allowScriptAccess" value="always" />';
            objectTag += '<param name="movie" value="' + bannerURL + '" />';
            objectTag += '<param name="quality" value="high" />';
            objectTag += '<param name="bgcolor" value="#ffffff" />';
            objectTag += '<param name="FlashVars" value="clickTag=' + clickURL + '" />';
            objectTag += '<embed src="' + bannerURL + '" quality="high" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="expandedBanner" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="clickTag=' + clickURL + '" />';
            objectTag += '</object>';
            expandedBanner.innerHTML = objectTag; //writes out the object tag we just built to the expandedBanner div
        }
        // INSERTS IFRAME FOR REDIRECTS       
        else if (bannerURL.substr(0, 39) == "http://ad.doubleclick.net/adi/umg.inrd/")
        {
            expandedBanner.innerHTML = '<iframe height="' + height + '" width="' + width + '" scrolling="no" src="' + bannerURL + '"  frameborder="0"></iframe>';
        }
        // INSERTS IMAGE
        else
        {
            expandedBanner.innerHTML = "<a href='" + clickURL + "' target='_blank'><img src='" + bannerURL + "' border='0' /></a>"; //writes out the regular anchor/tag to the expandedBanner div
        }
    }
}

