var intPollInterval = 5000;
var intCurrentPollInterval = intPollInterval;
var intAnimateSpeed = intCurrentPollInterval;
var blnShowGoals = true;
var blnPlaybackPaused = false;
var intCurrentInterval = 0;
var intCurrentTimer = false;

$(document).ready(function() {

	var fncUpdateDragger = function() {
		var intPercent = Math.round((intCurrentInterval / intTotalIntervals)*100);
		//var intDraggerWidth = parseInt($('#dragregion').width(), 10) - parseInt($('#dragger').width(), 10);
		//var intLeftPixels = Math.round(intPercent*intDraggerWidth);
		$('#dragger').css('left', (intPercent-1)+'%');
		$('#green').width($('#dragger').css('left'));
    $("#green-field").animate({width: intPercent+'%'}, {
      duration: intAnimateSpeed,
      queue: false,
      easing: 'linear'
    });
	}

	if(!blnMatchInProgress) {
		$('#pausebutton').css('opacity','0.2');
		$('#playbutton').css('opacity','0.2');
		$('#pausebutton').fadeIn('slow');
		$('#playbutton').fadeIn('slow');

		// hovering interactivity:
		var fncPlayHover = function(){
			$(this).css('opacity','0');
		}
		var fncPlayUnHover = function(){
			$(this).css('opacity','0.2');
		}
		// attach events:
		$('#pausebutton').hover(fncPlayHover);
		$('#playbutton').hover(fncPlayHover);
		$('#pausebutton').mouseout(fncPlayUnHover);
		$('#playbutton').mouseout(fncPlayUnHover);

		// the hover events:
		$('#pausebutton').click(function(){
			if(!blnPlaybackPaused) {
				clearTimeout(intCurrentTimer);
				blnPlaybackPaused = true;
				$('#playbutton').removeClass('active');
				$('#pausebutton').addClass('active');
				fncUpdateDragger();
			}
		});
		$('#playbutton').click(function(){
			if(blnPlaybackPaused) {
				blnPlaybackPaused = false;
				fncPlaybackPoll();
				$('#pausebutton').removeClass('active');
				$('#playbutton').addClass('active');
				//fncUpdateDragger();
			}
		});
		$('#dragregion').click(function(ev) {
        $('#pausebutton').click();
				var intPosition = ev.clientX - parseInt($('#dragregion').css('left'), 10);
				intCurrentInterval = Math.round((intPosition/100)*intTotalIntervals);
        blnShowGoals = false;
				fncUpdateDragger();
        $('#playbutton').click();
		});

		$('#dragger').draggable({
      axis: 'x',
      containment: 'parent',
      drag: function(ev,obj) {
        $('#pausebutton').click();
        $('#green').width(obj.position.left);
        blnShowGoals = false;

        intPercent = obj.position.left/100;
        var intTargetInterval = Math.round((intPercent)*intTotalIntervals);

        // Restart the Playback at the new interval
        intCurrentInterval = intTargetInterval;
        intAnimateSpeed = 0;
        $('#playbutton').click();
      },
      stop:function(ev, obj) {
        intPercent = obj.position.left/100;
        var intTargetInterval = Math.round((intPercent)*intTotalIntervals);

        // Restart the Playback at the new interval
        intCurrentInterval = intTargetInterval;
        $('#playbutton').click();
        intAnimateSpeed = intCurrentPollInterval;
      }
    });
	}

  // Polls the server for match updates.
  var fncAjaxPoll = function() {
    $.ajax({
      url: '/ajaxPoll/'+intMatchId,
      dataType: 'json',
      success: function(objResponse) {
        objCurrentInterval = objResponse;
        fncUpdateDisplay.call(this);

        $.each(objResponse['Signals'], function(i, objSignal) {
          if(objSignal['Signal']['type'] == 'refresh') {
            location.reload();
          }
        });

        if(blnMatchInProgress === true) {
          intCurrentTimer = setTimeout(fncAjaxPoll, intPollInterval);
        }
      }
    });
  };

  // Polls the server for match updates.
  var fncPlaybackPoll = function() {
    clearTimeout(intCurrentTimer);
    objCurrentInterval = objIntervals[intCurrentInterval];
    fncUpdateDisplay.call(this);
    fncUpdateDragger.call(this);
    if(blnMatchInProgress === false && blnPlaybackPaused === false && intCurrentInterval < intTotalIntervals) {
      intCurrentInterval = Math.round(objCurrentInterval['Match']['intMatchProgress'])+2;
      intCurrentTimer = setTimeout(fncPlaybackPoll, intCurrentPollInterval);
    } else {
      $("#pausebutton").click();
    }
  };

  /**
   * Function: UpdateDisplay
   *
   * Updates the page to display match details, using the global objCurrentInterval.
   * This basically means setting the goal and bar heights.
  **/
  var fncUpdateDisplay = function() {
    fncUpdateScores.call(this, objCurrentInterval['Match']['intTeamAScore'], objCurrentInterval['Match']['intTeamBScore']);

    fncUpdateTeamLogos.call(this, objCurrentInterval['TeamA']['intLogoSize'], objCurrentInterval['TeamA']['intLogoTopLeft'], objCurrentInterval['TeamB']['intLogoSize'], objCurrentInterval['TeamB']['intLogoTopLeft']);

    $.each(objCurrentInterval['TeamA']['Players'], function(k, objPlayer) {
      fncUpdatePlayer.call(this, objPlayer.intPlayerId, objPlayer['intBlockHeight'], objPlayer['intSpacerHeight']);
    });

    $.each(objCurrentInterval['TeamB']['Players'], function(k, objPlayer) {
      fncUpdatePlayer.call(this, objPlayer.intPlayerId, objPlayer['intBlockHeight'], objPlayer['intSpacerHeight']);
    });
  };

  /**
   * Function: UpdatePlayer
   *
   * Tweens the height of a single bar graph element. Assumes the HTML structure
   * set out in the index.html file.
   *
   * @param id The player and, and in turn #id of the element.
   * @param height_percentage The target percentage height.
  **/
  var fncUpdatePlayer = function(intPlayerId, intBlockHeight, intSpacerHeight) {
    $('#'+intPlayerId+' .block').animate({height: intBlockHeight}, {
      duration: intAnimateSpeed,
      queue: false
    });
    $('#'+intPlayerId+' .spacer').animate({height: intSpacerHeight}, {
      duration: intAnimateSpeed,
      queue: false
    });
  };

  /**
   * Function: update_buzz
   * Updates the logo sizes of each team, changing size according to popularity.
   *
   * @param team1buzz
   * @param team2buzz
  **/
  var fncUpdateTeamLogos = function(intTeamALogoSize, intTeamALogoTopLeft, intTeamBLogoSize, intTeamBLogoTopLeft) {
    // let's normalise them so that the bigger one is the full 64px
    $('#logo1 img').animate({
      left: intTeamALogoTopLeft+'px',
      top: intTeamALogoTopLeft+'px',
      width: intTeamALogoSize+'px',
      height: intTeamALogoSize+'px'
    }, {
      duration:'slow',
      queue: false
    });

    $('#logo2 img').animate({
      left: intTeamBLogoTopLeft+'px',
      top: intTeamBLogoTopLeft+'px',
      width: intTeamBLogoSize+'px',
      height: intTeamBLogoSize+'px'
    }, {
      duration:'slow',
      queue: false
    });
  };

  /**
   * Function: update_scores
   *
   * @param team1score First team's score
   * @param team2score Second team's score
  **/
  var fncUpdateScores = function(intTeamAScore, intTeamBScore) {
    var strTeamAPreviousScore = $('#team2score').text();
    var strTeamBPreviousScore = $('#team1score').text();

    if((strTeamAPreviousScore < intTeamAScore || strTeamBPreviousScore < intTeamBScore) && blnShowGoals) {
      fncAnnounceGoal.call(this);
    }

    $('#team2score').text(intTeamAScore);
    $('#team1score').text(intTeamBScore);
  };

  /**
   * Function: announce_goal
   *
   * Announces a goal. yeh.
  **/
  var fncAnnounceGoal = function() {
    $('#goaltext').fadeIn('slow', function() {
      setTimeout(fncHideGoalAnnouncement, 2000);
    });
  };

  /**
   * Function: hide_goal_announcement
   *
   * Just fades the goal message off.
  **/
  var fncHideGoalAnnouncement = function() {
    $('#goaltext').fadeOut('slow');
  }

	$('#team1text').css('opacity',0.9);
	$('#team1text').fadeIn('slow');
	$('#team2text').css('opacity',0.9);
	$('#team2text').fadeIn('slow');

	$('#team1 li.player').mouseover(function(e) {
		$('.hoverbox').fadeOut('slow');
		var player = $(this).attr('id');
		var offset = $('#'+player).offset();

		if(offset.left < 198)
			$('#'+player+'hover').removeClass('hoverright').addClass('hoverleft');
		else
			$('#'+player+'hover').removeClass('hoverleft').addClass('hoverright');

		var pt = 70;

		bubbleoffset = $('#'+player+'hover').height() - $('#'+player+'hover .bubble').height();

		$('#'+player+'hover').hide().css({paddingTop:pt,left:offset.left,top:offset.top}).fadeIn('slow');
	 });

	 $('.hoverbox img').mouseout(function() {
		$('.hoverbox').fadeOut('slow');
	 });

	$('#team2 li.player').mouseover(function(e) {
		$('.hoverbox').fadeOut('slow');
		var player = $(this).attr('id');
		var offset = $('#'+player).offset();

		if(offset.left < 198)
			$('#'+player+'hover').removeClass('hoverright').addClass('hoverleft');
		else
			$('#'+player+'hover').removeClass('hoverleft').addClass('hoverright');

		var  pt = 0;

		bubbleoffset = $('#'+player+'hover').height() - $('#'+player+'hover .bubble').height();

		$('#'+player+'hover').hide().css({paddingTop:pt,left:offset.left,top:offset.top}).fadeIn('slow');
	 });

	 $('.hoverbox img').mouseout(function() {
		$('.hoverbox').fadeOut('slow');
	 });
  fncUpdateDisplay.call(this);

  if(blnMatchInProgress) {
  	fncAjaxPoll.call(this);
		$('#playbutton').click();
  } else {
    intCurrentPollInterval = 2000;
    intAnimateSpeed = intCurrentPollInterval;
		$('#pausebutton').click();
    //fncPlaybackPoll.call(this);
  }
 });