var AjaxHelper = {
  // Use it to see if any of the remote calls is in progress...
  ajax_in_progress: false,

  setup: function() {
    $("body").bind("ajaxStart", function() {
      AjaxHelper.ajax_in_progress = true
    });

    $("body").bind("ajaxComplete", function() {
      AjaxHelper.ajax_in_progress = false
    });
  }
}

/*
 * Insert emoticon into the #card_message textarea.
 */
function insert_emoticon(characters) {
  var old_value = $('#sent_card_conductor_message').val();
  $('#sent_card_conductor_message').val(old_value + characters);
  $('#sent_card_conductor_message').focus();
}

/*
 * Insert address in a "name#email" format into card recipient form fields.
 */
function insert_addressbook_address(packed_address) {
  var arr = packed_address.split("#");
  /* We need to find last recipient field id */
  id = $('#recipients_list li:last')[0].id.match(/recipient_(\d)$/)[1];
  $('#recipient_name_' + id + '_input').val(arr[0]);
  $('#recipient_email_' + id + '_input').val(arr[1]);
}

/*
 * Condition for sending remote call with user query
 */

var previous_user_query = ""

function check_send_user_query() {
  // User can type new characters or delete them to see all entries
  var ret = $('#user_query').val().length > 2 ||
    previous_user_query.length > $('#user_query').val().length;
  previous_user_query = $('#user_query').val();
  return ret;
}

/*
 * Replace element of given ID with spinner
 */
function replace_with_spinner(id) {
  $("#" + id + " *").hide();
  $("#" + id).append('<img id=\'spinner_image\', src=\'/images/spinner.gif\'/>');
  return true;
}

/*
 * Register form popup functions
 */
function on_popup_form_key_pressed(e, form_id) {
  var key  = (window.event) ?    // MSIE or Firefox?
    event.keyCode : e.keyCode;
  var escape = (window.event) ?
    27 : e.DOM_VK_ESCAPE; // MSIE : Firefox
  var enter = 13;

  if(key == enter) {
    $(form_id).submit();
  } else if(key == escape) {
    Windows.closeAll();
  }
}

function submit_register_form() {
  $('new_user').submit(); return true;
}

function submit_login_form() {
  $('login_form').submit(); return true;
}

function delayed_focus_on(id) {
  setTimeout(function() {$(id).focus();}, 500);
  return true;
}

function on_register_form_showed() {
  return delayed_focus_on('user_login');
}

function on_login_form_showed() {
  return delayed_focus_on('email');
}

/*
 * Addressbook
 */

function addressbook_copy_real_name() {
  $('addressbook_details_conductor_owner_name').value =
    $('addressbook_details_conductor_forename').value + ' ' +
    $('addressbook_details_conductor_surname').value
}

function hide_bookmark_no_js_warn() {
  $('.bookmark_box_no_js').hide();
  $('.bookmark_link').show();
}

function act_as_link(id) {
  id = "#" + id
  $(id).mouseover(function(e) {
    $(id).addClass('hover');
  });

  $(id).mouseout(function(e) {
    $(id).removeClass('hover')
  });
}

function enableJS() {
  $($A(document.getElementsByTagName("body")).first()).addClassName("with-js");
}

function selectCheckboxesCallback(buttonId, checkboxesRegexp, deselectCaption) {
  var button = $("#" + buttonId);
  button.checkboxesRegexp = checkboxesRegexp;
  button.selectCaption = button.html();
  button.deselectCaption = deselectCaption;
  button.click(function(e) {
    var check = button.html() == button.selectCaption;
    if(check)
      button.html(button.deselectCaption);
    else
      button.html(button.selectCaption);
    $("input[type=checkbox]").attr('checked', check);
  });
}

// Djabbi

function attachDjabbiFormEvents() {
  if($('#shipping_link') != null) {
    $('#shipping_link').click(function(event) {
      $('#recipient-fields').removeClass('without-js');
      $('#shipping_link').hide();
      return true;
    })
  }

  if($('#message_link') != null) {
    $('#message_link').click(function(event) {
      $('#message').removeClass('without-js');
      $('#message_link').hide();
      return true;
    })
  }
}

function hideAfterClick(buttonID) {
  $('#' + buttonID).click(function(event){
    $(this).hide();
  })
}

function directoryTrashItemsObserver(directoryCardsPath, confirmationText) {
  var setVisibilityAndPulsate = function(selector, visible, pulsate) {
    if(visible) {
      if(pulsate) $(selector).fadeIn("slow");
      else $(selector).show();
    } else
      $(selector).hide();
  }

  var setFormAction = function(actionPath) {
    $("#directory_cards_form").attr('action', actionPath);
  }

  var itemStateChanged = function(e) {
    var checked = false;
    $(".directory_card_checkbox").each(function() {
      if(this.checked) checked = true;
    });

    $.each(["#undo_delete", "#final_remove"], function() {
      setVisibilityAndPulsate(this + "_link", checked, e != null);
    });
    setVisibilityAndPulsate("#empty_trash_link", !checked, e != null);
  };

  $(".directory_card_checkbox").click(itemStateChanged);
  $("#select_all_button").click(itemStateChanged);
  itemStateChanged(null);

  var actions = {"undo_delete": "undo_delete", "empty_trash": "clear",
    "final_remove": "delete_cards"};
  $.each(actions, function(action_id, caption) {
    $("#" + action_id + "_link").click(function(e) {
      if(action_id == "undo_delete" || confirm(confirmationText)) {
        $("#directory_cards_form").attr('action', directoryCardsPath + '/' + caption);
        $("#directory_cards_form").submit();
      };
    });
  });
}

$(function() {
  $.each([".login", ".registration"], function(i, type) {
    $(type + "_link").click(function(e) {
      e.preventDefault();
      $(type + "_popup").modal();
    });
  });

  $("#card-with-features").mouseover(function() {
    $("#card-features").addClass("visible");
  });

  $("#card-with-features").mouseout(function() {
    $("#card-features").removeClass("visible");
  });

  $("#special-emoticons-link").click(function() {
    $("#special-emoticons-bar").show();
  });

  $("#new_feedback").append("<input type='hidden' name='feedback[javascript]' value='enabled' />")

  AjaxHelper.setup();
})
