// add authenticity token to ajax requests
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

// add browser name to body class
$(document).ready(function() {
  var b = $.browser;
  var c;
  if(b.safari)  c = 'safari';
  if(b.mozilla) c = 'mozilla';
  if(b.msie)    c = 'msie';
  if(b.opera)   c = 'opera';
  $('body').addClass(c);
  
  // add profile masks
  $('.profile_image img').each(function() {
    $(this).after("<span class=\"mask\"></span>");
  });
  
  // move possible inline overlay blocks outside content wrapper
  // -- needs to be done for absolute positioning
  $('.overlay').each(function() {
    $('body').append($(this).remove());
  });
  
  // initialise all help links
  initHelp();
});

// initialise any inline help links
function initHelp() {
  $('a.help:not(.initialised)').each(function() {
    var a = $(this);
    if(a.attr('href')) {
      if ($(a.attr('rel')).length == 0) {
        $('body').append('<div id="' + a.attr('rel').substr(1) + '" class="overlay"><div class="wrap"></div></div>');
      };
    }
    a.addClass('initialised');
  })
  .overlay({
    onBeforeLoad : function() {
      var wrap = this.getContent().find("div.wrap");
      // load only for the first time it is opened 
      if (wrap.is(":empty")) { 
        wrap.load(this.getTrigger().attr("href"));
      }
    },
    onLoad : function() {
      // scan help links again in case popup 
      // help has new help links
      // TODO initHelp();
    }
  });
}


// serialize the form and submit via ajax
// TODO return true if script fails - this will fall back to 
// a standard form submission.
function submitRemoteForm(form) {
  $.ajax({
    type:     "POST",
    url:      form.action,
    data:     $(form).serialize(),
    dataType: "script"
  });
  return false;
}
// validate and submit home page form
function validateAndSubmitNewRoll(form) {
  // disable form button
  var button = $('form#new_roll button');
  button.disable();
  
  // remove any errors
  removeInlineErrors();
  
  // are all fields valid?
  var valid = true;
  
  // action name not blank
  var action_name_valid = $('#roll_action_name').val().length > 0;
  if (!action_name_valid) {
    addInlineError("action_name", "Hmm, what's the action?");
    valid = false;
  }
  
  // TODO DRY up all this error stuff
  // split participants
  var participants_raw = $('#roll_participants').val().split(',');
  var participants = new Array();
  for (var i=0; i < participants_raw.length; i++) {
    var name = participants_raw[i].strip();
    if(name.length > 0) participants.push(name);
  };
  var participants_empty = $('#roll_participants').hasClass('empty');
  if (participants.length < 2 || participants_empty) {
    addInlineError("participants","You'll need at least 2 people (comma separated)");
    valid = false;
  } else {
    var names_valid = true;
    for (var i=0; i < participants.length; i++) {
      if (!participants[i].strip().match(/^@?[a-z_0-9]+$/i)) {
        names_valid = false;
        break;
      };
    };
    if (!names_valid) {
      addInlineError("participants","Names may only have 15 letters, numbers or '_'");
      valid = false;
    };
  }
  
  if (valid) { 
    $('#roll_tweet_field').hide();
    $(form).append('<div id="loading"><img src="/images/loader.gif" alt="" /><p>Twurn is thinking...</p></div>');
    return submitRemoteForm(form);
  }
  
  // enable form button
  button.enable();
  return false;
}
// Add an inline error to the homepage fields
function addInlineError(field_name, message) {
  $('#roll_' + field_name + '_field').addClass('validation_error');
  // get the form errors div
  var form_errors = $('#new_roll_errors');
  if (form_errors.length == 0) {
    $('form#new_roll').append('<ul id="new_roll_errors"></ul>');
    form_errors = $('#new_roll_errors');
  };
  form_errors.append('<li>' + message + '</li>');
}
// Remove all inline errors from homepage
function removeInlineErrors() {
  $('div.validation_error').each(function() {
    $(this).removeClass('validation_error');
  });
  $('#new_roll_errors').remove();
}

// strip whitespace from around a string
String.prototype.strip = function() {
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
// enable button
$.fn.extend({
  disable: function() {
    return this.each(function() { $(this).attr('disabled','disabled').addClass('disabled') });
  },
  enable: function() {
    return this.each(function() { $(this).removeAttr('disabled').removeClass('disabled') });
  }
});

function getMoreTwurns(trigger) {
	var _trigger = $(trigger);
	_trigger.parent().addClass('loading');
	$.ajax({
		type:     "GET",
		url:      _trigger.attr('href'),
		data:     "offset="+moreTwurnsOffset,
		dataType: "script"
	});
	return false;
}

function fetchTwitterProfile(userId) {
  $.getScript('/users/' + userId + '/profile');
}
