/*
 * student-visa-assessment.js
 *
 * Contains the functions that are used by the student visa assessment form.
 */


// Called when the user changes their selection for English language ability.
// Shows the secondary list 'secConfirmEnglish' if the user has selected 'Native/Advanced (Excellent)'.
function enableEnglishAbility(englishList) {
    var nativeLanguage = (englishList.value == 25);
    $('secConfirmEnglish').setStyle("display", nativeLanguage ? "" : "none");
    resetColor('lblEnglish');
}

// Called when the user selects an option for whether they have studied in Australia.
function enableStudy() {
    if ($('studyinausYes').checked) {
        // Yes
        $('spanDetailsOfAustStudy').set('html', "What was the highest qualification you attained while studying in Australia?");
        $('spanDateCompletedStudy').set('html', "Please specify the date you completed your studies:");
    }
    else if ($('studyinausCurrent').checked) {
        // Currently studying
        $('spanDetailsOfAustStudy').set('html', "What is the highest qualification you will attain while studying in Australia?");
        $('spanDateCompletedStudy').set('html', "Please specify the date you expect to complete your studies:");
    }
    
    resetColor('lblStudyInAus');
}

// Called when a user changes the highest qualification that they have achieved.
function enableBachelor(qualificationList) {
    var gotBachelor = (qualificationList.value == "19" || qualificationList.value == "16");
    $('secCompleteBachelor').setStyle("display", gotBachelor ? "" : "none");
    resetColor('lblDetailsOfAustStudy');
}

// Called when a user indicates that they have studied in regional Australia.
// Makes the postcode box visible.
function enablePostcode(studiedInRegional) {
    $('secAusPostcode').setStyle("display", studiedInRegional ? "" : "none");
    resetColor('lblStudyInAustCountry');
}

// Called when the user selects an occupation.
// Enables the employment-related questions, depending on which occupation the user
// has selected, and whether they have any work experience.
function enableEmployment(industryListName, occupationList, hasWorkExperience) {
    var i = occupationList.value.indexOf("-");
    var displayWorkExperence = (i > 0 && hasWorkExperience);
    $('secEmployment').setStyle("display", displayWorkExperence ? "" : "none");
    
    if (i > 0) {
        // Display the IT Specialisation area, if the user has chosen an IT occupation.
        /*
        var industryList = $(industryListName);
        if (industryList.value == "17") {
            $('secITSpecialisation').setStyle("display", "");
        }
        else {
            $('secITSpecialisation').setStyle("display", "none");
        }
        */

        // The selected occupation should be of the form ID-Points-Bonus-SSASSL-STNI, e.g.: 12197-60-True-False-False"
        var arr = occupationList.value.split("-");
        
        var sixtyPoints = (arr[1] == "60"); // 60 point occupation
        var fourtyOrFiftyPoints = (arr[1] == "50" || arr[1] == "40") // 40/50 point occupation
        var modl = arr[2].test("true", "i"); // Bonus
        
        if (sixtyPoints && modl) {
            $('secMODLExperience1').setStyle("display", "");
            $('secNonMODL').setStyle("display", "none");
            $('sec60Points').setStyle("display", "");
            $('sec40or50Points').setStyle("display", "none");
        }
        else if (sixtyPoints) {
            $('secMODLExperience1').setStyle("display", "none");
            $('secNonMODL').setStyle("display", "");
            $('sec60Points').setStyle("display", "");
            $('sec40or50Points').setStyle("display", "none");
        }
        else if (fourtyOrFiftyPoints) {
            $('secMODLExperience1').setStyle("display", "none");
            $('secNonMODL').setStyle("display", "");
            $('sec60Points').setStyle("display", "none");
            $('sec40or50Points').setStyle("display", "");
        }
        else {
            // Elsewhere option selected.
            $('secMODLExperience1').setStyle("display", "none");
            $('secNonMODL').setStyle("display", "none");
            $('sec60Points').setStyle("display", "none");
            $('sec40or50Points').setStyle("display", "none");
        }
    }

    resetColor('lblOccupation');
}

// Called when the user selects a preferred state/territory.
function enableRegionalArea(stateList) {
    var stateName = "";
    var selected = stateList.getSelected();
    selected.each(function(s) {
        if (s.value == "NSW" || s.value == "VIC" || s.value == "WA" || s.value == "QLD") {
            stateName = s.text;
        }
    });
    
    $('stateName').set('html', stateName);
    
    if (stateName.length > 0) {
        $('secRegionalArea').setStyle("display", "");
    }
    else {
        $('secRegionalArea').setStyle("display", "none");
        $('secConsiderOtherRegional').setStyle("display", "none");
    }
}

// Called when the user selects yes/no for whether they would consider living in a
// rural region of their preferred state.
function enableConsiderOtherRegional(wouldConsiderRegional) {
    $('secConsiderOtherRegional').setStyle("display", wouldConsiderRegional ? "" : "none");
}

// Called when the user answers one of the questions relating to job experience for 60 point occupations.
// Displays the question relating to a job offer if they have indicated that they have the necessary experience.
function enableJobOffer() {
    var gotExperience = ($('modl_experience1Yes').checked || $('modl_experienceYes').checked);
    $('secMODLJobOffer').setStyle("display", gotExperience ? "" : "none");
}

// Called when the user answers the first question relating to job experience for 60 point occupations.
// Displays a couple of other questions if they answer 'no'.
function enableMODLExperience() {    
    if ($('modl_experience1No').checked) {
        $('secMODLExperience').setStyle("display", "");
        $('secMODLExperience2').setStyle("display", "");
    }
    else {
        $('secMODLExperience').setStyle("display", "none");
        $('secMODLExperience2').setStyle("display", "none");
    }
}

// Called when the user selects one of the available options for marital status.
function enableSpouse(maritalStatus) {
    resetColor('lblMaritalStatus');
    
    // Display the additional questions if they have a partner of any kind
    var displaySpouse = (maritalStatus.value == "1" || maritalStatus.value == "2" || maritalStatus.value == "5" || maritalStatus.value == "7" || maritalStatus.value == "8");
    if (displaySpouse) {
        $('secPartnerDetails').setStyle("display", "");
        $('orYourPartner1').setStyle("display", "");
        $('orYourPartner2').setStyle("display", "");
        
        // Change the questions relating to sponsorship to include the partner
        $('secPartnerSponsorship').setStyle("display", "");
        $('myRelationship').type = "radio"; // TODO: Causes an error in IE?
    }
    else {
        $('secPartnerDetails').setStyle("display", "none");
        $('orYourPartner1').setStyle("display", "none");
        $('orYourPartner2').setStyle("display", "none");
        
        // Change the questions relating to sponsorship to exclude the partner
        $('secPartnerSponsorship').setStyle("display", "none");
        $('myRelationship').type = "hidden"; // TODO: Causes an error in IE?
    }
}

// Called when the user selects whether his spouse ahs a skilled occupation.
function enableSpouseOccupation(hasSkilledOccupation) {
    if (hasSkilledOccupation) {
        $('secSpouseIndustry').setStyle("display", "");
        $('secSpouseOccupation').setStyle("display", "");
        $('secSpouseJobExperience1').setStyle("display", "");
        // $('secSpouseJobExperience2').setStyle("display", "");
        // $('secSpouseJobExperience3').setStyle("display", "");
    }
    else {
        $('secSpouseIndustry').setStyle("display", "none");
        $('secSpouseOccupation').setStyle("display", "none");
        $('secSpouseJobExperience1').setStyle("display", "none");
        // $('secSpouseJobExperience2').setStyle("display", "none");
        // $('secSpouseJobExperience3').setStyle("display", "none");
    }

    resetColor('lblSpouseHasOccupation');
}

// Called with the user has selected fluency in a second language.
function enableLanguage(isFluent) {
    $('secLanguage').setStyle("display", isFluent ? "" : "none");
}

// Called with the user has selected their second language.
function showOtherLanguage(languages) {
    if (languages.value == "300") {
        $('secOtherLanguage').setStyle("display", "");
        $('secLanguageAccreditation').setStyle("display", "none");
    }
    else if (languages.value != "") {
        $('secOtherLanguage').setStyle("display", "none");
        $('secLanguageAccreditation').setStyle("display", "");
    }
    else {
        $('secOtherLanguage').setStyle("display", "none");
        $('secLanguageAccreditation').setStyle("display", "none");
    }
}

// Makes sure that the three options for additional language accreditation don't conflict.
// Called hen the user has selected any of the options under language accreditation.
function checkLanguageAccreditation(enableLanguage) {
    if (enableLanguage) {
        $('language_none').checked = false;
    }
    else {
        $('language_degree').checked = false;
        $('NAATI').checked = false;
    }
}

// Called then the user chooses whether they have a sponsor.
function enableSponsorship(hasRelative) {
    $('secSponsorship').setStyle("display", hasRelative ? "" : "none");
    resetColor('lblHaveSponsorship');
}

// Called when the user changes their option for the intentionality question.
// Populates the key drivers section.
function populateKeyDrivers(intentionality) {
    // Show the 'other' text box if they have chosen the 'other' option.
    var other = (intentionality.value == "10");
    $('intentionality_other').setStyle("display", other ? "" : "none");

    // Call the AJAX request to get the intentionality questions if they have selected anything other
    // than the default 'Please select' option.
    if (intentionality.value != "0") {
        getKeyDrivers(intentionality.value, "keyDriversSection");
    }
    
    resetColor('lblIntentionality');
}

// Called when the user changes their choice for the key drivers.
function checkKeyDriversReason() {
    var other = false;
    
    // Get all the select boxes in the key drivers section into an element array (should only be one)
    var selects = $$($('keyDriversSection').getElementsByTagName('select'));

    // The select with the name 'txt_key_drivers' is the one we care about.
    // If we can find it, figure out whether they have selected the 'other' value.
    selects.each(function(select) {
        if (select.name == 'txt_key_drivers') other = (select.value == "12");
    });
    
    // Show/hide the key_drivers_other text box.
    $('key_drivers_other').setStyle("display", other ? "" : "none");
}

// Called when the user submits the form.
// Validate the form, check for any errors and highlight any fields that need to be filled in correctly.
function checkPointSubmit(theForm, showLogin) {
    if (showLogin) {
        if ((!theForm.title[0].checked) && (!theForm.title[1].checked) && (!theForm.title[2].checked) && (!theForm.title[3].checked) && (!theForm.title[4].checked))
            return validationError("lblTitle", "Please select your title.", theForm.title[0]);

        var nameRegex = "^[A-Za-z-'` ]+$";
        var fn = theForm.contact_firstname.value.trim();
        if (fn == "")
            return validationError("lblFirstName", "Please specify your first name.", theForm.contact_firstname);
            
        if (!fn.test(nameRegex))
            return validationError("lblFirstName", "First must be contain only valid characters (no numbers of punctuation)", theForm.contact_firstname);

        var sn = theForm.contact_surname.value.trim()
        if (sn == "")
            return validationError("lblSurname", "Please specify your last name.", theForm.contact_surname);
            
        if (!sn.test(nameRegex))
            return validationError("lblSurname", "Last must be contain only valid characters (no numbers of punctuation)", theForm.contact_surname);

        if ((!theForm.sex[0].checked) && (!theForm.sex[1].checked))
            return validationError("lblSex", "Please select your gender.", theForm.sex[0]);

        var email = theForm.email.value.trim();
        var email2 = theForm.emailConfirmation.value.trim();
        
        if (email == "")
            return validationError("lblEmail", "Please specify your email address.", theForm.email);
            
        if (!isValidEmail(email))
            return validationError("lblEmail", "Your email address does not seem to be correct.", theForm.email);

        if (email2 == "")
            return validationError("lblEmail2", "Please verify your e-mail address.", theForm.emailConfirmation);
            
        if (email != email2)
            return validationError("lblEmail2", "Your e-mail address do not match.", theForm.emailConfirmation);

        var usernameRegex = "[\\s']+";
        var login = theForm.customerLogin.value;
        
        if (login.length < 6 || login.length > 20)
            return validationError("lblUsername", "Username has to be 6 - 20 characters", theForm.customerLogin);

        if (login.test(usernameRegex))
            return validationError("lblUsername", "Login cannot have any spaces or punctuation characters", theForm.customerLogin);
        
        var password = theForm.customerPassword.value;
        var password2 = theForm.customerPasswordConfirmation.value;
        
        if (password.length < 6 || password.length > 12)
            return validationError("lblPassword", "Password has to be 6 - 12 characters", theForm.customerPassword);
            
        if (password.test(usernameRegex))
            return validationError("lblPassword", "Password can't have any spaces or the single quote (') character", theForm.customerPassword);

        if (password != password2)
            return validationError("lblPassword2", "Password and retype have to be the same", theForm.customerPasswordConfirmation);
    }

    if (theForm.dobDay.value == "0")
        return validationError("lblDOB", "Please select your date of birth.", theForm.dobDay);

    if (theForm.dobMonth.value == "0")
        return validationError("lblDOB", "Please select the month of your birthday.", theForm.dobMonth);

    if (theForm.dobYear.value == "0")
        return validationError("lblDOB", "Please select the year of your birthday.", theForm.dobYear);
        
    var maxDay;
    var month = parseInt(theForm.dobMonth.value, 10);
    if (month == 4 || month == 6 || month == 9 || month == 11)
        maxDay = 30;
    else if (month == 2)
        maxDay = 29;
    else
        maxDay = 31;
    
    if (theForm.dobDay.value > maxDay)
        return validationError("lblDOB", "Please enter a valid date of birth.", theForm.dobDay);
    
    if (theForm.nationality.value == "0")
        return validationError("", "Please select your country of citizenship.", theForm.nationality);

    if (theForm.country_id.value == "0")
        return validationError("", "Please select your country of residence.", theForm.country_id);

    if (theForm.english.value == "-1")
        return validationError("lblEnglish", "Please select your English ability", theForm.english);

    if (theForm.english.value == "25" && $('secConfirmEnglish').getStyle("display") != "none" && !theForm.confirmEnglishAbility[0].checked && !theForm.confirmEnglishAbility[1].checked)
        return validationError("lblConfirmEnglish", "Please confirm if you would be willing to undertake an English language test to gain maximum points (IELTS Level 7).", theForm.confirmEnglishAbility[0]);
    
    if (!theForm.studyinaus[0].checked && !theForm.studyinaus[1].checked)
        return validationError("lblStudyInAus", "Please specify if you have completed your studies in Australia.", theForm.studyinaus[0]);

    if (theForm.courseName.value.trim() == "")
        return validationError("lblCourseName", "Please enter your course name.", theForm.courseName);

    if (theForm.detailsofaustudy.value == "")
        return validationError("lblDetailsOfAustStudy", "Please select your Australian qualification.", theForm.detailsofaustudy);

    if (theForm.durationofstudy.value == "")
        return validationError("lblDurationOfStudy", "Please select the duration of your Australian studies.", theForm.durationofstudy);

    if (theForm.detailsofaustudy.value == "")
        return validationError("lblDetailsOfAustStudy", "Please select the level of your Australian studies.", theForm.detailsofaustudy);

    if (theForm.monthofcompletion.value == "0")
        return validationError("lblDateCompletedStudy", "Please select the month of completion of your Australian studies.", theForm.monthofcompletion);

    if (theForm.yearofcompletion.value == "0")
        return validationError("lblDateCompletedStudy", "Please select the year of completion of your Australian studies.", theForm.yearofcompletion);

    if (!theForm.studyinauscountry[0].checked && !theForm.studyinauscountry[1].checked)
        return validationError("lblStudyInAustCountry", "Please indicate whether you have studied outside the main cities in Australia.", theForm.studyinauscountry[0]);

    if (theForm.existingVisaSubclass.value == "")
        return validationError("lblExistingVisaSubclass", "Please select your existing visa type.", theForm.existingVisaSubclass);
    
    if (theForm.occupationCategory.value == "-1")
        return validationError("", "Please select your occupation category.", theForm.occupationCategory);

    var index = theForm.occupation.value.indexOf("-");
    if (index < 0)
        return validationError("lblOccupation", "Please select your occupation.", theForm.occupation);

    if (!theForm.workExperience[0].checked && !theForm.workExperience[1].checked)
        return validationError("lblWorkExperience", "Please indicate whether you have work experience.", theForm.occupation);
        
    // Other computing? (currently disabled).

    if ($('secEmployment').getStyle("display") != "none" && theForm.workExperience[0].checked) {
        // The user has indicated that they have work experience, and the work experience secondary selection is visible.

        /*        
        // The selected occupation should be of the form ID-Points-Bonus-SSASSL-STNI, e.g.: 12197-60-True-False-False"
        var arr = theForm.occupation.value.split("-");
        var points = arr[1]; // Points
        var modl = arr[2].test("true", "i"); // Bonus
         */

        // MODL checks.
        if ($('secMODLExperience1').getStyle("display") != "none" && !theForm.modl_experience1[0].checked && !theForm.modl_experience1[1].checked)
            return validationError("lblMODLExperience1", "Please specify if you have worked in this (or a closely related) occupation for 12 out of the last 24 months.", theForm.modl_experience1[0]);

        if ($('secMODLExperience').getStyle("display") != "none" && !theForm.modl_experience[0].checked && !theForm.modl_experience[1].checked)
            return validationError("secMODLExperience", "Please specify if you have worked in this (or a closely related) occupation for 12 out of the last 48 months.", theForm.modl_experience[0]);

        if ($('secMODLJobOffer').getStyle("display") != "none" && !theForm.Targeting[0].checked && !theForm.Targeting[1].checked)
            return validationError("lblMODLJobOffer", "Please specify if you have a job offer with an Australian company.", theForm.Targeting[0]);

        if ($('secMODLExperience2').getStyle("display") != "none" && !theForm.modl_experience2[0].checked && !theForm.modl_experience2[1].checked)
            return validationError("lblMODLExperience2", "Please specify if you have worked for 12 out of the last 24 months in ANY skilled occupation.", theForm.modl_experience2[0]);

        // Non-MODL check
        if ($('secNonMODL').getStyle("display") != "none" && !theForm.experience1[0].checked && !theForm.experience1[1].checked)
            return validationError("lblExperience1", "Please specify if you have worked in this occupation (or ANY other skilled occupation) for 12 out of the last 24 months.", theForm.experience1[0]);

        // 40-50 points check
        if ($('sec40or50Points').getStyle("display") != "none" && !theForm.monthsofemployment4050[0].checked && !theForm.monthsofemployment4050[1].checked)
            return validationError("lblMonthsOfEmployment", "Please specify if you have worked in this or any skilled occupation for at least 3 out of the last 4 years.", theForm.monthsofemployment4050[0]);

        // 60 points check
        if ($('sec60Points').getStyle("display") != "none" && !theForm.monthsofemployment60[0].checked && !theForm.monthsofemployment60[1].checked && !theForm.monthsofemployment60[2].checked)
            return validationError("lblMonthsOfEmployment2", "Please specify your work experience.", theForm.monthsofemployment60[0]);
    }
    
    // Regional area? (currently disabled)

    var maritalStatus = theForm.marital.value;
    if (maritalStatus == "-1")
        return validationError("lblMaritalStatus", "Please select your marital status.", theForm.marital);
    
    if ($('secPartnerDetails').getStyle("display") != "none" && (maritalStatus == "1" || maritalStatus == "2" || maritalStatus == "5" || maritalStatus == "7")) {
        // The user has indicated that they have a partner, and the secondary partner selection is visible.
        if (theForm.sAge.value == "")
            return validationError("lblSpouseAge", "Please select your partner's age.", theForm.sAge);

        if (theForm.sEnglish.value == "-1")
            return validationError("lblSpouseEnglish", "Please select your partner's english ability.", theForm.sEnglish);

        if (!theForm.sHasSkilledOccupation[0].checked && !theForm.sHasSkilledOccupation[1].checked)
            return validationError("lblSpouseHasOccupation", "Please spefify whether your partner has a skilled occupation.", theForm.sHasSkilledOccupation[0]);

        if (theForm.sHasSkilledOccupation[0].checked) {
            if ($('lblSpouseIndustry').getStyle("display") != "none" && theForm.occupationCategory2.value == "-1")
                return validationError("lblSpouseIndustry", "Please specify your partner's industry.", theForm.occupationCategory2);
            
            if ($('secSpouseOccupation').getStyle("display") != "none") {
                index = theForm.occupation2.value.indexOf("-");
                if (index < 0)
                    return validationError("lblSpouseOccupation", "Please select your partner's occupation.", theForm.occupation2);
            }

            if ($('secSpouseJobExperience1').getStyle("display") != "none" && !theForm.sExperience1[0].checked && !theForm.sExperience1[1].checked)
                return validationError("lblSpouseExperience1", "Please select your partner's experience.", theForm.sExperience1[0]);
        }
    }

    if (!theForm.have_children[0].checked && !theForm.have_children[1].checked)
        return validationError("lblHaveChildren", "Please specify if you have children.", theForm.have_children[0]);

    if (theForm.foreign_language_bonus.checked) {
        if (theForm.languages.selectedIndex == 0)
            return validationError("", "Please choose a language that your are fluent in.", theForm.languages);
            
        if (theForm.languages.value == "300" && theForm.languages_Other.value.trim() == "")
            return validationError("", "Please specify the language you are fluent in.", theForm.languages_Other);
            
        if (!theForm.language_degree.checked && !theForm.NAATI.checked && !theForm.language_none.checked)
            return validationError("", "Please check at least one of the check boxes regarding to your foreign languages skills.", theForm.foreign_language_bonus);
    }

    if (!theForm.Relationship[0].checked && !theForm.Relationship[1].checked)
        return validationError("lblHaveSponsorship", "Please select whether you have a sponsor.", theForm.Relationship[0]);

    if ($('secSponsorship').getStyle("display") != "none" && theForm.Relationship[0].checked) {
        if (theForm.sponsor_region.value == "")
            return validationError("", "Please select the region your sponsor lives.", theForm.sponsor_region);
            
        if (theForm.relativesRelationshipToYou.value == "")
            return validationError("", "Please specify your sponsor's relationship.", theForm.relativesRelationshipToYou);

        if (theForm.sponsorIsan.value == "")
            return validationError("", "Please specify the status of your sponsor.", theForm.sponsorIsan);
    }

    if (theForm.intentionality.value == "0")
        return validationError("lblIntentionality", "Please tell us how far into the immigration process you are currently.", theForm.intentionality);

    theForm.occupationHidden2.value = theForm.occupation2.value;
    theForm.occupationCategoryHidden2.value = theForm.occupationCategory2.value;
    theForm.occupationHidden.value = theForm.occupation.value;
    if (theForm.occupationCategory.value == "")
        theForm.occupationCategoryHidden.value = 0;
    else
        theForm.occupationCategoryHidden.value = theForm.occupationCategory.value;
    
    // Form validation has passed!
    return true;
}
