var pathRegex = /([^ =\(,]*(\.[^ =,)]+))/;
var arrRegex  = /([^ =\(,]*(\.[^ =,)]+)) *(not)? *in *\(([^)]+)\)/gi;
var likeRegex  = /('.*?') *(not)? *like ('.*?')/i;
$(document).ready(function(){
		$(".itemcondition").each(initConditionalItem)
	}
)

function initConditionalItem(dummy,object) {
	addEventHandlers(object);
	executeConditionalShowHide(object);
}

function addEventHandlers(object) {
	var arr;
	var condition = object.value;

	while((arr = pathRegex.exec(condition)) != null) {
		var fld = getFieldObject(arr[0]);
		if (!fld) {
			condition = condition.replace(arr[0], "''");
			continue;
		}
		condition = condition.replace(arr[0], "'" + fld.value + "'");
		$(getFieldObject(arr[0])).change(function(){executeConditionalShowHide(object);});
	}
}

function executeConditionalShowHide(object) {
	var condition = translateCondition(object.value);
	var objects = object.title.split(",");
	
	var result = eval(condition);
	
	var tab = document.getElementById(objects[0]);
	var tabheader = document.getElementById(objects[1]);
	
	if ((tabheader && $(tabheader).find("a").length == 0 && result)
			|| (!tabheader && result))
	{
		$(tab).removeClass("hidden");
		$(tab).removeClass("notrequired");
	}
	else
	{
		$(tab).addClass("hidden");
		$(tab).addClass("notrequired");
		clearFieldValues(tab);
	}
	
	if (tabheader)
	{
		tabheader.style.display = result ? "block" : "none";
		showVisibleTab(tabheader);
		hideShowTabHeader(tabheader);
	}
}

function showVisibleTab(header)
{
	if (!$(header).hasClass("selected")) return;
	var items = $(getEnclosingElem(header, "div")).find("li");
	for (var i = 0; i < items.length; i++)
	{
		if (items[i].style.display == 'none')
			continue;
		if ($(items[i]).find("a").length == 0) continue;
        location.href = $(items[i]).find("a")[0].href;
		return;
	}
}

function hideShowTabHeader(header) {
	var list = getEnclosingElem(header, "ol");
	var tabgroup = getEnclosingElem(list, "div");
	
	list.style.display = allHidden($(list).find("li")) ? "none" : "block";
	tabgroup.style.display = allHidden($(tabgroup).find("ol")) ? "none" : "block";
}

function allHidden(arr) {
	for (var i = 0; i < arr.length; i++)
		if (arr[i].style.display != 'none')
			return false;
	return true;
}

function translateCondition(condition) {
	// TODO: Beter doen (als de tekens in een string staan dan moeten ze niet aangepast worden)

	condition = condition.replace(arrRegex, "('$3' == '' ? in_array([$4], $1) : !in_array([$4], $1))");
	condition = condition.replace(/([^=!])=([^=]) (not) in \(([^)*?)])/g, '$1==$2');
	condition = condition.replace(/<>/g, '!=');
	condition = condition.replace(/([^=!])=([^=])/g, '$1==$2');
	condition = condition.replace(/ and /gi, ' && ');
	condition = condition.replace(/ or /gi, ' || ');
	
	var arr;
	while((arr = pathRegex.exec(condition)) != null) {
		var fld = getFieldObject(arr[0]);
		if (!fld) {
			condition = condition.replace(arr[0], "''");
			continue;
		}
		var value = '';
		if (fld.type == 'checkbox')
			value = document.getElementById(fld.id + "_value").value;
		else
			value = "'" + fld.value + "'";
		condition = condition.replace(arr[0], value);
	}
	
	// Like condities herschrijven
	while(likeRegex.test(condition))
	{
		var eq = RegExp.$2 == ''; // not of ''
		var le = RegExp.$1;       // [xxx] like ...
		var re = RegExp.$3;       // ... like [xxx]
		var replace = (eq ? "" : "!") + "/" + re.replace(/^['"]|['"]$/g, "") // Quotes verwijderen
							  					.replace(/\./g, "\\.")		 // . moet matchen met . en niet met alles
							  					.replace(/\?/g, ".")		 // ? moet met alles matchen
							  					.replace(/%/g, ".*")		 // % herschrijven naar .* wildcard 
							  				+  "/.test(" + le + ")"
		condition = condition.replace(likeRegex, replace);
	}
	return condition;
}