/***
 * Creates new ajax object
 */
function ajax() {
	this.request			= false;
	this.requestBusy		= false;
	this.requestTimer		= null;
	this.requestTimeout		= 10;

	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;
	
	if(this.isBusy()) {
		window.setTimeout(function() { current.load(target, url); }, 100);
	} else {
	
		if(isEmpty(target) || isEmpty(url)) {
			return;
		}
	
		try {
			this.request = new XMLHttpRequest();
			if(this.request.overrideMimeType) {
	            this.request.overrideMimeType('text/xml; charset=latin1');
	            //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;
				} 
			}
		}
	
		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);
		}

		this.requestBusy = true;

		this.request.onreadystatechange = function(e) { current._insertContent(target); };
		this.request.open('GET', url, true);
		this.request.send(null);
	}

	delete current;
	
	return;
};

// Send url
ajax.prototype.send = function (target, url, query, formname) {
	var current = this;
	
	if(this.isBusy()) {
		window.setTimeout(function() { current.send(target, url, query, formname); }, 100);
	} else {
	
		if(isEmpty(target) || isEmpty(url) || isEmpty(formname)) {
			return;
		}

		try {
			this.request = new XMLHttpRequest();
			if(this.request.overrideMimeType) {
	            this.request.overrideMimeType('text/xml; charset=latin1');
//	            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 != '') {
				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(hasFiles && form['ProgressId'] && form['ProgressId'].value != '') {
			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.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);
		}
	}

	delete current;
	
	return;
};

// Insert loaded page in target object
ajax.prototype.reset = function () {
	window.clearTimeout(this.requestTimer);

	if(this.request) {
		delete this.request;
		delete this.requestBusy;
		delete this.requestTimer;

		this.request = false;
		this.requestBusy = false;
		this.requestTimer = false;
	}
};

// Insert loaded page in target object
ajax.prototype._closeUploadStatus = function (progressId) {
	var divUploadStatus = GetLayer('boxUploadStatus');
	if(divUploadStatus) {
		window.setTimeout(function() { SwitchLayer(divUploadStatus, 0); }, 1000);
	}

	this.uploadStatus = false;
	this.withLoading = true;

	this.reset();
}	

// 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', '200');
		SetStyle(divUploadStatus, 'position', 'absolute');
		SetStyle(divUploadStatus, 'visibility', 'hidden');
		SetStyle(divUploadStatus, 'backgroundColor', '#f6f6f6');
		SetStyle(divUploadStatus, 'border', 'solid 1px #666666');
		SetStyle(divUploadStatus, 'overflow', 'hidden');
 		SetStyle(divUploadStatus, 'padding', '10px 10px 10px 10px;');
 		SetStyle(divUploadStatus, 'width', '300px');
		SetStyle(divUploadStatus, 'height', '180px');
		
		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', GeoBIP.getRoot() + 'upload_status.php?' + GeoBIP.getSession() + '&ProgressId=' + progressId);
			window.setTimeout(function() { current._openUploadStatus(progressId); }, 1000);
		}
	}
	
	delete current;
}

// 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; background-color: #FFFFFF;"></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 = encodeURIComponent(target);
		form.appendChild(e);
		
		var e = document.createElement('INPUT');
		e.type = 'hidden';
		e.name = 'query';
		e.value = encodeURIComponent(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		= 'upload.pl?&ProgressId=' + progressId + '&ProgressCountFiles=' + encodeURIComponent(countFiles);

		var e = document.createElement('INPUT');
		e.type = 'hidden';
		e.name = 'ProgressCountFiles';
		e.value = encodeURIComponent(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) {
	var current = this;

    if(this.request.readyState != 4) {
		window.clearTimeout(this.requestTimer);
		this.requestTimer = window.setTimeout(function() { current.reset(); }, (this.requestTimeout*1000));
		
	 	return;
    }

	if(this.request && 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();
	
	delete current;
	
	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;
};
