// validates form fields given requirements on data that should be entered. Requires external fuctions for specific data validation, 
// exmaple is function is_email(string) which returns true if given value is valid e-mail address. Similar functions are required for
// other data types validation
// params:
// fields - array of tuples specifying field name and expected value format
// examples:
// validateform([['name_field','string'], ['email_field','email']]);
function validateForm(fields) {
	var errorCount = 0;

	for (i in fields) {
		try {
			e=document.getElementById(fields[i][0]);
			ret=false;
			eval("ret=is_"+fields[i][1]+"('"+e.value+"');");
			
			if (!ret) {
				e.style.border="2px dotted #B1953A";
				++errorCount;
			}
		}
		catch (exception) {
			++errorCount;
			alert(exception);
		}
	}

	return errorCount == 0;
}

// validates given string checking if it forms a valid e-mail address. Returns TRUE on success, FALSE otherwise
function is_email(value) {
	if ((value == "") || (value == undefined)) {
		return false;
	}

	if (RegExp) {
		var pat = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pat.test(value);
	}
	else {
		var ind = value.idexOf("@");
		return (ind != -1) && (value.indexOf(".", ind+1) != -1);
	}
}

// hardcoded form submission checking function
function submitForm(frm) {
	var e=document.getElementById(frm);
	
	if (!e) {
		show_user_message("Page not properly loaded", "warning");
		return;
	}
	
	if (validateForm([['email_f','email']]))
		e.submit();
	else
		show_user_message("Please provide your e-mail address", "information");
}

// shows system wide user messages
// requires a DIV tag with ID named "main_center" where it places message content
function show_user_message(message, type) {
	var elem = document.getElementById("main_center");
	
	if (!elem)
		return;

	var usr_msg_block = document.getElementById("user_message");
	
	if (usr_msg_block) {
		children_c = usr_msg_block.childNodes.length;
		
		for (i = 0; i < children_c; ++i)
			usr_msg_block.removeChild(usr_msg_block.childNodes.item(0))
	}
	else {
		usr_msg_block = document.createElement("div");
		usr_msg_block.setAttribute("class", "user_message");
		usr_msg_block.setAttribute("id", "user_message");
	}
	
	var img = document.createElement("img");
	img.setAttribute("src", "images/ui/icon_"+type+".png");
	usr_msg_block.appendChild(img);
	usr_msg_block.appendChild(document.createTextNode(message));
	elem.insertBefore(usr_msg_block, elem.childNodes.item(0));
}
