$().ready(function() {

  // Enable all forms
  $('input[type="submit"]').removeAttr('disabled');

  // Catch all AJAX links
  $('a[rel="ajax"]').live('click', function(e) {
    var self = this;
    
    // Do not follow link
    e.preventDefault();
    var href = $(self).attr('href');
    var static = $(self).hasClass('static');
    
    // Reload same page
    if (href == window.location.href || href == window.location.pathname) {
      window.location.href = href;
    }
    
    // Close button
    else if (href == '#close') {
      // Close any modals
      if ( $('#modal').length ) {
        $('#modal').fadeTo("fast", 0, function() { $(this).remove(); });
      }
    }
    
    // A bundle
    else if ($(self).hasClass('bundle')) {
      var data = Object();
      $('input.bundle:checked').each(function() {  
        var name = $(this).attr('name');
        data[name] = $(this).val();
      });
      ajax_fetch(href, data, static);    
    }
    
    // Fetch via AJAX
    else {
      ajax_fetch(href, null, static);
    }
  });


  // Catch all AJAX forms
  $('#modal form').live('submit', function(e) {
    var self = this;
  
    // Disable submit
    e.preventDefault();
    $(self).find('input[type="submit"]').attr('disabled', 'disabled');
    
    // Generate post data
    var href = $(self).attr('action');
    var data = Object();
    $(self).find('input[type="text"], input[type="hidden"], input[type="password"], input[type="checkbox"]:checked, select').each(function() {
      var name = $(this).attr('name');
      data[name] = $(this).val();
    });
    
    // Fetch via AJAX
    ajax_fetch(href, data);
  
  });
  
  
  // Fetches via AJAX
  function ajax_fetch(href, data, noanimate) {
    $.ajax({
      type: (data) ? 'POST' : 'GET',
      url: href,
      data: data,
      dataType: 'html',
      success: function(data, textStatus, jqXHR) {

        // No data try to reload page via ajax
        if (data == '') {
          ajax_fetch(window.location.href);
        }
        
        // Modal page
        else if ($(data)[0].nodeName == 'DIV') {
        
          // ID of modal contents, redirect if none
          var id = $(data).find('div').attr('id');
          if (!id) { window.location.href = href; }
        
          // Open a modal if not open
          if ( !$('#modal').length ) {
            $('<div id="modal"><div class="blackout"></div><div class="content"></div></div>').appendTo('body');
            $('#modal').fadeTo("fast", 1);
          }
          
          // Prepare to show content           
          var _show = function() {
            $('#modal .content').replaceWith(data);
            if (!$(data).find('div').hasClass('noclose')) {
              var closer = $('<a class="close" href="#close" rel="ajax">Close</a>');
              $('#modal .content').prepend(closer);
              $('#modal .blackout').click(function() { $(closer).click(); } );
            }
            if (noanimate) { $('#modal .content').fadeTo(0, 1); } else { $('#modal .content').fadeTo("fast", 1); }
            $('#modal input[type="submit"]').removeAttr('disabled');
          }
          
          // Animate or just show
          if (noanimate) { _show(); } else { $('#modal .content').fadeTo("fast", 0, function() { _show(); }); }

        }
  
        // Full page
        else {
        
          // Iterate each ajax element
          $(data).filter('.ajax').add($(data).find('.ajax')).each(function() {
          
            // Replace client elements with remote
            var id =  $(this).attr('id');
            if (id) { $('#'+id).replaceWith(this); }
            
            // Close any modals
            if ( $('#modal').length ) {
              $('#modal').fadeTo("fast", 0, function() { $(this).remove(); });
            }
          });
          
          // Reset the page
          reset_page();
        }
        
      }
    });
  }
  
});
