// JavaScript Document © (mt) Media Temple, all rights reserved.

var $form_error_holder;
$(document).ready(function() {
    // Make sure we always have a place to put form validation errors.
    $form_error_holder = $('#form_error_holder');

    if ( ! $form_error_holder.size() ) {
        $form_error_holder = $('<div id="form_error_holder"></div>')
            .prependTo('div.pagecontent')
            .hide();
    }

    $('#open').submit(function(){
        return checkForm();
    });
    $('#sendto').change(function(){
        noInquiry();
    });
    $('#open').append(
        '<input type="hidden" name="javascript" value="enabled" />'
    );
});

function checkForm() {
        var f = $('#open');
        var subject_value = $('#sendto').val();

        var $required_fields =
            $('#sendto, #name, #company, #email, #phone, #inquiry');
        if (subject_value == 'sales') {
            f.attr('action', '/cgi-bin/contact/contact.cgi');
        }
        else {
            f.attr('action', '');
        }

        var error_field_labels = [];
        
        $required_fields.each(function() {
            var $this = $(this);
            if ( $.trim( $this.val() ) === '' ) {
                error_field_labels.push(
                    $('label[for=' + $this.attr('id') + '] span')
                        .text().replace(/:$/, '')
                );
                $this.addClass('boxerror');
            }
            else {
               $this.removeClass('boxerror');
           }
        });

        if( error_field_labels.length ) {
            $form_error_holder.html(
                '<p><strong>Oops!</strong> The fields '
                + error_field_labels.join(', ') 
                + ', are required.</p>'
            ).show();
            return false;
        }
        return true;
}

function noInquiry() {
    var $contactform = $('#contactform');
    var sendto = $('#sendto').val();

    if ( sendto == 'support' || sendto == 'billing' ) {
        $contactform
            .find('div.yesinquiry').hide().end()
            .addClass('usac')
            ;
        $('#noinquiry').show();
    }
    else {
        $('#noinquiry').hide();
        $contactform
            .removeClass("usac")
            .find('div.yesinquiry').show()
            ;
    }
}
