// AVPlayerBehavior - Begins

function AVPlayerBehaviorExists(AVPlayerClientID){
    if ($get(AVPlayerClientID).AVPlayerBehavior == null) {
        alert("One more second please...the content is not quite loaded yet.  Please click again.");
        return false;
    }
    return true;
} 
Type.registerNamespace('GDTV.WebControls');

GDTV.WebControls.AVPlayerBehavior = function(element) {
    GDTV.WebControls.AVPlayerBehavior.initializeBase(this, [element]);

    this._imageRoot = null;
    this._PlayerDivClientId = null;
    this._ConnectionSpeedDivClientID = null;
    this._PlayerClickUrl = null;

    this._playTriggerEvent = null;
    this._playTriggerElement = null;
    this._MediaId = null;
    this._CurrentStreamingMediaData = null;
}

GDTV.WebControls.AVPlayerBehavior.prototype = {
  get_CurrentMedia: function() {
    if (this._CurrentStreamingMediaData != null)
      return this._CurrentStreamingMediaData.media;
    else
      return null;
  },

  get_imageRoot: function() {
    return this._imageRoot;
  },
  set_imageRoot: function(value) {
    this._imageRoot = value;
  },

  get_PlayerClickUrl: function() {
    return this._PlayerClickUrl;
  },
  set_PlayerClickUrl: function(value) {
    this._PlayerClickUrl = value;
  },

  get_PlayerDivClientId: function() {
    return this._PlayerDivClientId;
  },
  set_PlayerDivClientId: function(value) {
    this._PlayerDivClientId = value;
  },

  get_ConnectionSpeedDivClientID: function() {
    return this._ConnectionSpeedDivClientID;
  },
  set_ConnectionSpeedDivClientID: function(value) {
    this._ConnectionSpeedDivClientID = value;
  },

  add_MediaSelectionChanged: function(handler) {
    this.get_events().addHandler("MediaSelectionChanged", handler);
  },
  remove_MediaSelectionChanged: function(handler) {
    this.get_events().removeHandler("MediaSelectionChanged", handler);
  },
  raiseMediaSelectionChanged: function() {
    var eh = this.get_events().getHandler("MediaSelectionChanged");
    if (eh) {
      eh(this, Sys.EventArgs.Empty);
    }
  },

  add_BeforeMediaSelectionChanged: function(handler) {
    this.get_events().addHandler("BeforeMediaSelectionChanged", handler);
  },
  remove_BeforeMediaSelectionChanged: function(handler) {
    this.get_events().removeHandler("BeforeMediaSelectionChanged", handler);
  },
  raiseBeforeMediaSelectionChanged: function() {
    var eh = this.get_events().getHandler("BeforeMediaSelectionChanged");
    if (eh) {
      eh(this, Sys.EventArgs.Empty);
    }
  },

  initialize: function() {
    GDTV.WebControls.AVPlayerBehavior.callBaseMethod(this, 'initialize');
  },

  dispose: function() {
    GDTV.WebControls.AVPlayerBehavior.callBaseMethod(this, 'dispose');
  },

  playMedia: function(mediaId, event, element) {
    this._playTriggerEvent = event;
    this._playTriggerElement = element;
    if (mediaId == null || mediaId.length == 0)
      return;

    if (this._CurrentStreamingMediaData == null || this._CurrentStreamingMediaData.media.Id != mediaId) {
      this._MediaId = mediaId;
      this._getMedia();
    }
    else {
      this._playCurrentMedia();
    }
  },

  _setElementVisibility: function(elem, visible) {
    if (visible)
      elem.style.display = "";
    else
      elem.style.display = "none";
  },

  _scrollIntoView: function() {
    //If false, the scrolled element is aligned with the bottom of the scroll area. 
    this.get_element().scrollIntoView(false);
  },

  _getMedia: function() {
    if (this._MediaId != null) {
      this._scrollIntoView();
      var connSpeedBehavior = $find("ConnectionSpeedBehavior", $get(this._ConnectionSpeedDivClientID));
      var connSpeed = ConnectionSpeed.Unknown;
      if (connSpeedBehavior != null) {
        connSpeed = connSpeedBehavior.get_CurrentConnectionSpeed();
      }
      if (connSpeed == ConnectionSpeed.Unknown) {
        connSpeed = ConnectionSpeed.High;
      }
      var getMediaSuceededHandler = Function.createDelegate(this, this._getMediaSuceeded);
      var getMediaFailedHandler = Function.createDelegate(this, this._getMediaFailed);
      PageMethods.GetStreamingMediaData(this._MediaId, connSpeed, getMediaSuceededHandler, getMediaFailedHandler);
    }
  },

  _getMediaSuceeded: function(result, eventArgs) {
    this._CurrentStreamingMediaData = result;
    this.raiseBeforeMediaSelectionChanged();
    this._playCurrentMedia();
    this.raiseMediaSelectionChanged();
  },

  _getMediaFailed: function(error) {
    alert(error.get_message());
  },

  _playCurrentMedia: function() {
    //log the click here if CiView is available
    if (this._CurrentStreamingMediaData.media.CiView > 0) {
      if (typeof (FastballEvent_MouseClick) !== 'undefined') {
        FastballEvent_MouseClick(this._playTriggerEvent, this._CurrentStreamingMediaData.media.CiView, this._playTriggerElement, '', 'a');
      }
    }
    //video or audio or ringtone
    if (this._CurrentStreamingMediaData.media.Type == 1 || this._CurrentStreamingMediaData.media.Type == 2 || this._CurrentStreamingMediaData.media.Type == 5) {
      this._playAudioVideo();
    }
    
    //streaming audio
    if (this._CurrentStreamingMediaData.media.Type == 6) {
      this._playStreamingAudio();
    }
  },
  
  _checkPlugin: function(plugIn) {
	    //check browser plugins
	    var plugInExist = false;
	    for (i = 0; i < navigator.plugins.length; i++) {
		    if (navigator.plugins[i].name.indexOf(plugIn) != -1) {
			    plugInExist = true;}
	    } 
	    return(plugInExist);
  },
  
  _playStreamingAudio: function() {
        var playerwidth = 355;
        var playerheight = 61;
        var sGlobal_secPrefix = 'http';
        
        var playerDiv = $get(this._PlayerDivClientId)
        if(playerDiv){
	        playerDiv.innerHTML = '';
	        playerDiv.style.width = playerwidth;
	        playerDiv.style.height = playerheight;
        }

        var displayStr = '<object style="margin:0px;" id="mediaPlayer" width="' + playerwidth + '" height="' + playerheight + '" ';
        displayStr += 'classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" ';
        displayStr += 'codebase="' + sGlobal_secPrefix + ':\/\/activex.microsoft.com\/activex\/controls\/mplayer\/en\/nsmp2inf.cab#version=5,1,52,701" ';
        displayStr += 'standby="loading microsoft windows media player components..." type="application\/x-oleobject">';
        displayStr += '<param name="URL" value="' + this._CurrentStreamingMediaData.Url + '">';
        displayStr += '<param name="autostart" value="true">';
        displayStr += '<param name="showaudiocontrols" value="true">';
        displayStr += '<param name="showcontrols" value="true">';
        displayStr += '<param name="loop" value="false">';
        displayStr += '<param name="enablecontextmenu" value="false">';
        displayStr += '<param name="showpositioncontrols" value="true">';
        displayStr += '<param name="showstatusbar" value="true">';
        displayStr += '<param name="kioskmode" value="true">';

        if (this._checkPlugin("Flip")){
	        displayStr += '<embed type="video\/quicktime" ';
	        displayStr += 'pluginspage="www.apple.com\/quicktime\/download" ';}
        else{
	        displayStr += '<embed type="application/x-mplayer2" ';
	        displayStr += 'pluginspage="' + sGlobal_secPrefix + ':\/\/microsoft.com\/windows\/mediaplayer\/en\/download" ';}
    	
        displayStr += 'name="mediaPlayer" displaysize="4" autosize="-1" ';
        displayStr += 'background="#000000" bgcolor="#000000" showaudiocontrols="1" showcontrols="1" autostart="1" autoplay="true" showstatusbar="1" enablecontextmenu="0" showpositioncontrols="1" ';
        displayStr += 'showtracker="-1"	showdisplay="0" videoborder3d="-1" ';
        displayStr += 'width="' + playerwidth + '" height="' + playerheight + '" ';
        displayStr += 'src="' + this._CurrentStreamingMediaData.Url + '" autostart="true" designtimesp="5311" loop="false" EnableJavaScript="true">';
        displayStr += '<\/embed><\/object>';	

        if($get(this._PlayerDivClientId)){
	        $get(this._PlayerDivClientId).innerHTML = displayStr;
        }
  },

  _playAudioVideo: function() {
    var playerwidth = 356;
    var playerheight = 246;
    var swfFileName;
    if (this._CurrentStreamingMediaData.media.Type == 1) {//video
      if (this._CurrentStreamingMediaData.media.PlayerURL > "") {
        swfFileName = this._CurrentStreamingMediaData.media.PlayerURL;
      }
      else {
        swfFileName = "GD_VidPlayer_FS_smallLB_7";
      }
    }
    else {
      swfFileName = "GD_MP3Player";
    }
    var playerDiv = $get(this._PlayerDivClientId)
    if(playerDiv){
        playerDiv.innerHTML = '';
        playerDiv.style.width = playerwidth;
        playerDiv.style.height = playerheight;
    }
    if (swfFileName.indexOf('GD_VidPlayer_FS_xlpopupLB') != -1) {
      playerwidth = 660;
      playerheight = 440;    
    }      
    AC_FL_RunContent2(
	        'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
	        'width', playerwidth,
	        'height', playerheight,
            'src', this._imageRoot + 'gdtv/swf/' + swfFileName + '.swf?myXML=' + escape('<video><info vTitle="' + this._CurrentStreamingMediaData.media.Name + '" vURL="' + this._CurrentStreamingMediaData.Url + '" vClick="' + this._MediaId + '">Info</info></video>'),
	        'quality', 'high',
	        'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
	        'align', 'middle',
	        'play', 'true',
	        'loop', 'true',
	        'scale', 'noborder',
	        'wmode', 'transparent',
	        'devicefont', 'false',
	        'id', swfFileName,
	        'bgcolor', '#999999',
	        'name', swfFileName,
	        'menu', 'true',
	        'allowFullScreen', 'true',
	        'allowScriptAccess', 'always',
	        'salign', '',
	        'maindiv', this._PlayerDivClientId
	    ); //end AC code
  },

  _playAudio: function() {
    var playerStr = '<object height="44" width="280" id="mp3PlayerObject" style="border: solid 1px #666666;">';
    playerStr += '<param name="kioskmode" value="true" />';
    playerStr += '<param name="src" value="' + this._CurrentStreamingMediaData.Url + '"/>';
    playerStr += '<param name="autoplay" value="true" />';
    playerStr += '<param name="controller" value="true" />';
    playerStr += '<embed height="44" src="' + this._CurrentStreamingMediaData.Url + '" type="video/quicktime" width="280" controller="true" autoplay="true" kioskmode="true" style="border: solid 1px #666666;" />';
    playerStr += '</object>';

    if (document.getElementById(this._PlayerDivClientId)) {
      $get(this._PlayerDivClientId).innerHTML = "&nbsp;" + playerStr + "&nbsp;";
    }
  }
}

GDTV.WebControls.AVPlayerBehavior.registerClass('GDTV.WebControls.AVPlayerBehavior',Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

// AVPlayerBehavior - Ends
// ~~~~~~~~~~**********~~~~~~~~~~~**************

// ConnectionSpeedBehavior - Begins

Type.registerNamespace('GDTV.WebControls');

GDTV.WebControls.ConnectionSpeedBehavior = function(element) {
    GDTV.WebControls.ConnectionSpeedBehavior.initializeBase(this, [element]);
    
    this._CurrentConnectionSpeed = ConnectionSpeed.Unknown;
    this._connSpeedDivClientId = null;
    this._connSpeedHighDivClientId = null;
    this._connSpeedLowDivClientId = null;
    
    this._connSpeedHighDivClickHandler = null;
    this._connSpeedLowDivClickHandler = null;
}

GDTV.WebControls.ConnectionSpeedBehavior.prototype = {
    get_CurrentConnectionSpeed : function() {
        return this._CurrentConnectionSpeed;
    },
    set_CurrentConnectionSpeed : function(value) {
        this._CurrentConnectionSpeed = value;
    },

    get_connSpeedDivClientId: function() {
        return this._connSpeedDivClientId;
    },
    set_connSpeedDivClientId : function(value) {
        this._connSpeedDivClientId = value;
    },
    
    get_connSpeedHighDivClientId : function() {
        return this._connSpeedHighDivClientId ;
    },
    set_connSpeedHighDivClientId  : function(value) {
        this._connSpeedHighDivClientId  = value;
    },
    
    get_connSpeedLowDivClientId: function() {
        return this._connSpeedLowDivClientId;
    },
    set_connSpeedLowDivClientId : function(value) {
        this._connSpeedLowDivClientId = value;
    },
    
    add_ConnectionSpeedSelectionChanged : function(handler) {
        this.get_events().addHandler("ConnectionSpeedSelectionChanged", handler);
    },
    remove_ConnectionSpeedSelectionChanged : function(handler) {
        this.get_events().removeHandler("ConnectionSpeedSelectionChanged", handler);
    },
    raiseConnectionSpeedSelectionChanged : function() {
        var eh = this.get_events().getHandler("ConnectionSpeedSelectionChanged");
        if (eh) {
            eh(this, Sys.EventArgs.Empty);
        }
    },
		
    initialize : function() {
        GDTV.WebControls.ConnectionSpeedBehavior.callBaseMethod(this, 'initialize');
   
        this._connSpeedHighDivClickHandler = Function.createDelegate(this, this._onConnectionSpeedOptionClicked);
        this._connSpeedLowDivClickHandler = Function.createDelegate(this, this._onConnectionSpeedOptionClicked);
   
        $addHandler($get(this._connSpeedHighDivClientId), "click", this._connSpeedHighDivClickHandler);
        $addHandler($get(this._connSpeedLowDivClientId), "click", this._connSpeedLowDivClickHandler);
       
        if (this._CurrentConnectionSpeed == ConnectionSpeed.Unknown)
            this._CurrentConnectionSpeed = ConnectionSpeed.High;
    
        this._highlightCurrentConnectionSpeed();
    },
    
    dispose : function() {
       GDTV.WebControls.ConnectionSpeedBehavior.callBaseMethod(this, 'dispose');
    },
    
    _onConnectionSpeedOptionClicked : function(evt) {
        var connectionSpeed = ConnectionSpeed.Unknown;
        if (evt.target.id == this._connSpeedHighDivClientId) {
            connectionSpeed = ConnectionSpeed.High;
        }
        if (evt.target.id == this._connSpeedLowDivClientId) {
            connectionSpeed = ConnectionSpeed.Low;
        }
        
        if (connectionSpeed != this._CurrentConnectionSpeed)
        {
            this._CurrentConnectionSpeed = connectionSpeed;
        
            this._highlightCurrentConnectionSpeed();
        
            this.raiseConnectionSpeedSelectionChanged();
            
            var setConnectionSpeedSuceededHandler = Function.createDelegate(this, this._onSetConnectionSpeedSuceeded);
            var setConnectionSpeedFailedHandler = Function.createDelegate(this, this._onSetConnectionSpeedFailed);
            PageMethods.SaveConnectionSpeed(this._CurrentConnectionSpeed, setConnectionSpeedSuceededHandler, setConnectionSpeedFailedHandler);
        }
    },
    
    _highlightCurrentConnectionSpeed : function() {
        if (this._CurrentConnectionSpeed != ConnectionSpeed.Unknown) {
            if (this._CurrentConnectionSpeed == ConnectionSpeed.High) {
                Sys.UI.DomElement.removeCssClass($get(this._connSpeedLowDivClientId), "conn_speed_active");
                Sys.UI.DomElement.addCssClass($get(this._connSpeedHighDivClientId), "conn_speed_active");
            }
            else {
                Sys.UI.DomElement.removeCssClass($get(this._connSpeedHighDivClientId), "conn_speed_active");
                Sys.UI.DomElement.addCssClass($get(this._connSpeedLowDivClientId), "conn_speed_active");
            }
        }
    },
    
    _onSetConnectionSpeedSuceeded : function(result, eventArgs) {
    },
    
    _onSetConnectionSpeedFailed : function(error) {
    }
}

GDTV.WebControls.ConnectionSpeedBehavior.registerClass('GDTV.WebControls.ConnectionSpeedBehavior',Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

// ConnectionSpeedBehavior - Ends
// ~~~~~~~~~~**********~~~~~~~~~~~**************

// Flash Player related functions - begins

// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	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;			
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
	if (src.indexOf(".") < 0){
		if (src.indexOf('?') != -1){
		  return src.replace(/\?/, ext+'?'); }
		else{
		  return src + ext;}
  }
  else{
		return src;}
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }
    document.write(str);
}

function AC_Generateobj2(objAttrs, params, embedAttrs, maindiv) 
{ 
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }
		if(document.getElementById(maindiv)) {
			document.getElementById(maindiv).innerHTML = str;		
		}
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_FL_RunContent2(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );

  var maindiv = AC_GetArgs2 (arguments);

  AC_Generateobj2(ret.objAttrs, ret.params, ret.embedAttrs, maindiv);
}

function AC_FL_RunContent3(){
  var ret = AC_GetArgs(arguments, ".mp3", "movie", "", "");
  var maindiv = AC_GetArgs2 (arguments);
  AC_Generateobj2(ret.objAttrs, ret.params, ret.embedAttrs, maindiv);
}

function AC_GetArgs2(args){
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
		if(currArg == "maindiv") return args[i+1];
	}
}


function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
      case "maindiv":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
      case "style":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  if (classid) ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

// Flash Player related functions - Ends

// BPTVSurveyBehavior - Begins

Type.registerNamespace('GDTV.WebControls');

GDTV.WebControls.BPTVSurveyBehavior = function(element) {
    GDTV.WebControls.BPTVSurveyBehavior.initializeBase(this, [element]);
    
    this._bpURLRoot = null;
    this._voteButtonClientId = null;
    this._radioButtonIds = null;
    this._clientIPAddress = null;
    this._surveyResultsFlashDivClientId = null;
    this._surveyResultsPopupDivID = null;
   
    this._AVPlayerClientId = null;
    this._AVPlayerBehaviorId = null;

    this._mediaSelectionChanged = null;
    this._avPlayerDisposingHandler = null;
    this._voteButtonClickedHandler = null;
}

GDTV.WebControls.BPTVSurveyBehavior.prototype = {
    get_bpURLRoot: function() {
        return this._bpURLRoot;
    },
    set_bpURLRoot : function(value) {
        this._bpURLRoot = value;
    },
    
    get_radioButtonIds : function() {
        return this._radioButtonIds ;
    },
    set_radioButtonIds  : function(value) {
        this._radioButtonIds  = value;
    },
    
    get_surveyDivClientId: function() {
        return this._surveyDivClientId;
    },
    set_surveyDivClientId : function(value) {
        this._surveyDivClientId = value;
    },
    
    get_clientIPAddress: function() {
        return this._clientIPAddress;
    },
    set_clientIPAddress : function(value) {
        this._clientIPAddress = value;
    },
    
    get_voteButtonClientId: function() {
        return this._voteButtonClientId;
    },
    set_voteButtonClientId : function(value) {
        this._voteButtonClientId = value;
    },
    
    get_surveyResultsFlashDivClientId: function() {
        return this._surveyResultsFlashDivClientId;
    },
    set_surveyResultsFlashDivClientId : function(value) {
        this._surveyResultsFlashDivClientId = value;
    },
    
    get_surveyResultsPopupDivID: function() {
        return this._surveyResultsPopupDivID;
    },
    set_surveyResultsPopupDivID : function(value) {
        this._surveyResultsPopupDivID = value;
    },
    
    get_AVPlayerClientId : function() {
		return this._AVPlayerClientId;
	},
	set_AVPlayerClientId : function(value) {
		this._AVPlayerClientId = value;
	},
	
	get_AVPlayerBehaviorId: function() {
        return this._AVPlayerBehaviorId;
    },
    set_AVPlayerBehaviorId : function(value) {
        this._AVPlayerBehaviorId = value;
    },

    initialize : function() {
        GDTV.WebControls.BPTVSurveyBehavior.callBaseMethod(this, 'initialize');
   
        this._mediaSelectionChanged = Function.createDelegate(this, this._onMediaSelectionChanged);
        this._avPlayerDisposingHandler = Function.createDelegate(this, this._onAVPlayerDisposing);
        this._voteButtonClickedHandler = Function.createDelegate(this, this._voteButtonClicked);
   
        var AVPlayerBehavior = $find(this._AVPlayerBehaviorId, $get(this._AVPlayerClientId));        
        AVPlayerBehavior.add_MediaSelectionChanged(this._mediaSelectionChanged);        
        AVPlayerBehavior.add_disposing(this._avPlayerDisposingHandler);
        
        $addHandler($get(this._voteButtonClientId), "click", this._voteButtonClickedHandler);
    },
        
    _onAVPlayerDisposing: function(sender, eventargs) {
        if (this._voteButtonClickedHandler != null)
            $removeHandler($get(this._voteButtonClientId), "click", this._voteButtonClickedHandler);
            
        if (this._mediaSelectionChanged != null)
            sender.remove_MediaSelectionChanged(this._mediaSelectionChanged);
            
        if (this._avPlayerDisposingHandler != null)
            sender.remove_disposing(this._avPlayerDisposingHandler);
            
        this._mediaSelectionChanged = null;
        this._avPlayerDisposingHandler = null;
        this._voteButtonClickedHandler = null;
    },
    
    dispose : function() {
       GDTV.WebControls.BPTVSurveyBehavior.callBaseMethod(this, 'dispose');
    },
    
    _onMediaSelectionChanged : function() {
        var AVPlayerBehavior = $find(this._AVPlayerBehaviorId, $get(this._AVPlayerClientId)); 
        var media = AVPlayerBehavior.get_CurrentMedia();
        if (media != null && (media.SurveyId != "undefined" && media.SurveyId > 0)) {
            this._initializeSurvey();
            this._setVisibility(this.get_element(), true);
        }
        else {
            this._setVisibility(this.get_element(), false);
        }
    },
    
    _initializeSurvey : function() {
      for(var i=0; i < this._radioButtonIds.length; i++)
        {
            var radioButton = $get(this._radioButtonIds[i]);
            if (radioButton.value == "liked")
            {
                radioButton.checked = true;
                break;
            }
        }  
    },
    
    _voteButtonClicked : function(evt) {
        var AVPlayerBehavior = $find(this._AVPlayerBehaviorId, $get(this._AVPlayerClientId));
        var media = AVPlayerBehavior.get_CurrentMedia();
        var saveSurveyResultsSuceededHandler = Function.createDelegate(this, this._onSaveSurveyResultsSuceeded);
        var saveSurveyResultsFailedHandler = Function.createDelegate(this, this._onSaveSurveyResultsFailed);
        
        var opinion = this._getOpinion();
        PageMethods.SaveBPTVSurveyResults(this._bpURLRoot + "survey.php", media.SurveyId, opinion, saveSurveyResultsSuceededHandler, saveSurveyResultsFailedHandler);                

        var so = new SWFObject( this._bpURLRoot + "Charts/FC_2_3_Bar2D.swf?chartWidth=400&chartHeight=100&dataUrl=" + escape(this._bpURLRoot + "sdata.php?corp=1&entry_id=") + media.SurveyId, "flashswf", "402", "120", "8", "#DCDCDC");
	    so.addParam("wmode", "transparent");
	    so.write(this._surveyResultsFlashDivClientId); 
    },
    
    _onSaveSurveyResultsSuceeded : function(result, eventArgs) {
        this._setVisibility(this.get_element(), false);
        this._setVisibility($get(this._surveyResultsPopupDivID), true);
    },
    
    _onSaveSurveyResultsFailed : function(error) {
    },
    
    _setVisibility : function(elem, show) {
        if (show) 
            elem.style.display = "";
        else
            elem.style.display = "none";
    },
    
    _getOpinion : function() {
        var opinion;
        for(var i=0; i < this._radioButtonIds.length; i++)
        {
            var radioButton = $get(this._radioButtonIds[i]);
            if (radioButton.checked == true)
            {
                opinion = radioButton.value;
                break;
            }
        }
        return opinion;
    }
}

GDTV.WebControls.BPTVSurveyBehavior.registerClass('GDTV.WebControls.BPTVSurveyBehavior',Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

// BPTVSurveyBehavior - Ends
// ~~~~~~~~~~**********~~~~~~~~~~~**************
