dojo.registerModulePath("de.uebergebuehr.ue5.workbench", "/resources/js/workbench");
dojo.require("dojo.fx");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.ComboBox");
dojo.require("de.uebergebuehr.ue5.workbench.data.ItemFileReadStore");

var wipeOut;
var wipeIn;
var currentAnimation;
var scrollState = {};
var pagers = {};

/* === MENUS === */

function toggleMenu() {
	switch(currentAnimation) {
		case 0:
			currentAnimation = 2;
			dojo.attr(dojo.byId("navigation-full"),'height','auto');
			wipeIn.play();
			break;
		case 1:
			currentAnimation = 2;
			wipeIn.play();
			break;
		case 2:
			currentAnimation = 1;
			wipeOut.play();
			break;
	}
}

function fadeOutPage(containerId) {
	dojo.style("main", "cursor", "wait");
	var contentFadeOut = dojo.fadeOut({
		node: dojo.byId(containerId),
		duration: 600
	});
	contentFadeOut.play();
}

function fadeInPage(containerId) {
	var contentFadeIn = dojo.fadeIn({
		node: dojo.byId(containerId),
		duration: 800
	});
	contentFadeIn.play();
	dojo.connect(contentFadeIn, "onEnd", function() {
		dojo.style("main", "cursor", "default");
	});
}

function wipeInOut(containerId1, containerId2) {
	dojo.fx.wipeIn({node: dojo.byId(containerId1), duration: 350 }).play();
	dojo.fx.wipeOut({node: dojo.byId(containerId2), duration: 200 }).play();
}

/* === TREES === */

dojo.addOnLoad(function(){
	var themenTreeStore = new dojo.data.ItemFileReadStore({
		id: "themenTreeStore",
		url: "/services/rest/themen/tree"
	});
	var themenTree = new dijit.Tree({
		showRoot: true,
		store: themenTreeStore,
		getIconClass: function(/*dojo.data.Item*/ item, /*Boolean*/ opened) {
			return "dijitWithoutFolder";
			// return (!item || this.model.mayHaveChildren(item)) ? (opened ? "" : "") : ""
		},
		onClick: function(item) {
			if (!dojo.cookie.isSupported()) {
				var jsessionid = document.location.href.split(";")[1]; // .split("=")[1];
				if (jsessionid) {
					var url = themenTreeStore.getValue(item,'url') + ";" + jsessionid;
					location.href = url;
					return;
				}
				console.error("session id verloren!");
			}
			location.href = themenTreeStore.getValue(item,'url');
		}
	}, dojo.byId('themenTree'));
	themenTree.startup();
});

dojo.addOnLoad(function(){
	var dossiersTreeStore = new dojo.data.ItemFileReadStore({
		id: "dossiersTreeStore",
		url: "/services/rest/dossiers/tree"
	});
	var dossiersTree = new dijit.Tree({
		showRoot: true,
		store: dossiersTreeStore,
		onClick: function(item) {
			if (!dojo.cookie.isSupported()) {
				var jsessionid = document.location.href.split(";")[1]; // .split("=")[1];
				if (jsessionid) {
					var url = dossiersTreeStore.getValue(item,'url') + ";" + jsessionid;
					location.href = url;
					return;
				}
				console.error("session id verloren!");
			}
			location.href = dossiersTreeStore.getValue(item,'url');
		}
	}, dojo.byId('dossiersTree'));
	dossiersTree.startup();
});

dojo.addOnLoad(function(){
	var artikelsetsTreeStore = new dojo.data.ItemFileReadStore({
		id: "artikelsetsTreeStore",
		url: "/services/rest/artikelsets/tree"
	});
	var artikelsetsTree = new dijit.Tree({
		showRoot: true,
		store: artikelsetsTreeStore,
		onClick: function(item) {
			if (!dojo.cookie.isSupported()) {
				var jsessionid = document.location.href.split(";")[1]; // .split("=")[1];
				if (jsessionid) {
					var url = artikelsetsTreeStore.getValue(item,'url') + ";" + jsessionid;
					location.href = url;
					return;
				}
				console.error("session id verloren!");
			}
			location.href = artikelsetsTreeStore.getValue(item,'url');
		}
	}, dojo.byId('artikelsetsTree'));
	artikelsetsTree.startup();
});


dojo.addOnLoad(function(){
	var regionalContextTreeStore = new dojo.data.ItemFileReadStore({
		id: "regionalContextTreeStore",
		url: "/services/rest/regions/tree"
	});
	var regionalContextTree = new dijit.Tree({
		showRoot: true,
		store: regionalContextTreeStore,
		onClick: function(item) {
			if (!dojo.cookie.isSupported()) {
				var jsessionid = document.location.href.split(";")[1]; // .split("=")[1];
				if (jsessionid) {
					var url = 'http://' + regionalContextTreeStore.getValue(item,'domain') + location.pathname + location.search + ";" + jsessionid;
					location.href = url;
					return;
				}
				console.error("session id verloren!");
			} else {
				// sessionid über die subdomains mitschleifen!
				var jsessionid = dojo.cookie("JSESSIONID");
				console.debug(jsessionid);
			}
			location.href = 'http://' + regionalContextTreeStore.getValue(item,'domain') + location.pathname + location.search;
		}
	}, dojo.byId('regionalContextTree'));
	regionalContextTree.startup();
	
	setInterval('expandRegionalContextTree()', 200);
});

function expandRegionalContextTree() {
    var regionalContextTree = dijit.byId('regionalContextTree');
    dojo.forEach(regionalContextTree.rootNode.getChildren(), function(n) {
            this._expandNode(n);
    }, regionalContextTree);
}

/* === PAGER === */

function page(containerId, endPoint, suffix, page) {
	console.debug(containerId);
	var urlA = endPoint + "/seite/" + page + suffix;
	var urlP = endPoint + "/seite/" + page;
	fadeOutPage(containerId);
	dojo.xhrGet( {
		url: urlA, 
		handleAs: "text",
		timeout: 5000,
		load: function(response, ioArgs) {
			dojo.byId(containerId).innerHTML = response;
			fadeInPage(containerId);
			try {
				var stateObj = {};
				history.pushState(stateObj, "", urlP);
			} catch(err) {}
			try {
				for (var i = 0; i < pagers[containerId].length; i++) {
					dojo.query('#pagerArea-'+pagers[containerId][i]+' a').removeClass("pagerCurrent");
					dojo.addClass('pagination-'+pagers[containerId][i]+'-'+page, 'pagerCurrent');
				}

			} catch(err) {}
			return response;
		},
		error: function(response, ioArgs) {
			dojo.byId(containerId).innerHTML = "<h1>Konnte Inhalt nicht laden.</h1>";
			fadeInPage(containerId);
			return response;
		}
	});
}

function pagerScroll(pagerScrollContainerId, direction) {
	if (scrollState[pagerScrollContainerId] == null) {
		scrollState[pagerScrollContainerId] = 0;
	}
	if (direction != null) {
		// console.debug('change scrollState of '+pagerScrollContainerId+' : '+scrollState[pagerScrollContainerId]+'->'+direction);
		scrollState[pagerScrollContainerId] = direction;
	}
	if (scrollState[pagerScrollContainerId] == 1) {
		var d = document.getElementById(pagerScrollContainerId);
		if (d) {
			var scrollLeft = d.scrollLeft;
			if (scrollLeft >= 3) {
				d.scrollLeft = d.scrollLeft - 3;
				window.setTimeout(function() {
					pagerScroll(pagerScrollContainerId);
				}, 10);
			} else {
				d.scrollLeft = 0;
				scrollState[pagerScrollContainerId] = 0;
			}
		}
	}
	if (scrollState[pagerScrollContainerId] == 2) {
		var d = document.getElementById(pagerScrollContainerId);
		if (d) {
			var scrollLeft = d.scrollLeft;
			if ((scrollLeft + d.style.width) <= (d.scrollWidth - 3)) {
				d.scrollLeft = d.scrollLeft + 3;
				window.setTimeout(function() {
					pagerScroll(pagerScrollContainerId);
				}, 10);
			} else {
				d.scrollLeft = d.scrollWidth;
				scrollState[pagerScrollContainerId] = 0;
			}
		}
	}
}

var createPager = function(paginationContainerId, listContainerId, relatedContainerId, endPoint, suffixAjaxContent, suffixAjaxRelated, maxPages, currentPage) {
	if (maxPages < 2) return;
	if (pagers[listContainerId] == null) {
		pagers[listContainerId] = new Array();
	}
	pagers[listContainerId].push(paginationContainerId);
	var pagerContainer = dojo.create('div', {
		className: 'pager'
	});
	var pagerScrollContainer = dojo.create('div', {
		id: 'pagerScroll-'+paginationContainerId,
		className: 'pagerScroll'
	});
	var pagerArea = dojo.create('div', {
		id: 'pagerArea-'+paginationContainerId,
		className: 'pagerArea'
	});
	var pagerCtrlLeft = dojo.create('img', {
		className: 'pagerControl',
		src: '/resources/gfx/user/pager/previous.png',
		alt: 'scroll left',
		onmouseover: 'pagerScroll("pagerScroll-'+paginationContainerId+'", 1);',
		onmouseout: 'pagerScroll("pagerScroll-'+paginationContainerId+'", 0);'
	});
	var pagerCtrlRight = dojo.create('img', {
		className: 'pagerControl',
		src: '/resources/gfx/user/pager/next.png',
		alt: 'scroll right',
		onmouseover: 'pagerScroll("pagerScroll-'+paginationContainerId+'", 2);',
		onmouseout: 'pagerScroll("pagerScroll-'+paginationContainerId+'", 0);'
	});
	for(i=1;i<=maxPages;i++) {
		dojo.create('a', {
			id: 'pagination-'+paginationContainerId+'-'+i,
			className: 'pagerItem',
			href: endPoint+'/seite/'+i,
			onclick: 'page("'+listContainerId+'", "'+endPoint+'", "'+suffixAjaxContent+'", '+i+'); page("'+relatedContainerId+'", "'+endPoint+'", "'+suffixAjaxRelated+'", '+i+'); return false;',
			innerHTML: i
		}, pagerArea);
	}
	dojo.place(pagerArea, pagerScrollContainer);
	dojo.place(pagerCtrlLeft, pagerContainer);
	dojo.place(pagerScrollContainer, pagerContainer);
	dojo.place(pagerCtrlRight, pagerContainer);
	dojo.place(pagerContainer, paginationContainerId, "only");
	dojo.addClass('pagination-'+paginationContainerId+'-'+currentPage, 'pagerCurrent');
}


/* === SEARCH === */

var autocompleteStore;
var autocompletePreviousQuery = '';

var openAutocompleteSearch = function() {
	console.debug("openAutocompleteSearch");
	if (autocompleteStore.getValues().length > 0) {
		searchBox.open();
	}
}

var updateAutocompleteStore = function(query) {
	console.debug("updateAutocompleteStore: "+query);
	if (autocompletePreviousQuery == query) {
		return;
	}
	autocompletePreviousQuery = query
	if (autocompleteStore == null) {
		autocompleteStore = new de.uebergebuehr.ue5.workbench.data.ItemFileReadStore({
			id: 'autocompleteStore',
			url: '/services/rest/user/search/autocomplete?q='+query,
			clearOnClose: true
		});
	} else {
		autocompleteStore.close();
		autocompleteStore.url = '/services/rest/user/search/autocomplete?q='+query;
	}
	var searchBox = dijit.byId('q');
	if (searchBox) {
		searchBox.store = autocompleteStore;
		console.debug("before fetch");
		searchBox.store.fetch();
		console.debug("after fetch");
		window.setTimeout('openAutocompleteSearch()', 100);
	}
}

/*var openAutocompleteSearch = function() {
	console.debug("fokus");
	var searchBox = dijit.byId('search-word');
	var v = searchBox.attr("value");
	if (v == "Suchbegriff") {
		searchBox.attr("value", "");
	}
//	if (v.length >= 3) {
//		try {
//			searchBox.open();
//		} catch (e) {
//			console.debug("could not open...");
//			console.error(e);
//		}
//	}
}*/

var keypressAutocompleteSearch = function(event) {
	if (event.keyCode == 13) {
		var form = dojo.byId('search-form');
		form.submit();
	} else {
		var searchBox = dijit.byId('q');
		var v = searchBox.attr('value');
		console.debug('keyup: '+v);
		console.debug(event);
		if (v.length >= 3) {
			updateAutocompleteStore(v);
		} else {
			updateAutocompleteStore('');
		}
	}
}

var changeAutocompleteSearch = function() {
	var searchBox = dijit.byId('q');
	var v = searchBox.attr("value");
	console.debug("change: "+v);
	updateAutocompleteStore(v);
}

var selectAutocompleteSearch = function() {
	var searchBox = dijit.byId('q');
	var v = searchBox.attr("value");
	var uuid = "";
	console.debug("select: should load "+v+" (uuid:"+uuid+")");
}

function getAutocompleteLabel(item, store){
	var label=store.getValue(item, 'title');
	return label;
//	var datatype=store.getValue(item, 'datatype');
//	return label+'('+datatype+')';
}

var createAutocompleteWidget = function() {
	if (!dojo.cookie.isSupported()) return;
	console.debug("createAutocompleteWidget");
	var searchWidget = dojo.byId('search-form-wrapper');
	var value = dojo.byId('q').value;
	var searchBox = new dijit.form.ComboBox({
		id: 'q',
		name: 'q',
		value: value,
		className: 'search-word',
		searchAttr: 'title',
		labelAttr: 'title',
		queryExpr: '*',
		store: autocompleteStore,
//		onKeyPress: keypressAutocompleteSearch,
		onKeyUp: keypressAutocompleteSearch,
		onChange: changeAutocompleteSearch,
		onSelect: selectAutocompleteSearch,
		selectOnClick: true,
		hasDownArrow: false,
		labelFunc: getAutocompleteLabel,
		highlightMatch: 'none',
		promptMessage:"Suchbegriff",
		autoComplete: false
//		queryExpr: '*${0}*',
//		searchDelay: 50,
//		labelType: 'html',
//		onFocus: openAutocompleteSearch,
	}, 'q');
}

dojo.addOnLoad(function(){
	fullmenuNode = dojo.byId("navigation-full-wrapper");
	console.debug(fullmenuNode);
	wipeOut = dojo.fx.wipeOut({
		node: fullmenuNode,
		duration: 600
	});
	wipeIn = dojo.fx.wipeIn({
		node: fullmenuNode,
		duration: 600
	});
	currentAnimation = 0;
	updateAutocompleteStore('');
	createAutocompleteWidget();
});


