// This behaviour class (for lowpro) will turn form into ajax-multipart form (form capable of file
// uploads throught ajax). It is basically simplified version of this:  http://valums.com/ajax-upload/

AjaxUpload = Behavior.create({
  initialize: function() {
  },

  onsubmit: function() {
    var iframe = this.createIFrame();
    this.element.target = iframe.name;

    // HACK: force :format=js (Rails only!)
    this.element.action = this.element.action.replace(/(\.[^\.\/]+)?$/, '.js')

	  var toDeleteFlag = false;	
    iframe.observe('load', function() {
	    if (iframe.src == "about:blank") {
				// First time around, do not delete.
				if (toDeleteFlag) {
  				// Fix busy state in FF3
					setTimeout(function() { document.body.removeChild(iframe); }, 0);
				}
				return;
			}				
				
			var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
      var response = doc.body.innerHTML;
      response = response.replace(/(^<[^>]+>)|(<\/[^>]+>$)/g, '');
      response = response.unescapeHTML();
									
			this.onComplete(response);
				
			// Reload blank page, so that reloading main page
			// does not re-submit the post. Also, remember to
			// delete the frame
			toDeleteFlag = true;				
			iframe.src = "about:blank"; //load event fired									
		}.bind(this));
	},

  onComplete: function(response) {
    this.element.getElementsBySelector("input[type=file]").each(function(element) {
      element.value = '';
    });

    eval(response);

    // reapply lowpro behaviours.
    if (Event.addBehavior) {
      Event.addBehavior.reload();
    }
  },

  createIFrame: function() {
		// unique name
		// We cannot use getTime, because it sometimes return
		// same value in safari :(
		var id = this.getUID();
		
		// Remove ie6 "This page contains both secure and nonsecure items" prompt 
		// http://tinyurl.com/77w9wh
		var iframe = new Element('iframe', {'src': 'javascript:false;', 'name': id, 'id': id});
		iframe.style.display = 'none';

		document.body.appendChild(iframe);
    return iframe;
	},

  getUID: function() {
    var id = 0;
    return function() {
      return 'ajax_upload_' + id++;
    };
  }()  
});
