
var or = or || {};  //very simple namespacing.break TODO: support/extend namespaces better

or.admin = {
  initialize: function(){
    $.ajaxSetup({
      'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript");
      }
    });

    if (!window.console)
    {
        window.console = {
            log: function(msg){
                //alert(msg);
            }
        };
    }
  },

  has_errors: function(error_data){

    if (error_data['errors'] != undefined){

      $.displayStatus("There were " + error_data.errors.length + " errors");
      $.each(error_data.errors, function(i, val){
        console.log("error " + i);
        console.log(val);

        $.displayStatus(val[0] + " " + val[1]);
      });
      return true;
    }
    return false;
  }
};
//***
// Active Resource common
//
// *******


function new_resource(url, create_resource_callback)
{
  $.get(url, null, function(data, status){
    var dialog = $("<div></div>").html(data).dialog();

    dialog.find("form").submit(function() {
      $(this).ajaxSubmit({   //context here is the dynamically loaded form
        dataType: 'json',
        success: function(data, status){
          create_resource_callback(data, status);
          dialog.dialog('close');
        }
      });
      return false; //don't *really* submit the form
    });
  },
  "html");
}

function update_resource(url, element, callback)
{
  $.get(url,
    null,
    function(data){
      var dialog = $("<div></div>").html(data).dialog();

      dialog.find('form').submit(function(){
          $(this).ajaxSubmit({
            dataType: 'json',
            success: function(data, status){
              callback(data, status);
              dialog.dialog('close');
            }
          });
          return false;
        });
    },
    "html");
}

function delete_resource(element_to_delete, container_selector, confirm_msg, callback)
{
  var delete_confirmed = false;
  if (confirm_msg == undefined)
  {
    delete_confirmed = true;
  }
  else
  {
    delete_confirmed = confirm(confirm_msg);
  }

  if (delete_confirmed) {
    $.post(
      $(element_to_delete).attr('rel'),
        {
          '_method': 'delete',
          "authenticity_token": form_authenticity_token
        },
        callback
      );

//    $(element_to_delete).closest(container_selector)
////      .css('min-width', '0px')
////      .animate({width: 0}, 1000)
//      .fadeOut(function(){
//        $(this).remove();
//        if (callback)
//        {
//          callback();
//        }
//      });
  }
}

function delete_resources(elements, container_selector, confirm_msg, callback)
{
  if (elements.length == 0)
  {
    alert("No items selected to delete");
  }
  else if (confirm(confirm_msg))
  {
    elements.each(function(index, val){
      delete_resource(val, container_selector, null, callback);
    });
  }
}
