﻿
function alltrim(stringToTrim) {
  if (stringToTrim == null)
    return "";
  else
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
  if (stringToTrim == null)
    return "";
  else
   	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
  if (stringToTrim == null)
    return "";
  else
   	return stringToTrim.replace(/\s+$/,"");
}

function right(str, n){
  if (n <= 0)
    return "";
  else if (n > String(str).length)
    return str;
  else {
    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
  }
}

// Number to string, padding a 2-digit number with a left zero if needed:
function LZ(x) { return (x>=10||x<0?"":"0") + x }

// Return a date as a string in the format YYYYMMDD:
function jsYYYYMMDD(dtDate)
{
	return dtDate.getFullYear() * 10000 + (dtDate.getMonth() + 1) * 100 + dtDate.getDate();
}

// Return a datetime as a string in the format YYYYMMDD HH:MM:SS:
function jsSQLDateTime(dtDate)
{
	return (dtDate == null) ? "" : jsYYYYMMDD(dtDate) + " " + LZ(dtDate.getHours()) + ":" + LZ(dtDate.getMinutes()) + ":" + LZ(dtDate.getSeconds());
}

// Return a datetime as a string in the format YYYYMMDD 00:00:00:
function jsSQLDate(dtDate)
{
	return (dtDate == null) ? "" : jsYYYYMMDD(dtDate) + " 00:00:00";
}

// Return a date as a string in the format DD/MM/YY
function jsDDMMYY(dtDate)
{
	return LZ(dtDate.getDate()) + "/" + LZ(dtDate.getMonth() + 1) + "/" + (dtDate.getFullYear() + "").substr(2);
}

// Return a date as a string in the format DD/MM/YYYY
function jsDDMMYYYY(dtDate)
{
	return LZ(dtDate.getDate()) + "/" + LZ(dtDate.getMonth() + 1) + "/" + dtDate.getFullYear();
}

function jsMMM(dtDate) 
{
  var strMonths = "JanFebMarAprMayJunJulAugSepOctNovDec";
  return strMonths.substr(dtDate.getMonth() * 3, 3);
}

// Return a date as a string in the format DD MMM YYYY (e.g. 25 Feb 2008)
function jsDateToString(dtDate)
{
  // Don't use toUTCString, as this gets BST wrong around midnight.
  return dtDate.getDate() + " " + jsMMM(dtDate) + " " + dtDate.getFullYear();
}

// Return a date as a string in the format DD MMM YYYY HH:MM (e.g. 25 Feb 2008 09:00)
function jsDateTimeToString(dtDate)
{
  return jsDateToString(dtDate) + " " + LZ(dtDate.getHours()) + ":" + LZ(dtDate.getMinutes());
}

// Return a datetime as a string in the format YYYYMMDDHHMMSS
function jsDateTimeToTimeStamp(dtDate)
{
	return (dtDate == null) ? "" : jsYYYYMMDD(dtDate) + LZ(dtDate.getHours()) + LZ(dtDate.getMinutes()) + LZ(dtDate.getSeconds());
}

function jsTimeStampToDateTime(strDate) {
  // Convert a YYYYMMDDHHMMSS string to a datetime.
  if (strDate.length == 14) {
    var nYear = parseInt(strDate.substr(0, 4), 10);
    var nMonth = parseInt(strDate.substr(4, 2), 10) - 1;
    var nDay = parseInt(strDate.substr(6, 2), 10);
    var nHour = parseInt(strDate.substr(8, 2), 10);
    var nMins = parseInt(strDate.substr(10, 2), 10);
    var nSecs = parseInt(strDate.substr(12, 2), 10);
    if (nYear > 1970 && nMonth >= 0 && nMonth < 12 && nDay >= 1 && nDay <= 31)
      return new Date(nYear, nMonth, nDay, nHour, nMins, nSecs);
  }
  debugger; // Will only get here if the function is called incorrectly
  return null;
}

function jsNoDoubleQuotes(strSource) {
  if (strSource == null)
    return "";
  return strSource.replace(/\"/g, "");
}

function jsNoQuotes(strSource) {  
  // See http://msdn.microsoft.com/en-us/library/ms161953.aspx
  if (strSource == null)
    return "";
  var strResult = strSource.replace(/\'/g, "");
  strResult = strResult.replace(/;/g, "");
  strResult = strResult.replace(/--/g, "");
  return strResult.replace(/\"/g, "");
}

function jsSafeInt(nSource) {
  if (typeof nSource == "undefined")
    return 0;
  else {
    var nResult = parseInt("" + nSource, 10);
    return isNaN(nResult) ? 0 : nResult;
  }
}

function jsSafeFloat(nSource) {
  if (typeof nSource == "undefined")
    return 0.0;
  else {
    var nResult = parseFloat("" + nSource);
    return isNaN(nResult) ? 0.0 : nResult;
  }
}

function jsSessionToString(strSessionName) {
  if (Session(strSessionName) == undefined)
    return "";
  else
    return Session(strSessionName);
}

function jsOccurs(strText, strFind)
{
  // How many times is strFind in strText?
  var nOccurs = 0;
  var nStart = -1;
  do {
    nStart = strText.indexOf(strFind, nStart + 1);
    if (nStart > -1)
        nOccurs++;
    else
      break;
  } while (true);
  return nOccurs;
}

function GetXMLTagAndAttribs(strXML, strTag, bOuter) {
  // Get a named tag which may have attribs.
  // Return the tag contents and the attribs in an array.
  // If bOuter = true, include the enclosing tag and end tag.
	var arrResult = new Array();
	arrResult[0] = "";
	arrResult[1] = "";
	var nAt = strXML.indexOf("<" + strTag + ((strTag.indexOf(" ") == -1) ? " " : ""));
	if (nAt > -1) {
	  var nEndTag = strXML.indexOf(">", nAt + strTag.length + 1);
	  if (nEndTag > -1) {
	    if (strXML.substring(nEndTag - 1) == "/") {
		      arrResult[0] = bOuter ? strXML.substring(nAt, nEndTag) : "";
		      arrResult[1] = strXML.substring(nAt + strTag.length + 2, nEndTag - 1);
	    }
	    else {
	      var strShortTag = strTag;
	      var nSpace = strTag.indexOf(" ");
	      if (nSpace > -1)
	        strShortTag = strTag.substr(0, nSpace);
	        
		    var nClose = strXML.indexOf("</" + strShortTag + ">", nEndTag);
		    if (nClose > -1) {
		      arrResult[0] = bOuter ? strXML.substring(nAt, nClose + strShortTag.length + 3) : strXML.substring(nEndTag + 1, nClose);
		      arrResult[1] = strXML.substring(nAt + strShortTag.length + 2, nEndTag);
		    }
		  }
		}
	}
	else {
	  nAt = strXML.indexOf("<" + strTag + ">");
	  if (nAt > -1) {
	    var nEndTag = nAt + strTag.length + 2;
      var nClose = strXML.indexOf("</" + strTag + ">", nEndTag);
      if (nClose > -1) {
        arrResult[0] = bOuter ? strXML.substring(nAt, nClose + strTag.length + 3) : strXML.substring(nEndTag + 1, nClose);
      }
	  }
	}
	return arrResult;
}

function jsGetXMLAttrib(strAttribs, strAttribName)
{
  // Get a named attrib from a list (XML style)
  var strValue = "";
  var nAt = strAttribs.indexOf(strAttribName + "=\"");
  if (nAt > -1) {
    var nClose = strAttribs.indexOf("\"", nAt + strAttribName.length + 2);
    if (nClose > -1) {
      strValue = strAttribs.substring(nAt + strAttribName.length + 2, nClose);
    }
  }
  return strValue;
}

function jsReplace(strText, strFind, strReplace, bFirstOnly)
{
  // Replace one or more occurrences of strFind in strText with strReplace.
  //  bFirstOnly = true: Only replace the first occurrence.
  //  bFirstOnly = false: Replace all occurrences.
  if (strFind != "") {
    var nFound = -1;
    do {
      nFound = strText.indexOf(strFind, nFound + 1);
      if (nFound > -1) {
        strText = strText.substr(0, nFound) + strReplace + strText.substr(nFound + strFind.length);
        if (bFirstOnly)
          nFound = -1;
      }
    } while (nFound > -1 && strText != "");
  }
  return strText;
}

function jsNumToCurrency(nValue, bSimplify)
{
  // Convert the given value to a currency format (e.g. 9.50).
  // If bSimplify is true, 9.00 will get simplified to 9.
  var strResult = nValue.toFixed(2);
  if (bSimplify && right(strResult, 3) == ".00")
    strResult = nValue.toFixed(0);
  return strResult;
}

function jsShortAddress(strAddress, strPostcode)
{
  if (strPostcode == "") {
     strAddress = jsReplace(jsReplace(strAddress, " | ", ", ") + "  ", ",  ", "");
  }
  else {
    var nAt = strAddress.indexOf(",");
    var nAt2 = strAddress.indexOf("|");
    if (nAt2 > -1 && nAt2 < nAt)
      nAt = nAt2;
    if (nAt > -1) {
      strAddress = strAddress.substr(0, nAt) + " " + strPostcode;
    }
    else {
     strAddress = jsReplace(jsReplace(strAddress, " | ", ", ") + "  ", ",  ", "");
    }
  }
  return strAddress;  
}

function jsMaxWidth(strText, nMaxLength)
{
  if (strText.length > nMaxLength) {
    return strText.substr(0, nMaxLength);
  }
  else {
    return strText;
  }
}

function jsPrepareColumn(strData, nMaxLength)
{
  return jsMaxWidth(jsNoQuotes(alltrim(strData)), nMaxLength);
}

function jsCleanAddress(strAddress)
{
  // Cleans an address, removing pipes, double commas etc. Does NOT remove quotes or limit width.
  strAddress = jsReplace(jsReplace(strAddress, " | ", ", ") + "  ", ",  ", ", ");
  strAddress = jsReplace(strAddress, ", , ", ", ");
  strAddress = jsReplace(strAddress, ", , ", ", ");
  strAddress = jsReplace(strAddress, ",, ", ", ");
  strAddress = alltrim(jsReplace(strAddress, ",, ", ", "));
  while (right(strAddress, 1) == ",") {
    strAddress = rtrim(strAddress.substring(0, strAddress.length - 1));
  }
  while (strAddress.substring(0, 1) == ",") {
    strAddress = ltrim(strAddress.substring(1));
  }
  return strAddress;
}

function jsTextToPoint(strText)
{
  var nX = 0;
  var nY = 0;

  var strTemp = strText;
  var nComma = strTemp.indexOf(",");
  if (nComma > -1) {
    nX = jsSafeInt(strTemp.substring(0, nComma));
    strTemp = strTemp.substring(nComma + 1);

    nY = jsSafeInt(strTemp);
  }
  
  return [nX, nY];
}

function jsTextToRect(strText)
{
  var nLeft = 0;
  var nTop = 0;
  var nRight = 0;
  var nBottom = 0;

  var strTemp = strText;
  var nComma = strTemp.indexOf(",");
  if (nComma > -1) {
    nLeft = jsSafeInt(strTemp.substring(0, nComma));
    strTemp = strTemp.substring(nComma + 1);

    nComma = strTemp.indexOf(",");
    if (nComma > -1) {
      nTop = jsSafeInt(strTemp.substring(0, nComma));
      strTemp = strTemp.substring(nComma + 1);

      nComma = strTemp.indexOf(",");
      if (nComma > -1) {
        nRight = jsSafeInt(strTemp.substring(0, nComma));
        strTemp = strTemp.substring(nComma + 1);

        nBottom = jsSafeInt(strTemp);
      }
    }
  }
  
  return [nLeft, nTop, nRight, nBottom];
}

function jsIsDigit(strChar)
{
  var strDigits = "0123456789";
  return strDigits.indexOf(strChar.substr(0, 1)) > -1;
}

function jsIsLetter(strChar)
{
  var strLetters = "abcdefghijklmnopqrstuvwxyz";
  return strLetters.indexOf(strChar.substr(0, 1).toLowerCase()) > -1;
}

function jsStartsWith(strString, strStart) {
  return strString.substr(0, strStart.length) == strStart;
}

function jsEndsWith(strString, strEnd) {
  return strString.substr(strString.length - strEnd.length) == strEnd;
}

function jsCheckPostcode(strPostcode)
{
  return strPostcode != "" && strPostcode.match(/[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}/);
  // This is the alternative short regular expression from
  // http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
}

function jsCheckEmailAddress(strEmail) {
  // Check a basic email pattern.
  return alltrim(strEmail) != ""
        && strEmail.indexOf("@") >= 1
        && strEmail.lastIndexOf(".") > strEmail.indexOf("@")
        && (strEmail.length - strEmail.lastIndexOf(".") - 1) >= 2
        && (strEmail.length - strEmail.lastIndexOf(".") - 1) <= 3
        && alltrim(strEmail).indexOf(" ") == -1;
}
