jQuery(document).ready(function($){

  $('a[rel*=facebox]').facebox();

  $("#classification_title").autocomplete("/jobs/auto_complete_for_classification_title",
    { autoFill:false, matchContains:true, max:25, cacheLength:3,
      formatItem: function(row) {
            return row[0];
      }
    }
    );

  $("#classification_title").result(function(event, data, formatted) {
      if (data)
        $("#job_classification_id").val(data[1]);
    });

  $('.submit-link').livequery('click', function() {
    var form = $(this).parents('form');
    if ($(this).attr('href') != '#') {
      form.attr('action', $(this).attr('href'));
    }
    form.submit();
    return false;
  });

  $('.hide-flash-link').click(function() {
    $(this).parents('.system-message').fadeOut();
    return false;
  });

  $(".ajax-destroy").click( function() {
    var my_id = $(this).attr('id');
    var destroy_msg = $('#' + my_id + '_destroy_msg');
    var msg = "Are you sure you want to PERMANENTLY delete this?";
    if (destroy_msg.length > 0)
      msg = destroy_msg.val();

    if ( confirm(msg) ) {
      $.ajax({
        type: "POST",
        data: {_method: "delete"},
        dataType: 'json',
        url: this.href,
        success: function(data,status) {
          if(data == null){
            alert('Nothing in data');
          } else if(data['remove_selector']){
            $(data.remove_selector).fadeAndRemove().not(data.remove_selector);
          } else if(data['replace_selector']) {
            $(data.replace_selector).replaceWith(data['html']);
            $(data.replace_selector).effect("highlight", {}, 1000);
          } else {
            alert(data);
            alert('Missing data in the JSON object');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#facebox .content").html(XMLHttpRequest.data);
          alert(XMLHttpRequest.getAllResponseHeaders());
        }
      });
    }
    return false;
  });

  $("#job_actions").change(function(){
    var selected = $("select#job_actions option:selected");
    var str = $("form").serialize();

    // are there jobs checked?
    if ($("form input:checked").length > 0){
      switch(selected.text()){
        case "Delete":
          var msg = "Are you sure you want to PERMANENTLY delete the jobs selected?";

          var post_data = str + "&_method=delete";

          if ( confirm(msg) ) {
            $.ajax({
              type: "POST",
              data: post_data,
              dataType: 'json',
              url: this.value,
              success: function(data,status) {
                if(data == null){
                  alert('Nothing in data');
                } else if(data['ids_to_remove']){
                  for (i=0; i < data.ids_to_remove.length; i++){
                    $(data.ids_to_remove[i]).fadeAndRemove().not(data.ids_to_remove[i]);
                  }
                } else {
                  alert(data);
                  alert('Missing data in the JSON object');
                }
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.getAllResponseHeaders());
              }
            });
          }
          break;
      }
    } else{
      // TODO: Implement some sort of global FLASH for js stuffs.
      alert('No jobs are selected.');
    }
    $("select#job_actions").val("With Selected");
    return false;
  });

  $('.datepicker').datepicker();
  $('.datepicker').attr("autocomplete","off");

  $(".open-close").click(function() {
    // toggle display of elements
    var child_elements = "." + $(this).attr('id');
    $(child_elements).toggle_show();
    $(this).toggleClass('open');

    if ($(this).hasClass('save-status')) {
      // save opened elements to session
      var state = $(this).hasClass('open') ? 'opened' : 'closed';

      $.ajax({
        type: 'POST',
        data: {_method: 'put', 'element_id': $(this).attr('id'), 'state': state},
        dataType: 'json',
        url: '/preferences/update_open_close'
      });
    }
    return false;
  });

  $('.show-link').click(function() {
    $(this).parents('form')[0].method = "get"
    $(this).parents('form')[0].submit();
    return false;
  });

  hide_state_when_country_is_not_usa($('select.country'));
  $('select.country').change(function() {
      hide_state_when_country_is_not_usa($(this));
  });

  disable_slug_when_not_cw3_linked($('select.cw3client'));
  $('select.cw3client').change(function() {
      disable_slug_when_not_cw3_linked($(this));
      if ($('select.cw3client').val() == "")
        $('input.slug').val('');
      else {
        $('input.slug').val('Uses CW3 Permalink');
      }
  });

  $('ul.jobs-manager li .col-name').masque('.popup-actions');
});

jQuery.fn.masque = function(classSelector) {
  $(this).hover(function(){
        $(this).find(classSelector).stop().show();
    },function () {
        $(this).find(classSelector).stop().hide();
    });
};

function disable_slug_when_not_cw3_linked(cw3_dropdown) {
  if (cw3_dropdown.val() == "")
    $('input.slug').removeAttr("disabled");
  else {
    $('input.slug').attr("disabled", true);
  }
}

function hide_state_when_country_is_not_usa(country_dropdown) {
    if (country_dropdown.val() == "United States")
      $('tr.state-row').show();
    else {
      $('select.state').val('');
      $('tr.state-row').hide();
    }
}


jQuery(document).ajaxSend(function(event, request, settings) {
  if(typeof(AUTH_TOKEN) == "undefined") return;
  if(settings.type == "GET") return;
  if(settings.contentType != "application/x-www-form-urlencoded") return;
  if(settings.data)
    settings.data += "&";
  else {
    request.setRequestHeader("Content-Type",settings.contentType);
    settings.data = "";
  }
  settings.data += "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

jQuery.fn.fadeAndRemove = function() {
  $(this).fadeOut(300, function() { $(this).remove(); });
  return $(this);
};

jQuery.fn.toggle_show = function() {
  return this.each( function() {
    var open_close = $(this).find('.arrow a.open-close')
    if (open_close.hasClass('open')) {
      var child_elements = "." + open_close.attr('id');
      $(child_elements).toggle_show();
    }
    $(this).toggle();
  });
};

