jQuery.preloadImages = function() {
    for(var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

$(document).ready(function() {

    $("a[rel*='external']").click(function() {
        window.open($(this).attr('href'));
        return false;
    });

    $("body.homepage ul.homepage_links li").append(' <span class="arrow">»</span> ');

    $.preloadImages("/images/button_form_back_on.png", "/images/button_form_continue_on.png", "/images/button_form_submit_application_on.png", "/images/button_form_submit_on.png");
    $(".rollover").hover(
        function()
        {
            this.src = this.src.replace("_off", "_on");
        },
        function()
        {
            this.src = this.src.replace("_on", "_off");
        }
    );


    // contact form
    if($("#contact").length > 0) {

        $("div.required>label").append(' <span class="required">*</span>');
    }

    // job application
    if($("#apply").length > 0) {
        $("div.required>label").append(' <span class="required">*</span>');
        $('#apply input').keypress(function (event) { return event.keyCode == 13 ? false : true; });    // prevent form submission from Enter key
        stepify();  // I'm not sure why this has to be a function; it probably has to do with the $.fn. stuff inside it
    }

    function stepify() {
        $(".step").hide();
        $('#step1').show();

        $.fn.bindStep.defaults.prevBtn = "/images/button_form_back_off.png"; 
        $.fn.bindStep.defaults.nextBtn = "/images/button_form_continue_off.png";
        $.fn.bindStep.defaults.generateMarkup = function(id1, id2, img) {
            var buttonClass = 'nextButton';
            if(img == $.fn.bindStep.defaults.prevBtn)
            {
                buttonClass = 'prevButton';
            }
            return([
                '<div class="form_button ' + buttonClass + '" ',
                    'id="', id1, '" ',
                '>',
                    '<img ',
                        'src="', img, '" ',
                        'id="', id2 , '" ',
                    'class="rollover ' + buttonClass + '" onmouseover="this.src = this.src.replace(\'_off\', \'_on\');" onmouseout="this.src = this.src.replace(\'_on\', \'_off\');" />',
                '</div>'
            ].join(''));
        }


        $('#step1').bindStep($('#step2'), {
            transition: function(currStep, nextStep) {
                window.scroll(0,0);
                currStep.fadeOut();
                nextStep.fadeIn(function() { if($.browser.msie) { this.style.removeAttribute('filter'); } });
            }, nextValidator: function() { return validate('#step1'); }
        });
        $('#step2').bindStep($('#step3'), {
            transition: function(currStep, nextStep) {
                window.scroll(0,0);
                currStep.fadeOut();
                nextStep.fadeIn(function() { if($.browser.msie) { this.style.removeAttribute('filter'); } });
            }, nextValidator: function() { return validate('#step2'); }
        });
        /*$('#step3').bindStep($('#step4'), {
            transition: function(currStep, nextStep) {
                window.scroll(0,0);
                currStep.fadeOut();
                nextStep.fadeIn(function() { if($.browser.msie) { this.style.removeAttribute('filter'); } });
            }, nextValidator: function() { return validate('#step3'); }
        });*/
    }


    function validate(step)
    {
        var errorsFound = false;
        $(".error").removeClass("error");
        $(".warn").remove();

        window.scroll(0,0);

        var warn = '';

        // check for empty required fields
        $(step + " .required:input[type!='radio']").each(function() {
            if(!$(this).val())
            {
                errorsFound = true;
                $(this).parents(".required").addClass("error");
                warn = "<li>Some of the <strong>required fields</strong> are missing.</li>"
            }
        });

        // radio button arrays need to be validated as a set of elements
        $(step + " .required:input[type='radio']").parents(".radio").each(function() {
            var radioSet = this;
            if($('input[type=radio]:checked', radioSet).length <= 0 ) {
                errorsFound = true;
                $(this).parents(".required").addClass("error");
                warn = "<li>Some of the <strong>required fields</strong> are missing.</li>"
            }
        });

        // validate input
        $(step + " :input").each(function() {
            if(/*(*/$(this).val() /*|| $(this).is(":checked"))*/ && !$(this).is("textarea")) {
                var emailPattern = /^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i;
                var otherPattern = /^[a-z0-9()\/\'":\*+|,.; \- !?&#$@_]{1,255}$/i;   // old pattern
                //var otherPattern = /^[\p{L}\p{M}\p{P}\p{N}\p{S} ]{0,255}$/i;  // we need a JavaScript plugin to support UNICODE

                // validate email field
                if($(this).is("#email"))
                {
                    if(!$(this).val().match(emailPattern))
                    {
                        errorsFound = true;
                        $(this).parents("div").addClass("error");
                        warn += "<li>A valid <strong>Email Address</strong> is required.</li>";
                    }
                }
                else    // validate normal fields
                {
                    if(!$(this).val().match(otherPattern))
                    {
                        errorsFound = true;
                        $(this).parents("div").addClass("error");
                        var id = $(this).attr("id");
                        var prettyName = $("label[for='" + id + "']").text();
                        warn += "<li><strong>" + prettyName + "</strong> contains invalid characters.</li>";
                    }
                }
            }
        });

        if(errorsFound) {
            $("#apply").prepend("<div class=\"warn\"><h2>Errors were found.</h2><p>There seem to be some errors in your form. Please see below:</p><ul class=\"warn\">" + warn + "</ul></div>");
            return false;
        }
        else { return true; }
    }


    // IE6 fixes
    if(jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6) {
        $('ul.topnav ul').wrap("<table><tr><td></td></tr></table>");    /* ridiculous hack that makes the drop downs only as wide as they need to be */
        $('ul.topnav li').hover(function() {                            /* add hover events to all <li> in the top navigation menu */
            $(this).addClass('ie6_hovering');
        }, function() {
            $(this).removeClass('ie6_hovering');
        });
    }

});
