/**
* common.js -- javascript functions common to all identity apps
*
*/


/*
* password submit javascript -- used by migrator and manager
*/

function passwd_onload_functions()
{
    document.passwd.submitted_passwd.focus();
}



function passwd_input_check()
{
    // check answers
    if ( (document.passwd.submitted_passwd.value != document.passwd.confirm_passwd.value) )
    {
        document.getElementById("error_box").innerHTML = "The passwords you submitted don't match";
        return false;
    }
    else
    {
        ajax_check_passwd();
    }
}



function passwd_input_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            passwd_input_check();
            return false;
        }
    };
}



/*
* basic authentication javascript -- used by editor, helpdesk, etc
*/

function auth_input_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            auth_input_check();
            return false;
        }
    };
}


function auth_onload_functions()
{
    document.auth.netid.focus();

    if ( navigator.cookieEnabled == false )
    {
        alert("you'll need to enable cookie support in your browser to continue");
    }
}


function auth_input_check()
{
    if (document.auth.netid.value == "")
    {
        document.getElementById("login_message").innerHTML = "Don't forget your UCSBnetID";
        document.auth.netid.focus();
        return false;
    }
    else if (document.auth.passwd.value == "")
    {
        document.getElementById("login_message").innerHTML = "Don't forget your password";
        document.auth.passwd.focus();
        return false;
    }
    else
    {
        ajax_authenticate();
    }
}


function utf8_encode(argString)
{

    if (argString === null || typeof argString === "undefined")
    {
        return "";
    }

    var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
    start, end, stringl = 0;

    start = end = 0;
    stringl = string.length;

    for (var n = 0; n < stringl; n++)
    {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128)
        {
            end++;
        }
        else if (c1 > 127 && c1 < 2048)
        {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        }
        else
        {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }

        if (enc !== null)
        {
            if (end > start)
            {
                utftext += string.slice(start, end);
            }
            utftext += enc;
            start = end = n + 1;
        }
    }

    if (end > start)
    {
        utftext += string.slice(start, stringl);
    }

    return utftext;
}


function base64_encode(data)
{
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

    if (!data)
    {
        return data;
    }

    data = this.utf8_encode(data + '');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch (data.length % 3)
    {
        case 1:
        enc = enc.slice(0, -2) + '==';
        break;
        case 2:
        enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}



/*
* editor javascript -- used by editor, helpdesk, etc
*/

var TimeToFade = 2500.00;

function fade(eid)
{
    var element = document.getElementById(eid);
    if (element == null) return;

    if (element.FadeState == null)
    {
        if (element.style.opacity == null
        || element.style.opacity == ''
        || element.style.opacity == '1')
        {
            element.FadeState = 2;
        }
        else
        {
            element.FadeState = -2;
        }
    }

    if (element.FadeState == 1 || element.FadeState == -1)
    {
        element.FadeState = element.FadeState == 1 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
    }
    else
    {
        element.FadeState = element.FadeState == 2 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade;
        setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
    }
}



function animateFade(lastTick, eid)
{
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;
    var element = document.getElementById(eid);

    if (element.FadeTimeLeft <= elapsedTicks)
    {
        element.style.opacity = element.FadeState == 1 ? '1' : '0';
        element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '100' : '0') + ')';
        element.FadeState = element.FadeState == 1 ? 2 : -2;
        return;
    }

    element.FadeTimeLeft -= elapsedTicks;
    var newOpVal = element.FadeTimeLeft/TimeToFade;

    if (element.FadeState == 1) newOpVal = 1 - newOpVal;

    element.style.opacity = newOpVal;
    element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
    setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}



function editor_input_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            editor_input_check();
            return false;
        }
    };
}



function update_mail_pri()
{
    if (document.editor.ucsbEmailBusiness1.value == "")
    {
        return false;
    }
    else
    {
        document.getElementById("mail").innerHTML = document.editor.ucsbEmailBusiness1.value;
        document.editor.mail.value = document.editor.ucsbEmailBusiness1.value;
        return true;
    }
}



function update_mail_sec()
{
    if (document.editor.ucsbEmailBusiness2.value == "")
    {
        return false;
    }
    else
    {
        document.getElementById("mail").innerHTML = document.editor.ucsbEmailBusiness2.value;
        document.editor.mail.value = document.editor.ucsbEmailBusiness2.value;
        return true;
    }
}



function update_mail_alt()
{
    if (document.editor.ucsbEmailPersonal.value == "")
    {
        return false;
    }
    else
    {
        document.getElementById("mail").innerHTML = document.editor.ucsbEmailPersonal.value;
        document.editor.mail.value = document.editor.ucsbEmailPersonal.value;
        return true;
    }
}


function update_mail_stu()
{
    // is student email set?
    if (document.editor.ucsbEmailStudent.value == "")
    {
        // no -- add a blank value
        document.getElementById("mail").innerHTML = 'student@umail.ucsb.edu';
        document.editor.mail.value = 'student@umail.ucsb.edu';
        return true;
    }
    else
    {
        // yes. use the real value
        document.getElementById("mail").innerHTML = document.editor.ucsbEmailStudent.value;
        document.editor.mail.value = document.editor.ucsbEmailStudent.value;
        return true;
    }
}


function validate_email_address(submitted_address)
{
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if (reg.test(submitted_address) == false)
    {
        return false;
    }
    else
    {
        return true;
    }
}




function editor_input_check()
{
    var has_errors = 0;

    // is mail set?
    if (document.editor.mail.value == "")
    {
        // no.
        has_errors = 1;
        document.getElementById("error_box").innerHTML  = "At minimum please set your UCSB E-Mail Address";
        document.getElementById("error_mail").innerHTML = "&bull;";
        document.editor.mail.focus();
    }
    else
    {
        // yes. check it
        if ( ! validate_email_address(document.editor.mail.value) )
        {
            has_errors = 1;
            document.getElementById("error_box").innerHTML  = "Make sure to provide a valid E-Mail Address";
            document.getElementById("error_mail").innerHTML = "&bull;";
        }
    }


    if ( has_errors == 0)
    {
        document.editor.submit();
    }
    else
    {
        return false;
    }
}



/**
* ajax_authenticate - send authentication keys to php db_authenticate
*
*/
function ajax_authenticate()
{
    var netid         = document.auth.netid.value;
    var passwd        = document.auth.passwd.value;

    // escape any special characters in password with base64
    base64_passwd = base64_encode(passwd);

    x_db_authenticate(netid,base64_passwd,ajax_authenticate_callback);
}



/**
* ajax_authenticate_callback - handle return value from ajax_authenticate
*
* @param string auth_return
*/
function ajax_authenticate_callback(auth_return)
{
    // what did db_authenticate return?
    if (auth_return == false)
    {
        // null -- failure

        document.auth.netid.value = "";
        document.auth.passwd.value = "";
        document.auth.netid.focus();
        document.getElementById("login_message").innerHTML = "Invalid UCSBnetID and Password";

    }
    else if (auth_return == "empty")
    {
        // unmigrated netid -- failure
        document.auth.netid.value = "";
        document.auth.passwd.value = "";
        document.auth.netid.focus();
        document.getElementById("login_message").innerHTML = "Please <a target=\"_new\" href=\"https://secure.identity.ucsb.edu/migrator/\">migrate your identity</a> before logging in to our new service";
    }
    else
    {
        // campusid -- success
        document.login.login_token.value = auth_return;
        document.login.submit();
    }
}



/**
* ajax_check_passwd - check password strength
*
*/
function ajax_check_passwd()
{
    sajax_request_type = "POST";

    var campusid         = document.getElementById("campusid").value;
    var submitted_passwd = document.passwd.submitted_passwd.value;

    var digit_regex      = /[0-9]+/;
    var lower_regex      = /[a-z]+/;
    var upper_regex      = /[A-Z]+/;
    var whitespace_regex = /\s+/;

    // check the passwd syntax
    if ( submitted_passwd.length < 8)
    {
        document.getElementById("error_box").innerHTML = "your new password must be at least 8 characters in length";
        return(false);
    }

    if ( ! digit_regex.test(submitted_passwd) )
    {
        document.getElementById("error_box").innerHTML = "your new password must contain at least one digit";
        return(false);
    }

    if ( ! upper_regex.test(submitted_passwd) )
    {
        document.getElementById("error_box").innerHTML = "your new password must contain at least one uppercase letter";
        return(false);
    }

    if ( ! lower_regex.test(submitted_passwd) )
    {
        document.getElementById("error_box").innerHTML = "your new password must contain at least one lowercase letter";
        return(false);
    }

    if ( whitespace_regex.test(submitted_passwd) )
    {
        document.getElementById("error_box").innerHTML = "your new password may not contain the [space] character";
        return(false);
    }

    // now run the php check_passwd_strength function
    x_check_passwd_strength(submitted_passwd, ajax_check_passwd_callback);
}



/**
* ajax_check_passwd_callback - handle the return value of check_passwd_strength
*
* @param boolean strong_enough
*/
function ajax_check_passwd_callback(strong_enough)
{
    if (strong_enough)
    {
        document.passwd.submit();
    }
    else
    {
        document.getElementById("error_box").innerHTML = 'your new password may not be based on a word we can find in our dictionary';
    }
}




/*
* account intro javascript -- used by manager & migrator
*/


function account_intro_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            account_intro_input_check();
            return false;
        }
    };
}



function account_intro_input_check()
{
    // no inputs to check
    document.account_intro.submit();
}



/*
* select entry javascript -- used by helpdesk & editor
*/

function select_entry_input_check()
{
    // loop through radio boxes to see if one was checked
    for (var i=0; i < document.select_entry.selected_entry.length; i++)
    {
        if ( document.select_entry.selected_entry[i].checked )
        {
            var checked = document.select_entry.selected_entry[i].value;
        }
    }

    // was a radio box checked?
    if (checked == null)
    {
        // no
        document.getElementById("error_box").innerHTML = "make sure to select an entry to edit";
        return false;
    }
    else
    {
        // yes
        return true;
    }
}



/*
* secret questions javascript -- used by migrator & manager
*/

function questions_onload_functions()
{
    document.questions.answer1.focus();
}



function questions_submit_keytrap(e)
{
    var keyPressed;

    if (document.layers)
    {
        keyPressed = String.fromCharCode(e.which);
    }
    else if (document.all)
    {
        keyPressed = String.fromCharCode(window.event.keyCode);
    }
    else if (document.getElementById)
    {
        keyPressed = String.fromCharCode(e.keyCode);
    }

    if (keyPressed == "\r" || keyPressed == "\n")
    {
        questions_input_check();
    }
}



function questions_input_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            questions_input_check();
            return false;
        }
    };
}



function questions_input_check()
{
    // check answers
    if ( (document.questions.answer1.value == "")
    || (document.questions.answer2.value == "")
    || (document.questions.answer3.value == "")
    || (document.questions.answer4.value == "")
    || (document.questions.answer5.value == "") )
    {
        document.getElementById("error_box").innerHTML = "Make sure to provide an answer to each question before continuing";
        return false;
    }
    else
    {
        document.questions.submit();
    }
}



/**
* ajax_log_handler - send a message to log_handler
*
* @param string $message
*/
function ajax_log_handler(message)
{
    x_log_handler(message, 0, ajax_log_handler_callback);
}



/**
* ajax_log_handler_callback - handle log_handler return value
*
*/
function ajax_log_handler_callback()
{
    // do nothing
}


/*
* netid selection javascript
*/


function netid_select_input_submit_event(input)
{
    input.onkeydown = function(e)
    {
        e = e || window.event;

        if (e.keyCode == 13)
        {
            netid_select_input_check();
            return false;
        }
    };
}



function netid_select_input_check()
{
    var is_checked = false;

    for (var i=0; i < document.netid_select.selected_netid.length; i++)
    {
        if ( document.netid_select.selected_netid[i].checked )
        {
            is_checked = true;
        }
    }

    if (is_checked)
    {
        ajax_check_netid();
    }
    else
    {
        document.getElementById("error_box").innerHTML = "Make sure to select a UCSBnetID before continuing";

        // is the custom_netid errorbox displayed
        if ( document.getElementById("custom_netid_error_box") )
        {
            // blank it just in case
            document.getElementById("custom_netid_error_box").innerHTML = '';
        }

        return false;
    }
}



// unset the custom netid radio group
function netid_select_radio_onclick()
{
    if ( document.custom_netid )
    {
        if ( document.custom_netid.selected_netid.value == "on" )
        {
            document.custom_netid.selected_netid.checked = false;
        }
    }
}



function custom_netid_input_check()
{
    // blank the main error box
    document.getElementById("error_box").innerHTML = '';

    // what does the form look like?
    if ( document.custom_netid.selected_netid.value != "on" )
    {
        // radio button isn't clicked
        document.getElementById("custom_netid_error_box").innerHTML = "Make sure to select a UCSBnetID before continuing";
        return false;
    }
    else if ( document.custom_netid.custom_netid.value == "" )
    {
        // text field is empty
        document.getElementById("custom_netid_error_box").innerHTML = "Your UCSBnetID must contain a mix of lowercase letters, digits, and underscores only";
        return false;
    }
    else
    {
        // we have a checked button & a netid string -- validate it
        ajax_check_netid();
        return true;
    }
}



// unset the preset netid radio group and set the custom netid textbox focus
function custom_netid_radio_onclick()
{

    for (var i=0; i < document.netid_select.selected_netid.length; i++)
    {
        if ( document.netid_select.selected_netid[i].checked )
        {
            document.netid_select.selected_netid[i].checked = false;
        }
    }

    document.custom_netid.custom_netid.focus();
}



// set the custom netid radio group
function custom_netid_text_onclick()
{
    document.custom_netid.selected_netid.checked = true;
    custom_netid_radio_onclick();
}

/**
* ajax_check_netid - check password strength
*
*/
function ajax_check_netid()
{
    sajax_request_type = "POST";

    var submitted_netid;
    var campusid         = document.getElementById("campusid").value;

    // loop through the radio group
    for (var i=0; i < document.netid_select.selected_netid.length; i++)
    {
        // is this element checked?
        if ( document.netid_select.selected_netid[i].checked )
        {
            // set the submitted netid
            submitted_netid = document.netid_select.selected_netid[i].value;
        }
    }

    // was a preselected netid checked?
    if ( submitted_netid == null )
    {
        // no. it was a custom one
        var netid_type      = "custom_netid";
        var submitted_netid = document.getElementById("custom_netid").value
    }
    else
    {
        // yes.
        var netid_type      = "netid_select"
    }

    x_check_candidate_netid(campusid, submitted_netid, netid_type, ajax_check_netid_callback);
}



/**
* ajax_check_netid_callback - handle the return value of check_candidate_netid
*
* @param string json_error_array
*/
function ajax_check_netid_callback(json_result_array)
{
    result_array = JSON.parse(json_result_array);
    netid_type   = result_array[0];
    error_array  = result_array[1];

    var form_submit;
    var error_display;
    var error_string  = '';
    var i;

    // which form did we submit from?
    if (netid_type == "netid_select")
    {
        // preselected netid
        error_display     = document.getElementById("error_box");
        alt_error_display = document.getElementById("custom_netid_error_box");
        form_submit       = document.netid_select;
    }
    else
    {
        // custom netid
        error_display     = document.getElementById("custom_netid_error_box");
        alt_error_display = document.getElementById("error_box");
        form_submit       = document.custom_netid;
    }

    // was there an netid validation error?
    if (error_array)
    {

        // yes. loop through the error array and
        for (i in error_array)
        {
            error_string = error_array[i] + "<br>" + error_string;

        }

        // display the error
        error_display.innerHTML = error_string;

        // does the alternate error display element exist?
        if (alt_error_display)
        {
            // yes. blank it just in case something is there
            alt_error_display.innerHTML = '';
        }
    }
    else
    {
        // no. submit the form
        form_submit.submit();
    }
}

function noenter()
{
  return !(window.event && window.event.keyCode == 13);
}

function select_qualification_input_check()
{
    if (document.auth.netid.value == "")
    {
        document.getElementById("login_message").innerHTML = "Don't forget your UCSBnetID";
        document.auth.netid.focus();
        return false;
    }
    else if (document.auth.passwd.value == "")
    {
        document.getElementById("login_message").innerHTML = "Don't forget your password";
        document.auth.passwd.focus();
        return false;
    }
    else
    {
        ajax_authenticate();
    }
}

function select_qualification_input_check()
{
    var qualification_checked;

    // loop through radio boxes to see if one was checked
    for(i=0; i<document.select_qualifications.qualification.length; i++)
    {
        if ( document.select_qualifications.qualification[i].checked )
        {
            var qualification_checked = document.select_qualifications.qualification[i].value;
        }
    }


    if (!qualification_checked)
    {
        // radio button isn't clicked
        document.getElementById("qualification_error_box").innerHTML = "you didn't specify the reason for your request";
        return false;
    }
    else if (document.select_qualifications.qualification_desc.value == "")
    {
        document.getElementById("qualification_error_box").innerHTML = "make sure to provide a description of your situation";
        document.select_qualifications.qualification_desc.focus();
        return false;
    }
    else
    {
        document.select_qualifications.submit();
        return true;
    }
}

function validate_date(date_string)
{
    regex = /^\d{2}\/\d{2}\/\d{4}$/;

    if ( date_string != '' && date_string.match(regex) )
    {
        return false;
    }
    else
    {
        return true;
    }
}
