function formOnClickChoice( el )
{
	if ( typeof( el ) == 'string' ) el = $( el );
	el.checked = ( el.getAttribute( 'mandatory' ) || !el.checked );
	return false;
}

function setSimpleDateValue ( id )
{
	el_day = $(id+"_d");
	el_month = $(id+"_m");
	el_year = $(id+"_y");
	el = $(id);
		
	el.value = el_day.value + "-" + el_month.value + "-" + el_year.value;
}

function focusForm( frm )
{
	for ( var i = 0; i < frm.length; i++ )
	{
		if ( ( frm[i].tagName == 'INPUT' || frm[i].tagName == 'TEXTAREA' ) && frm[i].type != 'hidden' && frm[i].type != 'button' && frm[i].value == '' )
		{
			try
			{
				frm[i].focus();
				return;
			}
			catch( errorObject )
			{
			}
		}
	}
}

function submitForm( frm )
{
	if ( !validateForm( frm ) ) return false;

	// Set the target if any
	if ( frm.getAttribute( 'formtarget' ) ) frm.setAttribute( 'target', frm.getAttribute( 'formtarget' ) );

	disableSubmit();
	
	return true;
}

function disableSubmit()
{
	// Without the timeout 'idButtonSubmit' is not set in the $_POST array
	setTimeout( 'if ( $( "idButtonSubmit" ) ) $( "idButtonSubmit" ).disabled = true;', 100 );
	// Hide cancel
	setTimeout( 'if ( $( "idButtonCancel" ) ) $( "idButtonCancel" ).style.display = "none";', 100 );
}

function validateForm( frm )
{
	var bValid	= true;

	for ( var i = 0; i < frm.length; i++ )
	{
		// Skip buttons fields
		if ( frm[i].tagName == 'INPUT' && ( frm[i].type == 'button' || frm[i].type == 'submit' ) ) continue;
		if ( frm[i].tagName == 'BUTTON' ) continue;

		bValid = bValid && validateElement( frm[i] );

		if ( !bValid )
		{
			markElement( frm[i], true );
			eventCancel();
			return bValid;
		}
		markElement( frm[i], false );
	}

	return bValid;
}

function setFeedback( el, value )
{
	var col;
	var tmp = el;
	var label = el.getAttribute( 'name' );
	while ( !col || !col.length )
	{
		tmp = tmp.parentNode;
		col = tmp.getElementsByTagName( 'label' );
	//	if ( !confirm( 'continue with ' + col.length + '?' ) ) break;
	}

	if ( col.length )
	{
		label = col[0].innerHTML;
		// Remove html and replace 2 or more spaces with one
		label = label.replace( /(<([^>]+)>|\n)/g, ' ' ).replace( /([\s]{2,})/g, ' ' );
		// Remove mandatory
		var pos = label.indexOf( ' *' );
		if ( pos ) label = label.substring( 0, pos );
		// Trim
		label = trim( label );
	}

	// Set feedback element or alert when not found
	if ( !( tmp = $( el.id + '_feedback' ) ) ) alert( lang( 'input not complete or valid for' ) + ' \'' + label + '\'' + ':\n\n' + value );
	else tmp.innerHTML = value;	//.replace( /\\\'/g, '\'' );
}

function markElement( el, mark )
{
	// Set or reset feedback message
	var tmp = $( el.id + '_feedback' );
	if ( tmp )
	{
		// Clear
		if ( mark )
		{
			// Overwrite
			if ( typeof( mark ) == 'string' ) tmp.innerHTML = mark;
			// Set feedback if not set
			if ( !tmp.innerHTML ) tmp.innerHTML = el.getAttribute( 'feedback' );
		}
		// Clear
		else
			tmp.innerHTML = '';
	}
	// Get element
	tmp = el;

	// Get parent div that holds the element
	while ( el.className != 'clsFormElement' && el.className != 'clsFormElementError' && el.parentNode && el.parentNode != el )
		el = el.parentNode;

	if ( !el ) return;
	el.className = ( mark ? 'clsFormElementError' : 'clsFormElement' );

	try {
		if ( mark && el.scrollIntoView ) el.scrollIntoView();
	}
	catch ( e )
	{
		alert( 'Het formulier bevat een element (' + tmp.tagName + ', ' + tmp.className + ', ' + tmp.title + ') met een fout, maar door een onbekende oorzaak (' + e.message + ') kan het element niet getoond worden.' + '\n\n' + tmp.innerHTML );
	};
}

function validateElement( el )
{
//	setFeedback( el,  el.tagName + ', ' + el.id + ', value: ' + el.value + ', mandatory: ' + el.getAttribute("mandatory") );

	// Trim text inputs
	if ( ( el.getAttribute("type") == 'text' || el.getAttribute("type") == 'hidden' ) && el.value != null ) el.value = trim( el.value );

	// Set defaults
//	if ( el.getAttribute("min") == null ) el.setAttribute("min",null);
//	if ( el.getAttribute("max") == null ) el.setAttribute("max",null);
	
//	if ( !confirm( el.id + ', value: ' + el.value + ', mandatory: ' + el.getAttribute("mandatory") ) ) die();

	switch( el.getAttribute("mandatory") )
	{
		case 'title':
/*
			// check title
			if ( !textCheckField( el, 1, 255 ) ){
				el.focus();
				return false;
			}
			break;
/**/
		case 'text':

		case 'description':

		case 'textInput':

		case 'url':
		case 'urlInput':

		case 'email':
		case 'emailInput':

		case 'password':
		
		case 'textArea':

		case 'textRichEdit':

		case 'audioRecorder':

		case 'videoRecorder':

		case 'fileInput':

		case 'selectSingleObject':
			
		case 'datepicker':

			// Check selectSingleObject
			if ( el.getAttribute("mandatory") == 'selectSingleObject' && el.value == 0 )
				el.value = '';

			// Check innertext for RichEdit
			if ( el.getAttribute("mandatory") == 'textRichEdit' )
			{
			//	setFeedback( el,  el.tagName + ' - ' + el.id + "\n\n" + el.value );
				var tmp = el.value.toLowerCase();
				tmp = tmp.replace( /^[\n]+/g, '' );
			//	setFeedback( el,  '|' + tmp + '|' );
				if ( !tmp || tmp == '<br>' || tmp == '<br />' || tmp == '<p></p>' || tmp == '<div></div>' || tmp == '<p>&nbsp;</p>' || tmp == '<div>&nbsp;</div>' || tmp == '&#160;' )
					el.innerText = '';
			}
		//	if ( !confirm( el.name + ', ' + el.getAttribute("min") + ', ' + el.getAttribute("max") + ', ' + el.getAttribute("feedback") ) ) die();

			// Check text, no value or check requirements
			if ( el.value == '' || !textCheckField( el, el.getAttribute("min"), el.getAttribute("max"), true, el.getAttribute("feedback") ) )
			{
				focusElement( el );
				return false;
			}

			break;

		case 'select':

		case 'listClickSelect':
		
		case 'listDClickSelect':
		
		case 'listButtonSelect':
		
		case 'listSmartSelect':

			// Check select
			if ( !selectCheckField( el, el.getAttribute("min"), el.getAttribute("max"), true, el.getAttribute("feedback") ) )
			{
				focusElement( el );
				return false;
			}
			break;

		case 'singleCheck':

			if ( !el.checked )
				setFeedback( el,  ( el.getAttribute( 'feedback' ) == '' ) ? 'Check the checkbox by clicking it' : el.getAttribute( 'feedback' ) );
			return el.checked;
			break;

		case 'listChoice':
		case 'listChoiceOptional':
		case 'listChoiceHorizontal':
		case 'listChoiceOptionalHorizontal':

			// Get all checkboxes with this name
			var els = document.getElementsByName( el.name );

			for ( var i = 0, l = els.length; i < l; i++ )
				if ( els[i].checked ) return true;

			setFeedback( el,  ( el.getAttribute( 'feedback' ) == '' ) ? 'Choose at least one option' : el.getAttribute( 'feedback' ) );
			return false;
			break;

		case 'listCheck':
		case 'listCheckOptional':
		case 'listCheckHorizontal':
		case 'listCheckOptionalHorizontal':

			// Get all checkboxes with this name
			var els = document.getElementsByName( el.name );

			for ( var i = 0, l = els.length; i < l; i++ )
				if ( els[i].checked ) return true;

			setFeedback( el,  ( el.getAttribute( 'feedback' ) == '' ) ? 'Check at least one checkbox' : el.getAttribute( 'feedback' ) );
			return false;
			break;
	/*
		case 'url':
			// check url
			if ( !textCheckURL( el ) ){
				el.focus();
				return false;
			}				
			break;

		case 'email':
			// check email
			if ( !textCheckEmail( el ) ){
				el.focus();
				return false;
			}				
			break;

		case 'location':
			// check location
			if ( !textCheckLocation( el ) ){
				el.focus();
				return false;
			}
			break;

		case 'phone':	
			// Check empty allowed
			if ( el.allowempty != null && el.value == '' ) return true;
			// Check phone number
			if ( !textCheckPhone( el ) ){
				el.focus();
				return false;
			}
			break;
	
		case 'numeric':
			// convert
			el.value = parseInt( el.value );

			// check for a value
			if (  el.value == 'NaN' )
			{
				el.value = '';
				setFeedback( el,  'Invalid or empty numeric value for field' );
				el.focus();
				return false;
			}

			// check within range
			if ( el.min != null ){
				if ( parseInt( el.value ) < parseInt( el.min ) ){
					setFeedback( el,  'Value for ' + el.name + ' should be larger than ' + el.min );
					el.focus();
					return false;
				}
			}
			if ( el.max != null ){
				if ( parseInt( el.value ) > parseInt( el.max ) ){
					setFeedback( el,  'Value for ' + el.name + ' should be smaller than ' + el.min );
					el.focus();
					return false;
				}
			}
			break;

		case 'object':
			// Check if not empty or zero
			if ( el.value == '' || el.value == 0 )
			{
				setFeedback( el,  'No object selected' );
				return false;
			}
			break;
	/**/

		default:
		
		//	setFeedback( el,  el.id + ', value: ' + el.value + ', mandatory: ' + el.getAttribute("mandatory") );

		//	if ( el.getAttribute("mandatory") != '' && el.getAttribute("mandatory") != null && el.getAttribute("mandatory") != false )
		//		setFeedback( el,  'validateElement(): Unrecognized mandatory type: `' + el.getAttribute("mandatory") + '`' );
	}	// switch

	// IE or FF
	var el_min = el.min || el.getAttribute( 'min' );
	var el_max = el.max || el.getAttribute( 'max' );
	var el_sum = el.sum || el.getAttribute( 'sum' );

//	if ( !confirm( 'min: ' + el_min + ', max: ' + el_max + ', sum: ' + el_sum ) ) die();

	// Number with min or max or sum
	if ( el.value && ( el_min != null || el_max != null || el_sum != null ) )
	{
		// Convert number
		el.value = parseInt( el.value );

		// Check for a value
		if (  el.value == 'NaN' )
		{
			el.value = '';
			setFeedback( el, lang( 'LSTR_NUMERIC_INVALID' ) );
			el.focus();
			return false;
		}

		// Check min
		if ( el_min != null ){
			if ( parseInt( el.value ) < parseInt( el_min ) ){
				setFeedback( el, lang( 'LSTR_NUMERIC_LARGER_THAN' ).replace( /%1/, el_min ) );
				el.focus();
				return false;
			}
		}

		// Check max
		if ( el_max != null ){
			if ( parseInt( el.value ) > parseInt( el_max ) ){
				setFeedback( el, lang( 'LSTR_NUMERIC_SMALLER_THAN' ).replace( /%1/, el_max ) );
				el.focus();
				return false;
			}
		}

		// Check sum
		if ( el_sum != null ){
		//	if ( !confirm( 'sum, id: ' + el.id + ', name: ' + el.name ) ) die();

			var tmp = nr = sum = 0;
			var id = el.name.substr( 0, el.name.indexOf( '[' ) );

			while ( tmp = $( id + '[' + nr++ + ']' ) )
				sum += parseInt( tmp.value );

			if ( sum != parseInt( el_sum ) ){
				setFeedback( el, lang( 'LSTR_NUMERIC_SUM_SHOULD_BE' ).replace( /%1/, el_sum ) );
				el.focus();
				return false;
			}
		}
	}	// number

	// Check for regular expression, and make sure 
	if ( el.getAttribute("regexp") != null && el.getAttribute("regexp") != '' && el.value != '' && el.value != 'http://' )
	{
		// Set regular expression
	//	setFeedback( el,  'var oRegExp = ' + el.getAttribute("regexp") + ';' );
		eval( 'var oRegExp = ' + el.getAttribute("regexp") + ';' );

		// Check any regular expression
		if ( oRegExp != null && oRegExp != '' )
		{
			if ( !oRegExp.test( el.value ) )
			{
				if ( el.getAttribute("feedback") != null && el.getAttribute("feedback") != '' )
					setFeedback( el,  el.getAttribute("feedback") );
				else
					setFeedback( el,  'Input did not match the required pattern, please try again' );

				focusElement( el );

				return false;
			}
		}
	}

	return true;
}

function focusElement( el )
{
	// Focus editor
	if ( el.getAttribute("mandatory") == 'textRichEdit' )
	{
		if ( !el.getAttribute("setfocus") ) return;
		el = FCKeditorAPI.GetInstance(el.getAttribute("setfocus"));
		if ( !el ) return;
		try
		{
			// Does not work
//			el.Focus();
			// Insert nothing to set focus since method `Focus()` does not work
			el.InsertHtml('');
		}
		catch ( e )
		{
			alert( 'Fout in focusElement() tijdens el.Focus();' );
		}
		return;
	}

	// Change element to focus
	if ( typeof( el.getAttribute("setfocus") ) == 'string' && el.getAttribute("setfocus") != '' )
		el = $( el.getAttribute("setfocus") );

	// Focus element
	try
	{
		if ( el.focus ) el.focus();
		if ( el.scrollIntoView ) el.scrollIntoView();
	}
	catch( e )
	{
		// Try tabs
		tmp = el;

		while ( el && el.parentNode && el.parentNode != el && el.tagName != 'FORM' && el.className != 'dhtmlgoodies_aTab' )
		{
			el = el.parentNode;
//			if ( !confirm( el.tagName + ', ' + el.className ) ) die();
		}

		if ( window.showTab && el && el.className && el.className == 'dhtmlgoodies_aTab' )
		{
			// Get tabs id
			var parentId = el.id.substring( 7, el.id.lastIndexOf( '_' ) );
			var tabIndex = el.id.substring( el.id.lastIndexOf( '_' ) + 1 );
			showTab( parentId, tabIndex );
			setTimeout( function() { focusElement( tmp ); tmp = null; }, 100 );
		}
		else
		{
			alert( 'De focus kon niet naar het gewenste element worden gezet (' + tmp.tagName + ', ' + tmp.className + ', ' + tmp.name + '). ' + '\n\n' + tmp.innerHTML);
		}
	}
}

function textCheckField( el, minsize, maxsize, morecheck, errmsg )
{
	if ( morecheck == null ) morecheck = 1;
	if (maxsize == null) {
		if (el.value.length < minsize) {
			if (errmsg && errmsg != '' ) setFeedback( el, errmsg);
			else setFeedback( el, 'the text-field must be at least ' + minsize + ' characters long');
			return false;
		}
		else return morecheck;
	}
	else {
		if (el.value.length < minsize || el.value.length > maxsize) {
			if (errmsg && errmsg != '' ) setFeedback( el, errmsg);
			else setFeedback( el, 'the text-field must be within specified bounds');
			return false;
		}
		else return morecheck;
	}
}

function selectCheckField( selection, minselected, maxselected, morecheck, errmsg )
{
	if ( morecheck == null )	morecheck	= 1;
	if ( minselected == null )	minselected	= 1;
	if ( maxselected == null )	maxselected	= -1;
	
	// Count selected
	var count = 0;
	for (var i = 0; i < selection.options.length; i++ )
		if ( selection.options[i].selected ) count++;

	// Minimum selected and less than max or no max
	if ( count >= minselected && ( count <= maxselected || maxselected == -1 ) )
	{
		return morecheck;
	}
	else
	{
		if (errmsg) alert(errmsg);
		else alert('you should select more than ' + minselected + ( ( maxselected == -1 ) ? '' : ' and less than ' + maxselected ) + ' items in one of the required select-boxes' );
		return false;
	}
}

function textCheckEmail(text,morecheck,errmsg) {
	if ( morecheck == null ) morecheck = 1;
	if (text.value.length == 0 ) {
		if ( errmsg ) alert( errmsg );
		else alert( 'empty field for email' );
		return false;
	}
	else {
		var emailRegExp = /^[A-z0-9][A-z0-9-\.]+@(([A-z0-9][A-z0-9-]+)\.)+[A-z]{2,4}$/;
		if (!emailRegExp.test(text.value)) {
			if ( errmsg ) alert( errmsg );
			else alert('invalid e-mail address, please try again');
			return false;
		} else {
			return morecheck;
		}
	}
}

function textCheckURL(text,morecheck,errmsg) {

	if ( morecheck == null ) morecheck = 1;
	if (text.value.length == 0 ) {
		if ( errmsg ) alert( errmsg );
		else alert( 'empty field for url' );
		return false;
	}
	else {
		//						type			login : pass	@	servername	.	extension	/		anything
		var urlRegExp = /^(https|http|ftp):\/\/(((\w+):(\w+)@)*)([a-z0-9\.\-]+)(\.+)([a-z0-9]{2,4})((\/)*)(.*)$/i;
		if (!urlRegExp.test(text.value)) {
			if ( errmsg ) alert( errmsg );
			else alert('invalid url address, please try again');
			return false;
		} else {
			return morecheck;
		}
	}
}

function isURL( text )
{
		//						type			login : pass	@	servername	.	extension	/		anything
		var urlRegExp = /^(https|http|ftp):\/\/(((\w+):(\w+)@)*)([a-z0-9\.\-]+)(\.+)([a-z0-9]{2,4})((\/)*)(.*)$/i;
		return urlRegExp.test( text );
}

function textCheckLocation(text,morecheck,errmsg) {

	if ( morecheck == null ) morecheck = 1;
	if ( !textCheckField( text, 1, 255, morecheck, errmsg ) ) {
		return false;
	}
	else {
		var locRegExp = /^([a-z]+)([a-z0-9]+)$/i;
		if (!locRegExp.test(text.value)) {
			if ( errmsg ) alert( errmsg );
			else alert('the text-field can only consist of letters and numbers and cannot start with a number');
			return false;
		} else {
			return morecheck;
		}
	}
}

function textCheckPhone(text,morecheck,errmsg) {

	if ( morecheck == null ) morecheck = 1;

	if ( !textCheckField( text, 1, 255, morecheck, errmsg ) ) {
		return false;
	}
	else {
		var phoneRegExp = /^([0-9\+]+)([0-9\- \(\)]+)([0-9]+)$/i;
		if (!phoneRegExp.test(text.value)) {
			if ( errmsg ) alert( errmsg );
			else alert('invalid phone number format');
			return false;
		} else {
			return morecheck;
		}
	}
}

function upload( obj )
{
	if ( f_group.onsubmit() )
	{
		if ( f_group.f_filename.value != '' )
		{
			obj.value		= 'Uploading';
			obj.disabled	= true;
		}
		f_group.submit();
	}
}

function selectDate( oObj )
{
	window.dateElement	= oObj;
	openWindow( ROOT_URL + 'datepicker.html', null, 200, 200 );
}

function selectColor( oObj )
{
  	var color = showModalDialog( ROOT_URL + "widgets/colorpicker/colorpicker.html",
                             "",
                             "font-family:Verdana; font-size:12; dialogWidth:30em; dialogHeight:34em" );

  	if ( color != null ) {
  		oObj.value = color;
  		setColor( oObj );
  	}
}

function setColor( obj ) {
	obj.style.color = ( ( obj.value == '#000000' || obj.value == 'black' ) ? 'white' : 'black' );
	obj.style.backgroundColor = obj.value;
}

function insertDate( oDate )
{
	window.dateElement.value = oDate.getFullYear() + '-' + twoDigits( oDate.getMonth() + 1 ) + '-' + twoDigits( oDate.getDate() );
}

function twoDigits( num )
{
	return ( ( num < 10 ) ? '0' + num : num );
}

function valiDateSimple( id )
{
	var y = $( id + '_y' );
	var m = $( id + '_m' );
	var d = $( id + '_d' );
	var date = new Date( y.value, m.value - 1, d.value );
	y.value = date.getFullYear();
	m.value = twoDigits( date.getMonth() + 1 );
	d.value = twoDigits( date.getDate() );
}

function selectMoveText( source, dest ) {
	if ( source == null || source.tagName != 'SELECT' ) alert( 'selMoveText: source is not an object (' + ( source ? source.tagName : source ) + ')!' );
	if ( dest == null  || dest.tagName != 'SELECT' ) alert( 'selMoveText: destination is not an object!' );
	if ( source == null || dest == null ) return;

	for ( var i = source.options.length-1; i >= 0 ; i-- )
	{
		if ( source.options[i].selected )
		{
			listAddToList( dest, source.options[i].text, source.options[i].value, -1 );
			listDeleteFromList( source, i );
		}
	}
}

function listAddToList( listname, text, value, index ) {
	// Name or object
	if ( typeof( listname ) == 'string' ) listname = $(listname);
	// Value equals text
	value = value || text;
	// Initialize new option values	
	newOption = document.createElement ("OPTION");
	newOption.text = text;
	newOption.value = value;
	// Insert new option at position index
	if ( index == null ) index = listname.options.length;
	listname.options.add(newOption, index);		
}

function listClearAll( list )
{
	for ( var i = list.options.length-1; i >= 0 ; i-- )
		listDeleteFromList( list, i );
}

function listTransferListElems(from, to) {
	while (from.selectedIndex != -1) {
		// last argument can be changed into the position at which the element has to be added			
		listAddToList (to, from.options[from.selectedIndex].text, from.options[from.selectedIndex].value, 0);
		listDeleteFromList (from, from.selectedIndex);
	}
}		

function listTransferAllElems(from, to) {
	for (i=from.options.length-1; i>=0; i--) {
		listAddToList (to, from.options[i].text, from.options[i].value, 0);
		listDeleteFromList (from, i);
	}
}
		
function listToggleDisable(list, edit) {
	if (list.options[list.selectedIndex].value == 0) {
		edit.disabled = false;
	} else {
		edit.disabled = true;
	}
}

function listSelectAll(list) {
	if ( list == null || list.tagName != 'SELECT' ) alert("listSelectAll(): List ("+list+") not found or not an object");
	for ( var i = list.options.length - 1; i >= 0; i-- )
		list.options[i].selected = true;
}

function listDeSelectAll(list) {
	for (var i=list.options.length-1; i>=0; i--) {
		list.options[i].selected = false;
	}
}

function listFindTextValue(list,text) {
	for ( var i = 0; i < list.options.length; i++ )
		if ( list.options[i].text == text ) return list.options[i].value;
	return false;
}

function listFindTextIndex(list,text) {
	for ( var i = 0; i < list.options.length; i++ )
		if ( list.options[i].text == text ) return i;
	return false;
}

function listMergeLists(fixedlist,freelist,targetlist,reqd) {
	var tmp = null;
	count = fixedlist.options.length;
	for (var i = fixedlist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = fixedlist.options[i].value;
		else tmp = tmp + "," + fixedlist.options[i].value;
	}
	for (var i = freelist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = freelist.options[i].value;
		else tmp = tmp + "," + freelist.options[i].value;
	}
	targetlist.value = tmp;
	if (reqd && count <= 0) {
		alert('You must select at least 1 fixed item');
		return false;
	}
	else return true;
}

function listMergeListsMore(fixedlist,freelist,targetlist,morecheck,reqd) {
	var tmp = null;
	count = fixedlist.options.length;
	for (var i = fixedlist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = fixedlist.options[i].value;
		else tmp = tmp + "," + fixedlist.options[i].value;
	}
	for (var i = freelist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = freelist.options[i].value;
		else tmp = tmp + "," + freelist.options[i].value;
	}
	targetlist.value = tmp;
	if (reqd && count <= 0) {
		alert('You must select at least 1 fixed item');
		return false;
	}
	else return (morecheck);
}

function listCopyList(sourcelist,targetlist,reqd) {
	var tmp = null;
	count = sourcelist.options.length;
	for (var i = sourcelist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = sourcelist.options[i].value;
		else tmp = tmp + "," + sourcelist.options[i].value;
	}
	targetlist.value = tmp;
	if (reqd && count <= 0) {
		alert('You must select at least 1 item');
		return false;
	}
	else return true;
}

function listCopyListMore(sourcelist,targetlist,morecheck,reqd) {
	var tmp = null;
	count = sourcelist.options.length;
	for (var i = sourcelist.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = sourcelist.options[i].value;
		else tmp = tmp + "," + sourcelist.options[i].value;
	}
	targetlist.value = tmp;
	if (reqd && count <= 0) {
		alert('You must select at least 1 item');
		return false;
	}
	else return (morecheck);
}

function listFromSelect(selection,targetlist) {
	var tmp = null;
	count = selection.options.length;
	for (var i = selection.options.length-1;i >= 0;i--) {
		if (tmp == null) tmp = selection.options[i].value;
		else tmp = tmp + "," + selection.options[i].value;
	}
	targetlist.value = tmp;
}

function listSelectClear(listSelect,listClear) {
	listSelectAll(listSelect);
	listDeSelectAll(listClear);
	return true;
}

function listTransferGivenElement(from,to,elemValue) {
	var i = 0;
	var j = true;
	while (i < from.options.length && j) {
		if (from.options[i].value == elemValue) j = false;
		else i++;
	}
	if (!j) {
		listAddToList (to, from.options[i].text, from.options[i].value,j);
		listDeleteFromList (from, i);
	}
}

// Returns true if a text is already in the listbox
function listInList(list, value, bExact)
{
	bExact = bExact || true;

	for ( var i = 0; i < list.options.length; i++ )
		if ( bExact && list.options[i].text == value ) return true;
		if ( !bExact && list.options[i].text.toLowerCase() == value.toLowerCase() ) return 
	return false;
}

function listDeleteFromList( listname, index )
{
	listname.remove( index );
}

function getRadioValue( radio )
{
	for ( var i = 0; i < radio.length; i++ )
		if ( radio[i].checked ) return radio[i].value;
}

// buggy?
function listDeleteSelectedList(listname) {
	while (listname.selectedIndex)
		listDeleteFromList (listname, listname.selectedIndex);
}

function smartListChange( list, text, event )
{
	if ( list.options.length == 0 ) return false;

	var bCancel = true;

	switch ( event.keyCode )
	{
		// Comma
		case 188:

		// Enter
		case 13:
		// Arrow right
		case 39:
			if ( list.ondblclick )
			{
				var i = list.options.selectedIndex;
				list.ondblclick();
				list.options.selectedIndex = i;
			}
			text.value = '';
			break;

		// Arrow up
		case 38:
			list.options.selectedIndex = ( ( list.options.selectedIndex == 0 ) ? list.options.length - 1 : list.options.selectedIndex - 1 );
			text.value = list.options[list.options.selectedIndex].text;
			break;

		// Arrow down
		case 40:
			list.options.selectedIndex = ( ( list.options.selectedIndex == list.options.length - 1 ) ? 0 : list.options.selectedIndex + 1 );
			text.value = list.options[list.options.selectedIndex].text;
			break;

		default:
			bCancel = false;
	}

	if ( bCancel ) return eventCancel();

	// Try select match, cancel previous
	if ( list.selectTimeout ) clearTimeout( list.selectTimeout );
	list.selectTimeout = setTimeout( function() { smartListSelect( list, text, event ); }, 200 );

}	// smartListChange()

function smartListSelect( list, text, event )
{
	var t = text.value, tl = t.length, lt = t.toLowerCase();
	var o = list.options, ol = o.length;
	// Node, node text, match, partial match and last match
	var n = nt = m = pm = lm = null;

	if ( !tl ) return;
//	alert( 'search for `' + lt + '`' );

	// Starts with
	for ( var i = 0; i < ol; ++i )
	{
		n = o[i];
		// Search text
		if ( t )
		{
			nt = n.text.toLowerCase();
			if ( nt.substring( 0, tl ) == lt )
			{
			//	alert( 'found exact for `' + lt + '` in `' + nt + '`' );
				m = i;
				n.setAttribute( 'smartListSelect', 1 );
				n.selected = true;
				return;
			}
			// Partial match not set yet
			else if ( !pm && nt.indexOf( lt ) > -1 )
			{
			//	alert( 'found partial for `' + lt + '` in `' + nt + '`' );
				pm = i;
			}
		}
		// Unset selected
		else if ( n.selected )
		{
			// Last match
			if ( n.getAttribute( 'smartListSelect' ) )
			{
				alert( 'reset old, save last match' );
				n.setAttribute( 'smartListSelect', null );
				lm = i;
			}
			n.selected = false;
		}
	}
	
	// No return, so no exact match, try partial or last match
	if ( pm || lm )
	{
	/**
		// No return, so no exact match, try partial match		
		if ( pm )
			alert( 'no exact, but partial' );
		// No return, no partial match, try last match
		else if ( lm )
			alert( 'no exact, no partial, but last match' );
	/**/
		i = pm || lm;
		n = o[i];
		n.setAttribute( 'smartListSelect', 1 );
		n.selected = true;
	}
}	// smartListSelect()

function fillRandom( id ) {
	var ids = new Array();
	var frm = document.forms[id];
	var col = frm.getElementsByTagName( "INPUT" );
	for ( var c = 0, l = col.length, el; c < l; ++c )
	{
		el = col[c];
		if ( el.type.toString().match( /(hidden|button|submit)/i ) ) continue;

		// Process unique names
		if ( ids[el.name] ) continue;
		ids[el.name] = true;

		switch ( el.type )
		{
			case "radio":
				var tmp = document.getElementsByName( el.name );
				var i = Math.floor( Math.random() * tmp.length );
				tmp[i].checked = "checked";
				break;

			case "checkbox":
				var tmp = document.getElementsByName( el.name );
				for ( var i = 0, tl = tmp.length; i < tl; ++i )
					tmp[i].checked = ( Math.round( Math.random() ) ? "checked" : false );
				break;

			case "text":

				el.value = randomString();

			default:
				continue;
		}
	}	// for
	
	var col = frm.getElementsByTagName( "TEXTAREA" );
	for ( var c = 0, l = col.length, el; c < l; ++c )
		col[c].value = randomString();
}	// fillRandom()

function randomString( length ) {
	length = length || 8;
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var str = "";
	for ( var i = 0; i < length; i++ )
	{
		var rnum = Math.floor( Math.random() * chars.length );
		str += chars.substring( rnum, rnum + 1 );
	}
	return str;
}
function setDirty()
{
	window.isDirty = true;
}

function unsetDirty()
{
	window.isDirty = false;
}

function unloadCanceled()
{
	unsetDirty();
//	alert( 'User canceled unload' );
	var div = document.createElement( 'DIV' );
	div.id = 'idSaveForm';
	div.className = 'clsInformation';
	div.style.margin = '10px';
	div.innerHTML = '<a href="javascript:;" onclick="saveForm();">' + lang( 'LSTR_CLICK_HERE_TO_SAVE_CHANGES' ) + '</a>';
	document.body.insertBefore( div, document.body.firstChild );
}

function checkDirty()
{
	if ( window.isDirty == true )
	{
		var msg = '------------------------------------------------------------------------------------------------------------\n';
		msg += lang( 'LSTR_CHANGES_NOT_SAVED_CONTINUE' );
		msg += '\n------------------------------------------------------------------------------------------------------------';
//		if ( !confirm( msg ) ) eventCancel();
		setTimeout( 'unloadCanceled();', 100 );
		return msg;
	}
}

function tableElementInsertRow( obj )
{
	// Get row
	var row = obj.parentNode.parentNode;
	// Insert clone
	var clone = insertCloneAfter( row, row );
	// Clear event
	obj.onfocus = null;

	// Get inputs
	var col = clone.getElementsByTagName( 'INPUT' );
	
	if ( col.length == 0 ) return;
	
	// Get next
	var nr;
	if ( nr = col[0].name.match( /\[([0-9]+)\]/ ) ) nr = parseInt( nr[1] );

	// Set next nr for inputs
	for ( var c = 0, l = col.length; c < l; ++c )
		col[c].name = col[c].name.replace( "[" + nr + "]", "[" + ( nr + 1 ) + "]" );
}
