/**
 * Author: James Carmichael
 * www.siteclick.co.uk
 *
 * If you use this plugin in your project, please kindly consider linking to the above
 *
 * JQuery ajax upload plugin
 *
 * v0.1 22/06/2008
 * v0.2 01/05/2009	Added 'onStart' function to settings, so upload start can be detected
 *
 * License: MIT
 */

jQuery.fn.ajaxUpload = function(settings) {

  // Set defaults
  var settings = jQuery.extend({
    'loading'    : function() {},
    'onComplete' : function() {},
    'onStart'		 : function() {},
    'type'       : 'json'
  }, settings);

  var _this = this;

  // For each item
  return this.each(function(){

    jQuery(this).submit(function() {
			
			// Do onStart function
			settings.onStart(this);

      // Make up a number
      var iframeId = 'upload_' + Math.round(Math.random() * 1000000);

      // Create iframe for data transfer
      var iframe = jQuery('<iframe name="' + iframeId + '" id="' + iframeId + '"></iframe>');
      jQuery(document.body).append(iframe);
      jQuery(iframe).hide();

      // Set form action attribute
      jQuery(this).attr('target', iframeId);

      // Call the loading function
      settings.loading();

      /**
       * Function to poll iframe every second
       */
      _this.pollIframe = function() {

        // Get iframe HTML
        var html = jQuery('#'+iframeId).contents().find('body').html();

        // Data blank - try later
        if(!html) {
          window.setTimeout(_this.pollIframe, 1000);
          return;
        }
        
      

        // We have some data - send it to the oncomplete function
        switch(settings.type) {
          case 'json':
            var data = eval('('+html+')');
            settings.onComplete(data);
            break;
        }

        // Discard the iframe
        jQuery('#'+iframeId).remove();
      }

      // Begin polling
      window.setTimeout(_this.pollIframe, 1000);


    })

  })
}

