﻿function HCMPlayer(params) {
    this.mpuDisplayDuration = (params.mpuDuration == null) ? HCMPlayer.mpuDisplayDuration : params.mpuDuration;
    this.playerWidth = params.playerWidth || 300;
    this.playerHeight = params.playerHeight || 300;
    this.playerFile = params.playerFile || "playlist.xml";
    this.playerRecommendations = params.playerRecommendations;
    this.playerConfiguration = { width: this.playerWidth, height: this.playerHeight, image: undefined, shownavigation: "true", autostart: "false", file: this.playerFile, playlist: "bottom", playlistsize: "0", controlbar: "bottom", repeat: "list", recommendations: this.playerRecommendations, volume: "90", fullscreen: "true", quality: "false", stretching: "uniform", bufferlength: "5", showstop: "false", showdownload: "false" };
    // html can obverride default player configuration
    this.overrideConfiguration(params.playerConfiguration);
    this.mpuDivId = params.mpuDivId || false;
    this.playerDivId = params.playerDivId || false;
    this.playerObjectId = 'HCMPlayer' + this._randomId();
    this.baseUrl = 'http://code.haymarket.com/hcmmediaplayer/rc1/';
    this.playerInstance = undefined;
    this.debug = false;

    return this;
};

HCMPlayer.prototype.overrideConfiguration = function(config) {
    if (typeof (config) !== 'undefined') {
        for (var item in config) {
            this.playerConfiguration[item] = config[item];
        }
    }
};

/* static property for advert display duration */
HCMPlayer.mpuDisplayDuration = 0;
HCMPlayer.hasGoogleanalyticsSupport = false;
HCMPlayer.analyticsPrefix = '/hcm_playback_event/';

/* static callback Function to set ad duraction */
HCMPlayer.trigger = function(timeout) {
    /* convert to int and ms */
    HCMPlayer.mpuDisplayDuration = parseInt(timeout);
};

HCMPlayer.prototype.init = function() {
    /* convert s to ms */
    var delay = (this.mpuDisplayDuration > 0) ? (this.mpuDisplayDuration * 1000) : 0;
    //*object reference */
    var thisobj = this;
    /* start coutdown */
    setTimeout(function() { thisobj._initPlayer(thisobj) }, delay);
    return this;
};

HCMPlayer.prototype._getPlayer = function() { return document.getElementById(this.playerDivId); };

HCMPlayer.prototype._getMpuDiv = function() { return document.getElementById(this.mpuDivId); };

/**
* Method returns the actualy mpu replaceable container, rather than the parent DIV
* You can have many divs in the page with a class of prerollAdContainerReplaceable that will be hidden when the player is shown
*/
HCMPlayer.prototype._getMpu = function() {
    var els = this.getElementsByClassName('prerollAdContainerReplaceable', 'div', this._getMpuDiv());
    return (els.length > 0) ? els.pop() : this._getMpuDiv();
};


HCMPlayer.prototype.showPlayer = function() {
    this._hideMpu();
    this._getPlayer().style.display = "block";
};

HCMPlayer.prototype._hidePlayer = function() {
    this._getPlayer().style.display = "none";
};

HCMPlayer.prototype.showMpu = function() {
    this._hidePlayer();
    this._getMpu().style.display = "block";

    /* enable+show flash  MPU files in IE6! */
    var objects = this._getMpuDiv().getElementsByTagName('object');
    if (objects.length > 0) {
        for (var i = 0; i < objects.length; i++) {
            objects[i].style.display = "block";
        }
    }
};


HCMPlayer.prototype._hideMpu = function() {
    var mpu = this._getMpu();
    mpu.style.display = "none";

    /* disable+hide flash  MPU files in IE6! */
    var objects = this._getMpuDiv().getElementsByTagName('object');
    if (objects.length > 0) {
        for (var i = 0; i < objects.length; i++) {
            objects[i].style.display = "none";
        }
    }
};

HCMPlayer.prototype.playbackPlaypause = function() {
    return (typeof (this.playerInstance.sendEvent) !== 'undefined') ? this.playerInstance.sendEvent('PLAY') : false;
};

HCMPlayer.prototype.playbackStop = function() {
    return (typeof (this.playerInstance.sendEvent) !== 'undefined') ? this.playerInstance.sendEvent('STOP') : false;
};

HCMPlayer.prototype._initPlayer = function(thisobj) {

    thisobj.detectAnalyticsSupport();

    var so = new SWFObject(thisobj.baseUrl + 'mediaplayer.swf', thisobj.playerObjectId, thisobj.playerConfiguration.width, thisobj.playerConfiguration.height, '9');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('allowfullscreen', thisobj.playerConfiguration.fullscreen);
    //so.addVariable('tracecall','alert');

    /**
    * Asign values form playerConfiguration into swf object variables
    */
    for (var param in thisobj.playerConfiguration) {
        var valueString = eval('thisobj.playerConfiguration["' + param + '"]');
        if (typeof (valueString) == "string") {
            so.addVariable(param, encodeURIComponent(valueString));
            if (this.debug) {
                alert(param + ' = ' + encodeURIComponent(valueString));
            }
        }
    }

    if (thisobj.playerConfiguration.recommendations != undefined) {
        so.addVariable('recommendations', thisobj.playerConfiguration.recommendations);
    }
    so.addVariable('enablejs', 'true');
    so.addVariable('javascriptid', thisobj.playerObjectId);

    /* automatic hoocking up of start/end trackign into google analytics */
    if (HCMPlayer.hasGoogleanalyticsSupport !== false) {
        so.addVariable('callback', HCMPlayer.hasGoogleanalyticsSupport);
    }

    so.write(thisobj.playerDivId);
    thisobj.showPlayer();

    // save reference to player
    thisobj.playerInstance = thisMovie(thisobj.playerObjectId);

    /* now add classes to DOM to allow css to alter UI to show that MPU has been played */
    document.body.setAttribute("class", document.body.getAttribute("class") + ' HCMPlayerMpuPlayed');
};


HCMPlayer.prototype.detectAnalyticsSupport = function() {

    if (typeof (window._gat) != 'undefined') {
        HCMPlayer.hasGoogleanalyticsSupport = 'analytics';
    }
    else
        if (typeof (urchinTracker) != 'undefined') {
        HCMPlayer.hasGoogleanalyticsSupport = 'urchin';
    }
};

HCMPlayer.prototype._randomId = function() { return Math.floor(Math.random() * 99999); };

HCMPlayer.logToAnalytics = function(event) {

    var pagename = HCMPlayer.analyticsPrefix + event;
    /* alert(pagename); */
    switch (HCMPlayer.hasGoogleanalyticsSupport) {
        case "analytics":
            if (typeof (window.pageTracker._trackPageview) == "function") {
                pageTracker._trackPageview(pagename);
            }
            break;

        case "urchin":
            if (typeof (window.urchinTracker) == "function") {
                urchinTracker(pagename);
            }
            break;
    }
}

/* simple utility to  find elements by class name(s) */
HCMPlayer.prototype.getElementsByClassName = function(strClass, strTag, objContElm) {
    strTag = strTag || "*";
    objContElm = objContElm || document;
    var objColl = objContElm.getElementsByTagName(strTag);
    if (!objColl.length && strTag == "*" && objContElm.all) objColl = objContElm.all;
    var arr = new Array();
    var delim = strClass.indexOf('|') != -1 ? '|' : ' ';
    var arrClass = strClass.split(delim);
    for (var i = 0, j = objColl.length; i < j; i++) {
        var arrObjClass = objColl[i].className.split(' ');
        if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
        var c = 0;
        comparisonLoop:
        for (var k = 0, l = arrObjClass.length; k < l; k++) {
            for (var m = 0, n = arrClass.length; m < n; m++) {
                if (arrClass[m] == arrObjClass[k]) c++;
                if ((delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
                    arr.push(objColl[i]);
                    break comparisonLoop;
                }
            }
        }
    }
    return arr;
};

function thisMovie(swf) {
    return (navigator.appName.indexOf("Microsoft") != -1) ? window[swf] : document[swf];
};

/* playback tracking */
HCMPlayer.playbackPercentage = 0;
HCMPlayer.playbackState = 0;
HCMPlayer.playbackPlaylist = undefined;
HCMPlayer.playbackItem = undefined;

function alertPosition(obj) {
    HCMPlayer.playbackPercentage = Math.round((obj.position / obj.duration) * 100);

    if (HCMPlayer.playbackState == 'PLAYING') {
        switch (parseInt(HCMPlayer.playbackPercentage)) {
            case 1:
                //document.getElementById('reportHolderPosition').innerHTML  = 'START' + HCMPlayer.playbackItem;
                HCMPlayer.logToAnalytics('start/' + HCMPlayer.playbackItem);
                break;

            case 49:
                //document.getElementById('reportHolderPosition').innerHTML  = 'MIDPOINT' + HCMPlayer.playbackItem;
                HCMPlayer.logToAnalytics('mid/' + HCMPlayer.playbackItem);
                break;

            case 99:
                //document.getElementById('reportHolderPosition').innerHTML  = 'ENDPOINT' + HCMPlayer.playbackItem;
                HCMPlayer.logToAnalytics('end/' + HCMPlayer.playbackItem);
                break;
        }
    }
};

function alertState(obj) {
    HCMPlayer.playbackState = obj.newstate
};

function alertMeta(obj) {
    HCMPlayer.playbackPlaylist = thisMovie(obj['id']).getPlaylist();
    HCMPlayer.playbackItem = HCMPlayer.playbackPlaylist[obj.index].title;
};

function playerReady(obj) {
    var swf = thisMovie(obj['id']);
    swf.addModelListener("TIME", "alertPosition");
    swf.addModelListener("STATE", "alertState");
    swf.addControllerListener("ITEM", "alertMeta");
};