	

function SystemRequest()
{
	
}

SystemRequest.responseMessagesHandler = null;

/**
 * 
 * @param module
 * @param method
 * @param parameters
 * @param callback
 * @param gateway optional
 * @return
 */
SystemRequest.load	= function(module, method, parameters, callback,context, gateway, crossDomainGateway_)
{
	var req					= new Request();
	req.setContext(context);
	req.gateway				= gateway ? gateway : SystemRequest.gateway;
	req.crossdomainGateway 	= crossDomainGateway_ != undefined ? crossDomainGateway_ : "";
	
	req.load(module, method, parameters, callback);
	
	return req;
}


SystemRequest.loadCrossDomain	= function(module, method, parameters, callback, context, crossDomainGateway)
{
	var req					= new Request();
	req.setContext(context);
	req.gateway				= SystemRequest.gateway;
	req.crossdomainGateway 	= crossDomainGateway;
	req.crossdomain			= true;
	
	req.load(module, method, parameters, callback);
	
	return req;
}


SystemRequest.loadExternal = function(url,handler)
{
	$.ajax({url:url,dataType:"jsonp",success:handler});
}

SystemRequest.gateway	= SystemCore.MODULES_GATEWAY;


SystemRequest.loadCustom	= function(gateway, module, method, parameters, callback,context)
{
	var req			= new Request();
	req.setContext(context);
	req.gateway		= gateway;
	req.load(module, method, parameters, callback);
	return req;
};


SystemRequest.handleResponseMessages = function(response)
{
	var str = "";	
	
	var errorMessagesExist = false;
	
	if (response.messages && response.messages.length > 0)
	{
		for (i in response.messages)
		{
			if (response.messages[i]['title'] == "Error" || response.messages[i]['title'] == "Eroare" || response.messages[i]['title'] == "")
			{
				errorMessagesExist = true;
			}
			str += "<p>"+response.messages[i]['text']+"</p>";
		}
	}
	
	if (response.errors && response.errors.length > 0)
	{
		for (i in response.errors)
		{
			str += response.errors[i]['text']+"<br /><br />";
		}
	}
	
	if (str.length > 0)
	{
		if (SystemRequest.responseMessagesHandler != null)
		{
			SystemRequest.responseMessagesHandler(!errorMessagesExist, str);
		}
		else
		{
			$("<div>"+str+"</div>").dialog({
				modal: true,
				title: errorMessagesExist == true ? "Eroare" : "Succes",
				width: 400,
				buttons: {
					Ok: function() {
						$( this ).dialog( "close" );
					}
				}
			});
		}
	}
}


function testFunction(response)
{
	console.log(response);
}

/**
 * Request class
 * Uses gateway defined in core
 * @return
 */





function Request()
{
	var self				= this;
	this.gateway			= '';
	this.crossdomainGateway;
	
	var context;
	
	this.setContext	= function(cntx)
	{
		context	= cntx ? cntx : this;
	};
	
	
	this.load	= function(module, method, parameters, callback, errorCallBack)
	{		
		if (this.gateway == '') // Request.gateway
		{
			alert("No gateway defined");
			return false;
		}
		var jsonType	= "json";
		
		$(document.body).css("cursor","progress");
		$.ajax({
			url: this.gateway,
			type:"post",
			processData: true,
			data: { 
				'params':parameters,
				'class':module,
				'module':module,
				'language':SystemRequest.language,
				'crossdomain':this.crossdomainGateway ? "1" : "0",
				'crossdomainGateway':this.crossdomainGateway,
				method:method
			},
			success: function(obj) 
			{
				var response;
				if (obj!=null)
				{
					response = new RequestResponse(obj["data"]!==false ? obj["data"] : {}, obj["success"] ? obj["success"] : false, obj['messages'], obj['errors']);
					console.log(obj);
				}
				else
				{
					response = new RequestResponse({}, false);
				}
				
				$(document.body).css("cursor","");
				SystemRequest.handleResponseMessages(response);
				if (callback != null && callback != undefined)
				{
					callback.apply(context,[response]);
				}
			}, 
			error:function(req, textStatus, errorThrown)
			{ 
				$(document.body).css("cursor","");
				//try{console.log("REQ_ERROR - status:" + textStatus + " error:" + errorThrown); }	catch(err){// console.log not supported}
			}, 
			dataType: jsonType
		});	
	}
	
}


function RequestResponse(data, success, messages,errors)
{
	this.success 	= success;
	this.data 		= data;
	this.messages 	= messages;
	this.errors	 	= errors;
}


function KeepAliveOperation(module, method, params, jsHandler)
{
	this.module			= module;
	this.method			= method;
	this.params			= params;
	this.jsHandler		= jsHandler;
}


function SystemManager()
{
}

SystemManager.listeners		= [];

SystemManager.init	= function()
{
	$(document).click(SystemManager.dispatchEvent);
}

SystemManager.dispatchEvent	= function(event)
{
	var len	= SystemManager.listeners.length;
	var refFnc;
	for (i=0;i<len; i++)
	{
		refFnc	= SystemManager.listeners[i];
		if (refFnc)
		{
			refFnc(event);
		}
	}
}

SystemManager.addListener	= function( refFunction )
{
	SystemManager.listeners.push(refFunction);
}

SystemManager.removeListener	= function( refFunction )
{
	// remove from SystemManager.listeners
}


$(document).ready(function(){
	SystemManager.init();
});


SystemRequest.keepAlives 				= [];
SystemRequest.keepAliveAlreadyStarted 	= false;

SystemRequest.keepAliveInterval;

SystemRequest.enableKeepAlive = function()
{
	if (SystemRequest.keepAlives && SystemRequest.keepAlives.length > 0 && !SystemRequest.keepAliveAlreadyStarted)
	{
		SystemRequest.keepAliveInterval = setInterval(function() {
			SystemRequest.load('KeepAlive','executeOperations',[SystemRequest.keepAlives], SystemRequest.keepAliveResponseHandler);
		}, SystemCore.KEEP_ALIVE_TIME);
		
		SystemRequest.keepAliveAlreadyStarted = true;
	}
}


SystemRequest.resetKeepAlive = function()
{
	clearInterval(SystemRequest.keepAliveInterval);
	SystemRequest.keepAliveAlreadyStarted = false;
	SystemRequest.enableKeepAlive();
}

SystemRequest.registerKeepAlive = function(module, method, params, jsHandler)
{
	var op = {operation:module+"."+method, params:params, jsHandler:jsHandler};
	SystemRequest.keepAlives.push(op);
	
	SystemRequest.enableKeepAlive();
	
}

SystemRequest.keepAliveResponseHandler = function(response)
{
	if (SystemRequest.keepAlives && SystemRequest.keepAlives.length > 0)
	{
		var i=0;
		var functParts;
		for (i=0; i<SystemRequest.keepAlives.length; i++)
		{
			for (key in response.data)
			{
				if (SystemRequest.keepAlives[i].operation == key)
				{
					functParts	= SystemRequest.keepAlives[i].jsHandler.split(".");
					if (functParts.length == 2)
					{
						// OBJ CONTEXT
						window[functParts[0]][functParts[1]](response.data[key]);
					}
					else
					{
						// GLOBAL
						window[SystemRequest.keepAlives[i].jsHandler](response.data[key]);
					}
					break;
				}
			}
		}
	}
}



