/******************************************************************************
 *	Author:  Petr Suchy (xsuchy09) <suchy@wamos.cz>
 *	Subject:  WAMOS <http://www.wamos.cz>
 *	Copyright: (c) Petr Suchy (xsuchy09) <suchy@wamos.cz> <http://www.wamos.cz>
 ******************************************************************************
 *	SVN info
 ******************************************************************************
 *	$Author: xsuchy09 $
 *	$Date: 2009-10-08 19:29:56 +0200 (čt, 08 X 2009) $
 *	$Revision: 382 $
 *	$Id: ajax.js 382 2009-10-08 17:29:56Z xsuchy09 $
 ******************************************************************************/


/**
 * Objekt pro odesilani a zpracovani XMLHTTP požadavků.
 * @author Petr Suchy (xsuchy09) <suchy@wamos.cz>
 * @copyright (c) 2009 Petr Suchy (xsuchy09) <suchy@wamos.cz> <http://www.wamos.cz>
 */
var ajax = {
	xmlhttp : null, 
	buffer : new Array(), 
	active_request : '', 
	csrf_token : '', 
	
	addRequest : function(url, method, content, headers, userFunction, userFunctionArgument) {
		ajax_state = ajax.getReadyState();
		if (ajax_state == false || ajax_state == 'COMPLETE') {
			ajax.send(url, method, content, headers, userFunction, userFunctionArgument);
		} else {
			ajax.buffer.unshift(new Array(url, method, content, headers, userFunction, userFunctionArgument));
		}
	}, 
	
	trySendRequest : function(ajax_state) {
		if (ajax_state != null && ajax_state == 'COMPLETE') {
			request = ajax.buffer.pop();
			if (request != null && request.length > 0) {
				ajax.send(request[0], request[1], request[2], request[3], request[4], request[5]);
			}
		}
	}, 
	
	send : function(url, method, content, headers, userFunction, userFunctionArgument) {
		try {
			// vytvor xmlhttp request
			this.xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
		} catch (e) {
			// nepodarilo se vytvorit xmlhttp request
			alert('Chyba v soubor ajax.js - Nepodarilo se vytvorit objekt xmlhttp request!');
			return false;
		}
		
		// k pozadavku musime pridat token - jen pokud je definovan a jiz v nem neni
		// pokud neni, tak je jiz v pozadavku
		// nebo se poklada za form bez kontroly CSRF
		if (url.indexOf('csrf_token') == -1 && this.csrf_token.length > 0) {
			if (url.indexOf('?') == -1) {
				url += '?csrf_token=' + this.csrf_token;
			} else {
				url += '&csrf_token=' + this.csrf_token;
			}
		}
		// k pozadavku POST musime pridat token, pokud jiz v nem definovan neni
		if (method.toLowerCase() == 'post' && 
				content.indexOf('csrf_token') == -1 && this.csrf_token.length > 0) {
			if (content.length > 0) {
				content += '&csrf_token=' + this.csrf_token;
			} else {
				content += 'csrf_token=' + this.csrf_token;
			}
		}
		
		// otevri xmlhttp request, asynchronni
		this.xmlhttp.open(method, url, true);
		
		// pokud je uzivatelska funkce pro zpracovani requestu, zavolame ji
		this.xmlhttp.onreadystatechange = function() {
			var request_state = ajax.getReadyState();
			if (userFunction != null) {
				if (userFunctionArgument != null) {
					userFunction(ajax.getReadyState(request_state), userFunctionArgument);
				} else {
					userFunction(ajax.getReadyState(request_state));
				}
			}
			ajax.trySendRequest(request_state);
		};
		
		// pokud jsou stanovene hlavicky, odesleme je
		if (headers != null) {
			// headers je "asociativni pole", projedeme ho a pridame k xmlhttp requestu
			for (var key in headers) {
				this.xmlhttp.setRequestHeader(key, headers[key]);
			}
		} else {
			this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
			if (content != null) {
				this.xmlhttp.setRequestHeader('Content-Length', content.length);
			}
			this.xmlhttp.setRequestHeader('Connection', 'close');
		}
		
		// oznacime si jaky pozadavek prave zpracovavame
		this.active_request = url;
		
		// odesleme pozadavek s predanym obsahem
		this.xmlhttp.send(content);
		
		return true;
	},
	
	getReadyState : function(type) {
		// musi byt aktivni xmlhttp spojeni
		if (ajax.xmlhttp == null) {
			return false;
		}
		
		// vraci stav ajax requestu (lepsi nez default ciselne vyjadreni)
		if (type != 'number') {
			switch (ajax.xmlhttp.readyState) {
				case 0:
					return 'NOT_INITIALIZED';
				case 1:
					return 'INITIALIZED';
				case 2:
					return 'SENT';
				case 3:
					return 'IN_PROCESS';
				case 4:
					return 'COMPLETE';
				default:
					return 'UNDEFINED';
			}
		} else {
			return (ajax.xmlhttp.readyState);
		}
	}, 
	
	getStatusCode : function() {
		if (ajax.xmlhttp == null) {
			return false;
		}
		
		return ajax.xmlhttp.status;
	}, 
	
	getStatusText : function() {
		if (ajax.xmlhttp == null) {
			return false;
		}
		
		return ajax.xmlhttp.statusText;
	}, 
	
	getResponse : function(type) {
		if (this.xmlhttp == null) {
			return false;
		}
		// zda chceme odezvu v XML, nebo v textu
		if (type == 'xml') {
			return this.xmlhttp.responseXML;
		} else {
			// default text
			return this.xmlhttp.responseText;
		}
	}, 
	
	setToken : function(token) {
		this.csrf_token = token;
	}, 
	
	displayProgress : function(text) {
		// najdem odscrollovani
		var scrolledX, scrolledY;
		if ( window.pageYoffset ) {
			scrolledX = window.pageXoffset;
			scrolledY = window.pageYoffset;
		} else if( document.documentElement && document.documentElement.scrollTop ) {
			scrolledX = document.documentElement.scrollLeft;
			scrolledY = document.documentElement.scrollTop;
		} else if( document.body ) {
			scrolledX = document.body.scrollLeft;
			scrolledY = document.body.scrollTop;
		}
		
		// najdem stred
		var centerX, centerY;
		if ( window.innerHeight ) {
			centerX = window.innerWidth;
			centerY = window.innerHeight;
		} else if( document.documentElement && document.documentElement.clientHeight ) {
			centerX = document.documentElement.clientWidth;
			centerY = document.documentElement.clientHeight;
		} else if( document.body ) {
			centerX = document.body.clientWidth;
			centerY = document.body.clientHeight;
		}
		
		// vyska a sirka pro div s progress barem
		var Xwidth = 300;
		var Yheight = 50;
		
		// vypocteme offsety
		var leftoffset = scrolledX + (centerX - Xwidth) / 2;
		var topoffset = scrolledY + (centerY - Yheight) / 2;
		
		// vytvorime pruhledny container
		container = document.createElement('div');
		container.style.position = 'fixed';
		container.style.top = '0';
		container.style.left = '0';
		container.style.zIndex = '90';
		container.style.width = '100%';
		container.style.height = scrolledY + centerY + 'px';
		container.style.backgroundColor = '#000';
		container.style.filter = 'alpha(opacity=60)';
		container.style.MozOpacity = ' 0.6';
		container.style.opacity = '0.6';
		
		// vlozime div pro obrazek ktery je vycentrovany
		loading = document.createElement('div');
		loading.style.position = 'absolute';
		loading.style.width = Xwidth + 'px';
		loading.style.height = Yheight + 'px';
		// dle vysky okna klienta a dle scrollu
		loading.style.top = topoffset + 'px';
		loading.style.left = leftoffset + 'px';
		loading.style.textAlign = 'center';
		loading.style.zIndex = '100';
		loading.style.color = '#fff';
		loading.style.fontWeight = 'bold';
		// vlozime obrazek
		loading.innerHTML = '<img src="/js/loading.gif" alt="loading..." />';
		if (text != null && text.length > 0) {
			// pod obrazek vlozime pridany text
			loading.innerHTML += '<br /><span id="ajaxText">' + text + '</span>';
		}
		// pridame do containeru
		container.appendChild(loading);
		
		// container pridame k body
		if (document.getElementsByTagName('body').item(0) != null) {
			document.getElementsByTagName('body').item(0).appendChild(container);
		}
	}, 
	
	changeProgressText : function(text) {
		if (document.getElementById('ajaxText') != null && text != null && text.length > 0) {
			document.getElementById('ajaxText').innerHTML = text;
		}
	}, 
	
	hideProgress : function() {
		// odebereme container
		if (document.getElementsByTagName('body').item(0) != null) {
			document.getElementsByTagName('body').item(0).removeChild(container);
		}
	}
}
