/*
Reusable Javascript functions

NOTES:
 REGEX - Do not use /d for 'any digit' as this is not supported in all browsers (e.g. IE for Mac). Use [0-9] instead
         Do not use /w for 'non-whitespace' as this is not supported in all browsers (e.g. IE for Mac). Instead, use [a-zA-Z0-9_] without /i
         or [A-Z0-9_] with the /i option
         Only use the Regexp('expression','options') syntax
      
*/

function isBranch(strBranchCode){
	if (window.RegExp) {
			var re = new RegExp('^[0-9]{2}-[0-9]{2}-[0-9]{2}$', '');
            return re.test( strBranchCode );
	}
	else {
			if (strBranchCode.length != 8) { return false } else { return true }
	}
}

function isPhone(strTelephone){
	if (window.RegExp) {
		var re = new RegExp('^[+]?[0-9]+[0-9 ]*$', '');
		return re.test(strTelephone);
	}
	else {
			if (strTelephone.length == 0) { return false } else { return true }
		}
}
function isNumeric(strNumber){
	if (window.RegExp) {	
		var re = new RegExp('^[0-9]+$', '');
		return re.test(strNumber);
	}
	else {
		if (strNumber.length == 0) { return false } else { return true }
	}
}

function isDecimal(strNumber){
	if (window.RegExp){
		var re = new RegExp('^[0-9]*\.?[0-9]*$', '');
		return re.test(strNumber);
	} else {
		if (strNumber.length == 0) { return false } else { return true }
	}
}

function isCurrency(str){
	if (window.RegExp){
		var re = new RegExp('^[0-9]*(\.[0-9]{2})?$', '');
		return re.test(str);
	} else {
		if (str.length == 0) { return false } else { return true }
	}

}

function isCompanyRegistration(strReg){
	if (window.RegExp) {	
		var re = new RegExp('^[0-9]{8}$', '');
		return re.test(strReg);
	}
	else {
		if (strReg.length == 0) { return false } else { return true }
	}
		
}
function isVAT(strVAT){
	if (window.RegExp) {	
		var re = new RegExp('^GB[0-9]{9}$', 'i');
		return re.test(strVAT);
	}
	else {
		if (strVAT.length == 0) { return false } else { return true }
	}
}

function isEmail(strEmail){
	if (window.RegExp) {	
		var re = new RegExp('^[A-Z0-9_-]{1}[A-Z0-9_\.-]*[@]{1}[A-Z0-9_-]+[\.]{1}[A-Z0-9_-]+[A-Z0-9_\.-]+$', 'i');
		return strEmail.match(re) 
		//return re.test(strEmail);
	}
	else {
		return isEmailNoRegex(strEmail)
	}
}

function IsValidGuid(strEntry){
	if (window.RegExp) {	
		var re = new RegExp('[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', 'i')
		return re.test(strEntry)
	}
	else {
		if (strEntry.length == 0) { return false } else { return true }
	}
}
function isLeap (y) {
return (((y%4==0) && ((!(y%100==0)) || (y%400==0))) ? true : false );
}

function daysInMonth (m,y,bNumericMonth) {
	var aDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
	if (bNumericMonth){
		return (m==2 && isLeap(y)) ? 29 : aDays[m-1]	
	} else {
		var thisMonth = new Date("1 " + m + " " + y)
		var m = thisMonth.getMonth()
		return (m==1 && isLeap(y)) ? 29 : aDays[m]
	}
}

function validDMY (d,m,y, bNumericMonth) {
	return  (y < 1650 || d < 0 || d > daysInMonth(m,y, bNumericMonth)) ? false :  true;
}

function isaDate (strDate, nullOK) {
	if (nullOK && strDate =='') {
	    return true;
	} else {

	//for european date format: var RE = /([0-9]{1,2})\.([0-9]{2})\.([0-9]{4})/i.exec(strDate);
	//for british date format: var RE = /([0-9]{1,2})\/([0-9]{2})\/([0-9]{4})/i.exec(strDate);
	//medium date    var RE = /([0-9]{1,2})\W(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\W([0-9]{4})/i.exec(strDate);
		var bNumericMonth = true
	    var RE = /([0-9]{1,2})\/([0-9]{2})\/([0-9]{4})/i.exec(strDate);
	    if (RE) {
	        if (bNumericMonth){
				return validDMY(RE[1]*1, RE[2]*1, RE[3]*1, true) 
			} else {
				return validDMY(RE[1]*1, RE[2], RE[3]*1, false) 
			}
	    } else {
			return false;
	    }
	}
}

function isFutureDate(strDate, strLimit, nullOK) {
	if (nullOK && strDate =='') {
	    return true;
	} else {
		if (isDate(strDate, "dd/MM/yyyy")) {
			//strDate = strDate.replace("/",".")
			var d = new Date(getDateFromFormat(strDate, "dd/MM/yyyy"))
			var today = new Date()
			var latestDate = new Date(today.getTime() + (strLimit *1000*60*60*24))
			return ((d.getTime() > today.getTime()-1000*60*60*24) && (d.getTime() < latestDate.getTime()));
		} else {
			return false;
		}
	}
}

String.prototype.replace = stringReplace
function stringReplace(findText, replaceText){
	var originalString = new String(this)
	var len = findText.length
	var pos = 0
	pos = originalString.indexOf(findText)
	while (pos != -1){
		preString = originalString.substring(0,pos)
		postString = originalString.substring(pos + len , originalString.length)
		originalString = preString + replaceText + postString
		pos = originalString.indexOf(findText)
	}
	return originalString
}

function disableButtons(theform) {
	if (document.all || document.getElementById) {
		for (i = 0; i < theform.length; i++) {
			var tempobj = theform.elements[i];
			if (tempobj.type.toLowerCase() == "button" || tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset") {
				tempobj.disabled = true;
			}
		}
	}
}			

function closePopUpWindow(){
	if (window.windowOpen){
		openedWindow.close();
		confirmClosed();
	}
}
function confirmClosed(){
	windowOpen = false;
}

function popUpHelp(theURL,features) {
	closePopUpWindow();
	openedWindow = open(theURL,'GCHelp',features+"resizable=no,status=no,location=no,toolbar=no,scrollbars=yes,left=100,top=30,screenX=0,screenY=0");
	openedWindow.onunload = confirmClosed;
	onunload = closePopUpWindow;
	windowOpen = true;
	return (openedWindow);
}


/* 
	Non REGEX validation functions

*/
// whitespace characters
var whitespace = " \t\n\r";

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}
/****************************************************************/
// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isEmailNoRegex (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;
    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function CopyToClipboard(FData) {
     FData.focus();
     FData.select();
     var copyText = FData.value;
     if (window.clipboardData) { // IE send-to-clipboard method.
          window.clipboardData.setData('Text', copyText);
          
     } else if (window.netscape) {
          // You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
          netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
          
          // Store support string in an object.
          var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
          if (!str) return false;
          str.data=copyText;
          
          // Make transferable.
          var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
          if (!trans) return false;
          
          // Specify what datatypes we want to obtain, which is text in this case.
          trans.addDataFlavor("text/unicode");
          trans.setTransferData("text/unicode",str,copyText.length*2);
          
          var clipid=Components.interfaces.nsIClipboard;
          var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
          if (!clip) return false;
          
          clip.setData(trans,null,clipid.kGlobalClipboard);
     }
	 alert("'" + copyText + "' has been copied to the clipboard")
}



/*var requestSubmitted = false;   
function checkandsubmit() {
      if(requestSubmitted == true) {
         alert("You have already submitted " + 
            "the request.. Please wait");
            return;
         }
      requestSubmitted = true;
      //test is a name of the form in the example
      document.test.submit();
      }
*/
