﻿// dependencies: jQuery, CoreWS.js, global.js

// this class assumes knowledge of the names and functional interfaces
// of it's child object graph.

LivePage = function(seed, username, defaultMediaPlayer, livestreamURL, mediaURL, streamServerURL, totalVideos, rmtpServer, isLive, webcastID, lat, lon, zoom, title, flashArcURL, pp) {
  this.seqNum = seed;
  this.username = username;

  var pThis = this;
  this.RefreshLiveStatus = function() { LivePage.prototype.RefreshLiveStatus(pThis); }

  // connect events/event handlers of the top-level page objects
  wireUpEvents = function() {
    if (!(MediaPlayerControl && LivecastMapControl && Gallery &&
         UserProfileSidebar && PlayerController && InfoPanel && SharePanel && CommentsPanel)) {
      // child objects are not yet instantiated, try again in a bit...
      setTimeout(wireUpEvents, 150);
    }
    else {
      // event -> handlers          
      MediaPlayerControl.onGPSEvent = function(args) {
        LivecastMapControl.setLocation(args.latitude, args.longitude);
        LivecastMapControl.addCrumb(args.latitude, args.longitude);
      };

      InfoPanel.onLocationEvent = function(lat, lon, zoom) { LivecastMapControl.loadMap(lat, lon, zoom); };

      Gallery.onItemClickedEvent = function(args) { pThis.playArchive(pThis, args) };

      UserProfileSidebar.onSwitchToLivestreamEvent = function() {
        pThis.playLivestream();
        InfoPanel.fetchWebcastInfo(PlayerController.webcastID);
      };
      UserProfileSidebar.showSIPstatus(isLive);

      // init child objects with data from .cs
      UserProfileSidebar.isViewingLivestream = isLive;
      UserProfileSidebar.updateVideoCount(totalVideos);

      PlayerController.playingLive = isLive;
      PlayerController.webcastID = webcastID;
      PlayerController.livestreamURL = livestreamURL;
      PlayerController.streamServerURL = streamServerURL.replace(/<%=username%>/, username);
      if(IsMacAndNoWindowsMediaPlugin()) defaultMediaPlayer = 'QT'; // global.js
      PlayerController.setInitialTab(defaultMediaPlayer);
      PlayerController.flashArchiveSource = flashArcURL;

      MediaPlayerControl.rmtpServer = rmtpServer;
      if(defaultMediaPlayer == 'Flash') {
        MediaPlayerControl.isFlashPlayer = true;
        if(isLive) defaultMediaPlayer = 'Flowplayer';
      }
      MediaPlayerControl.currentPlayer = defaultMediaPlayer;
      MediaPlayerControl.onBufferEmpty = PlayerController.emptyBufferHandler;
      MediaPlayerControl.onBufferFull = PlayerController.fullBufferHandler;

      if(lat && lon && zoom) LivecastMapControl.loadMap(lat, lon, zoom); else LivecastMapControl.reset();      
      if(webcastID > 0 && !isLive)
        pThis.playArchive(pThis, { pp:pp, lat:lat, lon:lon, zoom:zoom, title:title, mediaID:webcastID });
      else
        MediaPlayerControl.play(mediaURL); // default video
      if(isLive) {
        if(webcastID > 0) InfoPanel.fetchWebcastInfo(webcastID);
        pThis.livecastID = webcastID ? webcastID : 0;
        pThis.livecastON();
      }
    }
  };

  wireUpEvents();
  SID = $.cookie['CSID'] || $('#SID').val(); // database session
  $('#copyYear').text(new Date().getFullYear().toString());
  $('#videoTitle').text( (title == null || title == '') ? 'Welcome to My Live Page' : title);
  window.setTimeout(this.RefreshLiveStatus, 10000);
};

LivePage.prototype = {

  seqNum: 0,
  username: '_',
  isLivecast : false,
  livecastID : 0,

  livecastON: function() {
    this.isLivecast = true;
    SharePanel.livestream(this.username);    
    SharePanel.setLivecast(this.livecastID);
    CommentsPanel.userPlayLive(this.livecastID);
  },
  
  livecastOFF: function(mediaID) {
    this.isLivecast = false;
  },

  playLivestream : function() {
    if(PlayerController.isLive()) {
      PlayerController.playLivestream(this.seqNum);
      $('#videoTitle').text('Live webcast');
      UserProfileSidebar.isViewingLivestream = true;
      this.livecastON();
      Gallery.setHighlight(0);
      if(this.livecastID > 0) MediaGridTabContainerObject.incrementViewCount(this.livecastID);
    };
  },

  playArchive : function(pThis, args) {
    PlayerController.playArchive(args.mediaID, args.pp);
    MediaGridTabContainerObject.incrementViewCount(args.mediaID);
    UserProfileSidebar.isViewingLivestream = false;
    if(args.lat && args.lon && args.zoom)
      LivecastMapControl.setLocation(args.lat, args.lon, args.zoom);
    else
      LivecastMapControl.reset();
    $('#videoTitle').text(args.title);
    InfoPanel.fetchWebcastInfo(args.mediaID);
    SharePanel.changeMedia(args.mediaID);
    pThis.livecastOFF();
    CommentsPanel.userPlayArchive(args.mediaID);    
  },

  // polling mechanism to test if
  // the user has a live stream, and display the appropriate icon
  RefreshLiveStatus : function(pThis)
  {
    try {
      ++pThis.seqNum;
      var url = "../status.aspx?" + pThis.username + "&seq=" + pThis.seqNum;
      document.getElementById('imgLive').src = url;      

      url = 'http://' + location.hostname + '/ajax/GetLivecast.ashx?sid='+SID;
      $.getJSON(url, 
        { u: pThis.username, seq: pThis.seqNum }, 
        function(result) {
          var id = result.webcast.id;
          PlayerController.setLivecast(id);
          SharePanel.setLivecast(id);
          CommentsPanel.setLivecast(id);
          UserProfileSidebar.showLivelink(id, pThis.seqNum);

          var isNewLivecast = (pThis.isLivecast && id && id != pThis.livecastID);
          pThis.livecastID = id || 0;
          if(result.webcast.title && pThis.isLivecast)
            $('#videoTitle').text(result.webcast.title);
          if(isNewLivecast) {
            if(result.webcast.lat) LivecastMapControl.setLocation(result.webcast.lat, result.webcast.lon, result.webcast.zoom);
            pThis.playLivestream();
            InfoPanel.fetchWebcastInfo(id);
          }
        }
      );
    } catch(err) {}

    window.setTimeout(pThis.RefreshLiveStatus,7000);
  }
};
