/**
 * Simple cross subdomain Ajax based on Prototype.
 * 2008-01-20 16:57:00 UTC Arrix
 *
 * Requires prototype.js
 *
 * Consists of
 * cross_subdomain_ajax.js
 * cross_subdomain_ajax.html
 *
 *
 * Usage:
 * Include cross_subdomain_ajax.js in your requesting page.
 * Put cross_subdomain_ajax.html in the domain being requested.
 *
 * CrossSubDomainAjax.baseDomain = 'xxx.com';
 *
 * CrossSubDomainAjax.request(url, options);
 * The parameters are the same as Protptype's new Ajax.Request(...)
 *
 * Configurations:
 * You must specify the base domain by
 * CrossSubDomainAjax.baseDomain = 'xxx.com';
 *
 * You can specify the url pattern for the html page required
 * CrossSubDomainAjax.htmlUrl = 'http://#{DOMAIN}/javascripts/lib/cross_subdomain_ajax.html?baseDomain=';
 *
 *
 * Tests
 * CrossSubDomainAjax.baseDomain = 'diigo.cn';
 * CrossSubDomainAjax.request('http://www.diigo.cn', {onSuccess: function(xhr) {console.log(xhr.responseText);}});
 *
 *
 * Reference:
 * http://www2007.org/program/paper.php?id=801
 * http://fettig.net/weblog/2005/11/30/xmlhttprequest-subdomain-update/
 */
var CrossSubDomainAjax = {
	//must set this before requesting!
	baseDomain: '',
	htmlUrl: 'http://#{DOMAIN}/javascripts/lib/cross_subdomain_ajax.html?baseDomain=',

	/**
	 * Gets the window object of the bridging iframe
	 */
	_getIframeWin: function(domain, baseDomain) {
		//reused existing one for each domain
		var id = 'iframe-crossDomainXHR-' + domain;
		var ifr = document.getElementById(id);
		if (!ifr) {
			ifr = document.createElement('iframe');
                        document.body.appendChild(ifr);
			ifr.id = id;
			ifr.src = this.htmlUrl.replace('#{DOMAIN}', domain) + encodeURIComponent(baseDomain);
            ifr = $(id);
			ifr.hide();
		}

		return ifr.contentWindow;
	},

	/**
	 * Taken from diigolet full2.js
	 */
	_parseDomain: function(url) {
		// add scheme is missing
		if (!/^[^:\/?#]+:\/\//.test(url)) {
			url = 'http://' + url;
		}
    var m = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
    return m[4].toLowerCase();
	},

	/**
	 * Parameters are the same as those of new Ajax.Request(...)
	 */
	request: function(url, options) {

		if (!this.baseDomain) {
			throw '[CrossSubDomainAjax]: you must specify base domain first!';
		}

		var timeout = 10000, interval = 500;

		document.domain = this.baseDomain;

		var ifr = this._getIframeWin(this._parseDomain(url), this.baseDomain);

		var i = 0;
		var timer = setInterval(function() {
			try {
				if (i++ >= timeout / interval || ifr.request) {
					clearTimeout(timer);
					timer = null;

					if (ifr.request) {
//						alert('got it');
						ifr.request(url, options);
					}
				}
			} catch(e) {}
		}, interval);
	}
};