﻿/*** Logon Form ***/
var $ui_logonControlPrefix = "";

function InitializeLogonFormControl() {
  if (typeof (logonControlPrefix) != "undefined")
    $ui_logonControlPrefix = logonControlPrefix;

  if ($("#" + $ui_logonControlPrefix + "logonUsername") == "undefined")
    return;

  $("#" + $ui_logonControlPrefix + "logonUsername").oneTime(500, "checkLogonIsNotEmpty", function() {
    if ($("#" + $ui_logonControlPrefix + "logonUsername").val())
      $("#" + $ui_logonControlPrefix + "lblLogonUsername").hide("fast");
  });

  $("#" + $ui_logonControlPrefix + "logonUsername").bind('focus', function(event) {
    $("#" + $ui_logonControlPrefix + "lblLogonUsername").hide("fast");
  });

  $("#" + $ui_logonControlPrefix + "logonUsername").bind('blur', function(event) {
    if (!$("#" + $ui_logonControlPrefix + "logonUsername").val())
      $("#" + $ui_logonControlPrefix + "lblLogonUsername").show("fast");
  });

  $("#" + $ui_logonControlPrefix + "logonPassword").bind('focus', function(event) {
    $("#" + $ui_logonControlPrefix + "lblLogonPassword").hide("fast");
  });

  $("#" + $ui_logonControlPrefix + "logonPassword").bind('blur', function(event) {
    if (!$("#" + $ui_logonControlPrefix + "logonPassword").val())
      $("#" + $ui_logonControlPrefix + "lblLogonPassword").show("fast");
  });

  $("#" + $ui_logonControlPrefix + "btnLogonSubmit").live('click', function(event) {
    event.preventDefault();
    ValidateLogonForm(event);
  });

  $("#" + $ui_logonControlPrefix + "logonUsername").bind('keypress', function(event) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (code == 13) { //Enter keycode
      event.preventDefault();
      ValidateLogonForm(event);
    }
  });

  $("#" + $ui_logonControlPrefix + "logonPassword").bind('keypress', function(event) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (code == 13) { //Enter keycode
      event.preventDefault();
      ValidateLogonForm(event);
    }
  });

  if ($("#" + $ui_logonControlPrefix + "btnLogonClose").html() !== null) {
    $("#" + $ui_logonControlPrefix + "btnLogonClose").live('click', function(event) {
      event.preventDefault();
      ResetLogonForm();
      LogonForm_Close(event);
    });
    $("#" + $ui_logonControlPrefix + "btnLogonClose").live('keypress', function(event) {
      event.preventDefault();
      ResetLogonForm();
      LogonForm_Close(event);
    });
  }
  if ($("#isFailedLogOn").val() == "1") {
    // show error, there was an attempt to log on that failed...
    ShowErrorMessage();
  }
}

// Prepare the links for other languages popups
$(document).ready(function() {
  $.each($(".alLink"), function(index, value) {
    $(value).click(function(event) {
      event.preventDefault();
      // get the language
      var lang = this.title;

      // get the logo url - logo should be displayed as anthembc always when on anthem - so this should be default
      var logoUrl = "/ols/images/common/logo_anthem_bc.png";

      // get the visual role - from hidden field on page (cookie is not available client side when the page loads first!)
      var visualRole = $("#ctl00_hdnVisualRole").length > 0 ? $("#ctl00_hdnVisualRole").val() : $("#hdnVisualRole").val();

      // set the brand
      var brand = visualRole;

      // map the visual role to appropriate brand for anthem
      if (visualRole == "anthembcbs" || visualRole == "anthembc") {
        brand = "abcbs";
      }

      // if the visual role is unicare - only change logo for unicare. For all other brands logo should be anthem bc logo
      if (visualRole == "unicare") {
        logoUrl = "/ols/images/common/logo_unicare.png";
      }

      var headerHtml = jQuery.format("<img src=\"/ols/images/common/altlanguage/{0}_{1}_header.png\" alt=\"Language Information {1}\" />", brand, lang);
      var spacerHtml = "<div style=\"clear:both;padding-top:15px;\" />";
      var printHtml = jQuery.format("<img src=\"/ols/images/common/altlanguage/{0}_{1}_print.png\" onClick=\"javascript:PrintWindow();\" alt=\"Print Logo {1}\" style=\"float:right;padding-right:50px;cursor:hand;cursor:pointer\" />", brand, lang);
      var logoHtml = visualRole == "anthembc" ? jQuery.format('<img src="{0}" alt="Company Logo {1}" />', logoUrl, brand) : '';
      var dialogHtml = jQuery.format(
          '<div>{2}{3}{4}{3}<img src="/ols/images/common/altlanguage/{0}_{1}_text.png" alt="{1}" />{3}{4}{3}</div>',
          brand,
          lang,
          logoHtml,
          spacerHtml,
          printHtml);

      // set up the html for the language div
      // display the language modal
      DisplayGenericModal(dialogHtml, headerHtml, null, '700px', { height: 500, buttons: null });
    });
  });
});

/* Print the browser window */
function PrintWindow() {
  window.print();
  return false;
}

// *** Validate Form fuction is called prior to submitting the form (to WCF service)
function ValidateLogonForm(event) {

  var errors = false;

  var username = $("#" + $ui_logonControlPrefix + "logonUsername").val();
  if (!username) {
    errors = true;
  }
  if (!errors && String(username).length < 6) {
    errors = true;
  }

  if (!errors) {
    var password = $("#" + $ui_logonControlPrefix + "logonPassword").val();
    if (!password) {
      errors = true;
    }
    if (!errors && String(password).length < 8) {
      errors = true;
    }
  }

  if (!errors) {
    $("#" + $ui_logonControlPrefix + "lblLogonError").hide("fast");
    SubmitLogonForm();
  } else {
    ShowErrorMessage();
  }
}

// *** Create a variable to store end point for the service (i.e. method name)
var logonServiceEndPoint = "LogonService.asmx/Logon";

// *** This function reset the form
function ResetLogonForm() {
  $("#" + $ui_logonControlPrefix + "logonUsername").val("");
  $("#" + $ui_logonControlPrefix + "logonPassword").val("");

  $("#" + $ui_logonControlPrefix + "lblLogonUsername").show("fast");
  $("#" + $ui_logonControlPrefix + "lblLogonPassword").show("fast");

  $("#" + $ui_logonControlPrefix + "lblLogonError").hide("fast");
}

// *** This function is used to post the logon info
function SubmitLogonForm() {

  AjaxWorkingStart($("#divLogonForm"), "Logon in Progress...");

  var secureHostname = $("#secureUrlScheme").val() + "://" + $("#secureHostname").val();

  $("#aspnetForm").validate().settings.rules = {};
  $("#aspnetForm").validate().settings.submitHandler = null;
  $("#aspnetForm").attr("action", secureHostname + "/ols/LogonHandler.hndlr");
  $("#aspnetForm").attr("method", "post");
  $("#aspnetForm").submit();
}

// *** This function builds the JSON to invoke the service
function BuildLogonFormRequestObject() {
  // get the input form field values
  var username = $("#" + $ui_logonControlPrefix + "logonUsername").val();
  var password = $("#" + $ui_logonControlPrefix + "logonPassword").val();

  // build the search criteria
  var requestObject = '{ "username" : "' + username + '", "password" : "' + password + '" }';
  return requestObject;
}

function ShowErrorMessage(m) {
  // show error message
  var logonErrorMsg = $("#" + $ui_logonControlPrefix + "lblLogonErrorMsg").html();
  if (m !== undefined) {
    switch (parseInt(m.Result.InvalidAttemps, 10)) {
      case 3: logonErrorMsg = $("#" + $ui_logonControlPrefix + "LOGONTHIRDATTEMPT").html(); break;
      case 6: logonErrorMsg = $("#" + $ui_logonControlPrefix + "LOGONSIXTHATTEMPT").html(); break;
      default: logonErrorMsg = $("#" + $ui_logonControlPrefix + "lblLogonErrorMsg").html(); break;
    }
  }
  $("#" + $ui_logonControlPrefix + "lblLogonErrorMsg").html("<span id='" + $ui_logonControlPrefix + "lblLogonErrorMsg'>" + logonErrorMsg + "</span>");
  $("#" + $ui_logonControlPrefix + "lblLogonError").removeClass("hide");
  $("#" + $ui_logonControlPrefix + "lblLogonError").show("fast");
}

function HideLogonFormControl() {
  // hide login inputs
  $("#divLogonForm").addClass("hide");
}

function ShowLogonFormControl() {
  // hide login inputs
  $("#divLogonForm").removeClass("hide");
}



/*** Logon Box ***/
/*
Initialize the logon box control that stays in the top right side of the screen
*/
function InitializeLogonBoxControl() {
  // Check if logged on, then decided what to show, so both controls start hidden
  InitializeLogonFormControl();
  InitializeLogonInfoControl(false);
  HideLogonFormControl();
  HideLogonInfoControl();

  GetProfileIdentityContext(OnSuccessGetIdentityContextForLogonBox);
}

/*
Call back for the GetIdentityContext when called from the InitializeLogonBoxControl
*/
function OnSuccessGetIdentityContextForLogonBox(result) {

  // if user is logged on, only show welcome box
  // other wise show logon form
  var identityContext = JSON.parse(result);
  if (identityContext.Credentials.IsLoggedOn) {
    ShowWelcomeBox(identityContext.Profile);
    if (identityContext.IsAgent) {
      pageobserver.fire('{ "messagetype" : "HideHomePageActionControl" }');
    }
  }
  else {
    ShowLogonFormControl();
  }
}



/*** Logon Info ***/
var ctrl = "";

// *** Add event handlers registration here
//$(document).ready(InitializeLogonInfoControl);

var IsLogonInfoInPopupMode = true;
function InitializeLogonInfoControl(callGetIdentityContext) {

  var hasToCallGetIdentityContext = true;
  if (typeof (callGetIdentityContext) != "undefined")
    hasToCallGetIdentityContext = callGetIdentityContext;

  if (typeof ($("#divWelcomeBox")) == "undefined")
    return;

  $("#lnkSignOut").click(function(event) {
    event.preventDefault();
    ConfirmLogoff();
  });

  if (hasToCallGetIdentityContext) {
    AjaxWorkingStart($("#divLogonForm"), "");
    GetProfileIdentityContext(OnSuccessGetIdentityContext);
  } else {
    // we are not in pop up mode so, this will be handy to logout
    IsLogonInfoInPopupMode = false;
  }
}

function ConfirmLogoff() {
  var logOffMessage = "Thank you for using our website. This window will close in 10 seconds and log you out of our website.<br /><br />If you would like to continue using the website, click Cancel, return to site button.";

  $dialog = $('#dialog').html(logOffMessage).dialog({
    draggable: false,
    modal: true,
    position: 'center',
    dialogClass: 'olsmodal',
    title: 'You have chosen to log out',
    buttons: {
      "Logout": function() {
        CallLogoff(OnSuccessLogoff);
        $('#dialog').dialog("close");
      },
      "Cancel, return to site": function() {
        $('#dialog').dialog("close");
      }
    }
  });


  setTimeout(function() {
    if ($('#dialog').dialog("isOpen") === true) {
      CallLogoff(OnSuccessLogoff);
      $('#dialog').dialog("close");
    }
  },
   10000);

  $dialog.dialog("open");
}

function CallLogoff(callBackFn) {

  CallWCFModel('POST', "LogonService.asmx/Logoff", "{}", callBackFn);
}

function GetProfileIdentityContext(callBackFn) {
  //alert("GetProfileIdentityContext, callBackFn -> " + callBackFn);
  CallWCFModel('POST', "LogonService.asmx/GetProfileIdentityContext", "{}", callBackFn);
}

function OnSuccessGetIdentityContext(result) {
  var identityContext = JSON.parse(result);

  if (identityContext.Credentials.IsLoggedOn) {
    ShowWelcomeBox(identityContext.Profile);
  }
  else {
    ShowAnonymousBox();
  }
  AjaxWorkingDone($("#divLogonForm"));
}

function OnSuccessLogoff(result) {

  if (IsLogonInfoInPopupMode) {
    ShowAnonymousBox();
  } else {
    HideLogonInfoControl();
    ShowLogonFormControl();
  }
  var publicHostName = "http://" + $("#publicHostname").val();
  document.location.href = publicHostName + $("#logountRedirectUrl").val();
}

function ShowWelcomeBox(userProfile) {
  // prepare infor and show welcome box
  $("#lblMemberName").text(capitaliseFirstLetter(userProfile.FirstName));
  $("#lblLastVisit").text(userProfile.LastLogin);
  $("#divWelcomeBox").removeClass("hide");
  HideAnonymousBox();
}

function capitaliseFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}


function ShowAnonymousBox(userProfile) {
  $("#divAnonymousBox").removeClass("hide");
  HideWelcomeBox();
}

function HideLogonInfoControl() {
  HideWelcomeBox();
  HideAnonymousBox();
}

function HideWelcomeBox() {
  $("#divWelcomeBox").addClass("hide");
}

function HideAnonymousBox() {
  $("#divAnonymousBox").addClass("hide");
}

