
function setupStartQuizText(min_words) {
	if ($('#latest-words .term').size() < min_words) {
		$('#start-quiz').hide();
	}

	$(document).bind('word:created', createQuizStatusUpdater());
	$(document).bind('word:deleted', createQuizStatusUpdater(-1));
	$(document).ready(createQuizStatusUpdater())
	
	function createQuizStatusUpdater(delta) {
	  return function() {
	    updateQuizStatus(delta); 
	  }
	}
	function updateQuizStatus(delta) {
	  var delta = delta === undefined ? 0 : delta;
	  var word_count = $('#latest-words .term').size() + delta;
	  var words_left = min_words - word_count;
	  $('#quiz-countdown').remove();
		if (word_count >= min_words) {
			$('#start-quiz').fadeIn('slow');
		}
		else {
		  $('#start-quiz').hide('slow')
		  if (word_count != 0) {
  		  var sentence = 'Enter ' + words_left + ' more words to enable the quiz';
  		  if (words_left == 1) {
  		    sentence = 'Only one more word now!';
  		  }
  		  $('#btn-add-given').after('<span id="quiz-countdown" class="help"><br/>' + sentence + '</span>');
  	    $('#quiz-countdown').hide().fadeIn('slow');
	    }
		}
	}
}

function setupRowControls(row) {
    var $row = $(row);
    var $form = $row.find('.deletion-form');
    
    replaceButton();
    ajaxifyForm();
    
    function replaceButton() {
        $row.find('.actions')
            .addClass('mini')
            .find('button')
                .replaceWith('<span class="button delete">[x]</span>');
        $row.find('.button.delete').click(function(){
            $form.submit();
            $(document).trigger('word:deleted');
        });
    }
    
    function ajaxifyForm() {
        $form.submit(function(){
            var action_uri = $form.get(0).action;
            var args = {'word_id': $row.find('input[name=word_id]').val()};
            $.post(action_uri, args, function() {
                $row.fadeOut('slow', function() { $row.remove(); });
            })
            
            return false;
        });
    }
}

(function() {


$(document).ready(function () {
  setupDashboardIndex();
  setupQuizQuestion();
  setupDictionaryLinks();
});

function setupDashboardIndex() {
  var $form = $('#add-word');
  var $field = $form.find('[name=word]');
  if ($form.size() == 0) {
    return;
  }
  
  $form.submit(function (event) {
    event.preventDefault();
    disableForm();
    $('#flash-messages').slideUp('slow', function(){ $(this).remove(); });
    $.ajax({
        type: 'POST',
        url: '/add_word',
        data: {'word': $field.val() },
        complete: completedAddWord
    });
  });
  
  function completedAddWord(res) {
    enableForm();

    var word = $field.val();
    $field.val('');

    if (res.status != 200) {
        $('#main').before('<div id="flash-messages" class="container"><p class="error">Could not find the word <em>' + word + '</em>. Sure you spelt it correctly?</p></div>');
        return;
    }

    addDefinitionRow(res.responseText);
    $(document).trigger('word:created');
  }
  
  function disableForm() {
    $('#add-word input').attr('disabled', 'disabled');
    $form.addClass('loading');
  }

  function enableForm() {
    $('#add-word input').removeAttr('disabled');
    $form.removeClass('loading');
  }
  
  function addDefinitionRow(html) {
    var $table = $('#latest-words');
    var row_id = $(html).attr('id');
    $('#' + row_id).remove();
    $table.prepend(html);
    $table.find('tr:first').hide().fadeIn('slow')
  }
}

function setupQuizQuestion() {
  $('#quiz-question [name=answer]').focus();
  $('#quiz-question [type=submit]').after('<input type="button" id="giveup" value="I give up">');
  $('#giveup').click(function(){
    $('#answer').val($('#solution').val());
    $('#gave-up').val(1);
  });
}

function setupDictionaryLinks() {
  $('a').live('click', function(event){
    if (! this.href.match(/\/dict\/[^\/]+\/?$/)) {
      return true;
    }
    event.preventDefault();
    $(this).popup({
      url: this.href + '?layout=popup',
      width: 600,
      height: 600,
    });
  });
}


})();


// Inspired by http://jehiah.cz/archive/prototype-powered-popup-script
jQuery.fn.popup = function(options) {
	this.options = {
		url: this.get(0).href,
		width: 800,
		height: 600,
		name: "_blank",
		location: "no",
		menubar: "no",
		toolbar: "no",
		status: "yes",
		scrollbars: "yes",
		resizable: "yes",
		left: "",
		top: "",
		normal: false
	}
	this.options = jQuery.extend(this.options, options || {});
   
	if (this.options.normal){
		this.options.menubar = "yes";
		this.options.status = "yes";
		this.options.toolbar = "yes";
		this.options.location = "yes";
	}
   
	this.options.width  = this.options.width  < screen.availWidth  ? this.options.width  : screen.availWidth;
	this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;

	var openoptions = 'width=' + this.options.width + ',height=' + this.options.height + ',location=' + this.options.location + ',menubar=' + this.options.menubar + ',toolbar=' + this.options.toolbar + ',scrollbars=' + this.options.scrollbars + ',resizable=' + this.options.resizable + ',status=' + this.options.status;
	
	if (this.options.top != "") {
		openoptions += ",top=" + this.options.top;
	}
	if (this.options.left != "") {
		openoptions += ",left=" + this.options.left;
	}
	window.open(this.options.url, this.options.name,openoptions);
	
	return false;
}
