// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function hide_flash(){
  $("#header .msg").slideUp();
}

$(function(){
  $.log = function(obj){
    if ( typeof window.console != "undefined" && typeof window.console.log == "function" ){
      window.console.log(obj)
    }else if ( debugging && print == "function" ){
      print(obj)
    }
  }

  $.notice = function(message){
    if($('#flash-messages .msg-notice').length < 1){
      $('#flash-messages').append('<div class="msg msg-notice"><p>' + message + '</p></div>')
    }
    $('#flash-messages .msg-notice').text(message).slideDown();
    window.setTimeout('hide_flash()',5000);
  }

  $.error = function(message){
    if($('#flash-messages .msg-alert').length < 1){
      $('#flash-messages').append('<div class="msg msg-alert"><p>' + message + '</p></div>')
    }
    $('#flash-messages .msg-alert').text(message).slideDown()
    window.setTimeout('hide_flash()',5000);
  }

  window.setTimeout('hide_flash()',5000);

  // AJAX tasks sending
  $('#task_submit').live('click', function(){
    var url = $('#new_task').attr('action') + '.json';
    var data = {};
    for each(param in $('#new_task').serializeArray())(
      data[param.name] = param.value
    )
    $.ajax({
      url: url,
      type: "POST",
      dataType: "json", 
      data: data, 
      success: function(data, textStatus, XMLHttpRequest){
        $('#task_name').val('')
        if(data.notice != undefined){
          $.notice(data.notice)
        }else if(data.error != undefined){
          $.error(data.error.join('<br/>'))
        }
      }, 
      error: function(request, textStatus, errorThrown){
        $.log(request)
        $.error(textStatus + ': ' + request.status + ' ' + request.statusText)
      }, 
    })
    return false
  })
})
