MVC.AdminAccess = {
	scheduleSearchEverything_lastText: '',
	scheduleSearchEverything_timer: null,
	initialSections: [],
	initialOptions: [],
};

MVC.AdminAccess.initialize = function() {
	MVC.AdminAccess.resizeForm();

	Event.observe(window, 'resize', function() {
		MVC.AdminAccess.resizeForm();
	});

	Event.on($$('td.column-1').first(), 'click', '.showOptions', function(evt, btn) {
		Event.stop(evt);
		var target = $(btn.readAttribute('data-target'));

		$$('td.column-2').first().select('tr.visible').each(function(tr) {
			tr.removeClassName('visible');
		});
		if (target) {
			target.up('tr').addClassName('visible');
		}

		$$('td.column-1 label.selected').each(function(elm){ elm.removeClassName('selected'); });
		$$('td.column-1 label.selected-fake').each(function(elm){ elm.removeClassName('selected-fake'); });
		$$('td.column-2 tr.selected').each(function(elm){ elm.removeClassName('selected'); });

		btn.up('label').addClassName('selected');
	});

	$('search').observe('keydown', MVC.AdminAccess.scheduleSearchIfNeeded);
	$('search').observe('keyup', MVC.AdminAccess.scheduleSearchEverything);



	$$('td.column-1 input[type=checkbox]').each(function(ck) {
		MVC.AdminAccess.initialSections.push({
			input: ck,
			value: ck.checked
		});
	});
	$$('td.column-2 input[type=checkbox]').each(function(ck) {
		MVC.AdminAccess.initialOptions.push({
			input: ck,
			value: ck.checked
		});
	});
	$$('td.column-2 select').each(function(ck) {
		MVC.AdminAccess.initialOptions.push({
			input: ck,
			value: $F(ck)
		});
	});

	Event.on(window, 'change', 'td.column-1 input[type=checkbox]', function(evt) {
		MVC.AdminAccess.onChangeSection(evt.element(), 'checkbox');
	});
	Event.on(window, 'tree:change', 'td.column-1 input[type=checkbox]', function(evt) {
		if (evt.memo.source=='click') {
			MVC.AdminAccess.onChangeSection(evt.element(), 'checkbox');
		}
		else if (evt.memo.source=='checkAll' || evt.memo.source=='uncheckAll') {
			MVC.AdminAccess.onChangeSection(evt.element(), 'checkbox');
		}
	});

	Event.on(window, 'change', 'td.column-2 input[type=checkbox]', function(evt) {
		MVC.AdminAccess.onChangeOption(evt.element(), 'checkbox');
	});
	Event.on(window, 'change', 'td.column-2 select', function(evt) {
		MVC.AdminAccess.onChangeOption(evt.element(), 'select');
	});
}

MVC.AdminAccess.resizeForm = function() {
	$$('table.formField-container-columns >tbody >tr >td >fieldset >div ').each(function(e) {
		e.setHeight(
			$$('div.buttons').first().getTop()
			- $$('table.formField-container-columns >tbody >tr >td >fieldset >div').first().getTop()
			- $$('table.formField-container-columns >tbody >tr >td >fieldset >legend').first().getHeight()

		);
	});

	$('form_').setHeight($$('div.buttons').first().getTop() - $('form_').getTop() - 15);
}

MVC.AdminAccess.onChangeSection = function(input, optionType) {
	var val = MVC.AdminAccess.initialSections.filter(function(ck){
		return input == ck.input;
	});

	var changed = (val[0].value != input.checked);

	input.up('label').removeClassName('changed');
	if (changed) {
		input.up('label').addClassName('changed');
	}
}

MVC.AdminAccess.onChangeOption = function(input, optionType) {
	var val = MVC.AdminAccess.initialOptions.filter(function(ck){
		return input == ck.input;
	});

	var changed = true;
	if (optionType=='checkbox') {
		changed = (val[0].value != input.checked);
	}
	else if (optionType=='select') {
		changed = (val[0].value != $F(input));
	}

	input.up('tr').removeClassName('changed');
	MVC.AdminAccess.getSectionElementFromOptionElement(input).removeClassName('changed-fake');
	if (changed) {
		input.up('tr').addClassName('changed');
		MVC.AdminAccess.getSectionElementFromOptionElement(input).addClassName('changed-fake');
	}
}

MVC.AdminAccess.getSectionElementFromOptionElement = function(option) {
	var optionContainer = option.up('fieldset');

	return $$('td.column-1 a[data-target='+optionContainer.identify()+']').first().up('label');
}



MVC.AdminAccess.scheduleSearchEverything = function(evt) {
	if (MVC.AdminAccess.scheduleSearchEverything_lastText==$F('search')) {
		return;
	}

	if (MVC.AdminAccess.scheduleSearchEverything_timer!=null) {
		clearTimeout(MVC.AdminAccess.scheduleSearchEverything_timer);
		MVC.AdminAccess.scheduleSearchEverything_timer = null;
	}
	MVC.AdminAccess.scheduleSearchEverything_timer = setTimeout(MVC.AdminAccess.searchEverything, 500);
}


MVC.AdminAccess.scheduleSearchIfNeeded = function(evt) {
	if (evt.keyCode==13) { // enter
		Event.stop(evt);

		MVC.AdminAccess.searchEverything_nextMatch();

		return false;
	}
	else if (evt.keyCode==27) {	// esc
		Event.stop(evt);

		// disable enter
		$('search').value = '';
		MVC.AdminAccess.searchEverything();


		return false;
	}

}

MVC.AdminAccess.searchEverything = function() {
	var text = $F('search');
	MVC.AdminAccess.scheduleSearchEverything_lastText = text;

	// reset all previously matched elements
	$$('label.search-matched').each(function(elm){ elm.removeClassName('search-matched'); });
	$$('tr.search-matched').each(function(elm){ elm.removeClassName('search-matched'); });
	$$('td.column-1 label.selected-fake').each(function(elm){ elm.removeClassName('selected-fake'); });
	$$('td.column-2 tr.selected').each(function(elm){ elm.removeClassName('selected'); });

	if (text.length==0) {
		// reset search fields
	}
	else {
		$$('td.column-1 label.selected').each(function(elm){ elm.removeClassName('selected'); });

		// do the actual search, with an actual text
		var regexp = new RegExp(text, 'i');
		var matchedElements = [];

		$$('#form_ td.column-1').first().select('label').each(function(elm) {
			var match = false;
			if (regexp.match(elm.innerText)) {
				match = true;
			}
			else if (regexp.match(elm.down('input').readAttribute('name').replace("sections[", "").replace("]", ""))) {
				match = true;
			}

			if (match) {
				matchedElements.push(elm);
			}
		});

		$$('#form_ td.column-2').first().select('td.label').each(function(td) {
			var match = false;
			if (regexp.match(td.innerText)) {
				match = true;
			}
			else {
				var input = td.up('tr').down('input');
				if (!input) {
					input = td.up('tr').down('select');
				}

				if (input && regexp.match(input.readAttribute('name').replace("options[", "").replace("]", ""))) {
					match = true;
				}
			}

			if (match) {
				matchedElements.push(td.up('tr'));
			}
		});

		if (matchedElements.length) {
			matchedElements.each(function(elm){
				elm.addClassName('search-matched');
			});
			MVC.AdminAccess.searchEverything_nextMatch();
		}
		else {
			MVC.AdminAccess.searchEverything_updateButtonsStatuses([], null);
		}
	}
}

MVC.AdminAccess.searchEverything_getIndex = function () {
	var matchedElements = [];
	$$('label.search-matched').each(function(elm){ matchedElements.push(elm); });
	$$('tr.search-matched').each(function(elm){ matchedElements.push(elm); });

	// sort matchedElements, human-friendly (options belonging to an option should be shown in that option)
	var matchedElementsSorted = [];
	for (var i=0; i<matchedElements.length; i++) {
		var moved = false;
		if (matchedElements[i] && matchedElements[i].descendantOf($$('#form_ td.column-1').first())) {
			var target = $(matchedElements[i].down('a').readAttribute('data-target'));

			for (var j=i+1; j<matchedElements.length; j++) {
				if (target && matchedElements[j] && matchedElements[j].descendantOf($$('#form_ td.column-2').first())) {
					if (matchedElements[j].descendantOf(target)) {
						if (matchedElements[i]) {
							matchedElementsSorted.push(matchedElements[i]);
							matchedElements[i] = null;
						}

						matchedElementsSorted.push(matchedElements[j]);
						matchedElements[j] = null;
						moved = true;
					}
				}
			}
		}

		if (matchedElements[i] && !moved) {
			matchedElementsSorted.push(matchedElements[i]);
			matchedElements[i] = null;
			moved = true;
		}
	}

	matchedElements = matchedElementsSorted;

	var foundIndex = null;
	for (var i=0; i<matchedElements.length; i++) {
		if (matchedElements[i].hasClassName('selected')) {
			foundIndex = i;
			break;
		}
	}

	return {
		matchedElements:matchedElements,
		foundIndex:foundIndex
	};
}

MVC.AdminAccess.searchEverything_updateButtonsStatuses = function (matchedElements, markedIndex) {
	var li_nextMatch = $('search').up().down('li[data-id=searchEverything_nextMatch]');
	var li_prevMatch = $('search').up().down('li[data-id=searchEverything_prevMatch]');

	if (markedIndex===null || matchedElements.length<=1) {
		if (!li_nextMatch.hasClassName('disabled')) {
			li_nextMatch.addClassName('disabled');
			li_nextMatch.down('var').className = li_nextMatch.down('var').className+="-disabled";
		}

		if (!li_prevMatch.hasClassName('disabled')) {
			li_prevMatch.addClassName('disabled');
			li_prevMatch.down('var').className = li_prevMatch.down('var').className+="-disabled";
		}
	}

	else if (markedIndex===0) {
		if (li_nextMatch.hasClassName('disabled')) {
			li_nextMatch.removeClassName('disabled');
			li_nextMatch.down('var').className = li_nextMatch.down('var').className.replace("-disabled", "");
		}

		if (!li_prevMatch.hasClassName('disabled')) {
			li_prevMatch.addClassName('disabled');
			li_prevMatch.down('var').className = li_prevMatch.down('var').className+="-disabled";
		}
	}

	else if (markedIndex>=(matchedElements.length-1)) {
		if (!li_nextMatch.hasClassName('disabled')) {
			li_nextMatch.addClassName('disabled');
			li_nextMatch.down('var').className = li_nextMatch.down('var').className+="-disabled";
		}

		if (li_prevMatch.hasClassName('disabled')) {
			li_prevMatch.removeClassName('disabled');
			li_prevMatch.down('var').className = li_prevMatch.down('var').className.replace("-disabled", "");
		}
	}

	else {
		if (li_nextMatch.hasClassName('disabled')) {
			li_nextMatch.removeClassName('disabled');
			li_nextMatch.down('var').className = li_nextMatch.down('var').className.replace("-disabled", "");
		}

		if (li_prevMatch.hasClassName('disabled')) {
			li_prevMatch.removeClassName('disabled');
			li_prevMatch.down('var').className = li_prevMatch.down('var').className.replace("-disabled", "");
		}
	}
}

MVC.AdminAccess.searchEverything_markMatchIndex = function (matchedElements, markedIndex) {
	$$('td.column-1 label.selected').each(function(elm){ elm.removeClassName('selected'); });
	$$('td.column-1 label.selected-fake').each(function(elm){ elm.removeClassName('selected-fake'); });

	if (!matchedElements[markedIndex]) {
		return;
	}
	matchedElements[markedIndex].addClassName('selected');

	if (matchedElements[markedIndex].descendantOf($$('#form_ td.column-1').first())) {
		Effect.ScrollContainerTo(
			matchedElements[markedIndex],
			$$('td.column-1 >fieldset >div').first(),
			{ duration: 0.25, offset: 100, referencePoint:'top', optimize: true, transition: Effect.Transitions.linear }
		);

		$$('td.column-2').first().select('tr.visible').each(function(tr) {
			tr.removeClassName('visible');
		});
	}
	else if (matchedElements[markedIndex].descendantOf($$('#form_ td.column-2').first())) {
		$$('td.column-2').first().select('tr.visible').each(function(tr) {
			tr.removeClassName('visible');
		});

		var container = null;
		$$('td.column-2 >fieldset >div >table >tbody >tr').each(function(tr) {
			if (matchedElements[markedIndex].descendantOf(tr)) {
				container = tr;
			}
		});
		if (container) {
			var reference = $$('td.column-1 label a[data-target='+container.down('fieldset').identify()+']').first().up('label');
			container.addClassName('visible');
			reference.addClassName('selected-fake');
			Effect.ScrollContainerTo(
				reference,
				$$('td.column-1 >fieldset >div').first(),
				{ duration: 0.1, offset: 100, referencePoint:'top', optimize: true, transition: Effect.Transitions.linear }
			);

			Effect.ScrollContainerTo(
				matchedElements[markedIndex],
				$$('td.column-2 >fieldset >div').first(),
				{ duration: 0.25, offset: 100, referencePoint:'top', optimize: true, transition: Effect.Transitions.linear }
			);
		}
	}
}

MVC.AdminAccess.searchEverything_nextMatch = function() {
	var gi = MVC.AdminAccess.searchEverything_getIndex();

	$$('td.column-2 tr.selected').each(function(elm){ elm.removeClassName('selected'); });

	var markedIndex = null;
	if (gi.foundIndex===null) {
		markedIndex = 0;
	}
	else {
		if (gi.matchedElements.length>(gi.foundIndex+1)) {
			markedIndex = gi.foundIndex+1;
		}
	}

	if (markedIndex!==null) {
		MVC.AdminAccess.searchEverything_markMatchIndex(gi.matchedElements, markedIndex);
		MVC.AdminAccess.searchEverything_updateButtonsStatuses(gi.matchedElements, markedIndex);
	}
}

MVC.AdminAccess.searchEverything_prevMatch = function() {
	var gi = MVC.AdminAccess.searchEverything_getIndex();

	$$('td.column-2 tr.selected').each(function(elm){ elm.removeClassName('selected'); });

	var markedIndex = null;
	if (gi.foundIndex===null) {
		markedIndex = gi.matchedElements.length-1;
	}
	else {
		if ((gi.foundIndex-1)>=0) {
			markedIndex = gi.foundIndex-1;
		}
	}

	if (markedIndex!==null) {
		MVC.AdminAccess.searchEverything_markMatchIndex(gi.matchedElements, markedIndex);
		MVC.AdminAccess.searchEverything_updateButtonsStatuses(gi.matchedElements, markedIndex);
	}
}
