/*============================================================================
  php-upload/submit.js - AJAX upload functions
  Developed for thikmedia by Southbyte -- http://www.southbyte.com/
============================================================================*/

/* track iframes in case of multiple submits */
var crctr = 0;

SouthbyteAJAXUpload = {
	make_iframe:
		/* generates a new iframe and appends it to the body to receive res */
		function (opts)
		{
			/* generate code for an iframe for asynchronous submit */
			var node = 'sbajn_' + Math.floor(Math.random() * 10000) + "_"
					 + crctr++;
			var html = '<iframe style="display: none" src="about:blank" ';
			html += 'id="' + node + '" name="' + node + '" ';
			html += "onLoad=\"SouthbyteAJAXUpload.uploaded('" + node;
			html += "')\"></iframe>";

			/* create a DIV to add iframe to document */
			var d = document.createElement('DIV');
			d.innerHTML = html;
			document.body.appendChild(d);

			/* install onComplete callback */
			if (opts && typeof(opts.onComplete) == 'function') {
				document.getElementById(node).onComplete = opts.onComplete;
			}

			/* success */
			return node;
		},

	uploaded:
		/* called when browser is done loading response */
		function (id)
		{
			var iframe;
			var doc;

			/* get document object from id */
			iframe = document.getElementById(id);
			if (iframe.contentDocument) {
				doc = iframe.contentDocument;
			}
			else if (iframe.contentWindow) {
				doc = iframe.contentWindow.document;
			}
			else {
				doc = window.frames[id].document;
			}

			/* make sure location changed */
			if (doc.location.href == "about:blank") {
				return;
			}

			/* call completion */
			if (typeof(iframe.onComplete) == 'function') {
				iframe.onComplete(doc.body.innerHTML);
			}
		},

	submit:
		/* called to submit a form */
		function (frm, opts)
		{
			var form;
			var iframe;

			/* set up an iframe for this submission */
			iframe = SouthbyteAJAXUpload.make_iframe(opts);

			/* direct result to the new iframe */
			frm.setAttribute('target', iframe);

			/* do we have an onStart callback to call? */
			if (opts && typeof(opts.onStart) == 'function') {
				/* allow callback to decide */
				return opts.onStart();
			}
			else {
				/* submit form */
				return true;
			}
		}
}

/* ======================================================================== */

