$(document).ready(function(){
            // Set USA Default
            $('#variantTarget').load('inc/formVariants.php #usaForm', function(){
                                // Check if email required
                                if($.getUrlVar('form') == 28042){
                                    $('.emailReq').show(0);
                                } else {
                                    $('.emailReq').hide(0);
                                };
                                setupRequired('#usaForm');
                                $('#variantTarget').fadeIn('fast');
            });
            // Handle other countries
            $('#country').change(function(){
                var cVal = $(this).val();
                //alert ("CountryValue ::: " + cVal);
                switch(cVal){
                    case 'USA':
                        //alert("Doing Country for US");
                        $('#variantTarget').fadeOut(200, function(){
                            $('#variantTarget').load('inc/formVariants.php #usaForm', function(){
                                    // Check if email required
                                if($.getUrlVar('form') == 28042){
                                    $('.emailReq').show(0);
                                } else {
                                    $('.emailReq').hide(0);
                                };
                                setupRequired('#usaForm');
                                $('#variantTarget').fadeIn('fast');
                            });
                        });                     
                    break;  
                    case 'Canada':
                                                //alert("Doing Country for Canada");
                        $('#variantTarget').fadeOut(200, function(){
                            $('#variantTarget').load('inc/formVariants.php #caForm', function(){
                                // Check if email required
                                if($.getUrlVar('form') == 28042){
                                    $('.emailReq').show(0);
                                } else {
                                    $('.emailReq').hide(0);
                                };
                                setupRequired('#caForm');
                                $('#variantTarget').fadeIn('fast');
                            });
                        });
                    break;
                    case 'UK':
                        //alert("Doing Country for UK");
                        $('#variantTarget').fadeOut(200, function(){
                            $('#variantTarget').load('inc/formVariants.php #ukForm', function(){
                                // Check if email required
                                if($.getUrlVar('form') == 28042){
                                    $('.emailReq').show(0);
                                } else {
                                    $('.emailReq').hide(0);
                                };
                                setupRequired('#ukForm');
                                $('#variantTarget').fadeIn('fast');
                            });
                        });
                    break;
                    default:
                        // Show others form if no case
                        //alert("Doing Country for Others");
                        $('#variantTarget').fadeOut(200, function(){
                            $('#variantTarget').load('inc/formVariants.php #othersForm', function(){
                                // Check if email required
                                if($.getUrlVar('form') == 28042){
                                    $('.emailReq').show(0);
                                } else {
                                    $('.emailReq').hide(0);
                                };
                                setupRequired('#othersForm');
                                $('#variantTarget').fadeIn('fast');
                            });
                        });     
                }
            });
            
            // F3 Integration
            $("#subBtn").click(function(event){
                
                                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});
                    
                    postDataToServer(myForm.attr('id')); // does the ajax
                    
                    // Take home if f3 already submitted
                    if($.cookie('f3')){
                        //this has to go to the appropriate destination, not /
                        window.location = destination;  
                    } 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});
        //document.getElementById('WhereToGo').value = destination;
                $('#followUp input[name="WhereToGo"]').val(destination);
        //document.getElementById('GotoN').value = destination;
                $('#followUp input[name="GotoN"]').val(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');
                        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);
            $('#country').change();

});

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['#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) {
                                            $('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 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.");
        }
    });
}
