/**
 * Javascript Document by Jeffrey Ouma. Copyright© 2008 artkenya.net Ltd. All rights reserved.
 * 
 * Form Function Library: ====================== Event handlers and validations for generic form fields such as name and email among others
 * 
 */
// Create the BLEEZ.form namespace
BLEEZ.form = {};
BLEEZ.form.step = {
  parentElm: "",
  Show: function(elm) {
    // Get the step to be activated
    var activeElm = (Dom.getAncestorByClassName(elm, "step")) ? Dom.getAncestorByClassName(elm, "step") : Dom.getAncestorByClassName(elm,
      "active-step");
    // Get all currently active steps and deactivate them
    var elmArray = Dom.getElementsByClassName("active-step", "div", BLEEZ.form.step.parentElm);
    Dom.replaceClass(elmArray, "active-step", "step");
    if(activeElm) {
      // Activate the step if it was not active
      // This method allows for opening and closing of steps, i.e. one-at-a-time collapsible panel
      Dom.replaceClass(activeElm, "step", "active-step");
    }
  }
};
BLEEZ.form.error = {
  Show: function(elmId, message) {
    var elm = Dom.get(elmId);
    Dom.addClass(elmId + "-label", "error"); // Append the "error" class to the field label to give it a red color
    Dom.addClass(elmId, "input-error"); // Append the "input-error" class to the field to give it a red color and border
    var parentElm = Dom.get(elmId + "-notification");
    if(parentElm) { // Hide all visible notifications
      var elmArray = parentElm.getElementsByTagName("p");
      Dom.addClass(elmArray, "hide");
      // Show the error message
      Dom.get(elmId + "-error").innerHTML = message;
      Dom.setStyle(elmId + "-error", "opacity", "0");
      Dom.removeClass(elmId + "-error", "hide");
      var animShow = new YAHOO.util.Anim(elmId + "-error", {
        opacity: {
          to: 1
        }
      }, 0.25, Easing.easeOut);
      var parentElm = Dom.getAncestorByClassName(elm, "form-field");
      var d = BLEEZ.util.Dimensions(parentElm);
      BLEEZ.util.scroll.Vertical(BLEEZ.form.scrollContainer, null, d["top"], null);
      animShow.animate();
      // Hide all notification icons
      Dom.removeClass(elmId + "-notification", "status-notification");
      Dom.removeClass(elmId + "-notification", "success-notification");
      // Display the error notification icon
      Dom.addClass(elmId + "-notification", "error-notification");
    }
    // End of BLEEZ.form.error.Show
  },
  Hide: function(elmId) {
    var elm;
    var anim = new YAHOO.util.Anim(elmId + "-error", {
      opacity: {
        to: 0
      }
    }, 0.25, Easing.easeIn);
    anim.animate();
    // Hide the error notification icon
    Dom.removeClass(elmId + "-notification", "error-notification");
    // Hide the error message
    if(elm = Dom.get(elmId + "-error")) {
      elm.innerHTML = "";
    }
    Dom.addClass(elmId + "-error", "hide");
    // Remove the "input-error" class from the field to return it to normal
    Dom.removeClass(elmId, "input-error");
    // Remove the "error" class from field label to return it to normal
    Dom.removeClass(elmId + "-label", "error");
    // End of BLEEZ.form.error.Hide
  }
};
BLEEZ.form.field = {
  Init: function(elmId, fieldType) {
    elm = Dom.get(elmId);
    if(!elm) {
      return;
    }
    if(fieldType) {
      elm.setAttribute("validate", fieldType);
    }
    if(elm.offsetTop)
      elm.setAttribute("o", elm.offsetTop);
    Event.addFocusListener(elm, function() {
      try {
        BLEEZ.form.field.Focus(elmId);
      } catch(e) {
        errorHandler(e);
      }
    });
    Event.on(elm, "blur", function() {
      try {
        BLEEZ.form.field.Blur(elmId);
      } catch(e) {
        errorHandler(e);
      }
    });
    switch(fieldType) {
      case "securitycode":
        Event.on(elm, "keyup", function(e) {
          try {
            if(BLEEZ.util.KeyCode(e.keyCode)) {
              if(Dom.hasClass(this, "input-error") || this.value.length == 5) {
                BLEEZ.form.field.Validate(this.id);
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        break;
      case "password":
        Event.on(elm, "keyup", function(e) {
          try {
            if(Dom.hasClass(this, "input-error") || this.value.length >= 6) {
              BLEEZ.form.field.Validate(this.id);
            }
            BLEEZ.form.PasswordStrength(this.value);
            if(Dom.get("confirm" + this.id)) {
              var confirmElm = Dom.get("confirm" + this.id);
              if(!this.value) {
                confirmElm.value = "";
                confirmElm.disabled = true;
                BLEEZ.form.error.Hide("confirm" + this.id);
              } else
                confirmElm.disabled = false;
              if(Dom.hasClass(confirmElm, "input-error"))
                BLEEZ.form.field.Validate(confirmElm);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        break;
      case "comboother":
        Event.on(elmId, "keyup", function(e) {
          try {
            if(e.keyCode == 27) {
              var selectElm = Dom.get(elmId + "-select");
              Dom.addClass(this, "hide");
              Dom.removeClass(selectElm, "hide");
              selectElm.options[0].selected = true;
              this.value = selectElm.value;
              BLEEZ.form.field.Blur(elmId);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elmId + "-select", "change", function(e) {
          try {
            var otherElm = Dom.get(elmId);
            if(otherElm) {
              otherElm.value = this.value;
              if(this.value == "Other") {
                otherElm.value = "";
                Dom.addClass(this, "hide");
                Dom.removeClass(otherElm, "hide");
                otherElm.focus();
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        if(Dom.get(elmId + "-select").value == "Other" && Dom.get(elmId)) {
          Dom.addClass(elmId + "-select", "hide");
          Dom.removeClass(elmId, "hide");
        } else {
          Dom.removeClass(elmId + "-select", "hide");
        }
        break;
      case "date":
        var maxdate, mindate, startdate, title = Dom.get(elmId + "-label").innerHTML;
        if(elm.getAttribute("datetype") == "dateofbirth") {
          maxdate = new Date();
          maxdate.setFullYear(maxdate.getFullYear() - 3);
          mindate = new Date("January 01, 1850 00:00:00");
          if(elm.getAttribute("startdate")) {
            startdate = new Date(elm.getAttribute("startdate"));
          } else {
            startdate = new Date();
            startdate.setFullYear(startdate.getFullYear() - 25);
          }
        } else {
          maxdate = (elm.getAttribute("maxdate")) ? new Date(elm.getAttribute("maxdate")) : null;
          mindate = (elm.getAttribute("mindate")) ? new Date(elm.getAttribute("mindate")) : null;
          startdate = (elm.getAttribute("startdate")) ? new Date(elm.getAttribute("startdate")) : new Date();
        }
        BLEEZ.form.date.Calendar[elmId] = new YAHOO.widget.Calendar(elmId + "-calendar", {
          close: true,
          maxdate: maxdate,
          mindate: mindate,
          navigator: true,
          pagedate: startdate,
          selected: elm.value,
          start_weekday: 1,
          title: title
        });
        BLEEZ.form.date.Calendar[elmId].render();
        BLEEZ.form.date.Calendar[elmId].hide();
        Dom.removeClass(elmId + "-calendar", "hide");
        // Subscribe to the show event on Calendar cells
        BLEEZ.form.date.Calendar[elmId].showEvent.subscribe(function() {
          try {
            var calElm = Dom.get(elmId + "-calendar"), parentElm = Dom.getAncestorByClassName(elmId, "step-bd");
            if(!Dom.hasClass(calElm, "open") && parentElm && parentElm.getAttribute("h")) {
              var d = BLEEZ.util.Dimensions(calElm);
              calElm.setAttribute("h", d["height"] + 25);
              var h = parseInt(parentElm.getAttribute("h")) + d["height"] + 25;
              d = BLEEZ.util.Dimensions(elmId + "-notification");
              h += d["height"];
              parentElm.setAttribute("h", h);
              var anim = new YAHOO.util.Anim(parentElm, {
                height: {
                  to: h,
                  unit: "px"
                }
              }, 1, Easing.backOut);
              anim.animate();
              Dom.addClass(calElm, "open");
            }
            BLEEZ.form.field.Focus(elmId);
          } catch(e) {
            errorHandler(e);
          }
        });
        // Subscribe to the hide event on Calendar cells
        BLEEZ.form.date.Calendar[elmId].hideEvent.subscribe(function() {
          try {
            var calElm = Dom.get(elmId + "-calendar"), parentElm = Dom.getAncestorByClassName(elmId, "step-bd");
            if(Dom.hasClass(calElm, "open") && parentElm && parentElm.getAttribute("h")) {
              var h = parseInt(parentElm.getAttribute("h")) - parseInt(calElm.getAttribute("h"));
              d = BLEEZ.util.Dimensions(elmId + "-notification");
              h -= d["height"];
              parentElm.setAttribute("h", h);
              var anim = new YAHOO.util.Anim(parentElm, {
                height: {
                  to: h,
                  unit: "px"
                }
              }, 1, Easing.backOut);
              anim.animate();
              Dom.removeClass(calElm, "open");
            }
            BLEEZ.form.field.Blur(elmId);
          } catch(e) {
            errorHandler(e);
          }
        });
        // Subscribe to the select event on Calendar cells
        BLEEZ.form.date.Calendar[elmId].selectEvent.subscribe(function(type, args) {
          BLEEZ.form.date.Rip(elmId, type, args);
          BLEEZ.form.field.Validate(elmId);
          BLEEZ.form.date.Calendar[elmId].hide();
        });
        Event.on(elmId + "-calendaricon", "click", function() {
          try {
            BLEEZ.form.date.Calendar[elmId].show();
          } catch(e) {
            errorHandler(e);
          }
        });
        Dom.removeClass(elmId + "-calendaricon", "hide");
        elm.disabled = true;
        Event.on(elm, "change", function() {
          try {
            if(Dom.hasClass(elmId, "input-error")) {
              BLEEZ.form.field.Validate(elmId);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "keyup", function(e) {
          try {
            if(BLEEZ.util.KeyCode(e.keyCode)) {
              if(Dom.hasClass(elmId, "input-error")) {
                BLEEZ.form.field.Validate(elmId);
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        break;
      case "numeric":
      case "percent":
        Event.on(elm, "keydown", function(e) {
          try {
            var re = /\./;
            if(e.keyCode == 32) {
              Event.preventDefault(e);
            } else if(e.shiftKey == true && e.keyCode < 48) {
            } else if(e.keyCode <= 57 || (e.keyCode >= 91 && e.keyCode <= 105) || (e.keyCode >= 112 && e.keyCode <= 145)) {
            } else if((e.keyCode == 110 || e.keyCode == 190) && !re.test(elm.value)) {
            } else {
              Event.preventDefault(e);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "change", function() {
          try {
            if(Dom.hasClass(elmId, "input-error")) {
              BLEEZ.form.field.Validate(elmId);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "keyup", function(e) {
          try {
            if(BLEEZ.util.KeyCode(e.keyCode)) {
              if(Dom.hasClass(elmId, "input-error")) {
                BLEEZ.form.field.Validate(elmId);
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        break;
      case "integer":
        Event.on(elm, "keydown", function(e) {
          try {
            if(e.keyCode != 32) {
            } else if(e.shiftKey == true && e.keyCode < 48) {
            } else if(e.keyCode <= 57 || (e.keyCode >= 91 && e.keyCode <= 105) || (e.keyCode >= 112 && e.keyCode <= 145)) {
            } else {
              Event.preventDefault(e);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "change", function() {
          try {
            if(Dom.hasClass(elmId, "input-error")) {
              BLEEZ.form.field.Validate(elmId);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "keyup", function(e) {
          try {
            if(BLEEZ.util.KeyCode(e.keyCode)) {
              if(Dom.hasClass(elmId, "input-error")) {
                BLEEZ.form.field.Validate(elmId);
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        break;
      default:
        Event.on(elm, "change", function() {
          try {
            if(Dom.hasClass(elmId, "input-error")) {
              BLEEZ.form.field.Validate(elmId);
            }
          } catch(e) {
            errorHandler(e);
          }
        });
        Event.on(elm, "keyup", function(e) {
          try {
            if(BLEEZ.util.KeyCode(e.keyCode)) {
              if(Dom.hasClass(elmId, "input-error")) {
                BLEEZ.form.field.Validate(elmId);
              }
            }
          } catch(e) {
            errorHandler(e);
          }
        });
    }
    BLEEZ.form.field.Blur(elmId);
    // End of BLEEZ.form.field.Init
  },
  Clear: function(elmId) {
    if(Dom.get(elmId)) {
      Dom.get(elmId).value = ""; // Clear the field
      // Hide the error message
      BLEEZ.form.error.Hide(elmId);
      BLEEZ.form.field.Blur(elmId);
    }
    // End of BLEEZ.form.field.Clear
  },
  Focus: function(elmId) {
    if(Dom.hasClass(elmId + "-error", "hide") && !Dom.hasClass(elmId + "-notification", "success-notification")
      && !Dom.hasClass(elmId + "-notification", "status-notification")) {
      var parentElm = Dom.get(elmId + "-notification");
      var elmArray = parentElm.getElementsByTagName("p");
      Dom.addClass(elmArray, "hide");
      // Show the hint
      Dom.setStyle(elmId + "-hint", "opacity", "0");
      Dom.removeClass(elmId + "-hint", "hide");
      var anim = new YAHOO.util.Anim(elmId + "-hint", {
        opacity: {
          to: 1
        }
      }, 0.25, Easing.easeOut);
      anim.animate();
    }
    // End of BLEEZ.form.field.Focus
  },
  Blur: function(elmId) {
    var elm = Dom.get(elmId);
    if(!Dom.hasClass(elmId + "-hint", "hide")) { // The hint is visible
      var anim = new YAHOO.util.Anim(elmId + "-hint", {
        opacity: {
          to: 0
        }
      }, 0.25, Easing.easeIn);
      anim.animate();
      // Hide the hint
      Dom.addClass(elmId + "-hint", "hide");
    }
    // End of BLEEZ.form.field.Blur
  },
  Validate: function(elmId) {
    var msg, required = Dom.hasClass(elmId + "-label", "required");
    var elm = Dom.get(elmId);
    if(elm) {
      elm.value = BLEEZ.util.format.Trim(elm.value);
      if(required && !elm.value) {
        // The value is required but is empty or default
        switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
          case "so":
            msg = "Macluumaadkan waa loo baahan yahay.";
            break;
          default:
            msg = "This information is required.";
        }
        BLEEZ.form.error.Show(elmId, msg);
        return false;
      }
      switch(elm.getAttribute("validate")) {
        case "name":
          if(elm.value && !BLEEZ.util.regX.Name(elm.value)) {
            // Invalid format
            msg = "Invalid name format. " + "Only letters, hyphens (-) and apostrophes (')<br>are allowed.";
          }
          break;
        case "email":
          if(elm.value && !BLEEZ.util.regX.Email(elm.value)) {
            // Invalid format
            switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
              case "so":
                msg = "Kani maahan e mail saxan.";
                break;
              default:
                msg = "This is not a valid email address.";
            }
          }
          break;
        case "phone":
          if(elm.value && !BLEEZ.util.regX.Phone(elm.value)) {
            // Invalid format
            msg = "This is not a valid phone format.";
          }
          break;
        case "uridomain":
          if(elm.value && !BLEEZ.util.regX.URIDomain(elm.value)) {
            // Invalid format
            msg = "This is not a valid URL.";
          }
          break;
        case "filename":
          if(elm.value && !BLEEZ.util.regX.Filename(elm.value)) {
            // Invalid format
            msg = "The filename you have specified is invalid.<br>Only letters (a-z), numbers (0-9), hyphens (-) and underscores (_) are allowed, NO SPACES.";
          }
          break;
        case "duration":
          if(elm.value && !BLEEZ.util.regX.Duration(elm.value)) {
            // Invalid format
            msg = "This is not a valid entry. Please enter a duration in the format h:m:s or m:s, e.g 1:25:07 or 6:39.";
          }
          break;
        case "decimal":
          if(elm.value && !BLEEZ.util.regX.Decimal(elm.value)) {
            // Invalid format
            msg = "This is not a valid decimal number.";
          }
          break;
        case "password":
          if(BLEEZ.util.format.Trim(elm.value).length < 6) {
            msg = "Please enter a password that is at least 6 characters long.";
          } else if(!BLEEZ.util.regX.Password(elm.value)) {
            msg = "Invalid password. Please enter a password made up of letters and/or numbers and standard symbols (!@#$%^&*). No spaces allowed.";
          }
          break;
        case "confirmpassword":
          var pwdElm = Dom.get(elm.id.replace(/confirm/, ""));
          if(BLEEZ.util.format.Trim(pwdElm.value) != BLEEZ.util.format.Trim(elm.value)) {
            msg = "The passwords you have enterred do not match.";
          }
          break;
        case "securitycode":
          if(BLEEZ.util.format.Trim(elm.value).length != 5) {
            switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
              case "so":
                msg = "Fadlan u gali 5ta jifar ee xuruufaha sirta ah sida lagu tusay.";
                break;
              default:
                msg = "Please enter the 5-character security code as shown.";
            }
          } else {
            BLEEZ.form.securityCode.Validate(elmId);
            return BLEEZ.form.securityCode.valid;
          }
          break;
      }
      if(msg) {
        if(Dom.get(elmId + "-error") && Dom.get(elmId + "-error").innerHTML != msg) {
          // Display an error message
          BLEEZ.form.error.Show(elmId, msg);
        }
      } else {
        BLEEZ.form.error.Hide(elmId);
        return true;
      }
    }
    // End of BLEEZ.form.field.Validate
  }
};
BLEEZ.form.PasswordStrength = function(pwd) {
  var elm = YAHOO.util.Dom.getElementsByClassName("bar", "div", "passwordstrength");
  var w = BLEEZ.util.regX.PasswordStrength(pwd) * 255;
  var anim = new YAHOO.util.Anim(elm[0], {
    width: {
      to: w
    }
  }, 0.5, YAHOO.util.Easing.easeOut);
  anim.animate();
};
BLEEZ.form.securityCode = {
  valid: false,
  Validate: function(elmId) {
    // Initialize variables
    var msg, elm = Dom.get(elmId + "-status");
    var parentElm = Dom.get(elmId + "-notification");
    var elmArray = parentElm.getElementsByTagName("p");
    Dom.addClass(elmArray, "hide");
    switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
      case "so":
        msg = "Xaqiiji xuruufaha sirta ah. Fadlan sug&hellip;";
        break;
      default:
        msg = "Verifying security code. Please wait&hellip;";
    }
    elm.innerHTML = msg;
    Dom.setStyle(elm, "opacity", "0");
    Dom.removeClass(elm, "hide");
    var anim = new YAHOO.util.Anim(elm, {
      opacity: {
        to: 1
      }
    }, 0.25, Easing.easeOut);
    anim.animate();
    // Hide all notification icons
    Dom.removeClass(elmId + "-notification", "error-notification");
    Dom.removeClass(elmId + "-notification", "success-notification");
    // Display the status notification icon
    Dom.addClass(elmId + "-notification", "status-notification");
    elm = Dom.get(elmId);
    var response = {
      timeout: 60000,
      success: function(x) {
        var xmlResponse = x.responseXML.documentElement;
        var success = parseInt(BLEEZ.util.readXML.Data(xmlResponse, "success"));
        if(!success) {
          switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
            case "so":
              msg = "Fadlan gali xuruufaha sirta ah ee saxan.";
              break;
            default:
              msg = "Please enter the correct security code.";
          }
          BLEEZ.form.error.Show(elmId, msg);
          BLEEZ.form.securityCode.valid = false;
        } else {
          // The security code is valid
          BLEEZ.form.securityCode.valid = true;
          BLEEZ.form.error.Hide(elmId);
          parentElm = Dom.get(elmId + "-notification");
          elmArray = parentElm.getElementsByTagName("p");
          Dom.addClass(elmArray, "hide");
          elm = Dom.get(elmId + "-success");
          switch(document.getElementsByTagName("html")[0].getAttribute("lang")) {
            case "so":
              msg = "Sixid ku samee";
              break;
            default:
              msg = "Correct";
          }
          elm.innerHTML = msg;
          Dom.setStyle(elm, "opacity", "0");
          Dom.removeClass(elm, "hide");
          var anim = new YAHOO.util.Anim(elm, {
            opacity: {
              to: 1
            }
          }, 0.25, Easing.easeOut);
          anim.animate();
          // Hide all notification icons
          Dom.removeClass(elmId + "-notification", "error-notification");
          Dom.removeClass(elmId + "-notification", "status-notification");
          // Display the status notification icon
          Dom.addClass(elmId + "-notification", "success-notification");
        }
      },
      failure: function(x) {
        // The request failed
        // Show error dialog
        var dialog = new BLEEZ.dialog.modal;
        dialog.Show("error-dialog", "Problem Encountered", "There was a problem accessing the server: " + x.statusText, [ {
          text: "OK",
          handler: function() {
            this.hide();
          }
        } ]);
      }
    };
    var postVars = "code=" + BLEEZ.util.format.Trim(elm.value);
    var securityPath = (Dom.get("rootpath").value) ? Dom.get("rootpath").value + "Includes/security.php" : "../../Includes/security.php";
    var xhr = Connect.asyncRequest("POST", securityPath, response, postVars);
  }
};
BLEEZ.form.date = {
  Calendar: new Array(),
  Rip: function(elmId, type, args) {
    // Get the date components
    var dateArray = args[0], dt = dateArray[0];
    var y = dt[0], m = dt[1], d = dt[2];
    // Create the formatted date string
    var dateString = m + "/" + d + "/" + y;
    // Insert the formatted date into the text field
    var elm = Dom.get(elmId);
    elm.value = dateString;
    elm.setAttribute("timestamp", y + "-" + m + "-" + d);
    elm.setAttribute("startdate", y + "," + m + "," + d);
    if(Dom.get(elmId + "-timestamp"))
      Dom.get(elmId + "-timestamp").value = y + "-" + m + "-" + d;
  }
};
