/*
	COMMUNICATION
	
	(c) Copyright 2003 - Ruben Daniëls, Virtual Cowboys C.V.
*/

if(self.HTMLElement){
HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr){
	var r = this.ownerDocument.createRange();
	r.setStartBefore(this);
	var parsedHTML = r.createContextualFragment(htmlStr);
	this.appendChild(parsedHTML)
}
}

HTTP = {
	calls : new Array(),
	bin : new Array(),
	
	getChannel : function(){
		if(this.bin.length) return this.bin.pop();
		
		document.body.insertAdjacentHTML("beforeEnd", "<iframe id='comm_channel' name='comm_channel'></iframe>");
		var iframe = document.getElementById("comm_channel");
		iframe.style.display = "none";

		if(DEBUG){
			iframe.style.display = "block";
			iframe.style.position = "absolute";
			iframe.style.left = "0px";
			iframe.style.top = "0px";
			iframe.style.width = "300px";
			iframe.style.height = "100px";
		}
		
		return iframe;
	},
	
	storeChannel : function(iframe){
		this.bin.push(iframe);
	},
	
	call : function(page, vars, receive){
		var iframe = this.getChannel();
		var request = new Array();
		
		for(var i=0;i<vars.length;i++) 
			request.push(vars[i][0] + "=" + encodeURI(vars[i][1]));

		request.push("request_id=" + (this.calls.push([iframe, receive]) - 1));
		iframe.src = page + "?" + request.join("&");
		return this.calls.length-1;
	},
	
	receive : function(id, data){
		if(this.calls[id][1]) this.calls[id][1](data);
		this.storeChannel(this.calls[id][0]);
	},
	
	abort : function(id){
		this.calls[id] = null;
	}
}