//
//-----------------------------------------------------------------------------/
//                                                                             /
//       PROTOTYPES                                                            /
//                                                                             /
//-----------------------------------------------------------------------------/
//
if (!Array.prototype.indexOf)
{
   Array.prototype.indexOf = function(object)
   {
      var len = this.length;

      var from = Number(arguments[1]) || 0;
      from = ((from < 0) ? Math.ceil(from) : Math.floor(from));
      if (from < 0)
      {
         from += len;
      }

      for (; from < len; from++)
      {
         if ((from in this) && (this[from] === object))
         {
            return from;
         }
      }
      return -1;
   };
}

if (!String.prototype.capitalise)
{
   String.prototype.capitalise = function()
   {
      return this.replace(/\b\w/gi, function(c, i, s) { return c.toUpperCase(); });
   }
}

//
//-----------------------------------------------------------------------------/
//                                                                             /
//       GLOBAL VARIABLES                                                      /
//                                                                             /
//-----------------------------------------------------------------------------/
//
var _leadCapture = new function()
{
   this.form;
   this.spanCodeGen;
   this.className = {focus: "focus", blur: "blur"};
   this.value = [];
   this.fields;
   this.loaded = false;
   this.checkbox = [];
   this.radio = [];
   this.indexMessage = 0;
   this.useBlur = false;
   this.hideNote = false;

//-----------------------------------------------------------------------------/
//       Function:      getRandom                                              /
//       Updated:       20100218_1456                                          /
//       Description:                                                          /
//          Returns a random integer in the range [0, max]. The random         /
//          generator is seeded from the current time.                         /
//       Notes:                                                                /
//          The algorithm used guarantees a uniform distributon.               /
//       Warning:                                                              /
//          Numbers in JavaScript are IEEE 754 floating point numbers with     /
//          round-to-nearest-even behavior. Math.random() by itself will       /
//          safely return [0, 1). But multiplying against Math.random() means  /
//          it's possible in extremely rare cases (on the order of 1 in 2^62)  /
//          to calculate the usually-excluded upper bound. This is why the if  /
//          statement in this function is always used.                         /
//       Parameters:                                                           /
//          max         Maximum random number                                  /
//-----------------------------------------------------------------------------/
   function getRandom(max)
   {
//
//-----------------------------------------------------------------------------/
//       Return the random number                                              /
//-----------------------------------------------------------------------------/
//
      var ranNum = Math.floor(Math.random() * (max + 1));
      if (ranNum > max)
      {
         ranNum = max;
      }
      return ranNum;
   }

//-----------------------------------------------------------------------------/
//       Function:      [_leadCapture].init                                    /
//       Updated:       20100218_1456                                          /
//       Description:                                                          /
//          Initialises the lead capture form.                                 /
//       Notes:                                                                /
//        * The fields property array is very important. It is used to         /
//          initialise and validate fields in the form. It has this format:    /
//             var fields =                                                    /
//             {                                                               /
//                <field id>:                                                  /
//                {                                                            /
//                   value: <string: caption on left of input field>,          /
//                   validation: <regular expression that tests true OR        /
//                      function that returns true if field value valid>,      /
//                   message: [<string: error message if field required but    /
//                      blank (use empty string to display value instead)>,    /
//                      <string: error message if value invalid>],             /
//                   required: <boolean: field required>,                      /
//                   focus: <boolean: focus this field after loading page>,    /
//                   [OPTIONAL] valueBlur: <string: value to display if blur   /
//                      feature enabled and value is blank>                    /
//                   [OPTIONAL] id: [<string: id of radio button label>+]      /
//                }+                                                           /
//             };                                                              /
//       Parameters:                                                           /
//          idForm      The id of the form element                             /
//          fields      Fields property array. Refer to Notes in this header.  /
//          useCode     Display the random generated code div                  /
//          useBlur     Display a grey hint in input[type=text] and textarea   /
//                      elements when blurred and their value is ""            /
//-----------------------------------------------------------------------------/
   this.init = function(idForm, fields, useCode, useBlur)
   {
      this.useBlur = useBlur;
      this.fields = fields;
      this.form = document.getElementById(idForm);
      if (useCode)
      {
         this.generateCode();
      }
      var allRequired = true;
      for (var id in this.fields)
      {
         this.value["input" + id] = (this.fields[id].valueBlur || this.fields[id].value);
         var input = this.getField(id);
         if (input)
         {
            if (useBlur)
            {
               input.value = this.value["input" + id];
               input.readOnly = true;
            }
            else
            {
               this.swapClass(input, this.className.blur, this.className.focus)
            }
         }
         allRequired &= this.fields[id].required;
      }
      if (allRequired && this.hideNote)
      {
         document.getElementById("divNote").style.visibility = "hidden";
      }
      for (var id in this.fields)
      {
         var label = document.getElementById("label" + id);
         label.innerHTML = this.fields[id].value + ((this.fields[id].value.indexOf("?") == -1) ? ":" : "");
         var span = document.createElement("span");
         span.id = "spanRequired" + id;
         span.className = (this.fields[id].required ? "required" : "notRequired");
         var textNode = document.createTextNode("\u2022");
         span.appendChild(textNode);
         this.insertAfter(document.getElementById("span" + id + "Caption"), span);
      }
   }

   this.insertAfter = function(referenceNode, newNode)
   {
      referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
   }

   this.load = function()
   {
      var __id = "";
      for (var id in this.fields)
      {
         var input = this.getField(id);
         if (input)
         {
            if (this.useBlur)
            {
               input.readOnly = false;
               input.value = this.value["input" + id];
            }
            if (this.fields[id].focus)
            {
               if (this.useBlur)
               {
                  input.value = "";
               }
               __id = id;
            }
         }
      }
      this.loaded = true;
      if (__id)
      {
         var input = this.getField(__id);
         input.blur();
         input.focus();
      }
   }

   this.generateCode = function()
   {
      this.spanCodeGen = document.getElementById("spanCodeGen");
      if (this.spanCodeGen)
      {
         this.spanCodeGen.innerHTML = (function (){var code = ""; for (var i = 0; i < 8; i++) code += String.fromCharCode("A".charCodeAt(0) + getRandom(25)); return code;})();
      }
   }

   this.focus = function(input)
   {
      if (!(this.loaded))
      {
         return;
      }
      if (this.swapClass(input, this.className.blur, this.className.focus))
      {
         if (!(this.value[input.id]))
         {
            this.value[input.id] = input.value;
         }
         if (this.useBlur)
         {
            input.value = "";
         }
      }
   }

   this.blur = function(input)
   {
      if (!(this.loaded))
      {
         return;
      }
      if (input.value.replace(/\s*/g, "") == "")
      {
         this.swapClass(input, this.className.focus, this.className.blur);
         if (this.useBlur)
         {
            input.value = this.value[input.id];
         }
      }
   }

   this.swapClass = function(input, classA, classB)
   {
      var swapped = false;
      var className = input.className.split(" ");
      var index = className.indexOf(classA);
      if (index != -1)
      {
         className[index] = classB;
         input.className = className.join(" ");
         swapped = true;
      }
      return swapped;
   }

   this.validate = function()
   {
      var valid = true;
      for (var id in this.fields)
      {
         var message = "";
         var input = this.getField(id);
         if (!input || (input.type == "checkbox") || (input.type == "radio"))
         {
            if (!(this.fields[id].required))
            {
               continue;
            }
            if (this.fields[id].validation && (typeof(this.fields[id].validation) == "function") && !(this.fields[id].validation()))
            {
               valid = false;
               message = (this.fields[id].message[this.indexMessage] || this.fields[id].value);
            }
         }
         else if ((input.value == this.value["input" + id]) || (input.value == ""))
         {
            if (!(this.fields[id].required))
            {
               continue;
            }
            valid = false;
            message = (this.fields[id].message[0] || this.fields[id].value);
         }
         else if ((this.fields[id].validation) && 
            (!(((typeof(this.fields[id].validation) == "function") ? this.fields[id].validation(input.value) : this.fields[id].validation.test(input.value))) || 
            ((id == "Code") && (input.value.toUpperCase() != this.spanCodeGen.innerHTML))))
         {
            valid = false;
            message = (this.fields[id].message[1] || this.fields[id].value);
         }
         document.getElementById("label" + id).style.color = (valid ? "" : "red");
         if (!valid)
         {
            this.alert("(Required) " + message);
            if (input)
            {
               input.focus();
            }
            break;
         }
      }
      if (valid)
      {
//
//       Clear any empty fields that are not required
//
         for (var id in this.fields)
         {
            var input = this.getField(id);
            if (input)
            {
               if ((input.value == this.value["input" + id]) || (input.value == ""))
               {
                  input.value = " "; // Use a single space so that the field appears in the email (although blank)
               }
            }
         }
//
//       Enter the hidden date field value
//
         this.form.date.value = new Date();
      }
      return valid;
   }

   this.validateImportant = function()
   {
      var valid = false;
      this.indexMessage = 0;
      var id = "Important";
      for (var index = 0; index < this.checkbox[id].length; index++)
      {
         var checkbox = this.checkbox[id][index];
         if (checkbox.checked)
         {
            valid = true;
            break;
         }
      }
      if (valid)
      {
         valid = false;
         this.indexMessage = 1;
         for (var index = 0; index < this.radio[id].length; index++)
         {
            var radio = this.radio[id][index];
            if (radio.checked)
            {
               valid = true;
               break;
            }
         }
      }
      return valid;
   }

   this.validatePlan = function()
   {
      var valid = false;
      this.indexMessage = 0;
      var id = "Plan";
      for (var index = 0; index < this.radio[id].length; index++)
      {
         var radio = this.radio[id][index];
         if (radio.checked)
         {
            valid = true;
            break;
         }
      }
      return valid;
   }

   this.validateTrack = function()
   {
      var valid = !(this.radio["Plan"][0].checked);
      this.indexMessage = 0;
      var id = "Track";
      for (var index = 0; index < this.radio[id].length; index++)
      {
         var radio = this.radio[id][index];
         if (radio.checked)
         {
            valid = true;
            break;
         }
      }
      return valid;
   }

   this.alert = function(message)
   {
      document.getElementById("divError").innerHTML = message;
   }

   this.getField = function(id)
   {
      var element;
      var fieldTypes = ["input", "textarea"];
      for (var index = 0; index < fieldTypes.length; index++)
      {
         element = document.getElementById(fieldTypes[index] + id);
         if (element)
         {
            break;
         }
      }
      return element;
   }

   this.checkRequiredTrack = function()
   {
      var input = document.getElementById("inputPlanYes");
      if (input)
      {
         fields["Track"].required = input.checked;
         var span = document.getElementById("spanRequiredTrack");
         if (span)
         {
            span.className = (input.checked ? "required" : "notRequired");
         }
      }
   }
}
