/*
 * assessment.js
 *
 * Contains the common functions that are used be assessment forms.
 */


// Opens a popup window.
function windowOpen(name, width, height, href, scroll) {
    var w = window.open(href, name, "scrollbars=" + scroll + ",width=" + width + ",height=" + height + ",top=0,left=0,screenX=0,screenY=0");
    if (!w.opener)
        w.opener = self;
    return false;
}

// Highlights the colour on a label (i.e. turns it red when there is an error on the page).
function highlightColor(labelName) {
    var label = $(labelName);
    if (label) {
        label.setStyle("color", "#F00");
        // label.setStyle("font-weight", "bold");
    }
}

// Resets the colour on a label (which may be turned red when there is an error on the page).
function resetColor(labelName) {
    var label = $(labelName);
    if (label) {
        label.setStyle("color", "#000");
        // label.setStyle("font-weight", "normal");
    }
}

// Validation error.
// Highlights the incorrect field, displays an error message and set focus on the incorrect field.
function validationError(labelName, message, input) {
    if (labelName != "")
        highlightColor(labelName);
    alert(message);
    input.focus();
    return false;
}

// Checks the string provided, returns true if it is a valid email address.
function isValidEmail(email) {
    // Apparently, this regex is good for 99.9% of email addresses out there in cyberspace.
    var emailRegex = /^[_\w\.\-]+@([\w\.-]+\.)+[a-zA-Z]{2,6}$/;
    return email.test(emailRegex);
}

// Check for duplicate email once the user navigates off the email input field.
// Use AJAX to call validateemail.asp.
function validateEmail(email) {
    email = email.trim();
    if (email == "") {
        alert("Please specify your email address.");
        return false;  // blank email, stop processing
    }
    if (!isValidEmail(email)) {
        alert("Please specify a valid email address. (" + email + ")");
        return false;  // invalid email, stop processing
    }

    // Format the query string
    var firstname = $('contact_firstname').value;
    var surname = $('contact_surname').value;
    var qs = "email=" + escape(email) + "&contact_firstname=" + escape(firstname) + "&contact_surname=" + escape(surname);

    document.body.style.cursor = 'wait';

    // Send the AJAX request, emailRequestComplete() will be called on completion.
    var ajaxRequest = new Request({ method: 'get', url: "/validateemail.asp", noCache: true, onSuccess: emailRequestComplete, onFailure: emailRequestFailure });
    ajaxRequest.send(qs);

    document.body.style.cursor = 'auto';

    return true;
}

// Callback for when the AJAX request to validate the email address has successfully completed.
function emailRequestComplete(responseText, responseXML) {
    if (responseText == "exists") {
        // alert("Email address already exists. Please try a different email address, or log in with your existing account.");
        $('duplicateEmail').setStyle("display", "");
        $('duplicateEmailSameUser').setStyle("display", "none");
    }
    else if (responseText == "exists_same_user") {
        // alert("You have already created an account. Please log in with your existing username.");
        $('duplicateEmail').setStyle("display", "none");
        $('duplicateEmailSameUser').setStyle("display", "");
    }
    else {
        // All Good!
        $('duplicateEmail').setStyle("display", "none");
        $('duplicateEmailSameUser').setStyle("display", "none");
    }
}

// Callback for when the AJAX request to validate the email address has failed.
function emailRequestFailure(request) {
    // Do nothing, I guess? Or: alert(...);
}

// Check for duplicate username once the login input text is out of focus.
// Use AJAX to call validatelogin.asp.
function validateLogin(username) {
    username = username.trim();
    if (username == "") {
        alert("Please specify a username.");
        return false;  // blank username, stop processing
    }

    // Format the query string
    var firstname = $('contact_firstname').value;
    var surname = $('contact_surname').value;
    var qs = "login=" + escape(username) + "&contact_firstname=" + escape(firstname) + "&contact_surname=" + escape(surname);

    document.body.style.cursor = 'wait';

    // Send the AJAX request, loginRequestComplete() will be called on completion.
    var ajaxRequest = new Request({ method: 'get', url: "/validatelogin.asp", noCache: true, onSuccess: loginRequestComplete, onFailure: loginRequestFailure });
    ajaxRequest.send(qs);

    document.body.style.cursor = 'auto';

    return true;
}

// Callback for when the AJAX request to validate the login has successfully completed.
function loginRequestComplete(responseText, responseXML) {
    if (responseText == "exists") {
        // alert("Username already exists.");
        $('duplicateLogin').setStyle("display", "");
        $('duplicateLoginSameUser').setStyle("display", "none");
    }
    else if (responseText == "exists_same_user") {
        // alert("You have already created an account.");
        $('duplicateLogin').setStyle("display", "none");
        $('duplicateLoginSameUser').setStyle("display", "");
    }
    else {
        // All Good!
        $('duplicateLogin').setStyle("display", "none");
        $('duplicateLoginSameUser').setStyle("display", "none");
    }
}

// Callback for when the AJAX request to validate the login has failed.
function loginRequestFailure(request) {
    // Do nothing, I guess? Or: alert(...);
}

// Used by the function getKeyDrivers()
var keyDriversSection;

// Gets the key drivers HTML.
// Use an AJAX request to call getKeyDrivers.asp
function getKeyDrivers(intentionality, section) {
    keyDriversSection = section;
    var qs = "q=" + intentionality;

    document.body.style.cursor = 'wait';

    var ajaxRequest = new Request({
        method: 'get',
        url: "/onlineassessments/include/getKeyDrivers.asp",
        noCache: true,
        onSuccess: keyDriversComplete
    });

    ajaxRequest.send(qs);

    document.body.style.cursor = 'auto';
}

// Callback for when the AJAX request to get key drivers has successfully completed.
function keyDriversComplete(responseText, responseXML) {
    $(keyDriversSection).set("html", responseText);
}

// Called with a new value is selected from an industry list.
// Populates the occupation list with all the occupations that belong to the industry.
function populateOccupations(industryList, occupationListName) {
    var occupationList = $(occupationListName);
    var points = 0;

    // Clear the occupation list
    if (occupationList.options) {
        occupationList.options.length = 0;
    }

    // Find the selected industry in the var containing all industries.
    industries.each(function(industry) {
        if (industry.industryID == industryList.value) {
            // Does the occupation list include a "not elsewhere classified" option?
            var elsewhere = false;

            // Add all the occupations for this industry as options.
            industry.occupations.each(function(occupation) {
                if (points != occupation.points) {
                    // Add the header (e.g. 60 point occupations) with blue background
                    points = occupation.points;
                    var option = new Element("option");
                    option.setStyle("background-color", "#9BD9F9");
                    option.value = "";
                    option.text = points.toString() + " point occupations";
                    occupationList.options.add(option);
                }

                // Add the occupation to the list of options
                var option = new Element("option");
                option.value = occupationToOptionValue(occupation);
                option.text = occupation.description;
                occupationList.options.add(option);

                // Update our "elsewhere" boolean - set to true if the text contains "elsewhere"
                elsewhere |= occupation.description.test("elsewhere", "i");
            });

            // Add the "elsewhere" option (if not included in the occupation list.
            if (!elsewhere) {
                var option = new Element("option");
                option.setStyle("background-color", "#FF8BFF");
                option.value = "11668-0-False-False-False";
                option.text = "My occupation is not listed here";
                occupationList.options.add(option);
            }
        }
    });
}

// Converts an occupation into the value used in a dropdown list.
// Format: ID-Points-Bonus-SSASSL-STNI
// e.g.: "12197-60-True-False-False"
function occupationToOptionValue(occ) {
    return occ.occupationID.toString() + "-" + occ.points.toString() + "-" + occ.bonus.toString().capitalize() + "-" + occ.SSASSL.toString().capitalize() + "-" + occ.STNI.toString().capitalize();
}
