// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var countdown;
var ct = 30;

$(document).ready(function() {	
  // $(document).supersleight(); 
  
	$('#flash-container').slideDown('slow', function() {
	  setTimeout(function() {
	    $('#flash-container').slideUp('slow');
	  },5000)
	});
	
	$('#start-btn').click(function(e) {
	  e.preventDefault();
	  startGame();
	});

	
	$('#term-form').submit(function(e) {
	  e.preventDefault();
	  if(!$(this).hasClass('invalid')) {
	    startGame();
	  }
	  
	});
	
	$('#input').focus();
	
	$('#input').keyup(function(e) {
	  $('#term-form').removeClass('invalid');
	  $('#length-alert').hide();
	  var terms = $(this).val().split(' ');
    $('#terms').empty();
    $.each(terms, function(i, term) {
      if(term.length > 2) {
        $(document.createElement('li')).addClass('term-'+(i+1)).html(term).appendTo($('#terms'));
      }
      
    });
	  if(terms[0].length < 1) {
	    $('#term-form').addClass('invalid');
	    return;
	  }

	  if($(this).val().match(/\b\w{1,2}\s/)) {
	    $('#term-form').addClass('invalid');
	    $('#length-alert').show();
	  };

	  $(this).val(terms.slice(0,5).join(' '));
	});
	

	$('.status-update-lnk').click(function(e) {
		e.preventDefault();
		var offset = $(this).offset();
    showDialogue(offset.left,offset.top);
	});
	
	$('.close-lnk').click(function(e) {
	  e.preventDefault();
	  $(this).parents('div').fadeOut('fast');
	});
	
	$('#tweet-form').keyup(function(e) {
    var clength = $('#tweet-input').val().length;
    $(this).find('.limit').html(140-clength);
    if(clength > 140) {
      $('#tweet-form').addClass('invalid');
    } else {
      $('#tweet-form').removeClass('invalid');
    }
  });
  
  
  $('#tweet-form').submit(function(e) {
    e.preventDefault();
    if($(this).hasClass('invalid')) {return false}
    $(this).ajaxSubmit(function(resp) {
      $('#tweet-prompt').hide();
    });
  });
  
  $.each($('.box'), function(i,box) {
    $(box).css({top:-$(box).height()}).show().animate({
      top:0
    }, 1000 - (i * 300), 'easeOutBounce')
  })
  
  $('#tutorial a').hover(function(e) {
    highlight($(this).attr('target'));
  }, function() {
    delight($(this).attr('target'));   
  });

  $('a.toggle-lnk').click(function(e) {
    e.preventDefault();
    var drawer = $('#nav').find('.drawer')
    if(!drawer.hasClass('expanded')) {
      drawer.slideDown('fast').addClass('expanded');
    } else {
      drawer.slideUp('fast').removeClass('expanded');
    }
    
  }); 
  
  $('#donations dd').click(function(e) {
    e.preventDefault(e)
    window.location = $(this).find('a').attr('href');
  });
  
  // startTutorial();
});

function hideFlashMessages() {
  $('p.flash_container').each(function(e) { 
    if (e) Effect.Fade(e, { duration: 2.0 });
  });
}


function startGame() {
  // ct = Number($('#rounds').html());
  ct --;
  $('#rounds').text(':'+ct);
  $('#message .content').fadeOut('slow');
    $.ajax({
      url:'/start-game',
      data:{'terms':$('#input').val()},
      success:function(resp) {
        parseTweets(resp);
      },
      error:function(XMLHttpRequest, textStatus, errorThrown) {
        $('#loader').hide();
        $('#fail').show();
        $.ajax({url:'/fail'})
      },
      timeout:30000
    })
  
  $('#summary').hide();
  $('#loader').show('fast');
  $('#results').show();
}

/* Added this back in for the time being */
function showDialogue(x, y) {
  var height = $("#tweet-prompt").height();
  $("#tweet-prompt").css({ 'top' : (y - height-200) + "px", 'left' : x-400 + "px"  } ).fadeIn('fast').draggable();
  $('#tweet-input').focus();
}

function updateTweets(url) {

  ct --;
  if(ct < 10) {
    $('#rounds').text(':0'+ct);
  } else {
    $('#rounds').text(':'+ct);
  }

  if(ct <= 0) {
    $('#loader').hide();
    $('#reset-btn').show();
    $('#input').hide();
    $('#start-btn').hide();
    
    $.ajax({
      url:'/summary', 
      success:function(json) { displayAjaxSummary(json) }
    });
  } else {
    callForTweets(url);
  }
}


function callForTweets(url) {
  $.ajax({
    url:url, 
    success:function(resp) {
      parseTweets(resp);
    },
    error:function(XMLHttpRequest, textStatus, errorThrown) {
      $('#loader').hide();
      $('#fail').show();
      $.ajax({url:'/fail'})
    },
    timeout:30000
  });
}

function parseTweets(resp) {
  $('#matches').html($(resp).find('.matches').html());
  $.each($(resp).find('.results dl'), function(i, tweet) {
    $(tweet).insertBefore($('#results dl:first')).slideDown('fast');
    // $('#results dl:first')
  });
  
  $('#terms').html($(resp).find('.terms').html())
  setTimeout(function() {updateTweets('/next-round')},200);
}

function displayAjaxSummary(resp) {

  $(resp).find('#summary').insertBefore($('#terms'));
  $('#summary .title').hide().fadeIn('fast');
  
  
  $('#summary').data('event_id', 0);
  scrollEvents();
  // $.scrollTo('#summary',500, {offset:{left:0,top:-30}});
}

function scrollEvents() {
  
  var event_id =  $('#summary').data('event_id');
  
  var ev = $('#summary').find('.event')[event_id];

  if($(ev).length == 1) {
    $('#summary .events').scrollTo($(ev), 1000);
    
    if((event_id + 1) >= $('#summary .event').length) {
      $('#summary').data('event_id',0);
    } else {
      $('#summary').data('event_id',event_id + 1);
    }
      
      setTimeout(scrollEvents, 3000);
    
  }

}


function startTutorial() {
  $('#tutorial').show()
}


function highlight(item) {
  var speed = 100;
  $(item).fadeOut(speed).css({color:'#6f0'}).fadeIn(speed).fadeOut(speed).fadeIn(speed)
}

function delight(item) {
  $(item).stop().fadeIn().css({color:'#FFF', opacity:1})
}

