var exaplayer = {
  player : null,
  track : null,
  highlighted : null,
  namedEntities : null,
  OCREntities : null,
  tagcloudLinks : null,
  spottedNamedEntities : $([]),
  duration : 0,
  currentTime : 0,
  noScroll : false,
  firstStart : true,
  keywordsTimeTag : [],
  timeLineUpdateNotifier  : null,

  seekTo : function seekTo(time) {
    if (time <= this.player.getClip().duration) {
      this.player.seek(time); this.currentTime = time;
      track.children(".over").trigger('timeUpdate');
    }
  },

  highlightSubtitle : function(second) {
    if (this.highlighted !== null) {
      this.highlighted.removeClass("highlight");
    }

    var selectors = $("#fulltext p span.sec"+second);
    if (selectors.size() >= 1) {
      this.highlighted = selectors.addClass("highlight");
      if (!exaplayer.noScroll){
        var parent = this.highlighted.parent().parent().stop();
        var fullOffset = (this.highlighted.offset().top + parent.scrollTop()) - parent.offset().top;
        parent.animate({scrollTop: fullOffset-100}, 350);
      }
    }
  },

  addKeywordsToTimeLine : function() {
    $('#fulltext .segment strong').each(function() {
      var elm = $(this).closest(".segment");
      var time = exaplayer.getSecondBySection(elm);

      var prevElms = elm.prevAll(":not(:empty):lt(4)");
      var nextElms = elm.nextAll(":not(:empty):lt(4)");
      var text = "";
      var isStart = false;
      var isEnd = false;

      if (prevElms.size() <= 2) {
        isStart = true;
        nextElms = nextElms.filter(":lt(" + (4 - prevElms.size()) + ")");
      } else if(nextElms <= 2) {
        isEnd = true;
        prevElms = prevElms.filter(":lt(" + (4 - nextElms.size()) + ")");
      } else {
        prevElms = prevElms.filter(":lt(2)");
        nextElms = nextElms.filter(":lt(2)");
      }

      prevElms.each(function(){
        text = $(this).html() + " " + text;
      });
      text += elm.html();
      nextElms.each(function(){
        text += " " + $(this).html();
      });

      if(isStart) {
        text = text.charAt(0).toUpperCase() + text.substr(1);
      } else {
        text = "&hellip;" + text;
      }
      if (!isEnd) {
        text += "&hellip;";
      }

      exaplayer.addBullet(time, text);
      exaplayer.keywordsTimeTag[exaplayer.keywordsTimeTag.length] = time;
    });
  },

  addNamedEntitiesToTimeLine : function() {
      exaplayer.spottedNamedEntities.each(function() {
        var elm = $(this);
        var segment = elm.parents(".segment");
        var time = exaplayer.getSecondBySection(segment);
        var text = elm.text();
        var className = "namedEnt";
        if (elm.hasClass("people")) {
          className += " people";
        } else if (elm.hasClass("location")) {
          className += " location";
        } else if (elm.hasClass("organization")) {
          className += " organization";
        }
        exaplayer.addBullet(time, text, className);
      });
  },

  removeTimeLineNamedEntities : function() {
    exaplayer.track.find(".namedEnt").remove();
  },

  removeTimeLineOCREntities : function() {
    exaplayer.track.find(".ocrbullet").remove();
  },

  getSecondBySection : function (section) {
    return parseInt(section.attr("className").replace(/([^0-9])/gi,""));
  },

  addBullet : function (time, text, className) {
    var bullet = $(document.createElement("div")).addClass("bullet");
    if (className && className !== "") {
      bullet.addClass(className);
    }
    var tooltip = $(document.createElement("span")).html(text).addClass("bulle");

    this.track.append(bullet);
    bullet.css("left", Math.round((time /this.duration * this.track.width()) - bullet.width() / 2) + "px");
    bullet.append(tooltip);

    bullet.click(function(event){
      exaplayer.seekTo(time);
      exaplayer.highlightSubtitle(time);
    });
  },

  seekToNextKeyword : function() {
    var keywordsCount = exaplayer.keywordsTimeTag.length;
    var i = 0;
    while (i < keywordsCount && exaplayer.keywordsTimeTag[i] < exaplayer.currentTime+1) {
      i++;
    }
    if (exaplayer.keywordsTimeTag[i] >= exaplayer.currentTime) {
      exaplayer.seekTo(exaplayer.keywordsTimeTag[i]);
    } else if (keywordsCount > 0) {
      exaplayer.seekTo(0);
    }
  }
};

$(function() {
  var timer = null;
  exaplayer.player = $f("exaplayer", {
    src:"media/flash/flowplayer-3.1.5.swf",
    wmode:"opaque"
  }, {
    clip: {
        autoPlay: true, accelerated: true, autoBuffering: true, scaling: 'fit', provider:
        'voxalead_stream'
    }, play: {
        label: 'Play', replayLabel: 'Replay'
    }, plugins: {
        controls: null, voxalead_stream: { url:
        'media/flash/flowplayer.rtmp-3.1.3.swf',
        netConnectionUrl: 'rtmpt://fms.3777.edgecastcdn.net/003777/sandeivideo' }
    }
  });

  var player = exaplayer.player;

  $(document).keypress(function(event) {
    if (exaplayer.player.isLoaded()) {
      if (event.which == 32) {
        exaplayer.player.toggle(); event.preventDefault();
      } else if (event.keyCode == 39) {
        exaplayer.seekToNextKeyword();
      }
    }
  });

  $("#q").keypress(function(event){
    event.stopPropagation();
  });

  $(".videoBox .radioLogo").click(function(event){
    if (exaplayer.player.isLoaded()) {
      exaplayer.player.toggle();
    }
  });

  var formatTime = function(time) {
     var sec = time % 60;
     var min = Math.floor((time % 3600) / 60);
     var hour = Math.floor(time / 3600); var date = "";
     if(hour>0) {
         date = hour+":";
     } if(min<10) {
         date += "0";
     } date+=min+":"; if(sec<10) {
         date += "0";
     }
     return date + sec;
  };

  var progress = $(document.createElement("div")).addClass("progress");
  exaplayer.track = $(document.createElement("div")).addClass("track");
  track = exaplayer.track;
  var timeDisplay = $(document.createElement("div")).addClass("time").text("00:00");
  var totalTimeDisplay = $(document.createElement("div")).addClass("totaltime").text("00:00");
  var over = $(document.createElement("div")).addClass("over");
  var fullBar = $(document.createElement("div")).addClass("fullBar");

  var playerControls = $(document.createElement("div")).addClass("playerControls");

  var playPauseButton = $(document.createElement("div")).click(function(){
    if (exaplayer.player.isLoaded()) {
      exaplayer.player.toggle();
    } else {
      exaplayer.player.play();
    }
  }).attr("class","play").attr("title","Play/Pause").attr("alt","Play/Pause");

  var nextKeywordButton = $(document.createElement("div")).addClass("nextKeyword").attr("title","Seek to next keyword");
  nextKeywordButton.click(function() {
    exaplayer.seekToNextKeyword();
  });

  playerControls.append(playPauseButton);
  playerControls.append(nextKeywordButton);
  playerControls.append(timeDisplay);

  track.append(progress); track.append(over);

  fullBar.append(playerControls);
  fullBar.append(track);
  fullBar.append(totalTimeDisplay);

  var onMouseMove = function(event) {
    progress.width(event.pageX - track.offset().left);
    event.stopPropagation();
  }

  var onTimeUpdate = function() {
    timeDisplay.text(formatTime(exaplayer.currentTime));
    progress.width(Math.round(exaplayer.currentTime/exaplayer.duration*track.width()));
  }

  var runTimer = function() { over.bind("timeUpdate",onTimeUpdate);
    timer = setInterval(function() {
    var newTime = Math.round(player.getTime());
      if (newTime !== exaplayer.currentTime) {
        exaplayer.currentTime = newTime;
        exaplayer.highlightSubtitle(exaplayer.currentTime-1);
      } over.trigger('timeUpdate');
    }, 250);
  };

  over.mousedown(function(event){
    over.bind("mousemove",onMouseMove);
    over.unbind("timeUpdate",onTimeUpdate);
    return false;
  });

  over.mouseup(function(event){
    var position = event.pageX - track.offset().left;
    over.bind("timeUpdate",onTimeUpdate);
    over.unbind("mousemove",onMouseMove);
    exaplayer.currentTime = Math.round(position/over.width()*exaplayer.duration);
    player.seek(exaplayer.currentTime);
    over.trigger("timeUpdate");
    exaplayer.highlightSubtitle(exaplayer.currentTime);
  });

  player.onStop(function() {
    clearInterval(timer);
    playPauseButton.attr("class","pause");
  });

  player.onFinish(function() {
    clearInterval(timer);
    exaplayer.currentTime = 0;
    player.seek(0);
    playPauseButton.attr("class","pause");
  });

  player.onPause(function() {
    clearInterval(timer);
    playPauseButton.attr("class","pause");
  });

  player.onSeek(function() {
    over.trigger('timeUpdate');
  });

  player.onResume(function() {
    runTimer();
    playPauseButton.attr("class","play");
  });

  player.onStart(function() {
    if (exaplayer.duration == 0) {
      exaplayer.duration = player.getClip().fullDuration || 0;
      totalTimeDisplay.text(formatTime(Math.round(exaplayer.duration)));
    }
    runTimer();

    if (exaplayer.firstStart) {
      exaplayer.addKeywordsToTimeLine();
      var startTime = 0;

      if ($("#startTime").val() !== "") {
        startTime = parseInt($("#startTime").val());
      } else {
        var firstSection = $('#fulltext strong:first').parent();
        if (firstSection.size() > 0) {
          startTime = exaplayer.getSecondBySection(firstSection);
        }
      }
      // hack because of pseudo streaming plug-in bug
      setTimeout(function() {
        exaplayer.seekTo(startTime);
      }, 250);
      exaplayer.player.setVolume(100);
      exaplayer.firstStart = false;
    }
  });

  var previousSec = function(elm) {
    if (elm.prev().size()>=1) {
      return elm.prev();
    } else {
    return elm.parent().prev().children(":last-child");
    }
  }

  $("#exaplayer").after(fullBar);

  var fullText = $("#fulltext");

  var resizeFulltext = function() {
  //adapt full text height
    var height = $(window).height() - fullText.offset().top - $('#Footer').outerHeight(true) - 2;
    if (height < 200) {
        height = 200;
    } else {
	height = 300;
    }
    fullText.height(height);
  }

  $(window).resize(resizeFulltext);
  resizeFulltext();

  fullText.mouseenter(function(event){
    exaplayer.noScroll = true;
  });

  fullText.mouseleave(function(event){
    exaplayer.noScroll = false;
  });

  $('#fulltext .segment').each(function() {
    $(this).click(function(event) {
      var section = $(event.target);
      //named entity click bugfix
      while (!section.hasClass("segment")) {
        section = section.parent();
      }
      var time = exaplayer.getSecondBySection(section);
      exaplayer.seekTo(time); exaplayer.highlightSubtitle(time);
      event.stopPropagation();
    });
  });

  fullText.click(function() {
    exaplayer.player.toggle();
  });

  $('#return').click(function() {
    exaplayer.player.stop();
  });

  spotThisNamedEntity = function(event) {
    event.preventDefault();
    event.stopPropagation();

    exaplayer.spottedNamedEntities.removeClass("spotted");
    exaplayer.tagcloudLinks.removeClass("selected");

    var currentClickedObject = $(event.target);
    var wordToSpot = currentClickedObject.text();

    exaplayer.spottedNamedEntities = exaplayer.namedEntities.filter(":contains("+wordToSpot+")").addClass("spotted");

    exaplayer.tagcloudLinks.filter(":contains("+wordToSpot+")").each(function(){
      if ($(this).text().length === wordToSpot.length) {
        $(this).addClass("selected");
      }
    })

    exaplayer.removeTimeLineNamedEntities();
    exaplayer.addNamedEntitiesToTimeLine();

    var firstChild = exaplayer.track.children(".namedEnt:first");
    if (firstChild.size() > 0) {
      var body = $("body");
      var effect = currentClickedObject.clone();
      body.append(effect.css({
        position : 'absolute',
        top : currentClickedObject.offset().top - parseInt(body.css("margin-top")),
        left : currentClickedObject.offset().left
      }).addClass("selectedTag").addClass( currentClickedObject.attr("className") ));
      var firstChildPosition = firstChild.offset();
      effect.animate({
         top: firstChildPosition.top - parseInt(body.css("margin-top")),
         left: firstChildPosition.left
      }, 750, function() {
        $(this).fadeOut(200, function() {
          $(this).remove();
        });
      });
      firstChild.click();
    }
  }
  exaplayer.namedEntities = $('#fulltext .location, #fulltext .people, #fulltext .organization');
  exaplayer.tagcloudLinks = $(".tagCloud a");
  exaplayer.tagcloudLinks.click(spotThisNamedEntity);
  exaplayer.namedEntities.click(spotThisNamedEntity);
});

