// 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();
    }

    $('.contactform-wrap > .contact-form').submit(function(event){
        return checkForm(event, $(this));
    });
    
    $('#open').append(
        '<input type="hidden" name="javascript" value="enabled" />'
    );    
    
    var sfLead = $('input[name="lead_source"]');
    var contactform = $('#self_post > form');
    var sfAction = $('input[name="sf_action"]').val();
    var selfPostSubject = $('#self_post_subject');
    		
    $('#formSelect').change(function() {
    	
    	var self = $(this);
    	var selectValue = self.val();
    	
    	
    	switch(selectValue) {
    		case 'sales':
    			yesInquiry();
    			sfLead.val('Sales Inquiry Form');
    			selfPostSubject.val('');
    			contactform.attr('action', sfAction);
    		break;
    		
    		case 'partner':
    			yesInquiry();
    			sfLead.val('Partner Inquiry Form');
    			selfPostSubject.val('');
    			contactform.attr('action', sfAction);
    		break;
    		
    		case 'billing':
    		case 'support':
    			noInquiry();
    			selfPostSubject.val('');
    			contactform.attr('action', '');
    		break;
    		
    		default:
    			yesInquiry();
    			selfPostSubject.val(selectValue);
    			contactform.attr('action', '');
    	}
    	
    }).trigger('change'); // Make sure this triggers even if the user hits the back button
    
    function yesInquiry() {
    	$('.yesinquiry').show();
    	$('#noinquiry').hide();
    }
    
    function noInquiry() {
    	$('.yesinquiry').hide();
    	$('#noinquiry').show();
    }
    
    function checkForm(event, form) {
        var f = form;
        var subject_value = $('#sendto').val();
		var $required_fields = $('#sendto, #first_name, #last_name, #company, #email, #phone, #inquiry');
        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();
            event.preventDefault();
        }
        return true;
    }
    
});

