dartInstreamObjects = new Array(3);


function CNBCDartPlayer(playerHandle, pubReadyCallback) 
{
	this.id = "Dart InStream Player";
    this.debug = true;
    this.playerImpl = null;
    this.playerObject = null;
    this.ad = null;
    this.commercial = false;
    this.customParameters = new Object();
    this.tileCntr = 1;


    // handlers
    this.pubReadyCallback = pubReadyCallback;
    this.adStartHandler = null;
    this.adCompleteHandler = null;
    this.adMidpointHandler = null;
    this.pauseHandler = null;
    this.restartHandler = null;
    this.muteHandler = null;
    this.fullscreenHandler = null;
    this.clickHandler = null;

    this.autoLogThirdPartyImpression = true;
    this.autoLogThirdPartyClick = true;
    this.autoLogThirdPartyComplete = true;
    this.initTimeoutId = null;


    this.getAd = function() { return this.ad } ;
    this.isCommercial = function() { return this.commercial };

    this.setAutoLogThirdPartyImpression = function(flag) { this.autoLogThirdPartyImpression = flag; }
    this.setAutoLogThirdPartyClick = function(flag) { this.autoLogThirdPartyClick = flag; }
    this.setAutoLogThirdPartyComplete = function(flag) { this.autoLogThirdPartyComplete = flag; }

    //***** callback handlers *****//
    this.getAdStartHandler = function() { return this.adStartHandler; }
    this.getAdCompleteHandler = function() { return this.adCompleteHandler; }
    this.getAdMidpointHandler = function() { return this.adMidpointHandler; }
    this.getPauseHandler = function() { return this.pauseHandler; }
    this.getRestartHandler = function() { return this.restartHandler; }
    this.getMuteHandler = function() { return this.muteHandler; }
    this.getFullscreenHandler = function() { return this.fullscreenHandler; }
    this.getClickHandler = function() {return this.clickHandler; }

    //**** end callback handlers ***//

    //********* callbacks *********//
    this.attachOnAdStart = function(fName) { this.adStartHandler = fName; }
    this.attachOnAdComplete = function(fName) { this.adCompleteHandler = fName; }
    this.attachOnAdMidpoint = function(fName) { this.adMidpointHandler = fName; }
    this.attachOnPause = function(fName) { this.pauseHandler = fName; }
    this.attachOnRestart = function(fName) { this.restartHandler = fName; }
    this.attachOnMute = function(fName) { this.muteHandler = fName; }
    this.attachOnFullscreen = function(fName) { this.fullscreenHandler = fName; }
    this.attachOnClick = function(fName) { this.clickHandler = fName; }

    this.detachOnAdStart = function() { this.adStartHandler = null; }
    this.detachOnAdComplete = function() { this.adCompleteHandler = null; }
    this.detachOnAdMidpoint = function() { this.adMidpointHandler = null; }
    this.detachOnPause = function() { this.pauseHandler = null; }
    this.detachOnRestart = function() { this.restartHandler = null; }
    this.detachOnMute = function() { this.muteHandler = null; }
    this.detachOnFullscreen = function() { this.fullscreenHandler = null; }
    this.detachOnClick = function() { this.clickHandler = null; }

    //******* end callbacks *******//

    this.unregister = function() {
        this.playerImpl.unregister();
        this.playerImpl = null;
        this.ad = null;
        this.adStartHandler = null;
        this.adCompleteHandler = null;
        this.adMidpointHandler = null;
        this.pauseHandler = null;
        this.restartHandler = null;
        this.muteHandler = null;
        this.fullscreenHandler = null;
    }

    this.setMetaProperties = function(args,createNew) {
        if (createNew) this.customParameters = new Object();
        var keyValues = args;
        for (var i=0; i<keyValues.length;++i) {
            var keyValueString = keyValues[i];
            var key = keyValueString.substring(0,keyValueString.indexOf("=")).toLowerCase();
            var value = keyValueString.substring(keyValueString.indexOf("=")+1, keyValueString.length);
            if (key == "customparams") {
                var customKeyValues = value.split(",");
                for (var j=0; j<customKeyValues.length;++j) {
                    var customKeyValueString = customKeyValues[j];
                    var customKey = customKeyValueString.substring(0,customKeyValueString.indexOf("=")).toLowerCase();
                    var customValue = customKeyValueString.substring(customKeyValueString.indexOf("=")+1, customKeyValueString.length);
                    this.customParameters[customKey] = customValue;
                }
            } else this.customParameters[key] = value;
        }
    }

    this.getMetaProperty = function(paramName) {
        return this.customParameters[paramName.toLowerCase()];
    }

    this.createGetCustomParameterFunction = function(dartplayer) {
        return  (function(param) {return dartplayer.getMetaProperty(param);});
    }

    this.flashAdStart = function() {
        this.setMetaProperties(arguments,true);

        var adObj = new InStreamAd();
        adObj.getCustomParameter = this.createGetCustomParameterFunction(this);
        this.ad = adObj;

        this.logUrl(this.getMetaProperty("dartImpURL"));
		this.logUrl(this.getMetaProperty("thirdPartyImpressionURL"));
		if(this.adStartHandler) {
			this.adStartHandler(adObj);
		}
		
		this.writeSurveyUrl(this.ad.getSurveyURL());
    }

    this.flashAdComplete = function() {
        this.logUrl(this.getMetaProperty("metPostingURL")+"eid1=13;ecn1=1;etm1=0;");
		this.logUrl(this.getMetaProperty("thirdPartyCompleteURL"));
		this.adCompleteHandler();
	}

	this.isWindows = function() {
		return (navigator.appVersion.indexOf("Windows") != -1);
	}

	this.isFirefox = function() {
		var appUserAgent = navigator.userAgent.toUpperCase();
		if(appUserAgent.indexOf("GECKO") != -1) {
			if(appUserAgent.indexOf("FIREFOX") != -1) {
				var version = parseFloat(appUserAgent.substr(appUserAgent.lastIndexOf("/") + 1));
				return (version >= 1) ? true : false;
			}
			else if(appUserAgent.indexOf("NETSCAPE") != -1) {
				var version = parseFloat(appUserAgent.substr(appUserAgent.lastIndexOf("/") + 1));
				return (version >= 8) ? true : false;
			}
		}
		return false;
	}



	this.isMac = function() {
		return (navigator.appVersion.indexOf("Mac") != -1);
	}


	this.isInternetExplorer = function() {
		return (navigator.appVersion.indexOf("MSIE") != -1 && navigator.userAgent.indexOf("Opera") < 0);
	}


    this.toObject = function(variableName) {
		if(document.layers) {
			return (document.layers[variableName]) ? eval(document.layers[variableName]) : null;
		}
		else if(document.all && !document.getElementById) {
			return (eval("window." + variableName)) ? eval("window." + variableName) : null;
		}
		else if(document.getElementById && document.body.style) {
			return (document.getElementById(variableName)) ? eval(document.getElementById(variableName)) : null;
		}
	}


	this.logUrl = function(url) {
		var logImage = document.createElement("IMG");
		logImage.src = url + "&ts=" + new Date().getTime() + ";";
	}


	this.writeSurveyUrl = function(scriptUrl) {
		if(scriptUrl) {
			var scriptElement = document.createElement("Script");
			scriptElement.src = scriptUrl;
			document.body.appendChild(scriptElement);
		}
	}


    //***** "Super" methods *****//
    this.logThirdPartyImpressionURL = function() {
        if(this.isDefined(this.ad.getThirdPartyImpressionURL())){
			this.logUrl(this.ad.getThirdPartyImpressionURL());
        }
    }

    this.logThirdPartyClickURL = function() {
        if(this.isDefined(this.ad.getThirdPartyClickURL())){
            this.logUrl(this.ad.getThirdPartyClickURL());
        }
    }

    this.logThirdPartyCompleteURL = function() {
        if(this.isDefined(this.ad.getThirdPartyCompleteURL())){
			this.logUrl(this.ad.getThirdPartyCompleteURL());
        }
    }

    this.logImpression = function() {
        this.logUrl(this.ad.getImpressionURL());
	}

    this.isDefined = function(obj) {
        return obj ? true : false;
    }

    this.storePlayer = function() {
        dartInstreamObjects["DARTInstream"] = this;
    }

    this.doneLoading = function() {
        this.pubReadyCallback();
    }

    this.initWMPlayer = function() {
        if(typeof(DARTInstreamImplDoneLoading) == "boolean" && DARTInstreamImplDoneLoading) {
            clearTimeout(this.initTimeoutId);
            this.playerImpl = new WMPlayer(this);
        }
        else {
            this.initTimeoutId = setTimeout("dartInstreamObjects['DARTInstream'].initWMPlayer()", 100);
        }
    }



	this.fsHook = function(variableName) {
		var str = "";
		str += 'function ' + variableName + '_DoFSCommand(command, args) { \n';
		str += '    dartInstreamObjects["' + "DARTInstream" + '"].FSCommandHandler(command, args);\n';
		str += '}\n';
		window.eval(str);

		// attach FSCommand handler
		var flashObj = this.toObject(variableName);
		var pointer = eval(variableName + "_DoFSCommand");
		if(this.isInternetExplorer()) {
			flashObj.attachEvent("FSCommand", pointer);
		}
		else if(this.isFirefox()) {
			flashObj.addEventListener("FSCommand", pointer, true);
		}
	}


	this.FSCommandHandler = function(command, args) {
		var argArray = this._splitArgs(args);
		var functionCall = command + "(";
		var count = 0;
		for(var k = 0; k < argArray.length; k++) {
			if(count > 0) {
				functionCall += ", ";
            }
			functionCall += "\"" + argArray[k] + "\"";
			count++;
		}
		functionCall += ")";
		try {
			return eval("dartInstreamObjects[\"" + "DARTInstream" + "\"]." + functionCall);
		}
		catch(e) {
			try {eval(functionCall);}
			catch(e) {}
		}
	}

	function _splitArgs(args) {
		var parameterArray = new Array();
		var unescapedArgs = unescape(args)
		var stringArray = unescapedArgs.split("#mtf#");
		for(var k = 0; k < stringArray.length; k++) {
			parameterArray[k] = stringArray[k];
		}
		return parameterArray;
	}
	this._splitArgs = _splitArgs;

    this.getCompanionURL = function(baseURL, paramName) {
        var re = new RegExp(paramName+"=\\d*");
        var match = re.exec(baseURL);
        if (match == null) {
            if (baseURL.lastIndexOf(";") != baseURL.length-1) baseURL += ";";
            baseURL += paramName+"="+this.getAd().getDartId();
        } 
        else {
            baseURL = baseURL.replace(re,paramName+"="+this.getAd().getDartId());
        }

        if (paramName == "dc_seed") {
            var tileRe = new RegExp("tile=\\d*");
            var tileMatch = tileRe.exec(baseURL);
            if (match == null) {
                if (baseURL.lastIndexOf(";") != baseURL.length-1) baseURL += ";";
                baseURL += "tile=" + ++this.tileCntr;
            }
        }
        return baseURL;
    }

    this.getRoadblockURL = function(baseURL) {
        return this.getCompanionURL(baseURL, "dc_seed");
    }

    this.writeFlashObject = function(varName) {
		document.write('<div style="visibility: hidden; position: absolute; top: 10px; left: 600px;">');
        document.write('<object id="' + varName + '" width="1" height="1"  classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">');
        document.write('<param name="movie" value="http://m1.2mdn.net/879366/imp_01_17.swf?uagent=' + navigator.userAgent + '" />');
        document.write('<embed id="' + varName + '" name="' + varName +'" play="true" src="http://m1.2mdn.net/879366/imp_01_17.swf?uagent=' + navigator.userAgent + '" AllowScriptAccess="always" quality="high" bgcolor="#ffffff" width="1" height="1"  align="middle" type="application/x-shockwave-flash" />');
        document.write('</object></div>');
	}

	this.createObserver = function() {
		//var variableName = "Flash_Observer_" + (new Date()).getTime();
		this.fsHook("Flash_Observer_" + cnbc_docid);
	}

    this.register = function(handle) {
        if(typeof(handle) == 'object') {
            this.playerObject = handle;
        }
        else {
            this.playerObject = this.toObject(handle);
        }

		if(!this.isInternetExplorer()) {
			if(dartPlayer==null)
			{
				this.createObserver();
			}
		}

        if(this.playerObject.classid == 'CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6') {
            this.initWMPlayer();
        }
        else if(this.playerObject.type == 'application/x-oleobject') {
            setTimeout("dartInstreamObjects['" + "DARTInstream" + "'].pubReadyCallback();", 100);
        }

        this.storePlayer();
    }

    this.register(playerHandle);   
}

function InStreamAd(item, media) {
    this.localParameters = new Object();
    this.id = "Dart InStream Ad";

    this.getCustomParameter = function(param) {
        return item.getItemInfo(param);
    }

    this.getThirdPartyImpressionURL = function() {
        return this.getCustomParameter('thirdPartyImpressionURL');
    }

    this.getThirdPartyClickURL = function() {
        return this.getCustomParameter('thirdPartyClickURL');
    }

    this.getThirdPartyCompleteURL = function() {
        return this.getCustomParameter('thirdPartyCompleteURL');
    }

    this.getSurveyURL = function() {
        return this.getCustomParameter('surveyURL');
    }

    this.getADID = function() {
        return this.getCustomParameter('ISCI');
    }

    this.getDartId = function() {
        return this.getCustomParameter('DartAdId');
    }

    this.getDartRenderingId = function() {
        return this.getCustomParameter('DartRenderingId');
    }

    this.getMetPostingURL = function() {
        return this.getCustomParameter('MetPostingURL');
    }

    this.getDuration = function() {
        return (media)?media.duration:-1;
    }

    this.getFirstQuarterPoint = function() {
        return (media)?media.duration * .25:-1;
    }

    this.getThirdQuarterPoint = function() {
        return (media)?media.duration * .75:-1;
    }

    this.getMidPoint = function() {
        return (media)?media.duration / 2:-1;
    }

    this.getClickString = function() {
        return this.getCustomParameter('clickString');
    }

    this.getClickThroughURL = function() {
        return this.getCustomParameter('clickThroughURL');
    }

    this.getImpressionURL = function() {
        return this.getCustomParameter('DartImpURL');
    }
}
