/**
 * Project:     aimscore - All Information Management System core
 * File:        core.js
 *
 * see aimscore.php for licence informations
 *
 * @copyright 2007-2009 Andrej Zieger
 * @author Andrej Zieger <andrej@ziegers.net>
 */

if (typeof aimscore=="undefined"){
	 // dont load core.js twice

	function isArray(a) {
	    return isObject(a) && a.constructor == Array;
	}

	function isObject(a) {
		
	    return (a && typeof a == 'object') || isFunction(a);; 
	}

	function isFunction(a) {
	    return typeof a == 'function';
	}
	
	function isNumber(a) {
	    return typeof a == 'number' && isFinite(a);
	}
	
	function isString(a) {
    		return typeof a == 'string';
	}

	var debugbuild = true;
	var debugrow = 0;
	function debug(text){
		if(!debugbuild)
			return;
		theTime = new Date().getTime();

		if(document.getElementById("debug")){ 
			document.getElementById("debug").appendChild(document.createTextNode(debugrow+" at "+theTime+": "+ text));
			document.getElementById("debug").appendChild(document.createElement("br"));
		}
			//document.getElementById("debug").innerHTML += debugrow+" at "+theTime+": "+ text + "<br>";
		debugrow++;
	}


var aimscore = new Object();

aimscore.output = function(msg){ 
	var output = $("output");
	output = output.lastChild;
	var li = gui.createElementTo("li",output,null,output.firstChild);
	gui.createTextNodeTo(msg,li);
}

aimscore.isParentOfCaller = function(e,caller,tagName){
	var tg = (e.srcElement) ? e.srcElement : e.target;
	
	
	while(tg.tagName != tagName) {
		if(tg == document) return true;
		tg = tg.parentNode;
	}
		
	if(tg != caller)
		return true;
	
}

/**
	Loads a .js file dynamicly on runtime
**/
aimscore.loadjs = function(file){
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.setAttribute("src", file);
  document.getElementByTagName("head")[0].appendChild(script);
}

/**
	Checks if this script belongs to core scripts
	If it does, give the base absolute url back
**/
aimscore.checkBase = function(script){
	if (script.src && /system\/js\/(core|gui|net|windows).js/.test(script.src)) {
		baseURL = script.src.substring(0, script.src.lastIndexOf('/'));
		url = baseURL.replace('http://','');
		url = url.substring(url.indexOf('/'));
		return url;
	}
	else 
		return null;
}

aimscore.init = function(){
		// Check document
		nl = document.getElementsByTagName('script');
		for (i=0; i<nl.length; i++) {
			if (url = aimscore.checkBase(nl[i])){
				//URL to HomePath
				aimscore.homePath = url.substring(0,url.lastIndexOf('system/js'));
				break;
			}
		}
}

aimscore.pathfinder = new Object();
aimscore.pathfinder.instance = false;

aimscore.pathfinder.show = function(target,filter){
	this.init(filter);

	this.instance.setTarget(target);
	this.instance.show();
}

aimscore.pathfinder.init = function(filter){
	this.instance = new aimscore.pathfinder.cPath(filter);
	this.instance.load();
}


/**
 * The Pathfindertool
 * @param filter - Sets the Filter for Files. Will show only files matching the filters regular expression.
 * 					"DIR:expression" will show only folders, "FILES:expression" will allow only File selects and
 * 					will only show Files matching expression and folders.
 */
aimscore.pathfinder.cPath = function(filter){	
	
	// read Filter
	var onlyDir = false;
	var onlyFileSelect = false;
	var fileFilter = ".*";
	if(typeof filter != "undefined"){
		if(filter.match(/DIR:.*/)){
			onlyDir = true;
		}
		if(filter.match(/FILES:.*/)){
			filter = filter.replace(/FILES:/,"");
			onlyFileSelect = true;
		}
		fileFilter = filter;
	}
	
	var instance = this;
	var container = document.createElement("div");
	var addressBar = gui.createElementTo("input",container);
	var foldersView = gui.createElementTo("div",container);
	var contentView = gui.createElementTo("div",container);
	var controllView= gui.createElementTo("div",container);
	
	var progressBar = gui.createElementTo("div",contentView);
	
	container.className	  = "pathFinder";
	addressBar.className  = "addressBar";
	foldersView.className = "folderTreeView";
	contentView.className = "contentView";
	controllView.className= "controllView";
	
	progressBar.className = "progressbar";
	progressBar.innerHTML = "Loading...";
	
	//Adressbar
	addressBar.type = "text";
	
	//Controll content
	
	var newFolder = gui.createElementTo("input",controllView);
	newFolder.type = "button";
	newFolder.value= "Neuer Ordner";
	newFolder.style.cssFloat = "left";
	
	var newFile = gui.createElementTo("input",controllView);
	newFile.type = "button";
	newFile.value= "Neue Datei";
	newFile.style.cssFloat = "left";
	if(onlyDir){
		controllView.removeChild(newFile);
	}
	
	var okay = gui.createElementTo("input",controllView);
	okay.type = "button";
	okay.value = "Auswählen";
	
	var cancel = gui.createElementTo("input",controllView);
	cancel.type = "button";
	cancel.value = "Abbrechen";
	

	cancel.onclick = function(){ instance.destroy()};
	okay.onclick = function() { instance.onOkay();};
	newFolder.onclick = function() { instance.onNewFolder();};
	newFile.onclick = function() { instance.onNewFile();};
	
	var wnd = new gui.cWindow(container,document.body,"Path Finder");
	
	wnd.setHeight("300px");
	wnd.setWidth("600px");
	wnd.setPosition("200px","200px");
	
	var targetObj = null;
	

	
	function addItem(name,target){
		var item = gui.createElementTo("div",target);
		var img  = gui.createElementTo("div",item);
		var title= gui.createElementTo("p",item);
		
		item.className = "item";
		img.className = "img";
		title.innerHTML = name;

		return item;
	}
	
	this.content = new Object();
	this.content.parent = this;
	this.content.loadedFolder = false;
	this.content.selectedItem = false;
	
	this.content.cItem = function(name,path,item){
		this.name = name;
		this.path = path;
		this.item = item;
		return this;
	}
	
	this.content.addFile = function(name){
		var item = addItem(name,contentView);
		var citem = new this.cItem(name,this.loadedFolder.path+name,item);
		item.className += " file";
		
		var inst = this;
		item.onclick = function(e){
			inst.select(citem,this);
		}
		
		return item;
	}
	
	this.content.addFolder=function(folder){
		var item = addItem(folder.name,contentView);
		item.className += " folder";
		var inst = this;
		item.onclick = function(e){
			inst.select(folder,this);
		}
		item.ondblclick = function(e){ 
					aimscore.config.toggleClassName(folder.item,"open");
					inst.load(folder);
					};
		
		return item;
	}
	
	
	this.content.load = function(folder){
		this.clear();
		this.loadedFolder = folder;
		
		this.select(null);
		
		for(var i = 0; i < folder.childs.length; i++){
			var item = this.addFolder(folder.childs[i]);
		}
		if(!onlyDir)
			for(var i = 0; i < folder.files.length; i++){
				if(folder.files[i].match(fileFilter))
					this.addFile(folder.files[i]);
			}
	}

	this.content.clear = function(){
		gui.removeChilds(contentView);
	}
	//item must be an citem or folder
	this.content.select = function(item,obj){
		if(onlyFileSelect && ((typeof item == "undefined")||(item == null)||(typeof item.childs != "undefined"))){
			return;
		}
		
		addressBar.value = this.loadedFolder.path;
		if(item != null)
			addressBar.value += item.name;
		if(this.selectedItem != null)
			aimscore.config.toggleClassName(this.selectedItem.contentItem,"selected");
		this.selectedItem = (item == null) ? this.loadedFolder : item;
		aimscore.config.toggleClassName(obj,"selected");
		this.selectedItem.contentItem = obj;
	}
	
	this.folderTree = new Object();
	this.folderTree.parent = this;
	this.folderTree.addFolder = function(folder,parent){
		if(parent == null)
			parent = foldersView;
		var item = addItem(folder.name,parent);
		item.className += " folder";
		
		var inst = this;
		item.onclick = function(e){
					if(aimscore.isParentOfCaller(e,this,"DIV"))
						return;
					
					inst.parent.content.load(folder);
					};
		item.ondblclick = function(e){
					if(!aimscore.isParentOfCaller(e, this, "DIV")) 
						aimscore.config.toggleClassName(this,"open");
					return false;
					};
		item.onmouseover = function(e){
					document.onmousedown = function(){return false};
					};
		
		item.onmouseout = function(e){
						document.onmousedown = function(){return true};
					};
		item.firstChild.onclick = function(e){
				if(!aimscore.isParentOfCaller(e, this, "DIV")) 
					aimscore.config.toggleClassName(this.parentNode,"open");
				return false;
				};
				
		folder.item = item;
		return item;
	}
	
	this.folderTree.load = function(folder,parent){
		var item = this.addFolder(folder,parent);
			
		if(parent == null)
			item.className += " open";
		
		for(var i = 0; i < folder.childs.length; i++){
			this.load(folder.childs[i],item);
		}
	}
	
	this.show = function(){
		wnd.show();
	}
	
	
	this.setTarget = function(target){
		targetObj = target;
	}
	
	this.getTarget = function(){
		return targetObj;
	}
	
	this.load = function(){
		//contentView
		
		var data = new Object();
		var i = aimscore.ajax.cmd("core","pathfinder.ajax.php","folder.list",data,aimscore.ajax.progress);
		var inst = this;
		aimscore.ajax.request[i].callback = function(){inst.progress(response)};
	}
	
	this.progress = function(response){
		var folder = response.folder;
		this.folderTree.load(folder,null);
		this.content.load(folder);
	}
	
	this.getSelectedItem = function(){
		return this.content.selectedItem;
	}
	
	this.getPath = function(){
		return addressBar.value;
	}
	
	this.destroy = function(){
		wnd.destroy();
	}
	
	this.onOkay = function(e){
		if(is_function(targetObj)){
			targetObj(this);
		}else{
			targetObj.value = this.getPath();
		}
		this.destroy();
	}
	
	this.onNewFolder = function(){
		var spec = {
				titlebar:true,
				resize:false,
				minimize:false,
				drag:false,
				type: gui.WND_OK
			}
		var input = document.createElement("input");
		
		var dlg = new gui.cWindow(input,container,"Neuer Ordner",null,spec);
		dlg.setHeight("100px");
		dlg.setWidth("200px");
		dlg.setPosition("50px","50px");
		
		dlg.onok = function(){ instance.newFolder(input.value); dlg.destroy();};
		input.focus();
	}
	
	this.newFolder = function(name){
		if(name == "") return;
		var folder = new this.content.cItem(name, this.content.loadedFolder.path+name+"/", null);
		folder.childs = new Array();
		folder.files = new Array();
		this.folderTree.addFolder(folder, this.content.loadedFolder.item);
		this.content.addFolder(folder);
		this.content.loadedFolder.childs.push(folder);
	}
	
	this.onNewFile = function(){
		var spec = {
				titlebar:true,
				resize:false,
				minimize:false,
				drag:false,
				type: gui.WND_OK
			}
		var input = document.createElement("input");
		
		var dlg = new gui.cWindow(input,container,"Neue Datei",null,spec);
		dlg.setHeight("50px");
		dlg.setWidth("200px");
		dlg.setPosition("50px","50px");
		
		dlg.onok = function(){ instance.newFile(input.value); dlg.destroy();};
		input.focus();
	}
	
	this.newFile = function(name){
		if(name == "") return;
		this.content.addFile(name);
		this.content.loadedFolder.files.push(name);
	}
	
	return this;
}


aimscore.ajax = new Object();
aimscore.ajax.request = new Array();

aimscore.ajax.progress = function(){
	if(!this.ajax)
		return;
	try {
 	 	response = eval("("+this.ajax.responseText+")");
 	 //	respoDIR:expressionnse =this.ajax.responseText;
	} catch(error) {
		debug(decodeURIComponent("Error. Return:"+this.ajax.responseText));
	} finally {
		if(this.callback)
			this.callback(response);
	}
}

aimscore.ajax.escape = function(obj){
	if(isFunction(obj))
		return;
	if(isArray(obj)||isObject(obj)){
		for(var key in obj){
			obj[key] = aimscore.ajax.escape(obj[key]);
		}
	}else{
		return encodeURIComponent(obj);
	}
	
	return obj;
}

aimscore.ajax.cmd = function(module,file,request,data,callback){
	url = aimscore.homePath+"system/"+module+"/ajax/"+file;
	onload = callback;

	post = "&request="+request+"&data="+Object.toJSON(aimscore.ajax.escape(data));

	var ongather = null;
	var onerror = function(){
		if(typeof debug != "undefined") 
			debug("error fetching data! Status:"+this.ajax.status);
		else
			alert("error fetching data! Status:"+this.ajax.status+" \nurl:"+url);
	};
	var i = aimscore.ajax.request.length;

	aimscore.ajax.request[i] = new net.postRequest(url,onload,post,ongather,onerror);
	aimscore.ajax.request[i].nr = i;

	return i;
}

aimscore.onload = new Object();
aimscore.onload.functions = new Array();
aimscore.onload.old = window.onload;

aimscore.onload.add = function(func){
	aimscore.onload.functions.push(func);
}

aimscore.onload.load = function(e){
	var e = (window.event) ? window.event : e;
	for(var i = 0; i < aimscore.onload.functions.length;i++){
		aimscore.onload.functions[i].call(this,e);
	}
}

if(aimscore.onload.old)
	aimscore.onload.add(aimscore.onload.old);
window.onload = aimscore.onload.load;


aimscore.config = new Object();
aimscore.config.core  = new Object();

aimscore.config.findParent= function(obj,type,className){
	var found = false;
	obj = obj.firstChild;
	do{
		obj = obj.parentNode;
		
		if(obj == document) return false;
		found = true;
		if(type&&obj.tagName.toLowerCase !=type.toLowerCase)
			found = false;
		if(className&&obj.className.indexOf(className) == -1)
			found = false;
	}while(!found);
	return obj;
}

aimscore.config.toggleClassName = function(obj,className){
	if(!obj)
		return false;
	if(obj.className.indexOf(className)!=-1)
		obj.className = obj.className.replace(className,'');
	else
		obj.className += " "+className;
	
	return (obj.className.indexOf(className)!=-1);
}


aimscore.config.toggleValue = function(obj,value,limiter){
	if(obj.value == value)
		obj.value = "";
	else if(limiter != "") 
		if(obj.value.indexOf(value)==0)
			obj.value = obj.value.replace(value+limiter,'');
		else if(obj.value.indexOf(value)>0)
			obj.value = obj.value.replace(limiter+value,'');
		else if(obj.value != "")
			obj.value += limiter+value;
		else
			obj.value = value;
	else
		obj.value = value;
}

aimscore.config.minimize = function(obj,type,className,e){
	obj = aimscore.config.findParent(obj,type,className);
	
	return aimscore.config.toggleClassName(obj,"minimized");
}

aimscore.config.extend = function(obj,type,className,e){
	obj = aimscore.config.findParent(obj,type,className);
	
	return aimscore.config.toggleClassName(obj,"extended");
}

aimscore.config.select = function(obj,type,className){
	obj = aimscore.config.findParent(obj,type,className);
	
	return aimscore.config.toggleClassName(obj,"selected");
	
}






aimscore.config.core.pages = new Object();
aimscore.config.core.pages.newPage = new Object();

aimscore.config.core.pages.newPage.selectEntry = function(obj){
	var selected = aimscore.config.select(obj);
	var list = aimscore.config.findParent(obj,"ul","aimscore_menuetree");
	var input = list.previousSibling;
	aimscore.config.toggleValue(input,obj.firstChild.value,",");
	if(selected && (input.value.indexOf(obj.firstChild.value)==-1))
		aimscore.config.toggleValue(input,obj.firstChild.value,",");

}

aimscore.config.core.pages.mce = new Object();

aimscore.config.core.pages.mce.loadImageGallery = function(obj,search){
	//homePath = "../../../../../..";
	var data = {"search":search};
	
	aimscore.homePath = window.opener.aimscore.homePath; // Hack because its a seperate window -.-
	var i = aimscore.ajax.cmd("core","gallery.ajax.php","gallery.list",data,aimscore.ajax.progress);
	aimscore.ajax.request[i].callback = aimscore.config.core.pages.mce.progress;
	aimscore.ajax.request[i].obj = obj;
}

aimscore.config.core.pages.mce.progress = function(response){
//	alert(this.obj);
	obj = this.obj;
	gui.removeChilds(obj);
	var images = response.images;
	for(var i = 0; i < images.length; i++){
		var img = gui.createElementTo("img",obj);
		img.src = images[i];
		img.alt = images[i];
		img.onclick = function(e){
							var par = this.parentNode;
							for(var i = 0; i < par.childNodes.length; i++){
								par.childNodes[i].className = "";
							}
							this.className = 'selected';
							$("src").value = this.alt;
					};
	}
}

aimscore.config.core.areas = new Object();
aimscore.config.core.areas.newArea = new Object();

aimscore.config.core.areas.newArea.selectEntry = function(obj){
	var selected = aimscore.config.select(obj);
	var list = aimscore.config.findParent(obj,"ul","aimscore_menuetree");
	if(selected){
		
		var nodes = list.getElementsByTagName("div");
		for(var i = 0; i < nodes.length;i++)
		{
			if(nodes[i] != obj)
				while(aimscore.config.select(nodes[i]));
		}
		
	}	
	var input = list.previousSibling;
	
	aimscore.config.toggleValue(input,obj.firstChild.value,"");
	if(selected && (input.value.indexOf(obj.firstChild.value)==-1))
		aimscore.config.toggleValue(input,obj.firstChild.value,"");

}

aimscore.config.core.menue = new Object();
aimscore.config.core.menue.currentObject = null;
aimscore.config.core.menue.mouse = null;

aimscore.config.core.menue.onload = function(e){
	/*
	 var e = (window.event) ? window.event : e;
	
	var tg = (window.event) ? e.srcElement : e.target;

	if(!(tg.parentNode.parentNode == this))
		return;
	 */
	
	var parent = $("aimscore_menue_priority");
	var lis = parent.getElementsByTagName("li");
	for (var i = 0; i < lis.length; i++) {
		if (lis[i].className.indexOf("area") == -1) {
			Event.observe(lis[i], "click", aimscore.config.core.menue.onclick);
			Event.observe(lis[i], "mousedown", aimscore.config.core.menue.onmousedown);
			Event.observe(lis[i], "mouseover", aimscore.config.core.menue.onmouseover);
			Event.observe(lis[i], "mouseout", aimscore.config.core.menue.onmouseout);
		}
		
	}
	
	var div = aimscore.config.core.menue.mouse = gui.createElementTo("ul",document.body);
	div.style.position = "absolute";
	div.style.zIndex = "1000";
	div.style.border = "solid 1px black";
	div.style.padding = "10px";
	div.style.margin = "10px";
	div.className = "aimscore_menuetree";
	
	//new Effect.Opacity(div, { from: 1.0 , to: 0.9, duration: 0.0 });
	
	Event.observe(window,"mousemove",aimscore.config.core.menue.mousemove);
	Event.observe(window,"mouseup",aimscore.config.core.menue.onmouseup);
	//document.onmousedown = function(){return false;};
}


aimscore.config.core.menue.oldDocumentMouseDown;
aimscore.config.core.menue.onmouseover = function(e){
	var tg = (e.srcElement) ? e.srcElement : e.target;

	if(tg.className.indexOf("toggleopen") != -1) return;

	while(tg.tagName != "LI") {
		if(tg == document) return;
		tg = tg.parentNode;
	}
	
	if(!(tg == this))
		return;
	aimscore.config.core.menue.oldDocumentMouseDown = document.onmousedown;
	document.onmousedown = function(){return false;};
}

aimscore.config.core.menue.onmouseout = function(e){
	var tg = (e.srcElement) ? e.srcElement : e.target;

	if(tg.className.indexOf("toggleopen") != -1) return;

	while(tg.tagName != "LI") {
		if(tg == document) return;
		tg = tg.parentNode;
	}
	
	if(!(tg == this))
		return;
	document.onmousedown = aimscore.config.core.menue.oldDocumentMouseDown;
	
}

aimscore.config.core.menue.onclick = function(e){
	
	var tg = (e.srcElement) ? e.srcElement : e.target;

	if(tg.className.indexOf("toggleopen") != -1) return;

	while(tg.tagName != "LI") {
		if(tg == document) return;
		tg = tg.parentNode;
	}
	
	if(!(tg == this))
		return;
}

aimscore.config.core.menue.onmousedown = function(e){
	
	var tg = (e.srcElement) ? e.srcElement : e.target;

	if(tg.className.indexOf("toggleopen") != -1) return;

	while(tg.tagName != "LI") {
		if(tg == document) return;
		tg = tg.parentNode;
	}
	
	if(!(tg == this))
		return;
	
	aimscore.config.core.menue.currentObject = this;
	gui.cloneNodeTo(this,aimscore.config.core.menue.mouse);
}

aimscore.config.core.menue.onmouseup = function(e){
	
	gui.removeChilds(aimscore.config.core.menue.mouse);
	
	var tg = (e.srcElement) ? e.srcElement : e.target;

	if(tg.className.indexOf("toggleopen") != -1) return;

	while(tg.tagName != "LI") {
		if(tg == document) return;
		tg = tg.parentNode;
	}
	
	if(tg == this)
		return;
		
	aimscore.config.core.menue.drop(tg);
}

aimscore.config.core.menue.mousemove = function(e){
		var xPos = (e.clientX) ? e.clientX : e.pageX;
		var yPos = (e.clientY) ? e.clientY : e.pageY;
		
		var div = aimscore.config.core.menue.mouse;
		div.style.left = xPos+"px";
		div.style.top = yPos+"px";
}

aimscore.config.core.menue.drop = function(tg){
		if(!aimscore.config.core.menue.currentObject) return;	
	if((aimscore.config.core.menue.currentObject == tg)
	|| (aimscore.config.core.menue.currentObject.previousSibling == tg)) return;
	
	var parent = tg;
	while((parent = parent.parentNode) != document.body){
		if(parent == aimscore.config.core.menue.currentObject){
			aimscore.config.core.menue.currentObject = false;
			aimscore.output("Ein Menüpunkt kann nicht Untermenüpunkt seiner Selbst sein.");
			return;
		}
	}
	
	if((tg.className.indexOf("entry") != -1)){
		tg.getElementsByTagName("ul")[0].appendChild(aimscore.config.core.menue.currentObject.previousSibling);
		tg.getElementsByTagName("ul")[0].appendChild(aimscore.config.core.menue.currentObject);
		aimscore.config.core.menue.update(aimscore.config.core.menue.currentObject);
	}
		
	if ((tg.className.indexOf("prev") != -1)) {
		tg.parentNode.insertBefore(aimscore.config.core.menue.currentObject.previousSibling,tg);
		tg.parentNode.insertBefore(aimscore.config.core.menue.currentObject,tg);
		aimscore.config.core.menue.update(aimscore.config.core.menue.currentObject);
	}
	
	aimscore.config.core.menue.currentObject = false;
}

aimscore.config.core.menue.update = function(obj){
	var parent = obj.parentNode;
	while(parent.tagName != "LI"){
		if(parent == document) return;
		parent = parent.parentNode;
	}
	
	var parentid = parent.firstChild.value;
	var areaid = 0;
	if(parentid == 0)
		areaid = parent.firstChild.nextSibling.value;
		
	if((parentid ==0) &&( areaid == 0)) return debug("No parent found");
	
	var nextid = 0;
	if(obj.nextSibling && obj.nextSibling.nextSibling)
		nextid = obj.nextSibling.nextSibling.firstChild.value;
	

	
	var data = {"parentid":parentid,"areaid":areaid,"nextid":nextid,"entryid":obj.firstChild.value};
	
	var i = aimscore.ajax.cmd("core","menue.ajax.php","menue.moveEntry",data,aimscore.ajax.progress);
	aimscore.ajax.request[i].callback = aimscore.config.core.menue.progress;
}

aimscore.config.core.menue.progress = function(response){
	aimscore.output(response.output);
}

aimscore.onload.add(aimscore.init);
 }

