//pdr

var currentDate = new Date();
var invalidUsername = false;
var invalidPassword = false;

$(document).ready(function() {

  // Add year to the footer
  $(currentDate.getFullYear()).appendTo("#currentDate");

  // Handle jump navigation
  $(".jumpNav").change( function() {
    location.href = $(this).val();
  });

  // Add datepicker support
  try {
    $(".datepicker").datepicker({
      buttonImage: 'content/rx/images/iconDatePicker.gif',
      buttonImageOnly: true,
      buttonText: 'Choose a date',
      changeMonth: true,
      changeYear: true,
      dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
      showButtonPanel: true,
      showOn: 'button'
    });

    // Birth dates require a year range that goes very far back
    $(".birthDate").datepicker("option", "yearRange", "1900:" + currentDate.getFullYear());

    // Birth dates need to be limited to the current year and before
    $(".birthDate").datepicker("option", "maxDate", "+0d");
  }
  catch(e) {
  }

  try {
    // Initialize any custom tool tips
    setCustomToolTips();
  }
  catch(e) {
  }

  // Submit form if valid
  $("#btnSignIn").click(function() {
    if (validate(getLoginRuleset($("body").attr("id")))) {
      $("#signInForm").submit();
    }
    return false;
  });

  $("a#logout").click(function() {
    confirmLogoutAlert($(this));
    return false;
  });

  // This MUST be last
  try {
    // Page-specific initialization
    initPage();
  }
  catch(e) {
  }

});

function getURLParamValue(url, paramName) {
  paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

  var regExpStr = "[\\?&]" + paramName + "=([^&#]*)";
  var regExp = new RegExp(regExpStr);
  var results = regExp.exec(url);

  if ( results == null ) {
    return "";
  }
  else {
    return results[1];
  }
}

function closeThickboxSubmit(formId) {
  tb_remove();
  $("#" + formId).submit();
}

function toggleDisabled(element, enabled) {
  if (enabled) {
    $(element).removeAttr("disabled");
  }
  else {
    $(element).attr("disabled", "disabled");
  }
}

function confirmZip(formId, zipField1, zipField2) {
  var fullZip = (zipField2.length > 0) ? zipField1 + "-" + zipField2 : zipField1;

  tb_show('Confirm Zip Code', $('input#zipConfirmUrl').val() +
          '?&f=' + formId + '&zip=' + fullZip +
          '&TB_iframe=true&height=145&width=335&modal=true');
}

function confirmPhone(formId, phoneField1, phoneField2) {
  var fullPhone = (phoneField2.length > 0) ? phoneField1 + "-" + phoneField2 : phoneField1;

  tb_show('Confirm Phone', $('input#phoneConfirmUrl').val() +
          '?KeepThis=true&f=' + formId + '&phone=' + fullPhone +
          '&TB_iframe=true&height=145&width=335&modal=true');
}

function setCustomToolTips() {

  $("a.customToolTip").each(function() {

    $(this).attr("tabindex", "-1");

    $(this).hover(function(e) {
      $("#customToolTipContent").html($(this).attr("alt"));
      $(this).removeAttr("alt");
      $("#customToolTip").removeClass("left");

      var pageDimensions = getPageDimensions();
      var tipY = $(this).position().top - $(this).outerHeight();
      var tipX = $(this).position().left + ($(this).outerWidth() + 10);

      $("#customToolTip").css({"top": tipY, "left": tipX});
      $("#customToolTip").stop(true, true)
                         .fadeIn("fast");

      var divWidth = $("#customToolTip").width();
      var divRightEdge = tipX + divWidth;
      var rightOffset = divRightEdge - pageDimensions[0];

      if (rightOffset > 0) {
        tipX = (tipX - 60) - divWidth;
        $("#customToolTip").css({"top": tipY, "left": tipX});
        $("#customToolTip").addClass("left");
      }

      $(this).removeAttr("alt");
      $(this).children("img").removeAttr("alt");
    }, function() {
      $("#customToolTip").stop(true, true)
                         .fadeOut("fast");
      $(this).attr("alt", $("#customToolTipContent").html());
    });
  });
}

function setCustomRichToolTip(anchorElem, contentElem) {
  $(anchorElem).hover(function(e) {
    $(contentElem).removeClass("left");

    var pageDimensions = getPageDimensions();
    var tipY = $(this).position().top - $(this).outerHeight();
    var tipX = $(this).position().left + ($(this).outerWidth() + 10);

    $(contentElem).css({"top": tipY, "left": tipX});
    $(contentElem).stop(true, true)
                  .fadeIn("fast");

    var divWidth = $(contentElem).width();
    var divRightEdge = tipX + divWidth;
    var rightOffset = divRightEdge - pageDimensions[0];

    if (rightOffset > 0) {
      tipX = (tipX - 60) - divWidth;
      $(contentElem).css({"top": tipY, "left": tipX});
      $(contentElem).addClass("left");
    }
  }, function() {
    $(contentElem).stop(true, true)
                  .fadeOut("fast");
  });
}

function getPageDimensions() {
  var docElem = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (docElem && docElem.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (docElem && docElem.clientHeight) || document.body.clientHeight;

  return [w,h];
}

function clearAllValidationErrors(jQueryObj) {
  var errorMsgElems;

  if (!jQueryObj) {
    errorMsgElems = $("#formWrapper .fieldErrorMessage");
  }
  else {
    errorMsgElems = $(jQueryObj).find(".fieldErrorMessage");
  }

  // Clear all error messages
  $(errorMsgElems).each(function() {
    childEmElems = $(this).children("em");

    if ($(childEmElems).size() > 0) {
      $(childEmElems).html("");
    }
    else {
      $(this).html("");
    }
  });

  // Hide for IE6
  $(errorMsgElems).hide();
}

function validate(fieldRuleSet, keepPrevErrors) {
  if (!keepPrevErrors) {
    clearAllValidationErrors();
  }

  return (validateFields(fieldRuleSet) == 0);
}

function setError(element, message) {
  $(element).html(message);

  if ($(element).hasClass("fieldErrorMessage")) {
    $(element).show();
  }
  else {
    var parentElem = $(element).parent();

    if ($(parentElem).hasClass("fieldErrorMessage")) {
      $(parentElem).show();
    }
  }
}

function setState(element, valid) {
  if (valid) {
    $(element).removeClass("invalid");
    $(element).addClass("valid");
  }
  else {
    $(element).removeClass("valid");
    $(element).addClass("invalid");
  }
}

function appendError(element, message) {
  if ($(element).html().indexOf(message) < 0) {
    setError(element, $(element).append(message + "<br/>").html());
  }
}

function setPhoneError(areaId, prefixId, numberId, messageId, allowBlank) {
  var re = /^\d+$/;
  var area = $("#" + areaId).val();
  var prefix = $("#" + prefixId).val();
  var number = $("#" + numberId).val();

  if (area.length == 0 && prefix.length == 0 && number.length == 0) {
    if (!allowBlank) {
      setError("#" + messageId, "Enter the phone number");
    }
  }
  else {
    if (!re.test(area) || !re.test(prefix) || !re.test(number)) {
      setError("#" + messageId, "Phone number must be 10 digits");
    }
    else {
      setError("#" + messageId, "");
    }
  }
}

function setPasswordError(id, username) {
  var field = $("#" + id);
  var errorMsg;
  var tempPassword = $(field).val().toLowerCase();
  var tempUsername = username.toLowerCase();

  if ($(field).val().length == 0) {
    errorMsg = "Enter your password";
  }
  else if ($(field).val().length < 8 || $(field).val().length > 20) {
    errorMsg = "Your password must be between 8-20 characters";
  }
  else if ($(field).val().hasSpecialChars() || (tempPassword.indexOf(" ") >= 0)) {
    errorMsg = "Your password may not contain spaces or special characters";
  }
  else if (tempUsername.length > 0 && tempPassword.indexOf(tempUsername) >= 0) {
    errorMsg = "Your password may not contain your username";
  }
  else {
    errorMsg = "Your password must contain at least one number";
  }

  return errorMsg;

}

function checkForInteger(string) {

  var hasInteger = false;

  for (var i=0; i < string.length; i++) {
    if (string.charAt(i).isInteger()) {
      hasInteger = true;
    }
  }

  return hasInteger;

}

function validateByIndex() {
  clearAllValidationErrors();

  mapRulesByIndex($("div.formSection"), fields1, validateFields);

  return $(".invalid").size() == 0;
}

function mapRulesByIndex(jqSelector, ruleSetTemplate, functionCall) {

  $(jqSelector).each(function(i) {
    var jqIndex = i + 1;
    var newRuleSet = jQuery.extend(true, {}, ruleSetTemplate); // Deep copy

    for (var ruleIndex in newRuleSet) {
      var fieldRules = newRuleSet[ruleIndex];

      // Iterate over each property and replace [index]
      for (var propertyIndex in fieldRules) {

        if ((propertyIndex == "ignore"   ||
             propertyIndex == "required" ||
             propertyIndex == "custom"   ||
             propertyIndex == "ifValid"  ||
             propertyIndex == "ifInvalid") && typeof fieldRules[propertyIndex] == "string") {
          // Create the anonymous function
          var newFunctionStr = fieldRules[propertyIndex].replace(/\[index\]/g, jqIndex);
          var newFunction = new Function(newFunctionStr);
          fieldRules[propertyIndex] = newFunction;
        }
        else if (propertyIndex == "id") {
          fieldRules[propertyIndex] = fieldRules[propertyIndex].replace(/\[index\]/g, jqIndex);
        }

      }

    }

    // For debugging
    // alert(JSON.stringify(newRuleSet));

    // Call the passed function passing in the modified template rule set
    functionCall(newRuleSet);

  });

}

function ToggleAllCheckboxes(parentId, clickedIndex) {

  // If the first checkbox is checked, uncheck the others
  if (clickedIndex == 0 && $("#" + parentId + " input:checkbox:first").attr("checked")) {
    $("#" + parentId + " input:checkbox").each(function(i) {
      if (i > 0) {
        $(this).attr("checked", false);
      }
    });
  }
  else {
    // Uncheck the first
    if ($("#" + parentId + " input:checkbox:checked").length > 1) {
      $("#" + parentId + " input:checkbox:first").attr("checked", false);
    }
  }
}

function setTextAreaError(errorMsgElem, descStr, maxLength, errorMsg) {

  if (descStr.length > maxLength) {
    setError(errorMsgElem, "Please enter " + maxLength + " characters or less");
  }
  else {
    setError(errorMsgElem, errorMsg);
  }
}

function validatePassword(password, username) {
  var tempPassword = password.toLowerCase();
  var tempUsername = username.toLowerCase();

  return ((tempUsername.length > 0) ? tempPassword.indexOf(tempUsername) < 0 : true) &&
         (tempPassword.indexOf(" ") < 0) &&
         checkForInteger(password) &&
         password.length > 0;
}

function getLoginRuleset(page) {

  var fields;

  switch (page) {

    case "signIn_1" :

      fields = [ {"id" : "username",
                  "trim" : "both",
                  "custom" : function(){return (!invalidUsername && $("#username").val().length != 0);},
                  "ifInvalid" : function(){setError('#username_Msg', ($("#username").val().length == 0) ? 'Enter your username' : 'This username doesn\'t exist. Please try again.');},
                  "classIfValid" : "valid",
                  "classIfInvalid" : "invalid"},

                 {"id" : "password",
                  "trim" : "both",
                  "custom" : function(){return (!invalidPassword && $("#password").val().length != 0);},
                  "ifInvalid" : function(){setError('#password_Msg', ($("#password").val().length == 0) ? 'Enter your password' : 'This password doesn\'t match our records. Please try again.');},
                  "classIfValid" : "valid",
                  "classIfInvalid" : "invalid"}
               ];
      break;

    default :

      fields = [ {"id" : "username",
                  "trim" : "both",
                  "custom" : function(){return (!invalidUsername && $("#username").val().length != 0);},
                  "ifInvalid" : function(){appendError('#login_Msg', ($("#username").val().length == 0) ? 'Enter your username' : 'This username doesn\'t exist. Please try again.');},
                  "classIfValid" : "valid",
                  "classIfInvalid" : "invalid"},

                 //{"id" : "password",
                 // "trim" : "both",
                 // "custom" : function(){return (!invalidPassword && $("#password").val().length != 0);},
                 // "ifInvalid" : function(){appendError('#login_Msg', ($("#password").val().length == 0) ? 'Enter your password' : 'This password doesn\'t match our records. Please try again.');},
                 // "classIfValid" : "valid",
                 // "classIfInvalid" : "invalid"}

                 {"id" : "password",
                  "trim" : "both",
                  "custom" : function(){return (!invalidPassword && $("#password").val().length != 0);},
                  "ifInvalid" : function(){ appendError('#login_Msg_pwd', ($("#password").val().length == 0) ? 'Enter your password' : 'This password doesn\'t match our records. Please try again.'); appendError('#login_Msg','&nbsp;');},
                  "classIfValid" : "valid",
                  "classIfInvalid" : "invalid"}
               ];
      break;
  }

  return fields;

}

function limitTextareaChars(jqElem, charLimit) {
  var len = $(jqElem).val().length;

  if (len >= charLimit) {
    var newValue = $(jqElem).val().substring(0, charLimit);
    $(jqElem).val(newValue);
  }
}

function confirmLogoutAlert(jqElem) {
  var rxCount = $("#cartContents").html().match(/\d+/);
  var logoutUrl = $(jqElem).attr("href");

  if (rxCount > 0) {
    if (window.top.confirm("There are prescriptions remaining in your cart. Are you sure you want to log out?")) {
      logout(targetUrl);
    }
  }
  else {
    logout(logoutUrl);
  }
}

function confirmLogout(jqElem) {
  var rxCount = $("#cartContents").html().match(/\d+/);
  var logoutUrl = $(jqElem).attr("href");

  if (rxCount > 0) {
    self.parent.tb_show('Confirm', 'logoutConfirm.htm' +
            '?t=' + escape(logoutUrl) +
            '&TB_iframe=true&height=170&width=435&modal=true');
  }
  else {
    logout(logoutUrl);
  }
}

function logout(targetUrl) {
  window.location.href = targetUrl;
}

Date.prototype.add = function(datePart, addQty) {
  var tempDate = this;

  if (datePart) {

    switch (datePart.toLowerCase()){
      case "ms":
        tempDate.setMilliseconds(tempDate.getMilliseconds() + addQty);
        break;

      case "s":
        tempDate.setSeconds(tempDate.getSeconds() + addQty);
        break;

      case "mi":
        tempDate.setMinutes(tempDate.getMinutes() + addQty);
        break;

      case "h":
        tempDate.setHours(tempDate.getHours() + addQty);
        break;

      case "d":
        tempDate.setDate(tempDate.getDate() + addQty);
        break;

      case "mo":
        tempDate.setMonth(tempDate.getMonth() + addQty);
        break;

      case "y":
        tempDate.setFullYear(tempDate.getFullYear() + addQty);
        break;
    }
  }

  return tempDate;
}

Date.prototype.format = function(delimiter, leadingZeros) {
  var tempDate = this;
  var day = tempDate.getDate()
  var month = tempDate.getMonth() + 1;
  var year = tempDate.getFullYear();

  month = (leadingZeros && month < 10) ? "0" + month : month;
  day = (leadingZeros && day < 10) ? "0" + day : day;

  return month + delimiter + day + delimiter + year;
}