/* handle omniture code */
function isDefined(v)
{
	if(typeof v == 'undefined' || v == null || v == '' || v == 'undefined') return false;
   	else return true;
};

function safeString(s) 
{
	try
    {
    	s = unescape(s);
    	s = s.replace(/\W+/gi,"_").toLowerCase();
    	s = s.replace(/\s+/gi,"_").toLowerCase();
    	s = s.replace(/_+/g,"_");
    }
    catch(e)
    {
    	return s;
    }
    return s;
};

function replaceSpecials(oString)
{
    var nString = oString;
    
    nString = nString.replace(/[^\S ]+/g, ' ');
    nString = nString.replace(/&lt;/g, '');
    nString = nString.replace(/&gt;/g, '');
    nString = nString.replace(/&nbsp;/g, '');
    nString = nString.replace(/&quot;/g, '');
    nString = nString.replace(/&amp;/g, '');
    nString = nString.replace(/&#?\w+;/g, '');
    nString = nString.replace(/\t/g, '');
    nString = nString.replace(/'/g, '');
    nString = nString.replace(/"/g, '');
    nString = nString.replace(/&/g, '');
    nString = nString.replace(/|/g, '');
    nString = nString.replace(/#/g, '');
    nString = nString.replace(/$/g, '');
    nString = nString.replace(/%/g, '');
    nString = nString.replace(/^/g, '');
    nString = nString.replace(/\*/g, '');
    nString = nString.replace(/:/g, '');
    nString = nString.replace(/!/g, '');
    //nString = nString.replace(/\/g, '');
    nString = nString.replace(/</g, '');
    nString = nString.replace(/>/g, '');
    nString = nString.replace(/~/g, '');
    nString = nString.replace(/;/g, '');

    return nString;
};

ReportingEvent = function (event_type, page_name_function, page_url_function, page_variable_function)
{
	this.event_type = event_type; // "PAGE" or "LINK"
	this.generatePageName = page_name_function;
	this.generatePageURL = page_url_function;
	this.setPageVariables = page_variable_function;

	this.data = {}; // holds a copy of the data passed in (for use by methods of this object)
};

dojo.lang.extend(ReportingEvent,
                    {
						populateData : function(data)
						{
							for (var i in data) this.data[i] = data[i];
						},
						clearPageVariables : function() 
						{
							this.data = { }; // reset data passed in by app
						}
					}
				);

ReportControllerHBX = function ()
{
   this.self = this;
   this.intCmp = null;
   this.myvar = "foobar";
   this.last_gateway = "";
   this.stubTimer=null;
   this.callTimer=null;
   this.currentVideoTitle = "foo";
   this.currentVideoCat = "foo";
   this.events = { };
   this.playerController = null;
   
   this.startMark = null;
   this.lastPos = 0;	
   this.duration = 0;
   this.dragTime = 0;
   this.dragThresh = 10;
   
   this.mediaLength = 0;
   this.mark25 = false;
   this.mark50 = false;
   this.mark75 = false;
   this.mark100 = false;
   this.reporting = false;
   this.trackDuration = false;
   
   this.liveTimer = null;
   this.liveDuration = 0;
   
   this.populateEvents();
}

dojo.lang.extend(ReportControllerHBX,
                    {
						//***************reportPlayVideo********************
						reportPlayVideo : function(current, buff)
						{
						 	try 
							{
								if (current.content.length==0) { cont = "playlist"; }
								var thevideo_event = { gateway: current.gateway.name };
								if (current.url)
								{
									thevideo_event.url = current.url;
								} 
								if (current.content)
								{
									thevideo_event.content_record = unescape(current.content.type); 
									if (current.content.typeid)
										thevideo_event.content_recordid = unescape(current.content.typeid);
									thevideo_event.content_id = unescape(current.content.id)
									thevideo_event.content_title = unescape(current.content.title);									
								}		
								if (current.title)        thevideo_event.video_title = unescape(current.title);
								if (current.id)           thevideo_event.video_id = current.id;
								if (current.artistName)   thevideo_event.artist_name = unescape(current.artistName);
								if (current.artistId)     thevideo_event.artist_id = current.artistId;
								if (current.label)        thevideo_event.label = unescape(current.label);
								if (current.agreement)    thevideo_event.label_gov_id = current.agreement;
								if (current.vidtype)      thevideo_event.vidtype = current.vidtype;
								if (current.vidtypename)  thevideo_event.vidtypename = unescape(current.vidtypename);
                                thevideo_event.trackingString = current.trackingString;                                
								
								clearTimeout(this.callTimer);
								var thisObj = this;
			                    this.callTimer = setTimeout(function() { thisObj.HBXCallStub(thevideo_event); },2000); 
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: reportPlayVideo() " + e.message); 
							}
						},
						//***************reportEndVideo********************
						reportEndVideo : function()
						{
						 	try 
							{
								if (this.currentVideoTitle != "foo")
								{
									//track the media
									this.hbxMediaTracking(this.currentVideoTitle, 'stop', this.duration - this.dragTime, this.mediaLength, 'ctvBBP', '1.5');

									this.currentVideoTitle = "foo";
									this.mediaLength = 0;
									
									this.lastPos = 0;	
								    this.duration = 0;
								    this.dragTime = 0;
	
									this.mark25 = false;
									this.mark50 = false;
									this.mark75 = false;
									this.mark100 = false;								}
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: reportEndVideo() " + e.message); 
							}
						},
						//***************reportPauseVideo********************
						reportPauseVideo : function()
						{
						 	try 
							{
								if (this.currentVideoTitle != "foo")
								{
									//track the media
									var currentPos = this.playerController.playerControl.controls.currentPosition;
									this.hbxMediaTracking(this.currentVideoTitle, 'pause', currentPos, this.mediaLength, 'ctvBBP', '1.5');
								}
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: reportPauseVideo() " + e.message); 
							}
						},
						//***************reportProgressVideo********************
						reportProgressVideo : function()
						{
						 	try 
							{
								if (this.mediaLength == 0) return;
								if (this.reporting) return;
								if (this.currentVideoTitle == "foo") return;
								if (this.trackDuration == false) return;

								this.reporting = true;
								
								//track the media
								var currentPos = this.playerController.playerControl.controls.currentPosition;
								if (currentPos > 0)
								{
									var gap = currentPos - this.lastPos;
									if (gap > this.dragThresh)
									{
										this.dragTime += gap;
									}
								this.duration += Math.abs(gap);
								this.lastPos = currentPos;
								}
								
								var pcnt = (this.duration - this.dragTime)/this.mediaLength;
	
								if ( pcnt >= 0.25 && !this.mark25)
								{
									this.mark25 = true;
									this.hbxMediaTracking(this.currentVideoTitle, 'playp', this.duration - this.dragTime, this.mediaLength, 'ctvBBP', '1.5');
								}
								else if ( pcnt >= 0.5 && !this.mark50)
								{
									this.mark50 = true;
									this.hbxMediaTracking(this.currentVideoTitle, 'playp', this.duration - this.dragTime, this.mediaLength, 'ctvBBP', '1.5');
								}
								else if ( pcnt >= 0.75 && !this.mark75)
								{
									this.mark75 = true;
									this.hbxMediaTracking(this.currentVideoTitle, 'playp', this.duration - this.dragTime, this.mediaLength, 'ctvBBP', '1.5');
								}
								else if ( pcnt >= 0.95 && !this.mark100)
								{
									this.mark100 = true;
									this.hbxMediaTracking(this.currentVideoTitle, 'playp', this.duration - this.dragTime, this.mediaLength, 'ctvBBP', '1.5');
								}
								
								this.reporting = false;
							} 
							catch(e) 
							{
								this.reporting = false;
								dojo.debug("EXCEPTION: reportProgressVideo() " + e.message); 
							}
							
						},
						//***************startReportLiveProgress********************
						startReportLiveProgress : function()
						{
						 	try 
							{
								clearTimeout(this.liveTimer);
								var thisObj = this;
								this.liveDuration = 0;
								this.liveTimer = setTimeOut(function() { thisObj.TrackingLive(); },60000);
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: reportProgressVideo() " + e.message); 
							}
							
						},
						//***************Tracking Live********************
						TrackingLive : function()
						{
						 	try 
							{
								clearTimeout(this.liveTimer);
								var thisObj = this;
								this.liveDuration += 60000;
								this.hbxMediaTracking(this.currentVideoTitle, 'playp', this.liveDuration, 1000*60*120, 'ctvBBP', '1.5');							
								this.liveTimer = setTimeOut(function() { thisObj.TrackingLive(); },60000);
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: reportProgressVideo() " + e.message); 
							}
							
						},

						//***************HBXCallStub********************
						HBXCallStub : function(vidE)
						{
							try 
							{
								var theVid=vidE;
								if(this.playerController.playerControl.controls.currentPosition>2)
								{
									if (theVid.video_id == this.playerController.videoEvent.id)
									{
									    var error_vid = this.playerController.playerControl.currentMedia.getItemInfo("ERROR_VID");
									    var error_country = this.playerController.playerControl.currentMedia.getItemInfo("ERROR_COUNTRY");
									    var error_auth = this.playerController.playerControl.currentMedia.getItemInfo("ERROR_AUTH");
									    var error_expired = this.playerController.playerControl.currentMedia.getItemInfo("ERROR_EXPIRED");
									    var error_badvid = this.playerController.playerControl.currentMedia.getItemInfo("ERROR_BADVID");
									    var video_content_type = this.playerController.playerControl.currentMedia.getItemInfo("video_content_type");
										
							            if(isDefined(error_vid))
										{
							               theVid.errorstate = true;
							               theVid.error_vid = error_vid;
							               if(isDefined(error_auth))
										   {
							                  theVid.errortype = "no_auth";
							               }
							               if(isDefined(error_country))
										   {
							                  theVid.errortype = "country_block";
							                  theVid.error_country = error_country;
							               }
							               if(isDefined(error_expired))
										   {
							                  theVid.errortype = "expired";
							               }
							               if(isDefined(error_badvid))
										   {
							                  theVid.errortype = "badvid";
							               }
							            }     
							
							            if(isDefined(video_content_type))
										{
							               theVid.video_content_type = video_content_type;
							            }
										   
										/******************************************************/
										if (!this.playerController.playIntro && !this.playerController.adPlaying)
										{
											this.makeHBXCall("video_play", theVid);
									   	}
										/******************************************************/
									}	 
								} 
							  	else if (this.playerController.playerControl.controls.currentPosition < 2)
								{
									clearTimeout(this.callTimer);
									var thisObj = this;
			                    	this.callTimer = setTimeout(function() { thisObj.HBXCallStub(theVid); },2000); 
							 	}
							} 
							catch(e) 
							{
								dojo.debug("EXCEPTION: HBXCallStub() " + e.message); 
							}
						},												
						//***************makeHBXCall********************
						makeHBXCall : function (event_id, data_object) 
						{
							if (typeof(this.events[event_id]) == "undefined") return false;

							// setup page variables
							this.events[event_id].populateData(data_object);
							this.events[event_id].setPageVariables();
							
							
							if (event_id == 'video_play')
							{							
								//try report a end on last video
								this.reportEndVideo();
								this.trackDuration = true;
								var contentCat = g_site + this.events[event_id].generatePageURL();
								var pageName = this.events[event_id].generatePageName();
								
								this.currentVideoTitle = contentCat + '/' + pageName;
                                this.currentVideoCat = contentCat;
								if (data_object.live)
									this.mediaLength = 0;
								else
									this.mediaLength = this.playerController.playerControl.currentMedia.duration;  //convert into ms

								_hbVisitorSeg(g_popGroup, replaceSpecials(pageName), replaceSpecials(contentCat));
								
								//track the media
								this.hbxMediaTracking(this.currentVideoTitle, 'play', 0, this.mediaLength, 'ctvBBP', '1.5');
								
								if (data_object.live)
									this.startReportLiveProgress();
							}
						}
					}						
				);
				
dojo.lang.extend(ReportControllerHBX,
                    {
						populateEvents : function()
						{
							//Video Play
							this.events['video_play'] = new ReportingEvent(
								"PAGE",						
								function() { // generatePageName()									
									var name = "";
									if (this.data['video_title']) name = this.data['video_title'];					
						         	return name;
								},
								function() { // generatePageURL()
							      if(isDefined(this.data['errorstate'])){
							         if(this.data['errorstate'] == true){
							            var pagebase = "/error/error_";
							
							            if(isDefined(this.data['errortype'])) {
							               pagebase += this.data['errortype']; 
							            }
							
							            if(isDefined(this.data['error_country'])) {
							               pagebase += "_" + this.data['error_country'];
							            }					
							            return pagebase;
							         }
							      }
								  	var url_components = [''];
                                    if (this.data['trackingString'] == "")  //oldway of tracking
                                    {
    								  	/*
                                                                                                if (isDefined(this.data['gateway']))        url_components.push(this.data['gateway']);
    								  	if (isDefined(this.data['content_recordid'])) url_components.push('s' + this.data['content_recordid']);
    									if (isDefined(this.data['content_record'])) url_components.push(this.data['content_record']);
    									if (isDefined(this.data['content_id']))  url_components.push('e' + this.data['content_id']);
    									if (isDefined(this.data['content_title']))  url_components.push(this.data['content_title']);
    									if (isDefined(this.data['video_id']))  url_components.push('c' + this.data['video_id']);
                                                                                                        */
    								  	var showStr = "s";
                                        if (isDefined(this.data['content_recordid'])) showStr += this.data['content_recordid'];
                                        if (isDefined(this.data['content_record'])) showStr += "_" + this.data['content_record'];
                                        url_components.push(showStr);
                                        url_components.push("sn0");
                                        url_components.push("ep0");
                                        url_components.push("na");
                                        if (isDefined(this.data['video_id']))  url_components.push('c' + this.data['video_id']);
                                        if (isDefined(this.data['video_title'])) url_components.push(this.data['video_title']);
                                        if (isDefined(this.data['content_id']))  url_components.push('e' + this.data['content_id']);
                                        if (isDefined(this.data['content_title']))  url_components.push(this.data['content_title']); 
                                        if (isDefined(this.data['gateway'])) url_components.push(this.data['gateway']);
                                    }
                                    else 
                                    {
                                        var arr = this.data['trackingString'].split("|");
                                        url_components.push("s" + arr[0] + "_" + arr[1]);
                                        url_components.push("sn" + arr[2]);
                                        url_components.push("ep" + arr[3]);
                                        url_components.push(arr[4]);
                                        if (isDefined(this.data['video_id']))  url_components.push('c' + this.data['video_id']);
                                        if (isDefined(this.data['video_title'])) url_components.push(this.data['video_title']);
                                        if (isDefined(this.data['content_id']))  url_components.push('e' + this.data['content_id']);
                                        if (isDefined(this.data['content_title']))  url_components.push(this.data['content_title']); 
                                        if (isDefined(this.data['gateway'])) url_components.push(this.data['gateway']);
                                    }			
									return (url_components.join('/'));
								},
								function() { // setPageVariables()
									return;
								}
							); // END: video_play
						}
					}
				);

dojo.lang.extend(ReportControllerHBX,
                    {
						hbxMediaTracking : function (hbxFileName, eventName, hbxCurrentPos, hbxEndPos, playerName, playerVersion)
						 {
							var pos = Math.round(hbxCurrentPos * 1000) - 1;
							if (pos < 0) pos = 0;
							

                            
							var fn = replaceSpecials(hbxFileName);
                            var lastPos = fn.lastIndexOf("/");
                            if (lastPos > 0)
                            {
                                var cat = fn.substring(0,lastPos);
                                _hbSet('vcon', cat + ';ctvgm/' + cat); 
                            }
                            
                            _hbSet('m.f',fn);
							_hbSet('m.cp',pos);
							_hbSet('m.ep',Math.round(hbxEndPos * 1000));
							_hbSet('m.s',eventName);
							_hbSet('m.cl',playerName);
							_hbSet('m.cv',playerVersion);
							_hbSet('m.tt','e');
							_hbSend();

						},
						videoState8 : function ()
						{
							this.trackDuration = false;
							clearTimeout(this.liveTimer);
						}							
					}
				);

				
var ReporterHBX = new ReportControllerHBX();
				

