/*	Some functions you'd commonly use in form-checking.
	Martin Warin, Jan 2008
*/

// an isDefined(name) function for js
function isDefined(id){
    return (!(!(document.getElementById(id))));
}

// saves keystrokes
function get(id){
    return document.getElementById(id);
}
function getV(id){
    return get(id).value;
}
function getL(id){
    return getV(id).length;
}

// snabbis for formchecking
function notNull(id){
    if(!get(id)){
		alert("Es gibt gar nicht " + id);
		return false;
    }
    if(get(id).value == "" || get(id).value == 0){
		alert(id + " fehlt.");
		get(id).focus();
		return false;
    }
    return true;
}

// perl-style push method
function push(arr, x){
    arr[arr.length] = x;
}

// saves keystrokes when you wanna create a new dom node.
// e.g. var foo = make('select', 'chooseRole');
// or get('myDiv').appendChild(make('br', ''));
function make(type, nameId){
    var e 	= document.createElement(type);
    if(nameId != ""){
	e.name	= nameId;
	e.id 	= nameId;
    }
    return e;
}

/*	validates email address
	e.g., in your formcheck function, you could do:
	if(!emailChecker(get('email'))){
		return false;
	}
*/
function emailChecker(id){
    var email = get(id);
    if( email.value == "" 
	|| !email.value.match(/^.+@.+\..+$/) 
	|| email.value.match(/[^a-zA-Z0-9\.\-_@]/) ){
	alert("Ungültig Email.");
	email.select();
	return false;
    }
    return true;
}

// kollar att en URL e giltig
function urlChecker(addr){	
	if(!getV(addr).match(/^(https?|ftp):\/\/[^.]+.[^.]+/)){
		alert("Ogiltig URL");
		get(addr).select();
		return false;
	}
	return true;
}

// textarea maxlength
// e.g. <textarea ... onKeyPress="return checkLength(event, this.id, 5);"></textarea>
function checkLength(e, id, maxLen){
	if(e.keyCode == 13 || e.charCode != 0){ // only applies to real char-events and ENTER.
		if(get(id).value.length >= maxLen){
			alert("The maximum length for this field is " +maxLen+ " characters.");
			return false;
		}
	}			
	return true;
}
