var tooltip = null;
var tooltiptext = null;
var _name = '';
var _pw = '';
var _email = '';
var _kaptcha = '';
var _confirmpw = '';

//Error definitions used for preValidateName
var NOERROR = 0;
var NORMALERROR = 1;
var NONVALIDCHARSERROR = 2;
var COMMONNAMEINUSEERROR = 3;

var commonNameAlreadyUsed = false;

function readFormData(){

	var formData = document.K19Form.elements;

	for(var i=0; i<formData.length; i++){

		if(formData[i].name == 'value(commonname)'){
			_name = formData[i].value;
		}
		if(formData[i].name == 'value(password)'){
			_pw = formData[i].value;
		}
		if(formData[i].name == 'value(confirmPassword)'){
			_confirmpw = formData[i].value;
		}
		if(formData[i].name == 'value(email)'){
			_email = formData[i].value;
		}
		if(formData[i].name == 'value(kaptcha)'){
			_kaptcha = formData[i].value;

			var _v4 = document.getElementById('v4');

			if(_v4!=null && (_kaptcha==null || _kaptcha=="")){
				_v4.innerHTML = "";
			}
		}
	}
}


function addEvent(obj, evType, fn){
 if (obj.addEventListener){
   obj.addEventListener(evType, fn, false);
   return true;
 } else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
 } else {
   return false;
 }
}
//execute showErrorOnLoad() when site is shown.
addEvent(window, 'load', showErrorOnLoad);
addEvent(window, 'resize', moveTooltipOnResize);
addEvent(window, 'load', readFormData);

//horizontal move the Tooltip on window resize
function moveTooltipOnResize(){

	position = getPosition(document.getElementById('tf1'));
	tooltip.style.left = (position.x + 150) + "px";
}

/*
 function to retrieve effective css style property of a DOM element
 pass DOM element reference, javascript name of CSS property and
 CSS name of property (both are needed for Cross-Browser functionality )
 example usage:
 var obj = document.getElementById("foo");
 var cssValue = GDgetElementStyle( obj, "backgroundColor", "background-color" );
*/

function GDgetElementStyle(elem, StyleProp, CSSStyleProp) {
    if(elem != null){
    	if (elem.currentStyle) {
		return elem.currentStyle[StyleProp];
    	} else if (window.getComputedStyle) {
    	var compStyle = window.getComputedStyle(elem, "");
        return compStyle.getPropertyValue(CSSStyleProp);
    	}
    }
    return "";
}

/* Find the coordinates of an Element */
function getPosition(element){

  var tagname="";
  var x = 0, y = 0;


/* if "element" is an object, run through this loop for "element" and all its offset-parents*/

  while ((typeof(element)=="object")&&(typeof(element.tagName)!="undefined"))
  {
    y += element.offsetTop;     				/* add offset of the element */
    x += element.offsetLeft;    				/* add offset of the element */
    tagname = element.tagName.toUpperCase(); 	/* get tag-name in capitals */

	/* when "body"-tag is reached, set element to "0" to break */
    if (tagname=="BODY"){
    	element=0;
    }


	/*if "element" is an object and contains offsetParent continue with parent*/
    if (typeof(element)=="object")
      if (typeof(element.offsetParent)=="object")
      {
        element=element.offsetParent;

	/* in case we are embedded into a relative positioning CSS layout,
           we should boil out at the first relative positioned element */
        if ( GDgetElementStyle(element, "position", "position" ) == "relative" )
          element = 0;
      }
  }


	/*return element-coordinates*/
 	position = new Object();
 	position.x = x;
 	position.y = y;
 	return position;

}


/*
 *Finds the first Substring containing figueres and converts it to Integer
 *even if the String starts with a non Integer Char.
 */
function gdParseInt(n){

	var tmp = "";

	for(var j=0; j < n.length; j++){
		if( !isNaN(parseInt(n.charAt(j))) ){
			tmp += n.charAt(j);
			if( isNaN(parseInt(n.charAt(j))) ){
				break;
			}
		}
	}
	return parseInt(tmp);
}

//show the icon
function showIcon(id, validate){


	var id_num = gdParseInt(id);
	var v_id = 'v' + (id_num);

	if(id == 'tf1'){

		if(preValidateName(id) != NOERROR){
			document.getElementById(v_id).innerHTML = getImageError();
		}
		else{
			document.getElementById(v_id).innerHTML = getImageValid();

		}
	}

	if(id == 'tf2'){

		if(!preValidatePassword(id)){
			document.getElementById(v_id).innerHTML = getImageError();
		}
		else{
			document.getElementById(v_id).innerHTML = getImageValid();

		}
	}

	if(id == 'tf5'){

		if(!preValidateConfirmPassword()){
			document.getElementById(v_id).innerHTML = getImageError();
		}
		else{
			document.getElementById(v_id).innerHTML = getImageValid();

		}
	}

	if(id == 'tf3'){

		if(!checkEmail(id)){
			document.getElementById(v_id).innerHTML = getImageError();
		}
		else{
			document.getElementById(v_id).innerHTML = getImageValid();

		}
	}

	if(id == 'tf4'){

		if(!preValidateKaptcha(id)){
			document.getElementById(v_id).innerHTML = getImageError();
		}
		else{
			document.getElementById(v_id).innerHTML = getImageValid();

		}
	}
}

//Displays the Tooltips
function showToolTip(toolTipIndex, elementId) {

	var position;
	var temp;

	if((errorStatic[toolTipIndex] == true) && (document.getElementById(elementId).value == _name) && (_name.length > 0)){
		temp = errorText[toolTipIndex];
	}
	else if((errorStatic[toolTipIndex] == true) && (document.getElementById(elementId).value == _email) && (_email.length >0)){
		temp = errorText[toolTipIndex];
	}

	else{
		temp = message[toolTipIndex];
	}
	message[toolTipIndex] = infoText[toolTipIndex];

	//Hack to insert invalid chars message if this error occurs
	var testName = document.getElementById(elementId).value;
	if (elementId == 'tf1' && testName.length > 0 && preValidateName('tf1') == NONVALIDCHARSERROR) {
		temp = errorText[3];
	} else if (elementId == 'tf3' && testName.length > 0 && !checkEmail('tf3')) {
	//Hack to insert invalid mail message if this error occurs
	temp = errorText2[2];
	}

	//change tooltip text
	tooltiptext = document.getElementById('tooltiptext');
	tooltiptext.innerHTML = temp;

	//make tooltip visible
	tooltip = document.getElementById('tooltipcontainer');
	tooltip.style.display = "block";
	tooltiptext.style.display = "block";
	tooltip.style.width = "180px";
	tooltiptext.style.width = "180px";

	//set the tooltip next to the textfield
	position = getPosition(document.getElementById(elementId));
	tooltip.style.left = (position.x + 140) + "px";
	tooltip.style.top  = (position.y) + "px";
}

// send the dwr request for checking if the entered common name is
// is already in use. The response for this request will evoke
// the callback function handleCommonNameInUse.
function performRequestCommonNameInUse() {
	var cn = document.getElementById("tf1").value;
	if (cn == "") {
		return;
	}
	Userservice.isCommonNameInUse(cn, handleCommonNameInUseResult);
}

//make tootip invisble and show icon for current textfield
function hideToolTip(id) {
	if(tooltip != null){
		tooltip.style.display = "none";
	}
	showIcon(id, true);
}

//show icons and first error message when site is shown
function showErrorOnLoad(){

	var v_id;
	var noError = true;
	//prepare Messages/ show Icons
	for(var i=0; i< errors.length; i++){

		 v_id = 'v' + (i+1);

		if(errors[i] == true){
			var element = document.getElementById(v_id);
			if (element != null && element != "" && element != 'undefined'){
				message[i] = errorText[i];
				if(errorOccured() == true){
					document.getElementById(v_id).innerHTML = getImageError();
					noError = false;
				}
			}
		}
		else{
			var element = document.getElementById(v_id);
			if (element != null && element != "" && element != 'undefined'){
				message[i] = infoText[i];
				if(errorOccured() == true){
					document.getElementById(v_id).innerHTML = getImageValid();
				}
			}
		}
	}
	if(noError){
		setInputFocus(document.getElementById('tf1'));
	}

	//show tooltip for first error
	for(var i=0; i< errors.length; i++){
		if(errors[i] == true){
			setInputFocus(document.getElementById("tf"+(i+1)));
			break;
		}
	}
}

function setInputFocus(element){
	if (element != null){
		if(element.parentNode != null){
			if(element.parentNode.parentNode != null){
				if(element.parentNode.parentNode.style.display != 'none'){
					element.focus();
				}
			}
		}
	}
}

//shows error after pre-validation of form data
function showErrorBeforePost(){

	//show tooltip for first error
	for(var i=0; i< errors.length; i++){
		if(errors[i] == true){
			if (typeof(wt_be) != "undefined"){
				var temp = wt_be;
				wt_be = wt_be + webtrekk;
				if(typeof(wt_sendinfo) != "undefined") wt_sendinfo();
				webtrekk="";
				wt_be = temp;
			}
			var element = document.getElementById("tf"+(i+1));
			if (element != null && element != "" && element != 'undefined'){
				element.focus();
			}
			var element = document.getElementById('tf4');
			if (element != null && element != "" && element != 'undefined'){
				element.focus();
				element.blur();
			}
			else {
				var element = document.getElementById('tf3');
				if (element != null && element != "" && element != 'undefined'){
					element.focus();
					element.blur();
				}
			}

			var element = document.getElementById("tf"+(i+1));
			if (element != null && element != "" && element != 'undefined'){
				element.focus();
			}
			break;
		}
	}
}
/*
 * validate E-Mail
 *
 * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
 * http://javascript.internet.com
 */
     function checkEmail(id) {

     var emailStr = document.getElementById(id).value.toString();
               if (emailStr.length == 0) {
                   return false;
               }
               var emailPat=/^(.+)@(.+)$/;
               //var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]a";
               // var specialChars="\\(\\)<>@,;:[������]\'{}`����|�\^\\\\\\\"\\.\\[\\]";
               //var validChars="\[^\\s\/^������\'{}`����|�\^" + specialChars + "\]";
               // var validChars="\[^\\s" + specialChars + "\]";
               //var validChars = "\[a-zA-Z0-9_!#$%&*+/=?~-]";
               var validChars = "\[a-zA-Z0-9]";
               var validCharsSign = "\[a-zA-Z0-9_-]";
               var quotedUser="(\"[^\"]*\")";
               var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
               var atom=validChars + validCharsSign + '*';
               var word="(" + atom + "|" + quotedUser + ")";
               var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
               var userCheckPat=new RegExp("[wW]{3}[\\.][a-zA-z0-9\\-\\_\\.]*");
               var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
               var matchArray=emailStr.match(emailPat);
               if (matchArray == null) {
                   return false;
               }
               var user=matchArray[1];
               var domain=matchArray[2];
               if (user.match(userPat) == null) {
                   return false;
               }
               // added in order to avoid user entries starting with 'www.' for e-mail address
               if (user.match(userCheckPat) != null) {
                   return false;
               } /////////////////////////////////////////////////////////////////////////////
               var IPArray = domain.match(ipDomainPat);
               if (IPArray != null) {
                   for (var i = 1; i <= 4; i++) {
                      if (IPArray[i] > 255) {
                         return false;
                      }
                   }
                   return true;
               }
               var domainArray=domain.match(domainPat);
               if (domainArray == null) {
                   return false;
               }
               var atomPat=new RegExp(atom,"g");
               var domArr=domain.match(atomPat);
               var len=domArr.length;
               if ((domArr[domArr.length-1].length < 2) /*|| (domArr[domArr.length-1].length > 3)*/) {
                   return false;
               }
               if (len < 2) {
                   return false;
               }

               if(errorStatic[gdParseInt(id)-1] == true && document.getElementById(id).value == _email){
					return false;
			   }

               return true;
            }

// End E-Mail

//check the common name
function preValidateName(id){
	var isValid = true;

	// NOTE: this is the js validation of the username.
	// if js is deactivated the validation will be done here:
	// de.gameduell.struts.Util:hasValidChars()
	// make sure to edit both methods if you do.
	//
	// Another validation will be done at
	// com.sferix.model.event.EventPerson:validCn()
	// It'll also be called on deactivated javascript.
	// validCn() is as hard to pass as this javascript validation and not that kind
	// of neglectful like the one in hasValidChars().
	// hasValidChars() seems to be used on several points for several operations
	var validChars = "\[a-zA-Z0-9-_]";

    var quotedUser="(\"[^\"]*\")";
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(" + word + ")*$");

    if (commonNameAlreadyUsed) {
    	return COMMONNAMEINUSEERROR;
    }

    //is username allowed
    if (document.getElementById(id).value.match(userPat) == null) {
		return NONVALIDCHARSERROR;
    }

	//has username valid length
	if(document.getElementById(id).value.length < 3 || document.getElementById(id).value.length > 20){
		return NORMALERROR;
	}

	// if any error from ActionCheck
	if(errorStatic[gdParseInt(id)-1] == true && document.getElementById(id).value == _name){
		return NORMALERROR;
	}

	return NOERROR;
}

//check the password
function preValidatePassword(id){
	var isValid = true;

	if(document.getElementById(id).value.length < 5 || document.getElementById(id).value.length > 10){
		isValid = false;
	}

	// if any error from ActionCheck
	if(errorStatic[gdParseInt(id)-1] == true && document.getElementById(id).value == _pw){
		return false;
	}

	return isValid;
}

//check the confirmed password
function preValidateConfirmPassword(){
	var isValid = true;
	var passwordField1 = document.getElementById('tf2');
	var passwordField2 = document.getElementById('tf5');


	if(passwordField2!=null && (passwordField2.value.length==0 || passwordField1.value!=passwordField2.value)){
		isValid = false;
	}

	return isValid;
}



//check the kaptcha code
function preValidateKaptcha(id){
	var isValid = true;
	var kaptchaField = document.getElementById(id);

	// length of capture code will be set in web.xml
	if(kaptchaField!=null && kaptchaField.value.length != 5){
		isValid = false;
	}

	return isValid;
}

// The callback function for the call to Userservice.isCommonNameInUse
// in hideToolTip. If the name is in use show the error icon and the
// correct error tooltip.
function handleCommonNameInUseResult(result) {
	if (result == false) {
		commonNameAlreadyUsed = false;
		if (preValidateName("tf1") == NOERROR) {
			document.getElementById("v1").innerHTML = getImageValid();
		}
	} else {
		document.getElementById("v1").innerHTML = getImageError();
		message[0] = errorText[0];
		commonNameAlreadyUsed = true;
	}



	// any special handling for showErrorOnLoad? (in which context is that function called
	// anyway?)

}

//validate form data
function preValidateAll(){
	var isValid = true;
	var preValName = preValidateName('tf1');
	if(preValName != NOERROR){
		isValid = false;
		errors[0] = true;

		if(document.getElementById('tf1') == _name || preValName == COMMONNAMEINUSEERROR){
			message[0] = errorText[0];
		} else if (preValName == NONVALIDCHARSERROR){
			message[0] = errorText2[3];
			webtrekk += errorWebtrekk[1];
		} else {
			message[0] = errorText2[0];
			webtrekk += errorWebtrekk[0];
		}
		if (blacklistError == "noAllowed") {
			message[0] = errorText[4];
		}
		document.getElementById('v1').innerHTML = getImageError();
	}
	else{
		errors[0] = false;
		message[0] = infoText[0];
		document.getElementById('v1').innerHTML = getImageValid();
	}

	if(!preValidatePassword('tf2')){
		isValid = false;
		errors[1] = true;
		message[1] = errorText2[1];
		webtrekk += errorWebtrekk[2];
		document.getElementById('v2').innerHTML = getImageError();
	}
	else{
		errors[1] = false;
		message[1] = infoText[1];
		document.getElementById('v2').innerHTML = getImageValid();

	}

	var element = document.getElementById('tf5');
	if (element != null && element != 'undefined'){
		if(!preValidateConfirmPassword()){
			isValid = false;
			errors[4] = true;
			message[3] = errorText2[5];
			webtrekk += errorWebtrekk[3];
			document.getElementById('v5').innerHTML = getImageError();
		}
		else{
			errors[4] = false;
			message[4] = infoText[1];
			document.getElementById('v5').innerHTML = getImageValid();

		}
	}

	if(!checkEmail('tf3')){
		isValid = false;
		errors[2] = true;
		message[2] = errorText2[2];
		webtrekk += errorWebtrekk[4];
		document.getElementById('v3').innerHTML = getImageError();
	}
	else{
		errors[2] = false;
		message[2] = infoText[2];
		document.getElementById('v3').innerHTML = getImageValid();
	}

	var element = document.getElementById('tf4');
	if (element != null && element != 'undefined'){
		if(!preValidateKaptcha('tf4')){
			isValid = false;
			errors[3] = true;
			message[3] = errorText2[4];
			webtrekk += errorWebtrekk[6];
			document.getElementById('v4').innerHTML = getImageError();
		}
		else{
			errors[3] = false;
			message[3] = infoText[1];
			document.getElementById('v4').innerHTML = getImageValid();

		}
	}

	if(isValid){
		var regButton = document.getElementById('registrationButton');
		regButton.name='anmelden';
	}
	else{
		showErrorBeforePost();
	}

	return isValid;
}
//end validate form data


function nameValid(name){
	var validChars = "\[a-zA-Z0-9-_]";

    var quotedUser="(\"[^\"]*\")";
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(" + word + ")*$");
    //is username allowed
    if (name.match(userPat) == null) {
		return false;
    }
    return true;

}


function validateNameFaceBookConnect(name){
	var nameIsValid = true;
	if(!nameValid(name)){
		document.getElementById('errorIconBoxCommonName').style.display='block';
		document.getElementById('errorTextBoxCommonName').innerHTML=errorText[3];
		nameIsValid = false;
	}

	if(name.length<3||name.length>20){
		document.getElementById('errorIconBoxCommonName').style.display='block';
		document.getElementById('errorTextBoxCommonName').innerHTML=errorText2[0];
		nameIsValid = false;
	}

	Userservice.isCommonNameInUse(name,function(inUse){
		if(inUse){
			document.getElementById('errorIconBoxCommonName').style.display='block';
			document.getElementById('errorTextBoxCommonName').innerHTML=errorText[0];
			nameIsValid = false;
		}
	});
	if(nameIsValid){
		document.getElementById('errorIconBoxCommonName').style.display='none';
		document.getElementById('errorTextBoxCommonName').innerHTML="";
	}
	return nameIsValid;
}

function validatePasswordFacebookConnect(name,passwd){
	var passwdValid = true;
	if(passwd.length>10 || passwd.length<5){
		document.getElementById('errorIconBoxPassword').style.display='block';
		document.getElementById('errorTextBoxPassword').innerHTML=errorText2[1];
		passwdValid = false;
	}
	if(passwd==name){
		document.getElementById('errorIconBoxPassword').style.display='block';
		document.getElementById('errorTextBoxPassword').innerHTML=errorText[1];
		passwdValid = false;
	}
	if(passwdValid){
		document.getElementById('errorIconBoxPassword').style.display='none';
		document.getElementById('errorTextBoxPassword').innerHTML="";
	}
	return passwdValid;
}

function prevalidateFacebookConnectForm(){
	var name = document.getElementById('fbCn').value;
	var passwd = document.getElementById('fbPasswd').value;
	var validName  = validateNameFaceBookConnect(name);
	var validPasswd = validatePasswordFacebookConnect(name, passwd);
	return ( validName && validPasswd);
}
