﻿Type.registerNamespace("TitanTV");

// Constructor
TitanTV.LineupCreator = function(element)
{

  TitanTV.LineupCreator.initializeBase(this, [element]);

  // Private variables
  this._postbackID = null;
  this._modalExtenderElementID = null;
  this._lineupFilePath = '';
  this._lineupData = null;
  this._searchZip = null;
  this._showWelcome = false;

  // UI Elements
  this._WelcomeViewElement = null;
  this._WelcomeUseButton = null;
  this._WelcomeCustomizeButton = null;

  this._ContentTypeViewElement = null;
  this._BroadcastElement = null;
  this._CableElement = null;
  this._DigitalCableElement = null;
  this._SatelliteElement = null;
  this._ContentTypeCancelButton = null;

  this._LoadingViewElement = null;
  this._LoadingErrorViewElement = null;

  this._ZipEntryViewElement = null;
  this._ZipEntryInput = null;
  this._ZipEntrySelectionsElement = null;
  this._ZipEntrySelectButton = null;
  this._ZipEntrySelectButtonDisabled = null;
  this._ZipEntryCancelButton = null;
  this._ZipEntryBackButton = null;
  this._ZipEntryPreZipMessage = null;
  this._ZipEntryPostZipMessage = null;
  this._ZipEntryNoMatchesMessage = null;

  this._LineupViewElement = null;

  this._CustomViewElement = null;
  this._CustomNameInput = null;
  this._CustomSaveButton = null;
  this._CustomCancelButton = null;

  // Methods
  this.setView = null;

  // Private methods
  this.cancel = null;
  this.back = null;
  this.pageLoading = null;
  this.selectContentType = null;
  this.loadProviderData = null;
  this.providerDataLoaded = null;
  this.onZipInput = null;
  this.searchProviders = null;
  this.onSelectLineup = null;
  this.isObjectOrChild = null;
  this.onSaveCustom = null;
}

TitanTV.LineupCreator.prototype = {

  // property accessors.

  get_postbackID: function() { return this._postbackID; },
  set_postbackID: function(value) { this._postbackID = value; },

  get_lineupFilePath: function() { return this._lineupFilePath; },
  set_lineupFilePath: function(value) { this._lineupFilePath = value; },

  get_modalExtenderElementID: function() { return this._modalExtenderElementID; },
  set_modalExtenderElementID: function(value) { this._modalExtenderElementID = value; },

  get_showWelcome: function() { return this._showWelcome; },
  set_showWelcome: function(value) { this._showWelcome = value; },

  initialize: function()
  {
    var element = this.get_element();

    // create Delgates
    if (this.setView === null) this.setView = Function.createDelegate(this, this._setView);
    if (this.cancel === null) this.cancel = Function.createDelegate(this, this._cancel);
    if (this.back === null) this.back = Function.createDelegate(this, this._back);
    if (this.pageLoading === null) this.pageLoading = Function.createDelegate(this, this._pageLoading);
    if (this.selectContentType === null) this.selectContentType = Function.createDelegate(this, this._selectContentType);
    if (this.loadProviderData === null) this.loadProviderData = Function.createDelegate(this, this._loadProviderData);
    if (this.providerDataLoaded === null) this.providerDataLoaded = Function.createDelegate(this, this._providerDataLoaded);
    if (this.onZipInput === null) this.onZipInput = Function.createDelegate(this, this._onZipInput);
    if (this.searchProviders === null) this.searchProviders = Function.createDelegate(this, this._searchProviders);
    if (this.onSelectLineup === null) this.onSelectLineup = Function.createDelegate(this, this._onSelectLineup);
    if (this.isObjectOrChild === null) this.isObjectOrChild = Function.createDelegate(this, this._isObjectOrChild);
    if (this.onSaveCustom === null) this.onSaveCustom = Function.createDelegate(this, this._onSaveCustom);

    // Welcome
    this._WelcomeViewElement = $get('welcome', element);
    this._WelcomeUseButton = $get('welcomeUse', this._WelcomeViewElement);
    this._WelcomeCustomizeButton = $get('welcomeCustomize', this._WelcomeViewElement);

    Sys.UI.DomEvent.addHandler(this._WelcomeUseButton, 'click', this.cancel);
    Sys.UI.DomEvent.addHandler(this._WelcomeCustomizeButton, 'click', this.back);


    // Content Type
    this._ContentTypeViewElement = $get('contentType', element);
    this._BroadcastElement = $get('broadcast', this._ContentTypeViewElement);
    this._CableElement = $get('cable', this._ContentTypeViewElement);
    this._DigitalCableElement = $get('digitalCable', this._ContentTypeViewElement); ;
    this._SatelliteElement = $get('satellite', this._ContentTypeViewElement);
    this._ContentTypeCancelButton = $get('contentTypeCancel', this._ContentTypeViewElement);

    Sys.UI.DomEvent.addHandler(this._BroadcastElement, 'click', this.selectContentType);
    Sys.UI.DomEvent.addHandler(this._CableElement, 'click', this.selectContentType);
    Sys.UI.DomEvent.addHandler(this._DigitalCableElement, 'click', this.selectContentType);
    Sys.UI.DomEvent.addHandler(this._SatelliteElement, 'click', this.selectContentType);

    Sys.UI.DomEvent.addHandler(this._ContentTypeCancelButton, 'click', this.cancel);

    // Loading
    this._LoadingViewElement = $get('loading', element);

    // Loading Error
    this._LoadingErrorViewElement = $get('loadingError', element);
    this._LoadingErrorCancelButton = $get('loadingErrorCancel', this._LoadingErrorViewElement);

    Sys.UI.DomEvent.addHandler(this._LoadingErrorCancelButton, 'click', this.cancel);

    // Zip Entry
    this._ZipEntryViewElement = $get('zipEntry', element);
    this._ZipEntryInput = $get('zipEntryInput', this._ZipEntryViewElement);
    this._ZipEntrySelectionsElement = $get('zipEntrySelections', this._ZipEntryViewElement);
    this._ZipEntrySelectButton = $get('zipEntrySelect', this._ZipEntryViewElement);
    this._ZipEntrySelectButtonDisabled = $get('zipEntrySelectDisabled', this._ZipEntryViewElement);
    this._ZipEntryCancelButton = $get('zipEntryCancel', this._ZipEntryViewElement);
    this._ZipEntryBackButton = $get('zipEntryBack', this._ZipEntryViewElement);
    this._ZipEntryPreZipMessage = $get('zipEntryPreZipMessage', this._ZipEntryViewElement);
    this._ZipEntryPostZipMessage = $get('zipEntryPostZipMessage', this._ZipEntryViewElement);
    this._ZipEntryNoMatchesMessage = $get('zipEntryNoMatchesMessage', this._ZipEntryViewElement);

    Sys.UI.DomEvent.addHandler(this._ZipEntryInput, 'keyup', this.onZipInput);
    Sys.UI.DomEvent.addHandler(this._ZipEntryCancelButton, 'click', this.cancel);
    Sys.UI.DomEvent.addHandler(this._ZipEntryBackButton, 'click', this.back);
    Sys.UI.DomEvent.addHandler(this._ZipEntrySelectButton, 'click', this.onSelectLineup);

    // Custom

    this._CustomViewElement = $get('custom', element);
    this._CustomViewElement.invalidValueCSSClass = this._CustomViewElement.getAttribute("invalidCSSClass");

    this._CustomSaveButton = $get('customSave', this._CustomViewElement);
    this._CustomCancelButton = $get('customCancel', this._CustomViewElement);
    this._CustomNameInput = $get('customName', this._CustomViewElement);

    Sys.UI.DomEvent.addHandler(this._CustomSaveButton, 'click', this.onSaveCustom);
    Sys.UI.DomEvent.addHandler(this._CustomCancelButton, 'click', this.cancel);

    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(this.pageLoading);

    if (this._showWelcome)
      this.setView('welcome');

    TitanTV.LineupCreator.callBaseMethod(this, 'initialize');

    Sys.Debug.trace('Initialize: ' + element.id);
  },

  // Release resources before control is disposed.
  dispose: function()
  {
    var element = this.get_element();

    if (this.setView) delete this.setView;

    if (this.cancel)
    {
      Sys.UI.DomEvent.removeHandler(this._ContentTypeCancelButton, 'click', this.cancel);
      Sys.UI.DomEvent.removeHandler(this._ZipEntryCancelButton, 'click', this.cancel);
      Sys.UI.DomEvent.removeHandler(this._LoadingErrorCancelButton, 'click', this.cancel);
      Sys.UI.DomEvent.removeHandler(this._CustomCancelButton, 'click', this.cancel);
      Sys.UI.DomEvent.removeHandler(this._WelcomeUseButton, 'click', this.cancel);
      delete this.cancel;
    }

    if (this.back)
    {
      Sys.UI.DomEvent.removeHandler(this._ZipEntryBackButton, 'click', this.back);
      Sys.UI.DomEvent.removeHandler(this._WelcomeCustomizeButton, 'click', this.back);
      delete this.back;
    }

    if (this.pageLoading)
    {
      Sys.WebForms.PageRequestManager.getInstance().remove_pageLoading(this.pageLoading);
      delete this.pageLoading;
    }

    if (this.selectContentType)
    {
      Sys.UI.DomEvent.removeHandler(this._BroadcastElement, 'click', this.selectContentType);
      Sys.UI.DomEvent.removeHandler(this._CableElement, 'click', this.selectContentType);
      Sys.UI.DomEvent.removeHandler(this._DigitalCableElement, 'click', this.selectContentType);
      Sys.UI.DomEvent.removeHandler(this._SatelliteElement, 'click', this.selectContentType);
      delete this.selectContentType;
    }

    if (this.loadProviderData) delete this.loadProviderData;
    if (this.providerDataLoaded) delete this.providerDataLoaded;
    if (this.onZipInput)
    {
      Sys.UI.DomEvent.removeHandler(this._ZipEntryInput, 'keyup', this.onZipInput);
      delete this.onZipInput;
    }

    if (this.onSelectLineup)
    {
      Sys.UI.DomEvent.removeHandler(this._ZipEntrySelectButton, 'click', this.onSelectLineup);
      delete this.onSelectLineup;
    }

    if (this.searchProviders) delete this.searchProviders;
    if (this.isObjectOrChild) delete this.isObjectOrChild;

    if (this.onSaveCustom)
    {
      Sys.UI.DomEvent.removeHandler(this._CustomSaveButton, 'click', this.onSaveCustom);
      delete this.onSaveCustom;
    }

    TitanTV.LineupCreator.callBaseMethod(this, 'dispose');

    Sys.Debug.trace('Dispose: ' + element.id);
  },

  // Show Cell Menu
  _setView: function(view)
  {
    this._WelcomeViewElement.style.display = 'none';
    this._ContentTypeViewElement.style.display = 'none';
    this._LoadingViewElement.style.display = 'none';
    this._ZipEntryViewElement.style.display = 'none';
    this._LoadingErrorViewElement.style.display = 'none';
    this._ZipEntrySelectButton.style.display = 'none';
    this._ZipEntrySelectButtonDisabled.style.display = '';
    this._ZipEntryPreZipMessage.style.display = 'none';
    this._ZipEntryPostZipMessage.style.display = 'none';
    this._ZipEntryNoMatchesMessage.style.display = 'none';
    this._CustomViewElement.style.display = 'none';

    switch (view)
    {
      case "welcome":
        this._WelcomeViewElement.style.display = 'block';
        break;

      case "loading":
        this._LoadingViewElement.style.display = 'block';
        break;

      case "loadingError":
        this._LoadingErrorViewElement.style.display = 'block';
        break;

      case "zipEntry":
        this._ZipEntryViewElement.style.display = 'block';
        this._ZipEntryPreZipMessage.style.display = 'block';
        this._ZipEntryInput.value = (this._searchZip != null) ? this._searchZip : '';
        break;

      case "noMatches":
        this._ZipEntryViewElement.style.display = 'block';
        this._ZipEntryNoMatchesMessage.style.display = 'block';
        break;

      case "selectLineup":
        this._ZipEntryViewElement.style.display = 'block';
        this._ZipEntrySelectButton.style.display = '';
        this._ZipEntryPostZipMessage.style.display = 'block';
        this._ZipEntrySelectButtonDisabled.style.display = 'none';
        break;

      case "custom":
        if (this._CustomViewElement.invalidValueCSSClass) Sys.UI.DomElement.removeCssClass(this._CustomNameInput, this._CustomViewElement.invalidValueCSSClass);
        this._CustomNameInput.value = "";
        this._CustomViewElement.style.display = 'block';
        break;

      default:
        this._ContentTypeViewElement.style.display = 'block';
        break;
    }

  },

  _cancel: function(e)
  {
    this.lineupData = null;

    var modalExtender = $find(this._modalExtenderElementID);

    if (modalExtender)
      modalExtender.hide();
    else
      __doPostBack(this._postbackID, 'cancel');
  },

  _back: function(e)
  {
    if (e.target === this._ZipEntryBackButton || e.target === this._WelcomeCustomizeButton)
      this.setView("contentType");
  },

  _pageLoading: function(sender, args)
  {
    if (!args) return;

    var dataItems = args.get_dataItems();
    var elementId = this.get_element().id;

    var command = dataItems[elementId];

    switch (command)
    {
      case "custom":
        this.setView("custom");
        break;
      case "reset":
        this._showWelcome = false;
        this.setView();
        break;
      case "hide":
        break;
    }
  },

  _selectContentType: function(e)
  {
    var dataFile = null;

    if (this.isObjectOrChild(this._BroadcastElement, e.target))
    //if(e.target === this._BroadcastElement)
      dataFile = "broadcast.js";
    else if (this.isObjectOrChild(this._CableElement, e.target))
      dataFile = "cable.js";
    else if (this.isObjectOrChild(this._DigitalCableElement, e.target))
      dataFile = "digital_cable.js";
    else if (this.isObjectOrChild(this._SatelliteElement, e.target))
      dataFile = "satellite.js";
    else
      return;

    this.setView("loading");

    this.loadProviderData(this._lineupFilePath + dataFile);
  },

  _loadProviderData: function(dataUrl)
  {
    // Instantiate the WebRequest object.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request Url.
    wRequest.set_url(dataUrl);

    // Set the request verb.
    wRequest.set_httpVerb("GET");

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(this.providerDataLoaded);

    // Execute the request.
    wRequest.invoke();
  },

  // This the handler for the Web request completed event
  // that is used to display return data.
  _providerDataLoaded: function(executor, eventArgs)
  {
    if (executor.get_responseAvailable())
    {
      try
      {
        var lineupData = "(" + executor.get_responseData() + ")";
        this._lineupData = eval(lineupData);
        this.setView("zipEntry");
        this.searchProviders();
      }
      catch (ex)
      {
        Sys.Debug.trace("Data Load Error: " + executor.get_responseData());
        this.setView("loadingError");
      }
    }
    else
    {
      if (executor.get_timedOut())
        Sys.Debug.trace("Request Timed Out");
      else if (executor.get_aborted())
        Sys.Debug.trace("Request Aborted");

      this.setView("loadingError");
    }
  },

  _onZipInput: function(e)
  {
    var zipCode = e.target.value;

    if (!zipCode.match(/[0-9]{5}/)) return;

    if (zipCode == this._searchZip) return;

    this._searchZip = zipCode;

    this.searchProviders();
  },

  _searchProviders: function()
  {
    if (this._searchZip == null) return;

    // Run the search
    var lineupArray = new Array();

    var zipSearchArray = this._lineupData.zipcodes[this._searchZip]

    if (zipSearchArray != null && zipSearchArray != 'undefined' && zipSearchArray.length > 0)
      Array.addRange(lineupArray, zipSearchArray);

    var nationalArray = this._lineupData.zipcodes["00000"]

    if (nationalArray != null && nationalArray != 'undefined' && nationalArray.length > 0)
      Array.addRange(lineupArray, nationalArray);

    var selectionHtml = null;
    if (lineupArray.length > 4)
    {
      var selectName = this.get_element().id + "_select";

      selectionHtml = String.format("<select name='{0}'>", selectName);
      for (var i = 0; i < lineupArray.length; i++)
      {
        var lineup = this._lineupData.lineups[lineupArray[i]];
        var lineupName = String.format("{0} ({1})", lineup.name, lineup.location);
        if (lineupName.length > 50) lineupName = lineupName.substring(0, 50)
        selectionHtml += String.format("<option value='{0}'>{1}</option>", lineupArray[i], lineupName);
      }
      selectionHtml += "</select>";
    }
    else if (lineupArray.length > 0)
    {
      var radioName = this.get_element().id + "_radio";

      selectionHtml = "<table>";
      for (var i = 0; i < lineupArray.length; i++)
      {
        var lineup = this._lineupData.lineups[lineupArray[i]];
        var checked = (i == 0) ? "checked='checked'" : "";
        selectionHtml += String.format("<tr><td valign='top' style='padding-right:5px;'><input type='radio' name='{3}' value='{0}' {4}></td><td valign='top' style='text-align:left; padding-bottom:5px;'><b>{1}</b><br />{2}</td></tr>", lineupArray[i], lineup.name, lineup.location, radioName, checked);
      }
      selectionHtml += "</table>";
    }

    if (selectionHtml == null)
      this.setView('noMatches');
    else
      this.setView('selectLineup');

    this._ZipEntrySelectionsElement.innerHTML = selectionHtml;
  },

  _onSelectLineup: function()
  {
    var selectedLineup = null;

    var form = document.forms[0];

    for (var i = 0; i < form.elements.length; i++)
    {
      var radioName = this.get_element().id + "_radio";
      var selectName = this.get_element().id + "_select";
      var formElement = form.elements[i];

      if (formElement.type == 'radio' && formElement.name == radioName && formElement.checked == true)
        selectedLineup = formElement.value;
      else if (formElement.type == 'select-one' && formElement.name == selectName)
        selectedLineup = formElement.value

      if (selectedLineup != null) break;
    }

    if (selectedLineup == null || selectedLineup == "")
      return;

    Sys.Debug.trace("Selected Lineup: " + selectedLineup);

    this._ZipEntryInput.value = "";

    this.lineupData = null;

    var modalExtender = $find(this._modalExtenderElementID);

    if (modalExtender) modalExtender.hide();

    __doPostBack(this._postbackID, 'select|' + selectedLineup + "|" + (this._showWelcome ? 1 : 0));
  },

  _isObjectOrChild: function(object, target)
  {
    if (object === target) return true;
    else if (target.parentNode)
      return this.isObjectOrChild(object, target.parentNode);
    else
      return false;
  },

  _onSaveCustom: function()
  {
    var valid = true;

    // Validate Name
    if (this._CustomNameInput.value.trim() == "")
    {
      if (this._CustomViewElement.invalidValueCSSClass) Sys.UI.DomElement.addCssClass(this._CustomNameInput, this._CustomViewElement.invalidValueCSSClass);
      valid = false;
    }
    else if (this._CustomViewElement.invalidValueCSSClass)
    {
      Sys.UI.DomElement.removeCssClass(this._CustomNameInput, this._CustomViewElement.invalidValueCSSClass);
    }

    if (!valid)
    {
      return false;
    }

    var modalExtender = $find(this._modalExtenderElementID);

    if (modalExtender) modalExtender.hide();

    __doPostBack(this._postbackID, String.format('createcustom|{0}', escape(this._CustomNameInput.value)));
  }

}

TitanTV.LineupCreator.registerClass('TitanTV.LineupCreator', Sys.UI.Control);

// 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();