//============================================================================
function VSCSM_SetError( control_id, msg ) {
	var e = document.getElementById( control_id + '_Error' ) ;
	if( e ) {
		if( msg != '' ) {
			e.innerHTML = "! " + msg ;
			e.style.display = 'inline' ;
		} else {
			e.innerHTML = '' ;
			e.style.display = 'none' ;
		}
	}
}

function VSCSM_ClearError( control_id ) {
	VSCSM_SetError( control_id, '' );
}

function VSCSM_GetControlErrorMessage(control_id, error_code, default_error_message) {
	//Error message will be in the DIV with ID={control_id}_MSG_{error_code}
	var error_message = default_error_message ;
	if ( error_code ) {
		if( error_code != '' ) {
			var ctrl_id = control_id + "_msg_" + error_code ;
			var error_msg_div = document.getElementById( ctrl_id );
			if ( error_msg_div ) {
				error_message = error_msg_div.innerHTML ;
			}
		}
	}
	return error_message;
}

function VSCSM_RemoveSpaces( str ) {
	var result = '' ;
	for( var i = 0 ; i < str.length ; i++ ) {
		var c = str.charAt( i ) ;
		if( c > ' ' ) {
			result += c ;
		}
	}
	return( result ) ;
}

//============================================================================
// Auxilary functions

function VSCSM_IsEmpty( text ) {
	return( (text == null) || (text.length == 0) ) ;
}

function VSCSM_IsInteger( text ) { 
	filter = /^\d+$/;
	return( filter.test( text ) ) ;
}

var daysInMonth = [ 0, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] ;
var MonthsShortNames = [ 'jan', 'feb', 'apr', 'mar', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] ;
var KnownDateInputFormats = [ '(\\d+)-(\\d+)-(\\d+)', '(\\d+)/(\\d+)/(\\d+)', '(\\d+)[ -](\\w+)[ ,](\\d+)', '(\\w+) (\\d+),? ?(\\d+)' ] ;
var KnownDateOutputFormats = [ '$3|$2|$1', '$3|$1|$2', '$3|$2|$1', '$3|$1|$2' ] ;

function VSCSM_DaysInFebruary( year ) {   // February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return( ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 ) ;
}

//============================================================================

function VSCSM_CheckMandatory( control_id, error_code ) {
	var result = false ;
	var DVEM_MANDATORY = 'Field is mandatory';
	var elements = document.getElementsByName( control_id ) ;
	if( elements.length > 0 ) {
		for( var i = 0 ; i < elements.length ; i++ ) {
			var element = elements[ i ] ;
			switch( element.type ) {
				case 'text' :
				case 'password' :
				case 'hidden' :
				case 'textarea' :
				case 'select-multiple' :
				case 'select-one' :
					if( !VSCSM_IsEmpty( element.value ) ) {
						result = true ;
					}
					break;
				case 'checkbox' :
				case 'radio' :
					if( element.checked ) {
						result = true ;
					}
					break ;
			}
		}
		if( !result ) {
			VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage( control_id, error_code, DVEM_MANDATORY ) ) ;
		}
	}
	return( result ) ;
}

function VSCSM_CheckFieldLength( control_id, min_symbols, max_symbols, error_code ) {
	var result = true ;
	var DVEM_FIELD_LENGHT_RANGE = 'Det indtastede er enten for langt eller for kort.';
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		if( !VSCSM_IsEmpty( control.value ) ) {
			result = control.value.length >= min_symbols && ( max_symbols == 0 || control.value.length <= max_symbols ) ;
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, DVEM_FIELD_LENGHT_RANGE) );
			}
		}
	}
	return( result ) ;
}

function VSCSM_CheckFieldLengthWS( control_id, min_symbols, max_symbols, error_code ) {
	var result = true ;
	var DVEM_FIELD_LENGHT_RANGE = 'Field length is not in allowed range.';
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		if( !VSCSM_IsEmpty( control.value ) ) {
			var value = VSCSM_RemoveSpaces( control.value ) ;
			result = value.length >= min_symbols && ( max_symbols == 0 || value.length <= max_symbols ) ;
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, DVEM_FIELD_LENGHT_RANGE) );
			}
		}
	}
	return( result ) ;
}

// Function will either return valid_symbols parameter if it is not empty or
// predefined valid symbols string otherwise.
function VSCSM_GetValidSymbols(valid_symbols) {
	if ( valid_symbols ) {
		if ( valid_symbols!='') {
			 return valid_symbols;
		}
	}

	// Supposed, that real sequence of valid chars will be here instead of cycle.
	valid_symbols='';
	for( var i = 32; i < 127; i++ ) {
		valid_symbols += String.fromCharCode( i );
	}
	return( valid_symbols ) ;
}

function VSCSM_CheckValidSymbols( control_id, valid_symbols, error_code ) {
	var result = true ;
	var DVEM_NOT_VALID_SYMBOL = 'Mindst et af de indtastede tegn er ulovligt i dette felt.';
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		var control_text = control.value;
		if( !VSCSM_IsEmpty( control.value ) ) {
			valid_symbols = VSCSM_GetValidSymbols( valid_symbols );
			for( var i = 0 ; i < control_text.length ; i++ ) {
				var ch = control_text.charAt(i);
				if( valid_symbols.indexOf( ch ) == -1 ) {
					result = false ;
					break;
				}
			}
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, DVEM_NOT_VALID_SYMBOL) );
			}
		}
	}
	return( result);
}

function VSCSM_CheckControlForRegExp(control_id, filter, error_code, default_error_message) {
	var result = true ;
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		if( !VSCSM_IsEmpty( filter ) && !VSCSM_IsEmpty( control.value ) ) {
			result = filter.test( control.value );
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, default_error_message) );
			}
		}
	}
	return( result );
}

function VSCSM_CheckEmailsList( control_id, error_code ) {
	var result = true ;
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		var val = control.value ;
		if( !VSCSM_IsEmpty( val ) ) {
			var i ;
			var err = '' ;
			var err_msg = VSCSM_GetControlErrorMessage( control_id, error_code, 'E-mail addressen "{email}" findes ikke i databasen.' ) ;
			var filter = /^[a-z0-9][a-z0-9_.-]*@(?:[a-z0-9][a-z0-9-_]*\.)+(?:[a-z]{2,4})$/i ;
			var vals = val.split( '\r\n' ) ;
			for( i = 0 ; i < vals.length ; i++ ) {
				var v = vals[ i ] ;
				if( !VSCSM_IsEmpty( v ) ) {
					if( !filter.test( v ) ) {
						err += err_msg.replace( '{email}', v ) + '<br/>' ;
						result = false ;
					}
				}
			}
			if( !result ) {
				VSCSM_SetError( control_id, err ) ;
			}
		}
	}
	return( result );
}

function VSCSM_CheckEmail( control_id, error_code ) {
	var VF_EMAIL   = /^[a-z0-9][a-z0-9_.-]*@(?:[a-z0-9][a-z0-9-_]*\.)+(?:[a-z]{2,4})$/i;
	var DVEM_EMAIL = 'Det indtastede er ikke en gyldig e-mail adresse.' ;
	return( VSCSM_CheckControlForRegExp( control_id, VF_EMAIL, error_code, DVEM_EMAIL ) );
}

function VSCSM_CheckInteger( control_id, error_code ) {
	var VF_INT = /^\d+$/;
	var DVEM_INT = 'Fejl - tallet er ikke et heltal.' ;
	return( VSCSM_CheckControlForRegExp(control_id, VF_INT, error_code, DVEM_INT) );
}

function VSCSM_CheckIntegerRange( control_id, min_value, max_value, error_code ) {
	var result = true ;
	var DVEM_INT_RANGE = 'Fejl - tallet er ikke i det tilladte interval.' ;
	var control = GetNamedElement( control_id ) ;
	if( control ) {
		if( !VSCSM_IsEmpty( control.value ) && VSCSM_IsInteger( control.value ) ) {
			var val = parseInt( control.value ) ;
			if( ( min_value != null && val < min_value )
				|| ( max_value != null && val > max_value ) ) {
				result = false;
			}
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, DVEM_INT_RANGE) );
			}
		}
	}
	return( result );
}

function VSCSM_CheckFloat( control_id, error_code ) {
	var VF_FLOAT = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
	var DVEM_FLOAT = 'Fejl - tallet er ikke et flydende tal.' ;
	return( VSCSM_CheckControlForRegExp( control_id, VF_FLOAT, error_code, DVEM_FLOAT) );
}


function VSCSM_ConvertYear(year) {
	var result = null;
	if( VSCSM_IsInteger(year) ) {
		year = parseInt( year, 10 ) ;
		if( year<100 ) {
			result = year>70 ? year + 1900 : year + 2000;
		} else {
			result = year;
		}

	}
	return result;
}

function VSCSM_ConvertMonth(month) {
	var result = null;
	if( VSCSM_IsInteger(month) ) {
		month = parseInt( month, 10 ) ;
		if( month>=1 && month<=12 ) {
			result = month;
		}
	} else {
		// here should go convertion from text versions of months to internal number representation.
		if( month.length == 3 ) {
			var month_name = month.toLowerCase();
			for( var m=1; m<=12; m++ ) {
				if( month_name == MonthsShortNames[m] ) {
					result = m;
					break;
				}
			}
		}
	}
	return result;
}

function VSCSM_IsDay(day, int_month, int_year) {
	var result = false;
	if( VSCSM_IsInteger(day) ) {
		day = parseInt( day, 10 ) ;
		var days_in_month = (int_month==2) ? VSCSM_DaysInFebruary(int_year) : daysInMonth[int_month];
		if( day>=1 && day<=days_in_month ) {
			result = true;
		}
	}
	return result;
}

function VSCSM_ConvertDateFormat( text, in_format, yymmdd_format ) {
	var result = null;
	var re = new RegExp(in_format);
	if( re.test(text) ) {
		var converted = text.replace(re, yymmdd_format);
		var date_parts_array = converted.split("|");
		var year = VSCSM_ConvertYear(date_parts_array[0]);
		var month = VSCSM_ConvertMonth(date_parts_array[1]);
		if( year && month ) {
			if( VSCSM_IsDay(date_parts_array[2], month, year) ) {
				result = "" + year + "/" + month + "/" + parseInt(date_parts_array[2],10) ;
			}
		}
	}
	return result;
}

function VSCSM_CheckDate( control_id, error_code ) {
	var result = true ;
	var DVEM_DATE = 'Fejl - datoen er ikke gyldig.';
	var control = GetNamedElement( control_id ) ;
	var new_date_value = null;
	if( control ) {
		if( !VSCSM_IsEmpty( control.value ) ) {
			result = false ;
			for( var format=0; format < KnownDateInputFormats.length; format++ ) {
				new_date_value = VSCSM_ConvertDateFormat(control.value, KnownDateInputFormats[format], KnownDateOutputFormats[format]);
				if( new_date_value ) {
					result = true;
					break;
				}
			}
			if( !result ) {
				VSCSM_SetError( control_id, VSCSM_GetControlErrorMessage(control_id, error_code, DVEM_DATE) );
			}
		}
	}
	return( result );
}

function VSCSM_SelectionCount( control_id ) {
	var result = 0 ;
	var list = document.getElementsByName( control_id ) ;
	for( var i = 0 ; i < list.length ; i++ ) {
		if( list[ i ].checked ) {
			result++ ;
		}
	}
	return( result ) ;
}

function VSCSM_ErrorAlert() {
	var list = document.getElementsByTagName( 'div' ) ;
	for( var i = 0 ; i < list.length ; i++ ) {
		var id = list[ i ].id ;
		var l = id.length ;
		var id1 = id.substr( l - 6, 6 ) ;
		if( id1 == '_Error' && !VSCSM_IsEmpty( list[ i ].innerHTML ) ) {
			alert( g_common_msg_error_alert ) ;
			break ;
		}
	}
}
