var current_error = '';
var handle_blurred = null;
var handle_error = false;
var cur_form; // makes it easier to track the form, will cause issues if trying to use handle check on more than one form on a page
var waiting = false;
var firstSubmit = 1;
/*
Function:
checkInput
Desc:
Verify form inputs against length and/or regular expressions
Vars (all required):
obj = the input element
check_type = int (1 = just length, 2 = just pattern, 3 = both length and pattern)
output_div = id name of div you want output in
input_min = min length of input
input_max = max length of input
pattern = regex to test input against
*/
function checkInput(obj,check_type,output_div,input_min,input_max,pattern,field_name,custom_error) {
    if (typeof(obj) == 'object') {
        try {
            var out = document.getElementById(output_div);
            var input_text = obj.value;
            var has_error = '';
            if (check_type == 1 || check_type == 3) {
                if (input_text.length < input_min) {
                    has_error += ' '+field_name+' is too short.';
                }
                if (input_text.length > input_max) {
                    has_error += ' '+field_name+' length is too long.';
                }
            }
            if (check_type == 2 || check_type == 3) {
                if (!input_text.match(pattern)) {
                    has_error += ' '+field_name+' is invalid.';
                }
            }
            if (has_error != '' && current_error != has_error) {
                var err_msg = '<font color=red>';
                err_msg += (custom_error) ? custom_error : has_error;
                err_msg += '</font>';
                out.innerHTML = err_msg;
                out.style.display='block';
                current_error = has_error;
                requiredFieldError = true;
                if (output_div.match(/handle/)) handle_error = true;
            } else if (has_error == '') {
                current_error = false;
                if ( output_div != 'handle_out' ) {
                    handle_blurred = false;
                    out.innerHTML = '';
                    out.style.display='none';
                }
                if (output_div.match(/handle/)) handle_error = false;
            }
        } catch(e) {alert(e.message)}
    }
}
var checkrunning;
function startCheck(obj,check_type,output_div,input_min,input_max,pattern,field_name,custom_error) {
    current_error = '';
    checkrunning = setInterval('checkInput('+obj+','+check_type+',\''+output_div+'\','+input_min+','+input_max+','+pattern+',\''+field_name+'\',\''+custom_error+'\')',50);
}
function stopCheck() {
    clearInterval(checkrunning);
}

var firstSubmit = 1;
var requiredFieldError = null;

function checkRequiredFields(f, num) {
    var isError = false;

    var errors = new Array();

    // "I am a"
    try {
        if ( num >= 1 && !isFieldChecked( f.REG_sex ) ) {
            document.getElementById('reg_sex_out').innerHTML = register_error_codes.sex;
            document.getElementById('reg_sex_out').style.display = 'block';
            errors.push(register_error_codes.sex2);
            isError = true;
        }
        else if ( isFieldChecked( f.REG_sex ) ){
            document.getElementById('reg_sex_out').innerHTML = '';
            document.getElementById('reg_sex_out').style.display='none';
        }
    }catch(e){alert(e.message)}

    // "Interested in meeting a"
    try{
        if ( num >= 2 && !isFieldChecked( f.looking_for_person ) ) {
            document.getElementById('interested_in_meeting_out').innerHTML = register_error_codes.interested_in_meeting;
            document.getElementById('interested_in_meeting_out').style.display = 'block';
            errors.push(register_error_codes.interested_in_meeting2);
            isError = true;
        }
        else if ( isFieldChecked( f.looking_for_person ) ) {
            document.getElementById('interested_in_meeting_out').innerHTML = '';
            document.getElementById('interested_in_meeting_out').style.display='none';
        }
    }catch(e){alert(e.message)}

    // "For"
    try{
        if ( num >= 3 && !isFieldChecked( f.looking_for_what ) )
        {
            document.getElementById('looking_for_what_out').innerHTML = register_error_codes.looking_for_what;
            document.getElementById('looking_for_what_out').style.display = 'block';
            errors.push(register_error_codes.looking_for_what2);
            isError = true;
        }
        else if ( isFieldChecked( f.looking_for_what ) ) {
            document.getElementById('looking_for_what_out').innerHTML = '';
            document.getElementById('looking_for_what_out').style.display='none';
        }
    }catch(e){alert(e.message)}

    // Age
    try{
        if ( num >= 4 )
        {
            if ( !isOver18() ) {
                document.getElementById('age_out').innerHTML = register_error_codes.age;
                document.getElementById('age_out').style.display = 'block';
                errors.push(register_error_codes.age);
                isError = true;
            }
            else {
                document.getElementById('age_out').innerHTML = '';
                document.getElementById('age_out').style.display='none';
            }
        }
    }catch(e){alert(e.message)}

    // "Zipcode"
    try {
        var country = f.country.options[f.country.selectedIndex].value;
        if ( num > 5 && country == 'United States' ) {
            var zip_out = document.getElementById('zip_out');
            checkZipcode()
            if ( zip_out.style.display == 'block' || zip_out.value == '' ) {
                if ( zip_out.value == '' ) {
                    zip_out.style.display = 'block';
                    zip_out.innerHTML = register_error_codes.zip;
                }
                errors.push(register_error_codes.zip);
                isError = true;
            }
        }
    }catch(e){alert(e.message)}

    // "Handle"
    try {
        if ( num > 7 && f.REG_handle.value == '' ) {
            document.getElementById('handle_out').innerHTML = register_error_codes.handle;
            document.getElementById('handle_out').style.display='block';
            errors.push(register_error_codes.handle);
            isError = true;
        } else {
            if (f.REG_handle.value.length < 4) {
                handle_error = true;
                document.getElementById('handle_out').innerHTML = register_error_codes.handle2;
                document.getElementById('handle_out').style.display='block';
                errors.push(register_error_codes.handle);
                isError = true;
            } else {
                document.getElementById('handle_out').style.display='none';
            }
        }
    }catch(e){alert(e.message)}

    // "Email"
    try {
        if ( num > 6 ) {
            //document.getElementById('email_out').style.display='none';
            checkInput(document.reg.email,3,'email_out',0,64,/^([a-z0-9][a-z0-9\-\.\_]*\@([a-z0-9][a-z0-9\-\.]*\.[a-z]{2,4}?))?$/i,'Email');
            if ( document.getElementById('email_out').style.display == 'block' || f.email.value == '') {
                if ( f.email.value == '' ) {
                    document.getElementById('email_out').innerHTML = register_error_codes.email;
                } else {
                    document.getElementById('email_out').innerHTML = register_error_codes.email2;
                }

                document.getElementById('email_out').style.display='block';
                errors.push(register_error_codes.email2);
                isError = true;
            }
        }
    }catch(e){alert(e.message)}



    if (errors.length > 0) {
        document.getElementById('regError').innerHTML = '<font size=2>'+errors.join('<br/>')+'</font>';
        document.getElementById('regErrorHolder').style.display = 'block';
        
        if (firstSubmit == 1) document.location.href='#top';
    } else {
        document.getElementById('regError').innerHTML = '';
        document.getElementById('regErrorHolder').style.display='none';
    }

    requiredFieldError = isError;
    return errors.length
}

function checkAllFields(formEle) {
    current_error = '';
    var ret = !checkRequiredFields(formEle,99);
    if (firstSubmit == 1) {
        firstSubmit = 0;
        afterFirstSubmit();
    }
    return ret;
}

// function to check whether a radio option array or a checkbox array is checked
function isFieldChecked( fieldObj ) {
    for ( var i = 0; i < fieldObj.length; i++ )
        if ( fieldObj[i].checked ) return true;

    return false;
}

function checkZipcode() {
    var country = document.forms.reg.country.options[document.forms.reg.country.selectedIndex].value;
    if ( country == 'United States')
        checkInput(document.forms.reg.zip,2,'zip_out',5,10,/(^\d{5}$)|(^\d{5}-\d{4}$)/,'Zipcode', register_error_codes.zip);
}

function isOver18() {
    /* the minumum age you want to allow in */
    var min_age = 18;

    /* change "age_form" to whatever your form has for a name="..." */
    var year = parseInt(document.forms.reg.bday_year.options[document.forms.reg.bday_year.selectedIndex].text);
    var month = parseInt(document.forms.reg.bday_month.value) - 1;
    var day = parseInt(document.forms.reg.bday_day.value);

    var theirDate = new Date((year + min_age), month, day);
    var today = new Date;

    if ( (today.getTime() - theirDate.getTime()) < 0) {
        return false;
    } else {
        return true;
    }
}

function addListenerToFields( fieldObj) {
    for ( var i = 0; i < fieldObj.length; i++ ) {
        fieldObj[i].onclick = function() {
            checkRequiredFields( document.forms.reg, 99 );
        };
    }
}

function afterFirstSubmit() {
    var formx = document.forms['reg'];
    addListenerToFields( formx.REG_sex);
    addListenerToFields( formx.looking_for_person);
    addListenerToFields( formx.looking_for_what);

    // Age
    formx.bday_month.onchange = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };
    formx.bday_day.onchange = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };
    formx.bday_year.onchange = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };

    // Country
    formx.country.onchange = function() {
        if ( document.forms.reg.country.options[document.forms.reg.country.selectedIndex].value != 'United States' )
            document.getElementById('zip_out').innerHTML = '';
    };

    // Zip
    formx.zip.onfocus = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };
    formx.zip.onblur = function() {
        document.getElementById('zip_out').style.display = 'none';
        checkRequiredFields( document.forms.reg, 99 );
    };

    // Email
    formx.email.onchange = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };
    formx.email.onblur = function() {
        checkRequiredFields( document.forms.reg, 99 );
    };

    // Handle
    formx.REG_handle.onchange = function() {
        checkRequiredFields( document.forms.reg, 99 );
        handle_blurred = false;
    };

    formx.REG_handle.onkeyup = function() {
        checkInput(formx.REG_handle,2,'handle_out',0,16,/^[a-z_0-9]*$/i,'Handle','Username can only contain a-z,A-Z,0-9,_');
    };

    
    formx.REG_handle.onblur = function () {
        handle_blurred = true;
        formx.REG_handle.onkeyup();
        if ( document.forms.reg.REG_handle.value.length < 4 ) {
            handle_error = true;
            document.getElementById('handle_out').innerHTML = register_error_codes.handle2;
        }
        stopCheck();
    };
}
