/***
 * Creates new ajax object
 */
function ajax() {
	this.request			= false;
	this.requestBusy		= false;
	this.requestTimeout		= 60;
	this.requestTimestamp	= 0;

	this.withLoading		= true;
	this.uploadStatus		= false;
};

// Return true if request is busy
ajax.prototype.isBusy = function () {
	return this.requestBusy;
};

// Load url
ajax.prototype.load = function (target, url) {
	var current = this;
	
	var dateNow = new Date();
	var timeNow = dateNow.getTime();

	if(this.isBusy() && (this.requestTimestamp + this.requestTimeout) < timeNow) {
		this.reset();
	}

	if(this.isBusy()) {
		window.setTimeout(function() { current.load(target, url); }, 100);
	} else {
	
		if(target == undefined || target == '' || url == undefined || url == '')
			return;
	
		try {
			this.request = new XMLHttpRequest();
			if(this.request.overrideMimeType) {
	            this.request.overrideMimeType('text/xml; charset=ISO-8859-1');
	        }
		} catch(e) {
			try {
				this.request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					this.request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					this.request = false;
				} 
			}
		}
	
		this.requestBusy = true;
		this.requestTimestamp = timeNow;
	
		if(this.withLoading) {
			var body = document.getElementsByTagName("body")[0];
			if(body) body.style.cursor = 'wait';
	
			if(this.parent && this.parent.switchLoading)
				this.parent.switchLoading(1);
		}
	
		var current = this;
		this.request.onreadystatechange = function(e) { current._insertContent(target); };
		this.request.open('GET', url, true);
		this.request.send(null);
	}

	return;
};

// Send url
ajax.prototype.send = function (target, url, query, formname) {
	var current = this;
	
	var dateNow = new Date();
	var timeNow = dateNow.getTime();

	if(this.isBusy() && (this.requestTimestamp + this.requestTimeout) < timeNow) {
		this.reset();
	}

	if(this.isBusy()) {
		window.setTimeout(function() { current.send(target, url, query, formname); }, 100);
	} else {
	
		if(target == undefined || target == '' || url == undefined || url == '' || formname == undefined || formname == '')
			return;
	
		try {
			this.request = new XMLHttpRequest();
			if(this.request.overrideMimeType) {
	            this.request.overrideMimeType('text/xml; charset=iso-8859-1');
	        }
		} catch(e) {
			try {
				this.request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					this.request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					this.request = false;
				} 
			}
		}
			
		var hasFiles = false;
		var requestBody = query;
		var ContentType = 'application/x-www-form-urlencoded; charset=iso-8859-1';
		var form = document.forms[formname];
		var elems = form.elements;
		for(var i=0;i<elems.length;i++) {
			var elem = elems[i];
			if(elem.name != '' && elem.value != '') {
				if(elem.type == 'file' && elem.value != '') {
					hasFiles = true;
				} else if(elem.type == 'select-multiple') {
					for(var opt=0;opt<elem.options.length;opt++) {
						// Disabled for use select fields as assigning fields
						if(elem.options[opt].selected == true) {
							var value = encodeURIComponent(elem.options[opt].value);
							requestBody += '&' + elem.name + '=' + value;
						}
					}
				} else if(elem.type == 'select-one') {
					var value = encodeURIComponent(elem.value);
					if(elem.value != '') {
						requestBody += '&' + elem.name + '=' + value;
					}
				} else if(elem.type == 'checkbox' || elem.type == 'radio') {
					var value = encodeURIComponent(elem.value);
					if(elem.checked && elem.value != '') {
						requestBody += '&' + elem.name + '=' + value;
					}
				} else if(elem.type == 'submit' || elem.type == 'button') {
					//elem.disabled = true;
				} else {
					var value = encodeURIComponent(elem.value);
					if(elem.value != '') {
						requestBody += '&' + elem.name + '=' + value;
					}
				}
				/*	
				if(elem.type == 'file') {
					hasFiles = true;
				} else {
					var value = encodeURI(elem.value);
					if(elem.type == 'checkbox' && elem.checked == false) {
						value = '';
					}
				
					requestBody += '&' + elem.name + '=' + value;
				}*/
			}
		}

		if(hasFiles) {
			this._uploadFiles(form, target, requestBody);
		} else {
			if(this.withLoading) {
				var body = document.getElementsByTagName("body")[0];
				if(body) body.style.cursor = 'wait';
	
				if(this.parent && this.parent.switchLoading)
					this.parent.switchLoading(1);
			}

			form.action		= '';
			form.enctype	= 'application/x-www-form-urlencoded';
			form.target		= '';
			form.method		= 'post';
			
			this.requestBusy = true;
			this.requestTimestamp = timeNow;

			var current = this;
			this.request.onreadystatechange = function(e) { current._insertContent(target); };
			this.request.open('POST', url, true);
			this.request.setRequestHeader("Content-Type", ContentType); 
			this.request.setRequestHeader("Content-Length", requestBody.length); 
			this.request.setRequestHeader("Connection", "close"); 
			this.request.send(requestBody);
		}
	}

	return;
};

// Insert loaded page in target object
ajax.prototype.reset = function () {
	if(this.request) {
		this.request = false;
		this.requestBusy = false;
	}
};

// Insert loaded page in target object
ajax.prototype._closeUploadStatus = function (progressId) {
	var divUploadStatus = GetLayer('boxUploadStatus');
	if(divUploadStatus) {
		window.setTimeout(function() { SwitchLayer(divUploadStatus, 0); }, 2000);
	}

	this.uploadStatus = false;
	this.withLoading = true;

	this.request = false;
	this.requestBusy = false;
}	

// Insert loaded page in target object
ajax.prototype._openUploadStatus = function (progressId) {
	var current = this;
	
	if(!this.uploadStatus) {
		return;
	}
	
	var divUploadStatus = GetLayer('boxUploadStatus');
	if(typeof(divUploadStatus) == 'undefined' || !divUploadStatus) {
		divUploadStatus = document.createElement('DIV');
	    divUploadStatus.id = 'boxUploadStatus';
	    divUploadStatus.name = 'boxUploadStatus';
	    divUploadStatus.setAttribute('id', 'boxUploadStatus');
	    divUploadStatus.setAttribute('name', 'boxUploadStatus');

		SetStyle(divUploadStatus, 'position', 'absolute');
		SetStyle(divUploadStatus, 'display', 'none');
		SetStyle(divUploadStatus, 'zIndex', '99999');
		SetStyle(divUploadStatus, 'position', 'absolute');
		SetStyle(divUploadStatus, 'visibility', 'hidden');
		SetStyle(divUploadStatus, 'backgroundColor', '#f6f6f6');
		SetStyle(divUploadStatus, 'border', 'solid 1px #647ca3');
		SetStyle(divUploadStatus, 'overflow', 'hidden');
 		SetStyle(divUploadStatus, 'padding', '10px 10px 10px 10px;');
 		SetStyle(divUploadStatus, 'width', '300px');
		SetStyle(divUploadStatus, 'height', '200px');
		
		var body = document.getElementsByTagName('body')[0];
		var bodyWidth = parseInt(GetWidth(body));
		var bodyHeight = parseInt(GetHeight(body));
			
		var statusWidth = parseInt(GetStyle(divUploadStatus, 'width'));
		var statusHeight = parseInt(GetStyle(divUploadStatus, 'height'));

		SetStyle(divUploadStatus, 'left', (bodyWidth/2-statusWidth/2) + 'px');
		SetStyle(divUploadStatus, 'top', (bodyHeight/2-statusHeight/2) + 'px');

		body.insertBefore(divUploadStatus, body.firstChild);
	}

	if(divUploadStatus) {
		SwitchLayer(divUploadStatus, 1);

		// Reload
		if(this.isBusy()) {
			window.setTimeout(function() { current._openUploadStatus(progressId); }, 10);
		} else {
			this.load('boxUploadStatus', Prospitalia.getRoot() + 'upload_status.php?' + Prospitalia.getSession() + '&ProgressId=' + progressId);
			window.setTimeout(function() { current._openUploadStatus(progressId); }, 1000);
		}
	}
}

// Insert loaded page in target object
ajax.prototype._uploadFiles = function (form, target, requestBody) {
	var progressId = form['ProgressId'].value;

	if(progressId == '') {
		alert('No Progress-Id found!!');
		return;
	}
	
	if(typeof form != 'undefined' && form) {
		var hiddenDiv = GetLayer('boxUpload');
		if(typeof(hiddenDiv) == 'undefined' || !hiddenDiv) {
			hiddenDiv = document.createElement('DIV');
			hiddenDiv.id = 'boxUpload';
			hiddenDiv.name = 'boxUpload';
			hiddenDiv.setAttribute('id', 'boxUpload');
			hiddenDiv.setAttribute('name', 'boxUpload');

			var debugSize = "0";
					    
		    SetStyle(hiddenDiv, 'position', 'absolute');
			if(debugSize == "0") {
				SetStyle(hiddenDiv, 'display', 'none');
				SetStyle(hiddenDiv, 'visibility', 'hidden');
			}
			hiddenDiv.innerHTML = '<iframe name="UploadIFrame" id="UploadIFrame" style="width:' + debugSize + 'px; height:' + debugSize + 'px; overflow:hidden; border:none"></iframe>';

	        var body = document.getElementsByTagName('body')[0];
			body.insertBefore(hiddenDiv, body.firstChild);
		}

		form.onsubmit	= '';
		form.enctype	= 'multipart/form-data';
		form.target		= 'UploadIFrame';
		form.method		= 'post';
	
		if(form.mergeAttributes) {
			form.mergeAttributes(form, false);
		}

		var e = document.createElement('INPUT');
		e.type = 'hidden';
		e.name = 'target';
		e.value = encodeURI(target);
		form.appendChild(e);
		
		var e = document.createElement('INPUT');
		e.type = 'hidden';
		e.name = 'query';
		e.value = encodeURI(requestBody);
		form.appendChild(e);
	
		var countFiles = 0;
		var elems = form.elements;
		for(var i=0;i<elems.length;i++) {
			var elem = elems[i];
			if(elem.type == 'submit' || elem.type == 'button') {
				elem.disabled = true;
			} else if(elem.type == 'file' && elem.name != '' && elem.value != '') {
				countFiles++;
			}
		}

		form.action		= form.action + '?&ProgressId=' + progressId + '&ProgressCountFiles=' + encodeURI(countFiles);

		var e = document.createElement('INPUT');
		e.type = 'hidden';
		e.name = 'ProgressCountFiles';
		e.value = encodeURI(countFiles);
		form.appendChild(e);

		this.uploadStatus = true;
		this.withLoading = false;
		this._openUploadStatus(progressId);
		
		form.submit();
	}
};

// Insert loaded page in target object
ajax.prototype._insertContent = function (target) {
    if(this.request.readyState != 4) {
    	return;
    }
	
	if(this.request.status == 200) {
		var targetObj = GetObject(target);
		if(targetObj) {
			SetContent(targetObj, this.request.responseText);
			this._execJS(targetObj);
		}
	
		var body = document.getElementsByTagName("body")[0];
		if(body) body.style.cursor = 'auto';
			
		if(this.parent && this.parent.switchLoading)
			this.parent.switchLoading(0);
	}

	this.reset();
	
	return;
};

// Execute javascript in loaded page
ajax.prototype._execJS = function (node) {
	var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
	var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
	var bMoz = (navigator.appName == 'Netscape');
	var st = node.getElementsByTagName('script');
	var strExec;
	
	for(var i=0;i<st.length; i++) {
		if (bSaf) {
			strExec = st[i].innerHTML;
		} else if (bOpera) {
			strExec = st[i].text;
		} else if (bMoz) {
			strExec = st[i].textContent;
		} else {
			strExec = st[i].text;
		}

		try {
			eval(strExec);
		} catch(e) {
		}
	}

	return;
};
