// global values...
var CurrentDate    = new Date();
var CurrentDay     = CurrentDate.getDate();
var CurrentMonth   = CurrentDate.getMonth();
var CurrentYear    = CurrentDate.getYear();

if (CurrentYear < 1000) CurrentYear += 1900;

//var DaysinMonth    = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
//var AllDaysinMonth = new Array("DD","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15",
                               //"16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31");
//var DisplayedDay;
//var DisplayedMonth;
//var DisplayedYear;

var digits               = "0123456789";
var lowercaseLetters     = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var validDomainNameChars = digits + uppercaseLetters + lowercaseLetters + "-_./?=:~#+%&@";
var validEmailChars      = digits + uppercaseLetters + lowercaseLetters + "./-_"
var alphaDelimiters      = "'()$-._: ";                                  // bag of allowed characters for alpha and alphanumeric strings
var numberDelimiters     = ".";                                          // bag of allowed characters for numeric strings
var telephoneDelimiters  = "-().+ ";                                     // bag of allowed characters for telephone numbers
var globalDelimeters     = "/@" + alphaDelimiters + telephoneDelimiters; // bag of allowed characters for global defaults page.

// ************************************************************************

function isEmpty(theField)
{
  return ((theField == null) || (theField.length == 0))
}

// ************************************************************************

function stripCharsInBag (theField, bag)
{
  var i;
  var returnString = "";

  for (i = 0; i < theField.length; i++)
  {   
    var c = theField.charAt(i);

    if (bag.indexOf(c) == -1)
    {
      returnString += c;
    }
  }
  return returnString;
}

// ************************************************************************

function isLetter(c)
{
  return (((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")))
}

// ************************************************************************

function isDigit(c)
{
  return ((c >= "0") && (c <= "9"))
}

// ************************************************************************

function isLetterOrDigit(c)
{
  return (isLetter(c) || isDigit(c))
}

// ************************************************************************

// Checks for valid characters in a string
function isLegalData(theField, dataType)
{
  var i;

  if (isEmpty(theField))
  {
    return true;
  }

  if ((dataType == 0) || (dataType == 2))
  {
    theField = stripCharsInBag(theField, alphaDelimiters);
  }
  else if (dataType == 1)
  {
    theField = stripCharsInBag(theField, numberDelimiters);
  }
  else if (dataType == 3)
  {
    theField = stripCharsInBag(theField, telephoneDelimiters);
  }
  else if (dataType == 6)
  {
    theField = stripCharsInBag(theField, globalDelimeters);
  }

  for (i = 0; i < theField.length; i++)
  {   
    var c = theField.charAt(i);

    switch (dataType)
    {
      case 0:  if (!(isLetter(c)))
               {
                 return false;
               }
               break;
      case 1:  if (!(isDigit(c)))
               {
                 return false;
               }
               break;
      case 2:  if (!(isLetterOrDigit(c)))
               {
                 return false;
               }
               break;
      case 3:  if (!(isDigit(c)))
               {
                 return false;
               }
               break;
      case 6:  if (!(isLetterOrDigit(c)))
               {
                 return false;
               }
               break;
      default: break;
    }
  }

  return true;
}

// ************************************************************************

// Checks that a string is in URL format
function isURL(theField, theMsg)
{
  if (isEmpty(theField))
  {
    return true;
  }

  var i           = 0;
  var j           = 0;
  var k           = 0;
  var URLstart    = 0;
  var fieldString = theField.value
  var fieldLength = fieldString.length;
  var msg3        = "\nPlease try again";

  // Check for invalid characters in string
  while ((j < fieldLength) && (validDomainNameChars.indexOf(fieldString.charAt(j)) != -1))
  {
    j++
  }

  if (j < fieldLength)
  {
    theMsg = theMsg + "\nThere are invalid characters in the domain name." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  // Check for missing "dot" in domain name
  while ((i < fieldLength) && (fieldString.charAt(i) != "."))
  {
    i++
  }

  if (i == fieldLength)
  {
    theMsg = theMsg + "\nThere is no \"dot\" in the domain name." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  // Check for case of "dot" being the first character
  if (i == (URLstart))
  {
    theMsg = theMsg + "\nThere are no characters before the first \"dot\" in the domain name." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }
			
  // Check for too many "dots" in the domain name
  k = URLstart + 1;
  while (k < fieldLength)
  {
    if ((fieldString.charAt(k) == ".") && (fieldString.charAt(k + 1) == "."))
    {
      theMsg = theMsg + "\nThere are too many \"dots\". in the domain name" + msg3;
      warnInvalid(theField, theMsg);
      return false;
    }
    k++;
  }

  // Check for case of "dot" being the last character
  l = fieldLength;
  while ((i < fieldLength - 2) && (l != i) && (fieldString.charAt(l) != "."))
  {
    l = l - 1;
  }

  if ((i >= fieldLength - 2) || (fieldString.charAt(i) != ".") || (l >= fieldLength - 2))
  {
    theMsg = theMsg + "\nThere are not enough characters after the \"dot\"." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  return true;
}

// ************************************************************************

function isEmail(theField, theMsg)
{
  if (isEmpty(theField))
  {
    return true;
  }

  var i           = 1;
  var j           = 0;
  var atloc       = 0;
  var fieldString = theField.value
  var fieldLength = fieldString.length;
  var msg3        = "\nPlease try again";
						
  while ((i < fieldLength) && (fieldString.charAt(i) != "@"))
  {
    i++
  }

  if ((i >= fieldLength) || (fieldString.charAt(i) != "@"))
  {
    theMsg = theMsg + "\nThere is no \"@\" sign in the address." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }
  else
  {
    atloc = i;
  }

  j = i + 1;
  i += 1;

  while ((j < fieldLength) && (validEmailChars.indexOf(fieldString.charAt(j)) != -1))
  {
    j++
  }

  if (j < fieldLength)
  {
    theMsg = theMsg + "\nThere are invalid characters in the address." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  while ((i < fieldLength) && (fieldString.charAt(i) != "."))
  {
    i++
  }

  if (i == fieldLength)
  {
    theMsg = theMsg + "\nThere is no \"dot\" in the address." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  if (i == (atloc + 1))
  {
    theMsg = theMsg + "\nThere are not enough characters between the \"@\" and the \"dot\" in the address." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }

  k = atloc + 1;

  while (k < fieldLength)
  {
    if ((fieldString.charAt(k) == ".") && (fieldString.charAt(k + 1) == "."))
    {
      theMsg = theMsg + "\nThere are too many \"dots\" in the address." + msg3;
      warnInvalid(theField, theMsg);
      return false;
    }
    k++
  }

  l = fieldLength;

  while ((i < fieldLength - 2) && (l != i) && (fieldString.charAt(l) != "."))
  {
    l = l - 1
  }

  if ((i >= fieldLength - 2) || (fieldString.charAt(i) != ".") || (l >= fieldLength - 2))
  {
    theMsg = theMsg + "\nThere are not enough characters after the \"dot\" in the address." + msg3;
    warnInvalid(theField, theMsg);
    return false;
  }
  return true;
}

// ************************************************************************

// Displays the required warning message
function warnInvalid(theField, msg)
{
  theField.value = "";
  theField.focus();
  alert(msg);
  return false;
}

/* Validates data in form text field ...
   valid fieldTypes:
   0 = ALPHA
   1 = NUMERIC
   2 = ALPHANUMERIC
   3 = TELEPHONE
   4 = URL
   5 = EMAIL */

// ************************************************************************

function checkField(theField, fieldType)
{
  if (isEmpty(theField.value))
  {
    return true;
  }
  else
  {
    var msg1   = "The data you have entered is ";
    var msg2   = "";
    var msg3   = "or contains invalid characters.\nPlease try again";
    var theMsg = "";

    // Calculate the second part of the warning message...
    switch (fieldType)
    {
      case 0:  msg2 = "non-alphabetic ";
                      break;
      case 1:  msg2 = "non-numeric ";
                      break;
      case 2:  msg2 = "non-alphanumeric ";
                      break;
      case 3:  msg2 = "not a valid telephone number ";
                      break;
      case 4:  msg2 = "not a valid URL.";
                      break;
      case 5:  msg2 = "not a valid email address.";
                      break;
      case 6:  msg2 = "non-alphanumeric ";
                      break;
      default: break;
    }

    // For the case of ALPHA, NUMERIC, ALPHANUMERIC or TELEPHONE NUMBER validation...
    if ((fieldType == 0) || (fieldType == 1) || (fieldType == 2) || (fieldType == 3) || (fieldType == 6))
    {
      theMsg = msg1 + msg2 + msg3;

      if (!isLegalData(theField.value, fieldType))
      {
        warnInvalid(theField, theMsg);
        return false;
      }
      else
      {
        return true;
      }
    }
    // For the case of URL validation...
    else if (fieldType == 4)
    {
      isURL(theField, (msg1 + msg2));
    }
    // For the case of EMAIL validation...
    else if (fieldType == 5)
    {
      isEmail(theField, (msg1 + msg2));
    }
  }
}

// ************************************************************************

function doHelpPopUp(winURL)
{
  var screenWidth  = screen.availWidth;
  var screenHeight = screen.availHeight;
  var popUpLeft    = (screenWidth-320)/1.5;
  var popUpTop     = (screenHeight-400)/2;
  var winFeatures  = "height=400,width=320,top=" + popUpTop + ",left=" + popUpLeft + ",scrollbars=yes,status=no,toolbar=no,menubar=no,location=no";
  var popUpWin     = window.open(winURL, 'mtPopUp', winFeatures);
  
  popUpWin.focus();
}

// ************************************************************************

function checkInvalidPostCode(oID)
{
  var sPostcode    = new String(oID.value.toUpperCase());
  
  //alert("checkInvalidPostCode:" + sPostcode);
  // only do the validation if the user has in fact entered something...
  if (sPostcode != "")
  {
    var bInvalid     = true;
    var iPCLength    = sPostcode.length;
    var sValidPCList = "A99AA,A999AA,AA99AA,AA999AA,A9A9AA,AA9A9AA";
    var sPCToCheck   = translate(sPostcode,
                                 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                                 '9999999999AAAAAAAAAAAAAAAAAAAAAAAAAA');
    var sPCListArray = sValidPCList.split(/[,]/);
    var sWarningMsg1 = "The Postcode you have entered is not in a recognised format.\nPlease enter it again.";
    var sWarningMsg2 = "Are you sure you have entered your Postcode correctly?"

    // check that the post code is in the correct format...
    for (i = 0 ; i <= (sPCListArray.length - 1) ; i++)
    {
      if (sPCToCheck == sPCListArray[i])
      {
        bInvalid = false;
      }
    }
  
    if (bInvalid)
    {
      alert(sWarningMsg1);
      oID.value = "";
      oID.focus();
      bInvalid = true;
    }
    else
    {
      // check other postcode rules...
  
      // 'Q', 'V' and 'X' cannot be used in the first position...
      if ((sPostcode.charAt(0) == 'Q') || (sPostcode.charAt(0) == 'V') || (sPostcode.charAt(0) == 'X'))
      {
        alert(sWarningMsg1);
        oID.value = "";
        oID.focus();
        bInvalid = true;
      }
      // 'I','J' and 'Z' cannot be used in the second position...
      else if ((sPostcode.charAt(1) == 'I') || (sPostcode.charAt(1) == 'J') || (sPostcode.charAt(1) == 'Z'))
      {
        alert(sWarningMsg1);
        oID.value = "";
        oID.focus();
        bInvalid = true;
      }
      else
      {
        // test for the the third character being alpha and valid...
        if (sPCToCheck == "A9A9AA")
        {
          if ((sPostcode.charAt(2) == 'A') || (sPostcode.charAt(2) == 'B') || (sPostcode.charAt(2) == 'C') ||
              (sPostcode.charAt(2) == 'D') || (sPostcode.charAt(2) == 'E') || (sPostcode.charAt(2) == 'F') ||
              (sPostcode.charAt(2) == 'G') || (sPostcode.charAt(2) == 'H') || (sPostcode.charAt(2) == 'J') ||
              (sPostcode.charAt(2) == 'K') || (sPostcode.charAt(2) == 'S') || (sPostcode.charAt(2) == 'T') ||
              (sPostcode.charAt(2) == 'U') || (sPostcode.charAt(2) == 'W'))
          {
            bInvalid = false;
          }
          else
          {
            alert(sWarningMsg1);
            oID.value = "";
            oID.focus();
            bInvalid = true;
          }
        }
      }
  
      // validation still OK so continue...
      if (!bInvalid)
      {
        // check the last two characters of the postcode are valid...
        {
          var cPenultimateAlpha = sPostcode.charAt(iPCLength - 2);
          var cLastAlpha        = sPostcode.charAt(iPCLength - 1);
          var cInvalidAlphas    = new Array('C','I','K','M','O','V');
      
          for (i = 0 ; i < cInvalidAlphas.length ; i++)
          {
            if ((cPenultimateAlpha == cInvalidAlphas[i]) || (cLastAlpha == cInvalidAlphas[i]))
            {
              alert(sWarningMsg1);
              oID.value = "";
              oID.focus();
              bInvalid = true;
              break;
            }
          }
        }
      }
    
      // finally, validation is STILL OK so continue...
      if (!bInvalid)
      {
        // check for 'JE', 'GY', 'IM' and 'IO' postcodes...
        if (((sPostcode.charAt(0) == 'J') && (sPostcode.charAt(1) == 'E')) ||
            ((sPostcode.charAt(0) == 'G') && (sPostcode.charAt(1) == 'Y')) ||
            ((sPostcode.charAt(0) == 'I') && (sPostcode.charAt(1) == 'M')) ||
            ((sPostcode.charAt(0) == 'I') && (sPostcode.charAt(1) == 'O')))
        {
          //alert("foreign postcode found");
          if (confirm(sWarningMsg2))
          {
            document.location.href = "referDecline.asp?t=d&r=9103"
            bOKToSubmit = false;
          }
          else
          {
            oID.value = "";
            oID.focus();
            bInvalid = true;
          }
        }
      }
    }
  }
}

// ************************************************************************

// returns a string value replacing "sInStr" values with "sOutStr" values for "sConvertStr" variable
function translate(sConvertStr,sInStr,sOutStr)
{
  var sRtnVal = "";
  
  for (i = 0 ; i < sConvertStr.length ; i++)
  {
    for (j = 0 ; j < sInStr.length ; j++)
    {
      if ((sConvertStr.substring(i,(i + 1))) == (sInStr.substring(j,(j + 1))))
      {
        sRtnVal += sOutStr.substring(j,(j + 1));
      }
    }
  }
  
  return sRtnVal;
}

// ************************************************************************

// re-number day option list when month/year changed
//function setDaysinMonth(dayField,monthField,yearField)
//{
//  setDisplayedValues(dayField,monthField,yearField);
//
//  // If DisplayedMonth is reset to MMM then set to 1 to force days back to 31.
//  if (DisplayedMonth == 0)
//  {
//		DisplayedMonth = 1;
//  }
//  
//  var DaysinThisMonth = DaysinMonth[DisplayedMonth - 1];
//  
//  eval("document.getElementById('" + dayField + "')").length = DaysinThisMonth + 1;
//  
//  for (var i = 0 ; i < DaysinThisMonth + 1 ; i++)
//  {
//    eval("document.getElementById('" + dayField + "')").options[i].value = AllDaysinMonth[i];
//    eval("document.getElementById('" + dayField + "')").options[i].text  = AllDaysinMonth[i];
//  }
//  // Leap Year calculation...
//  if ((DisplayedMonth == 2) && (DisplayedYear % 4 == 0) && ((DisplayedYear % 100 != 0) || (DisplayedYear % 2000 == 0)))
//  {
//    eval("document.getElementById('" + dayField + "')").length = 30;
//    
//    for (var j = 0 ; j < 30 ; j++)
//    {
//      eval("document.getElementById('" + dayField + "')").options[j].value = AllDaysinMonth[j];
//      eval("document.getElementById('" + dayField + "')").options[j].text  = AllDaysinMonth[j];
//    }
//  }
//}

// ************************************************************************

//function setDisplayedValues(dayField,monthField,yearField)
//{
//  DisplayedDay   = eval("document.getElementById('" + dayField + "')").options[eval("document.getElementById('" + dayField + "')").selectedIndex].value;
//  DisplayedMonth = eval("document.getElementById('" + monthField + "')").selectedIndex;
//  DisplayedYear  = parseInt(eval("document.getElementById('" + yearField + "')").value);
//}

// ************************************************************************

function doCancelWarning(cancelURL)
{
  var bYN = confirm("Are you sure you want to exit this quotation?\n" +
                    "If you want to make amendments then please click the 'cancel' button below\n" +
                    "and continue with the quote.  You will have the opportunity to make amendments\n" +
                    "or alternatively, use the 'back' button on your browser.");

  if (bYN) top.location.href = cancelURL;
}

// ************************************************************************

function doDOBCheck(iDOBD,sDOBM,iDOBY)
{
  var bM1Found  = false;
  var bM2Found  = false;
  var now       = new Date();
  var startDate = new String(document.getElementById("csd").value);
  var csdArray  = startDate.split(/[ ]/);
  var csdD      = new Number(csdArray[0]);
  var csdM      = csdArray[1];
  var csdY      = new Number(csdArray[2]);
  var sMonths   = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
  var iMonth1;
  var iMonth2;
  
  for (i = 0 ; i <= sMonths.length ; i++)
  {
    if (sDOBM == sMonths[i])
    {
      iMonth1 = i;
      bM1Found = true;
    }
  
    if (csdM == sMonths[i])
    {
      iMonth2 = i;
      bM2Found = true;
    }
  
    if ((bM1Found) && (bM2Found))
    {
      break;
    }
  }
    
  if (iDOBY < (csdY - 50))
  {
    return true;
  }
  else if ((iMonth1 < iMonth2) && (iDOBY <= (csdY - 50)))
  {
    return true;
  }
  else if ((iDOBD <= csdD) && (iMonth1 <= iMonth2) && (iDOBY <= (csdY - 50)))
  {
    return true;
  }
  else
  {
    return false;
  }
}

// ************************************************************************

function doChangeVisibilityBC(iType,iNum1)
{
  if (iType == 0)
  {
    var oTheElementToCheck = document.getElementById("BCover");
    var oTheAreaToChange   = document.getElementById("CTB");
    var oTheDataElement    = document.getElementById("coverTypeB")
    
    if (document.getElementById("propertyType" + iNum1).value == "16")
    {
      oTheAreaToChange.style.display = "none";
      oTheElementToCheck.selectedIndex = 1;
      oTheDataElement.selectedIndex  = 0;
    }
  }
  else
  {
    var oTheElementToCheck = document.getElementById("CCover");
    var oTheAreaToChange   = document.getElementById("CTC");
    var oTheDataElement    = document.getElementById("coverTypeC")
  }

  if (oTheElementToCheck.value == "N")
  {
    oTheAreaToChange.style.display = "none";
    oTheDataElement.selectedIndex  = 0;
  }
  else
  {
    oTheAreaToChange.style.display = "inline";
  }
}

// ************************************************************************

function doDateDiff(iMaxYear,sID1,sID2)
{
  var bM1Found    = false;
  var bM2Found    = false;
  var defaultDate = new String(document.getElementById(sID1).value);
  var eventDate   = new String(sID2);
  var dateArray1  = defaultDate.split(/[ ]/);
  var dateArray2  = eventDate.split(/[ ]/);
  var date1D      = new Number(dateArray1[0]);
  var date1M      = dateArray1[1];
  var date1Y      = new Number(dateArray1[2]);
  var date2D      = new Number(dateArray2[0]);
  var date2M      = dateArray2[1];
  var date2Y      = new Number(dateArray2[2]);
  var sMonths     = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
  var iMonth1;
  var iMonth2;
      
  for (i = 0 ; i <= sMonths.length ; i++)
  {
    // get the default month...
    if (date1M == sMonths[i])
    {
      iMonth1 = i;
      bM1Found = true;
    }
       
    // get the input month...
    if (date2M == sMonths[i])
    {
      iMonth2 = i;
      bM2Found = true;
    }
       
    if ((bM1Found) && (bM2Found))
    {
      break;
    }
  }

  // if the input YEAR is less than the default year (minus the iMaxYear parameter passed),
  // return false...
  if (date2Y < (date1Y - iMaxYear))
  {
    return false;
  }
  // if the input MONTH is less than the default month AND the input year is less than or equal
  // to the default year (minus the iMaxYear parameter passed), return false...
  else if ((iMonth2 < iMonth1) && (date2Y <= (date1Y - iMaxYear)))
  {
    return false;
  }
  // if the input DAY is less than the default day AND the input month is less than or equal to
  // the default month AND the input year is less than or equal to the default year (minus the
  // iMaxYear parameter passed), return false...
  else if ((date2D < date1D) && (iMonth2 <= iMonth1) && (date2Y <= (date1Y - iMaxYear)))
  {
    return false;
  }
  // otherwise return true...
  else
  {
    return true;
  }
}

// ************************************************************************

function popup(total,popupheight,popupwidth)
{
  if (document.all)
  {
    //ie version...
    var xMax       = screen.width;
    var yMax       = screen.height;
    var xOffset    = (xMax - popupwidth) / 5;
    var yOffset    = (yMax - popupheight) / 2;
    var mainwindow = window.open(total,"telepopup","screenx=" + xOffset + ", screeny=" + yOffset + ", top=" + yOffset + ",left=" + xOffset + ",toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=yes, resizable=no,copyhistory=no,width=" + popupwidth + ",height=" + popupheight + "");
  }
  else
  {
    //netscape version...
    var xMax       = window.outerWidth;
    var yMax       = window.outerHeight;
    var xOffset    = (xMax - popupwidth) / 5;
    var yOffset    = (yMax - popupheight) / 2;
    var mainwindow = window.open(total,"telepopup","screenx=" + xOffset + ", screeny=" + yOffset + ", top=" + yOffset + ",left=" + xOffset + ",toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=yes, resizable=no,copyhistory=no,width=" + popupwidth + ",height=" + popupheight + "");
  }
}

// ************************************************************************

function openit(oneToOpen)
{
  open(oneToOpen);
}

// ************************************************************************
function checktelephonenum(oID)
{   
    if (oID.value != '')
    {
        oID.value=oID.value.replace(/ /g,"")
        oID.value=oID.value.replace(/-/g,"")
        oID.value=oID.value.replace(/\)/g,"")
        oID.value=oID.value.replace(/\(/g,"")
        oID.value=oID.value.replace(/\+/g,"")

	    if((oID.value.length != 10)&&(oID.value.length != 11))
	    {
    		alert("Please enter a valid UK telephone number");
		    oID.value='';
		    oID.focus();
		    return false;
        }
        
    	if(oID.value <= 1)
    	{
		    alert("Please enter a valid UK telephone number");
		    oID.value='';
		    oID.focus();
		    return false;
	    }
    	
    	if(oID.value.charAt(0) != 0)
    	{
	    	alert("Please enter a valid UK telephone number");
		    oID.value='';
		    oID.focus();
		    return false;
	    }
    }
}
