
/**
 * _ptools.Ajax
 *
 * @author PCSG - Henning
 * @package com.pcsg.ptools.ajax
 * 
 * @copyright  2008 PCSG
 * @version    0.3 $Revision: 2672 $
 * @since      Class available since Release P.MS 0.1
 */

if (typeof _ptools == 'undefined') {
	var _ptools = {};
};
 
function ajax() { };

ajax.prototype.sync = function(php, params)
{
	var _AjaxSync = new _ptools.Ajax({
		'host'        : _ptools._System.getAttribute('host'),
		'name'        : '_ajax_get_products',
		'request_url' : _ptools._System.getAttribute('ajax')
	});
	
	var r = '';
	
	if (params)
	{
		var r = _AjaxSync.request(php, '', params);
	} else
	{
		var r = _AjaxSync.request(php);
	};
	
	_AjaxSync = null;
	delete _AjaxSync;
	
	return r;
};

ajax.prototype.syncPost = function(php, params)
{
	var _AjaxSync = new _ptools.Ajax({
		host        : _ptools._System.getAttribute('host'),
		name        : '_ajax_post_sync',
		request_url : _ptools._System.getAttribute('ajax'),
		type        : 'POST'
	});
	
	var r = '';
	
	if (params)
	{
		var r = _AjaxSync.request(php, '', params);
	} else
	{
		var r = _AjaxSync.request(php);
	};
	
	_AjaxSync = null;
	delete _AjaxSync;
	
	return r;
};

ajax.prototype.async = function(php, func, params)
{
	var _aAjax = new _ptools.Ajax({
		'host'        : _ptools._System.getAttribute('host'),
		'name'        : '_ajax_get_products',
		'request_url' : _ptools._System.getAttribute('ajax'),
		'func'        : func
	});
	
	if (params)
	{
		_aAjax.request(php, this.ExceptionCheckAsync, params);
		return;
	};
	
	_aAjax.request(php, this.ExceptionCheckAsync);
};

ajax.prototype.asyncPost = function(php, func, params)
{
	var System  = _ptools._System;
	var _params = params || {};
	
	_params.host = System.getAttribute('host');
	_params.name = '_ajax_post_async';
	_params.type = 'POST',
	_params.func = func;
	_params.request_url = System.getAttribute('ajax');
	
	var _aAjax = new _ptools.Ajax(_params);
	
	if (params)
	{
		_aAjax.request(php, this.ExceptionCheckAsync, params);
		return;
	};
	
	_aAjax.request(php, this.ExceptionCheckAsync);
};

ajax.prototype.ExceptionCheckAsync = function(result, AJAX)
{
	// Wenn kein Exception geworfen wurde
	if (typeof result.type == 'undefined' || 
		result.type != '_ptools::Exception') 
	{
		var f = AJAX.getAttribute('func');
		
		if (typeof f == 'function') 
		{
			f( result, AJAX );
			return;
		};
		
		eval(f + "( result, AJAX )");
		return;
	};
	
	// Wenn Exception geworfen UND onError deklatiert wurde
	if (typeof _ptools.onError == 'function') 
	{
		_ptools.onError( result );
		return;
	};
	
	// Wenn Exception geworfen aber keine User Funktion deklatiert wurde
	throw result;
};


_ptools.Ajax = function( settings )
{
	var t = this;
	var _settings = settings || {};
	
	t.http_request = false;
	
	t.name   = settings.name;
	t.type   = '_ptools::Ajax';
	t.params = [];
	
	t.getAttribute = function(name) 
	{
		if (_settings[name]) {
			return _settings[name];
		};
		
		return false;
	};
	
	t.setAttribute = function(name, value) 
	{
		_settings[name] = value;
	};
	
	t.getParams = function(name)
	{
		if (t.params[name]) {
			return t.params[name];
		};
		
		return false;
	};
	
	t.request_url = 'ajax_request.php';
	
	if (settings && settings.request_url) {
		t.request_url = settings.request_url;
	};
};

/**
 * Request verarbeiten
 */
_ptools.Ajax.prototype.request = function(phpFunction, jsFunction, params)
{
	var t     = this;
	var async = false;
	
	t.http_request = false;
	t.params       = params;
	
	if (jsFunction) // Asyncron
	{
		async = true;
		t.setAttribute('jsFunction', jsFunction);
	};
	
    if (window.XMLHttpRequest) 
    { // Mozilla, Safari,...
        t.http_request = new XMLHttpRequest();
        
        if (t.http_request.overrideMimeType) {
            t.http_request.overrideMimeType('text/xml');
        };
        
    } else if (window.ActiveXObject) 
    { // IE
        try 
        {
            t.http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) 
        {
            try 
            {
                t.http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {};
        };
    };

    if (!t.http_request) 
    {
        alert('XMLHTTP-Instanz konnt nicht erzeugt');
        return false;
    };

    if (async == true)
    {
	    var self = t; 
	    
		t.http_request.onreadystatechange = function() {
	    	self.result();
	    };
    };
   
    var request_host   = t.getAttribute('host') +  t.request_url;
    var request_string = "pcsg_rf=" + phpFunction;

    if (params)
    {
    	for (k in params)
    	{
    		if (typeof params[k] == 'undefined') {
    			continue;
    		};
    		
    		if (typeof params[k] == 'function') {
    			continue;
    		};
    		
    		if (typeof params[k].nodeName != 'undefined') {
    			continue;
    		};
    		
    		str2 = params[k].toString();
    		str2 = str2.replace(/\+/g, '%2B');
    		str2 = str2.replace(/\&/g, '%26');
    		str2 = str2.replace(/\'/g, '%27');
    		
    		request_string = request_string + "&" + k +"=" + str2;
    	};
    };

	if (t.http_request.overrideMimeType) {
		t.http_request.overrideMimeType('text/plain; charset=utf-8');
	};
		   
	if (t.getAttribute('type') == 'POST')
	{
		if (async == false) // syncron
	    {
		    var r = t.http_request.open('POST', request_host, false);
		    t.http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
		    t.http_request.send(request_string);
		    
		    return t.ajaxreturn(t.http_request.responseText);	
	    } else // asyncron
	    {
	   
	    	var r = t.http_request.open('POST', request_host, true);
		    t.http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
		    t.http_request.send(request_string);
	    };
	    
	} else
	{
	    if (async == false) // syncron
	    {
		    var r = t.http_request.open('GET', request_host+'?'+request_string, false);
		    t.http_request.send(null);
		    
		    return t.ajaxreturn(t.http_request.responseText);
	    } else // asyncron
	    {
	    	var r = t.http_request.open('GET', request_host+'?'+request_string, true);
		    t.http_request.send(null);
	    };
	};
};

/**
 * Resulat vom Request
 */
_ptools.Ajax.prototype.result = function()
{
	if (this.http_request.readyState != 4) {
		return;
	};
	
	if (this.http_request.status != 200) {
		return;
	};
		
	try
	{
		var l = this.http_request.responseText.length;
		var f = this.getAttribute('jsFunction');
		
		if (typeof f == 'function')
		{
			f( this.ajaxreturn(this.http_request.responseText), this);
			return true;
		};

		eval(f + "(this.ajaxreturn(this.http_request.responseText), this)");
		return true;
		
	} catch (e)
	{
		alert(e + "\n\n" + this.getAttribute('jsFunction') + "(this.ajaxreturn( this.http_request.responseText, true ))" + "\n\n" + this.ajaxreturn( this.http_request.responseText ));
	};
};

_ptools.Ajax.prototype.ajaxreturn = function(str)
{
	var len = str.length;
	var end = len-6;

	// Fehler abfangen
	if (str.substring(0, 6) == '<pcsg>' && str.substring(len-7, len) == '</pcsg>')
	{
		var result = eval('('+ str.substring(6, len-7) +')');

		// Hilfetexte
		if (result.message)
		{
			for (var i = 0, len = result.message.length; i < len; i++)
			{
				var m = result.message[i];

				_ptools._Helper.addNotice( 
					false,
					m.text,
					m.solution,
					m.docu
				);
			};

			_ptools._Helper.show();
		};

		if (result.ajax_result) {
			return result.ajax_result;
		};

		if (result.PException)
		// Fehlermeldungen abfangen
		{
			var message = result.PException.message ? result.PException.message : ''; 
			var code = result.PException.code ? result.PException.code : 404;

			if (code == 401 && 
				typeof _pcsg != 'undefined' && 
				_pcsg.Controls && 
				_pcsg.Controls.Login) {
				
				_pcsg.Controls.Login.open();
			};

			var _Exception = new _ptools.Exception(message, code);

			return _Exception;
		};

	} else
	{
		throw new _ptools.Exception('No PCSG XML', 404);
	};

	return false;
};

