/* Check the form values */
function checkEntry(evt){
    var theForm = yui.get('student_ins');
    if(!evt) evt = window.event; // Make sure we've got the event properly
    
    // The field names to check
    var arrInput = new Array('Studying', 'Staying', 'Halls', 'SharedUni', 'Year');
    // Reset everything
    resetAlerts(arrInput);
    resetMessageAlerts(arrInput);
    hideit('errorBoxMain');
    
    // First check part time cover, display pop-up
    var partTimeSelect = yui.get("Course");
    if(yui.isObject(partTimeSelect) && yui.isObject(endsleighPopups.Course)) {
        if(partTimeSelect.options[partTimeSelect.selectedIndex].value == 'CoursePart') {
            endsleighPopups.Course.custom.showPopup();
            // Stop the form submitting
            lib.cancelEvent(evt);
            return false;
        } else {
            endsleighPopups.Course.custom.hidePopup();
        }
    }
    
    //document.getElementById('boxError').style.visibility = 'hidden';	
    var arrErrors = new Array();
    var alertString = ''
    var errorFlag = 0;
    
    // Popup should be happening if part time (see si_tooltips.js), so cancel
    if(this.Course.value == 'CoursePart') {lib.cancelEvent(evt)}
    
    for (i=0; i < arrInput.length; i++){
        formName = arrInput[i];
        
        if (isVisible(theForm.elements[formName].parentNode) // It's visible within the form
            && theForm.elements[formName].value=='') { // And it's empty
            
            if(formName == 'HallsSelector' && document.forms['student_ins']['Halls'].value == 'not listed') continue;
            if(formName == 'SharedSelector' && document.forms['student_ins']['Halls'].value == 'not listed') continue;
            
            arrErrors[arrErrors.length] = arrInput[i] + '_error';
            arrErrors[arrErrors.length] = arrInput[i] + '_err_mess';
            errorFlag++;
        }
    }
    
    // Extras
    if(document.forms.student_ins.StudyingSelector.disabled == false && document.forms.student_ins.StudyingSelector.value == '') {
        arrErrors[arrErrors.length] = 'Studying_error';
        arrErrors[arrErrors.length] = 'Studying_err_mess';
        errorFlag++;
    } else if(document.forms.student_ins.HallsSelector.disabled == false && isVisible(document.forms.student_ins.HallsSelector.parentNode) && document.forms.student_ins.HallsSelector.value == '') {
        arrErrors[arrErrors.length] = 'Halls_error';
        arrErrors[arrErrors.length] = 'Halls_err_mess';
        errorFlag++;
    } else if(document.forms.student_ins.SharedUniSelector.disabled == false && isVisible(document.forms.student_ins.SharedUniSelector.parentNode) && document.forms.student_ins.SharedUniSelector.value == '') {
        arrErrors[arrErrors.length] = 'SharedUni_error';
        arrErrors[arrErrors.length] = 'SharedUni_err_mess';
        errorFlag++;
    }
              
    if (errorFlag > 0) {
        showit('errorBoxMain');
        //document.getElementById('boxError').style.visibility = 'visible';	
        showErrors(arrErrors);
        // Stop the form submitting
        lib.cancelEvent(evt);
        return false;
    } else return true; // Allow the form to submit
}

lib.verbose = true; // Set the TamarLibrary verbose option to see all errors and log notes

/* Show the Ajax error message */
function showAjaxMessage() {
    yui.removeClass('less_than_ie6','showIE5only');
    window.location.hash = 'boxTop';
    return false;
}



var uniSearchableBox;

/* Now we set everything up */
window.addListener('load',
    function(evt) { // Function to execute when page loads - basically contains everything
        // Reset the form
        document.forms.student_ins.reset();
        
        // Set up the uni searchable box
        uniSearchableBox = new searchableBox('studyingSearch');
        
        /*// Populate unis
        var enableSubmit = {
            success: function () {return yui.get('student_possessions_submit').disabled = false},
            failure: showAjaxMessage
        }
        var uniSearchableBox = new searchableBox('studyingSearch','/scripts/student-insurance.cgi?action=get_unis','uni_id','uni_desc',enableSubmit);*/
        
        // "Where will you be staying" functionality
        // If "In halls of residence (on or off campus)" is selected, checks with server if there are any halls, if so, populate new search box.
        // If "In a shared house provided by university/college" or "In a shared property provided by Kexgill or Club Easy" is selected, do the same for shared accomodation
        function displayHallsShared() {
            var uniId = lib.getFieldValue(uniSearchableBox.visibleSelect);
            var stayingValue = lib.getFieldValue('Staying');
            // If staying in halls
            if(stayingValue == 'StayingHalls') {
                var hallsSearchableBox;
                var hallsCallBack = {
                    success: function() {
                        if(hallsSearchableBox.selectAll.options.length > 0) {showit('hallsSearch');}
                        else {hideit('hallsSearch')}
                    },
                    failure: showAjaxMessage
                }
                hallsSearchableBox = new searchableBox('hallsSearch','/scripts/student-insurance.cgi?action=find_property_for_uni;property_type=halls;uni_id=' + uniId,'prop_id','prop_address',hallsCallBack);
            } else {hideit('hallsSearch')}
            
            if(stayingValue.match(/^StayingSharedUni|StayingSharedKexgill$/)) {
                var sharedSearchableBox;
                var sharedCallBack = {
                    success: function() {
                        if(sharedSearchableBox.selectAll.options.length > 0) {showit('sharedSearch');}
                        else {hideit('sharedSearch')}
                    },
                    failure: showAjaxMessage
                }
                sharedSearchableBox = new searchableBox('sharedSearch','/scripts/student-insurance.cgi?action=find_property_for_uni;property_type=shared;uni_id=' + uniId,'prop_id','prop_address',sharedCallBack);
            } else {hideit('sharedSearch')}
        }
        
        // Do "displayHallsShared" on change
        yui.get("Staying").addListener('change',displayHallsShared);
        
        // Test every 1/10 second for uniSearchableBox to add the listener
        window.addSharedListenerInterval = window.setInterval(
            function() {
                if(yui.isObject(uniSearchableBox)) {
                    uniSearchableBox.visibleSelect.addListener('change',displayHallsShared);
                    window.clearInterval(window.addSharedListenerInterval);
                }
            }
            ,100
        );
        // Give up after 5 seconds
        window.setTimeout(function() {window.clearInterval(window.addSharedListenerInterval);},5000);
        
        
        // submit image rollover
        yui.get('student_possessions_submit').addHoverClass('hover');
        
        // set up the form check entry
        yui.get('student_ins').addListener('submit',checkEntry);
        
        // Focus on the first input box
        document.getElementById("Studying").focus();
        
        // Enable the submit button
        yui.get('student_possessions_submit').disabled = false
    }
);
