$(document).ready(function(){
            // Set USA Default
            
            // Handle other countries
            $('#country').change(function(){
                var cVal = $(this).val();
                //no longer need to use ajax.  There should be a javascript array containing all forms
                form_to_load = '';
                switch(cVal){
                    case 'USA':
                        form_to_load = 'usaForm';
                        
                    break;  
                    case 'Canada':
                        form_to_load = 'caForm';
                        
                    break;
                    case 'UK':
                        form_to_load = 'ukForm';
                        
                    break;
                    case 'Australia':
                        form_to_load = 'auForm';
                        break;
                    default:
                        // Show others form if no case
                        form_to_load = 'othersForm';
                        
                }
                $('#variantTarget').fadeOut(200);
                $('#variantTarget').html(form_variants[form_to_load]);
                
                // Support for popup
                $('#variantTargetPop').html(form_variants[form_to_load]);
                
                if($.getUrlVar('form') == 28042){
                        $('.emailReq').show(0);
                    } else {
                        $('.emailReq').hide(0);
                    };
                    setupRequired('#' + form_to_load);
                
                $('#variantTarget').fadeIn('fast',function(){
                    
                    // Set BG color on focused form elements
                    $('.field-decor input, #formWrap select').not('.red').focus(function(){
                        $(this).parent().css('background-color', '#f9ffa1');
                    });
                    
                    // Remove BG color on blured elemenats
                    $('.field-decor input, #formWrap select').not('.red').blur(function(){
                        $(this).parent().css('background-color', '#f7f7f7');
                        
                        if($(this).hasClass('form_required')){
                            if(!$(this).val()){
                                $(this).addClass('errorRed');
                            } else {
                                $(this).removeClass('errorRed');
                            }
                        };
                        
                        
                    });
                    $('#country').focus(); 
                    
                    
                });
            });
            /*
            $('#country').val(siteSettings.default_country);
            
            $('#variantTarget').html(form_variants['usaForm']);
            if($.getUrlVar('form') == 28042){
                        $('.emailReq').show(0);
                    } else {
                        $('.emailReq').hide(0);
                    };
                    setupRequired('#usaForm');
                    $('#variantTarget').fadeIn('fast');
            */
            
            // F3 Integration
            $("#subBtn").click(function(event){
                // Custom home page redirect message
                var cForm = $('input[name="RFIForm"]').val();
                if(cForm == '28043') {
                    $.cookie('HOMEMESSAGE','<h1 id="hookHeader">Thanks!</h1><h2>A Design Representative will contact you shortly about taking a test swim.</h2>',{expires:0});
                } else {
                    $.cookie('HOMEMESSAGE','<h1 id="hookHeader">Thanks!</h1><h2>You should receive your information within a week.</h2>',{expires:0});
                } 
                myForm = $(event.currentTarget).parents('form');
                //alert ("MYID: " + myForm.attr('id'));
                var formOk = false;
                formOk = validateForm();
                // either submit form or trigger error
                
                if (formOk) {
                    $.cookie('IK','yes',{expires:0});
                    if (siteSettings.demographic_form_method == 'ajax') {
                        $('#rfiForm input[name="WhereToGo"]').val('N/A');
                        $('#rfiForm input[name="GotoN"]').val('N/A');
                    }
                    postDataToServer(myForm.attr('id')); // does the ajax
                    
                    // Take home if f3 already submitted
                    if (!siteSettings.show_f3) {
                        if (typeof(siteSettings.demographic_followup) == 'function') {
                                    siteSettings.demographic_followup();
                        }
                    }
                    else {
                        if($.cookie('f3')){
                                    //this has to go to the appropriate destination, not /
                                    //window.location = destination;    Not on Australia
                                    siteSettings.extra_followup();
                        } else {                
                                    // Display f3
                                    $('h2:eq(1), .formWrapper, #formContent, #videoLoader').fadeOut(0, function(){
                                        // Suppress page content
                                        $('.f3').hide();
                                        // Bring in F3
                                        $("#f3").show();    
                                    });
                        }
                    }
                    
                }
                else {
                    logEvent('Form Submitted Bad'); 
                    //$('#errorWrapper').overlay().load();
                }
            
            
            
            });

            // Close Button Reset
            $('.close').mouseup(function(){
                $('h2:eq(1), .formWrapper, #formContent, #videoLoader').delay(1500).fadeIn('slow');
            });
            
            $('#f3-submit').click(function() {
                // Flag as having seen f3
                $.cookie('f3','yes',{expires:0});
                if (typeof destination != "undefined") {
                        document.getElementById('WhereToGo').value = destination;
                        document.getElementById('GotoN').value = destination;
                        siteSettings.extra_goton = destination;
                }
                
                var f3_query = $(this).parents('form').serialize();
        //alert ('Destination: ' + destination);
        //alert ('WhereToGo: ' + document.getElementById('WhereToGo').value);
        //alert ('GoToN: ' + document.getElementById('GotoN').value);
        //alert (f3_query);
        if (siteSettings.extra_form_method == 'ajax') {
                        var myForm  = $(this).parents('form');
                        $('#followUp input[name="WhereToGo"]').val('N/A');
                        $('#followUp input[name="GotoN"]').val('N/A');
                        postDataToServer(myForm.attr('id'));
                        //$('#videoOverlayForm').css('display', 'none');
                        siteSettings.extra_followup();
                }
                else {
                        $('#followUp input[name="WhereToGo"]').val(siteSettings.extra_goton);
                        $('#followUp input[name="GotoN"]').val(siteSettings.extra_goton);
                        $(this).parents('form').submit();
                }
                
            });
            
            $('#country option[value="' + siteSettings.default_country + '"]').attr('selected', 'selected');
            $('#country').val(siteSettings.default_country);
            // at this point in the process the last_request object will be from the database, if it exists at all
            // so I need a flag to tell the setupRequired function to only do country when this is true
            initial_page_load = true;
            $('#country').change();
            
            
            
            // Commercial Form Company Name Injection
            switch($('input[name="RFIForm"]').val()){
            case "28060":
                // Clear div
                $('fieldset div:eq(0)').css('height','1px');
                var m = '<ul class="alternate"><li><label for="">Company Name</label><input type="text" class="textInput" value="" name="Company" id=""></li></ul>';
                $(m).insertAfter('.cPush:eq(0)');
            break;
            
            }
            

});

function validateForm() {
    var ret = true;
    $('.form_required').each(function(index, element) {
        if (element.value == '' || element.value == element.defaultValue) {
            ret = false;
            $(element).addClass('errorRed');
        }
        else {
            $(element).removeClass('errorRed');
        }
    });
    return ret;
}

function setupRequired(el) {
    var requiredFields = new Array();
    requiredFields['#usaForm'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'PrimAdd', 'PrimCity', 'State', 'ZipCode', 'Country'];
    requiredFields['#caForm'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'PrimAdd', 'PrimCity', 'State', 'ZipCode', 'Country'];
    requiredFields['#ukForm'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'PrimAdd', 'PrimCity', 'State', 'ZipCode', 'Country'];
    requiredFields['#auForm'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'PrimAdd', 'PrimCity', 'State', 'ZipCode', 'Country', 'email'];
    requiredFields['#othersForm'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'PrimAdd', 'PrimCity', 'State', 'ZipCode', 'Country'];
    requiredFields['email_only'] = ['FirstConTitle', 'ContactFirst', 'ContactLast', 'email'];
    
    var reqFields = requiredFields[el];
    if (typeof(email_only_form) != 'undefined' && email_only_form) {
        reqFields = requiredFields['email_only'];
    }
    $.each(reqFields, function(index, value) {
        $(el + " input[name=" + value + "]").addClass('form_required');
    });
    
    $('input[name="ContactLast"]').parents('form').find('select, input').change(function() {
        save_form_field(this);
    });
    $('input[name="ContactLast"]').parents('form').append('<input type="hidden" name="unique_form_id" value="' + unique_form_id + '" />');
    
    if (prev_request) {  // prepopulate form fields if a previous request exists.
        $.each(last_request, function(key, value) {
            //alert (key + ": " + value);
                        if (value.length > 0) {
                                    if ($('input[name="' + key +'"]').length > 0) {
                                        $('input[name="' + key +'"]').val(value);
                                    }
                                    else if($('select[name="' + key +'"]').length > 0) {
                                                if (key == 'Country') {
                                                            if (initial_page_load) {
                                                                        $('select[name="' + key +'"] option[value="' + value + '"]').attr('selected', 'selected');
                                                                        $('select[name="' + key +'"]').val(value);
                                                                        initial_page_load = false;
                                                            }
                                                }
                                                else {
                                                            $('select[name="' + key +'"] option[value="' + value + '"]').attr('selected', 'selected');
                                                            $('select[name="' + key +'"]').val(value);
                                                }
                                        
                                    }
                        }
            
        });
    }
}

function save_form_field(element) {
    //alert (unique_form_id + " : " + element.name + " : " + element.value);
    var elem_val = jQuery.trim(element.value);
    if (typeof(last_request) == 'undefined') {
        prev_request = true;
        last_request = {};
    }
    
    if (elem_val.length > 0) {
        form_save_url = '/all/save_form_field.php?fid=' + escape(unique_form_id) + '&elem_name=' + escape(element.name) + '&elem_value=' + escape(element.value);
        jQuery.ajax({
            url: form_save_url,
            type:'GET',
            dataType:'json',
            async:true,
            timeOut:10000,
            success: function(json) {
            
            },
            error: function() {
            
            },
            complete: function() {
            
            }
        });
        last_request[element.name] = elem_val;
    }
}

function postDataToServer(FormID) {
    var postData = $('#' + FormID).serialize();
    var postURL = jQuery('#' + FormID)[0].action;
    jQuery.ajax({
        url: postURL,
        type:'POST',
        data: postData,
        dataType:'html',
        async:'false',
        timeOut:10000,
        success: function(html) {
            logEvent('Form Submitted Good');
            createCookie('formSubmissionDate', Date(), 365);
            var currentPathName = location.pathname;
            if (currentPathName.charAt(0) == "/") {
                currentPathName = currentPathName.slice(1);
            }
            $('body').append('<iframe frameBorder="0" id="conversion_frame" style="display: inline; height: 1px; width: 1px; max-height: 1px; max-width: 1px;"></iframe>');
            $('#conversion_frame').attr('src', '/all/conversion_tracking.html');
            
        },
        error: function() {
            alert("We experienced an error sending your request, please try again.");
        }
    });
}

