/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/
var safari2Timer = null;
var safari2PollCount = 0;
var safari2PollInterval = 25;

AIM = {

	frame : function(c) {
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display: none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);

        // Safari 2 (WebKit 41x) doesn't fire onload events for the iframe loading if it contains xml.
        // Unfortunately, we have to poll whether out root node exists.
        if (navigator.userAgent.match('WebKit/41.'))
        {
            
            safari2Timer = setInterval(function () {
                safari2PollCount++;
                if (safari2PollCount > (1000 / safari2PollInterval) * 30)
                {
                    clearInterval(safari2Timer);
                    alert('Upload failed. Please reload the page and try again');
                }
                if (window.frames[n] && window.frames[n].document && window.frames[n].document.getElementsByTagName('odo')[0])
                {
                    clearInterval(safari2Timer);
                    AIM.loaded(n);
                }
            }, safari2PollInterval);
        }

		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}

		if (!d || !d.location)
		  d = window.frames[id];

		if (d.location.href == "about:blank") {
			return;
		}

		if (typeof(i.onComplete) == 'function') {
//		    var k = []; for (a in d) { k.push(a) }; alert(k.join(', '))
            var v = null;

            // Internet Explorer will return its fancy pancy javascript xml tree's html by default
            // This line makes it return the original XML DOM.
            try {
                if (d.XMLDocument)
                    v = d.XMLDocument.getElementsByTagName('odo')[0];
            } catch (e) {
                // We're obviously doing it wrong for this browser, stop and undo what it might've done
                v = null;
            }
            
			i.onComplete(v || d.documentElement || d.document.documentElement);
		}
	}

}
