/**
 * Validate Field [jQuery]
 *
 * Intelligently checks a form field to make sure either a selection has
 * been made or a value entered (as appropriate to the field type).
 *
 * Last modified: 2009-01-22 {pf}
 *
 */

function validateField(field) {
    
    switch ( field.attr('type') ) {
        
        case 'select':
        case 'select-one':
            if ( !field.val() ) {
                return false;
            }
            break;
        
        case 'checkbox':
        case 'radio':
            if ( field.hasClass('requiredGroup') ) {
                var groupChecked = false;
                var fieldset = $(field).parents('fieldset')[0];
                $('input.requiredGroup', fieldset).each ( function() {
                    if ( $(this).attr('checked') ) {
                        groupChecked = true;
                    }
                });
                return groupChecked;
            }
            else if ( !field.attr('checked') ) {
                return false;
            }
            break;
        
        case 'password':
            // not currently testing or comparing passwords in JS, so treated as...
        default: // text
            if ( field.hasClass('validateEmail') ) {
                var emailPattern = new RegExp(/^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
                if ( field.val().match(emailPattern) === null ) {
                    return false;
                }
            }
            else if ( !field.val() ) {
                return false;
            }
        
    }
    
    return true;
    
}


/**
 * Check Requireds [jQuery]
 *
 * Alerts the user to any 'required' inputs, in the target form, which
 * have not been completed.
 *
 * Last modified: 2009-01-22 {pf}
 */
function checkRequireds(thisForm) {
    
    var validated = false;
    
    //  Failure counter
    var failed = 0;
    
    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required', thisForm).each( function () {
        
        var fieldValid = validateField($(this));
        
        if ( !fieldValid ) {
            
            failed++;
            
            //  Highlight error
            if ( $(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio' ) {
                $(this).parent().addClass('error');
            }
            else if ( !$(this).parent().hasClass('error') ) {
                $(this).wrap('<div class="error"></div>');
            }
            
        }
        else {
            
            //  Remove error highlight (if present)
            $(this).parent().removeClass('error');
            
        }
        
    });
    
    if (failed > 0) {
        
        if ( $('div.alert', thisForm).length < 1 ) {
            //  Requires 'reqWarn' HTML string (compiled in head of actual HTML document)
            thisForm.prepend(reqWarn);
        }
        
    }
    else if (failed == 0) {
        
        validated = true;
        
    }
    
    return validated;
    
}

/**
 * Find Requireds [jQuery]
 *
 * Automatically scans the page for forms, then adds an 'onsubmit'
 * function to any forms which contain input elements classed as
 * 'required'.
 *
 * Last modified: 2009-08-14 {pf}
 */

function findRequireds() {
    
    $('.formWrapper').each( function() {
        var thisForm = $(this);
        if ( $(':input.required', thisForm) ) {
            $(':submit', thisForm).click( function() {
                return checkRequireds(thisForm);
            });
        }
    });

}

// Bind form validation when DOM ready [uses jQuery]
$(document).ready( function() {
    if ( $(':input.required').length > 0 ) {
        findRequireds();
    }
});


/**
 *  Find Externals [jQuery]
 *  Finds all 'rel="external"' anchors on a page and automatically
 *  makes those open in a new window, without harming accessibility.
 *  Last modified: 2009-02-11 {pf}
 */

function findExternals() {
    $('a[rel="external"]').each( function() {
        if ( $(this).attr('title') && $(this).attr('title').length > 0 ) {
            $(this).attr('title', ( $(this).attr('title') + ' [opens in a new window]' ) );
        }
        else {
            $(this).attr('title', 'Opens in a new window');
        }
        $(this).click( function() {
            window.open($(this).attr('href'));
            return false;
        });
    });
    
}

$(document).ready( function() {
   findExternals(); 
});


/**
 *  Course Cost Calculator
 *  If the user has JS enabled, this will allow them to use the course
 *  cost calculator without needing to reload the page.
 *  Last modified: 2009-08-14 {pf}
 */

$(document).ready( function() {
    if ( $('#costCalculator.formWrapper').length > 0 ) {
        setupCostCalculator();
    }
});


/**
 *  Setup Cost Calculator
 *  Initial viewstate and function bindings for the Course Cost
 *  Calculator, including reading data and disabling controls.
 *  Last modified: 2009-08-19 {pf}
 */

function setupCostCalculator() {
    
    var costForm = $('#costCalculator.formWrapper');
    
    toggleUniversityOptions(costForm);
    
    //  Remove the submits needed for the server-side fallback
    $(':submit', costForm).each( function() {
        $(this).remove();
    });
    
    //  Disable the "Apply now" button (hyperlink) at the bottom
    $('a.button', costForm).click( function() {
        return false;
    });
    
    //  Strip all existing options from dropdowns
    $('select option', costForm).remove();
    
    //  Add default empty prompt option to "University"
    $('.selectUniversity').append('<option value="0" selected="selected">' + costData.selectText + '</option>');
    
    //  Setup university options
    $.each(costData.universities, function(i, university) {
        $('.selectUniversity').append('<option value="' + university.guid + '">' + university.name + '</option>');
    });
    
    //  Bind feedback funtions
    $('.selectUniversity').change( function() {
        changeUniversityOptions(costForm);
    });
    $('.selectCourse').change( function() {
        updateCost('#courseCost', '.selectCourse');
    });
    $('.selectTransfer').change( function() {
        updateCost('#transferCost', '.selectTransfer');
    });
    
}


/**
 *  Update Cost
 *  Simple effects-based function to update the on-screen cost for each
 *  option (when selected).
 *  Last modified: 2009-08-20 {pf}
 */
function updateCost(target, input) {
    $(target).hide();
    $(target).html( $(input).val() );
    $(target).fadeIn( 450, updateTotal() );
}


/**
 *  Update Total
 *  Simple addition function that totals the Course and Transfer values
 *  and displays this on-screen.
 *  Last modified: 2009-08-20 {pf}
 */
function updateTotal() {
    var total = parseInt($('.selectCourse').val()) + parseInt($('.selectTransfer').val());
    $('#totalCost').hide();
    $('#totalCost').html(total);
    $('#totalCost').fadeIn(450);
}


/**
 *  Change University Options
 *  Populates the course and transfer options based on the university
 *  selected.
 *  Last modified: 2009-08-19 {pf}
 */
function changeUniversityOptions(costForm) {
    
    //  Enable/disable university options as appropriate to university chosen
    toggleUniversityOptions(costForm);
    
    //  Clear out existing course and transfer options
    $('.selectCourse option').remove();
    $('.selectTransfer option').remove();
    
    //  Reset cost numbers
    $('#courseCost').html('0');
    $('#transferCost').html('0');
    $('#totalCost').html('0');
    
    if ( $('.selectUniversity').val() !== 0 ) {
        
        //  Add default prompt option to course and transfers
        $('.selectCourse').append('<option value="0" selected="selected">' + costData.selectText + '</option>');
        $('.selectTransfer').append('<option value="0" selected="selected">' + costData.transferText + '</option>');
        
        $.each(costData.universities, function(i, university) {
            
            if ( university.guid !== 0 && university.guid == $('.selectUniversity').val() ) {
                
                //  Add courses
                $.each(university.courses, function(i, course) {
                    $('.selectCourse').append('<option value="' + course.cost + '">' + course.name + '</option>');
                });
                
                //  Add transfers
                $.each(university.transfers, function(i, transfer) {
                    $('.selectTransfer').append('<option value="' + transfer.cost + '">' + transfer.name + '</option>');
                });
                
            }
            
        });
        
    }
    
}


/**
 *  Toggle University Options
 *  Simplistic utility function that just either disables or enables
 *  the various dropdowns under each university, depending on the
 *  on the numeric value passed.
 *  Last modified: 2009-08-19 {pf}
 */
function toggleUniversityOptions(costForm) {
    
    if ( $('.selectUniversity').val() != 0 ) {
        
        //  Enable course and transfer rows (inc. controls)
        $('tr.disabled select', costForm).each( function() {
            $(this).attr('disabled', false);
        });
        $('tr#course', costForm).removeClass('disabled');
        $('tr#transfer', costForm).removeClass('disabled');
        $('tr#total', costForm).removeClass('disabled');
        $('tr#apply', costForm).removeClass('disabled');
        //  Set currency
        $.each(costData.universities, function(i, university) {
            if ( university.guid != 0 && university.guid == $('.selectUniversity').val() ) {
                $('span.currency', costForm).html(university.currency);
            }
        });
        
    }
    else if ( $('.selectUniversity').val() == 0 ) {
        
        //  Disable course and transfer rows initially (inc. controls)
        $('tr#course', costForm).addClass('disabled');
        $('tr#transfer', costForm).addClass('disabled');
        $('tr#total', costForm).addClass('disabled');
        $('tr#apply', costForm).addClass('disabled');
        $('tr.disabled :input', costForm).each( function() {
            $(this).attr('disabled', true);
        });
        
    }
    
}


/**
 *  Language Modal Window
 *  Opens a custom modal window, using the jqModal plugin:
 *  http://dev.iceburg.net/jquery/jqModal/
 *  Last modified: 2009-08-28 {pf}
 */


//  Global language cookie details
var cookieName = 'language';

function cookieLanguage() {
    
    if ( $.cookie(cookieName) == null && $.cookie(cookieName) != false ) {
        changeLanguage();
    }
    
}

function cookieSessionOnly() {
    
    $.cookie(cookieName, false);
    
}

function changeLanguage() {
    $('#changeLanguage').jqmShow();// reveal modal window
    if ( $.cookie(cookieName) == null && $.cookie(cookieName) != false ) {
        cookieSessionOnly();// ensures the language overlay doesn't nag the user again after initial viewing, regardless of user choice
    }
    return false;// prevent hyperlink click
}

$(document).ready( function() {
    if ( $('a#lang').length > 0 ) {
        $('#changeLanguage').jqm();// instantiate modal window plugin/class on link element
        $('#footer .languageList').clone(true).insertAfter('#changeLanguage div.intro');// clone language list from footer into modal markup
        $('a#lang').click( function() {
            return changeLanguage();
        });
        cookieLanguage();
    }
});


/**
 *  Modal Content Links
 *  Binds modal window functionality to regular hyperlinks that are
 *  classed as "modal", then shows the link's HREF in the modal's
 *  IFRAME.
 *  Last modified: 2009-09-04 {pf}
 */

function openContentModal(url) {
    $('#contentModalIframe').attr('src', url);
    $('#contentModal').jqmShow();
    return false;// prevent hyperlink click
};

$(document).ready( function() {
    if ($('#contentModal').length > 0) {
        $('#contentModal').jqm();
        $('a.modal').click( function() {
            return openContentModal($(this).attr('href'));
        });
    }
});


/**
 *  IE6 Hover Fixes [jQuery]
 *  Adds rollover behaviour to jQuery-pathed non-anchor elements in IE6.
 *  Last modified: 2009-09-16 {pf}
 */
function ie6HoverFixes(hoverElements) {
    for (var e = 0; e < hoverElements.length; e++) {
        $(hoverElements[e]).hover(
            function() {
                $(this).addClass('hover');
            },
            function () {
                $(this).removeClass('hover');
            }
        );
    }
}

$(document).ready( function() {
    if ( $.browser.msie && $.browser.version == 6 ) {
        var hoverElements = [
            "#homePage #findCourse .findButton input"
        ];
        ie6HoverFixes(hoverElements);
    }
});
