
/*  Rounded Corners
    -----------------------------------------------
    Simulate rounded corners, in browsers that don't support it yet.
    ----------------------------------------------- */
    (function() {

      var tries = 0;

      function initialize() {
        waitForBody();
      };

      function waitForBody() {
        var body = document.getElementsByTagName("body");
        if (body == null || body.length <= 0) {
          // If we haven't been trying for more than 5 seconds
          if (tries++ < 50) {
            // Wait 1/10 second, and try again
            setTimeout(waitForBody, 100);
          }
        } else {
          // If the browser supports input placholders, there's no need to continue
          if (supportsBorderRadius()) return;

          tries = 0;
          waitForContent();
        }
      };

      function waitForContent() {
        var content = document.getElementById("content");
        if (content == null) {
          // If we haven't been trying for more than 5 seconds
          if (tries++ < 50) {
            // Wait 1/10 second, and try again
            setTimeout(waitForContent, 100);
          }
        } else {
          var div;
          div = document.createElement("div");
          div.className = "corner-top-left";
          content.appendChild(div);
          div = document.createElement("div");
          div.className = "corner-top-right";
          content.appendChild(div);
          div = document.createElement("div");
          div.className = "corner-bottom-right";
          content.appendChild(div);
          div = document.createElement("div");
          div.className = "corner-bottom-left";
          content.appendChild(div);
        }
      };

      // KUDOS: http://chris-barr.com/entry/detect_browser_support_for_css_properties/
      function supportsBorderRadius(){
        var s = document.body.style;
        return  s.WebkitBorderRadius !== undefined || 
                s.MozBorderRadius !== undefined ||
                s.BorderRadius !== undefined;
      }

      initialize();

    })();


/*  Placeholder Text
    -----------------------------------------------
    Simulate placeholder text, in browsers that don't support it yet.
    ----------------------------------------------- */
    (function() {

      var tries = 0;

      function initialize() {
        // If the browser supports input placholders, there's no need to continue
        if (supportsInputPlaceholder()) return;

        waitForBody();
      };

      function waitForBody() {
        var body = document.getElementsByTagName("body");
        if (body == null || body.length <= 0) {
          // If we haven't been trying for more than 5 seconds
          if (tries++ < 50) {
            // Wait 1/10 second, and try again
            setTimeout(waitForBody, 100);
          }
        } else {
          tries = 0;
          // Only look for a placeholder field on the home page (at the time of this
          // writing, that's the only document in which a placeholder field appears).
          if (body[0].id == "home-page") {
            waitForField();
          }
        }
      };

      function waitForField() {
        // Only look for a subscribe field (at the time of this writing,
        // that's the only section in which a placeholder field appears)
        var signup = document.getElementById("subscribe");
        if (signup) {
          var fields = signup.getElementsByTagName("input");
          for (var index = 0; index < fields.length; index++) {
            var placeholderText = fields[index].getAttribute("placeholder");
            if (placeholderText != null && placeholderText != "") {
              addPlaceholderText(fields[index], placeholderText);
            }
          }
        } else {
          // If we haven't been trying for more than 5 seconds
          if (tries++ < 50) {
            // Wait 1/10 second, and try again
            setTimeout(waitForField, 100);
          }
        }
      };

      function addListener(element, eventName, handler) {
          if (element.addEventListener) {
            element.addEventListener(eventName, handler, false);
          } else {
            element.attachEvent("on" + eventName, handler);
          }
      };

      // KUDOS: http://diveintohtml5.org/detect.html
      function supportsInputPlaceholder() {
        var i = document.createElement('input');
        return 'placeholder' in i;
      };

      function addPlaceholderText(field, text) {
        var placeholder = document.createElement("i");
        placeholder.innerHTML = text;
        placeholder.className = "placeholder";
        field.parentNode.appendChild(placeholder);

        // Handle the case where the field has a value when the page loads.
        if (field.value != null && field.value != "") {
          placeholder.style.display = "none";
        }

        addListener(field, "focus", function() {
          placeholder.style.display = "none";
        });
        addListener(placeholder, "click", function() {
          placeholder.style.display = "none";
        });
        addListener(field, "blur", function() {
          if (field.value == null || field.value == "") {
            placeholder.style.display = "block";
          }
        });
      };

      initialize();

    })();


    /* =ValidateForm
    ----------------------------------------------- */
    function getAncestor(contextElement, tagName) {
      tagName = String(tagName).toLowerCase();
      var ancestor = contextElement.parentNode;
      while(ancestor && String(ancestor.nodeName).toLowerCase() != tagName) {
        ancestor = ancestor.parentNode;
      }
      return ancestor;
    };
    function addListener(element, eventName, handler) {
      if (element.addEventListener) {
        element.addEventListener(eventName, handler, false);
      } else {
        element.attachEvent("on" + eventName, handler);
      }
    };
    function preventDefault(e) {
      if (e.preventDefault) e.preventDefault();
      e.returnValue = false; // For IE
    };

    // KUDOS: Prototype JS (http://www.prototypejs.org/)
    function addClassName(element, className) {
      if (hasClassName(element, className)) return;
      var existingClassName = (element.className == null || element.className == "") ? "" : element.className + " ";
      element.className = existingClassName + className;
    };
    function removeClassName(element, className) {
      element.className = strip(element.className.replace(
        new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " "));
    };
    function hasClassName(element, className) {
      var elementClassName = element.className;
      return (elementClassName.length > 0 && (elementClassName == className ||
        new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
    };
    function strip(str) {
      return str.replace(/^\s+/, "").replace(/\s+$/, "");
    };

    var ValidateForm = function(element) {
      if (!element) return;

      var fields = [];
      var errorMessage;
      var submitButtonContainer;
      var isMemberForm = (element.id == "member_form");
      var isProfileEditPage = (document.body.id == "profile-edit-page");

      function initialize() {

        var labels = element.getElementsByTagName("label");
        var buttons = element.getElementsByTagName("button");

        if (!buttons || !buttons.length || buttons.length <= 0) return;

        submitButtonContainer = getAncestor(buttons[buttons.length - 1], "p");
        if (submitButtonContainer == null) {
          submitButtonContainer = getAncestor(buttons[buttons.length - 1], "ul");
        }
        for (var index = 0; index < labels.length; index++) {
          var label;
          var field;

          // TBD: It might be more reliable to add a required class name to
          // the label, instead of relying on the presence of the "*" indicator.
          required = (labels[index].innerHTML.indexOf("*") >= 0);
          if (!required) continue;
          label = getLabel(labels[index]);
          field = getField(labels[index]);

          if (!label || !field) continue;
          fields.push({
            container: labels[index],
            field: field,
            label: label,
            email: (String(label.toLowerCase()).indexOf("email") >= 0)
          });
        }
        addListener(element, "submit", onSubmit);
      };

      function onSubmit(e) {
        var emptyFields = [];
        var ignorePasswords = false;

        if (isMemberForm && isProfileEditPage) {
          ignorePasswords = true;
          // If one of the password fields has been filled out, do not ignore them.
          for (var index = 0; index < fields.length; index++) {
            if (fields[index].field.type == "password" && 
                fields[index].field.value != "" && 
                fields[index].field.value != null) {
              ignorePasswords = false;
            }
          }
        }

        for (var index = 0; index < fields.length; index++) {
          if (
            (fields[index].field.value == "" ||
            fields[index].email && !isValidEmail(fields[index].field.value)) &&
            (!ignorePasswords || fields[index].field.type != "password")) {
            emptyFields.push(fields[index]);
            addClassName(fields[index].container, "error");
          } else {
            removeClassName(fields[index].container, "error");
          }
        }

        if (errorMessage) {
          errorMessage.parentNode.removeChild(errorMessage);
          errorMessage = null;
        }
        if (emptyFields.length <= 0) return;

        errorMessage = document.createElement("div");
        errorMessage.className = "error-message";

        // This makes the offsetLeft calculation work properly.
        //element.style.position = "relative";
        //errorMessage.style.marginLeft = submitButtonContainer.offsetLeft + "px";

        submitButtonContainer.parentNode.insertBefore(errorMessage, submitButtonContainer);

        var messageText = document.createElement("p");
        messageText.appendChild(document.createTextNode("One or more required fields is empty or contains an invalid value:"));
        errorMessage.appendChild(messageText);

        var errorMessageList = document.createElement("ul");
        errorMessage.appendChild(errorMessageList);

        for (var index = 0; index < emptyFields.length; index++) {
          var li = document.createElement("li");
          errorMessageList.appendChild(li);
          var span = document.createElement("span");
          li.appendChild(span);
          span.innerHTML = emptyFields[index].label;
        }

        preventDefault(e);
      }

      function getLabel(element) {
        try {
          var labelContainer = element.getElementsByTagName("span")[0];
          var candidates = labelContainer.childNodes;
          for (var index = 0; index < candidates.length; index++) {
            // If it's a text node, and it has length, assume it's the label.
            if (candidates[index].nodeType == 3 && candidates[index].length > 1) {
              return candidates[index].nodeValue;
            }
          }
        } catch(e) {
          console.error(e);
        }
      };

      function getField(element) {
        var candidates = element.childNodes;
        for (var index = 0; index < candidates.length; index++) {
          if (String(candidates[index].nodeName).toLowerCase() == "textarea" ||
              (String(candidates[index].nodeName).toLowerCase() == "input" && 
              ( candidates[index].type == "text" || 
                candidates[index].type == "email" || 
                candidates[index].type == "username" || 
                candidates[index].type == "password"))) {
            return candidates[index];
          }
        }
      };

      function isValidEmail(value) {
        var regExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return (regExp.test(value));
      };

      initialize();
    };

    (function() {

      var tries = 0;

      function initialize() {
        waitForFooter();
      };

      function waitForFooter() {
        var target = document.getElementById("info");
        if (target) {
          tries = 0;

          var forms = document.body.getElementsByTagName("form");
          for (var index = 0; index < forms.length; index++) {
            new ValidateForm(forms[index]);
          }

        } else {
          // If we haven't been trying for more than 5 seconds
          if (tries++ < 50) {
            // Wait 1/10 second, and try again
            setTimeout(waitForFooter, 100);
          }
        }
      };

      initialize();

    })();

