var membersHome = {
  LONG_DESC_THRESH: 450,
  PLAYLIST_HEIGHT: 372,
  DESC_HEIGHT: 0,

  activeChannel: null,

  currentLongDesc: null,

  initEvents: function () {
    // Added by Gaston
    $("#freeOnly").change(function () {
      // <input type="checkbox" name="freeOnly" id="freeOnly" onchange="revCove.freeContentOnly = $(this).is(':checked');revCove.displayPlaylist();" />*@
      revCove.freeContentOnly = $(this).is(':checked');
      revCove.displayPlaylist();
    });

    // EOF Added by Gaston
    $("#sortByWrapper .customDropdownOptions div").click(function () {
      revCove.currentSortBy = $(this).attr("data-value");
      $("#sortByWrapper span.bBlue").html(revCove.sortByDisplayNamesMap[revCove.currentSortBy]);
      revCove.sortVideos({
        field: revCove.currentSortBy,
        dir: revCove.currentSortDir,
        action: revCove.setPlaylist,
        loadFirst: false
      });
    });

    $("#swapDir").click(function () {
      revCove.currentSortDir = !revCove.currentSortDir;
      if (revCove.currentSortDir == revCove.DESC) {
        $(this).html("desc");
      }
      else {
        $(this).html("asc");
      }

      revCove.sortVideos({
        field: revCove.currentSortBy,
        dir: revCove.currentSortDir,
        action: revCove.setPlaylist,
        loadFirst: false
      });
    });

    $("#addToFavorites").click(function () {
      if ($(this).text().indexOf("Add") > -1) {
        revCove.favorite(true, function () {
          membersHome.refreshFavoritesDD();
        });
      }
      else {
        revCove.favorite(false, function () {
          membersHome.refreshFavoritesDD();
        });
      }

      // EOF Added by Gaston
    });

    $("#videoDescription .moreLess").click(function () {
      var spanEl = $(this).find("span");
      var desc = $(this).prev();
      var playlist = $("#playlistWrapper");

      if (spanEl.html() == "More") {
        spanEl.html("Less");
        desc.html(membersHome.currentLongDesc.fullDisplay);
        playlist.css("height", ($(this).parent().height() - membersHome.DESC_HEIGHT)
                        + membersHome.PLAYLIST_HEIGHT);
        revCove.updateScroll();
      } else {
        spanEl.html("More");
        desc.html(membersHome.currentLongDesc.shortDisplay);
        playlist.css("height", membersHome.PLAYLIST_HEIGHT);
        revCove.updateScroll();
      }
    });

    //get favorites' names and build dropdown
    // Not necessary anymore because we've already pupulated the name for each favorited video
    // in the home view
    // Therefore, we just call the previous callback
    //        revCove.getVideosByIds({
    //            ids: revCove.objArrayToSimpleArray(revCove.currentFavorites, "id"),
    //            callbackId: "Favorited",
    //            fields: "id,name"
    //        });
    membersHome.onVideosByIdsFavorited(revCove.currentFavorites);

    //get products' names and build dropdown
    membersHome.createProductsDropDown();

    $('#addToCart').bind('click', function (e) {
      e.preventDefault();
      var url = '/ShoppingCart/AddVideoToCart/?videoId=' + revCove.currentVideo.id;

      $.get(url, function (data) {
        modal.setWidth(700);
        var posX = ($(window).width() / 2) - ((modal.getWidth() / 2));
        if (posX < 50) {
          posX = 50;
        }
        modal.setPosition([posX, 110]);
        modal.setTitle("Add to Cart");
        modal.setHtml(data);
        modal.open();
      });
    });
  },

  refreshFavoritesDD: function () {
    // Refresh the Your Favorites dropdown
    // First, clear the dropdown options
    $("#yourFavoritesWrapper .customDropdownOptions").html("");
    // Then, fill options again
    // Not necessary anymore because revCove.favorite uses the name value for the video, already populated
    //revCove.getVideosByIds({ ids: revCove.objArrayToSimpleArray(revCove.currentFavorites, "id"), callbackId: "Favorited", fields: "id,name" });
    // Now, we just have to refresh the dropdown options, without retrieving additional values from Brightcove
    membersHome.onVideosByIdsFavorited(revCove.currentFavorites);
  },

  onVideosByIdsFavorited: function (items) {
    if (items && items.length > 0) {
      for (var i = 0, max = items.length; i < max; i++) {
        //revCove.currentFavorites[items[i].id].name = items[i].name;
        membersHome.createVideoDropDownItem(items[i], "yourFavoritesWrapper", (i == (max - 1) ? "last" : ""));
      }
    }
    else {
      $("#yourFavoritesWrapper .customDropdownOptions")
                .append($("<div></div>").addClass("last")
                    .append($("<span></span>").text("You have no favorite videos.")));
    }
  },

  //after getting the full video obj from brightcove we have to get its additional details from the db
  onVideosByIdsAd: function (items) {
    alert("onVideosByIdsAd");

    //only one item should be returned
    revCove.currentVideo = items[0];

    revCove.getVideosDetails({
      items: [revCove.currentVideo],
      success: function () {
        revCove.currentVideo.notComplete = false;
        revCove.setBasePageValues(revCove.currentVideo);
      },
      error: function () {
        //error handling
      },
      setNewDataTo: revCove.currentVideo
    });
  },

  createProductsDropDown: function () {
    if (revCove.currentPurchased.length > 0) {
      for (var i = 0, max = revCove.currentPurchased.length; i < max; i++) {
        $("#yourProductWrapper .customDropdownOptions")
                    .append($("<div></div>").attr("data-value", revCove.currentPurchased[i].id).addClass(i == (max - 1) ? "last" : "")
                        .append($("<span></span>").text(revCove.currentPurchased[i].productName))
                        .click(function () {
                          window.location.href = "/home/product/" + $(this).attr("data-value");
                        }));
      }
    }
    else {
      $("#yourProductWrapper .customDropdownOptions")
                .append($("<div></div>").addClass("last")
                    .append($("<span></span>").text("You have no purchased videos.")));
    }
  },

  createVideoDropDownItem: function (item, containerName, className) {
    $("#" + containerName + " .customDropdownOptions")
            .append($("<div></div>").attr("data-value", item.id).addClass(className)
                .append($("<span></span>").text(item.name))
                .click(function () {
                  window.location.href = "/home/video/" + $(this).attr("data-value");
                }));
  },

  changeFavoriteText: function () {
    var add = $("#addToFavorites span");
    if (add.text().indexOf("Add") > -1) {
      add.html("Remove from my favorites");
    }
    else {
      add.html("Add this to my favorites");
    }
  },

  //used when clicking chapter names (don't want to just toggle in case it is already open)
  expandTree: function (jqElement) {
    var chapVideos = jqElement.siblings(".chapVideos");
    if (!chapVideos.hasClass("active")) {
      chapVideos.addClass("active");
    }
  },

  //init functional elements and values that are not events
  initFunc: function () {
    //store current sorting / filter values
    revCove.freeContentOnly = $("#freeOnly").is(":checked");

    //init slider
    membersHome.initSlider();
    //init slider for channel
    membersHome.initSliderForChannel();
  },

  initSlider: function () {
    revCove.playlistScroller = $('#playlistWrapper');
    revCove.playlistScroller.jScrollPane({
      showArrows: true,
      verticalGutter: 0,
      animateScroll: true,
      verticalDragMinHeight: 98,
      verticalDragMaxHeight: 98,
      animateTo: true
      //            autoReinitialise: true
    });
    revCove.playlistScrollerApi = revCove.playlistScroller.data('jsp');
  },

  initSliderForChannel: function () {
    revCove.channelScroller = $('#channelWrapper');
    revCove.channelScroller.jScrollPane({
      showArrows: true,
      verticalGutter: 0,
      animateScroll: true,
      verticalDragMinHeight: 98,
      verticalDragMaxHeight: 98,
      animateTo: true
      //            autoReinitialise: true
    });
    revCove.channelScrollerApi = revCove.channelScroller.data('jsp');
  },

  //set appropriate values in page that need setting as a video starts playing
  setValues: function (item) {
    var videoDescription = $("#videoDescription"),
            videoActions = $("#videoActions"),
            rating,
            ratingNode;

    //set description: preference is longDescription > shortDescription > default text
    membersHome.currentLongDesc = {
      original: item.longDescription || item.shortDescription || null,
      fullDisplay: item.longDescription || (item.shortDescription || "This video has no description."),
      shortDisplay: item.longDescription || (item.shortDescription || "This video has no description.")
    };

    if (membersHome.currentLongDesc.fullDisplay.length > membersHome.LONG_DESC_THRESH) {
      membersHome.currentLongDesc.shortDisplay =
                    membersHome.currentLongDesc.fullDisplay.substr(0, membersHome.LONG_DESC_THRESH) + "...";
      videoDescription.find(".moreLess").find("span").html("MORE").end().show();
    }
    else {
      videoDescription.find(".moreLess").hide();
    }

    videoDescription.find("span.longDescription").html(membersHome.currentLongDesc.shortDisplay);
    videoDescription.find("span.name").html(item.name);

    //set rating
    rating = revCove.getRating(item);
    ratingNode = videoActions.find("#rating");

    revCove.updateRatingClass("#rating", rating.type);
    ratingNode.attr("data-rating", rating.rating);

    if (rating.rating != Math.round(rating.rating)) {
      revCove.displayPartialRating(ratingNode);
    }
    else {
      revCove.updateRating("#rating", rating.rating);
    }
    videoActions.find("#ratingNumber").html(rating.rating != "0" ? rating.rating : "none");

    //set favorite text
    // old code
    // $("#addToFavorites span").text(item.favorited ? "Remove from my favorites" : "Add this to my favorites");
    // item.favorited can be undefined
    var isFavorited = false;
    if (item.favorited) {
      // item.favorited is true and not undefined, and therefore, we can use its bool value
      isFavorited = item.favorited;
    }
    else {
      // item.favorited is undefined or false!!!
      // Check the current favorites array
      isFavorited = (jQuery.grep(revCove.currentFavorites, function (value) { return value.id == revCove.currentVideo.id; }).length > 0);
    }
    videoActions.find("#addToFavorites span").text(isFavorited ? "Remove from my favorites" : "Add this to my favorites");

    //update the comments below to work with the current video/clique
    revCove.updateComments();

    //set status of "now playing" thumb in playlist
    revCove.updateNowPlaying(item.id);

    //hide/show add to cart button for free/paid video
    if (item.paid && !item.owned) {
      videoActions.find("#addToCart").show();
      videoActions.find("#download").hide();
    }
    else {
      videoActions.find("#addToCart").hide();
      if (item.downloadURL) {
        videoActions.find("#download").attr("href", item.downloadURL).show();
      }
      else {
        videoActions.find("#download").hide();
      }
    }
  },

  setPlaylistValues: function (playlistTitle) {
    //set playlist title
    $("#playlistName span").html(playlistTitle.substr(0, 62) +
                (playlistTitle.length > 62 ? "..." : ""));
  },

  startLoading: function () {
    $("#playlistLoading").stop().show().fadeTo(200, .7);
    $("#playlistLoadingIndicator").stop().show().fadeTo(200, 1);
  },

  stopLoading: function () {
    $("#playlistLoading, #playlistLoadingIndicator").stop().fadeTo(200, 0).hide();

    //Set the VIP-only video icon for videos after the first 3.
//    $("img.thumbImg").each(function (index, element) {
//      if (!isVipMember && index >= freePreviewVidLimit)
//        //console.log(freePreviewVidLimit);
//      $(this).attr("src", "http://" + location.host + "/Content/Images/Vip/Public/RGVipAccessOnly.png");
//    });
  },

  setActiveChannel: function (interested_in, optionText) {
    revCove.updateActiveChannel(interested_in);
    revCove.loadVideosBySearch({ data: { all: 'tag:interested_in|' + interested_in} });
    revCove.scrollToTop();
    membersHome.setPlaylistValues(optionText);
    membersHome.showPlaylistTab();
    membersHome.activeChannel = interested_in;
  },

  setActivePlaylist: function (bcPlaylistId) {
    // TODO: MAKE NEW SERVICE CALL
    membersHome.activeChannel = null;
    revCove.loadVideosByPlaylistId(927094221001);
    revCove.scrollToTop();
    //membersHome.setPlaylistValues(optionText);
    membersHome.showPlaylistTab();
  },

  showPlaylistTab: function (checkRefresh) {
    // Activate the Playlists tab and hide the Channels tab
    $("#playlistTopTab2").hide();
    $("#channelWrapper").hide();
    $("#channelName").hide();
    $("#playlistTopTab1").show();
    $("#playlistName").show();
    $("#playlistWrapper").show();

    if (checkRefresh && membersHome.activeChannel) {
      // Refresh the default playlist here
      // Reset the active channel to avoid unnecessary refresh calls for default playlist
      membersHome.activeChannel = null;
      // revCove.defaultPlaylistId is the value retrieved by the Web.config setting
      membersHome.setActivePlaylist(revCove.defaultPlaylistId);
    }
  },

  showChannelTab: function () {
    // Activate the Channels tab and hide the Playlist tab
    $("#playlistTopTab1").hide();
    $("#playlistTopTab2").show();
    $("#playlistName").hide();
    $("#playlistWrapper").hide();
    $("#channelWrapper").show();
    $("#channelName").show();
  }
};

// after page load init
$(document).ready(function () {
  revCove.basePageObject = membersHome;
  membersHome.startLoading();
  membersHome.initEvents();
  membersHome.initFunc();

  revCove.currentItemsComplete = true;
  revCove.setPlaylist(revCove.currentItems);
  membersHome.setValues(revCove.currentVideo);
  $("#currentVideoId").text(revCove.currentVideo.id);
  membersHome.showPlaylistTab();
});
