﻿/***********************
Global.js
Functions created here should be useful to most of MedCV.
Specialized functions should be added to other js files
**/

/*
  Error message decoder
*/
errors = {
    "success":              "Nothing bad happened",
    "not authorized":       "You are not an authorized member of this domain",
    "bad login":            "Invalid email/password",
    "bad email":            "Please enter a valid email address.",
    "locked":               "Account locked.",
    "duplicate email":      "Email address already in use.",
    "duplicate survey":     "You have already completed this survey",
    "duplicate key":        "Provided key is already in use",
    "service error":        "Service temporarily unavailable.",
    "not signed":           "You must agree to the terms of service and privacy policy.",
    "incomplete":           "Required fields are missing or invalid.",
    "error":                "An unknown error has occurred.",
    "password not matched": "Current password is incorrect.",
    "bad domain":           "Domain not authenticated",
    "email fail":           "Unable to send confirmation email"
    
};

function decodeError(error) {
  error = errors[error];
  if (error == undefined) {
    document.body.innerHTML = error;
  }
  
  return error;
}


var onLoadEvents = new Array();
var doneLoading = false;
window.onload = function() {
  for (var i = 0; i < onLoadEvents.length; i++) {
    onLoadEvents[i]();
  }

  doneLoading = true;
}


function addLoadEvent(event) {
  //check if onload has already finished
  if (doneLoading == false) {
    onLoadEvents.push(event);
  //if it has then just run the event
  } else {
    event();
  }
}
/**
extends the String class to count the number of 
occurences within a given string
*/
String.prototype.count = function(s1) {
  return this.length - this.replace(new RegExp(s1, "g"), '').length;
}

/**
  Determines if a value is a valid email address
*/
String.prototype.isEmail = function() {
  var reg = new RegExp(
    "^[0-9a-zA-Z._%+-]+@[0-9a-zA-Z]+[\\.]{1}[0-9a-zA-Z]+[\\.]?[0-9a-zA-Z]+$"
  );

  return reg.test(this);
}

String.prototype.padL = function(pad, length) {
  var padded = this;
  while (padded.length < length) {
    padded = pad + padded;
  }
  return padded
}

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "")
}
/**
Converts a given array list into a post string
for example:

myPost = new Array();
myPost["email"] = "bob@ki.com";
myPost"password"] = "password";
ToPostData(myPost);
    
will yield "email=bob@ki.com&password=password"
The method is useful for posting data to the server
*/
function ToPostData(form) {
  var post = "";
  for (var i = 0; i < form.length; i++) {
    if (form[i].type != "submit" && form[i].type != "button" &&
        form[i].name != null && form[i].value != null &&
        form[i].className.match("ignored") == null) {
      var data = form[i].value;
      //remove any masking from masked data fields
      if (form[i].className && form[i].className.match("mask")) {
        data = form[i].value.replace(/[^A-Za-z0-9]/g, "");
      }
      //assign a true false value to check boxes
      if (form[i].type == "radio" && form[i].checked == false) {
        continue;
      }
        data = data.replace(/%/g, "%25");
        data = data.replace(/&/g, "%26");
        data = data.replace(/=/g, "%3D");
     
       if (!(form[i].type == "checkbox" && form[i].checked == false))
           post += form[i].name + "=" + data + "&";
    }
  }

  return post.substring(0, post.length - 1);
}

/**
Simplifies AJAX requests to a simple function call
Arguments:
uri: address to send the request to
listener: function to be called when the request completes
function will recieve:
arguments[0], response text
arguments[1], response xml,
arguments[2], if the request was successful
            
parameters: post parameters to send to the server as an
array. See ToPostData for more information
*/


function request(uri, parameters, listener, isAsync) {
  var rq = new XMLHttpRequest();
  if (isAsync == null) {
      isAsync = true;
  }

  if (isAsync) {
      rq.onreadystatechange = function() {
          //The request was successful
          if (rq.readyState == 4 && listener) {
              if (rq.status == 200) {
                  listener(rq.responseText, rq.responseXML, true);
              } else {
                  listener(null, null, false);
                  document.body.innerHTML = rq.responseText;
              }
          } else if (rq.readyState == 5) {
              listener(null, null, false);
              document.body.innerHTML = rq.responseText;
          }
      }
  }
  
  //make the request
  if (parameters == null) { //if there are no post variables, GET
    rq.open("get", uri, true);
    rq.send(null);
  } else { //otherwise send them and POST
    rq.open("post", uri, isAsync);
    rq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    rq.send(ToPostData(parameters));
    if (!isAsync)
        return rq.responseText;
  }
}

/**
From a list of checkboxes create a multi-select.
*/
function ConsolidateSelect(select) {
  var checks = select.getElementsByTagName("input");
  var output = "";
  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked) {
      output += checks[i].value + ","
    }
  }

  return output.substring(0, output.length - 1);
}

/**
grey out everything and display the loading dialog
*/
function loadScreen(show) {

}

function loginScreen(show) {
  try {
    if (show) {
      document.getElementById("login_overlay").style.display = "block";
    } else {
      document.getElementById("login_overlay").style.display = "";
    }
  } catch (ex) {
    
  }
}


/**
Overlay to display the reset your password dialog
*/
function passwordResetScreen(show) {
  hasSecurityQuestion = false;
  securityAttempts = 0;

  document.forms['reset']['username'].value = document.forms['login']['username'].value;
  document.forms['reset']['answer'].value = "";
  document.getElementById("reset_question").style.display = "none";
  document.getElementById("passResetLoad").style.display = "none";
  document.getElementById("reset_explination").innerHTML =
    "Please enter your account's email address to " +
    "begin resetting your password";

  if (show) {
    loginScreen(false);
    document.getElementById("resetPassword_overlay").style.display = "block";
  } else {
    loginScreen(true);
    document.getElementById("resetPassword_overlay").style.display = "";
  }
}

//makes the value of name friendly for regex
function SanitizeRegex(exp) {
  exp = exp.replace(/\(/g, "\\(");
  exp = exp.replace(/\)/g, "\\)");
  exp = exp.replace(/\[/g, "\\[")
  exp = exp.replace(/\]/g, "\\]")
  exp = exp.replace(/\./g, "\\.")
  return exp;
}
/*
  Load the document from the given URL into an invisible iframe,
  print the content once it loads, and then remove the iframe when
  finished.
*/
function printDocument(url) {
  loadScreen(true);
  var frame = document.createElement("iframe");
  frame.width = "1";
  frame.height = "1";

  try { //try for IE
    frame.attachEvent('onload', function() {
      loadScreen(false);
      frame.contentWindow.focus();
      frame.contentWindow.print();
      //remove the iframe
      window.onfocus = function() {
        document.body.removeChild(frame);
        window.onfocus = null;
      };
    });
  } catch (e) { //catch for firefox
    frame.onload = function() {
      loadScreen(false);
      frame.contentWindow.focus();
      frame.contentWindow.print();
      //remove the iframe
      window.onfocus = function() {
        document.body.removeChild(frame);
        window.onfocus = null;
      };

    };
  }

  frame.src = url;
  document.body.appendChild(frame);
  return false;
}

/*
  Print the given div by moving it to an iframe
  printing it, and then deleting it
  
  id: id of the div to print
  title: give the document a title to display at the top of the page
*/
function printDiv(id, title) {
  var div = document.getElementById(id);
  var frame = document.createElement("iframe");
  frame.style.width = "1";
  frame.style.height = "1";

  try { //try for IE
    frame.attachEvent('onload', function() {
      var newDiv = frame.contentWindow.document.createElement("div");
      newDiv.innerHTML = div.innerHTML;
      newDiv.className = div.className;
      newDiv.id = div.id;

      var styles = document.getElementsByTagName("link")
      for (var i = 0; i < styles.length; i++) {
        createStyle(styles[i].href, styles[i].media, frame.contentWindow.document);
      }

      frame.contentWindow.title = title;
      frame.contentWindow.document.body.appendChild(newDiv);
      frame.contentWindow.focus();
      frame.contentWindow.print();
      //remove the iframe
      window.onfocus = function() {
        document.body.removeChild(frame);
        window.onfocus = null;
      };
    });
  } catch (e) { //catch for firefox
    frame.onload = function() {
      //this is the exact same function as above but for firefox.
      //There are many subtle differences, so it was easier to just
      //seperate the two.
      var newDiv = frame.contentDocument.createElement("div");
      newDiv.innerHTML = div.innerHTML;
      newDiv.className = div.className;
      newDiv.id = div.id;
      var styles = document.getElementsByTagName("link")
      for (var i = 0; i < styles.length; i++) {
        createStyle(styles[i].href, styles[i].media, frame.contentDocument);
      }

      frame.contentDocument.title = title;
      frame.contentDocument.body.appendChild(newDiv);
      frame.contentWindow.print();
      //remove the iframe
      window.onfocus = function() {
        document.body.removeChild(frame);
        window.onfocus = null;
      };
    };
  }

  document.body.appendChild(frame);
}

function createStyle(href, media, doc) {
  if (doc == null) doc = document;
  var link = doc.createElement("link");
  link.href = href;
  link.media = media;
  link.type = "text/css";
  link.rel = "stylesheet";

  doc.getElementsByTagName("head")[0].appendChild(link);
}
