/**
 * This javascript checks the current form for changed fields. If a field is not in its default position it will show a notice
 * asking the user if he is sure he wants to lose the changed data.
 * This file uses JQuery so it is not compatible with IE 5.5.
 */
var formChanged;
var canSubmitForm;
var formSubmitErrors;
var formChangedFields;
var doColorChanged;
var doColorValidated;
var errorFields = new Array();;
var shfRequired = new Object();

/**
 * Add confirmation checks on all links and forms. Also add the current value as default value for drop-down boxes.
 */
$(document).ready(function(){
	// Add onsubmit events on forms but not the login form.
	$("form[name!='bodyform']").each(function(a,b){if (b.id != "login") b.onsubmit = confirmOnFormChanged});
	
	// Add events on links which have href attributes and aren't in a tab header.
	$("a[href]").each(function(a,b) { addIfNotInHeader(b); });
	
	// Set the default item in the defaultValue property of lists.
	$("select").each(function(a,b){b.defaultValue = b.value; if (b.value == "" && b.options.length > 0) b.defaultValue = b.options[0].value;} );
	
	// Sla alle required elementen van het formulier op in shfRequired.
	$(".required").each(function(i, o) {
		shfRequired[o.id] = true;
	});
	
	// Execute onblur scripts on formfields.
	$("*[onblur]").each(function(a,b){if (/^formfield_/.test(b.name)) b.onblur();});
	$("*[onchange]").each(function(a,b){if (/^formfield_/.test(b.name)) b.onchange();});
	
	var totalCount = document.getElementById("totalCount");
	if (totalCount)
	{
		var next = $(".navigateNext")[0];
		var prev = $(".navigatePrevious")[0];
		if (parseInt(totalCount.value)-1 == document.getElementById("index").value)
		{
			next.onclick = "";
			next.src = next.src.replace(/\.gif/, "_na.gif");
			stripClass(next, "cursor");
		}
		if (0 == document.getElementById("index").value)
		{
			prev.onclick = "";
			prev.src = prev.src.replace(/\.gif/, "_na.gif");
			stripClass(prev, "cursor");
		}
	}
});

function addIfNotInHeader(item) {
	if (item.href.indexOf("#") >= 0)
		return;
	
	if (item.href) {
		if (/^javascript:.*/.test(item.href))
			return;
	}

	var itm = item.parentNode;
	while (itm.parentNode) {
		if (hasClass(itm, "tabHeader") || hasClass(itm, "smileTabHeader"))
			return;
		itm = itm.parentNode;
	}

	if (item.onclick) {
		var oldOnClick = item.onclick;
		item.onclick = function() {
			if (oldOnClick)
				if (confirmOnFormChanged())
					return oldOnClick();
				else
					return false;
			else
				return confirmOnFormChanged();
		}
	} else {
		item.onclick = function () { return confirmOnFormChanged(); };
	}
}

/**
 * Checks if the form is changed and then opens the given URL.
 * @param url
 */
function goLink(url) {
	if (confirmOnFormChanged())
		navigate(url);
}
/**
 * Check if the form has a changed field. If it does then show a message to confirm the loss of data.
 * @return <code>true</code> if no fields have changed or if the user still wants to navigate away.
 */
function confirmOnFormChanged() {
	doColorChanged = true;
	doColorValidated = false;
	formValidate();
	$(".notvalid").each(function (i, o) { stripClass(o, "notvalid")});
	
	if (formChanged) {
		return confirm("Er zijn aanpassingen gemaakt welke nog niet opgeslagen zijn."
					+ "\nAls u verder gaat zullen deze aanpassingen verloren raken."
					+ "\n\nWeet u zeker dat u verder wilt gaan?");
	}
	return true;
}

/**
 * Validate the form.
 * @return <code>true</code> if the form is succesfully validated.
 */
function doFormValidate() {
	doColorChanged = false;
	doColorValidated = true;
	
	formValidate();
	$(".changed").each(function (i, o) { stripClass(o, "changed")});
	
	if (!canSubmitForm && formSubmitErrors.length > 0) 
	{
		var message = "";
		for(var i = 0; i < formSubmitErrors.length; i++) 
		{
			message=message+formSubmitErrors[i] + "\n";
		}
		alert(message);
	}
	return canSubmitForm;
}

/**
 * Iterate over all labels and their corresponding fields to find changed fields and invalid values.
 */
function formValidate() {
	// Get all input fields.
	errorFields = new Array();
	formChanged = false;
	canSubmitForm = true;
	formChangedFields = "";
	formSubmitErrors = new Array();
	
	map( getElementsByClass("notvalid"), function (o) {stripClass(o, "notvalid");});
	
	$(".notvalid").each(function (i, o) { stripClass(o, "notvalid")});
	$(".changed").each(function (i, o) { stripClass(o, "changed")});
	
	$(".updateform label").each(validateField);
	$("#bodyform input[type!=file]").each(validateField);
	$("#bodyform textarea").each(validateField);
	$("#bodyform select").each(validateField);
	$("label.label").each(validateField);
	if (isdefined('checkCustom'))
	{
		var customErrors = new Array();
		checkCustom(customErrors);
		if(customErrors.length>0)
		{
			formSubmitErrors = formSubmitErrors.concat(customErrors);
			canSubmitForm = false;
		}
	}
}

/**
 * Validate a single field/label.
 * @param index Not used.
 * @param obj The label which is validated.
 * @return Always <code>true</code>
 */
function validateField(index, obj) {
    var fieldObj
    
    // Don't validate the copy checkboxes in smiletables.
    if (/^copy/.test(obj.name))
    	return true;
    
    if (obj.htmlFor) {
    	fieldObj = document.getElementById(obj.htmlFor);
    } else if (obj.multiple || /_X$/.test(obj.id))
    	return true;
    else
    	fieldObj = obj;
    
    if (obj.className == "disabled")
        return true;
    
    if (!fieldObj) return true;
    if ($(fieldObj).parents(".notrequired").length > 0) return true;
    
    
    stripClass(fieldObj, "notvalid");
    stripClass(fieldObj, "changed");
    
    var isRequired = hasClass(obj, "required");
    var fieldName = obj.innerHTML;

    // Struts required label.
    if (obj.htmlFor && obj.getElementsByTagName("span").length != 0) {
    	isRequired = true;
    	// Strip the required * and : from the html.
    	fieldName = fieldName.replace(/<span[^>]*>[^<]<\/span>|:$/ig, "");
    }
    
    var isEmpty = fieldObj.value == ""
                || (fieldObj.type == 'checkbox' && !fieldObj.checked);
    
    // If the field is required but empty.
    if (isRequired && isEmpty)
    {
    	// Only check visible fields.
//    	if (isVisible(fieldObj, 5))
    	{
	    	if (doColorValidated) {
	    		addClass(fieldObj, "notvalid");
	    		addClass(displayFieldFor(fieldObj), "notvalid");
	    		fieldName = getFormTabFor(fieldObj, fieldName);
	    	}
	
	    	if (/label/i.test(obj.tagName))
	    		formSubmitErrors.push(getMessage(requiredmsg, fieldName));
	    	
	    	canSubmitForm = false;
    	}
    }

    // Check the mask for the field (if a mask is present).
    var maskField = document.getElementById(fieldObj.id + "_mask");
    if (maskField) {
    	var mask = maskField.value;
    	var error = document.getElementById(fieldObj.id + "_message").value;
    	
    	error = error.replace("{1}", fieldName);
    	
    	if (!isEmpty && !new RegExp(mask).test(fieldObj.value)) {
    		fieldName = getFormTabFor(fieldObj, fieldName);
    		if (!errorFields[fieldObj])
    			formSubmitErrors.push(error);
    		
    		errorFields[fieldObj] = true;
    		canSubmitForm = false;
    		if (doColorValidated)
    		{
    			addClass(fieldObj, "notvalid");
    			addClass(displayFieldFor(fieldObj), "notvalid");
    		}
    	}
    }

    if (fieldObj.type == "checkbox") return true;
    
    // Check if the field has changed.
    if (isChanged(fieldObj)) {
    	formChangedFields += "Het veld '" + obj.innerHTML + "' is veranderd.\n";
    	formChangedFields = obj;
    	if (doColorChanged)
    	{
    		addClass(fieldObj, "changed");
    		addClass(displayFieldFor(fieldObj), "changed");
    		getFormTabFor(fieldObj, fieldName, "changed");
    	}
    	formChanged = true;
    }
    
    return true;
}

function displayFieldFor(field)
{
	if (/_display$/.test(field.id)) return;
	return document.getElementById(field.id + "_display");
}

/**
 * Gets the tab path to the field object and returns the fieldname with the path prefixed. Also colors the tabs red.
 * @param fieldObj
 * @param fieldName
 * @return
 */
function getFormTabFor(fieldObj, fieldName, className) {
	if (!className)
		className = "notvalid";
	
	var tabPath = "";
	
	var i = 0;
	var parent = fieldObj;
	while (parent != null) {
		if (i++ == 100) return "Fout";
		parent = parent.parentNode;

		if (parent && parent.id && /^tab_/.test(parent.id)) {
			var elem = document.getElementById(parent.id.replace("tab", "tabHeader"));
			if (!elem)
				continue;
			
			addClass(elem, className);
			if (tabPath != "")
				tabPath += getTextFromNode(  elem  ) + " - ";
			else
				tabPath += getTextFromNode(  elem  );
		}
	}
	
	return fieldName + " (" + tabPath + ")";
}

/**
 * Checks if the defaultvalue is different from the current value.
 * @param field The field which is checked.
 * @return If the field has changed.
 */
function isChanged(field) {
	// Don't check SmileTable header fields.
    if (/hdr.*/.test(field.name))
    	return false;
    
    // Don't check hidden fields unless they are formfields
    if (field.type == "hidden" && ! /^formfield_\d+/.test(field.id) || hasClass(field, "readonly"))
    	return false;
	
	var isChecked;
	if (document.all)
		isChecked = field.getAttribute("CHECKED") || field.getAttribute("checked");
	else
		isChecked = field.getAttribute("checked") == "checked";
	
	if (/input/i.test(field.tagName) && /checkbox/i.test(field.type) &&
			field.checked == isChecked) {
		return false;
	} else if (/input/i.test(field.tagName) && /checkbox/i.test(field.type))
		return true;
	
    return (field.value != field.defaultValue)            				// Value has not been changed
        && !(!isdefined('defaultValue', field) && field.value != -1);   // No defaultValue, but also no value selected.
}

/**
 * Navigate to a related entity.
 * @param params The parameters that are needed to know what the entity type is.
 * @param field The field which contains the ID of the entity.
 */
function navigateTo(params, link, fieldName) {
	var fld = getFieldFromForm(link, fieldName);

	if (fld.value == "")
		return;
	
	navigate("Main.action?" + params + "&id=" + fld.value);
}

/**
 * Reset all forms.
 */
function resetForm() {
	map( document.getElementsByTagName("form"),
			function(e) {e.reset();} 
	);

	var normal = function(a,b) {stripClass(b, "notvalid"); stripClass(b, "changed");};
	$("input").each(normal);
	$("textarea").each(normal);
	$("select").each(function(a,b) {
		normal(a,b);
		while(b.length>0){b.remove(0);}
		b.options[0] = new Option("-",b.defaultValue);
	});
	
	$(".gridTab").each(function(a, b){b.innerHTML = "";});
	$(".tabHeader .selected a").each(function(a,b){location.href = b.href;})
	
	if (window.updateForm)
		window.updateForm();
}

/**
 * Set the privilege to delete and submit the form.
 */
function deleteForm() {
	var form = document.getElementById("bodyform");
	var prevPrv = form.prv.value; 
	form.prv.value = 16; // nl.smile.smartcom.data.profile.Right.DELETE
	if (!form.submit())
		form.prv.value = prevPrv;
}

function openPopup(url,name, width, height) {
	var x = window.screenX;
	var y = window.screenY;
	var winWidth
	var winHeight
	if (window.innerHeight) {
		winWidth = window.innerWidth;
		winHeight = window.innerHeight;
	}
	else {
		winWidth = document.documentElement.clientWidth;
		winHeight = document.documentElement.clientHeight;
	}
	
	var left = (winWidth/2)-(width/2);
	var top = (winHeight/2)-(height/2);
	
	left += x;
	top += y;
	
	if (url.indexOf("?") == -1)
		url += "?";
	else
		url += "&";
	url +=  'width='+width;
	url += '&height='+height;
	url += '&popup=true';
	
	window.open(
			url
		  , name
		  , 'height='+height+',width='+width+',screenX='+left+',screenY='+top+',top='+top+',left='+left+',resizable=yes,status=no,scrollbars=no');
}
/** 
 * Open a popup to Add a Document
 * @param entity of instance
 * @param identifier of instance
 * @param gridtab id
 */
function addDocument(entity,identifier,gridtab)
{
	openPopup('./AddDocument.action?entity='+entity +
		    '&identifier='+identifier +
		    '&gridtab='+gridtab
		    , 'addDocument', 350, 200);
}

/** 
 * Open a popup to Add a Letter
 * @param form of instance
 * @param identifier of instance
 */
function doLetter(form,identifier,params)
{
	if (!params) params = "";
	else		 params = "&" + params;
	openPopup('./DoLetter.action?formId='+form +
		    '&id='+identifier + params
		    , 'doLetter', 350, 200);
}

/** 
 * @param parameters to pass to form
 * @param width
 * @param height
 */
function popupForm(parameters,swidth,sheight,cols)
{
	if (cols > 1) swidth *= 1.5;
	w = window.open('./Main.action?popup=true&'+
		parameters,
		'popupForm',
		'height='+sheight+',width='+swidth+',screenX=10,screenY=10,top=10,left=10,resizable=yes,status=no,scrollbars=no');
	w.focus();
}

/** 
 * Open a popup for a ManualMail
 * @param mail id of ManualMail template
 * @param id of loaded instance
 * @param columnSpec, columns of docs to be shown
 * @param formId, form id of calling form
 */
function sendEmail(mail,columnSpec)
{
	var width = 600;
	var height = 550;
	var formId = document.getElementById("form").value;
	var id = document.getElementById("id").value;
	window.open(
	'./SendEmail.action?'+
	'mail='+mail+
	'&id='+id+
	'&columnSpec='+columnSpec+
	'&formId='+formId+
	'&width='+width+
	'&height='+height+
	'&popup=true',
	'sendEmail',
	'height='+height+',width='+width+',screenX=10,screenY=10,top=10,left=10,resizable=yes,status=no,scrollbars=no').focus();
}


/**
 * Set display and post value for a field.
 * @param field
 * @param post
 * @param display
 */
function setValue(field, post, display) {
	var doc = document;

	var p = document.getElementById("formfield_" + field);
	var d = document.getElementById("formfield_" + field + "_display");
	
	if (!p && window.opener) p = window.opener.document.getElementById("formfield_" + field);
	if (!d && window.opener) d = window.opener.document.getElementById("formfield_" + field + "_display");

	if (p) p.value = post;
	if (d) d.value = display;
}

/** 
 * Open a popup to Ask a Question
 * @param question id
 */
function askQuestion(question,task)
{
	if (!doFormValidate()) return;
	var width = 360;
	var height = 220;
	var x = 10;
	var y = 10;

	w=window.open(
	'AskQuestion.action?question='+question+
					  '&task='+task+
				      '&popup=true',
	'askQuestion',
	'height='+height+',width='+width+',screenX='+x+',screenY='+y+',top='+y+',left='+x+',resizable=yes,status=no,scrollbars=no');
	w.focus();
}

/**
 * Check a required status for a field, if empty
 * add a required message to messages
 */
function checkRequired(field,messages)
{
	if(field==null || !isArray(messages)){return;}
	if (/select/i.test(field.tagName)) {
		if(field.value!='-1' && !isEmpty(field.value)){return;}	
	}
	else if(!isEmpty(field.value)){return;}
	messages.push(getMessage(requiredmsg, document.getElementById(field.id+'_label').innerHTML));
}
/**
 * Check a conditional required field, if conditionfield.value==true
 * andd field.value is empty add a required message to messages
 */
function checkConditionalRequired(field,conditionfield,messages)
{
	if(field==null || conditionfield==null || !isArray(messages)){return;}
	if(conditionfield.value=='true'){checkRequired(field,messages);}
}

/**
 * @param fnc
 * @param prv
 */
function submitWithFncPrv(fnc, prv, validate) {
	var form = document.getElementById('bodyform');
	var oldFnc = form.fnc.value;
	var oldPrv = form.prv.value;
	
	if (fnc !== false)
		form.fnc.value = fnc;
	if (prv !== false)
		form.prv.value = prv;
	
	if (validate === false)
		form.submit();
	else
		if (doFormValidate() && !submitForm(form))
		{
			form.fnc.value = oldFnc;
			form.prv.value = oldPrv;
		}
}

/**
 * @return
 */
function finish(byIcon) {
	if (byIcon) {
		map(document.getElementById("iconbar").getElementsByTagName("img"), function (o) {
			
			if (/finish\.gif$/.test(o.src)) {
				o.parentNode.click();
			}
		});
		return;
	}
	submitWithFncPrv(301, 2, true);
}

function finishSelectedTasks(tabId) {
	var input = document.createElement("input");
	input.type="hidden";
	input.name="finish";
	input.value=gridSelectedEntities(tabId, '{1}', false).replace(/&/g, ','); 
	document.getElementById("bodyform").appendChild(input);
	
	var process = document.createElement("input");
	process.type="hidden";
	process.name="process";
	process.value="1";
	document.getElementById("bodyform").appendChild(process);
	
	submitWithFncPrv(304, 2, false);
	input.parentNode.removeChild(input);
	process.parentNode.removeChild(process);
}

function navigateNextPrev(change)
{
	navigate(
			'Main.action?fnc=' + document.bodyform.fnc.value + '&prv=' + document.bodyform.prv.value + '&src=' +document.bodyform.src.value + '&index=' + (parseInt(document.bodyform.index.value) + change)
			, true
	);
}
function navigateUp()
{
	navigate(
			'Main.action?fnc=' + document.getElementById("upfnc").value + '&prv=8&id=' + document.getElementById("upid").value
			, true
	);
}
function showLoginForm(event, usernameLbl, passwordLbl, loginLbl)
{
	var loginForm = document.getElementById("loginform");
	if (!loginForm)
	{
		loginForm = $(	
			'<div style="z-index: 10006; position: absolute;" id="loginform" class="blackOnWhite tooltip" >\n '+
				'<form name="login" id="login" action="Main.action" method="post" onsubmit="this.password.value=sha1(this.passfield.value.toLowerCase());this.passfield.value=\'\';"> \n' +
					usernameLbl + ' <br /> \n' +
					'<input type="text" name="username" id="loginFormLoginBtn" /> <br /> \n' +
					passwordLbl + ': <br/> \n' +
					'<input type="password" name="passfield" /> <br /> \n' +
					'<input type="hidden" name="password" /> \n' +
					'<input type="submit" value="'+loginLbl+'" /> \n' +
				'</form>\n' +
			'</div>'
		)[0];
		document.body.appendChild(loginForm);
	}
	else
	{
		loginForm.parentNode.removeChild(loginForm);
		return;
	}
	var x = event.clientX;
	var y = event.clientY;
	// Bepaal de positie van de tooltip.
	if (loginForm.scrollHeight < y)
		y = y - loginForm.scrollHeight;
	else
		y += 4;
	x += 10;
	loginForm.style.left = x + "px";
	loginForm.style.top = y + "px";
	document.getElementById("loginFormLoginBtn").focus();
}