//--------------------------------------------------------------------
// CLARK - Webtrends
// Webtrends Brightcove tracking plug-in
// Mod History
// 8/13/2011	    JCLARK    	Release cantidate     v1.0.0
// 11/10/2013       JCLARK      updates               v2.0.0
// 01/06/2014       JCLARK      updated - removed http from js load
//
// Version 2.0.5
//--------------------------------------------------------------------
/*Configuration Options
 *
 * load: 			loaad event tracking valid values {true:false} default true
 * loadMeta: 	    loaadedmetadata event tracking valid values {true:false} default true
 * pause: 			pause/resume event tracking valid values {true:false} default true
 * quartile: 	    quartile event tracking valid values {true:false} default true
 * beacon: 		    beacon tracking valid values {true:false} default true
 * seek: 			seek event tracking valid values {true:false} default true
 * mute:            send mute evets default:true
 * beaconRate:      the number of seconds between beasons in seconds values {0-65,000} default 60
 * pctInc: 		    percentage increments for quartile tracking defaule 25
 * volume: 		    volume event and level tracking valid values {true:false} default true
 * bins: 			bin range for duration tracking in seconds. valid values [0-65000{ defaut 15
 * dcsid: 			override dcsid
 * menuEvents       send menu events default:false
 * cueEvents        send cue point events default: false
 * socialEvents     send social events default:false
 * menuEvents       send menu events default:false
 * adEvents         send ad events default:false
 * miscPlayerEvents send miscellaneous player events default:false
 *
 *    Parameters generated
 *     clip_n: 					clip name
 *     clip_id: 				clip identifier
 *     clip_secs: 				playhead positon in clip
 *     clip_ct: 				clip content (mp4,mov,avi,...)
 *     clip_perc: 				percentage played
 *     clip_ev: 				event identifier
 *     clip_duration: 		    clips duration
 *     clip_t: 					player media type
 *     clip_player: 			clip player name
 *     clip_vol: 				clip volume level (0-100)
 *     clip_res: 				clip resolution hxw
 *     clip_duration_n: 	    clip duration bin
 *     clip_tv: 				clip tag version
 *     clip_mode: 				streaming or fixed duration
 *     dl: 						 event type 41 - load, 40 for event
 *
 */
function BCTrack(experienceID, p) {

    this.version = '2.0.2';
    var self = this;


    this.module = {
        bcExp: null,
        modExp: null,
        modCon: null,
        modVP: null,
        modAdv: null,
        modMen: null,
        modSoc: null,
        modCue: null
    };
    // configuration flags
    // set to false to disable tracking for specific events
    var config = {
        menuEvents: false,
        cueEvents: false,
        socialEvents: false,
        adEvents: false,
        miscPlayerEvents: false,
        load: true,
        loadMeta: true,
        pause: true,
        quartile: true,
        beacon: false,
        seek: true,
        beaconRate: 10,
        pctInc: 25,
        volume: true,
        mute: true,
        bins: 15,
        dcsid: null
    };

    // overwrite the config value if they are specified on the plugin load line
    for (i in config) {
        if (p[i]) config[i] = p[i]
    }

    this.data = {
        WT: {
            clip_n: null,
            clip_id: null,
            clip_secs: null,
            clip_ct: null,
            clip_perc: null,
            clip_ev: null,
            clip_duration: null,
            clip_t: null,
            clip_player: "BrightCove",
            clip_provider: null,
            clip_vol: null,
            clip_res: null,
            clip_player_res: null,
            clip_q: null,
            clip_duration_n: null,
            clip_tv: "2.0.2",
            clip_mode: 'Fixed Duration',
            dl: 40
        },
        _state: 0,
        _mute: false,
        _volSettle: -1,
        _seekSettle: 0,
        _loaded: false,
        _mediaPlay: false,
        _mediaSeek: false,
        _mediaBegin: false,
        _mediaComplete: false,
        _currentVolume: 1.00,
        _lastBeacon: 0,
        _lastQuartile: 0,
        _currentVideo: null,
        _experienceID: null,
        _PublisherID: null,
        _pauseTimer: null,
        _currentPhase: 'Content'
    };

    //--------------------------------------------------------------------
    // EXPERIENCE EVENTS
    //--------------------------------------------------------------------
    this.Exp = {
        onExpEvent: function (evt) {
            if (evt.type == BCExperienceEvent.CONTENT_LOAD) {
                var vidInfo = self.module.modVP.getCurrentVideo();
                self.data.WT.clip_n = vidInfo.displayName;
                self.data.WT.clip_id = vidInfo.id;
                self.data.WT.clip_duration = Math.floor(vidInfo.length / 1000);
                for (c = 0; c < vidInfo.renditions.length; c++) {
                    if (vidInfo.renditions[c].encodingRate == vidInfo.encodingRate) {
                        self.data.WT.clip_res = vidInfo.renditions[c].frameHeight + 'x' + vidInfo.renditions[c].frameWidth;
                        self.data.WT.clip_t = vidInfo.renditions[c].videoCodec;
                        url = vidInfo.renditions[c].defaultURL.split('?')[0];
                        self.data.WT.clip_ct = url.split('.')[url.split('.').length - 1].toUpperCase();
                    }
                }
                if (config.bins && isFinite(vidInfo.length)) {
                    var b = Math.floor((Math.floor(vidInfo.length / 1000) + config.bins) / config.bins);
                    self.data.WT.clip_duration_n = (b - 1) * config.bins + '-' + b * config.bins;
                }
                self._mediaComplete = false;
                self._lastQuartile = 0;
                self._lastBeacon = 0;
                if (config.load) {
                    self.data.WT.clip_ev = 'load';
                    self.data.WT.dl = 41;
                    self.track.sendTag();
                    self.data.WT.dl = 40;
                }
            }
            self.data._PublisherID = self.module.modExp.getPublisherID();
            // if ready then send ready event
        }
    };
    //--------------------------------------------------------------------
    // PLAYER EVENTS
    //--------------------------------------------------------------------
    this.VP = {
        onPlayEvent: function (evt) {
            var data = self.data;
            data.WT.clip_perc = String(Math.floor((evt.position / evt.duration) * 100));
            if (data.WT.clip_perc > 100) data.WT.clip_perc = 100;
            data.WT.clip_secs = String(Math.floor(evt.position));

            switch (evt.type) {
                case BCMediaEvent.PLAY:
                    if (!data._mediaSeek) {
                        if (!data._mediaPlay) {
                            data._mediaPlay = true;
                            data._mediaSeek = false;
                            data._mediaComplete = false;
                            data._lastQuartile = 0;
                            data._lastBeacon = 0;
                            data.WT.clip_ev = 'Play';
                            self.track.sendTag();
                        } else {
                            if (config.pause) {
                                data.WT.clip_ev = 'Resume';
                                self.track.sendTag();
                            }

                            data._mediaPlay = false;

                        }
                    } else {
                        // seek resume
                        data._mediaSeek = false;
                    }
                    data._mediaComplete = false;
                    break;

                case BCMediaEvent.SEEK_NOTIFY:
                    //                case BCMediaEvent.SEEK:
                    data._mediaSeek = true;
                    if (config.seek) {
                        data.WT.clip_ev = 'Seek';
                        self.track.sendTag();
                        if (data._pauseTimer) {
                            clearTimeout(data._pauseTimer);
                            data.pauseTimer = null;
                        }
                    }
                    break;

                case BCMediaEvent.CHANGE:
                    data._mediaBegin = false;
                    data._mediaComplete = false;
                    break;

                case BCMediaEvent.BEGIN:
                    data._mediaBegin = true;
                    data._mediaComplete = false;
                    data.flag._lastQuartile = 0;
                    data._lastBeacon = 0;
                    break;

                case BCMediaEvent.PROGRESS:
                    if ((evt.position / evt.duration) > .98 && !data._mediaComplete) {
                        data._mediaComplete = true;
                        data.WT.clip_perc = 100;
                        data.WT.clip_ev = 'Complete';
						data.WT.si_cs = '1';
                        self.track.sendTag();
                    }

                    if (config.beacon) {
                        if (evt.position > data._lastBeacon + config.beaconRate) {
                            data.WT.clip_ev = 'Beacon';
                            data._lastBeacon += config.beaconRate;
							data.WT.si_cs = '';
                            self.track.sendTag();
                        }
                    }

                    if (config.quartile) {
                        if (data.WT.clip_perc >= data._lastQuartile + config.pctInc) {
                            data.WT.clip_perc = Math.floor(data.WT.clip_perc / config.pctInc) * config.pctInc;
                            data.WT.clip_ev = 'Quartile';
                            data._lastQuartile += config.pctInc;
							data.WT.si_cs = '';
                            self.track.sendTag();
                        }
                    }
                    break;

                case BCMediaEvent.COMPLETE:
                    data._mediaBegin = false;
                    data._mediaPlay = false;
                    data._mediaComplete = true;
                    if (!data._mediaComplete) {
                        data.WT.clip_ev = 'Complete';
                        self.track.sendTag();
                    }
                    break;

                case BCMediaEvent.MUTE_CHANGE:
                    data._mute = (data._mute ? false : true);
                    if (config.mute && !data._mute) {
                        data.WT.clip_ev = 'Mute';
                        self.track.sendTag();
                    }
                    break;
                case BCMediaEvent.STOP:
                    if ((evt.position / evt.duration) < .98) {
                        if (!data._mediaComplete) {
                            if (config.pause) {
                                data._pauseTimer = setTimeout(function () {
                                    data.WT.clip_ev = 'Pause';
                                    self.track.sendTag();
                                }, 250);
                            }
                        } else {
                            // already paused
                        }
                    }
                    break;

                case BCMediaEvent.VOLUME_CHANGE:
                    if (self.module.modVP.getVolume() >= data._currentVolume * 1.1 || self.module.modVP.getVolume() <= data._currentVolume * .9) {
                        data._currentVolume = self.module.modVP.getVolume();
                        if (config.vol) {
                            data.WT.clip_ev = 'Volume';
                            self.track.sendTag();
                        }
                    }
                    break;

                default:
                    if (config.miscPlayerEvents) {
                        data.WT.clip_ev = evt.type;
                        self.track.sendTag();
                    }
            }
        }
    };

    //--------------------------------------------------------------------
    // Ad EVENTS
    //--------------------------------------------------------------------
    this.Ad = {
        onAdEvent: function (evt) {
            if (config.adEvents) {
                if (evt.type == BCAdvertisingEvent.AD_START) self.flag._currentPhase = 'PreRoll';
                if (evt.type == BCAdvertisingEvent.AD_COMPLETE) self.flag._currentPhase = 'Content';
                self.data.WT.clip_ev = evt.type;
                self.track.sendTag();
            }
        }
    };

    //--------------------------------------------------------------------
    // Menu EVENTS
    //--------------------------------------------------------------------
    this.Men = {
        onMenuEvent: function (evt) {
            if (config.menuEvents) {
                self.data.WT.clip_ev = evt.type;
                self.track.sendTag();
            }
        }
    };

    //--------------------------------------------------------------------
    // Social EVENTS
    //--------------------------------------------------------------------
    this.Soc = {
        onSocEvent: function (evt) {
            if (config.socialEvents) {
                self.data.WT.clip_ev = evt.type;
                self.track.sendTag();
            }
        }
    };

    //--------------------------------------------------------------------
    // Cue Point EVENTS
    //--------------------------------------------------------------------
    this.CueEvent = {
        onCue: function (evt) {
            if (config.cueEvents) {
                self.data.WT.clip_ev = evt.type;
                self.track.sendTag();
            }
        }
    };
    try {
        this.data._experienceID = experienceID;
        this.module.bcExp = brightcove.getExperience(experienceID);
        // keep a pointer for the video module in the root scope so we can use it later
        this.module.modExp = this.module.bcExp.getModule(APIModules.EXPERIENCE);
        if (this.module.modExp) {
            for (keys in BCExperienceEvent) {
                this.module.modExp.addEventListener(BCExperienceEvent[keys], this.Exp.onExpEvent, false);
            }
        }

        // CONTENT EVENTS
        this.module.modCon = this.module.bcExp.getModule(APIModules.CONTENT);
        if (this.module.modCon) {
            for (keys in BCContentEvent) {
                this.module.modCon.addEventListener(BCContentEvent[keys], this.Exp.onExpEvent, false);
            }
        }

        // player events
        this.module.modVP = this.module.bcExp.getModule(APIModules.VIDEO_PLAYER);
        if (this.module.modVP) {
            for (keys in BCMediaEvent) {
                this.module.modVP.addEventListener(BCMediaEvent[keys], this.VP.onPlayEvent, false);

            }
        }
/*
        // Ad events
        this.module.modAdv = this.module.bcExp.getModule(APIModules.ADVERTISING);
        if (this.module.modAdv) {
            for (keys in BCAdvertisingEvent) {
                this.module.modAdv.addEventListener(BCAdvertisingEvent[keys], this.Ad.onAdEvent, false);
            }
        }

*/
        // Menu events
        this.module.modMen = this.module.bcExp.getModule(APIModules.MENU);
        if (this.module.modMen) {
            for (keys in BCMenuEvent) {
                this.module.modMen.addEventListener(BCMenuEvent[keys], this.Men.onMenuEvent, false);
            }
        }

        // Social events
        this.module.modSoc = this.module.bcExp.getModule(APIModules.SOCIAL);
        if (this.module.modSoc) {
            for (keys in BCSocialEvent) {
                this.module.modSoc.addEventListener(BCSocialEvent[keys], this.Soc.onSoc, false);
            }
        }
/*
        // CuePoint Events
        this.module.modCue = BCTrack.module.bcExp.getModule(APIModules.CUE_POINTS);
        if (this.module.modCue) {
            this.module.modCue.addEventListener(BCCuePointEvent.CUE, this.Cue.onCueEvent, false);
        }
        */
    } catch (e) {
    }

    // this is set up as a queue so its v9 tag comparable

    this.track = {
        sendTag: function () {
            var tags = [];
            var cache = [];

            for (var tag in self.data.WT) {
                tags.push('WT.' + tag);
                tags.push(self.data.WT[tag]);
            }
            cache.push({
                element: this,
                argsa: tags
            });
            if (typeof Webtrends != 'undefined') {
                Webtrends.multiTrack(cache.pop());
            }
        }
    }
}

Init = function (t, p) {

    // look for any videos in the markup
    BrightcoveWebtrends = [];

    window.onTemplateLoaded = function(experienceID) {
        BrightcoveWebtrends.push(new BCTrack(experienceID, p));
    };

    //load the API module if its not loaded
    if (typeof APIModules == 'undefined') {
        var s = document.createElement('script');
        s.async = false;
        s.type = "text/javascript";      
        s.src = "https://sadmin.brightcove.com/js/APIModules_all.js"
        var s2 = document.getElementsByTagName("script")[0];
        s2.parentNode.insertBefore(s, s2);
    }
};
Webtrends.registerPlugin('brightcove', Init);