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

// Code to run on page load
$().ready(function() {
	// Wire up the search boxes with auto-complete
	$('.searchq').autocomplete('/search_suggest', {
	  matchContains: true,
		minChars: 3,
		width: 362,
		max: 8,
		scrollHeight: 480,
    formatItem: function(row, i, total) {
      return '<img class="searchthumb" src="' + row[2] + '"/>' + row[0]
    },
	  formatResult: function(row) {
			return row[0];
		}
	});

	// Redirect the page to the link for the auto-completed results
	$('.searchq').result(function(event, data, formatted) {
		if (data)
			document.location.href = data[1];
	});
	
	// Add form validation
	$('.edit, .new, .edit_guitar, .edit_artist, .edit_song, .edit_page').validate();
});

function showForm() {
  $('#add_form').show();
  $('#add_button').hide();
  return false;
}

function hideForm() {
  $('#add_button').show();
  $('#add_form').hide();
  return false;
}

function restripe(table) {
  jQuery("tr:even", table).each(function() {$(this).removeClass('alt')})
  jQuery("tr:odd", table).each(function() {$(this).addClass('alt')})
}

function updateMultipleCheckboxes(value){
  $('.multiple-select input').each(function(){
      this.checked = value; 
      $('.multiselect').toggle();
  });
}

function countChars() {
  var inputs = $('*[maxChars]');

  // Create the count div & populate it
  $.each(inputs, function(i, input){
      $(input).after('<div class="character-count" id="' + countId(input) + '"></div>');
      updateCount(input);
  });

  // When a keyup event happens, update the count
  inputs.keyup(function(){
      updateCount(this);
  });

  function countId(input){
      return input.id + '_count';
  }

  function updateCount(input){
    var i = $(input);
    var l = i.val().length;
    var c = i.attr('maxChars'); 

    if(l  >= c){
      i.val(i.val().substr(0, c))
      l = c;
    }

    numClass = (l < i.attr('minChars') || l >= c) ? 'class="out-of-range"' : '';

    $('#' + countId(input)).html("<span " + numClass + ">" + l + "</span> of " + c + " characters");
  }

}

// Calls a function (fn), when the user types 
// something in an input and then stops typing.
//
// usage: $("#user_login").typing_stopped(checkLoginAvailablility);

(function($){
 $.fn.typing_stopped = function(callback) {
    this.each(function() { 

      var counter = 0;
      var input = $(this);

      input.keyup(function(e){

        // Don't count arrow keys, home, end
        var c = e.which;
        if(c >= 33 && c <= 40) return

        var key = this;

        counter += 1;
        setTimeout(function(){
          counter -= 1;
          if(counter == 0 && input.val()) callback.call(key, e);
        }, 1500);

      });

    });
    return this
 };
})(jQuery);
