// Global.js - Replaces FormChek.js
//
// Credit card validation provided by Eric Krock (c) 1997 Netscape Communications Corporation
//
// (c) 2000 Management Systems Modelling

// VARIABLE DECLARATIONS

var whitespace = " \t\n\r";

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
}

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
}

function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}

function isCarteBlanche(cc)
{
  return isDinersClub(cc);
}

function isAnyCard(cc)
{
  if (!isCreditCard(cc))
    return false;
  if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc)) {
    return false;
  }
  return true;
}

function isCardMatch(cardType, cardNumber)
{
	//cardType = cardType.toUpperCase();
	var doesMatch = true;

	if ((cardType == "VI") && (!isVisa(cardNumber)))
		doesMatch = false;
	if ((cardType == "MA") && (!isMasterCard(cardNumber)))
		doesMatch = false;
	if ( ( (cardType == "AX") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
	if ((cardType == "DN") && (!isDinersClub(cardNumber)))
		doesMatch = false;
	if ((cardType == "CB") && (!isCarteBlanche(cardNumber)))
		doesMatch = false;
	return doesMatch;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function stripCharsNotInBag(s, bag)
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function stripWhitespace(s)
{   return stripCharsInBag(s, whitespace);
}

function RemoveBad(InStr){
	InStr = InStr.replace(/\</g,"");
	InStr = InStr.replace(/\>/g,"");
	InStr = InStr.replace(/\"/g,"");
	InStr = InStr.replace(/\'/g,"");
	InStr = InStr.replace(/\%/g,"");
	InStr = InStr.replace(/\;/g,"");
	InStr = InStr.replace(/\(/g,"");
	InStr = InStr.replace(/\)/g,"");
	InStr = InStr.replace(/\&/g,"");
	InStr = InStr.replace(/\+/g,"");
		
	return InStr;
}

function cleanInput(input) {
	var s = input.value;
	input.value = RemoveBad(s);
	return true;
}

function RemoveBadCC(InStr){
	InStr = InStr.replace(/\</g,"");
	InStr = InStr.replace(/\>/g,"");
	InStr = InStr.replace(/\"/g,"");
	InStr = InStr.replace(/\'/g,"");
	InStr = InStr.replace(/\%/g,"");
	InStr = InStr.replace(/\;/g,"");
	InStr = InStr.replace(/\(/g,"");
	InStr = InStr.replace(/\)/g,"");
	InStr = InStr.replace(/\&/g,"");
	InStr = InStr.replace(/\+/g,"");
	InStr = InStr.replace(/\ /g,"");
	
	return InStr;
}
function cleanInputSpaces(input) {
	var s = input.value;
	input.value = RemoveBadCC(s);
	return true;
}
function OldFormatCurrency(f) {
	s = f.value;
	o = s;
	p = s.search(/[.]/);
	switch (p) {
		case -1: 
			s += '.00'; 
			break;
		case 0: 
			s = '0.' + o; 
			break;
		default: 
			sa = s.split('.'); 
			if (sa[1].length < 2) { 
				s += '0'; 
			} 
			break;
	}
	f.value = s;
}

function FormatCurrency(f) {
	num = f.value;
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num)) num = "0";
	f.value = FormatCurrencyAsString(num);
}

function FormatCurrencyAsString(c) {
	pence = Math.floor((c*100+0.5)%100);
	num = Math.floor((c*100+0.5)/100).toString();
	if (pence < 10) pence = "0" + pence;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0, num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));

	return num + '.' + pence;
}

function FormatSterling(c) {
	return "£" + FormatCurrencyAsString(c);
}

function DisplayCurrency(n, c) {
	var f = document.all[n];
	var type = browserType();
	if (type != 1) {
		f.value = FormatCurrencyAsString(c);
	} else {
		f.innerHTML = FormatSterling(c); 
	}
}

function isBlank(s) {
	var c;
	for(var i = 0; i < s.length; i++) {
		c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

function MM_swapImgRestore() 
{
	if (document.MM_swapImgData != null)
		for (var i=0; i<(document.MM_swapImgData.length-1); i+=2)
			document.MM_swapImgData[i].src = document.MM_swapImgData[i+1];
}

function MM_swapImage() 
{
	var i,j=0,objStr,obj,swapArray=new Array,oldArray=document.MM_swapImgData;
	for (i=0; i < (MM_swapImage.arguments.length-2); i+=3) {
		objStr = MM_swapImage.arguments[(navigator.appName == 'Netscape')?i:i+1];
		if ((objStr.indexOf('document.layers[')==0 && document.layers==null) || (objStr.indexOf('document.all[')   ==0 && document.all   ==null)) {
			objStr = 'document'+objStr.substring(objStr.lastIndexOf('.'),objStr.length);
		}
		obj = eval(objStr);
		if (obj != null) {
			swapArray[j++] = obj;
			swapArray[j++] = (oldArray==null || oldArray[j-1]!=obj)?obj.src:oldArray[j];
			obj.src = MM_swapImage.arguments[i+2];
		}
	}
	document.MM_swapImgData = swapArray; //used for restore
}

function isOrphan(c) 
{
	if (c > 0 ) {
		s1 = ((c == 1) ? 'is' : 'are');
		s2 = ((c == 1) ? 'item' : 'items');
		alert('Unable to delete this record since there ' + s1 + ' ' + c + ' related ' + s2);
		return false;
	} else return true;
}

function formSubmit() {
	if (formValidate()) {
		document.mainForm.submit();
	}
}

function formValidate() {
	f = document.mainForm;
	for(var i = 0; ((i < f.length)); i++) {
		if (f.elements[i].onchange != null) {
			if (!f.elements[i].onchange()) {
				//alert(f.elements[i].name);
				return false;
			}
		}
	}
	return true;
}

function validateInteger(field, title, allownull) {
	value = field.value;
	if (value.length < 1) {
		if (!allownull) {
			alert(title + ': This field will not accept a null value.');
			return false;
		}
		else return true;
	} else {
		valueint = parseInt(value);
		if (isNaN(valueint) || (valueint != value)) {
			alert(title + ': ' + value + ' is not an integer value.');
			return false;
		}
		else return true;
	}
}
	
function validateReal(field, title, allownull) {
	value = field.value;
	if (value.length < 1) {
		if (!allownull) {
			alert(title + ': This field will not accept a null value.');
			return false;
		}
		else return true;
	} else {
		valuereal = parseFloat(value);
		if (isNaN(valuereal) || (valuereal != value)) {
			alert(title + ': ' + value + ' is not an real value.');
			return false;
		}
		else return true;
	}
}

function isNull(s) 
{
	return (s.length <= 0);
}

function validateChar(field, title, len, checklength, allownull) 
{
	v = field.value;
	if ((!allownull) && (isNull(v))) {
		alert(title + ': A value must be entered for this field');
		return false;
	}
	if ((checklength) && (v.length > len)) {
		alert(title + ': Entered length ' + v.length + ' exceeds maximum of ' + len);
		return false;
	}
	return true;
}

function validateDate(o, allownull) 
{
	return true;
}

function validateEmail(o, len, checklength, allownull) 
{
	v = o.value;
	if ((allownull) && (isNull(v))) return true;
	if ((checklength) && (v.length > len)) {
		alert(o.name + ': Entered length ' + v.length + ' exceeds maximum of ' + len);
		return false;
	}
	okay = v.indexOf('@') >= 0;
	if (okay) return true;
	else {
		alert(o.name + ': does not contain a valid Email address');
		return false;
	}
}

function validatePassword(field) {
	value = field.value;
	if (value.length < 6) {
		alert('Password must be at least 6 characters in length.');
		return false;
	}
	else return true;
}

function validateNumber(o, min, max, range, allownull) 
{
	return validateNumberRaw(o, min, max, range, allownull, o.name);
}

function validateNumberRaw(o, min, max, range, allownull, name) 
{
	v = o.value;
	if (isNull(v)) {
		if (!allownull) {
			alert(name + ': A value must be entered for this field');
			return false;
		}
	}
	vi = parseInt(v);
	if (isNaN(vi) || (vi != v)) {
		alert(name + ': ' + v + ' is not a whole number');
		return false;
	}
	if (range) {
		if (((vi < min) && (min > 0)) || (( vi > max) && (max > 0))) {
			msg = name + ' must be';
			if (min > 0) msg = msg + ' at least ' + min;
			if (max > 0) {
				if (min > 0) msg = msg + ' and ';
				msg = msg + ' not more than ' + max;
			}
			alert(msg);
			return false;
		}
	}
	if (vi != v) {
		alert(name + ': ' + v + ' is not a whole number');
		return false;
	}
	return true;
}

function spanChange(id, str) {
  if (browserType()!=1) {
    with (document[id].document) {
      open();
      write(str);
      close();
    }
  } else {
    document.all[id].innerHTML = str;
  }
}

function browserType() {
	if (navigator.userAgent.indexOf("Mozilla/4.0") != -1) return 4;
	if (navigator.userAgent.indexOf("Mozilla/3.0") != -1) return 3;
	if (navigator.userAgent.indexOf("MSIE") != -1) return 1;
	if (navigator.userAgent.indexOf("Mozilla/2.0") != -1) return 2;
	return 0;
}
function uploadFormSubmit(){
	var c = 0;
	var d = 0;
	var f = document.uploadForm;
	for(var i = 0; i < f.length; i++) {
		var item = f.elements[i];
		var itemname = item.name;
		if (itemname.substring(0,8) == 'filename') {
			if (item.value==''){
				c++;
			}
			else{
				for(var i = 0; i < f.length; i++) {
					var item2 = f.elements[i];
					var itemname2 = item2.name;
					if (itemname2.substring(0,8) == 'filename') {
						if (item2.value==item.value){
							d++;
						}
					}
				
				}
			}
		}
	}
	if (c > 0) {
		alert('One or more input areas are blank');
		}
	else{
		if(d > 1){
			alert('Do NOT upload the same image more than once!');
		}
		else{document.uploadForm.submit();}
	}
}

function uploadCsvFormSubmit(){
	
	//make sure its a csv file
	strTemp = document.getElementById("filename1").value
	
	strTemp = strTemp.toString()
	strTemp = strTemp.toLowerCase()
	dots = strTemp.split(".")
	extension = dots[dots.length-1];
	
	if(extension!='csv'){
		alert('Please choose a CSV file to upload.');
	}else{
		document.getElementById("uploadForm").submit()
	}

}



/*
Form field Limiter script- By Dynamic Drive
For full source code and more DHTML scripts, visit http://www.dynamicdrive.com
This credit MUST stay intact for use
*/

var ns6=document.getElementById&&!document.all

function restrictinput(maxlength,e,placeholder){
if (window.event&&event.srcElement.value.length>=maxlength)
return false
else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
if (pressedkey.test(String.fromCharCode(e.which)))
e.stopPropagation()
}
}

function countlimit(maxlength,e,placeholder){
var theform=eval(placeholder)
var lengthleft=maxlength-theform.value.length
var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
if (window.event||e.target&&e.target==eval(placeholder)){
if (lengthleft<0)
theform.value=theform.value.substring(0,maxlength)
placeholderobj.innerHTML=lengthleft
}
}


function displaylimit(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='(<b><span id="'+theform.toString()+'">'+thelimit+'</span></b> characters remaining on your input limit)'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
}
}

