// application.js

(function($){

  $.log = function(msg){
    if(window.console){
      console.log(msg);
    }
  };

  /////////////////////////////
  // jQuery object functions //
  /////////////////////////////

  // Clear out the inputs/selects/checkbox/radio buttons for a form.
  $.fn.clear_form = function() {
    return this.each(function() {
      var type = this.type, tag = this.tagName.toLowerCase();
      if (tag == 'form')
        return $(':input',this).clear_form();
      if (type == 'text' || type == 'password' || tag == 'textarea')
        this.value = '';
      else if (type == 'checkbox' || type == 'radio')
        this.checked = false;
      else if (tag == 'select')
        this.selectedIndex = 0;
    });

  };

  //////////////////////////////
  // jQuery utility functions //
  //////////////////////////////

  // Adds the .json extension to the request.
  $.appendJsonExtension = function(url){
    parts = url.split("?");
    request = parts[0];
    params = parts[1];

    json_request_url = request + ".jsonr";
    if(params){
      json_request_url += "?" + params;
    }

    return json_request_url;
  };

  $.jsonRequest = function(options){
    validResponseCB = options.success || function(jsonResponse){
      $.log("Valid response returned");
      $.log(jsonResponse);
    };

    invalidResponseCB = options.error || function(jsonResponse){
      $.log("Invalid response returned");
      $.log(jsonResponse);
    };

    options.success = function(jsonResponse){
      if(jsonResponse.status == "redirect"){
        window.location = jsonResponse.to;
      }
      else{
        validResponseCB(jsonResponse);
      }
    };

    options.error = function(XMLHttpRequest, textStatus){
      if(XMLHttpRequest.status == 400){
        jsonResponse = window.eval('(' + XMLHttpRequest.responseText + ')');
        invalidResponseCB(jsonResponse);
      }
      else{
        $.log("Request error: " + textStatus);
        $.log(XMLHttpRequest);
      }
    };

    options.dataType = "json";
    options.type = options.type || "POST";
    options.url = $.appendJsonExtension(options.url);

    $.ajax(options);
  };

  $.buildFlash = function(type, message){
    $("<div id=\"flash-" + type + "\" class=\"flash grid_6 flash-js\"><p>" + message + "</p></div>").
      css({left: (($(window).width() / 2) - 230) + "px"}).
      prependTo("#container").
      animate({opacity: 1.0}, 3000).
      fadeOut("fast", function(){ $(this).remove(); });
  }

})(jQuery);


// Onload function
$(function(){

  if($(".destroy-action").length){
    $("a.destroy-action").live("click", function(){
      var delete_url = $(this).attr("href");
      if(confirm("Are you sure you want to remove this?")){
        $.jsonRequest({ type: "delete", url: delete_url });
      }
      return false;
    });
  }

  // Auto remove flash after 5 seconds.
  if($("#flash").length){
    setTimeout(function(){
      $("#flash").slideUp("fast");
    }, 5000);
  }
});



