/*
 * continuous AJAX Framework
 * May-2010
 */

var cleanUpAjaxRequest = function(){
  Loading.hide();
}

// defaultly allow javascript object notation as return object
jQuery.ajaxSetup({ 'beforeSend': function(xhr) {
  xhr.setRequestHeader("Accept", "text/javascript")} });

// the custom ajax_request
var _ajax_request = function(url, data, callback, type, method) {
  if (jQuery.isFunction(data)) {
      callback = data;
      data = {};
  }
  return jQuery.ajax({
      type: method,
      url: url,
      data: data,
      success: callback,
      dataType: type
      });
}

// create shortcuts for PUT and DELETE HTTP REST methods
jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

// the actual new ajax submit function
jQuery.fn.submitWithAjax = function() {
  this.unbind('submit', false);
  this.submit(function() {
    Loading.show();
    $.post(this.action, $(this).serialize(), cleanUpAjaxRequest, "script");
    return false;
  })
 
  return this;
};

// ajax GET request
jQuery.fn.getWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    Loading.show();
    $.get($(this).attr("href"), $(this).serialize(), cleanUpAjaxRequest, "script");
    return false;
  })
  return this;
};
 
// ajax POST request
jQuery.fn.postWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    Loading.show();
    $.post($(this).attr("href"), $(this).serialize(), cleanUpAjaxRequest, "script");
    return false;
  })
  return this;
};

// ajax PUT request
jQuery.fn.putWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    Loading.show();
    $.put($(this).attr("href"), $(this).serialize(), cleanUpAjaxRequest, "script");
    return false;
  })
  return this;
};
/*
var deleted = function(msg) {
  ZornMessage.add(msg);
}*/

// ajax DELETE request
jQuery.fn.deleteWithAjax = function() {
  this.removeAttr('onclick');
  this.unbind('click', false);
  this.click(function() {
    if (! $(this).hasClass('skip_confirmation')){
      var proceed = confirm("really delete this item?");
      if (!proceed)
        return false;
    }
    Loading.show('deleting item');
    $.delete_($(this).attr("href"), $(this).serialize(), cleanUpAjaxRequest,
              "script");
    return false;
  })
  return this;
};

// set the following classes to enable the above functionallity
function ajaxLinks(){
    $('.ajax_form').submitWithAjax();
    $('a.get').getWithAjax();
    $('a.post').postWithAjax();
    $('a.put').putWithAjax();
    $('a.delete').deleteWithAjax();
}

$(document).ready(function(){

    $('.js-get-focus:last').focus();
    $('.js-get-focus-force').focus();

    if($('#continuous-messages li').length > 0)
      $('#continuous-messages').show();

    $('.js_go_back').click(function(e){
      e.preventDefault();
      history.back();
    });
    // All non-GET requests will add the authenticity token
    // if not already present in the data packet
    $(document).ajaxSend(function(event, request, settings) {
      if (typeof(window.AUTH_TOKEN) == "undefined") return;
      // <acronym title="Internet Explorer 6">IE6</acronym> fix for http://dev.jquery.com/ticket/3155
      if (settings.type == 'GET' || settings.type == 'get') return;

      settings.data = settings.data || "";
      settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
    });
    ajaxLinks();

});

function arrToObj(arr)
{
  var obj = {};
  for(var i=0;i<arr.length;i++)
  {
    obj[arr[i]]='';
  }
  return obj;
}

/* ------------------------------------------------------------------ Messages */

var Messages = {
add: function(html_text,status){
        date = new Date()
        html_text = (new Date()).toTimeString().substring(0,8) + " &nbsp;&nbsp; " + html_text;
        var status = status || 'message';
        $('#continuous-messages ul').prepend($('<li/>')
            .html(html_text).addClass('continuous-message '+status));
        Messages.show();
      },
cmd_answer: function(cmd_text,answer){
        $('#continuous-messages ul').prepend($('<li/>')
            .addClass('continuous-message').html(answer));
        Messages.show();
      },
show: function(){
        $('#continuous-messages')
          .slideDown()
          .effect("highlight", 1000);
        $('#continuous-messages').scrollTop($('#continuous-messages').height());
      },
hide: function(){
        $('#continuous-messages').slideUp();
      },
load: function(f){
        $('#continuous-messages').load(f)
          .slideDown();
      },
clear: function(){
         $('#continuous-messages').html('');
       }
}

var Loading = {
show: function(text){
        if (text)
          Messages.add(text);
        else
          Messages.show();
        $('#continuous-loading').show();
      },
hide: function(){
        $('#continuous-loading').hide();
      }
}

$('#close-messages').click(function(e){
    Messages.hide();
});

var Dialog = {
  open: function(html, options){
    var width = options ? options.width || 400 : 400;
    var height = options ? options.height || 200 : 200;
    var title = options ? options.title || '' : '';
    $('#continuous-dialog').width(width)
                     .height(height)
                     .css('marginLeft','-' + (width/2).toString() + 'px');
    if (height < $(window).height())
      $('#continuous-dialog').css('marginTop','-' + (height/2).toString() + 'px');
    else
      $('#continuous-dialog').css({marginTop:'0px',top: 10});
    $('#continuous-dialog .title').text(title);
    $('#continuous-dialog .inner').html(html);
    $('#continuous-dialog').fadeIn();
    $('#continuous-dialog-close').bind('click',function(e){
      e.preventDefault();
      $('#continuous-dialog').fadeOut(500);
      setTimeout(function(){$('#continuous-dialog .inner').html('');},500);
    });
  },
  close: function(){
    $('#continuous-dialog').fadeOut();
  }
}

