
/* File: WNVideoWidgets.js
Contains the following classes:
- WNVideoWidgets
- WNVideoWidget
- WNEventManager
- WNPlayClipObject
- WNFlashVersionObject
- WNPlayClipObject
-- WNFlashVersionObject
*/

/* Class: String
- In JavaScript, we don't have a method to TRIM a string from both sides
- for this we've added a TRIM functionality for our use.
*/
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

/* Class: WNVideoWidgets
- Defines variables needed to manage the widgets.
- Creates variables from value pairs passed in with the javascript include.
- Uses WNFlashVersionObject's CompareVersions method to determine what to serve.  
*/
var WNVideoWidgets = function()
{
    var redirectURL                 = window.location;
    var doctitle                    = document.title.slice(0, 47) + " - Flash Player Installation";
    this.installParams              = "?MMredirectURL="+redirectURL+"&MMdoctitle="+doctitle+"&MMplayerType=";
    this.isIE                       = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
    this.isMac                      = (navigator.appVersion.toLowerCase().indexOf("mac") != -1) ? true : false;
    this.isOpera                    = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;  
    this.landingPage                = wnWidgetsFlashVars.landingPage;
	this.objClip                    = new Object();
	this.canvasObjectFlashVars		= "";
    var q                           = this.landingPage.lastIndexOf("?");
    var amp                         = this.landingPage.lastIndexOf("&");
    var len                         = this.landingPage.length;
   
    if(this.validateString(this.landingPage))
    {
        if(q > 0)
        {
            if(q == len || amp == len)
            {
                this.landingPage += "";
            }
            else
            {
                this.landingPage += "&";
            }
        }    
        else
        {
            this.landingPage += "?";
        }      
    }   
       
    this.major                      = 8;
    this.minor                      = 0;
    this.revision                   = 0;
    this.flaVersionObject           = new WNFlashVersionObject();
    this.hasFullScreenRequirements  = this.flaVersionObject.CompareVersions(9, 0, 28);
    this.canvasObject               = new Object();
    
    //flashplayer version 9,0,16 has a documented memory leak, force upgrade.
    if(this.flaVersionObject.majorVersion == "9" && this.flaVersionObject.minorVersion == "0" && this.flaVersionObject.revision == "16")
    {
		this.flashPlayer = "autoInstall";
	}
	else if(this.flaVersionObject.CompareVersions(this.major, this.minor, this.revision))
    {
        this.flashPlayer = "widget";
    }
    else if(this.flaVersionObject.CompareVersions(6, 0, 65))
    {
        this.flashPlayer = "autoInstall";
    }
    else
    {
        this.flashPlayer = "none";
    }

	//add browser unload event listener in case we need to capture the video end/browser close etc events for reporting
	/*
    if(window.addEventListener)
    {
        window.addEventListener("beforeunload", this.FireReportingBeacon, false);
    }
    else 
    {
        window.onbeforeunload = this.FireReportingBeacon;
    } 
	*/
}

 /* Method: GetEmbedCode
 - returns clip id for use by embed code window
 */
WNVideoWidgets.prototype.GetEmbedCodeClipId = function ()
{
	return wnVideoWidgets.objClip.objClip.id;
}

 /* Method: validateString
 - receives string
 - returns boolean indicating whether it is valid
 */
WNVideoWidgets.prototype.validateString = function(str)
{
    if(str == "") return false;
    if(str == " ") return false;
    if(str == "undefined") return false;
    if(str == undefined) return false;
    if(str == null) return false;
    if(str == "null") return false;
    return true;
}


WNVideoWidgets.prototype.StripWhitespace = function(strText)
{
    var strippedText    = strText.replace(/\s{3,}/g, "  ");
    return strippedText;
}


WNVideoWidgets.prototype.Strip = function(filter, str)
{
    var i, curChar;
    var retStr = '';
    for (i=0; i < str.length; i++) 
    {
	    curChar = str.charAt(i);
	    if (filter.indexOf(curChar)<0)
		    retStr += curChar;	
    }
    return retStr;
}
    
    
WNVideoWidgets.prototype.ValidateEmail = function(strText, isRecipient)
{
    var EmailPattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var arrEmailValues  = new Array;
    if(isRecipient)
    {
        strText             = strText.replace(/,/g, ";");
        arrEmailValues      = strText.split(";"); 
	}
	
    if (arrEmailValues.length >= 1)
    {
	    //if multiple addresses exist, validate each one
	    for(var i=0; i < arrEmailValues.length; i++)
	    {
		    if (!EmailPattern.test(this.Strip(' ', arrEmailValues[i])))
			    return false;
	    }
    } 
    else 
    {
	    if (!EmailPattern.test(strText)) 
		    return false;	
    }
    return true;
}

WNVideoWidgets.prototype.GetElementPosX = function(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
		{
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

WNVideoWidgets.prototype.GetElementPosY = function(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}

WNVideoWidgets.prototype.DisplaySilverlightScreen = function(clipObj)
{
	// this function is always called from the flash canvas
	// so make a note of its widget type = WNVideoCanvas
	var type = "WNVideoCanvas";
	
	// find the id that link all widgets on the page together
	var arrTemp = clipObj.domId.split("div");
	var collectionId = arrTemp[0].substr(type.length);	
	if(collectionId == undefined || collectionId == "") return false;	// can't go on
	
	var flashDiv = "div" + arrTemp[1];	// this is the div that was passed to the widget constructor parameter
	
	// what is the div tag containing the flash object
	// auto generated by the widget constructor
	for (var i in this.canvasObject)
	{
		if(i == collectionId) var flashObjDiv = this.canvasObject[i];
	}
	if(flashObjDiv == undefined || flashObjDiv == "") return false;		// can't go on
		
	// does the div tag containing the silverlight canvas exist
	var canvasSliverlightDivName = flashObjDiv + "WNSilverlight";
	var canvasSliverlightDiv = document.getElementById(canvasSliverlightDivName);

	if(canvasSliverlightDiv == undefined)
	{
		return this.RenderSilverlightScreen(clipObj,flashDiv,flashObjDiv,canvasSliverlightDivName);
	}
	else
	{
		WNSilverlightTrigger(clipObj,flashObjDiv,canvasSliverlightDivName);
		return true;
	}
}

WNVideoWidgets.prototype.RenderSilverlightScreen = function(clipObj,flashDiv,flashObjDiv,canvasSliverlightDivName)
{
	// this is the div that was passed to the widget constructor parameter
	// the flash object is rendered under it and so we will also render the silverlight object under it
	var videoCanvasDiv = document.getElementById(flashDiv);
	
	// add silverlight div tag 
	var newElem = document.createElement("div");
	newElem.setAttribute("id", canvasSliverlightDivName);
	videoCanvasDiv.appendChild(newElem);

	if(Silverlight.isInstalled('1.0'))
	{
		clipObj[WNConstFlashLayerDivNameKey.toString()] = flashObjDiv;
		clipObj[WNConstSilverlightLayerDivNameKey.toString()] = canvasSliverlightDivName;
		
		// render the silverlight canvas
		WNRenderSilverlight(clipObj);
		return true;  
	}
	else
	{
		var flashObj = document.getElementById(flashObjDiv);
		// prompt use to install silverlight
		videoCanvasDiv.innerHTML = '<a href="http://www.microsoft.com/Silverlight/Install.aspx" target="_blank"><img src="'+ wnSilverlightBaseUrl +'/getSilverlight.jpg" border="0" alt="Get Silverlight" title="Get Silverlight" width="' + flashObj.width + '" height="' + flashObj.height + '"/></a>';
		return false;
	}
}

/* Method: FireReportingBeacon
- Fired onbeforeunload event
- Loops through the canvasObj (which contains the id for the flash object of a given canvas) and fires the FireBeacon (ExternalInterface) method on each canvas.
*/
WNVideoWidgets.prototype.FireReportingBeacon = function()
{
    try
    {
        var canvasObj = wnVideoWidgets.canvasObject; 
        for(var i in canvasObj)
        {
           document.getElementById(canvasObj[i]).FireBeacon();
        }
    }
    catch(e)
    {}
}
    
/* Class: WNVideoWidget 
 - Receives parameters and builds an object containing necessary data to build a widget.
 - Contains method for setting variable values
 - Contains method for writing out the widget
*/

/* Method: WNVideoWidget Constructor
- Takes the following params
    - widget id (WNVideoCanvas, WNGallery, etc)
    - string id for the div in which the widget will be written into
    - key value, value used to distinguish between multiple instances of the same widget type
- Loops throught the wnWidgetsAttribute object to get default values for all of the widget variables 
*/

WNVideoWidget = function(p_id, p_target, p_key)
{
    this.widgetClassType = p_id; 
	this.wnFeedObject = new Object();
	this.wnFeedObject.feeds = new Array();
	
    for(var i in wnWidgetsAttributes[p_id])
    {
        this[i] = wnWidgetsAttributes[p_id][i]; 
    } 
    if(typeof p_key == "undefined") p_key = "";
    this.idKey              = wnVideoWidgets.validateString(p_key)?p_key:"DEFAULT";
    this.widgetType         = p_id;
    this.id                 = p_id + this.idKey;
	
	if (p_target.toLowerCase().indexOf("gallery") > -1) eval("document." + this.id + p_target + "_copy = this");
	
    this.flashVars          = new Object();
    //TB - May be better way to do this.
    for(var i in wnWidgetsFlashVars[p_id])
    {
        this.flashVars[i] = wnWidgetsFlashVars[p_id][i];
    }
    this.flashVars.domId    = this.id + p_target;
    this.flashVars.idKey    = this.idKey;
    this.installFlashVars   = wnWidgetsInstallFlashVars[p_id];
    this.uri;
    this.installUri;
    this.wmode;
    this.targetDiv          = wnVideoWidgets.validateString(p_target)?p_target:"div"+this.id;
    this.SetStylePackage(this.flashVars.defaultStyle);
    if(this.widgetClassType == videoCanvasId) 
    {
        wnVideoWidgets.canvasObject[this.idKey] = this.flashVars.domId;
        this.events                             = new Object();

    }     
}

/* Method: SetPreferredVideoFormat
- strVideoFormat (WMV,FLV,BOTH)
- Validate the Preferred Video Format and replace the global variable "wnPreferredVideoFormat" with new.
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetPreferredVideoFormat = function(strVideoFormat)
{
	switch(strVideoFormat.trim().toUpperCase())
	{
		case "WMV":
		case "FLV":
		case "BOTH":
			wnPreferredVideoFormat = strVideoFormat;
			break;
	}
}

/* Method: SetLiveStream
- strVideoUrl: wmv stream url 
- strHeadline: stream headline
- strAdTag: content classfication for pre-roll and companion ads
- strSummaryImageUrl: summary graphic url
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetLiveStream = function(strUrl, strHeadline, strAdTag, strSummaryImageUrl)
{
	this.flashVars["videoType"]				= "livestream";
	this.flashVars["preferredFormat"]		= "WMV";
	this.flashVars["liveStreamUrl"]         = strUrl;
	this.flashVars["liveStreamHeadline"]	= strHeadline;
	this.flashVars["liveStreamAdTag"]		= strAdTag;
	this.flashVars["liveStreamSummaryImgUrl"]= strSummaryImageUrl;
}

/* Method: SetStylePackage
- Receives the name of a style package
- Passes the parameters from that package to the widget
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetStylePackage = function(p_style)
{
    var stylePackage    = new Object();
    try
    {
        stylePackage        = wnDefaultPackage[this.widgetType][p_style] 
        for(var i in stylePackage)
        {
            this.flashVars[i] = stylePackage[i];
        }
        this.flashVars.defaultStyle = p_style;
    }
    catch(e)
    {}
}

/* Method: To set the widget player type. Possible value from list...
	- EMBEDDED
	- POPUP
	- MINI
	- STANDARD (default - set in WNVideo.asp)
*/
WNVideoWidget.prototype.SetPlayerType = function(type) {
	this.flashVars.playerType = type;
}

/* Method: SetWidth
- Receives specified width and assigns to widget
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetWidth = function(p_wid)
{
    this.flashVars["playerWidth"]           = p_wid;
    this.installFlashVars["playerWidth"]    = p_wid;
}

/* Method: SetHeight
- Receives specified height and assigns to widget
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetHeight = function(p_ht)
{
    this.flashVars["playerHeight"]          = p_ht;
    this.installFlashVars["playerHeight"]   = p_ht;
}

/* Method: SetVariable
- Receives the variable name and value and assigns to the widget
- Must be declared before rendering the widget
*/
WNVideoWidget.prototype.SetVariable = function(p_var, p_value)
{
    this.flashVars[p_var] = p_value;
    for(var i in this.installFlashVars)
    {
        if(i == p_var) this.installFlashVars[i] = p_value;
    }
}
    
           
/* Method: RenderWidget
- Writes out the flash widget based on the attributes of the WNVideoWidget object
- Receives a boolean.  If true, write out flash object tag, otherwise write out html
*/
WNVideoWidget.prototype.RenderWidget = function()
{
    var divId                       = document.getElementById(this.targetDiv);
    var id                          = this.flashVars.domId;
    var hasFlash;
    var uri;
    var swfWidth                    = this.flashVars.playerWidth;
    var swfHeight                   = this.flashVars.playerHeight;
    var flashVars                   = "";
    var isAX                        = wnVideoWidgets.flaVersionObject.isAX;
    this.flashVars.hasFullScreen    = wnVideoWidgets.hasFullScreenRequirements?this.flashVars.hasFullScreen:false;

	if(this.widgetClassType=="WNGraphicsHeader") {
		divId.innerHTML = "<a href='" + this.flashVars.graphicsHeaderClickUrl + "' target='_blank'><img src='" + this.flashVars.graphicsHeaderImageUrl + "' style='border: 0px; width: " + this.flashVars.playerWidth + "px; height: " + this.flashVars.playerHeight + "px;'/></a>";
		return;
	}
	if(this.widgetClassType=="WNGraphicsFooter") {
		divId.innerHTML = "<a href='" + this.flashVars.graphicsFooterClickUrl + "' target='_blank'><img src='" + this.flashVars.graphicsFooterImageUrl + "' style='border: 0px; width: " + this.flashVars.playerWidth + "px; height: " + this.flashVars.playerHeight + "px;'/></a>";
		return;
	}
	
    switch(wnVideoWidgets.flashPlayer)
    {
        case "widget" :
            hasFlash   = true;
            uri        = this.uri + "?divId=" + this.id;
            for(var i in this.flashVars)
            {
                flashVars += i;
                flashVars += "=";
                flashVars += this.flashVars[i];
                flashVars += "&";
            }
        break;
        case "autoInstall" :
            uri        = this.installUri + wnVideoWidgets.installParams;
            uri        += isAX?"ActiveX":"Plugin";
            hasFlash   = true;
            for(var i in this.installFlashVars)
            {
                flashVars += i;
                flashVars += "=";
                flashVars += this.installFlashVars[i];
                flashVars += "&";
            }                
        break;
        default :
            hasFlash   = false;
        break;
    }    
	if(hasFlash)
    {
        if(isAX)
        {
            var elem = '<object id="'+ id +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ swfWidth +'" height="'+ swfHeight +'" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'; 
        }
        else 
        {
            var elem = '<object id='+ id +' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" data=' + uri + ' width="'+ swfWidth +'" height="'+ swfHeight +'">';
        }
       
       elem += '<param name="allowFullScreen" value="true" /><param name="wmode" value="' + this.wmode + '" /><param name="movie" value="' + uri + '" /><param name="quality" value="high" /><param name="allowScriptAccess" value="always" /><param name="bgcolor" value="#FFFFFF" /><param name="FlashVars" value="' + unescape(flashVars) + '" />';
       elem += '<\/object>';
   }
    else
    {
       var fontSize = swfHeight>30?15:Math.floor(swfHeight/2);     
       var elem = '<div id="help" style="text-align:center;font-family:Arial, Verdana;font-size:'+fontSize+'px;color:#000000;font-weight:bold;background-color:#999999;width:'+swfWidth+'px;height:'+swfHeight+'px;padding:'+fontSize+'px;">';
       elem     += '<div id="top"><a style="color:#333333;text-decoration:none;" href="http://www.macromedia.com/go/getflash/" target="_blank">You need to download the latest version of flash player to use this player</a></div><br/>';
       //elem     += '<div id="flashImage"><a href="http://www.macromedia.com/go/getflash/" target="_blank"><img border="0" src="'+ wnVideoWidgets.imagepath +'gfx_getFlashButton.jpg"></div><br/>';
       elem     += '<div id="bottom" style="vertical-align:baseline"><a style="color:#333333;text-decoration:none;" href="' +wnVideoWidgets.helppage +'" target="_blank">Need Help?</a></div>';
       elem     += '</div>';            
    }
	if(this.widgetClassType=="WNVideoCanvas")
	{
		wnVideoWidgets.canvasObjectFlashVars = unescape(flashVars);
		var OverlayElem = '<div id="OverLay" style="display:none;">';
			OverlayElem += '</div>';
			elem = OverlayElem + elem;
			
		WNSilverlightWidgetClass = this;
		divId.innerHTML = elem;

		/*
		if(wnPreferredVideoFormat=="WMV")
		{
			WNSilverlightWidgetClass = this;
			if(Silverlight.isInstalled('1.0'))
			{
				WNRenderSilverlight();
			}
			else
			{
				divId.innerHTML = '<a href="http://www.microsoft.com/Silverlight/Install.aspx" target="_blank"><img src="'+ wnSilverlightBaseUrl +'/getSilverlight.jpg" border="0" alt="Get Silverlight" title="Get Silverlight" width="360" height="308"/></a>';
			}
		}
		else
		{
			divId.innerHTML = elem;
		}
		*/
	}
	else
	{
		divId.innerHTML = elem;
	}
}


/**
* WNGallery customization methods
*/
/**
* GalleryTab customization methods
*/
/**
* SetGalleryTabHeight
*/
WNVideoWidget.prototype.SetGalleryTabHeight = function(ht)
{
    this.flashVars.tabHeight = ht;
}

/**
* SetGalleryTabBackground
*/
WNVideoWidget.prototype.SetGalleryTabBackground = function(color1, color2)
{
    this.flashVars.tabBackgroundColors = color1 + "," + color2;
}


/**
* SetGalleryTabSelectedBackground
* Selects the background color of the selected tab
*/
WNVideoWidget.prototype.SetGalleryTabSelectedBackground = function(color)
{
    this.flashVars.tabBackgroundSelectedColors = color;
}

WNVideoWidget.prototype.SetGalleryTabSelectedBorderColor = function(color)
{
    this.flashVars.tabBackgroundSelectedBorderColor = color;
}

/**
* SetGalleryTabFontColors
*/
WNVideoWidget.prototype.SetGalleryTabFontColors = function(offColor, overColor)
{
    this.flashVars.tabOffFaceColor      = offColor;
    this.flashVars.tabOverFaceColor     = overColor;
}

/**
* SetGalleryTabFontSize
*/
WNVideoWidget.prototype.SetGalleryTabFontSize = function(size)
{
    this.flashVars.tabFontSize = size;
}

/**
* SetGalleryTabInnerBorderColors
*/
WNVideoWidget.prototype.SetGalleryTabInnerBorderColors = function(leftBorderColor, rightBorderColor)
{
    this.flashVars.tabLeftBorderColor   = leftBorderColor;
    this.flashVars.tabRightBorderColor  = rightBorderColor;
}

/**
* SetGalleryTabBorder
*/
WNVideoWidget.prototype.SetGalleryDropDownTabOverBorderColor = function(color)
{
    this.flashVars.dropDownTabOverBorderColor = color;
}

/**
* Gallery DropDown customization methods below
*/
/**
* SetGalleryDropDownBackground
*/
WNVideoWidget.prototype.SetGalleryDropDownBackground = function(color1, color2, color3, color4)
{
    this.flashVars.dropDownBackgroundColors = color1 + "," + color2 + "," + color3 + "," + color4;
}

/**
* SetGalleryDropDownBorderColor
*/
WNVideoWidget.prototype.SetGalleryDropDownBorderColor = function(color)
{
    this.flashVars.dropDownBorderColor = color; 
}

/**
* SetGalleryDropDownShadowColor
*/
WNVideoWidget.prototype.SetGalleryDropDownShadowColor = function(color)
{
    this.flashVars.dropDownDropShadowColor = color;
}

/**
* SetGalleryDropDownInnerBorderColors
*/
WNVideoWidget.prototype.SetGalleryDropDownInnerBorderColors = function(topBorderColor, bottomBorderColor)
{
    this.flashVars.dropDownTopBorderColor       = topBorderColor;
    this.flashVars.dropDownBottomBorderColor    = bottomBorderColor;
}

/**
* SetGalleryDropDownFontColors
*/
WNVideoWidget.prototype.SetGalleryDropDownFontColors = function(offFaceColor, overFaceColor, selectedFaceColor)
{
    this.flashVars.dropDownOffFaceColor         = offFaceColor;
    this.flashVars.dropDownOverFaceColor        = overFaceColor;
    this.flashVars.dropDownSelectedFaceColor    = selectedFaceColor;
}

/**
* SetGalleryDropDownFontSize
*/
WNVideoWidget.prototype.SetGalleryDropDownFontSize = function(size)
{
    this.flashVars.dropDownFontSize = size;
}

/**
* Gallery List Functions
*/

/**
* SetVideoListBackground
* Sets the background colors for the video list background
*/
WNVideoWidget.prototype.SetVideoListBackground = function(color1, color2)
{
    this.flashVars.videoListBackgroundColors = color1 + "," + color2;
}

/**
* SetVideoListBorderColor
* Sets the border color for the video list
*/
WNVideoWidget.prototype.SetVideoListBorderColor = function(color)
{
    this.flashVars.videoListBorderColor = color;
}

/**
* SetVideoListItemInnerBorders
* Sets the colors for the highlight and shadow borders of each list item
*/
WNVideoWidget.prototype.SetVideoListItemInnerBorders = function(highlightColor, shadowColor)
{
    this.flashVars.videoListItemHighlightBorderColor    = highlightColor;
    this.flashVars.videoListItemShadowBorderColor       = shadowColor;
}

/**
* SetVideoListItemFontColors
* Sets the color and highlight color for each video list item
*/
WNVideoWidget.prototype.SetVideoListItemFontColors = function(offFaceColor, overFaceColor)
{
    this.flashVars.videoListItemOffFaceColor    = offFaceColor;
    this.flashVars.videoListItemOverFaceColor   = overFaceColor;
}

/**
* SetVideoListItemFontSize
* Sets the font sizes for the headline and duration fields
*/
WNVideoWidget.prototype.SetVideoListItemFontSizes = function(headlineSize, durationSize)
{
	this.flashVars.videoListItemHeadlineFontSize    = headlineSize;
	this.flashVars.videoListItemDurationFontSize    = durationSize;
}

/**
* SetVideoListImageSize
* Sets the width and height for the video item thumbnail image
*/
WNVideoWidget.prototype.SetVideoListItemImageSize = function(width, height)
{
    this.flashVars.videoListImageWidth  = width;
    this.flashVars.videoListImageHeight = height;
}

/**
* Gallery Video List Navigation Methods
*/
/**
* SetVideoListNavigationHeight
* Sets the height for the video list navigation
*/
WNVideoWidget.prototype.SetVideoListNavigationHeight = function(ht)
{
    this.flashVars.videoListNavigationHeight = ht;
}

/**
* SetVideoListNavigationBackground
* Sets the background colors for the video list navigation
*/
WNVideoWidget.prototype.SetVideoListNavigationBackground = function(color1, color2)
{
    this.flashVars.videoListNavigationBackgroundColors = color1 + "," + color2;
}

/**
* SetVideoListNavigationBorderColor
* Sets the border color for the video list navigation
*/

WNVideoWidget.prototype.SetVideoListNavigationBorderColor = function(color)
{
    this.flashVars.videoListNavigationBorderColor = color;
}

/**
* SetVideoListNavigationColors
* Sets the colors for the previous and next buttons
*/
WNVideoWidget.prototype.SetVideoListNavigationColors = function(offFaceColor, overFaceColor)
{
    this.flashVars.videoListNavigationOffFaceColor  = offFaceColor;
    this.flashVars.videoListNavigationOverFaceColor = overFaceColor;
}

/**
* SetVideoListNavigationPageNumberColors
* Sets the colors for the page numbers
*/
WNVideoWidget.prototype.SetVideoListNavigationPageNumberColors = function(offFaceColor, overFaceColor, selectedFaceColor)
{
    this.flashVars.videoListPageNumberOffColor      = offFaceColor;           
    this.flashVars.videoListPageNumberOverColor     = overFaceColor;
    this.flashVars.videoListPageNumberSelectedColor = selectedFaceColor;
}

/**
* SetVideoListNavigationPageNumberFontSize
* Sets the font size for the video list navigation page numbers
*/
WNVideoWidget.prototype.SetVideoListNavigationPageNumberFontSize = function(size)
{
    this.flashVars.videoListPageNumberFontSize = size;
}

/**
* Gallery Search Methods below
*/
/**
* SetGallerySearchHeight
* Sets the height for the search area
*/
WNVideoWidget.prototype.SetGallerySearchHeight = function(ht)
{
    this.flashVars.gallerySearchFormHeight = ht;
}

/**
* SetGallerySearchBackground
* Sets the background colors for the search area
*/
WNVideoWidget.prototype.SetGallerySearchBackground = function(color1, color2)
{
    this.flashVars.searchBackgroundColors = color1 + "," + color2;
}

/**
* SetGallerySearchFontColors
* Sets the colors for the Search buttons and text
*/
WNVideoWidget.prototype.SetGallerySearchFontColors = function(offFaceColor, overFaceColor)
{
    this.flashVars.searchOffFaceColor   = offFaceColor;
    this.flashVars.searchOverFaceColor  = overFaceColor;
}

/**
* SetGallerySearchFormBorderColor
* Sets the border color for the search form
*/
WNVideoWidget.prototype.SetGallerySearchFormBorderColor = function(color)
{
    this.flashVars.searchFormBorderColor = color;
}

/**
* SetGallerySearchFormFontColor
* Sets the color for the input text in the search form
*/
WNVideoWidget.prototype.SetGallerySearchFormFontColor = function(color)
{
    this.flashVars.searchFormFaceColor = color;
}

/**
* SetGalleryCategory
* Sets the category to load into the category widget
* Must be called before rendering the widget.
*/
WNVideoWidget.prototype.SetGalleryCategory = function(id)
{
    this.flashVars.topVideoCatNo = id;
}

/**
* SetGalleryLeadClip
* Replaces lead clip in the Gallery
*/
WNVideoWidget.prototype.SetGalleryLeadClip = function(id)
{
    this.flashVars.clipId = id;
}

/**
* EnableGalleryControls
* Used
*/
WNVideoWidget.prototype.EnableControls = function(isEnabled)
{
    var widgetType = this.widgetClassType
    switch(widgetType)
    {
        case "WNGallery" :        
            var thisGallery = document.getElementById(this.flashVars.domId);
            thisGallery.EnableControls(isEnabled);
        break;
    }
}

/**
* Video Canvas Functions
*/

/**
* SetReportingKeywords
*/
WNVideoWidget.prototype.SetReportingKeywords = function(keyword)
{
    this.flashVars.reportingKeywords = keyword;
}

/**
* SetAdvertisingKeywords
*/
WNVideoWidget.prototype.SetAdvertisingKeywords = function(keyword)
{
    this.flashVars.advertisingKeywords = keyword;
}

/**
* AddUploadCategory
*/
WNVideoWidget.prototype.AddUploadCategory = function(categories)
{
	this.flashVars.categories = categories;
}

/**
* SetAdvertisingZone
*/
WNVideoWidget.prototype.SetAdvertisingZone = function(zone)
{
    this.flashVars.advertisingZone = zone;
}

/**
* EnableEmail
*/
WNVideoWidget.prototype.EnableEmail = function(isEnabled)
{
    this.flashVars.hasEmail = isEnabled;
}

/**
* EnableHelp
*/
WNVideoWidget.prototype.EnableHelp = function(isEnabled)
{
    this.flashVars.hasHelp = isEnabled;
}

/**
* EnableClosedCaption
*/
WNVideoWidget.prototype.EnableClosedCaption = function(isEnabled)
{
    this.flashVars.hasCC = isEnabled;
}

/**
* EnableFullScreen
*/
WNVideoWidget.prototype.EnableFullScreen = function(isEnabled)
{
    this.flashVars.hasFullScreen = isEnabled;
}

/**
* SetErrorMessage
*/
WNVideoWidget.prototype.SetErrorMessage = function(errorMessage)
{
    this.flashVars.errorMessage = errorMessage;
}

/**
* SetVideoScaleStyle
*/
WNVideoWidget.prototype.SetVideoScaleStyle = function(pct)
{
    if(pct.toLowerCase == "scaletofit") pct = "0";
    this.flashVars.playAtActualSize = pct;
}

/**
* SetVideoSmoothingMode
*/
WNVideoWidget.prototype.SetVideoSmoothingMode = function(smoothingMode)
{
    this.flashVars.smoothingMode = smoothingMode;
}

/**
* EnableAutoStart
*/
WNVideoWidget.prototype.EnableAutoStart = function(isEnabled)
{
    this.flashVars.isAutoStart = isEnabled;
}
/**
* EnableMute
*/
WNVideoWidget.prototype.EnableMute = function(isEnabled)
{
    this.flashVars.isMute = isEnabled;
}

/**
* SetSummaryGraphicScaleStyle
*/
WNVideoWidget.prototype.SetSummaryGraphicScaleStyle = function(style)
{
    this.flashVars.summaryGraphicScaleStyle = style;
}

/**
* SetCanvasBackgroundColors
*/
WNVideoWidget.prototype.SetCanvasBackgroundColors = function(outerColor, innerColor)
{
    this.flashVars.backgroundColors         = outerColor + "," + innerColor + "," + innerColor + "," + outerColor; 
    this.flashVars.controlsBackgroundColors = outerColor + "," + innerColor;
}

/**
* SetVideoControlsInnerBorderColors
*/
WNVideoWidget.prototype.SetVideoControlsInnerBorderColors = function(leftBorder, rightBorder)
{
    this.flashVars.controlsButtonLeftBorderColor = leftBorder;
    this.flashVars.controlsButtonRightBorderColor = rightBorder;
}

/**
* SetVideoControlsColors
*/
WNVideoWidget.prototype.SetVideoControlsColors = function(offFaceColor, overFaceColor)
{
    this.flashVars.controlsOffFaceColor     = offFaceColor;
    this.flashVars.controlsOverFaceColor    = overFaceColor;
}

/**
* SetVolumeSliderColors
*/
WNVideoWidget.prototype.SetVolumeSliderColors = function(offFaceColor, overFaceColor)
{
    this.flashVars.volumeSliderOffColor     = offFaceColor;
    this.flashVars.volumeSliderOverColor    = overFaceColor;
}

/**
* SetVideoSliderColors
*/
WNVideoWidget.prototype.SetVideoSliderColors = function(backgroundColor, loadColor, progressColor)
{
    this.flashVars.videoSliderBackgroundColor           = backgroundColor;
    this.flashVars.videoSliderLoadIndicatorColor        = loadColor;
    this.flashVars.videoSliderProgressIndicatorColor    = progressColor;
}

/**
* SetVideoSliderKnobColors
*/
WNVideoWidget.prototype.SetVideoSliderKnobColors = function(backgroundColor, borderColor, offFaceColor, overFaceColor)
{
    this.flashVars.videoSliderKnobBackgroundColors  = backgroundColor;
    this.flashVars.videoSliderKnobBorderColor       = borderColor;
    this.flashVars.videoSliderKnobOffFaceColor      = offFaceColor;
    this.flashVars.videoSliderKnobOverFaceColor     = overFaceColor;
}

/**
* SetCanvasOverlayBackgroundColor
*/
WNVideoWidget.prototype.SetCanvasOverlayBackgroundColor = function(color)
{
    this.flashVars.overlayBackgroundColors = color;
}

/**
* SetOverlayFontColors
*/
WNVideoWidget.prototype.SetCanvasOverlayFontColors = function(offFaceColor, overFaceColor, inputColor)
{
    this.flashVars.overlayOffFaceColor  = offFaceColor;
    this.flashVars.overlayOverFaceColor = overFaceColor;
    this.flashVars.emailInputFaceColor  = inputColor;
}

/**
* SetCanvasOverlayFormFieldColors
*/
WNVideoWidget.prototype.SetCanvasFormFieldBackgroundColor = function(color)
{
    this.flashVars.emailFormFieldColors = color;
}

/**
* SetCanvasOverlayErrorColors
*/
WNVideoWidget.prototype.SetCanvasOverlayErrorColors = function(textColor, borderColor)
{
    this.flashVars.emailErrorMessageFaceColor   = textColor;
    this.flashVars.emailErrorBorderColor        = borderColor;    
}

/**
* SetInfoPaneFontSizes
*/
WNVideoWidget.prototype.SetInfoPaneFontSizes = function(headlineSize, summarySize, durationSize)
{
    this.flashVars.headlineFontSize = headlineSize;
    this.flashVars.summaryFontSize  = summarySize;
    this.flashVars.durationFontSize = durationSize;    
}

/**
* SetInfoPaneFontColors
*/
WNVideoWidget.prototype.SetInfoPaneFontColors = function(headlineColor, summaryColor, durationColor)
{
    this.flashVars.headlineColor    = headlineColor;
    this.flashVars.summaryColor     = summaryColor;
    this.flashVars.durationColor    = durationColor;
}

/**
* EnableInfoPaneHeadline
*/
WNVideoWidget.prototype.EnableInfoPaneHeadline = function(isEnabled)
{
    this.flashVars.hasHeadline = isEnabled;
}

/**
* EnableInfoPaneSummary
*/
WNVideoWidget.prototype.EnableInfoPaneSummary = function(isEnabled)
{
    this.flashVars.hasSummary = isEnabled;
}

/**
* EnableInfoPaneDuration
*/
WNVideoWidget.prototype.EnableInfoPaneDuration = function(isEnabled)
{
    this.flashVars.hasDuration = isEnabled;
}

/**
* EnableInfoPaneImage
*/
WNVideoWidget.prototype.EnableInfoPaneImage = function(isEnabled)
{
    this.flashVars.hasImage = isEnabled;
}

/**
* SetInfoPaneImageProperties
*/
WNVideoWidget.prototype.SetInfoPaneImageProperties = function(imageWidth, imageHeight, imagePosition)
{
    this.flashVars.imageWidth       = imageWidth;
    this.flashVars.imageHeight      = imageHeight;
    this.flashVars.imagePosition    = imagePosition;
}

/**
* SetInfoPaneBackgroundColors
*/
WNVideoWidget.prototype.SetInfoPaneBackgroundColors = function(outerColor, innerColor)
{
    this.flashVars.backgroundColors = outerColor + "," + innerColor + "," + innerColor + "," + outerColor;
}

/**
* SetHeadlineFontSize
*/      
WNVideoWidget.prototype.SetHeadlineFontSize = function(fontSize)
{
    this.flashVars.fontSize = fontSize;
}

/**
* SetHeadlineFontColor
*/
WNVideoWidget.prototype.SetHeadlineFontColor = function(fontColor)
{
    this.flashVars.offFaceColor = fontColor;
}

/**
* SetHeadlineBackgroundColors
*/
WNVideoWidget.prototype.SetHeadlineBackgroundColors = function(color1, color2)
{
    this.flashVars.backgroundColors = color1 + "," + color2;
}

WNVideoWidget.prototype.NewCategory = function(catId, clipId)
{
    document.getElementById(this.flashVars.domId).wnNewCategory({catId:catId, clipId:clipId});
}

/**
* Expose Play/Pause toggle
*/
WNVideoWidget.prototype.PlayPause = function()
{
    document.getElementById(this.flashVars.domId).playPause();
}
WNVideoWidget.prototype.Play = function()
{
    document.getElementById(this.flashVars.domId).playMedia();
}
WNVideoWidget.prototype.Pause = function()
{
    document.getElementById(this.flashVars.domId).pauseMedia();
}


/**
*
*/
WNVideoWidget.prototype.ShowEmail = function()
{
    document.getElementById(this.flashVars.domId).showEmail();
}

WNVideoWidget.prototype.ShowSummary = function()
{
    document.getElementById(this.flashVars.domId).showSummary();
}

WNVideoWidget.prototype.ShowClosedCaption = function()
{
    document.getElementById(this.flashVars.domId).showClosedCaption();
}

WNVideoWidget.prototype.Mute = function()
{
    document.getElementById(this.flashVars.domId).muteToggle();
}

WNVideoWidget.prototype.LaunchHelp = function()
{
    document.getElementById(this.flashVars.domId).launchHelp();
}

////// ADDED - 02/28/2008 - TransportControls - Starts
WNVideoWidget.prototype.SetVolume = function(intVal)
{
	document.getElementById(this.flashVars.domId).setVolume(intVal);
}
//Disable Transport
WNVideoWidget.prototype.disableDefaultTransport = function()
{
	this.flashVars["disableTransport"] = "true";
	for(var i in this.installFlashVars)
	{
		if(i == "disableTransport") this.installFlashVars["disableTransport"] = "true";
	}
}
//Use Icons or Text for Video Controls.	
WNVideoWidget.prototype.showVideoIcons = function(isShowIcon)
{
	this.flashVars["isShowIcon"] = isShowIcon;
	for(var i in this.installFlashVars)
	{
		if(i == "isShowIcon") this.installFlashVars["isShowIcon"] = isShowIcon;
	}
}
//Set Video Time externally
WNVideoWidget.prototype.setVideoTime = function(timeVal)
{
	document.getElementById(this.flashVars.domId).ExternalSetVideoTime(timeVal);		
}
//Set Video Position externally
WNVideoWidget.prototype.setVideoPosition = function(vidPosition)
{
	document.getElementById(this.flashVars.domId).ExternalSetVideoPosition(vidPosition);		
}
//External Timer Object for Video
WNVideoWidget.prototype.getTimerObject = function()
{
	return document.getElementById(this.flashVars.domId).ExternalGetTimerObject();
}
////// ADDED - 02/28/2008 - TransportControls - Ends

////// ADDED - 02/28/2008 - MRSS - Starts
/* Method: ValidateURL 
* <ul>Generic Method to Validate URLs.</ul>
*/
WNVideoWidget.prototype.ValidateURL = function(url)
{
	var v = /^[A-Za-z]+:\/\/+[A-Za-z0-9-_]+\.[A-Za-z0-9-_%&\?\/.=:]+$/;
	if (v.test(url))
	{
        return true;
    }
	else
	{
		return false;
	}
}
/* Method: AddFeed 
* <ul>Creates a feed object.</ul>
*/
WNVideoWidget.prototype.AddFeed = function(name, source, type, url, priority, contentClass, adOwner, adSplit, policyFile, providerType)
{
	if(!this.wnFeedObject.hasFeeds)
	{
		this.wnFeedObject.hasFeeds = true;
	}
	var feedObj = new Object();
	//if(this.ValidateURL(url))
	//{
		feedObj.name = name;
		feedObj.source = source;
		feedObj.type = type;
		feedObj.url = url;
		feedObj.priority = priority;
		feedObj.contentClass = contentClass;
		feedObj.adOwner = adOwner;
		feedObj.adSplit = adSplit;
		feedObj.policyFile = policyFile;
		feedObj.providerType = providerType;
		this.wnFeedObject.feeds.push(feedObj); 
	//}
	//else
	//{
	//	alert("Provided MRSS source is not valid:\n"+url);
	//}
}
/* Method: SendFeedObject 
* <ul>Returns the feed object to flash.</ul>
*/
WNVideoWidget.prototype.SendFeedObject = function()
{
	tmpFeedObject = new Object;
	tmpFeedObject.hasFeeds = this.wnFeedObject.hasFeeds;
	tmpFeedObject.feeds = new Array();
	for (i=0; i< this.wnFeedObject.feeds.length; i++) {
        tmpFeedObject.feeds.push(this.wnFeedObject.feeds[i]);
    }

	delete this.wnFeedObject;
	return tmpFeedObject;
}
////// ADDED - 02/28/2008 - MRSS - Ends

/* Class: WNFlashVersionObject - determines version information of the user's Flash plugin/activeX control
    - constructor
    - compare versions method
*/
WNFlashVersionObject = function()
{
    this.majorVersion = 0;
    this.minorVersion = 0;
    this.revision     = 0;
    this.isAX         = false;
    if(navigator.plugins != null && navigator.plugins.length > 0) 
    {       
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) 
        {
            var swVer2              = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription    = navigator.plugins["Shockwave Flash" + swVer2].description;
            descArray               = flashDescription.split(" ");
            tempArrayMajor          = descArray[2].split(".");
            this.majorVersion       = tempArrayMajor[0];
            this.minorVersion       = tempArrayMajor[1];
            tempArrayMinor          = (descArray[3] != "")?descArray[3].split("r"):descArray[4].split("r");
            this.revision           = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
         }
    }        
    else if(window.ActiveXObject) 
    {
        this.isAX                   = true;
        var versionArray            = this.GetActiveXVersion();
        this.majorVersion           = versionArray[0];
        this.minorVersion           = versionArray[1];
        this.revision               = versionArray[2];
    }         
}

/* Method: CompareVersions
 - Receives required major, require minor and required revision
 - Returns true if the user has a sufficient version of the player and false if it does not
*/
WNFlashVersionObject.prototype.CompareVersions = function(reqMajor, reqMinor, reqRevision)
{
    if(this.majorVersion > reqMajor)return true;
    if(this.majorVersion < reqMajor)return false;
    if(this.minorVersion > reqMinor)return true;
    if(this.minorVersion < reqMinor)return false;
    if(this.revision >= reqRevision)return true;
    return false;        
}
    
/**
* GetActiveXVersion method
* Ideally, there would be no use for this method.  We should be able to get the version array with the following 2 lines:
*  - var ax    = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
*  - arr       = ax.GetVariable("$version").split(" ")[1].split(",");
* A bug in Flash Versions [6,0,r21], [6,0,r23] and [6,0,r29] causes IE to crash when the GetVariable method is performed on the ActiveXObject. (even with a try/catch)
* We get around this by trying to set the FlashPlayer 6 object and then attempting to set its AllowScriptAccess property to true.  This property is only available for Flash Version [6,0,r47] and later.     
*/    
WNFlashVersionObject.prototype.GetActiveXVersion    = function()
{
    var arr = new Array();
    try
    {
        var ax6                 = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
        ax6.AllowScriptAccess   = "always";
    }
    catch(e)
    {
        if(ax6 != null)
        {
            arr[0]  = 6;
            arr[1]  = 0;
            arr[2]  = 21;
            return arr;
        }
    }
    try
    {
        ax  = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        arr = ax.GetVariable("$version").split(" ")[1].split(",");
        return arr;
    }
    /**
    * Not overly interested in whether or not the user has a version less than 6 because you can't do auto-install and we will not be publishing movies 
    * less  than 8.
    */
    catch(e)
    {
        arr[0] = arr[1] = arr[2] = 0;
        return arr;
    }      
}

/* Class: WNAdWidget
Creates an ad widget and registers it for Canvas events.
 - p_adWidgetSize
 - p_callBackFunctionName
 - p_groupId
*/
WNAdWidget = function(p_adWidgetSize, p_callBackFunctionName, p_groupId)
{
    this.widgetClassType    = "WNAdWidget";    
    this.idKey              = wnVideoWidgets.validateString(p_groupId)?p_groupId:"DEFAULT";
    this.widgetName         = p_adWidgetSize;
    this.size               = p_adWidgetSize;
    this.id                 = p_adWidgetSize + this.idKey;
    
    //register for events
    evntMgr.Register({lstnr:this, evnt:"NewClip",       func:p_callBackFunctionName, idKey:this.idKey});
    evntMgr.Register({lstnr:this, evnt:"NewMedia",      func:p_callBackFunctionName, idKey:this.idKey});
    evntMgr.Register({lstnr:this, evnt:"MediaEnded",    func:p_callBackFunctionName, idKey:this.idKey});
    evntMgr.Register({lstnr:this, evnt:"NewCompanionAd",func:"SetWNCompanionAd",     idKey:this.idKey}); 
}

/* Method: SetTarget
Renders the widget in the specified DOM element.
*  - p_targetElement - DOM element to be written to using the innerHTML method
*/
WNAdWidget.prototype.SetTarget = function(p_targetElement)
{
    this.targetElement = p_targetElement;
}

WNAdWidget.prototype.SetTransitional = function(p_bln)
{
    this.isTransitional = p_bln;
}

WNAdWidget.prototype.SetHeight = function(p_height)
{
    this.height = p_height;
}

WNAdWidget.prototype.SetWidth = function(p_width)
{
    this.width = p_width;
}

WNAdWidget.prototype.SetWNAdsize = function(p_adSize)
{
    this.isTransitional = p_adSize;
}

/* Method: HandleWorldnowAd 
- Handles worldnow ads with loc/nat split.
*/
WNAdWidget.prototype.HandleWorldnowAd = function(p_evtObj)
{
    var objClip = p_evtObj.objClip; 
    var adCallDomain = objClip.adCallDomain;

	//only refresh the ad widgets for when a content clip loads
    if (p_evtObj.evnt == "NewClip" && !(this.isTransitional))
    {  
		var adUrl       = "http://" + adCallDomain + "/global/ad.asp?type=single&src1=" + objClip.preRollOwner + "&spct1=" + objClip.preRollSplitPct + "&sz1=" + this.size + "&cls1=" + objClip.adTag + "&rndNumOverride=" + objClip.rndNum;
        //var adUrl       = "http://" + adCallDomain + "/global/ad.asp?type=single&src1=loc&spct1=100&sz1=" + this.size + "&cls1=" + objClip.adTag + "&rndNum=" + objClip.rndNum;
        var iframeHtml  = "<iframe id='iframe" + this.id + "' src='" + adUrl + "' width='" + this.width + "' height='" + this.height + "' frameborder='0' scrolling='no' allowTransparency='true' marginwidth='0' marginheight='0'></iframe>";
        this.targetElement.innerHTML = iframeHtml;
    }
     
    if (p_evtObj.evnt == "MediaEnded")
    {
        //find ads that need to be closed after pre-roll|bookends
        if ((objClip.isPreRoll || objClip.isFlashVideoBookend) && this.isTransitional)
        {
            this.targetElement.innerHTML = "";
            //enable gallery controls 
            videoGallery.EnableControls(true);
        }   
    }
    
    if (p_evtObj.evnt == "NewMedia")
    {
        //find ads that need to be closed after pre-roll|bookends
        if (!(objClip.isPreRoll || objClip.isFlashVideoBookend) && this.isTransitional)
        {
            this.targetElement.innerHTML = "";
            //enable gallery controls 
            videoGallery.EnableControls(true);
        }   
    }
}   

/**
* SetWNCompanionAd Function
*  - need to prevent this function from being overwritten - maybe use a new GUID each time the client loads as a name - at the ASP level?
* SIZEID  = Ad Manager Tag 
* wnsz_35 = 180x150B Rectangle - B
* wnsz_1  = BannerFull Banner
* wnsz_26 = Bu120x60A Button - A
* wnsz_27 = Bu120x60B Button - B
* wnsz_28 = Bu120x60C Button - C
* wnsz_24 = We120x15 Weather
* wnsz_22 = SpH490x25 Sponsorship Header - A
* wnsz_14 = 120x600 Skyscraper
* wnsz_20 = 180x150 Rectangle
* wnsz_23 = VB120x240A Vertical Banner - A
* wnsz_18 = VB120x240B Vertical Banner - B
* wnsz_40 = PB468x60 Printable Page Banner
* wnsz_34 = Video120x60 Video 120x60
* wnsz_41 = 728x90A Leaderboard A
* wnsz_42 = 160x600A Wide Skyscraper
* wnsz_43 = 300x250A Medium Rectangle
* wnsz_46 = 728x90B Leaderboard B
* wnsz_44 = 300x75 National Promo
* wnsz_49 = 500x300A 500x300 Footer A
* wnsz_50 = 300x175A 300x175 Rectangle A
* wnsz_53 = HalfBanner
*/
WNAdWidget.prototype.SetWNCompanionAd = function(p_adObj)
{
    var objAd = p_adObj.objClip;
    
    //load the right size, might need to change to id if groups are used
    if (objAd.size == this.widgetName) 
    {
        if (this.isTransitional) 
        { 
            //disable gallery controls 
            videoGallery.EnableControls(false);
        }
       
        if(objAd.useRedirect == "true")
        {
            if (objAd.redirectHtml != "null")
            {
                //alert("redir ad");
                this.targetElement.innerHTML = objAd.redirectHtml; 
            }    
        } 
        else 
        {
		this.targetElement.innerHTML = "<a href='" + objAd.clickUrl + "' target='new'><img src='" + objAd.url + "' width='" + this.width + "' height='" + this.height + "' border='0'></a>";
		//alert(this.targetElement.innerHTML);
        }
    }
 }   
 
/* Class: WNReportingWidget
Creates an reporting widget and registers it for Canvas events.
 - p_widgetName
 - p_callBackFunctionName
 - p_groupId
*/
WNReportingWidget = function(p_widgetName, p_callBackFunctionName, p_groupId)
{
    this.widgetClassType    = "WNReportingWidget";    
    this.idKey              = wnVideoWidgets.validateString(p_groupId)?p_groupId:"DEFAULT";
    this.widgetName         = p_widgetName;
    this.id                 = p_widgetName + this.idKey;
    
    //register for events
    evntMgr.Register({lstnr:this, evnt:"NewMedia",      func:p_callBackFunctionName, idKey:this.idKey});
    evntMgr.Register({lstnr:this, evnt:"MediaEnded",    func:p_callBackFunctionName, idKey:this.idKey});
} 

/**
* EventManager class
* To ensure that all widgets are able to register for events, regardless of the order in which they load on the page, the event object is a javascript object.
* Since all widgets use this page, the code for the widget object is included with all widgets.
* To ensure the object is only created once, check to see if it has been created.  If so, do not create.
* The event object contains an object of listener arrays, a Register function and a Notify function.
*/
WNEventManager = function() 
{
    this.listeners = new Object();
}

WNEventManager.prototype.Register = function(evntObj)
{
    var lstnr   = evntObj.lstnr;
    var func    = evntObj.func;
    var evnt    = evntObj.evnt;
    var idKey   = evntObj.idKey;
    
    if(typeof this.listeners[idKey] == "undefined")
    {
        this.listeners[idKey] = new Array(); 
    }
    var len     = this.listeners[idKey].length;
    for(var i = 0;i < len;i++)
    {
        if(this.listeners[idKey][i].lstnr == lstnr && this.listeners[idKey][i].evnt == evnt)
        {
            return false;
        }
    }
    this.listeners[idKey].push({lstnr:lstnr, evnt:evnt, func:func}); //zr - cross browser/platform?
	//alert("evnt = " + evnt + "; func = " + func);
    return true;        
}
    
WNEventManager.prototype.Notify = function(evntObj, functionObj)
{
    var evnt    = evntObj.evnt;  
    var idKey   = evntObj.idKey;
    var len     = this.listeners[idKey].length;  
    var listeners = this.listeners;

    for(var i = 0;i < len;i++)
    {
        if(this.listeners[idKey][i].evnt == evnt)
        {            
            var lstnr   = this.listeners[idKey][i].lstnr;
            var func    = this.listeners[idKey][i].func;     
			
            if (lstnr.widgetClassType == "WNAdWidget" || lstnr.widgetClassType == "WNVideoListener" || lstnr.widgetClassType == "WNReportingWidget")
            {
                //determine the loc national split - call HandleNationalAd if it's nartional otherwise use the passed in callback func
                lstnr[func](evntObj);
            }
            else //use flash external interface methodology to call functions on swf's
            {   
                document.getElementById(lstnr)[func](evntObj);  
            }
        }
    }        
} 

WNCanvasListener = function(p_callBackFunctionName, p_groupId)
{
    this.widgetClassType    = "WNVideoListener";    
    this.idKey              = wnVideoWidgets.validateString(p_groupId)?p_groupId:"DEFAULT";
    evntMgr.Register({lstnr:this, evnt:"ModelInitiated", func:p_callBackFunctionName, idKey:this.idKey});
}   

/* Class: PlayClipObject 
- instantiated once when WNVideo is loaded, no need to instantiate the class 
- NewClipId: receives a clip id string and passes to the VideoCanvas if available.  If not, passes it to the PopVideoPlayer method 
*/

/**
Unexposed methods
 - PopVideoPlayer: called by NewClipObject and NewClipId when a VideoCanvas widget is not present. Pops a landing page
 - NewClipObject: receives a clip object and passes it to the VideoCanvas when available, if not, extracts the clip id and passes it to the PopVideoPlayer method
*/
WNPlayClipObject = function()
{
}
    
//TB - need to consider sizes for the landingpage.  global.inc?
//TB - need to get around popup blocker.  Might have to change, to onRelease.

WNPlayClipObject.prototype.PopVideoPlayer = function(evntObj)
{
    var landingPage = wnVideoWidgets.landingPage;
    if(wnVideoWidgets.validateString(landingPage))
    {
        var params  = "clipid=" + evntObj.objClip.id + "&topVideoCatNo=" + evntObj.topCatId + "&autoStart=true";
		if (evntObj.objClip.popupLandingPage == "true") {
			var popWin  = window.open(landingPage + params, "WNFlashLandingPage");
		} else {
			window.location = landingPage + params;
			return;
		}
        try 
        {
            if (popWin!=null)
            {
                popWin.focus();
            }
        } 
        catch(e) 
        {
            self.blur();
        }  
    } else {
		// open popup player by using existing function from VideoFunctions.js\
		playVideo(	evntObj.objClip.id,
					evntObj.objClip.strHeadline, 
					evntObj.objClip.strType, 
					evntObj.objClip.strAdTarget, 
					evntObj.objClip.strDuration, 
					evntObj.objClip.strlaunchPageAdTag, 
					evntObj.objClip.strQueryStringParams, 
					evntObj.objClip.strHostDomain,
					evntObj.objClip.strFormat);
    }
}

WNPlayClipObject.prototype.NewClipObject = function(obj)
{
	//var elemId = wnVideoWidgets.validateString(obj.idKey)?videoCanvasId + obj.idKey:videoCanvasId;
	wnVideoWidgets.objClip = obj;
    //alert(obj.isThirdParty);
	//if(wnPreferredVideoFormat=="FLV")
	//{
		for (var i in wnVideoWidgets.canvasObject)
		{
			if(i == obj.idKey) 
			{
				var elemId = wnVideoWidgets.canvasObject[i];
			}
		}
		var videoCanvas = document.getElementById(elemId);
		if(videoCanvas != null)
		{
			// does the div tag containing the silverlight canvas exist
			var canvasSliverlightDivName = elemId + "WNSilverlight";
			var canvasSliverlightDiv = document.getElementById(canvasSliverlightDivName);
			if(canvasSliverlightDiv != undefined && canvasSliverlightDiv.style.display != "none")
			{
				WNSilverlightStopClip();
				// hide the silverlight canvas
				canvasSliverlightDiv.style.display="none";			
				// show the flash canvas
				videoCanvas.width = WNSilverlightCanvasWidth;
				videoCanvas.height = WNSilverlightCanvasHeight;
			}
			videoCanvas.wnFlashVideoCanvas_PlayClip(obj.objClip);
		}
		else if(obj.objClip.isUserInitiated)
		{
			this.PopVideoPlayer(obj);
		}
	//}
	//else if(wnPreferredVideoFormat=="WMV")
	//{
		//if(Silverlight.isInstalled('1.0'))
		//{
			//WNSilverlightTrigger(obj);
		//}
	//}
    return true;  
}       

/* Method: NewClipId
- Takes clip id and collection id (optional)
- Plays clip on the canvas associated with the collection id
*/
WNPlayClipObject.prototype.NewClipId = function(id, idKey, strHeadline, strType, strAdTarget, strDuration, strlaunchPageAdTag, strQueryStringParams, strHostDomain, strFormat)
{
    //var elemId = wnVideoWidgets.validateString(idKey)?videoCanvasId + idKey:videoCanvasId;
    var idKey = wnVideoWidgets.validateString(idKey)?idKey:"DEFAULT";
    for (var i in wnVideoWidgets.canvasObject)
    {
        if(i == idKey) 
        {
           var elemId = wnVideoWidgets.canvasObject[i];
        }
    }     
    var videoCanvas = document.getElementById(elemId)
    if(videoCanvas != null)
    {
        videoCanvas.wnFlashVideoCanvas_PlayClip({id:id, isUserInitiated:true});
    }
    else
    {
        var clip = new Object();
        clip.id             = id;
        clip.toLocaleString = "";
		clip.strHeadline = strHeadline;
		clip.strType = strType;
		clip.strAdTarget = strAdTarget;
		clip.strDuration = strDuration;
		clip.strlaunchPageAdTag = strlaunchPageAdTag;
		clip.strQueryStringParams = strQueryStringParams;
		clip.strHostDomain = strHostDomain;
		clip.strFormat = strFormat;
        this.PopVideoPlayer({objClip:clip});
    }  
    return true;         
}
    

/**
- Instantiate the EventManager, PlayClipObject and VideoWidgets
- Make callBackFunctions
*/ 
var wnPlayClip      = new WNPlayClipObject();
var evntMgr         = new WNEventManager();
var wnVideoWidgets  = new WNVideoWidgets();
try
{
    for (var i in wnCallBackFunctions)
    {
        wnCallBackFunctions[i]();
    }
}
catch(e){}

/**
- place holder for Motif HTML ad units
*/
function syncRoadBlock(adTag)
{}


/* 
- Called by VideoCanvas when loaded. 
- To resolve situations when VideoCanvas loading after the Gallery.
*/
function setPrimaryClip(ID, recall) {
	if (recall >= 15) { eval("clearTimeout(canvasTimer"+galleryID+");"); return; }
	var videoCanvas = document.getElementById(ID);	
	var galleryID = ID.replace(/VideoCanvas/g, "Gallery");
	var Gallery = document.getElementById(galleryID);
	if (Gallery) {
		clipLoaded = Gallery.wnSetPrimaryClip();
		if (!clipLoaded) {
			if (recall >= 15) { eval("clearTimeout(canvasTimer"+galleryID+");"); return; }
			recall++;
			eval("canvasTimer"+galleryID+" = setTimeout (\"setPrimaryClip('"+ID+"', "+recall+")\", 500);");
		} else {
			eval("clearTimeout(canvasTimer"+galleryID+");");
		}
	} else {
		eval("canvasTimer"+galleryID+" = setTimeout (\"setPrimaryClip('"+ID+"', "+recall+")\", 500);");
	}
}
