// JavaScript Document
var stringDateFormatExplanation = '\n\n--------F&Ouml;RKLARING--------\n\nDatum skrivs p&aring; n&aring;got av f&ouml;ljande s&auml;tt.\n\nEndast datum: 2002-01-01\nDatum och klockslag: 2002-01-01 06:00';
var stringEmailFormatExplanation = '\n\n--------F&Ouml;RKLARING--------\n\nE-postadresser best&aring;r av tre delar. ett [anv&auml;ndarnamn], ett @ och ett servernamn eller IP-nummer\n\nAnv&auml;ndarnamnet: Det som st&aring;r innan snabel-a:t (t.ex. peter.svensson)\n@ = det som skiljer anv&auml;ndarnamnet och servern\nServer: Namn eller IP-nummer p&aring; mailservern (t.ex. telia.com el. 213.123.321.31)';
var stringLinkFormatExplanation = '\n\n--------F&Ouml;RKLARING--------\n\nKommer snart.';
var stringStringFormatExplanation = '\n\n--------F&Ouml;RKLARING--------\n\nKommer snart'
function checkData(field, type, mandatory, name) {
	switch (type) {
		case 'date':
			return checkDateTime(field, mandatory, name);
			break;
		case 'datetime':
			return checkDateTime(field, mandatory, name);
			break;
		case 'time':
			return checkDateTime(field, mandatory, name);
			break;
		case 'string':
			if (mandatory) {
				return checkString(field, 1, name);
			}
			else {
				return checkString(field, 0, name);
			}
			break;
		case 'integer':
			return checkNumber(field, type, mandatory, name);
			break;
		case 'float':
			return checkNumber(field, type, mandatory, name);
			break;
		case 'number':
			return checkNumber(field, type, mandatory, name);
			break;
		case 'email':
			return checkEmail(field, mandatory, name);
			break;
		case 'url':
			return checkURL(field, mandatory, name);
			break;
		default:
			return false;
			break;
	}
}
function checkDateTime(field, mandatory, name) {
	
	//Errors
	var stringLengthError = name + ' &auml;r f&ouml;r kort' + stringDateFormatExplanation;
	var stringFormatError = name + ' du angett g&aring;r inte att k&auml;nna igen!!' + stringDateFormatExplanation;
	
	var stringDateTime_Separator = ' '; //String that separates date / time
	
	//GET THE VALUE TO HANDLE IN THIS FUNCTION
	var stringValue = trimString(getFieldValue(field)); //Get the trimmed value

	var arrayDate_Time = stringValue.split(stringDateTime_Separator); // get a date / time array
	
	if (arrayDate_Time.length == 2) { // The value containt both date and time so...
		if (checkTimeString(arrayDate_Time[1])) {
			if (checkDateString(arrayDate_Time[0])) {
				return true;
			}
			else {
				return declineSend('Datumet i ' + name + ' (' + arrayDate_Time[0] + ') finns inte, eller &auml;r felaktig.' + stringDateFormatExplanation, field);
			}
		}
		else {
			return declineSend('Tidsangivelsen i ' + name + ' (' + arrayDate_Time[1] + ') finns inte, eller &auml;r felaktig.' + stringDateFormatExplanation, field);
		}
	} else if (arrayDate_Time.length == 1) { // the value contains only date...
		if (checkDateString(arrayDate_Time[0])) {
			return true;
		}
		else if (arrayDate_Time[0].length == 0 && mandatory) {
			return declineSend('Du har inte angivit ' + name + ' trots att det &auml;r en obligatorisk uppgift.' + stringDateFormatExplanation, field);
		}
		else if (arrayDate_Time[0].length == 0 && !(mandatory)) {
			return true;
		}
		else {
			return declineSend('Datumet i ' + name + ' (' + arrayDate_Time[0] + ') finns inte, eller &auml;r felaktig.' + stringDateFormatExplanation, field);
		}
	}
}

function checkString(field, minLength, stringName) {
	var stringError =  stringName + ' &auml;r f&ouml;r kort!';
	if (field.value.length < minLength) {
		return declineSend(stringError, field);
	}
	else
	{
		return true;
	}
}

function getFieldValue(field) {
	return field.value = trimString(field.value);
}

function focusThis(field) {
	field.focus();
	field.select();
}

function informUser(strInformation) {
	alert(strInformation);
}
function declineSend(errorString, field) {
	informUser(errorString);
	focusThis(field);
	return false;
}
function trimString (str) {
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}



function checkTime(field, mandatory, name) {
	var timeString = field.value;
	var stringTimeNonExistent = 'Tiden (' + timeString + ') som &auml;r angiven i ' + name + ' finns inte';
	if (timeString.length == 0 && !(mandatory)) {
		return true
	}
	else if (checkTimeString(timeString) && mandatory) {
		return true
	}
	else if (timeString.length == 0 && (mandatory)) {
		return declineSend('Du har inte angivit n&aring;gon tid f&ouml;r trots att det &auml;r en obligatorisk uppgift!')
	}
}

function checkTimeString(timeString) {
	
	var objRegExp = /^\d{2}(\:)\d{2}$/
	var strSeparator = ':';
	//check to see if in correct format
	if(!objRegExp.test(timeString))
		return false; //doesn't match pattern, bad Time
	else{
	var arrayTime = timeString.split(strSeparator); //split Time into hour, minute
	//check for February
	var intHour = parseInt(arrayTime[0]);
	var intMinute = parseInt(arrayTime[1]);
	
		if ((intHour <= 23) && (intHour >= 0) && (intMinute <= 59) && (intMinute >= 0)) 
		{
			return true;
		}
		else{
	
			return false;
		}
	}
	return false; //any other values, bad Time
}


function checkDate(field, mandatory, name) {
	var objRegExp = /^\d{4}(\-)\d{1,2}(\-)\d{1,2}$/
	var strSeparator = '-';//find date separator
	dateString = field.value;
	
	//check to see if in correct format
	if(!objRegExp.test(dateString))
		return false; //doesn't match pattern, bad date
	else{
		var arrayDate = dateString.split(strSeparator); //split date into month, day, year
		//create a lookup for months not equal to Feb.
		var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
						'08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
		var intDay = arrayDate[2]; 
	
		//check if month value and day value agree
		if(arrayLookup[arrayDate[1]] != null) {
		  if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
			return true; //found in lookup table, good date
		}
    
    	//check for February
    	var intYear = parseInt(arrayDate[0]);
    	var intMonth = parseInt(arrayDate[1]);

		if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
    	  return true; //Feb. had valid number of days
  		}
  		return false; //any other values, bad date
}

function checkDateString(dateString) {
	var objRegExp = /^\d{4}(\-)\d{1,2}(\-)\d{1,2}$/
	var strSeparator = '-';//find date separator
	
	//check to see if in correct format
	if(!objRegExp.test(dateString))
		return false; //doesn't match pattern, bad date
	else{
		var arrayDate = dateString.split(strSeparator); //split date into month, day, year
		//create a lookup for months not equal to Feb.
		var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
						'08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
		var intDay = arrayDate[2]; 
	
		//check if month value and day value agree
		if(arrayLookup[arrayDate[1]] != null) {
		  if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
			return true; //found in lookup table, good date
		}
    
    	//check for February
    	var intYear = parseInt(arrayDate[0]);
    	var intMonth = parseInt(arrayDate[1]);

		if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
    	  return true; //Feb. had valid number of days
  		}
  		return false; //any other values, bad date
}

function checkEmail(field, mandatory, name) {
<!-- Begin
	emailStr = field.value;

	if (emailStr.length == 0 && !mandatory) {
		return true;
	}
	else if (emailStr.length == 0 && mandatory) {
		return declineSend('Du har inte fyllt i' + name + '. Det &auml;r en obligatorisk uppgift!', field)
	}
	else {
		/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
					(the bug is actually in the weak regexp engine of the browser; I
					simplified the regexps to make it work).
		   1.1.1: Removed restriction that countries must be preceded by a domain,
					so abc@host.uk is now legal.  However, there's still the 
					restriction that an address must end in a two or three letter
					word.
			 1.1: Rewrote most of the function to conform more closely to RFC 822.
			 1.0: Original  */
		
		<!-- This script and many more are available free online at -->
		<!-- The JavaScript Source!! http://javascript.internet.com -->
		
		
		/* The following pattern is used to check if the entered e-mail address
		   fits the user@domain format.  It also is used to separate the username
		   from the domain. */
		var emailPat=/^(.+)@(.+)$/
		/* The following string represents the pattern for matching all special
		   characters.  We don't want to allow special characters in the address. 
		   These characters include ( ) < > @ , ; : \ " . [ ]    */
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
		/* The following string represents the range of characters allowed in a 
		   username or domainname.  It really states which chars aren't allowed. */
		var validChars="\[^\\s" + specialChars + "\]"
		/* The following pattern applies if the "user" is a quoted string (in
		   which case, there are no rules about which characters are allowed
		   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		   is a legal e-mail address. */
		var quotedUser="(\"[^\"]*\")"
		/* The following pattern applies for domains that are IP addresses,
		   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		   e-mail address. NOTE: The square brackets are required. */
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		/* The following string represents an atom (basically a series of
		   non-special characters.) */
		var atom=validChars + '+'
		/* The following string represents one word in the typical username.
		   For example, in john.doe@somewhere.com, john and doe are words.
		   Basically, a word is either an atom or quoted string. */
		var word="(" + atom + "|" + quotedUser + ")"
		// The following pattern describes the structure of the user
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
		/* The following pattern describes the structure of a normal symbolic
		   domain, as opposed to ipDomainPat, shown above. */
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
		
		
		/* Finally, let's start trying to figure out if the supplied address is
		   valid. */
		
		/* 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. */
			return declineSend(name + " &auml;r felaktig. Kolla s&aring; @:t och .:er &auml;r korrekta", field);
		}
		var user=matchArray[1];
		var domain=matchArray[2];
		
		// See if "user" is valid 
		if (user.match(userPat)==null) {
			// user is not valid
			return declineSend('Anv&auml;ndarnamnet i ' + name + ' &auml;r ogiltigt.', field)
		}
		
		/* 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++) {
				if (IPArray[i]>255) {
					return declineSend('Servernamnet i ' + name + ' &auml;r ogiltigt.', field)
				}
			}
			return true
		}
		
		// Domain is symbolic name
		var domainArray=domain.match(domainPat)
		if (domainArray==null) {
			return declineSend('Servernamnet i ' + name + ' &auml;r ogiltigt.', field);
		}
		
		/* 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.
			return declineSend('Dom&auml;nnamnet i ' + name + ' m&aring;ste sluta p&aring; ett tre bokst&auml;ver l&aring;ngt suffix (t.ex. .com) eller tv&aring; bokst&auml;ver l&aring;ngt land (t.ex .se)', field);
		}
		
		// Make sure there's a host name preceding the domain.
		if (len<2) {
			return declineSend(name + ' saknar ett dom&auml;nnamn.', field);
		}
		
		// If we've gotten this far, everything's valid!
		return true;
	}
}

function checkURL(field, mandatory, name) {
<!-- Begin
	URLStr = field.value;
	
	if (URLStr.length == 0 && !mandatory) {
		return true;
	}
	else if (URLStr.length == 0 && mandatory) {
		return declineSend('Du har inte fyllt i' + name + ' trots att det &auml;r en obligatorisk uppgift!', field)
	}
	else {
		/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
					(the bug is actually in the weak regexp engine of the browser; I
					simplified the regexps to make it work).
		   1.1.1: Removed restriction that countries must be preceded by a domain,
					so abc@host.uk is now legal.  However, there's still the 
					restriction that an address must end in a two or three letter
					word.
			 1.1: Rewrote most of the function to conform more closely to RFC 822.
			 1.0: Original  */
		
		<!-- This script and many more are available free online at -->
		<!-- The JavaScript Source!! http://javascript.internet.com -->
		
		
		/* The following pattern is used to check if the entered e-mail address
		   fits the user@domain format.  It also is used to separate the username
		   from the domain. */
		var URLPat=/^http:\/\/(.+)$/
		/* The following string represents the pattern for matching all special
		   characters.  We don't want to allow special characters in the address. 
		   These characters include ( ) < > @ , ; : \ " . [ ]    */
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
		/* The following string represents the range of characters allowed in a 
		   username or domainname.  It really states which chars aren't allowed. */
		var validChars="\[^\\s" + specialChars + "\]"
		/* The following pattern applies for domains that are IP addresses,
		   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		   e-mail address. NOTE: The square brackets are required. */
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		/* The following string represents an atom (basically a series of
		   non-special characters.) */
		var atom=validChars + '+'
				var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		/* The following string represents an atom (basically a series of
		   non-special characters.) */
		var atom=validChars + '+'
		
		/* The following pattern describes the structure of a normal symbolic
		   domain, as opposed to ipDomainPat, shown above. */
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
		/* Finally, let's start trying to figure out if the supplied address is
		   valid. */
		
		/* Begin with the coarse pattern to simply break up user@domain into
		   different pieces that are easy to analyze. */
		var matchArray=URLStr.match(URLPat)
		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. */
			return declineSend(name + " &auml;r inte en giltig URL. Kolla att den b&ouml;rjar p&aring; http://", field);
		}
		domain = matchArray[1]

		/* 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++) {
				if (IPArray[i]>255) {
					return declineSend(name + ' &auml;r ogiltigt. ' + domain + ' &auml;r inte ett giltigt IP-nummer', field)
				}
			}
			return true
		}
		
		// Domain is symbolic name
		var domainArray=domain.match(domainPat)
		if (domainArray==null) {
			return declineSend(name + ' &auml;r ogiltigt. ' + domain + ' &auml;r inte ett giltigt dom&auml;n namn', field);
		}

		/* 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.
			return declineSend('Dom&auml;nnamnet i ' + name + ' m&aring;ste sluta p&aring; ett tre bokst&auml;ver l&aring;ngt suffix (t.ex. .com) eller tv&aring; bokst&auml;ver l&aring;ngt land (t.ex .se)', field);
		}
		
		// Make sure there's a host name preceding the domain.
		if (len<2) {
			return declineSend(name + ' saknar ett dom&auml;nnamn.', field);
		}
		
		// If we've gotten this far, everything's valid!
		return true;

	}
}
//////////////////////////////
//Replacing commas with dots.
//////////////////////////////
function replaceChars(fielden) {
	out = ","; // replace this
	add = "."; // with this
	temp = "" + fielden.value; // temporary holder
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	fielden.value = temp;
	return fielden
}
//////////////////////////////
//Replacing the inputfields values
//////////////////////////////
function stringFilter (input) {
	s = input.value;
	filteredValues = "abcdefghijklmnopqrstuvwxyzċäöABCDEFGHIJKLMNOPQRSTUVXYZĊÄÖ /\\:;_-'*¨^~´`+?}{=)(][&%¤#£\"@!|<>§½";     // Characters stripped out
	var i;
	var returnString = "";
		for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
			var c = s.charAt(i);
			if (filteredValues.indexOf(c) == -1) returnString += c;
		}
	input.value = returnString;
	return input;
}

///////////////////////////////
//Checking if the inputfields value is a number after modufying it a bit.
///////////////////////////////

function checkNumber(fielden, type, mandatory, name) {
	/*fielden = stringFilter(fielden);*/
	fielden = replaceChars(fielden);
	if (mandatory==true && fielden.value == '') {
		return declineSend('Du har inte angett: ' + name, fielden);
	}
	else if (mandatory==false && fielden.value == '') {
		return true;
	}
	else if ( type == 'number' ) {
		
		if (isFloat(fielden) || isInteger(fielden)) {
			return true;
		}
		else {
			return declineSend(name + ' du angett &auml;r inte ett tal.\n\nDu m&aring;ste ange ett heltal eller ett decimaltal.\nEx 1 (Heltal): 140\nEx 2 (Decimaltal): 12.45', fielden);
		}
	}
	else if ( type == 'float' ) {
		if (isFloat(fielden)) {
			return true;
		}
		else {
			return declineSend(name + ' du angett &auml;r inte ett tal.\n\nDu m&aring;ste ange ett decimaltal.\nEx: 12.45', fielden);
		}
	}
	else if ( type == 'integer' ) {
		if (isInteger(fielden)) {
			return true;
		}
		else {
			return declineSend(name + ' du angett &auml;r inte ett tal.\n\nDu m&aring;ste ange ett heltal.\nEx: 140', fielden);
		}
	}
}
function isFloat(fielden) {
	if (isNaN(parseFloat(fielden.value))) {
		return false;
	}
	else {
		if (parseFloat(fielden.value) == fielden.value) {
			return true;
		}
		else {return false;}
	}
	
}

function isInteger(fielden) {
	if (isNaN(parseInt(fielden.value))) {
		return false;
	}
	else {
		if (parseInt(fielden.value) == fielden.value) {
			return true;
		}
		else {return false;}
	}
}
