/*
  JScript library    - common.js
  Author             - Brendon Matthews

Contents
  Common Methods.

History
  Oct 2000		BM				Started.
  Aug 2002		BM				Added Currency Formatting methods.
  May 2006		BM				Stripped tCommon functions.
  Jul 2006		BM				Added filterURL and filterEmail functions
  Dec 2006		BM				Removed currency formatting (replaced with generic decimal formatting)
  Feb 2007		BM				Removed Custom Select functions (these were moved to obj_tCustomSelect.js)
*/

// ---------------------- Image Preloading ---------------------- //

function BSP_preloadImages() { 
	if(document.images && arguments) {
		if(!document.BSP_p) document.BSP_p = new Array();
		var i,j = document.BSP_p.length;
		for(i=0; i<arguments.length; i++) {
			if (arguments[i] != null && arguments[i].indexOf("#") != 0) { 
				document.BSP_p[j] = new Image();
				document.BSP_p[j++].src = arguments[i];
			}
		}
	}
}

// ---------------------- Special Constants ---------------------- //

BSP_DOMAIN_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-';
BSP_MAILBOX_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&\'*+-/=?^_`{|}~.';

function BSP_validateDomainName(value) {
	if (value == null) return false;
	value = ""+value;
	if (value.length == 0) return false;
	var c;
	var len = 0;
	var lev = 1;
	for (x=0; x<value.length; x++) {
		c = value.charAt(x);
		if (c == '.') {
			if (len == 0) return false;
			len = 0;
			lev++;
		}
		else if (BSP_DOMAIN_CHARS.indexOf(c) < 0) {
			return false;
		}
		else {
			len++;
		}
	}
	return (lev > 1 && len > 0);
}

// ---------------------- Special Object Methods ---------------------- //

function getRadioGroupValue(rgp,value) {
	if (rgp == null) return value;
	if (rgp.length == null) {
		if (rgp != null) {
			if (rgp.checked) {
				value = rgp.value;
			}
		}
	}
	for (var i=0; i<rgp.length; i++) {
		if (rgp[i].checked) {
			value = rgp[i].value;
		}
	}
	return value;
}

function getComboBoxValue(cmb,value) {
	if (cmb == null) return value;
	for (var i=0; i<cmb.options.length; i++) {
		if (cmb.options[i].selected) {
			value = cmb.options[i].value;
		}
	}
	return value;
}

function stringReplaceAll(value,regex,repl) {
	if (!value || value == '') return '';
	if (!regex || regex == '') return value;
	value = ''+value;
	var result = '';
	var x = value.indexOf(regex);
	while (x >= 0) {
		result += value.substring(0,x);
		if (repl) result += repl;
		value = value.substring(x+regex.length);
		x = value.indexOf(regex);
	}
	return result+value;
}

function parseJSString(value) {
	value = stringReplaceAll(value,'\\','\\\\');
	value = stringReplaceAll(value,'\r','\\r');
	value = stringReplaceAll(value,'\n','\\n');
	value = stringReplaceAll(value,'\t','\\t');
	value = stringReplaceAll(value,'\'','\\\'');
	value = stringReplaceAll(value,'"','\\"');
	return value;
}

function parseHTMLString(value) {
	value = stringReplaceAll(value,'&','&amp;');
	value = stringReplaceAll(value,'<','&lt;');
	value = stringReplaceAll(value,'>','&gt;');
	value = stringReplaceAll(value,'\r','');
	value = stringReplaceAll(value,'\n','<br>\n');
	return value;
}

function parseArgumentString_s(arg) {
	if (arg == null) return 'null';
	else return '\''+parseJSString(arg)+'\'';
}

function parseArgumentString(args) {
	if (!args || args.length == 0) return '';
	var result = parseArgumentString_s(args[0]);
	for (i=1; i<args.length; i++) {
		result += ","+parseArgumentString_s(args[i]);
	}
	return result;
}

// ---------------------- Field Filter Methods ---------------------- //

function filterIntegerValue(value) {
	if (value == null) return 0;
	value = ""+value;
	var temp;
	var result = "";
	var minus = false;
	for (var i=0; i<value.length; i++) {
		temp = value.charAt(i);
		if (temp == '-') {
			if (result.length == 0) minus = !minus;
		}
		else if (temp == '.') {
			i = value.length;
		}
		else if (temp == '0') {
			if (result.length > 0) result += temp;
		}
		else if (temp == '1' || temp == '2' || temp == '3' || temp == '4'
				|| temp == '5' || temp == '6' || temp == '7' || temp == '8' || temp == '9') {
			result += temp;
		}
	}
	if (result.length == 0) return 0;
	else if (minus) return parseInt("-"+result);
	else return parseInt(result);
}

function filterDecimalValue(value) {
	if (value == null) return 0.0;
	value = ""+value;
	var temp;
	var result = "";
	var minus = false;
	var founddp = false;
	for (var i=0; i<value.length; i++) {
		temp = value.charAt(i);
		if (temp == '-') {
			if (result.length == 0) minus = !minus;
		}
		else if (temp == '.') {
			if (result.length == 0) result = "0.";
			else if (!founddp) result += temp;
			founddp = true;
		}
		else if (temp == '0') {
			if (result.length > 0) result += temp;
		}
		else if (temp == '1' || temp == '2' || temp == '3' || temp == '4'
				|| temp == '5' || temp == '6' || temp == '7' || temp == '8' || temp == '9') {
			result += temp;
		}
	}
	if (result.length == 0) return 0.0;
	if (!founddp) result += ".0";
	else if (result.substring(result.length-1) == '.') result += "0";
	if (minus) return parseFloat("-"+result);
	else return parseFloat(result);
}

function filterDateValue(value) {
	if (value == null) return null;
	value = ""+value;
	var i = value.indexOf('-');
	while (i >= 0) {
		value = value.substring(0,i)+'/'+value.substring(i+1);
		i = value.indexOf('-');
	}
	// Read field values
	i = value.indexOf("/");
	if (i <= 0) return null;
	var day = value.substring(0,i);
	value = value.substring(i+1);
	i = value.indexOf("/");
	if (i <= 0) return null;
	var month = value.substring(0,i);
	value = value.substring(i+1);
	i = value.indexOf(" ");
	if (i < 0) {
		year = value;
		value = "";
	}
	else {
		year = value.substring(0,i);
		value = value.substring(i+1);
	}
	// Verify field values
	while (day.length > 1 && day.charAt(0) == '0') day = day.substring(1);
	day = parseInt(day);
	if (isNaN(day) || day < 1 || day > 31) return null;
	while (month.length > 1 && month.charAt(0) == '0') month = month.substring(1);
	month = parseInt(month);
	if (isNaN(month) || month < 1 || month > 12) return null;
	if (year.length <= 2) {
		if (year.length > 1 && year.charAt(0) == '0') year = year.substring(1);
		year = parseInt(year);
		if (isNaN(year) || year < 0) return null;
		if (year < 50) year += 2000;
		else year += 1900;
	}
	else {
		while (year.length > 1 && year.charAt(0) == '0') year = year.substring(1);
		year = parseInt(year);
		if (isNaN(year) || year < 0 || year > 9999) return null;
	}
	// Return the date
	return new Date(year,month-1,day);
}

function filterEmailValue(value) {
	if (value == null) return "";
	value = ""+value;
	// Check for quoted local part, any text character allowed up to end of quotes
	if (value.indexOf('"') == 0) {
		var x = value.lastIndexOf('"')+1;
		if (x == 1 || x == value.length || value.charAt(x) != '@') return "";
		var domain = value.substring(x+1);
		value = value.substring(0,x);
		if (!BSP_validateDomainName(domain)) return "";
	}
	// Normal email addresses
	else {
		var x = value.indexOf("@");
		if (x < 1 || x == value.length-1) return "";
		var domain = value.substring(x+1);
		if (!BSP_validateDomainName(domain)) return "";
		value = value.substring(0,x);
		var c;
		for (x=0; x<value.length; x++) {
			c = value.charAt(x);
			if (c == '.') {
				// Cannot begin or end with dot
				if (x == 0 || x == value.length-1) 
					return "";
			}
			else if (BSP_MAILBOX_CHARS.indexOf(c) < 0) {
				return "";
			}
		}
	}
	return value+'@'+domain.toLowerCase();
}

function filterURLValue(value,allowEmails) {
	if (value == null) return "";
	var scheme = '';
	var uri = ""+value;
	var x = uri.indexOf(':');
	if (x > 0) {
		var temp = uri.substring(0,x+1).toLowerCase();
		if (temp == 'http:' || temp == 'https:' || temp == 'ftp:') {
			uri = uri.substring(x+1);
			while (uri.length > 0 && uri.charAt(0) == '/') {
				uri = uri.substring(1);
			}
			scheme = temp;
		}
		else if (allowEmails && temp == 'mailto:') {
			uri = uri.substring(x+1);
		}
	}
	// Scheme not found, try to guess
	var query = '';
	if (scheme == '') {
		x = uri.indexOf('@');
		y = uri.indexOf('?');
		if (allowEmails && x >= 0 && (y < 0 || y > x)) {
			// Guess email URL
			scheme = 'mailto:';
		}
		else if (uri.indexOf("/") == 0 || uri.indexOf("\\") == 0) {
			// Guess local http (must be absolute URL)
			scheme = '';
		}
		else {
			// Guess remote http
			scheme = 'http:';
		}
	}
	// Process HTTP or FTP uri's
	if (scheme == 'http:' || scheme == 'https:' || scheme == 'ftp:') {
		var host = uri;
		uri = '';
		x = host.indexOf("#");
		if (x >= 0) {
			query = host.substring(x)+query;
			host = host.substring(0,x);
		}
		x = host.indexOf("?");
		if (x >= 0) {
			query = host.substring(x)+query;
			host = host.substring(0,x);
		}
		x = host.indexOf("/");
		if (x >= 0) {
			uri = host.substring(x)+uri;
			host = host.substring(0,x);
		}
		x = host.indexOf("\\");
		if (x >= 0) {
			uri = host.substring(x)+uri;
			host = host.substring(0,x);
		}
		// Split out the Port String
		var port = '';
		x = host.indexOf(":");
		if (x >= 0) try {
			port = ':'+parseInt(host.substring(x+1));
			host = host.substring(0,x);
		}
		catch (e) {
			return "";
		}
		// Split out the username
		var user = '';
		if (scheme == 'ftp:') {
			x = host.indexOf("@");
			if (x >= 0) {
				user = host.substring(0,x+1);
				host = host.substring(x+1);
			}
		}
		// Check the domain name
		if (!BSP_validateDomainName(host)) return "";
		if (scheme == 'ftp:') query = '';
		scheme = scheme+'//'+user+host.toLowerCase()+port;
	}
	// Process MAILTO uri's
	else if (scheme == 'mailto:') {
		var email = uri;
		uri = '';
		x = email.indexOf("?");
		if (x >= 0) {
			query = email.substring(x)+query;
			email = email.substring(0,x);
		}
		email = filterEmailValue(email);
		if (email == '') return "";
		scheme = 'mailto:'+email;
	}
	// Process other (local HTTP) uri's
	else {
		x = uri.indexOf("#");
		if (x >= 0) {
			query = uri.substring(x)+query;
			uri = uri.substring(0,x);
		}
		x = uri.indexOf("?");
		if (x >= 0) {
			query = uri.substring(x)+query;
			uri = uri.substring(0,x);
		}
	}
	// Filter out uri and query string stuff
	x = query.indexOf(" ");
	while (x >= 0) {
		query = query.substring(0,x)+"%20"+query.substring(x+1);
		x = query.indexOf(" ");
	}
	x = uri.indexOf(" ");
	while (x >= 0) {
		uri = uri.substring(0,x)+"%20"+uri.substring(x+1);
		x = uri.indexOf(" ");
	}
	x = uri.indexOf("\\");
	while (x >= 0) {
		uri = uri.substring(0,x)+"/"+uri.substring(x+1);
		x = uri.indexOf("\\");
	}
	// Return result
	return scheme+uri+query;
}

function filterInteger(item) {
	if (item == null || item.value == null) return 0;
	var result = filterIntegerValue(""+item.value);
	item.value = result;
	return result;
}

function filterDecimal(item) {
	if (item == null || item.value == null) return 0.0;
	var result = filterDecimalValue(""+item.value);
	item.value = ""+result;
	return result;
}

function filterDate(item) {
	if (item == null || item.value == null) return "";
	var result = filterDateValue(""+item.value);
	if (result == null) {
		item.value = "";
	}
	else {
		var day = ""+result.getDate();
		var month = ""+(result.getMonth()+1);
		var year = ""+result.getFullYear();
		if (day.length == 1) day = "0"+day;
		if (month.length == 1) month = "0"+month;
		while (year.length < 4) year = "0"+year;
		item.value = day+"/"+month+"/"+year;
	}
	return result;
}

function filterEmail(item) {
	if (item == null || item.value == null) return "";
	var result = filterEmailValue(""+item.value);
	item.value = result;
	return result;
}

function filterURL(item,allowEmails) {
	if (item == null || item.value == null) return "";
	var result = filterURLValue(""+item.value,allowEmails);
	item.value = result;
	return result;
}

// ---------------------- Decimal Formatting Methods ---------------------- //

function integerToDecimal(ivalue,places,thousands) {
	var value = "";
	var sign = "";
	if (ivalue < 0) {
		sign = "-";
		ivalue = -ivalue;
	}
	if (places > 0) {
		for (var i=0; i<places; i++) {
			value = ""+(ivalue%10)+value;
			ivalue = parseInt(ivalue/10);
		}
		value = "."+value;
	}
        if (thousands) {
                var temp = "";
	        while (ivalue >= 1000) {
		        temp = ""+(ivalue%1000);
		        while (temp.length < 3) temp = "0"+temp;
		        value = ","+temp+value;
		        ivalue = parseInt(ivalue/1000);
	        }
        }
        return sign+ivalue+value;
}

function decimalToInteger(value,places) {
	var i = value.indexOf(".");
	if (places <= 0) {
		if (i < 0) return parseInt(value);
		else return parseInt(value.substring(0,i));
	}
	else if (i < 0) {
		for (i=0; i<places; i++) value += "0";
	}
	else {
		var decimal = value.substring(i+1);
		if (decimal.length > places) decimal = decimal.substring(0,places);
		else while (decimal.length < places) decimal += "0";
		value = value.substring(0,i)+decimal;
	}
	if (value.substring(0,1) == "-") {
		value = value.substring(1);
		while (value.length > 1 && value.charAt(0) == '0') value = value.substring(1);
		value = "-"+value;
	}
	else {
		while (value.length > 1 && value.charAt(0) == '0') value = value.substring(1);
	}
	return parseInt(value);
}

// ---------------------- Other Methods ---------------------- //

function getElementOffsets(element,parent) {
	var coords = {x: 0, y: 0};
	while (element) {
		if (parent && element == parent) {
			return coords;
		}
		coords.x += element.offsetLeft;
		coords.y += element.offsetTop;
		element = element.offsetParent;
	}
	return coords;
}
