// XML.Forms.wsc
/*global validateValue augmentValue */

// default.js
/*global isFirefox */

function ValidateElement(loElement, lsRegExp, whiteSpace, alphaChars, liMinLen, liMaxLen, lsError) {

/*
	return;
  mytext = loElement;
  setTimeout('mytext.focus();mytext.select();' , 0);


	
  return;	  
  */
  //NEVER attempt validation of an empty element
  if (loElement.value !== "") 
  {
    if (lsRegExp === "")
    {
      lsRegExp = ".*";
    }
    loElement.value = augmentValue(loElement.value, whiteSpace, alphaChars);
    var lbValid = validateValue(loElement.value, "^" + lsRegExp + "$", liMinLen, liMaxLen);

    if (!lbValid) {
      alert(lsError.replace("%value;", loElement.value));
      loElement.focus();
      loElement.select();
    }
  }
}

function chkNumeric(obj, minval, maxval, sideeffects)
{
  var chkNumericResult = true;
  var checkOK = "0123456789,.";
  if (minval < 0) {
    checkOK += "-";
  }
  var allValid = true;
  var decPoints = 0;
  var i, j;
  var objVal = obj.value;
  for (i = 0; i < objVal.length; i += 1) {
    var ch = objVal.charAt(i);
    for (j = 0; j < checkOK.length; j += 1) {
      if (ch === checkOK.charAt(j)) {
        break;
      }
    }
    if (j === checkOK.length) {
      allValid = false;
      break;
    }
  }
  if (!allValid) {
	if (sideeffects)
	  alert("Ugyldig værdi for feltet '" + obj.title + "'");
    chkNumericResult = false;
  }
  else
  {
    // check minimum and maximum
    var chkVal = obj.value;
    var prsVal = parseFloat(chkVal.replace(/,/g, '.')); //Make sure internal decimal-format is used
    if (chkVal !== "" && !(prsVal >= minval && prsVal <= maxval)) {
	  if (sideeffects)
        alert('Værdien "' + prsVal + '" er ikke i intervallet ' + minval + ' til ' + maxval);
      chkNumericResult = false;
    }
  }
  return chkNumericResult;
}

function checkOrDisable(minval, maxval, loElement)
{
	var obj = loElement;
	obj.value = obj.value.replace(".", ",");
	var minV = parseFloat(minval);
	var maxV = parseFloat(maxval);
	var chkOk = chkNumeric(obj, minV, maxV, false);
	if (!chkOk) {
		var ret = confirm('Værdien "' + obj.value + '" er ikke i intervallet ' + minV + ' til ' + maxV + '. Klikker du væk slås feltet fra.');
		if (ret){
			var namespace = obj.id.substring(0, (obj.id.length - 13));
			
			var checkboxId = namespace + '.CrossSectionElementPartTypeCheckbox1';
			var checkbox = document.getElementById(checkboxId);
			checkbox.checked = false;
			
			CrossSectionElementType_Toggle(namespace);
			
			return true;
		} else {
			mytext = obj;
			setTimeout('mytext.focus();mytext.select();' , 0);
			return false;
		}
	}else
		return true;
}

function checkNumeric(minval, maxval, loElement)
{
  var obj;
  if (!loElement) {
    obj = event.srcElement; //Proprietary MS - should not be used!
  } else {
    obj = loElement;
  }

  // THIS is where you setup the decimal separator to use!
  obj.value = obj.value.replace(".", ",");
  var minV = parseFloat(minval);
  var maxV = parseFloat(maxval);
  var chkOk = chkNumeric(obj, minV, maxV, true);
  if (!chkOk) {
    
	/*
	if (isFirefox) {
      
      //obj.focus();
      //obj.select();
      
      // The above code cause an infinite fouce/blur event loop in 
      // firefox! It has therefore currently been disabled.
    }
    else {
      obj.focus();
      obj.select();
    }
	*/
	
	// fixed to work in both browsers
	mytext = obj;
	setTimeout('mytext.focus();mytext.select();' , 0);
	
    return false;
  }	else {
    return true;
  }
}

function emailCheck(emailStr) {
  if (emailStr === "") {
    return true;
  }

  var emailPat = /^(.+)@(.+)$/;
  var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
  var validChars = "[^\\s" + specialChars + "]";
  var quotedUser = "(\"[^\"]*\")";
  var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
  var atom = validChars + '+';
  var word = "(" + atom + "|" + quotedUser + ")";
  var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
  var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

  /* Begin with the coarse pattern to simply break up user@domain into
     different pieces that are easy to analyze. */
  var matchArray = emailStr.match(emailPat);
  if (matchArray === null) {
    /* Too many/few @'s or something; basically, this address doesn't
       even fit the general mould of a valid e-mail address. */
    alert("Email-addressen er ikke gyldig (tjek @ og .'er)");
    return false;
  }
  var user = matchArray[1];
  var domain = matchArray[2];

  // See if "user" is valid
  if (user.match(userPat) === null) {
    // user is not valid
    alert("Brugernavnet er ikke gyldigt (brugernavnet står foran @'et i email-adressen).");
    return false;
  }

  /* if the e-mail address is at an IP address (as opposed to a symbolic
     host name) make sure the IP address is valid. */
  var IPArray = domain.match(ipDomainPat);
  if (IPArray !== null) {
    // this is an IP address
    for (var i = 1; i <= 4; i += 1) {
      if (IPArray[i] > 255) {
        alert("Destinations IP-addressen er ikke gyldig!");
        return false;
      }
    }
    return true;
  }

  // Domain is symbolic name
  var domainArray = domain.match(domainPat);
  if (domainArray === null) {
    alert("Domæne-navnet er ikke gyldigt (domæne-navnet står efter @'et og før det sidste punktum i email-adressen).");
    return false;
  }

  /* domain name seems valid, but now make sure that it ends in a
     three-letter word (like com, edu, gov) or a two-letter word,
     representing country (uk, nl), and that there's a hostname preceding
     the domain or country. */

  /* Now we need to break up the domain to get a count of how many atoms
     it consists of. */
  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) {
    // the address must end in a two letter or three letter word.
    alert("Email-adressen skal ende med et tre-bogstavs domæne (f.eks. com), eller en to-bogstavs landekode (f.eks. dk).");
    return false;
  }

  // Make sure there's a host name preceding the domain.
  if (len < 2) {
    var errStr = "Der skal angives et domæne-navn i email-adressen!";
    alert(errStr);
    return false;
  }

  // If we've gotten this far, everything's valid!
  return true;
}

function ValidateEmail(loElement) {
  loElement.value = loElement.value.toLowerCase();
  if (!emailCheck(loElement.value)) {
    loElement.focus();
    loElement.select();
  }
}