/**
*	Class:		Navigation
*	Purpose:	supports flyout navigation for IE6, adds delays before hiding menus
*/
var Navigation = new Class({
	options: {
		delay:200
	},
	initialize: function(list,options){
		this.list = list;
		this.items = list.getElements('li');
		Object.extend(this.options,options)||{};
		this.addHandlers();
	},
	addHandlers: function(){
		this.items.each(function(el){
			var sub = el.getElement('ul');
			if(sub) {
				el.getElement('a').addClass('hasSubMenu');
				el.addEvent('mouseenter',function(e){this.showSubMenu(el,sub,e);}.bind(this));
				el.addEvent('mouseleave',function(e){
					this.isHiding = sub;
					this.hiding = this.hideSubMenu.delay(this.options.delay,this,[el,sub]);
				}.bind(this));
			}
		}.bind(this));
	},
	showSubMenu: function(el,sub,e){
		if(this.isHiding == el) {this.isHiding = false; $clear(this.hiding); return;}
		el.addClass('fhover');
		if(sub)sub.addClass('fhover');
	},
	hideSubMenu: function(el,sub){
		this.isHiding = false;
		el.removeClass('fhover');
		sub.removeClass('fhover');
	}
});

var ProjectSearch = new Class({
	Implements: Options,
	options: {},
	initialize: function(input,options){
		this.input = $(input);
		this.form = $(this.input.form);
		this.setOptions(options);
		this.placeHolder = this.initPlaceHolderValue();
		this.addHandlers();
	},
	initPlaceHolderValue: function(){
		var txt = this.form.getElement('label').addClass('hide').get('text');
		this.input.set('value',txt);
		return txt;
	},
	addHandlers: function(){
		this.input.addEvents({
			'focus':this.onFocus.bindWithEvent(this),
			'blur':this.onBlur.bindWithEvent(this)
		});
	},
	onFocus: function(){
		this.input.addClass('active');
		if(this.input.get('value') == this.placeHolder) this.input.set('value','');
	},
	onBlur: function(){
		this.input.removeClass('active');
		if(this.input.get('value') == '') this.input.set('value',this.placeHolder);
	}
});

var InfoTips = new Class({
	Implements: Options,
	options: {
		'separator':'::',
		'moreInfoSeparator':' >>> ',
		'cssClassHover':'toolTip',
		'cssClassClick':'clickTip',
		'langClose' : 'close',
		'maintainLink' : false
	},
	initialize: function(cssSelector,options){
		this.cssSelector = cssSelector;
		this.setOptions(options);
		this.elements = this.getElements();
		//this.formatTitles();
		this.toolTip = this.createToolTip();
		this.toolTip.top = this.toolTip.getElement('.tip-top');
		if(!this.options.maintainLink) this.clickTip = this.createClickTip();
	},
	getElements: function(){
		return document.getElements(this.cssSelector);
	},
	createToolTip: function(){
		this.elements.each(function(el,i){
			var title = el.get('title');
			var foo = title.split(this.options.moreInfoSeparator);
			if(foo.length>1) el.store('tip:text',foo.pop());
			else el.store('tip:text','&nbsp;');
			foo = foo.join(this.options.moreInfoSeparator).split(this.options.separator);
			if(foo.length > 1) foo[0] = '<h1>' + foo[0] + '</h1>';
			el.store('tip:title',foo.join(''));
			if(!this.options.maintainLink) el.addEvent('click',this.fetchClickTip.bindWithEvent(this));
		}.bind(this));
		var toolTips = new Tips(this.elements,{className:this.options.cssClassHover});
		toolTips.addEvent('show',function(tip){
			//console.log(this.textElement);
			//console.log(tip.top);
			tip.top.set('text',this.textElement.get('text'));
		});
		return toolTips.tip;
	},
	createClickTip: function(){
		var clickTip = this.toolTip.clone().set('class',this.options.cssClassClick);
		var top = clickTip.getElement('.tip-top');
		var tip = clickTip.getElement('.tip');
		var bottom = clickTip.getElement('.tip-bottom');
		var resizer = new Element('div',{'class':'resizer'}).inject(bottom);
		var closeBtn = new Element('a',{
			'href':'#',
			'class':'tip-close',
			'title' : this.options.langClose,
			'events' : {'click':this.hideClickTip.bindWithEvent(this)}
		}).set('text',this.options.langClose).inject(top);
		this.clickTitle = new Element('div',{'class':'tip-title'}).inject(tip);
		this.clickText = new Element('div',{'class':'tip-text'}).inject(tip);
		clickTip.makeDraggable({'handle':top});
		tip.makeResizable({'handle':resizer});
		clickTip.inject(this.toolTip,'after');
		return clickTip;
	},
	fetchClickTip: function(e){
		new Event(e).stop();
		if(!e.target.hasClass('clicktip')) return false;
		this.wait(true);
		var id = String(e.target.id).split('__')[1];
		var jsonRequest = new Request.JSON({
			url:'./',
			onComplete: function(result){
				this.showClickTip(result);
				this.wait(false);
			}.bind(this)
		}).get({'action':'getClickTip','TOOLTIP_ID':id});
	},
	showClickTip: function(result){
		this.clickTitle.set('text',result.titleClick);
		this.clickText.set('html',result.textClick);
		var styles = this.toolTip.getStyles('top','left');
		styles.visibility = 'visible';
		this.clickTip.setStyles(styles);
		this.toolTip.setStyle('visibility','hidden');
	},
	hideClickTip: function(e){
		new Event(e).stop();
		this.clickTip.setStyle('visibility','hidden')
	},
	wait: function(show){
		if(show)this.toolTip.top.addClass('waiting');
		else this.toolTip.top.removeClass('waiting');
	}
});

var ProposalNodeInfo = new Class({
	Implements: Options,
	options: {
		offsets: {x: 16, y: 16},
		toolTipTxt: 'edit comment',
		readOnly: false
	},
	initialize: function(id,formWrapperId, options){
		this.setOptions(options);
		this.list = $(id);
		this.wrapper = $(formWrapperId).set('opacity',0.9);
		this.comment = this.wrapper.getElement('#nodeInfo');
		if(!this.options.readonly){
			this.form = this.wrapper.getElement('form');
			this.anchor = null;
		}
		this.addHandlers();
	},
	addHandlers: function(){
		this.wrapper.makeDraggable({handle:this.wrapper.getElement('.head')});
		
		this.wrapper.getElement('a.close').addEvent('click',this.hideTip.bindWithEvent(this));
		this.comment.makeResizable({handle:this.wrapper.getElement('.resize')});
		if(!this.options.readonly){
			this.form.addEvent('submit',this.saveTip.bindWithEvent(this));
		}
		this.list.getElements('.clicktip').each(function(el){
			el.store('title',el.title);
			el.title = this.options.toolTipTxt;
			el.addEvent('click',this.showTip.bindWithEvent(this,el));
		}.bind(this));
	},
	showTip: function(e,el){
		new Event(e).stop();
		this.anchor = el;
		this.position(e);
		this.wrapper.getElement('#nodeInfo').set((this.options.readonly)?'html':'value',el.retrieve('title'));
		this.wrapper.removeClass('hide');
	},
	hideTip: function(e){
		if(e)new Event(e).stop();
		this.anchor = null;
		this.wrapper.addClass('hide');
		this.comment.set('style',false); // resets box size (and position)
	},
	position: function(event){
		var size = window.getSize(), scroll = window.getScroll();
		var tip = {x: this.wrapper.offsetWidth, y: this.wrapper.offsetHeight};
		var props = {x: 'left', y: 'top'};
		for (var z in props){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > size[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.wrapper.setStyle(props[z], pos);
		}
	},
	saveTip: function(e){
		new Event(e).stop();
		if(this.options.readonly) return;
		if (!this.anchor) {
			alert('no nodeId retrieved');
			return false;
		}
		var nodeId = this.anchor.getParent('li[id^=node__]').id.split('__')[1];
		var tipTxt = this.comment.get('value');
		var jsonRequest = new Request.JSON({url: "?action=saveProposalNodeJson", onComplete: function(response){
			this.anchor.store('title',tipTxt);
			this.hideTip(e);
		}.bind(this)}).post({'PROPOSALNODE_ID': nodeId, 'info': tipTxt, 'updateInfo': 1});

	}
});

var ItnBudget = new Class({
	Implements: Options,
	options: {
		confirmTxt: 'Warning!\nThe figures in this row will be ignored, if you uncheck!\nDo you really want this?'
	},
	initialize: function(id, options){
		this.setOptions(options);
		this.wrapper = $(id);
		this.checks = this.wrapper.getElements('input[type=checkbox]');
		this.addHandlers();
	},
	addHandlers: function(){
		this.checks.each(function(el){
			el.store('row',el.getParent().getAllNext('input.text'));
			el.addEvent('click',this.toggleRow.bindWithEvent(this,el));
		}.bind(this));
	},
	toggleRow: function(e,checkbox){
		var row = checkbox.retrieve('row');
		var needsConfirm = false;
		if(!checkbox.checked) {
			row.each(function(el){
				if(el.get('value') > 0) needsConfirm = true;
			});
		}
		var confirmed = (needsConfirm) ? confirm(this.options.confirmTxt) : true;
		if(!confirmed) {new Event(e).stop();return;}
		else {row.set('disabled',!checkbox.checked);}
	}
});

var Timetable = new Class({
	Implements: Options,
	options: {
		txtCollapseAll: 'collapse all',
		txtExpandAll: 'expand all',
		defaultState: 'collapsed'
	},
	initialize: function(id,options){
		this.setOptions(options);
		this.table = $(id);
		this.slides = [];
		this.addTips();
		this.createSlides();
		this.toggler = this.table.getElement('#toggleAll');
		this.toggler.removeClass('hide');
		this.toggler.addEvent('click',this.toggleAll.bindWithEvent(this));
		if(this.options.defaultState == 'collapsed') this.collapseAll();
	},
	addTips: function(){
		var milestoneTips = new InfoTips('.milestone',{'maintainLink':true});
	},
	createSlides: function(){
		this.slides = this.table.getElements('.objectives');
		this.slides.each(function(el){
			this.initToggler(el);
		}.bind(this));
	},
	getToggler: function(el){
		return el.getPrevious('.wp').getElement('.toggler');
	},
	initToggler: function(el){
		var toggler = this.getToggler(el);
		toggler.store('slide',el);
		toggler.hide = this.hide.bind(toggler);
		toggler.show = this.show.bind(toggler);
		toggler.addEvent('click',this.toggle);
		//if(this.options.defaultState == 'collapsed') toggler.hide();
	},
	toggle: function(){
		this.retrieve('slide').toggleClass('hide');
		this.toggleClass('open');
	},
	hide: function(){
		this.retrieve('slide').addClass('hide');
		this.removeClass('open');
	},
	show: function(){
		this.retrieve('slide').removeClass('hide');
		this.addClass('open');
	},
	toggleAll: function(){
		if(this.toggler.get('text') == this.options.txtExpandAll) this.expandAll();
		else this.collapseAll();
	},
	expandAll: function(){
		this.slides.each(function(el){
			var toggler = this.getToggler(el);
			toggler.show();
		}.bind(this));
		this.toggler.set('text',this.options.txtCollapseAll);
	},
	collapseAll: function(){
		this.slides.each(function(el){
			var toggler = this.getToggler(el);
			toggler.hide();
		}.bind(this));
		this.toggler.set('text',this.options.txtExpandAll);
	}
});

var Proposal = new Class({
	Implements: Options,
	options: {
		active: 0,
		defaultState : 'collapsed',
		confirmDelete: 'Are you sure you want to delete this item?',
		readonly: false
	},
	initialize: function(options){
		this.setOptions(options);
		this.list = $('proposalChapters');
		this.list.getElements('.toggler').each(function(el){
			var ul = el.getNext('ul.list');
			if(ul) this.initToggler(el,ul);
		}.bind(this));
		if (this.options.active) this.expandAncestors(this.options.active);
		if (this.options.active && !this.options.readonly) {
			this.activeItem = $('node__'+this.options.active);
			this.initCaptionEdit();
		}
		
		if (!this.options.readonly) {
			this.list.getElements('li[id^=node__]').each(function(el){
				this.initTools(el);
			}.bind(this));
		}
	},
	initToggler: function(el,ul){
		el.addClass('enabled');
		el.toggle = this.toggle.bind(el);
		el.expand = this.expand.bind(el);
		el.collapse = this.collapse.bind(el);
		el.store('sublist',ul);
		el.collapse();
		el.addEvent('click',el.toggle);
	},
	toggle: function(){
		if(this.hasClass('expanded')) this.collapse();
		else this.expand();
	},
	expand: function(){
		this.addClass('expanded');
		this.retrieve('sublist').removeClass('hide');
	},
	collapse: function(){
		this.removeClass('expanded');
		this.retrieve('sublist').addClass('hide');
	},
	expandAncestors: function(nodeId){
		var node = $('node__'+nodeId);
		node.getParents('li').each(function(el){
			el.getFirst('.toggler').expand();
		});
	},
	initTools: function(el){
		var ul = el.getElement('ul.tools');
		var a = el.getFirst('a.text');
		if (a) {
			var toolbar = new Fx.Slide(ul,{duration:200});
			toolbar.hide();
			a.addEvents({
				'dblclick': function(e){
					new Event(e).stop();
					document.location.href = a.href;
				},
				'click': function(e){
					new Event(e).stop();
					el.blur();
					toolbar.toggle();
				}
			});
		}
		var del = ul.getElement('.delete');
		//console.log(el);
		del.addEvent('click',function(e){
			if(confirm(this.options.confirmDelete)==false) new Event(e).stop();
		}.bindWithEvent(this));
	},
	initCaptionEdit: function(){
		// resize form field width
		var el = this.activeItem.getElement('#nodeHeadline__' + this.options.active);
		var wF = $(el.form).getSize().x;
		var wL = el.getPrevious('label').getSize().x;
		el.setStyle('width',wF - wL - 8 + 'px');
		// add handler:
		el.addEvent('blur',this.saveCaption);
		
		el.form.addEvent('submit',function(e){
			new Event(e).stop();
			el.blur();
		});
	},
	saveCaption: function(){
		if(this.value.trim()=='') {
			this.set('value',this.defaultValue);
			return false;
		}
		var nodeId = this.id.split('__')[1];
		var jsonRequest = new Request.JSON({url: "?action=saveProposalNodeJson", onComplete: function(response){
			//console.log(response);
		}}).post({'PROPOSALNODE_ID': nodeId, 'headline': this.get('value')});

	}
});

var EthicalAspect = new Class({
	Implements: Options,
	options: {},
	initialize: function(id, options){
		this.setOptions(options);
		this.wrapper = $(id);
		this.flags = this.wrapper.getElements('.flag');
		this.slider = this.wrapper.getElement('.scroll');
		this.checks = this.slider.getElements('.checkbox');
		this.init();
	},
	init: function(){
		this.flags.each(function(el){
			if(el.checked) this.setState(el.value);
			el.addEvent('focus',function(e){
				this.setState(e.target.value);
			}.bind(this));
		}.bind(this));
	},
	setState: function(fAspects){
		if(fAspects==0) this.slider.addClass('hide');
		else this.slider.removeClass('hide');
		this.checks.each(function(el){
			el.set('disabled',(fAspects==0))
		});
	}
});

function addLinkTargets(extId){
	$(extId).getElements('a.target__blank').each(function(el){
		el.addEvent('click',function(e){
			var ev = new Event(e); ev.stop();
			window.open(el.href);
		})
	})
}

/* makes upload fields nicer */
function prettifyUpload(el){
	el = $(el);
	var w = el.getSize().size.x;
	var myWrapper = $(document.createElement('div')).addClass('uploadWrapper').setStyle('width',w+2+'px').injectBefore(el).adopt(el);
	var bg = el.getStyle('backgroundColor');
	var fakeFile = $(document.createElement('div')).addClass('fakeFile').injectAfter(el).setStyles({
		width: w - 18 + 'px',
		backgroundColor: bg
	});
	var fakeButton = $(document.createElement('div')).addClass('fakeButton').injectAfter(el);
	el.addEvent('change',function(e){
		foo = el.value.split('/');
		foo = foo[foo.length-1].split('\\');
		fakeFile.setText(foo[foo.length-1]);
	}).setOpacity(.01);
}
function appendTooltips(cssSelector){
	document.getElements(cssSelector).each(function(el,i){
		var foo = el.get('title').split('::');
		if(foo.length > 1) foo[0] = '<h1>' + foo[0] + '</h1>';
		el.set('title',foo.join(''));
	});
	var myTips = new Tips(cssSelector,{className:'toolTip'});
	
}


