﻿Type.registerNamespace("TitanTV");

// Constructor
TitanTV.GridDisplay = function(element)
{

  TitanTV.GridDisplay.initializeBase(this, [element]);

  // Private variables
  this._debug = null;
  this._commandUrl = null;
  this._detailsUrl = null;
  this._printUrl = null;
  this._context = null;
  this._layout = "table";

  this._stationData = null;
  this._commandFrame = null;

  // UI Elements

  // Methods
  this.pageLoading = null;
  this.openDetails = null;
  this.executePVRCommand = null;
  this.openIFrame = null;
  this.doCommand = null;
  this.getStationData = null;
  this.printGrid = null;
  this.toggleFavorite = null;

  // Private methods
}

TitanTV.GridDisplay.prototype = {

  // property accessors.

  get_debug: function() { return this._debug; },
  set_debug: function(value) { this._debug = value; },

  get_commandUrl: function() { return this._commandUrl; },
  set_commandUrl: function(value) { this._commandUrl = value; },

  get_detailsUrl: function() { return this._detailsUrl; },
  set_detailsUrl: function(value) { this._detailsUrl = value; },

  get_printUrl: function() { return this._printUrl; },
  set_printUrl: function(value) { this._printUrl = value; },

  get_context: function() { return this._context; },
  set_context: function(value) { this._context = value; },

  get_layout: function() { return this._layout; },
  set_layout: function(value) { this._layout = value; },

  get_stationData: function()
  {
    return TitanTV.GridDisplay.StationData[this.get_element().id];
  },

  set_stationData: function(value)
  {
    if (value == null || value == '') return;

    var stationData = Sys.Serialization.JavaScriptSerializer.deserialize(value);

    TitanTV.GridDisplay.StationData[this.get_element().id] = stationData;
  },

  initialize: function()
  {
    var element = this.get_element();

    TitanTV.GridDisplay.Instances[element.id] = this;

    // Special case for pages with only one GridDisplay Object
    // Most pages should fall under this case.
    TitanTV.GridDisplay.Instances['grid'] = this;

    // create Delgates
    if (this.pageLoading === null) this.pageLoading = Function.createDelegate(this, this._pageLoading);
    if (this.openDetails === null) this.openDetails = Function.createDelegate(this, this._openDetailsInternal);
    if (this.executePVRCommand === null) this.executePVRCommand = Function.createDelegate(this, this._executePVRCommandInternal);
    if (this.doCommand === null) this.doCommand = Function.createDelegate(this, this._doCommandInternal);
    if (this.openIFrame === null) this.openIFrame = Function.createDelegate(this, this._openIFrameInternal);
    if (this.getStationData === null) this.getStationData = Function.createDelegate(this, this._getStationData);
    if (this.printGrid === null) this.printGrid = Function.createDelegate(this, this._printGrid);
    if (this.toggleFavorite === null) this.toggleFavorite = Function.createDelegate(this, this._toggleFavorite);

    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(this.pageLoading);

    TitanTV.GridDisplay.callBaseMethod(this, 'initialize');

    Sys.Debug.trace('Initialize: ' + element.id);

  },

  // Release resources before control is disposed.
  dispose: function()
  {
    var element = this.get_element();

    TitanTV.GridDisplay.Instances[element.id] = null;

    // Special case for pages with only one GridDisplay Object
    // Most pages should fall under this case.
    TitanTV.GridDisplay.Instances['grid'] = null;

    Sys.WebForms.PageRequestManager.getInstance().remove_pageLoading(this.pageLoading);

    if (this.pageLoading) delete this.pageLoading;
    if (this.openDetails) delete this.openDetails;
    if (this.executePVRCommand) delete this.executePVRCommand;
    if (this.doCommand) delete this.doCommand;
    if (this.openIFrame) delete this.openIFrame;
    if (this.getStationData) delete this.getStationData;
    if (this.printGrid) delete this.printGrid;
    if (this.toggleFavorite) delete this.toggleFavorite;

    TitanTV.GridDisplay.callBaseMethod(this, 'dispose');

    Sys.Debug.trace('Dispose: ' + element.id);
  },

  _pageLoading: function(sender, args)
  {
    if (!args) return;

    var element = this.get_element();
    var dataItems = args.get_dataItems();

    if (dataItems[element.id] == "clear")
      element.innerHTML = '';
  },

  _getStationData: function(stationIndex)
  {
    return this.get_stationData()[stationIndex];
  },

  _openDetailsInternal: function(e, stationIndex, scheduleId, status, replaceWindowContents)
  {
    this.doCommand(e, stationIndex, scheduleId, null, this._detailsUrl, status, replaceWindowContents ? "replace" : "details", null, null);

    return false;
  },

  _executePVRCommandInternal: function(e, stationIndex, scheduleId, command)
  {
    this.doCommand(e, stationIndex, scheduleId, null, this._commandUrl, command);

    // Google
    if (pageTracker) { pageTracker._trackPageview('/pvrcommand/' + command); }

    return false;
  },


  _doCommandInternal: function(e, stationIndex, scheduleId, programId, targetPage, command, action, wndWidth, wndHeight)
  {
    var queryString = "";

    queryString += this._buildQueryString("programid", programId);
    queryString += this._buildQueryString("scheduleid", scheduleId);
    queryString += this._buildQueryString("command", command);
    queryString += this._buildQueryString("context", this._context);

    var stationData = this.getStationData(stationIndex);

    if (stationData != null && stationData != 'undefined')
    {
      queryString += this._buildQueryString("callsign", stationData.cs);
      queryString += this._buildQueryString("stationid", stationData.sid);
      queryString += this._buildQueryString("psipid", stationData.pid);
      queryString += this._buildQueryString("channel", stationData.dc);
      queryString += this._buildQueryString("contenttype", stationData.pt);
      queryString += this._buildQueryString("major", stationData.maj);
      queryString += this._buildQueryString("minor", stationData.min);
      queryString += this._buildQueryString("hdcapable", stationData.hd);
    }

    var href = targetPage + "?" + queryString;

    Sys.Debug.trace("Command URL: " + href);

    if (this._debug)
    {
      var popWin = window.open(href, "T3Popup", "width=728,height=500,scrollbars=1,toolbar=0,locationbar=1,resize=1,resizable=1");
      popWin.focus();
      if (e && e.stopPropagation) e.stopPropagation();
      e.cancelBubble = true;
      return;
    }

    switch (action)
    {
      case "details":

        var detailsWindow;
        try { detailsWindow = GetRadWindowManager().getWindowByName('Details'); } catch (e) { }
        if (detailsWindow)
        {
          detailsWindow.setUrl(href);
          detailsWindow.show();
          detailsWindow.center();
        }
        else Sys.Debug.trace("detail window now found");


        break;

      case "replace": // Replace the contents of the current window.
        document.location.href = href;
        break;

      case "window": // Open a new window. (obsolete)
        popWin = window.open(href, "T3Popup", "width=" + wndWidth + ",height=" + wndHeight + ",scrollbars=0,toolbar=0,locationbar=0,resize=0,resizable=0");
        popWin.focus();
        break;

      default: // Execute the command URL in an IFrame
        this.openIFrame(href);
        break;
    }

    // Stop the click event from propogating further
    if (e && e.stopPropagation) e.stopPropagation();
    e.cancelBubble = true;
  },

  _printGrid: function()
  {
    this.openIFrame(this._printUrl);
  },

  _openIFrameInternal: function(href)
  {
    this._commandFrame = $get('commandFrame');

    if (this._commandFrame)
    {
      this._commandFrame.src = href;
    }
    else if (this._commandFrame == null && document && document.createElement)
    {
      this._commandFrame = document.createElement('iframe');
      this._commandFrame.setAttribute('id', 'commandFrame');
      this._commandFrame.setAttribute('name', 'commandFrame');
      this._commandFrame.setAttribute('src', href);
      this._commandFrame.style.position = "absolute";
      this._commandFrame.style.left = "-100px";
      this._commandFrame.style.height = "1px";
      this._commandFrame.style.width = "1px";

      document.body.appendChild(this._commandFrame);
    }

    if (this._commandFrame == null)
    {
      // Handle the case were we could not find the IFrame document
      CmdWin = window.open(href, "T3CMDWIN", "width=1,height=1,scrollbars=0,toolbar=0,locationbar=0,resize=0,resizable=0");
      CmdWin.blur();
      setTimeout('CmdWin.close();', 5000);
    }
  },

  _buildQueryString: function(name, value)
  {
    if (value === null || value == 'undefined' || value === '')
    {
      return '';
    }

    return "&" + name + "=" + escape(value);
  },

  _toggleFavorite: function(title, remove)
  {
    if (!title || !this._layout) return;

    var lowerTitle = title.toLowerCase();

    var cells = null;

    if (this._layout == "table")
      cells = this.get_element().getElementsByTagName("td");
    else if (this._layout == "span")
      cells = this.get_element().getElementsByTagName("span"); /* Search Results */
    else
      cells = this.get_element().getElementsByTagName("div"); /* Daily */

    lowerTitle = lowerTitle.replace('&', '&amp;');

    for (i = 0; i < cells.length; i++)
    {
      var cell = cells[i];

      if (!cell) break;

      // if it doesn't have the data attribute, it's not the droid we're looking for.
      if (!cell.getAttribute("data")) continue;

      var titleNode = $get('tn', cell);
      if (titleNode && titleNode.innerHTML.toLowerCase() == lowerTitle)
      {
        var favClassName = "gFav";

        if (!remove && !Sys.UI.DomElement.containsCssClass(cell, favClassName))
          Sys.UI.DomElement.addCssClass(cell, favClassName);
        else if (remove && Sys.UI.DomElement.containsCssClass(cell, favClassName))
          Sys.UI.DomElement.removeCssClass(cell, favClassName);
      }
    }
  }
}

TitanTV.GridDisplay.registerClass('TitanTV.GridDisplay', Sys.UI.Control);

// Static Properties and Methods

TitanTV.GridDisplay.Instances = new Object();
TitanTV.GridDisplay.StationData = new Object();
TitanTV.GridDisplay.GetInstance = function(instanceId)
{
  if (instanceId == null || instanceId == '')
    instanceId = 'grid';

  return TitanTV.GridDisplay.Instances[instanceId];
}

TitanTV.GridDisplay.Print = function(instanceId)
{
  var gridDisplay = TitanTV.GridDisplay.GetInstance(instanceId);

  if (!gridDisplay) return;

  gridDisplay.printGrid();
}

// 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();

