/*************************************************
/  Javascipt functions for SEC
/
/
/************************************************/

/***************************************
/ Trims leading/ending white space
/
/ RETURNS
/ Trimmed value
/
/ PARAMETERS
/ value (string) = string to be trimmed
/
/**************************************/
function trim(value)
{
  return value.replace(/^\s+|\s+$/g,"");
}

/***************************************
/ Validate multiple fields by type
/
/ RETURNS
/ Success: true
/ Failure: false
/
/ PARAMETERS
/ valArray (array) = array of functions to call, with parameters (2 dimenional array)
/ eg: validateAll([["validateText", "Bill", 10, true], ["validateText", "Ben"]]);
/
/**************************************/
function validateAll(valArray)
{
	error = 0;
		// iterate through each function call
	for(i = 0; i < valArray.length; i++)
	{
		$icon = $("#img_" + valArray[i].slice(1,2));
		$icon.css({"visibility": "hidden"});
		$icon.removeClass('small-error-tick-icon');
		$icon.removeClass('small-error-icon');
		$icon.removeClass('small-warning-icon');
		
			// call each function with arguments
		result = this[valArray[i][0]].apply(this, Array.prototype.slice.call(valArray[i], 1));

		if(result[0] > 2)
		{
			error++; // for incrementing errors, but not acting on elements
		}
		else if(result[0] > 1)
		{
			error++;
			$("#" + valArray[i].slice(1,2)).addClass('error-highlight');
			$icon.addClass('small-error-icon');
			$icon.attr('title', result[1]);
			$icon.css({"visibility": "visible"});
		}
		else if(result[0] > 0)
		{
			$("#" + valArray[i].slice(1,2)).removeClass('error-highlight');
			$icon.addClass('small-warning-icon');
			$icon.attr('title', result[1]);
			$icon.css({"visibility": "visible"});
		}
		else if(result[0] > -1)
		{
			$("#" + valArray[i].slice(1,2)).removeClass('error-highlight');
			$icon.addClass('small-error-tick-icon');
			$icon.attr('title', result[1]);
			$icon.css({"visibility": "visible"});
		}
	}

	if(error > 0)
		return false;
	else
		return true;
}

/***************************************
/ Validate single field by type
/
/ RETURNS
/ Success: true
/ Failure: false
/
/ PARAMETERS
/ valArray (array) = array of function name and parameters
/ eg: validateMe(["validateText", "Bill", 10, true]);
/
/**************************************/
function validateMe(valArray)
{
	$icon = $("#img_" + valArray.slice(1,2));
	$icon.css({"visibility": "hidden"});
	$icon.removeClass('small-error-tick-icon');
	$icon.removeClass('small-error-icon');
	$icon.removeClass('small-warning-icon');
	
		// call each function with arguments
	result = this[valArray[0]].apply(this, Array.prototype.slice.call(valArray, 1));
	
	if(result[0] > 2)
	{
		// to not act on result
	}
	else if(result[0] > 1)
	{
			// error
		$("#" + valArray.slice(1,2)).addClass('error-highlight');
		$icon.addClass('small-error-icon');
		$icon.attr('title', result[1]);
		$icon.css({"visibility": "visible"});
	}
	else if(result[0] > 0)
	{
		$("#" + valArray.slice(1,2)).removeClass('error-highlight');
		$icon.addClass('small-warning-icon');
		$icon.attr('title', result[1]);
		$icon.css({"visibility": "visible"});
	}
	else if(result[0] > -1)
	{
		$("#" + valArray.slice(1,2)).removeClass('error-highlight');
		$icon.addClass('small-error-tick-icon');
		$icon.attr('title', result[1]);
		$icon.css({"visibility": "visible"});
	}

	if(result[0] > 0)
		return false;
	else
		return true;
}

/***************************************
/ Validate text field
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ length (int) = chars to limit too ("0" for no limit)
/ numerics (bool) = allow numerical characters
/ stripHTML (bool) = strip HTML tags
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateText(target, length, numerics, stripHTML, warning)
{
		// defaults
	length = typeof(length) != "undefined" ? length : 0;
	numerics = typeof(numerics) != "undefined" ? numerics : true;
	stripHTML = typeof(stripHTML) != "undefined" ? stripHTML : false;

	warning = typeof(warning) != "undefined" ? warning : false;
	returnVal = warning == true ? 1 : 2;

	obj = document.getElementById(target);
	
	if(stripHTML)
	{
		obj.value = String(obj.value).replace(/<\/?[^>]+>/gi, "");
	}
	
	obj.value = trim(obj.value);
	obj = obj.value;
	
	if(obj == "" || obj == null)
	{
		if(returnVal == 2)
	   		return [returnVal, "Input is required"];
		else
			return [returnVal, "Empty, but not a required field"];
	}
	
		// check if validating length
	if(length > 0)
		if(obj.length > length) return returnVal;
	
	if(!numerics)
	{
		if(obj.match(/\d+/))
			return [returnVal, "Text has numbers in"];
	}
	
	return [0, "Valid input"];
}

/***************************************
/ Validate text field
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ length (int) = chars to limit too ("0" for no limit)
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateTextarea(target, length, warning)
{
		// defaults
	length = typeof(length) != "undefined" ? length : 0;
	strip = typeof(strip) != "undefined" ? strip : true;
	warning = typeof(warning) != "undefined" ? warning : false;
	returnVal = warning == true ? 1 : 2;

	mceText = String(tinyMCE.get(target).getContent({format : "raw"})).replace(/(<([^>]+)>)/ig,"");
	
	if(mceText == "" || mceText == null)
	   return [returnVal, "Input is required"];
	
		// check if validating length
	if(length > 0)
		if(mceText.length > length) return [returnVal, "Text is too long"];

	return [0, "Valid input"];
}

/***************************************
/ Validate numeric field
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ type (string) = type of number to allow (int, float)
/ neg (bool) = allow negative values
/ decimals (int) = decimal places to set to (default 2)
/ size (int) = chars to limit too ("0" for no limit)
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateNumber(target, type, neg, decimals, size, warning)
{
		// defaults
	type = typeof(type) != "undefined" ? type : "int";
	neg = typeof(neg) != "undefined" ? neg : true;
	decimals = typeof(decimals) != "undefined" ? decimals : 2;
	size = typeof(size) != "undefined" ? size : 0;
	warning = typeof(warning) != "undefined" ? warning : false;
	returnVal = warning == true ? 1 : 2;
	
	obj = document.getElementById(target);

	if(trim(obj.value) === "")
		return [returnVal, "Input is required"];
		
	if(isNaN(trim(obj.value)))
		return [returnVal, "Value is not a number"];
		
	if(type == "float")
	{
		obj = document.getElementById(target);
		obj.value = round_number(obj.value, decimals);
	}

	obj.value = trim(obj.value);
	obj = obj.value;
		
	if(obj === "" || obj == null)
		return [returnVal, "Input is required"];
		
	if(isNaN(obj))
		return [returnVal, "Value is not a number"];
		
	if(!neg)
	{
		if(obj < 0)
			return [returnVal, "Value is negative"];
	}
	
	if(type == "int")
	{		
		if(obj.toString().search(/\./) > -1)
			return [returnVal, "Value is not an integer"];
	}
	
	if(size > 0)
		if(obj.toString().length > size) return [returnVal, "Value is too long"];
	
	return [0, "Valid input"];
}

/***************************************
/ Validate file upload field
/ (can only verify file extension, not MIME)
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ type (string) = type of number to allow (int, float)
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateFile(target, types, warning)
{
		// defaults
	type = typeof(type) != "undefined" ? type : ["jpeg", "jpg", "gif", "png", "bmp", "doc", "docx", "pdf", "txt", "zip", "rar", "tar"];
	returnVal = warning == true ? 1 : 2;
	
	obj = document.getElementById(target).value;
	
	fileArr = obj.split("."); 
	
	ext = fileArr.pop();
	
	if(jQuery.isArray(type))
		searchExt = jQuery.inArray(ext, type);
	else
		searchExt = -1;

	if(searchExt == -1)
		return [returnVal, "Invalid file type"];
		
	return [0, "Valid file"];
}

/***************************************
/ Validate passwords are identical
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target1 (string) = element 1 to compare
/ target2 (string) = element 2 to compare
/
/**************************************/
function validatePass(target1, target2)
{	
	obj1 = document.getElementById(target1).value;
	obj2 = document.getElementById(target2).value;
	
	objArray = [target1, target2];
	
	$icon[0] = $("#img_" + objArray[0]);
	$icon[1] = $("#img_" + objArray[1]);
	
	$icon[0].css({"visibility": "hidden"});
	$icon[1].css({"visibility": "hidden"});
	
	$icon[0].removeClass('small-error-tick-icon');
	$icon[0].removeClass('small-error-icon');
	$icon[0].removeClass('small-warning-icon');
	
	$icon[1].removeClass('small-error-tick-icon');
	$icon[1].removeClass('small-error-icon');
	$icon[1].removeClass('small-warning-icon');
	
	fatalError = false;
	
	if(trim(obj1) == "" || trim(obj2) == "")
		fatalError = true;
	
	if(obj1 != obj2 || fatalError == true)
	{
			$("#" + objArray[0]).addClass('error-highlight');
			$icon[0].addClass('small-error-icon');
			$icon[0].attr('title', 'Password values do not match');
			$icon[0].css({"visibility": "visible"});
			
			$("#" + objArray[1]).addClass('error-highlight');
			$icon[1].addClass('small-error-icon');
			$icon[1].attr('title', 'Password values do not match');
			$icon[1].css({"visibility": "visible"});
		
		
		return [3, ""];
	}
	else
	{		
			$("#" + objArray[0]).removeClass('error-highlight');
			$icon[0].addClass('small-error-tick-icon');
			$icon[0].attr('title', 'Password values match');
			$icon[0].css({"visibility": "visible"});
			
			$("#" + objArray[1]).removeClass('error-highlight');
			$icon[1].addClass('small-error-tick-icon');
			$icon[1].attr('title', 'Password values match');
			$icon[1].css({"visibility": "visible"});
		
		return [-1, ""];
	}
}

/***************************************
/ Validate email field
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ thisSite (bool) = only allow emails linked to "this" site
/ eg: on site "www.example.com" will only accept @example.com email addresses
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateEmail(target, thisSite, warning)
{
		// defaults
	thisSite = typeof(thisSite) != "undefined" ? thisSite : false;
	warning = typeof(warning) != "undefined" ? warning : false;
	returnVal = warning == true ? 1 : 2;
	
	var checkTLD=1;	
	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;	
	var emailPat=/^(.+)@(.+)$/;
	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";	
	var validChars="\[^\\s" + specialChars + "\]";
	
	var quotedUser="(\"[^\"]*\")";
		
	var atom=validChars + '+';
	
	var word="(" + atom + "|" + quotedUser + ")";	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	obj = document.getElementById(target);
		
	obj = obj.value;
		
	var matchArray=obj.match(emailPat);
	
	if (matchArray==null)
		return [returnVal, "Not a valid email address"];
	
	var user=matchArray[1];
	var domain=matchArray[2];
		
	if (user.match(userPat)==null)
		return [returnVal, "Not a valid email address"];

	var domArr=domain.split(".");
	var len=domArr.length;
		
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		return [returnVal, "Not a valid email address"];
	
	if (len<2)

		return [returnVal, "Not a valid email address"];
	
	return [0, "Valid email address"];
}

/***************************************
/ Validate multiple fields by type
/
/ RETURNS
/ Success: true
/ Failure: false
/
/ PARAMETERS
/ valArray (array) = array of functions to call, with parameters (2 dimenional array)
/ eg: validateAll([["validateText", "Bill", 10, true], ["validateText", "Ben"]]);
/ name (array) = static part of dynamic ids ("dyn_name_" of "dyn_name_1")
/ [["validateText", "dyn_name_", 10, true], ["validateText", "dyn_desc_"]]
/ idStore (string) = id of input storing all numbers of dynamic ids to be tested
/ eg: [0,1,3,4]; ("dyn_name_0", "dyn_name_1", "dyn_name_3", "dyn_name_4)
/
/**************************************/
function validateDynamicAll(valArray, dynArray, idStore)
{
	error = 0;
		// iterate through each function call
	for(i = 0; i < valArray.length; i++)
	{
		$icon = $("#img_" + valArray[i].slice(1,2));
		$icon.css({"visibility": "hidden"});
		$icon.removeClass('small-error-tick-icon');
		$icon.removeClass('small-error-icon');
		$icon.removeClass('small-warning-icon');
		
			// call each function with arguments
		result = this[valArray[i][0]].apply(this, Array.prototype.slice.call(valArray[i], 1));

		if(result > 2)
		{
			error++; // for incrementing errors, but not acting on elements
		}
		else if(result > 1)
		{
			error++;
			$("#" + valArray[i].slice(1,2)).addClass('error-highlight');
			$icon.addClass('small-error-icon');
			$icon.css({"visibility": "visible"});
		}
		else if(result > 0)
		{
			$("#" + valArray[i].slice(1,2)).removeClass('error-highlight');
			$icon.addClass('small-warning-icon');
			$icon.css({"visibility": "visible"});
		}
		else if(result > -1)
		{
			$("#" + valArray[i].slice(1,2)).removeClass('error-highlight');
			$icon.addClass('small-error-tick-icon');
			$icon.css({"visibility": "visible"});
		}
	}
	
	if($("#" + idStore).val() != "")
	{
		targetArr = String($("#" + idStore).val()).split("|");
		
		for(i = 0; i < dynArray.length; i++)
		{		
				// call each function with arguments
			callArray = dynArray;
			callName = dynArray[i][1];
			
			for(x in targetArr)
			{
				callArray[i][1] = callName+""+targetArr[x];
				
				$icon = $("#img_" + callArray[i][1]);
				$icon.css({"visibility": "hidden"});
				$icon.removeClass('small-error-tick-icon');
				$icon.removeClass('small-error-icon');
				$icon.removeClass('small-warning-icon');
				
				result = this[dynArray[i][0]].apply(this, Array.prototype.slice.call(callArray[i], 1));
		
				if(result > 2)
				{
					error++; // for incrementing errors, but not acting on elements
				}
				else if(result > 1)
				{
					error++;
					$("#" + callArray[i][1]).addClass('error-highlight');
					$icon.addClass('small-error-icon');
					$icon.css({"visibility": "visible"});
				}
				else if(result > 0)
				{
					$("#" + callArray[i][1]).removeClass('error-highlight');
					$icon.addClass('small-warning-icon');
					$icon.css({"visibility": "visible"});
				}
				else if(result > -1)
				{
					$("#" + callArray[i][1]).removeClass('error-highlight');
					$icon.addClass('small-error-tick-icon');
					$icon.css({"visibility": "visible"});
				}
			}
		}
	}

	if(error > 0)
		return false;
	else
		return true;
}

/***************************************
/ Validate no invalid characters
/
/ RETURNS
/ Success: 0
/ Failure: 2 (error) / 1 (warning)
/
/ PARAMETERS
/ target (string) = element id to test
/ URL (bool) = if checking for valid URL (http://)
/ warning (bool) = warning mode (does not fail validation)
/
/**************************************/
function validateURLChars(target, URL, warning)
{
		// defaults
	URL = typeof(URL) != "undefined" ? URL : false;
	warning = typeof(warning) != "undefined" ? warning : false;
	returnVal = warning == true ? 1 : 2;

	//var e=/&|\:|;|\[|\]|\=|\+|\*|\^|%|\$|£|\!|`|¬|\\|\/|\||<|>|~|#|@|{|}|€|\?|"/;
	
	var e=/[^a-zA-Z 0-9\s,.\-\_\']+/g; // foreign characters
	
	obj = trim(document.getElementById(target).value);
	
	if(obj == "" || obj == null)
	   return [returnVal, "Input is required"];

    if(obj.match(e))
		return [returnVal, "Input contains invalid character(s)"];
    else
		return [0, "Valid input"];
}

/***************************************
/ Format number accurately
/
/ RETURNS
/ Success: rounded number
/
/ PARAMETERS
/ number (float) = number to be rounded
/ dec_places (int) = number of decimal places to be rounded to
/
/ Version 2.0 (c) Copyright 2008, Russell Walker, Netshine Software Limited.
/ www.netshinesoftware.com
/
/**************************************/
function round_number(number,dec_places){
var new_number='';var i=0;var sign="";number=number.toString();number=number.replace(/^\s+|\s+$/g,'');if(number.charCodeAt(0)==45){sign='-';number=number.substr(1).replace(/^\s+|\s+$/g,'')}dec_places=dec_places*1;dec_point_pos=number.lastIndexOf(".");if(dec_point_pos==0){number="0"+number;dec_point_pos=1}if(dec_point_pos==-1||dec_point_pos==number.length-1){if(dec_places>0){new_number=number+".";for(i=0;i<dec_places;i++){new_number+="0"}if(new_number==0){sign=""}return sign+new_number}else{return sign+number}}var existing_places=(number.length-1)-dec_point_pos;if(existing_places==dec_places){return sign+number}if(existing_places<dec_places){new_number=number;for(i=existing_places;i<dec_places;i++){new_number+="0"}if(new_number==0){sign=""}return sign+new_number}var end_pos=(dec_point_pos*1)+dec_places;var round_up=false;if((number.charAt(end_pos+1)*1)>4){round_up=true}var digit_array=new Array();for(i=0;i<=end_pos;i++){digit_array[i]=number.charAt(i)}for(i=digit_array.length-1;i>=0;i--){if(digit_array[i]=="."){continue}if(round_up){digit_array[i]++;if(digit_array[i]<10){break}}else{break}}for(i=0;i<=end_pos;i++){if(digit_array[i]=="."||digit_array[i]<10||i==0){new_number+=digit_array[i]}else{new_number+="0"}}if(dec_places==0){new_number=new_number.replace(".","")}if(new_number==0){sign=""}return sign+new_number}
