
/********************************************************************
*  The copyright of this code belongs to Advertise By Design        *
*  Visit our site at www.advertisebydesign.co.uk                    *
********************************************************************/

  var browser=new Object();
  browser.version = parseInt(navigator.appVersion);
  browser.isNetscape = false;
  browser.isIE = false;
  browser.isOpera = false;
  browser.isMac = false;
  if (navigator.appName.indexOf("Netscape") != -1) {browser.isNetscape=true;}
  if (navigator.appName.indexOf("Microsoft") != -1) {browser.isIE=true;}
  if (navigator.appName.indexOf("Opera") != -1) {browser.isOpera=true;}
  var agt=navigator.userAgent.toLowerCase();
  if (agt.indexOf("mac")!=-1); {browser.isMac=true;}


  function addEventHandler (obj, eventName, handler)
  { // Use where more than one function is applicable to an Event
    if (document.attachEvent) {obj.attachEvent("on" + eventName, handler);}
    else
    {
      if (document.addEventListener) {obj.addEventListener (eventName, handler, false);}
    }
  }

  function calculateAge(f, dateName)
  { // Calculates the age, given a date
    var opt=eval("f." + dateName + "Day.selectedIndex");
    var day=eval("f." + dateName + "Day.options[opt].text");
    opt=eval("f." + dateName + "Month.selectedIndex");
    var month=eval("f." + dateName + "Month.options[opt].value");
    opt=eval("f." + dateName + "Year.selectedIndex");
    var year=eval("f." + dateName + "Year.options[opt].text");


    var thisDate=new Date();
    var thisYear=thisDate.getFullYear();
    var thisMonth=Number(thisDate.getMonth()) + 1;
    var thisDay=Number(thisDate.getDate());
    month=Number(month);
    day=Number(day);
    var age=thisYear-year;
    if (thisMonth>month) {return age;}
    if (thisMonth<month) {return age-1;}
    if (thisDay>=day) {return age;}
    else {return age-1;}
  }

  function checkDate(d,m,y)
  { // Checks for valid date in range 1/1/1900 to 31/12/2099
    if (!isNumeric(d) || !isNumeric(m) || !isNumeric(y)) {return false;}
        if (m<1 || m>12) {return false;}
        if (y<1900 || y>2099) {return false;}
    var daysInMonth=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        if (y%1000==0 ||(y%4==0 && y%100!=0)) {daysInMonth[1]=29;}
        if (d<1 || d>daysInMonth[m-1]) {return false;}
        return true;
  }


  function checkEmail(email)
  { // this checks for a valid format email address
    var pattern=/^[a-zA-Z0-9]+([.|_|-][a-zA-Z0-9]+)*[@]{1}[a-zA-Z0-9]+([.|_|-][a-zA-Z0-9]+)*[.]{1}[a-zA-Z0-9]{2,3}$/;
    var result=email.match(pattern);
    if (result==null)
      {
       return false;
      }
      else  return true;
  }

  function checkPassword(pass)
  { // This checks password is 6-12 chars, starts with a letter and contains
    // only alphanumerics

        if (pass.length<6 || pass.length>12) {return false;}
        var pattern=/^[a-zA-Z][a-zA-Z0-9]{0,11}$/;
    var result=pass.match(pattern);
    if (result==null)
      {
       return false;
      }
      else  return true;
  }

  function checkPhoneNo(phone)
  { // This checks a phone number contains at least 11 digits. It
    // ignores blanks and hyphens
        var p=phone.replace(/ |-/g,""); // Remove blanks or hyphens
        if (p.length<10 || !isNumeric(p)) {return false;}
        else {return true;}
  }

  function checkTime(h,m)
  {
    if (!isNumeric(h) || !isNumeric(m)) {return false;}
        if (h<0 || h>23) {return false;}
        if (m<0 || m>59) {return false;}
        return true;
  }

  function checkURL(URL)
  { // this checks for a valid format URL
    // NB this does not check anything beyond the basic address - ie no parameters
    var pattern=/^(http:\/\/)?[a-zA-Z0-9]+([.|_|-][a-zA-Z0-9]+)*[.]{1}[a-zA-Z0-9]{2,3}/;
    var result=URL.match(pattern);
    if (result==null)
      {
       return false;
      }
      else  return true;
  }

  function compareDates(f, date1Name, date2Name)
  { // This function validates the two dates and if both are valid it compares them.
    // It returns results as follows:
    // -1  One or both of the dates is invalid
    // 0 The dates are equal
    // 1 The first date is later than the second
    // 2 The second date is later than the first
     var opt=eval("f." + date1Name + "Day.selectedIndex");
     var day=eval("f." + date1Name + "Day.options[opt].text");
     opt=eval("f." + date1Name + "Month.selectedIndex");
     var month=eval("f." + date1Name + "Month.options[opt].value");
     opt=eval("f." + date1Name + "Year.selectedIndex");
     var year=eval("f." + date1Name + "Year.options[opt].text");

     if (!checkDate(day, month, year)) {return -1;}
     var tempMonth=month-1;    // Date expects an offset Month
     var firstDate=new Date(year, tempMonth, day);

     var opt=eval("f." + date2Name + "Day.selectedIndex");
     var day=eval("f." + date2Name + "Day.options[opt].text");
     opt=eval("f." + date2Name + "Month.selectedIndex");
     var month=eval("f." + date2Name + "Month.options[opt].value");
     opt=eval("f." + date2Name + "Year.selectedIndex");
     var year=eval("f." + date2Name + "Year.options[opt].text");

     if (!checkDate(day, month, year)) {return -1;}
     var tempMonth=month-1;    // Date expects an offset Month
     var secondDate=new Date(year, tempMonth, day);
     if (firstDate.getTime()==secondDate.getTime())  {return 0;}
     if (firstDate.getTime()>secondDate.getTime())  {return 1;}
     return 2;
  }

  function compareTimes(f, time1Name, time2Name)
  { // This function compares two times generated in a form with htmlTime
    // It returns 0 if they are equal,
    // 1 if the first is greater than the second
    // or 2 if the second is greater than the first
    var opt=eval("f." + time1Name + "Hour.selectedIndex");
    var hour=Number(eval("f." + time1Name + "Hour.options[opt].value"));
    var opt=eval("f." + time1Name + "Minutes.selectedIndex");
    var minutes=Number(eval("f." + time1Name + "Minutes.options[opt].value"));
    var opt=eval("f." + time1Name + "AmPm.selectedIndex");
    var ampm=eval("f." + time1Name + "AmPm.options[opt].text");
    if (ampm == "am")
    {
      if (hour == 12) {hour = "00";}
      else
      {
        if (hour < 10) {hour = "0" + hour;}
      }
    }
    else
    {
      if (hour != 12) {hour = hour + 12;}
    }
    if (minutes < 10) {minutes = "0" + minutes;}
    var time1 = "" + hour + minutes;

    var opt=eval("f." + time2Name + "Hour.selectedIndex");
    var hour=Number(eval("f." + time2Name + "Hour.options[opt].value"));
    var opt=eval("f." + time2Name + "Minutes.selectedIndex");
    var minutes=Number(eval("f." + time2Name + "Minutes.options[opt].value"));
    var opt=eval("f." + time2Name + "AmPm.selectedIndex");
    var ampm=eval("f." + time2Name + "AmPm.options[opt].text");
    if (ampm == "am")
    {
      if (hour == 12) {hour = "00";}
      else
      {
        if (hour < 10) {hour = "0" + hour;}
      }
    }
    else
    {
      if (hour != 12) {hour = hour + 12;}
    }
    if (minutes < 10) {minutes = "0" + minutes;}
    var time2 = "" + hour + minutes;
    if (time1 == time2) {return 0;}
    if (time1 > time2) {return 1;}
    return 2;
  }

  function createRequest()
  { // Create request object
    try {request = new XMLHttpRequest();}
    catch (tryMS)
    {
      try {request = new ActiveXObject("Msxml2.XMLHTTP");}
      catch (otherMS)
      {
        try {request = new ActiveXObject("Microsoft.XMLHTTP");}
        catch (failed) {request = null;}
      }
    }
    return request;
    /*  Sending Request
        request = createRequest();    // nb global variable so can access in processRequest
        request.onreadystatechange = processRequest;  // 'processRequest' is a function name nb No parentheses
                                          // nb If using synchronous request, no callback needed - process stops & waits
        if (request == null)
        {
          alert("Unable to create request);
          return;
        }
        var url = "wherever.php?userdata" + escape(usersata); // escape to make user entered data safe to transmit

        // If using GET
        request.open("GET", url, true);   // True signifies asynchronous processing, false means wait until complete
        request.send(null);  // If using GET, as no data is sent other than via the url

        // OR if using POST
        request.open("POST", url, true);   // True signifies asynchronous processing, false means wait until complete
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.send(escape(userdata));  // Using POST, so send (escaped) data
    */

    /* Process Request   (function processRequest())
      if (request.readystate == 4)
      { // Server indicates completion
        if (request.status == 200)
        { // Server indicates no problem, eg 404
          var data = request.responseText;  // if text response
          var xml = request.responseXML;    // if xml response
        }
      }
    */
  }

  function dateEntered (f, dateName)
  {
     var opt=eval("f." + dateName + "Day.selectedIndex");
     var day=eval("f." + dateName + "Day.options[opt].text");
     opt=eval("f." + dateName + "Month.selectedIndex");
     var month=eval("f." + dateName + "Month.options[opt].text");
     opt=eval("f." + dateName + "Year.selectedIndex");
     var year=eval("f." + dateName + "Year.options[opt].text");

     if (day == "DD" && month == "MM" && year == "YYYY") {return false;}
     else {return true}
  }

  function empty(s)
  {
    if (s=="" || s==null || isblank(s)) {return true;}
        else {return false;}
  }

  function formatDecimal(number)
  { // This takes a number and converts it to a string with 2 decimal places.
    var stringValue=String(number);
    var point=stringValue.search(/\./);
    if (point==-1) {stringValue+=".00";}
    else
    {
      if (point==stringValue.length-1) {stringValue+="00";}
      else
      {
        if (point==stringValue.length-2) {stringValue+="0";}
        else {stringValue=stringValue.substr(0,point+3);}
      }
    }
    return stringValue;
  }

  function formatEmail(name, site, suffix, text, paras, className)
  {
     // <SCRIPT language="Javascript">formatEmail("name", "site", "suffix", "text", "paras", "class");</SCRIPT>
     if (empty(suffix)) {suffix="co.uk";}

     var emailAddress=name + "@" + site + "." + suffix;
     document.write ("<a href='mailto:" + emailAddress);
     if (!empty(paras)) {document.write ("?" + paras);}
     document.write ("'");
     if (!empty(className)) {document.write (" class='" + className + "'");}
     document.write (">");
     if (empty(text)) {document.write (emailAddress);} else {document.write (text);}
     document.write ("</a>\n");
  }


  function generateRandomNo(x, y)
  { // This function generates a random integer between x & y
    var range = y - x + 1;
    return Math.floor(Math.random() * range) + x;
  }

  function getActivatedObject(e)
  {
    var obj;
    if (!e) // Early versions of MS
      {obj = window.event.srcElement;}
    else
    {
      if (e.srcElement) // IE 7 or later
      {
        obj = e.srcElement;
      }
      else
      { // DOM level 2
        obj = e.target;
      }
    }
    return obj;
  }

  function getElement(id)
  {
    if (document.getElementById) {var elmt=document.getElementById(id);}
    else
    {
      if (document.all) {var elmt=document.all[id];}
          else
          {
            if (document.layers) {var elmt=document.layers[id];}
            else elmt=false;
          }
    }
    //if (!elmt) {alert (id + " not found");} else  {alert (id + " found");}
    return elmt;
  }

  function isblank (s)
  { // Returns false if field contains any non-blank chars other than new line
    for (var i=0; i<s.length; i++) {
      var c=s.charAt(i);
          if (c!=" " && c!="\n" && c!="") {
          return false;
          }
    }
    return true;
  }


  function isNumeric (inputnumber, decPlaces)
  { // This function checks for numerics with a maximum of decPlaces decimal places
    var pattern = new RegExp("^([-])?[0-9]+$");
    if (decPlaces!= undefined && decPlaces!=0)
    { // Decimal places allowed
      var dPlaces=2;
      if (decPlaces > 0 && decPlaces <= 9) {dPlaces=decPlaces;}
      var exp = "^([-])?[0-9]+([.][0-9]{1," + dPlaces + "})?$";
      pattern = new RegExp(exp);
    }
    var result = pattern.test(inputnumber);
    return result;
  }

  function makeTime(f, timeName)
  { // Returns a string containng the time in hh:mm form
    var opt=eval("f." + timeName + "Hour.selectedIndex");
        var hour=eval("f." + timeName + "Hour.options[opt].text");
        opt=eval("f." + timeName + "AmPm.selectedIndex");
        var amPm=eval("f." + timeName + "AmPm.options[opt].text");
        opt=eval("f." + timeName + "Minutes.selectedIndex");
        var minutes=eval("f." + timeName + "Minutes.options[opt].text");
        if (amPm=="pm" && hour!=12) {hour=Number(hour)+12;}
        else
        {
          if (hour<10) {hour="0"+hour;}
        }
        if (minutes<10) {minutes="0" + minutes;}
        return hour+":"+minutes;
  }


  function newWindow(url, w, h)
  { // Opens URL w in a new window positioned top left and ensures it has the focus
    if (!w) {var wide=400;} else {wide=w;}
        if (!h) {var high=450;} else {high=h;}
        var paras="width=" + wide + ",height=" + high + ", align=center, scrollbars=yes, left=0, top=0, screenx=0, screeny=0, resizable";
    var x=window.open(url, "newWindow", paras);
        x.window.focus();
  }

  function refreshFrames(first, second)
  { // Refreshes contents of specified frams, where first & second are frame names. Use OnClick...
    eval("parent." + first + ".document.reload()");
    eval("parent." + second + ".document.reload()");
  }

  function setFrameURL (frameName, URL)
  { // Reloads the specified frame with the specified URL
    eval("parent." + frameName + ".location.href = '" + URL + "'" );
  }

  function setRelatedSelect(mainSelectID, dependSelectID, clonedOptions, sel2Default)
  {
    var tempOptions = eval(clonedOptions);
    var sel1 = getElement(mainSelectID);
    var sel2 = getElement(dependSelectID);
    if (sel1.options[sel1.selectedIndex].value == 0)  {sel2.disabled = true;} else {sel2.disabled = false;}
    while (sel2.options.length) {sel2.remove(0);}
    // Create regular expression objects for "select" and the value of the selected option of the main select box as class names
    var pattern1 = /( |^)(select)( |$)/;
    var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
    // Iterate through all cloned options
    var optCount = 0;
    for (var i = 0; i < tempOptions.length; i++)
    {
      // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
      if (sel1.options[sel1.selectedIndex].value == 0 || tempOptions[i].className.match(pattern2) || tempOptions[i].className=="any")
      {
        // Clone the option from the hidden option pool and append it to the dynamic select box
        sel2.appendChild(tempOptions[i].cloneNode(true));

        if (sel2Default)
        {  // If a default has been provided, ensure the option is still selected
           if (tempOptions[i].value == sel2Default)
           {
             sel2.options[optCount].selected = true;
           }
        }
        optCount++;
      }
    }
  }

  function validateDate(f, dateName, future)
  {
     var opt=eval("f." + dateName + "Day.selectedIndex");
     var day=Number(eval("f." + dateName + "Day.options[opt].text"));
     opt=eval("f." + dateName + "Month.selectedIndex");
     var month=Number(eval("f." + dateName + "Month.options[opt].value"));
     opt=eval("f." + dateName + "Year.selectedIndex");
     var year=Number(eval("f." + dateName + "Year.options[opt].text"));
     if (!checkDate(day, month, year)) {return false;}
     if (future!=null)
     {
       var tempMonth=month-1;    // Date expects an offset Month
       var theDate=new Date(year, tempMonth, day);
       var today=new Date();
       today.setHours(0,0,0,0);
       if (future=="Future" )
       {
         if (theDate.getTime() <= today.getTime()) {return false;} else {return true;}
       }
       else
       {
         if (theDate.getTime() >= today.getTime()) {return false;} else {return true;}
       }
     }
     else {return true;}
  }

  function validateSlashDate(ddmmyy)
  {
    var dateArray=ddmmyy.split("/");
        var d=dateArray[0];
        var m=dateArray[1];
        var y=dateArray[2];
        if (empty(d) || empty(m) || empty(y)) {return false;}
        var valid=checkDate(d, m, y);
        return valid;
  }
