var ludi_io = {};

ludi_io.cacheJSON = {};
ludi_io.offsetAtt =0;
ludi_io.allLanguages = [];
ludi_io.world = {};
ludi_io.world.items = [];
ludi_io.world.actions = [];
ludi_io.world.directions = [];
ludi_io.world.attributes = [];
ludi_io.world.attExceptions = [];

// to-do: must be dynamic

// ludi_io.readKernel (line 263 fails using file; must be http)
/*
document.URL o window.location.href (según si versión basic local o via http):
"file:///D:/Privado/Google%20Drive/nodejs/ludi/index.html"
"https://52f6acce2437378c9b940c454b1d1459c14354a7.googledrive.com/host/0B86brYRxx_nMQjJRRTJ4QkFvTzA/index.html"

var pathArray = window.location.pathname.split( '/' );

var newPathname = "";
for (i = 0; i < pathArray.length-1; i++) {
  newPathname += "/";
  newPathname += pathArray[i];
}

//ludi_io.xmlBasePath_basic = document.URL + 'client/data/';
//ludi_io.xmlBasePath_basic =  window.location.protocol + '//' + window.location.host + newPathname + '/client/data/';
// window.location.host = "" / "52f6acce2437378c9b940c454b1d1459c14354a7.googledrive.com"
// window.location.protocol "file:" / "https:"
// window.location.pathname "/D:/Privado/Google%20Drive/nodejs/ludi/index.html" / "/host/0B86brYRxx_nMQjJRRTJ4QkFvTzA/index.html"

*/

ludi_io.xmlBasePath_basic =  'https://googledrive.com/host/0B86brYRxx_nMQjJRRTJ4QkFvTzA/client/data/';
ludi_io.xmlBasePath = '';

ludi_io.kernelMessages = [];

ludi_io.initialization = function() {

	ludi_io.offsetAtt = 0;
	
	ludi_io.world = {};
	ludi_io.world.items = [];
	ludi_io.world.actions = [];
	ludi_io.world.directions = [];
	ludi_io.world.attributes = [];
	ludi_io.world.attExceptions = [];
	
	if (typeof socket !== "undefined") 
		ludi_io.xmlBasePath = './client/data/';
	else if  (document.URL.substr(0, 4) == "http") 
		ludi_io.xmlBasePath = './client/data/';
	else
		ludi_io.xmlBasePath = ludi_io.xmlBasePath_basic;

}

ludi_io.exportWorld = function() {
	
	return {
		items: ludi_io.world.items.slice(), 
		actions: ludi_io.world.actions.slice(), 
		directions: ludi_io.world.directions.slice(), 
		attributes: ludi_io.world.attributes.slice(),
		attExceptions: ludi_io.world.attExceptions.slice()
	};
	
}
 
ludi_io.freeMem = function() {
	ludi_io.cacheJSON = {};
	ludi_io.offsetAtt =0;
	ludi_io.allLanguages = [];
	ludi_io.world = {};
	ludi_io.world.items = [];
	ludi_io.world.actions = [];
	ludi_io.world.directions = [];
	ludi_io.world.attributes = [];
	ludi_io.world.attExceptions = [];
	ludi_io.kernelMessages = [];
}

ludi_io.load1JSON = function(fileName, flag) {

	ludi_io.debugMsg = document.URL + "|" + ludi_io.xmlBasePath + fileName;
	flag.loaded = false;
	flag.data = null;
	$.ajax({
		url:  ludi_io.xmlBasePath + fileName,
		async: true,
		dataType: 'json',
		success: function (response) {
			flag.loaded = true;
			flag.data = response;
		},

		timeout:   function (response) {
			console.log("timeout load1JSON " + ludi_io.xmlBasePath + fileName  );
			ludi_io.debugMsg = "timeout load1JSON " + ludi_io.xmlBasePath + fileName ;
		},
		error:   function (response) {
			console.log("error load1JSON " + ludi_io.xmlBasePath + fileName );
			ludi_io.debugMsg = "timeout load1JSON " + ludi_io.xmlBasePath + fileName ;
		}
	});
}

ludi_io.loadKernelData = function () {
	
	var fileNames = [];
	
	for (var ilan =0; ilan < ludi_io.language.length; ilan++) {
		if (ludi_io.language[ilan].toLoad_Kernel && !ludi_io.language[ilan].kernelLoaded) {
			fileNames.push ("kernel/kernel"+ludi_io.language[ilan].code+".json");
		}
	}
	ludi_io.multiLoadJSON (fileNames, "multiLoadJSON_Kernel_OK", "multiLoadJSON_Kernel_Error");

}

ludi_io.multiLoadJSON = function (fileNames, funOK, funError) {
	
	ludi_io.flags = [];
	for (var i=0;i<fileNames.length;i++) {
		ludi_io.flags[i]= {loaded:false};
	}

	for (var i=0;i<fileNames.length;i++) {
		if (fileNames[i] != 'skip') // tricky
			ludi_io.load1JSON (fileNames[i], ludi_io.flags[i]);
		else
			ludi_io.flags[i]= {loaded:true};	
	}

	var myTimeout = setTimeout(function () {
		
		var isError = false;

		for (var i=0;i<fileNames.length;i++) {
			if (!ludi_io.flags[i].loaded) {
				isError = true;
				break;
			}
		}

		// clear all intervals
		for (var i = 1; i < 99999; i++)  window.clearInterval(i);
		
		if (isError) ludi_routing[funError](fileNames);
		else ludi_routing[funOK](fileNames);
		
	}, 15000);

	var myInterval = setInterval(	function() { 
		for (var i=0;i<fileNames.length;i++) {
			if (!ludi_io.flags[i].loaded) return;
		}
		clearInterval(myInterval); 
		clearTimeout(myTimeout); 
		ludi_routing[funOK](fileNames);
	}, 500);
	
}


// append game items to lib items
ludi_io.mixingItems = function(tableIn) {
	ludi_io.world.items = ludi_io.world.items.concat (tableIn);
}

// append game actions to lib actions
ludi_io.mixingActions = function(tableIn) {
	ludi_io.world.actions = ludi_io.world.actions.concat (tableIn);
}

// append game directions to lib directions
ludi_io.mixingDirections = function(tableIn) {
	ludi_io.world.directions = ludi_io.world.directions.concat (tableIn);
}

// mix game attributes to lib attributes
ludi_io.mixingAttributes = function(tableIn) {
	// if lib att already exist, it must be overwritten
	ludi_io.world.attributes = ludi_io.world.attributes.concat (tableIn);
	var pos;
	for (var i=0; i<tableIn.length;i++) {
		pos = arrayObjectIndexOf(ludi_io.world.attributes, "id", tableIn[i].id);
		if (pos >=0) { // att def replaced
			ludi_io.world.attributes[pos] = tableIn[i];
		}
	}
}

// append game items to lib items
ludi_io.mixingAttExceptions = function(tableIn) {
	if (typeof ludi_io.world.attExceptions == 'undefined') 
		ludi_io.world.attExceptions = [];
	if (typeof tableIn != 'undefined') 
		ludi_io.world.attExceptions = ludi_io.world.attExceptions.concat (tableIn);	
}



/* dynamic code load 

use:  ludi_io.loadjscssfile("module.js, 	function_after_load); 

*/
ludi_io.loadjscssfile = function (filename, callback) {
    var fileref = document.createElement('script');
    fileref.onreadystatechange = fileref.onload = function () {

        var state = fileref.readyState;

        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filename);

	// it adds <script type="text/javascript" src="./client/data/games/gamename/game_reactions.js"></script>
    if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);

}


