if(typeof Validator != "function")
{
    function Validator(form, elements)
    {
        if(form.length == 0) return null;
        //create the object to return
        var o = new Object();
        //private instance variables
        var ERROR_ELEMENT_BACKGROUND_COLOR = 'pink';
        var ERROR_MSG_PRE_NAME = 'error_msg_';
        var ERROR_MSG_INVALID_EMAIL = 'invalid email';
        var ERROR_MSG_REQUIRED = 'required field';
        var ERROR_MSG_INVALID_STATE = 'invalid field';
        var ERROR_MSG_BACKGROUND_COLOR = 'gray';
        var ERROR_MSG_COLOR = 'yellow';
        var ERROR_MSG_FONT_WEIGHT = 'bold';
        var FOCUS_ELEMENT_BACKGROUND_COLOR = '#33FF99';
        var BLUR_NO_ERRORS_ELEMENT_BACKGROUND_COLOR = 'white';
        var error_found = false;
        var element_to_focus = null;
        var elements_binded = [];

        for(var i = 0 ; i < elements.length;i++)
        {
            //if(elements[i] == null) alert('null');
            basicEvents(elements[i]);
        }
        submitForm(form, elements);
        if($.trim(form.attr('id')) != '')
        {
            $('#'+form.attr('id')+" :input[type='text']:enabled:first").focus();
        }
        else $(":input[type='text']:enabled:first").focus();
        if(document.getElementById('cell_phone') && document.getElementById('work_phone') && document.getElementById('home_phone'))
        {
            function isAtLeastOneNotSelected()
            {
                return !(document.getElementById('home_phone_cb').checked == true && jQuery.trim($('#home_phone').val()) != '')
                &&!(document.getElementById('work_phone_cb').checked == true && jQuery.trim($('#work_phone').val()) != '')
                &&!(document.getElementById('cell_phone_cb').checked == true && jQuery.trim($('#cell_phone').val()) != '')
            }
            function numbersPink()
            {
                $('#home_phone').css('background-color', 'pink');
                $('#work_phone').css('background-color', 'pink');
                $('#cell_phone').css('background-color', 'pink');
            }
            function numbersWhite()
            {
                $('#home_phone').css('background-color', 'white');
                $('#work_phone').css('background-color', 'white');
                $('#cell_phone').css('background-color', 'white');
            }
            function showHomePhone()
            {
                document.getElementById('home_phone_div').style.display = 'block';
                document.getElementById('home_phone_div').style.visibility = 'visible';
                document.getElementById('pref_home').disabled = false;
                document.getElementById('home_phone').focus();
            }

            function hideHomePhone()
            {
                document.getElementById('home_phone_div').style.display = 'none';
                document.getElementById('home_phone_div').style.visibility = 'hidden';
                document.getElementById('pref_home').disabled = true;
                document.getElementById('pref_home').checked = false;
            }

            function showWorkPhone()
            {
                document.getElementById('work_phone_div').style.display = 'block';
                document.getElementById('work_phone_div').style.visibility = 'visible';
                document.getElementById('pref_work').disabled = false;
                document.getElementById('work_phone').focus();
            }

            function hideWorkPhone()
            {
                document.getElementById('work_phone_div').style.display = 'none';
                document.getElementById('work_phone_div').style.visibility = 'hidden';
                document.getElementById('pref_work').disabled = true;
                document.getElementById('pref_work').checked = false;
            }

            function showCellPhone()
            {
                document.getElementById('cell_phone_div').style.display = 'block';
                document.getElementById('cell_phone_div').style.visibility = 'visible';
                document.getElementById('pref_cell').disabled = false;
                document.getElementById('cell_phone').focus();
            }
            function hideCellPhone()
            {
                document.getElementById('cell_phone_div').style.display = 'none';
                document.getElementById('cell_phone_div').style.visibility = 'hidden';
                document.getElementById('pref_cell').disabled = true;
                document.getElementById('pref_cell').checked = false;
            }

            $('#home_phone_cb').click(function(e)
            {
                if(document.getElementById('home_phone_cb').checked == true)
                {
                    showHomePhone();
                    if(jQuery.trim(document.getElementById('home_phone').value) != '') clearErrorMsg($('error_msg_phones'));
                }
                else hideHomePhone();

            });
            $('#work_phone_cb').click(function(e)
            {
                if(document.getElementById('work_phone_cb').checked == true)
                {
                    showWorkPhone();
                    if(jQuery.trim(document.getElementById('work_phone').value) != '') clearErrorMsg($('error_msg_phones'));
                }
                else hideWorkPhone();
            });

            $('#cell_phone_cb').click(function(e)//) handleCellPhone(cell_phone)
            {
                if(document.getElementById('cell_phone_cb').checked == true)
                {
                    showCellPhone();
                    if(jQuery.trim(document.getElementById('cell_phone').value) != '') clearErrorMsg($('error_msg_phones'));
                }
                else hideCellPhone();
            });
            elements_binded.push('#home_phone_cb, #work_phone_cb, #cell_phone_cb');
        }//if phones

        //private methods
        function createError(element, msg, id, type)
        {//alert('element='+element+'\n\n/input/.test(element) && /name/.test(element)');alert(/input/.test(element) && /name/.test(element));
            //for radio buttons --input[name=q75769]
            if($(element).attr('type') != 'radio')
                $(element).css('background-color', ERROR_ELEMENT_BACKGROUND_COLOR);
            if(/input/.test(element) && /name/.test(element))
                element = '#'+element.substring(element.indexOf('=')+1, element.indexOf(']'));
            if(type == null) type = 'span';
            clearErrorMsg($('#'+id));
            $('<' + type + ' id="' + id + '" style="background-color: ' +  ERROR_MSG_BACKGROUND_COLOR
                + '; color: ' + ERROR_MSG_COLOR + '; font-weight: ' + ERROR_MSG_FONT_WEIGHT + ';">'
                + ' ' + msg + ' </span>').insertBefore(element);
            if(error_found == false)
            {
                //focusElement(element_to_validate);
                error_found = true;
                element_to_focus = $(element);
            }
        }//createError
        function clearErrorMsg(error_element)
        {if(error_element.length > 0) error_element.remove();}
        function isEmpty(element)
        {return jQuery.trim(element.val()) == '';}
        function isNotWordOrSpace(e)
        {
            var char_code = typeof e.charCode == "number" ? e.charCode : e.keyCode;//alert("e.keycode="+e.keyCode+"\n\ne.charcode="+e.charCode);
            return !/[\ta-zA-Z]/.test(String.fromCharCode(char_code)) && e.keyCode != 8
            && e.keyCode != 46 && e.keyCode != 13 && e.keyCode != 32
            && e.charCode != 44 && e.charCode != 46 && e.keyCode != 44
            && e.charCode != 45 && e.keyCode != 45 && e.charCode != 39
            && e.keyCode != 39 && e.charCode != 34 && e.keyCode != 34
            && e.keyCode != 9 && e.charCode != 16 && e.charCode != 32;
        }//isNotWordOrSpace
        function isNotANumber(e)
        {//checks if it's not a number, but additionally allows delete/backspace/spacebar/home/end/shift/
            var char_code = typeof e.charCode == "number" ? e.charCode : e.keyCode;
            return !/[\t0-9]/.test(String.fromCharCode(char_code)) && e.keyCode != 8
                        && e.keyCode != 46 && e.keyCode != 13
                        && e.keyCode != 9 && e.keyCode != 39 && e.charCode != 16;
        }
        function isNotPhoneNumber(e)
        {//firefox prevents arrow, home, and end keys
            var char_code = typeof e.charCode == "number" ? e.charCode : e.keyCode;
            return !/[\t0-9]/.test(String.fromCharCode(char_code)) && e.keyCode != 8
            && e.keyCode != 46 && e.keyCode != 13
            && e.keyCode != 9 && e.keyCode != 40 && e.charCode != 40
            && e.keyCode != 41 && e.charCode != 41 && e.charCode != 45
            && e.keyCode != 45 && e.keyCode != 39 && e.charCode != 16
            && e.charCode != 43 && e.keyCode != 43;
        }//isNotPhoneNumber
        function isNotAValidEmailAddress(element)
        {return !(/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/.test(element.val()))}
        function uncheckElement(element)
        {element.attr('checked', false);}
        function basicEvents(element_info)
        {
            //element_info = '#q1 fname restrictions-apply validate';
            var space = element_info.indexOf(' ');
            var element = element_info.substring(0, space);
            element_info = element_info.substring(space+1);
            space = element_info.indexOf(' ');
            var error_str = element_info.substring(element_info, space);
            element_info = element_info.substring(space+1)
            var no_restrictions = element_info.substring(0, element_info.indexOf(' '));
            var validation_required = element_info.substring(element_info.lastIndexOf(' ')+1);

            if($(element).length == 0 || $(element).attr('type') == 'hidden') return;
            elements_binded.push(element);

            if($(element).attr('type') == 'checkbox')
            {
                uncheckElement($(element));
            }
            if($(element).get(0).tagName.toLowerCase() == 'select')
            {
                $(element).change(function(e)
                {
                    if($(this).get(0).selectedIndex != 0) clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+'state'));
                });
            }
            $(element).blur(function(e)
            {
                if($(element).attr('type') != 'radio' && validation_required == 'no-validation') $(this).css('background-color', BLUR_NO_ERRORS_ELEMENT_BACKGROUND_COLOR);
                else if(error_str == 'phones')
                {
                    if(isAtLeastOneNotSelected())
                    {
                        numbersPink();
                    }
                    else numbersWhite();
                }//if
                else
                {
                    if($(element).attr('type') != 'radio' && ($(this).attr('type') == 'text' || $(element).get(0).tagName.toLowerCase() == 'textarea')
                        && ((error_str == 'state' && $(this).val().length < 2)
                            || (/email/.test(error_str) && isNotAValidEmailAddress($(this)))
                        || (isEmpty($(this)) || ($.trim($(this).val()).length < 2
                                                            && $(this).attr('type') != 'hidden'))
                        || ($(this).get(0).tagName.toLowerCase() == 'select' && $(this).get(0).selectedIndex == 0)))
                            $(this).css('background-color', ERROR_ELEMENT_BACKGROUND_COLOR);
                    else
                    {
                        if($(element).attr('type') != 'radio')
                        {
                            $(this).css('background-color', BLUR_NO_ERRORS_ELEMENT_BACKGROUND_COLOR);
                            clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+error_str));
                        }
                    }
                }//else
            });
            if($(element).attr('type') == 'radio')
            {
                $(element).change(function()
                {
                    clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+error_str));
                });
            }
            if(no_restrictions == 'restrictions-apply')
            {
                $(element).keypress(function (e)
                {
                    if((/numbers_only/.test(error_str) && isNotANumber(e)))
                        e.preventDefault();
                    else if((/phone/.test(error_str) && isNotPhoneNumber(e)))
                        e.preventDefault();
                    else if(!/numbers_only/.test(error_str) && !/phone/.test(error_str))if(isNotWordOrSpace(e)) {e.preventDefault();}
                });
                $(element).bind('paste', function(e)
                {
                    e.preventDefault();
                });
            }//if
            $(element).focus(function(e)
                {
                    if($(element).attr('type') != 'radio') $(this).css('background-color', FOCUS_ELEMENT_BACKGROUND_COLOR);
                });
            $(element).keyup(function(e)
            {//createError(document.getElementById('q3'), 'keycode='+e.keyCode+'charCode='+e.charCode,'err');
                if(/email/.test(error_str)) checkEmail($(this), error_str);
                else if($(this).attr('type') == 'text' && !isEmpty($(this))) clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+error_str));
                else if($(this).attr('type') == 'text' && error_str == 'phones' && !isEmpty($(this)))
                {
                    //numbersWhite();
                    $(this).css('background-color', FOCUS_ELEMENT_BACKGROUND_COLOR);
                }
            });
        }//basicEvents
        function checkEmail(element, err)
        {
            clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+err));
            if(!isEmpty(element) && isNotAValidEmailAddress(element))
            {
                element.css('background-color', ERROR_ELEMENT_BACKGROUND_COLOR);
            }
            else if(!isEmpty(element))
            {
                element.css('background-color', FOCUS_ELEMENT_BACKGROUND_COLOR);
                clearErrorMsg($('#'+ERROR_MSG_PRE_NAME+err));
            }
        }//checkEmail
        function validateElement(element_data)
        {
            var space = element_data.indexOf(' ');
            var element_to_validate = element_data.substring(0, space);
            if($(element_to_validate).length == 0 || $(element_to_validate).attr('type') == 'hidden') return;
            var str_type_of_input = element_data.substring(space+1);
            str_type_of_input = str_type_of_input.substring(0, str_type_of_input.indexOf(' '));
            if(str_type_of_input == 'state' && $(element_to_validate).attr('maxlength') == '2' && isEmpty($(element_to_validate)))
            {
                createError((element_to_validate), ERROR_MSG_INVALID_STATE, ERROR_MSG_PRE_NAME+str_type_of_input);
            }
            else if(($(element_to_validate).get(0).tagName.toLowerCase() == 'select'
                && $(element_to_validate).get(0).selectedIndex == 0)
                || ($(element_to_validate).length > 0
                    && (isEmpty($(element_to_validate)) || ($.trim($(element_to_validate).val()).length < 2
                                                            && $(element_to_validate).attr('type') != 'hidden'
                                                            && str_type_of_input != 'email')))
                || ($(element_to_validate).attr('type') == 'radio'
                    && $(element_to_validate).is(':checked') == false))
            {
                //element_to_validate.css('background-color', ERROR_ELEMENT_BACKGROUND_COLOR);
                if((!/no-validation/.test(element_data.substring(space+1))) && !(/phones/.test(element_data.substring(space+1))))
                    createError((element_to_validate), ERROR_MSG_REQUIRED, ERROR_MSG_PRE_NAME+str_type_of_input);
                //if(error_found == false) focusElement(element_to_validate);
            }//if
            else if(str_type_of_input == 'email' && isNotAValidEmailAddress($(element_to_validate)))
            {
                createError((element_to_validate), ERROR_MSG_INVALID_EMAIL, ERROR_MSG_PRE_NAME+str_type_of_input);
            }
        }//validateElement
        function submitForm(form, elements_to_search)
        {
            form.submit(submitHandler);
            function submitHandler(e)
            {
                error_found = false;
                element_to_focus =  null;
                for(var i=0;i<elements_to_search.length;i++)
                {
                    validateElement(elements_to_search[i]);
                }//for
                //q3 q5 q6 last_name q14 q16 cell_phone work_phone home_phone q10 state Message
                if(document.getElementById('cell_phone') && document.getElementById('work_phone') && document.getElementById('home_phone'))
                {
                    if(isAtLeastOneNotSelected())
                    {
                        createError(document.getElementById('home_phone_cb'),
                            'Please supply at least one phone number where we may reach you.',
                            'error_msg_phones', 'p');
                        numbersPink();
                        if(error_found == false)
                        {
                            error_found = true;
                            if(document.getElementById('home_phone_cb').checked == true)
                                element_to_focus = $('#home_phone');
                            else if(document.getElementById('work_phone_cb').checked == true)
                                element_to_focus = $('#work_phone');
                            else if(document.getElementById('cell_phone_cb').checked == true)
                                element_to_focus = $('#cell_phone');
                            else
                                element_to_focus = $('#home_phone_cb');
                        }//nested nested if
                    }//nested if
                }//if
                if (error_found)
                {
                    element_to_focus.focus();
                    element_to_focus.select();
                    e.preventDefault();
                }//if
                else if(!(e.isDefaultPrevented()))
                {
                    form.unbind('submit', submitHandler);
                    o.removeHandlers();
                    error_found = null;
                    element_to_focus = null;
                    elements_binded = null;
                }//else
            }//submitHandler
        }//submitForm

        //public methods
        o.removeHandlers = function()
        {
            for(var i in elements_binded)
                $(elements_binded[i]).unbind();
        };//removeHandlers

        //return the object
        return o;
    }//Validator
}//if(typeof Validator != "function")
if(typeof elements == 'undefined')
{
    var elements = ['#q1 fname restrictions-apply validate',
                    '#q2 lname restrictions-apply validate',
                    '#q3 name restrictions-apply validate',
                    '#q5 city restrictions-apply validate',
                    '#q6 state restrictions-apply validate',
                    '#last_name last_name restrictions-apply validate',
		    '#user_name user_name no-restrictions validate',
                    '#q14 email no-restrictions validate',
                    '#email_confirm email_confirm no-restrictions validate',
                    '#q16 day_phone restrictions-apply validate',
                    '#q10 phone restrictions-apply validate',
                    '#state state restrictions-apply validate',
                    '#Message Msg no-restrictions validate',
                    'input[name=q75769] stock_experience no-restrictions validate',
                    'input[name=q75770] stock_options_experience no-restrictions validate',
                    'input[name=q75766] commodity_experience no-restrictions validate',
                    'input[name=q75767] commodity_options_experience no-restrictions validate',
                    'select[name=pref_home_time] null no-restrictions no-validation',
                    'select[name=pref_work_time] null no-restrictions no-validation',
                    'select[name=pref_cell_time] null no-restrictions no-validation',
                    '#address null no-restrictions no-validation',
                    '#city null no-restrictions no-validation',
                    '#us_state null no-restrictions no-validation',
                    '#zip null no-restrictions no-validation',
                    '#country null no-restrictions no-validation',
                    '#comments null no-restrictions no-validation',
                    '#phone_ext numbers_only restrictions-apply no-validation',
                    '#home_phone,#work_phone,#cell_phone phones restrictions-apply validate',
		    '#pw pw no-restrictions validate',
		    '#pw_confirm pw_confirm no-restrictions validate'];
}//if
if(typeof v == 'undefined')
{//alert('defining');
    var v = null;
}
$(document).ready(function()
{
        v = Validator($('form'), elements);
});//document.ready
$(window).unload(function()
{//alert('unload validator');
    if(v != null)
    {
        v.removeHandlers();
        v = null;
    }
    elements = null;
    $(document).unbind();
    $(window).unbind();
});//$(window).unload
