﻿var __CurrentScriptBus = null;

function ScriptBus_DoCommand()
{
	if(__CurrentScriptBus == null) return;
	
	__CurrentScriptBus.doCommand(arguments);
}

Type.registerNamespace("TitanTV");

// Constructor
TitanTV.ScriptBus = function(element)
{

  TitanTV.ScriptBus.initializeBase(this, [element]);

  // Private variables
  this._postbackID = null;
  this._pageRequestManager = null;

  // UI Elements

  // Methods
  this.doCommand = null;
  this.pageLoading = null;

  // Private methods
}

TitanTV.ScriptBus.prototype = {

  // property accessors.

  get_postbackID: function()
  {
    return this._postbackID;
  },

  set_postbackID: function(value)
  {
    this._postbackID = value;
  },

  initialize: function()
  {
    var element = this.get_element();

    this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();

    // create Delgates
    if (this.doCommand === null) this.doCommand = Function.createDelegate(this, this._doCommand);
    if (this.pageLoading === null) this.pageLoading = Function.createDelegate(this, this._pageLoading);

    this._pageRequestManager.add_pageLoading(this.pageLoading);

    TitanTV.ScriptBus.callBaseMethod(this, 'initialize');

    __CurrentScriptBus = this;

    Sys.Debug.trace('Initialize: ' + element.id);
  },

  // Release resources before control is disposed.
  dispose: function()
  {
    var element = this.get_element();

    this._pageRequestManager.remove_pageLoading(this.pageLoading);

    if (this.doCommand) delete this.doCommand;
    if (this.pageLoading) delete this.pageLoading;

    TitanTV.ScriptBus.callBaseMethod(this, 'dispose');

    __CurrentScriptBus = null;

    Sys.Debug.trace('Dispose: ' + element.id);
  },

  // Show Cell Menu
  _doCommand: function(args)
  {
    if (this._postbackID == null || args == null || args.length == 0)
      return;

    var postbackArguments = 'command';

    for (var i = 0; i < args.length; i++)
    {
      postbackArguments += '|' + args[i];
    }

    __doPostBack(this._postbackID, postbackArguments);
  },

  _pageLoading: function(sender, args)
  {
    if (!args) return;

    var element = this.get_element();
    var dataItems = args.get_dataItems();

    if (!dataItems) return;

    if (dataItems[element.id] == "resetScroll") this._pageRequestManager._scrollPosition.y = 0;
  }
}

TitanTV.ScriptBus.registerClass('TitanTV.ScriptBus', Sys.UI.Control);

TitanTV.ScriptBus.DoCommand = function()
{
  if (__CurrentScriptBus == null) return;

  __CurrentScriptBus.doCommand(arguments);
}

// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager 
// that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


