// Runs on document ready state.
$(document).ready(function(){
  $('#url-form').bind('submit', formSubmit);
  $('#actions span').bind('click', panelToggle);
});

// Check to make sure a URL isn't blank or malformed
function urlCheck(field) {
  field = $(field);
  var urlRegex = new RegExp(/(http|https)\:\/\/(([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})|([\w\-]+\.)+(((af|ax|al|dz|as|ad|ao|ai|aq|ag|am|aw|au|at|az|bs|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|bn|bg|bf|kh|cm|ca|cv|ky|cf|td|cl|cn|cx|cc|km|cg|cd|ck|cr|ci|hr|cu|cy|cz|dk|dj|dm|do|ec|eg|sv|gq|er|ee|et|fk|fo|fj|fi|fr|gf|pf|tf|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt|gg|gn|gw|gy|ht|hm|va|hn|hk|hu|is|id|ir|iq|ie|im|il|it|jm|jp|je|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|nr|np|nl|an|nc|nz|ni|ng|nu|nf|mp|no|om|pk|pw|ps|pa|pg|py|pe|ph|pn|pl|pt|qa|re|ro|ru|rw|sh|kn|lc|pm|vc|ws|sm|st|sa|sn|cs|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|tl|tg|tk|to|tt|tn|tr|tm|tc|tv|ug|ua|gb|us|um|uy|uz|vu|ve|vn|vg|vi|wf|eh|ye|zm|zw|uk|com|edu|gov|int|mil|net|org|biz|info|name|pro|aero|coop|museum|arpa|co|in|ne|bi|na|pr|ae|mu|ar))))(:[\d]{1,4})?($|(\/([a-zA-Z0-9\.\?=\/#%&\+-])*)*|\/)/);
  return urlRegex.test(field.val());
}

// AJAX goodness for the URL
function formSubmit(event) {
  var userURL;
  var form = $('#url-form');
  var out = $('<li id="out"></li>')
  var message = $('#message');
  if (urlCheck('#url') == false) {
    event.preventDefault();
    message.text('The URL you entered is blank or hosed. Try again.');
    if ($('#out').is(':visible')) $('#out').remove();
    if (!message.hasClass('visible')) message.addClass('visible');
    form.animate({ backgroundColor: 'transparent' }, 125).animate({ backgroundColor: '#FDD' }, 250);
  } else if ($('#recaptcha_response_field').val() == '') {
    event.preventDefault();
    message.text('You need to fill in the text you see or hear for the reCaptcha form.');
    if ($('#out').is(':visible')) $('#out').remove();
    if (!message.hasClass('visible')) message.addClass('visible');
    form.animate({ backgroundColor: 'transparent' }, 125).animate({ backgroundColor: '#FDD' }, 250);
  }
}

// Toggle the panels showing the login and bookmarklet
function panelToggle(event) {
  event.preventDefault();
  if ($(this).next('.panel').is(':visible')) {
    $('#actions span').closest('li').removeClass('expanded');
    $(this).next('.panel').hide();
  } else {
    $('#actions span').closest('li').removeClass('expanded');
    $(this).closest('li').addClass('expanded');
    $('#actions .panel').hide();
    $(this).next('.panel').show();
  }
}
