﻿
var methodNames = ["DoLoginJSON", "DoAdminLoginJSON", "SendMailJSON", "ValidateJSON", "PasswordQuestionsJSON", "ChangePasswordJSON", "CheckNewUserJSON", "RegisterJSON"];
var PasswordQuestionType = "";
var ScrollDownTimeout;

function goElseWhere() {
  
    if (window.location.protocol == "http:") {
        var oldURL = window.location.hostname + window.location.pathname;
        var newURL = "https://" + oldURL;    
        window.location = newURL;
    }
}
goElseWhere();


// This function creates an asynchronous call to the service
function makeCall(operation) {
  
    // Create HTTP request
    var xmlHttp;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            DisplayInfoMessage("This sample only works in browsers with AJAX support");
                return false;
            }
        }
    }

    // Create result handler
    xmlHttp.onreadystatechange = function () {

        if (xmlHttp.readyState == 4) {
            //alert(xmlHttp.responseText)
            var result = xmlHttp.responseText;


            if (result == "") {
                DisplayInfoMessage("Internet connectivity problem occured.");
                return;
            }

            var fault = HasFault(result);

            if (fault != null) {
                DisplayInfoMessage(fault);
            }
            else {
                // no problem go ahead
                var action = findAction(result);

                CleanErrorMessage();

                if (action != null) {
                    // action is OK

                    switch (action) {
                        case "RedirectAfterNewUser":
                            document.location.href = findRedirect(result);
                            break;
                        case "RedirectAfterQuestion":
                            document.location.href = findRedirect(result);
                            break;
                        case "RedirectAfterRegistration":
                            DisplayInfoMessage(findJSONResponse(result, "UserData"));
                            HideOtherForms("trUserData");
                            break;
                        case "PasswordQuestions":
                            //which form to load change password or new user
                            var newUser = findNewUser(result);

                            if (newUser == "NewUser") {
                                //new user
                                ShowNewUser();
                                PopulatePasswordQuestions(result, "SelectSeqQuestionsConfirm");
                            }
                            else {
                                HideOtherForms("trChangePassword");
                                PopulatePasswordQuestions(result, "SelectSeqQuestions");

                                if (GetSelectedRadio() != 4) {
                                    document.getElementById("trSecurityQuestion").style.display =
                                document.getElementById("trSecurityAnswer").style.display = "none";
                                }
                            }
                            break;
                        case "RedirectToStrategy":
                            document.location.href = findRedirect(result);
                            break;
                        case "AdminRedirect":                   
                            document.location.href = findRedirect(result);
                            break;
                        case "Redirect":
                            var mustChangePassword = findMustChangePassword(result);

                            //user must change password
                            if (mustChangePassword) {
                                PasswordQuestionType = "ChangePassword";
                                makeCall("PasswordQuestionsJSON");
                                return;
                            }
                            else {
                                //strategy project show security answer
                                if (GetSelectedRadio() == 4) {

                                    // new user sec question
                                    var newUser = findNewUser(result);
                                    if (newUser == null || newUser == "null") {

                                        PasswordQuestionType = "NewUser";
                                        makeCall("PasswordQuestionsJSON");
                                    }
                                    else {
                                        ShowSecurityQuestion(result);
                                        HideOtherForms("tdAnsweDialog");
                                        var securityAnswer = document.getElementById("securityAnswer");
                                        var trForgetSec = document.getElementById("trForgetSec");

                                        trForgetSec.style.display = "block";

                                        securityAnswer.focus();
                                    }
                                }
                                else {
                                    document.location.href = findRedirect(result);
                                }
                            }
                            break;
                        case "MailSent":
                            SwitchStyleDisplay('trUserData', true, 'trUserData', GetSelectedRadio());
                            DisplayInfoMessage(findJSONResponse(result, "UserData"));
                            break;
                        default:
                            DisplayInfoMessage("No action is specified for" + action);
                            break;
                    }
                }
            }
        }
    }

    // Build the operation URL
    var url = "/LoginWCF/Login.svc/ajaxEndpoint/";
    url = url + operation;
  
    var bodyMsg='';
    switch (operation) {
        case "DoLoginJSON":
            bodyMsg = GetDoLoginJSONBody();
            break;
        case "DoAdminLoginJSON":
            bodyMsg = GetDoAdminLoginJSONBody();
            break;
        case "PasswordQuestionsJSON":
            bodyMsg = GetPasswordQuestionsJSONBody();
            break;        
        case "ChangePasswordJSON":
            bodyMsg = GetChangePasswordJSONBody();
            break;
        case "CheckNewUserJSON":
            bodyMsg = GetCheckNewUserJSONBody();
            break;                       
        case "RegisterJSON":
            bodyMsg = GetRegisterJSONBody();
            break;
        case "SendMailJSON":
            bodyMsg = GetSendMailJSONBody();
            break;
        case "ValidateJSON":
            bodyMsg = GetValidateJSONBody();         
            break;
        default:    
            DisplayInfoMessage("No operation is specified for - " + operation);
            break;
    }

    // Send the HTTP request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    //alert(body);
    xmlHttp.send(bodyMsg);

}

function GetDoLoginJSONBody() {

    var body = '{"userName":"';
    body = body + document.getElementById("username").value + '","password":"';
    body = body + document.getElementById("password").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';

    return body;
}

function GetDoAdminLoginJSONBody() {

    var body = '{"userName":"';
    body = body + document.getElementById("username").value + '","password":"';
    body = body + document.getElementById("password").value + '"}';

    return body;
}

function GetPasswordQuestionsJSONBody() {

    var body = '{"type":"';
    body = body + PasswordQuestionType + '","action":"';
    body = body + GetSelectedRadio() + '"}';    

    return body;
}

function GetCheckNewUserJSONBody() {

    var SelectSeqQuestions = document.getElementById("SelectSeqQuestionsConfirm");
    var selQuestion = SelectSeqQuestions.value;

    if (SelectSeqQuestions.value == "Other Question") {
        selQuestion = document.getElementById("SelectCustomQuestionsConfirm").value;
    }
    
    var body = '{"userName":"';
    body = body + document.getElementById("username").value + '","password":"';
    body = body + document.getElementById("password").value + '","newPassword":"';
    body = body + document.getElementById("txtNewSecPassword").value + '","question":"';
    body = body + selQuestion + '","answer":"';
    body = body + document.getElementById("txtSecAnswerConfirm").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';
    
    return body;
}

function GetChangePasswordJSONBody() {

    var SelectSeqQuestions = document.getElementById("SelectSeqQuestions");
    var selQuestion = SelectSeqQuestions.value;

    if (SelectSeqQuestions.value == "Other Question") {
        selQuestion = document.getElementById("SelectCustomQuestions").value;
    }    

    var body = '{"userName":"';
    body = body + document.getElementById("username").value + '","password":"';
    body = body + document.getElementById("password").value + '","newPassword":"';
    body = body + document.getElementById("txtNewSecPassword").value + '","question":"';
    body = body + selQuestion + '","answer":"';
    body = body + document.getElementById("txtSecAnswer").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';

    return body;
}

function GetRegisterJSONBody() {

    var body = '{"companyCode":"';
    body = body + document.getElementById("regCompanyCode").value + '","firstName":"';
    body = body + document.getElementById("regFirstName").value + '","lastName":"';
    body = body + document.getElementById("regLastName").value + '","gender":"';
    body = body + document.getElementById("regGender").value + '","ageRange":"';
    body = body + document.getElementById("regAgeRange").value + '","email":"';
    body = body + document.getElementById("regEmail").value + '","password":"';
    body = body + document.getElementById("regPassword").value + '","confirmPassword":"';
    body = body + document.getElementById("regConfirmPassword").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';
 
    return body;
}

function GetSendMailJSONBody() {

    var body = '{"userName":"';
    body = body + document.getElementById("forgotPassword").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';

    return body;
}

function GetValidateJSONBody() {
    var body = '{"userName":"';
    body = body + document.getElementById("username").value + '","password":"';
    body = body + document.getElementById("password").value + '","securityAnswer":"';
    body = body + document.getElementById("securityAnswer").value + '","action":"';
    body = body + GetSelectedRadio() + '"}';

    return body;
}

function findJSONResponse(result, field) {
    var JSON = "var Result = " + result  
    eval(JSON);

    for (var i = 0; i < methodNames.length; i++) {

        var JsonObject = eval("Result." + methodNames[i] + "Result");

        if (JsonObject != null) {   
            return eval("Result." + methodNames[i] + "Result." + field);
        }
    }
}

function HasFault(result) {
    return findJSONResponse(result, "Fault");
}

function findAction(result) {
    return findJSONResponse(result, "ResultAction");
}

function findMustChangePassword(result) {
    return findJSONResponse(result, "MustChangePassword");
}

function findNewUser(result) {
    return findJSONResponse(result, "UserData");
}

function findRedirect(result) {
    return findJSONResponse(result, "Redirect");
}

function GetSelectedRadio() {

    for (var i = 1; i < 6; i++) {
        var radio = document.getElementById("Radio" + i);

        if (radio.checked) {
            return radio.value;
        }
    }
}

//----------------------------

//method calls

//Admin Login

function AdminLogin()
{
    SwitchInputType(false);

    var fields = [];

    var obj = {};
    obj['DisplayName'] = 'Login ID';
    obj['Value'] = document.getElementById("username");
    fields[0] = obj;

    var obj = {};
    obj['DisplayName'] = 'Password';
    obj['Value'] = document.getElementById("password");
    fields[1] = obj;

    if (CheckForEmptyBatch(fields)) {
        Set_Cookie('LoginName', document.getElementById("username").value, 30, '/', '', '');

        return makeCall('DoAdminLoginJSON');
    }
}

function Login() {

    SwitchInputType(false);
    
    var fields = [];

    var obj = {};
    obj['DisplayName'] = 'Login ID';
    obj['Value'] = document.getElementById("username");
    fields[0] = obj;

    var obj = {};
    obj['DisplayName'] = 'Password';
    obj['Value'] = document.getElementById("password");
    fields[1] = obj;

    if (CheckForEmptyBatch(fields)) {
        Set_Cookie('LoginName', document.getElementById("username").value, 30, '/', '', '');   

        return makeCall('DoLoginJSON');
    }
}

function Register() {

    var fields = [];

    var obj = {};
    obj['DisplayName'] = 'Company Code';
    obj['Value'] = document.getElementById("regCompanyCode").value;
    fields[0] = obj;

    var obj = {};
    obj['DisplayName'] = 'First Name';
    obj['Value'] = document.getElementById("regFirstName").value;
    fields[1] = obj;

    var obj = {};
    obj['DisplayName'] = 'Last Name';
    obj['Value'] = document.getElementById("regLastName").value;
    fields[2] = obj;

    var obj = {};
    obj['DisplayName'] = 'Gender';
    obj['Value'] = document.getElementById("regGender").value;
    fields[3] = obj;

    var obj = {};
    obj['DisplayName'] = 'Age Range';
    obj['Value'] = document.getElementById("regAgeRange").value;
    fields[4] = obj;

    var obj = {};
    obj['DisplayName'] = 'Email';
    obj['Value'] = document.getElementById("regEmail").value;
    fields[5] = obj;

    var obj = {};
    obj['DisplayName'] = 'Password';
    obj['Value'] = document.getElementById("regPassword").value;
    fields[6] = obj;

    var obj = {};
    obj['DisplayName'] = 'Confirm Password';
    obj['Value'] = document.getElementById("regConfirmPassword").value;
    fields[7] = obj;

    if (CheckForEmptyBatch(fields)) {

        //Check Password and Confirm Password
        if (fields[6].Value != fields[7].Value) {
          
            DisplayInfoMessage("Password and Confirm Password do not match");
        }
        else 
        {                     
            if (!ValidateEmail(fields[5].Value)) {
                DisplayInfoMessage("Invalid Email address");          
            }
            else {
                DisplayInfoMessage("");
                makeCall('RegisterJSON');
            }    
        }
    }

}

function SendEmail() {
  
    var fields = [];

    var obj = {};
    obj['DisplayName'] = 'Forgot Password';
    obj['Value'] = document.getElementById("forgotPassword");
    fields[0] = obj;

    if (CheckForEmptyBatch(fields)) {    
        makeCall('SendMailJSON');
    }
}

function ValidateSecurityAnswer() {
  
    
    var fields = [];

    var obj = {};
    obj['DisplayName'] = 'Security Answer';
    obj['Value'] = document.getElementById("tdAnsweDialog");
    fields[0] = obj;

    if (CheckForEmptyBatch(fields)) {    
        makeCall('ValidateJSON');
    }
}

function CheckNewUser() {

    var fields = [];


    var SelectSeqQuestions = document.getElementById("SelectSeqQuestions");

    if (SelectSeqQuestions.value == "Other Question") {
        var obj = {};
       
        obj['DisplayName'] = 'Custom Questions';
        obj['Value'] = document.getElementById("SelectCustomQuestionsConfirm").value; 
        fields[0] = obj;
    }
    else {
        var obj = {};
        obj['DisplayName'] = 'Security Questions';
        obj['Value'] = document.getElementById("SelectSeqQuestionsConfirm").value;
        fields[0] = obj;
    }
  
    var obj = {};
    obj['DisplayName'] = 'Security Answer';
    obj['Value'] = document.getElementById("txtSecAnswerConfirm").value;
    fields[1] = obj;

    if (CheckForEmptyBatch(fields)) {
       makeCall('CheckNewUserJSON');        
    }
}

function ChangePassword() {
 
    var fields = [];
   
    var obj = {};
    obj['DisplayName'] = 'New Password';
    obj['Value'] = document.getElementById("txtNewSecPassword").value;
    fields[0] = obj;

    var obj = {};
    obj['DisplayName'] = 'Confirm Password';
    obj['Value'] = document.getElementById("txtSecConfirmPassword").value;
    fields[1] = obj;

    if (GetSelectedRadio() == 4) {
    
        var SelectSeqQuestions = document.getElementById("SelectSeqQuestions");

        if (SelectSeqQuestions.value == "Other Question") {
            var obj = {};
            obj['DisplayName'] = 'Custom Questions';
            obj['Value'] = document.getElementById("SelectCustomQuestions").value;   
            fields[2] = obj;
        }
        else {
            var obj = {};
            obj['DisplayName'] = 'Security Questions';
            obj['Value'] = document.getElementById("SelectSeqQuestions").value;
            fields[2] = obj;
        }

        var obj = {};
        obj['DisplayName'] = 'Security Answer';
        obj['Value'] = document.getElementById("txtSecAnswer").value;
        fields[3] = obj;
    }
    
    if (CheckForEmptyBatch(fields)) {

        //Check Password and Confirm Password
        if (fields[0].Value != fields[1].Value) {       
            DisplayInfoMessage("Password and Confirm Password do not match");        
        }
        else {
            makeCall('ChangePasswordJSON');
        }
    }    
}

//end method calls

function SwitchStyleDisplay(id, display, formId, index) {

    if (id == "trRegisterData") {
        ClearRegistrationForm();
    }
    
    ShowRegLink(index);
    CleanErrorMessage();
   
    //check if diabled on the first tr for firefox
    var trChk = document.getElementById("trRadio1");
   
    if (trChk.disabled) { return; }
     
    var el = document.getElementById(formId); 
    HideOtherForms(id);

    (display == true) ? el.style.display = "block" : el.style.display = "none";

    if (typeof (index) != "undefined") {

        var password = document.getElementById('password');

        if (password != null && password.value == "") {         
            SwitchInputType(false);
        }
        SetRadioSelection(index, true);
    }
}

function ShowRegLink(index) {

    var el = document.getElementById("spanReg");

    if (el != null) {
        (index == 3) ? el.style.display = "block" : el.style.display = "none";
    }
}


function SetRadioSelection(radioId, value) {

    var element = document.getElementById("Radio" + radioId);

    if (element != null) {
        element.checked = value;
        Custom.pushed(element)
        Custom.clear;
    }
}

//Clear Watermark
function Watermark(id, defaultValue, state) {
    var el = document.getElementById(id);

    //clear watermark
    if (state) {

        if (id == "username") {
            SwitchInputType(false);
        }

        if (el.value == defaultValue) {
            el.value = "";
        }
    }
    else {
        if (el.value == "") {
            el.value = defaultValue;
        }
    }
}

function SwitchInputType(state) {

    var password = document.getElementById('password');
    var passwordWaterMark = document.getElementById('passwordWaterMark');

    if (state) {
        password.style.display = 'block';
        password.value = "";
        passwordWaterMark.style.display = 'none';
        password.focus();
    }
    else {
        if (password.value == "Password" || password.value == "") {
            password.style.display = 'none';
            passwordWaterMark.style.display = 'block';
            passwordWaterMark.value = "Password";
        }
    }
}

// Only Make Visible form with passed Id
function HideOtherForms(id) {

    ClearInputValues();

    var formsIDs = ["trUserData", "trForgotPassword", "tdAnsweDialog", "trChangePassword", "trRegisterData", "trConfirm", "trForgetSec"];

    for (var i = 0; i < formsIDs.length; i++) {
        var currentEl = document.getElementById(formsIDs[i]);

        if (currentEl != null) {
            if (formsIDs[i] == id) {
                var showEl = document.getElementById(id);
                if (showEl != null) {
                    showEl.style.display = "block";
                }
            }
            else {
                currentEl.style.display = "none";
            }
        }
    }
}



function ClearRegistrationForm() {
    var formsIDs = ["regCompanyCode", "regFirstName", "regLastName", "regEmail", "password", "password", "regGender", "regAgeRange"];
   
    for (var i = 0; i < formsIDs.length; i++) {
        var currentEl = document.getElementById(formsIDs[i]);

        if (currentEl != null) {           
            currentEl.value = "";            
        }
    }

    ScrollDownTimeout = setTimeout("scrollDown()", 100);    
}

function scrollDown() {

    window.scrollBy(0, 100);

    if (ScrollDownTimeout != null) {  
    clearTimeout(ScrollDownTimeout);
    }
}

function SwitchSecQiestions(trId, selId, el) {

    var trCustomQuestion = document.getElementById(trId);

    var SelectSeqQuestions = document.getElementById(selId);

    
    if (SelectSeqQuestions.value == "Other Question") {
        document.getElementById(el).style.display = "block";
    }
    else {
        document.getElementById(el).style.display = "none";
    }

}


function ClearInputValues() {
    var inputIDs = ["forgotPassword", "passwordWaterMark",
"securityAnswer", "txtNewSecPassword", "txtSecConfirmPassword", "txtSecAnswer"];

    for (var i = 0; i < inputIDs.length; i++) {

        var currentEl = document.getElementById(inputIDs[i]);

        if (currentEl != null) {
            if (currentEl.value == "Login ID" || currentEl.value == "Password") {
                continue;
            }
            currentEl.value = "";
        }
    }
}

function ShowNewUser() {
    var trConfirm = document.getElementById("trConfirm");
    trConfirm.style.display = "block"
    HideOtherForms("trConfirm");
}

// pupulate options for Password Questions
function PopulatePasswordQuestions(result, id) {
    var passwordsList = findJSONResponse(result, "PasswordQuestionsList");

    var selectSeqQuestions = document.getElementById(id);

    if (selectSeqQuestions != null) {
        selectSeqQuestions.options[0] = new Option("Select", "");

        for (var i = 1; i < passwordsList.length; i++) {
            selectSeqQuestions.options[i] = new Option
(
passwordsList[i].PasswordQuestion1, passwordsList[i].PasswordQuestion1
);
        }

        selectSeqQuestions.options[passwordsList.length] = new Option("Other Question", "Other Question");

    }
}

function ShowSecurityQuestion(result) {

    var seqQuestion = findJSONResponse(result, "UserData");
    var divSeqQuestion = document.getElementById("divSeqQuestion");
    var spanSeqQuestion = document.getElementById("spanSeqQuestion");
    spanSeqQuestion.innerHTML = seqQuestion;
    divSeqQuestion.style.display = "block";
}

//check for empty batch
function CheckForEmptyBatch(fieldsAsJSON) {

    var errors = "";

    for (i = 0; i < fieldsAsJSON.length; i++) {
        var displayName = fieldsAsJSON[i].DisplayName;
        var value = fieldsAsJSON[i].Value;

        if (value == "") {
            errors += displayName + " is empty<br />";
        }
    }

    if (errors != "") {
        DisplayInfoMessage(errors);
        return false;
    }

    return true;
}

function LoginEnterKey(e) {

    if (GetKey(e) == 13) {
        Login();
    }
}

function ForgotPasswordEnterKey(e) {

    if (GetKey(e) == 13) {
        SendEmail();
    }
}

function ChangePasswordEnterKey(e) {
    if (GetKey(e) == 13) {
        ChangePassword();
    }
}

function AnswerEnterKey(e) {
    if (GetKey(e) == 13) {
        ValidateSecurityAnswer();
    }
}

function GetKey(e) {

var key;
if (window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox

return key;
}

function DisableRadioButtons() {

    for (var i = 1; i < 6; i++) {
        var radio = document.getElementById("trRadio" + i);
        radio.disabled = "disabled";
    }
}

function DisplayInfoMessage(message) {

var error = document.getElementById("error");
error.innerHTML = message + "<br />";
}

function CleanErrorMessage() {
var error = document.getElementById("error").innerHTML = "";
}

function ValidateEmail(email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email) == false) {     
return false;
}
return true;
}




function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}

