
if (typeof MVD === 'undefined') {
	MVD = {};
}

MVD.Ajax = function() {

	var getXMLHttpObject = function () {
		var ret = false;
	    if (window.XMLHttpRequest) {
	        ret = new XMLHttpRequest ();
			if(ret.readyState == null){
					ret.readyState = 1;
					ret.addEventListener('load', function(){
						ret.readyState = 4;
						if(typeof(ret.onreadystatechange)=='function')
							ret.onreadystatechange();
					}, false);
			}		
	    } else if (window.ActiveXObject) {     
	        try { ret = new ActiveXObject ("Msxml2.XMLHTTP"); }
	        catch (e)
	        { try { ret = new ActiveXObject ("Microsoft.XMLHTTP"); }
	          catch (e) { }
	        }
	    } 
	    return ret;
	}
	
	var encode = escape;
	
	var ajaxCall = function (url, parms, onComplete, onError) {
		var xmlHttp = getXMLHttpObject();
		if (xmlHttp) {		
			xmlHttp.onreadystatechange = function ()
			{		
				if (xmlHttp.readyState == 4 || xmlHttp.readyState=="complete") {
					var res_status = 0;
					try {res_status = xmlHttp.status;} catch(e){};				
					if ((res_status >= 200) && (res_status < 300)) {					
						if(onComplete) onComplete(xmlHttp.responseText);
					} else {					
						if(onError) onError(xmlHttp.responseText);
					}
				}
			}
			var qstr = null;
			if (parms) { // Post
				xmlHttp.open ('POST', url, true);
				xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');				
				qstr = '';
				for (var parm in parms) if (parms.hasOwnProperty(parm)) {
					if (qstr) qstr += '&';
					qstr += parm + '=' + encode(parms[parm]);
				}	
			} else { // Get
				// Evitar cache en IE
				xmlHttp.open ('GET', url, true);
				xmlHttp.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );				
			}
			xmlHttp.send (qstr);
		}
	}
	
	return { 
			get: function(url, onComplete, onError) {
				ajaxCall(url, null, onComplete, onError)
			},
			post: ajaxCall, 			
			setEncode: function(enc) {
				encode = (enc == 'UTF8') ? encodeURIComponent : escape;
			}
		}
}();
