/*
	This note must stay intact.
	
	Author:
		Mattias Rundqvist, Webparts (www.webparts.se)
	License:
		Creative Commons Attribution-Share Alike 3.0 License
		http://creativecommons.org/licenses/by-sa/3.0/
*/

function wp_HttpRequest( mcfg ) {
	
	var self = this;
	var obj = null;
	var data = null;
	
	var cfg = {
		mode : (mcfg.mode == "dom") ? "dom" : "text",
		autoload : (mcfg.autoload==false)?false:true,
		url : mcfg.url ? mcfg.url : "",
		parameters : mcfg.parameters ? mcfg.parameters : "",
		method : (mcfg.method == "post") ? "post" : "get",
		form : mcfg.form ? mcfg.form : "",
		cache : (mcfg.cache==false)?false:true,
		onload : mcfg.onload,
		onerror : mcfg.onerror
	};
	
	// -- debug
	try{var debug = new wp_Log();}catch(e){var debug = new Object();debug.log = function(){};};
	this._function = "wp_HttpRequest";
	this.debug = debug;
	// --
	
	init();
	
	function init() {

		if( cfg["autoload"] && cfg["url"]) {
			createConnection();
			load();
		}
	}
	
	function createConnection() {
	
		if( cfg["mode"] == "dom" ) {
			// -- Loading data as dom structure
			if( document.implementation && document.implementation.createDocument ) {
				obj = document.implementation.createDocument("", "", null);
				obj.onload = onload(); // -- mozilla doesn't support "readystatechange" on this object
			} else if( window.ActiveXObject ) {
				obj = new ActiveXObject("Microsoft.XMLDOM");
			} else {
				// -- no support
				obj = null;
			}
		} else {
			// -- Loading data as text
			if(window.XMLHttpRequest && !(window.ActiveXObject)) {
				obj = new XMLHttpRequest();
			} else if(window.ActiveXObject) {
			
				var ver = new Array("Msxml6","Msxml5","Msxml3","Msxml2","Msxml4","Microsoft");
				var i = 0;
				
				do {
					try {
						obj = new ActiveXObject(ver[i++]+".XMLHTTP");
					} catch(e) {
						obj = null;
					}
				} while( !obj && i<ver.length );
			}
			// --
		}
		
		if( !obj && cfg["onerror"] ) {
			cfg["onerror"]();
		}
		
		if( obj ) {
			obj.onreadystatechange = onstatechange;
		}
	}
	
	// -- public functions ------------------------------
	this.cancel = function() {
		if( obj )
			obj.abort();
	}
	
	function load( location, parameters ) {
		
		location = location ? location : cfg.url;
		
		// -- Kolla så vi har en url...
		if( !location ) {
			return false;
		}
		// --
		
		// -- Har vår url parametrar?
		if( location.indexOf("?") > -1 ) {
			//-- Ja, splitta...
			parameters = location.split("?")[1];
			location = location.split("?")[0];
		} else if( !parameters ) {
			// -- Nej, ladda parametrar från constructor
			parameters = cfg.parameters;
		}
		
		if( !cfg.cache ) {
			if( parameters.length ) {
				parameters += "&";
			}
			parameters += "__wp_nocache=";
			parameters += Math.random();	
		}
		
		debug.log(self,parameters);
		
		if( cfg.mode == "dom" ) {
			obj.load( url );
		} else {			
			createConnection();
			location = location + ((parameters.length) ? ("?" + parameters) : "");
			obj.open("GET", location, true);
			obj.send(null);
		}
	}
	this.load = load;
	
	this.submit = function( form, field, action ) {
	
		form = form ? form : cfg.form;
		var parameters = null;
		var data = "";
		
		// -- Försök skapa wp_Form objekt
		var wpform = null;
		
		debug.log(self,"trying to create wp_Form with: "+form);
		
		try {
			wpform = new wp_Form({ id : form });
		} catch( err ) {
			// -- wp_Form.js verkar inte finnas...
			debug.log(self,"FATAL: wp_Form missing...");
		}
		// --
		
		// -- Finns det något formulär att skicka?
		if( !wpform || !form || (field && !document[form][field]) ) {
		
			if( cfg.onerror ) {
				cfg.onerror();
			}
			return;
		}
		// --
		
		// -- bestäm action --
		action = action ? action : cfg.action;
		action = action ? action : document.getElementById(form).action;
		action = action ? action : "/";
		// --
		
		// -- skicka hela formuläret eller endast ett fält?
		if( field ) {
			parameters = wpform.collect( field );
		} else {
			parameters = wpform.collect();
		}
		// --
		
		// -- Bygg...
		for( param in parameters ) {
			if( typeof parameters[param] != "function" ) {
				
				if( data ) {
					data += "&";
				}
				
				if( typeof parameters[param] == "string" ) {
					data += (param + "=" + escape( parameters[param] ));
				} else {
					for( var count = 0; count < parameters[param].length; count++ ) {
						if( data && count ) {
							data += "&";
						}
						data += (param + "=" + escape( parameters[param][count] ));
					}
				}
			}
		}
		
		if( !cfg.cache ) {
			if( data.length ) {
				data += "&";
			}
			data += "__wp_nocache=";
			data += Math.random();	
		}
		
		debug.log(self,"data: "+data);
		// --
		
		// -- posta --
		debug.log(self,"Posting " + data.length + " bytes of data to: "+action);
		
		createConnection();
		obj.open("POST", action, true);
		obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		obj.setRequestHeader("Content-length", data.length);
		obj.setRequestHeader("Connection", "close");
		obj.send( data );
		// --
	};
	// --------------------------------------------------
	
	// -- event functions -------------------------------
	function onstatechange() {
	
		if( cfg["onstatechange"] ) {
			cfg["onstatechange"]( obj.readyState );
		}
		
		if(obj.readyState == 4) {
			onload();
		}
	}
	
	function onload() {
	
		var doc = null;
		
		if( typeof DOMParser == "function" ) {
			var dp = new DOMParser();
			doc = dp.parseFromString( obj.responseText, "text/xml" );
		} else if( window.ActiveXObject ) {
			doc=new ActiveXObject("Microsoft.XMLDOM");
			doc.async="false";
			doc.loadXML(obj.responseText);
		}
		this.dom = doc.documentElement;
		this.text = obj.responseText;
		
		debug.log(self,"Recieving "+this.text.length +" bytes of data");
		
		if( cfg["onload"] ) {
			cfg["onload"]( this );
		}
	}
	// --------------------------------------------------
	
}

