    img1 =  new Image();
    img1.src = "http://www.protect.com/wp-content/themes/sandbox/images/mortgage_pop_top.png";
    img2 =  new Image();
    img2.src = "http://www.protect.com/wp-content/themes/sandbox/images/mortgage_pop_repeat.png";
    img3 =  new Image();
    img3.src = "http://www.protect.com/wp-content/themes/sandbox/images/step2.png";
    img4 =  new Image();
    img4.src = "http://www.protect.com/wp-content/themes/sandbox/images/submit2_pop.png";
    img5 =  new Image();
    img5.src = "http://www.protect.com/wp-content/themes/sandbox/images/mortgage_pop_bottom.png";
    img6 =  new Image();
    img6.src = "http://www.protect.com/wp-content/themes/sandbox/images/submit2_pop.png";
    img7 =  new Image();
    img7.src = "http://www.protect.com/wp-content/themes/sandbox/images/calc_bg_repeat.png";
    img8 =  new Image();
    img8.src = "http://www.protect.com/wp-content/themes/sandbox/images/step3.png";
    img9 =  new Image();
    img9.src = "http://www.protect.com/wp-content/themes/sandbox/images/submit3_pop.png";

$(document).ready(function(){
    
  var mortgage_goal = $('#mortgage_goal').val();
  var home_type = $('#type_of_house').val();
  var home_purpose = $('#purpose_of_house').val();
  var query;
  var name = '';
  var value, doc_height, scrolltop;
  
  
            /////////////////////////////////////
            //loan to value validation purchase
            ////////////////////////////////////
            
            var ltv_purchase = function ltv_purchase(){
                var price = $('select[name="purchase_price"]').val() - 5000;
                var value = ($('select[name="subject_property_value"]').val() * 1) + 4999;
                var down = ($('select[name="estimated_down_payment"]').val() * 1) + 4999;
                var ltv = (price - down)/value;
                $('.ltv_purchase').remove();
                
                if(ltv >= 0.97){
                    var ltv = String(ltv);
                    $("<div class='field'><label class='error ltv_purchase'>Your Loan to Value (LTV) ratio must be below 0.97. You're currently at " + ltv.substr(0,5) +". LTV is affected by Loan Amount, Property Value and Estimated Down Payment.</label></div>").appendTo('.form_section');
                    return false;
                }else{
                    return true;
                }
            };
            
            
            /////////////////////////////////////
            //loan to value validation refinance
            ////////////////////////////////////
            
            var ltv_refi = function() {
                    var value = $('select[name="first_mortgage_balance"]').val() * 1 + 4999;
                    var value2 = 0;
                    if($('input[name="have_second_mortgage"]').is(':checked')){
                        value2 = $('select[name="second_mortgage_balance"]').val() * 1 + 4999;
                    }
                    var loan = $('select[name="subject_property_value"]').val() * 1 - 5000;
                    var ltv = (value + value2)/loan;
                    $('.ltv').remove();

                    if(ltv > 0.90){
                        var ltv = String(ltv);
                        $("<div class='field'><label class='error ltv'>Your Loan-to-Value (LTV) ratio must be below 0.90. You're currently at " + ltv.substr(0,5) +"</label></div>").appendTo('.form_section');
                        return false;
                    }else{
                        return true;
                    }
                
               }
               
               
               /*
                 If user checks 'Yes' for va_mortgage_eligible then the existing_va
                 question will slide down. If it is not visible it is also disabled so 
                 that it is not submitted.
                 */
                 
                 var va_eligible = function(){
                    
                    $('#existing_va_mortgage_field').hide();
                    $('.va_mortgage_eligible').change(function(){
                        
                        var va_value = $('input:radio[name=va_mortgage_eligible]:checked').val();
                        if(va_value == 'Yes'){
                            $('#existing_va_mortgage_field').slideDown();
                            $('#existing_va_mortgage_field').children('input').removeAttr('disabled');
                        } else {
                            $('#existing_va_mortgage_field').slideUp();
                            $('#existing_va_mortgage_field').children('input').attr('disabled', 'disabled');
                        }
                        
                    });
                
                 }
                 
                 
                 /*
                 If user checks 'Yes' for second_mortgage then the second mortgage questions
                 will slide down. If they are not visible they are also disabled so 
                 that they are not submitted.
                 */
                
                $('#second_mortgage, input:checkbox[name="have_second_mortgage"]').change(function(){
                    
                    var checked = $('input:checkbox[name="have_second_mortgage"]').is(":checked");
                    if(checked){
                        $('#second_mortgage_balance_field, #second_mortgage_rate_field').slideDown();
                        $('#second_mortgage_balance_field, #second_mortgage_rate_field').find('select, input').removeAttr('disabled');
                    } else {
                        $('#second_mortgage_balance_field, #second_mortgage_rate_field').slideUp();
                        $('#second_mortgage_balance_field, #second_mortgage_rate_field').find('select, input').attr('disabled', 'disabled');
                    }
                    
                });
                
                 
                 var mortgage_rate = function(){
                    
                    var rate_value = $('input[name="first_mortgage_rate"]').val();
                    
                    $('.first_rate').remove();
                    
                    if(rate_value > 15 || rate_value < 0){
                        $("<div class='field'><label class='error first_rate'>Not a valid Interest Rate</label></div>").insertAfter('input[name="first_mortgage_rate"]');
                        return false;
                    }else if(rate_value == ''){
                        $("<div class='field'><label class='error first_rate'>This field is required</label></div>").insertAfter('input[name="first_mortgage_rate"]');
                        return false;
                    }else{
                        return true;
                    }
                    
                 }
                 
                 
                 var property_value = function(){
                    var prop_val = $('select[name="subject_property_value"]').val();
                    
                    $('.property_value').remove();
                    
                    if(prop_val == ''){
                        $("<div class='field'><label class='error property_value'>This field is required</label></div>").insertAfter('select[name="subject_property_value"]');
                        return false;
                    }else{
                        return true;
                    }
                 }
                 
                  var first_mortgage = function(){
                    
                    var first_mortgage = $('select[name="first_mortgage_balance"]').val();
                    
                    $('.first_mortgage').remove();
                    
                    if(first_mortgage == ''){
                        $("<div class='field'><label class='error first_mortgage'>This field is required</label></div>").insertAfter('select[name="first_mortgage_balance"]');
                        return false;
                    }else{
                        return true;
                    }
                    
                 }
                
                 
                 var down_payment = function(){
                    
                    var down = $('select[name="estimated_down_payment"]').val();
                    
                    $('.down').remove();
                    
                    if(down == ''){
                        $("<div class='field'><label class='error down'>This field is required</label></div>").insertAfter('select[name="estimated_down_payment"]');
                        return false;
                    }else{
                        return true;
                    }
                    
                 }
                 
                 
                
                  jQuery.validator.addMethod("address", function(value, element){
                             
                                 var pattern = /[0-9]{7}/;
                                 var pattern2 = /[a-zA-Z]/;
                                 var result = pattern.test(value);
                                 var result2 = pattern2.test(value);
                                 if(result){ 
                                     return false;
                                 }else {
                                     return result2;
                                 }
                                   
                            }, "Not a valid address");
                 
           
           jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, ""); 
            if (phone_number.match(/^\(\d{3}\)\d{3}\-\d{4}$/) == null) return false;
            var x = $.ajax({
                            url: "../forms/checkphone.php",
                            type: "POST",
                            async: false,
                            data: "phone=" + phone_number,
             }).responseText;
            //alert(x);
            if (x=='') return true;
            return false;
             }, "Please specify a valid phone number");
            
            jQuery.validator.addMethod("first_mortgage_rate", function(rate, element){
                value = parseFloat(rate);
                return value;
            }, "This is an invalid rate");
            
            
            /*
             //Difference between purchase price and down payment can't be less than 75,000 or more than 800,000.
                         jQuery.validator.addMethod("down_payment", function(down, element){
                             var price = $('#purchase_price').val();
                             var down = $('#estimated_down_payment').val();
                             var max_diff = ((price * 1) + 4999) - (down - 5000);
                             var min_diff = (price - 5000) - ((down * 1) + 4999);
                             var max_down = (((price * 1) + 5000) - 75000);
                             var min_down = (((price * 1) - 5000) - 800000);
                             //var response = diff;
                             if(max_down < 0){
                                 var response = "Purchase price is too low for a down payment";
                             }else if(max_down > 0 && max_diff < 75000){
                                 var response = "Down payment can't be more than " + max_down;
                             }else if(min_diff > 800000){
                                 var response = "Down payment can't be less than " + min_down;
                             }
                             $.validator.messages.down_payment = response;
                             if(max_diff < 75000 || min_diff > 800000){
                                 return false;
                             } else {
                                 return true;
                             }
                         });   
             */
                   
     /////////////////////////////////////
    //Personal Info Validation
    ////////////////////////////////////
                
       var personal_info = function(){ 
        
        /*
        *   Field masking
        */
        jQuery(function($){
            $(".phone").mask("(999) 999-9999",{placeholder:"x"});
            //$("#first_mortgage_rate").mask("9%",{placeholder:"x"});
        });
        
            /*
         This auto-populates the work_phone field with the value in the home_phone field.
         */
        
        $('#home_phone').keypress(function(){
            var home = $('#home_phone').val();
            $('#work_phone').val(home);
        });
        
           var state = $("#state").val(); 
            
    	   $("form").validate({
    	       onkeydown: true,
               onblur: true,
               focusInvalid: false,
               ignore: ":hidden",
               rules: {
                    home_phone: {
                        required: true,
                        phoneUS: true
                    },
                    work_phone: {
                        required: true,
                        phoneUS: true
                    },
                    address_1: {
                        address: true
                    },
                    first_name: {
                        required: true,
                        minlength: 2
                    },
                    last_name: {
                        required: true,
                        minlength: 2
                    },
                    subject_property_value: {
                        required: true  
                    },
                    estimated_down_payment: {
                        required: true  
                    },
                    va_mortgage_eligible: {
                        required: true  
                    },
                    monthly_mortgage_payment: {
                      required: true,
                      digits: true  
                    },
                    purchase_price: {
                        required: true,
                    },
                    first_mortgage_balance: {
                        required: true  
                    },
                    first_mortgage_rate: {
                        required: true,
                        min: 0,
                        max: 15,
                        maxlength: 5  
                    },
                    zip: {
                        required: true,
                        minlength: 5,
                        maxlength: 5,
                        digits: true
                        /*
                         remote: {
                                                 url: "includes/checkzip.php",
                                                 data: {
                                                     state: function(){
                                                         return $("select#state").val();
                                                     }
                                                 }
                                                 } 
                         */
                    },
                    city: {
                        required: true
                    }
               },
               messages: {
                        zip: {
                            remote: jQuery.format("Postal code doesn't match State")
                        },
                        home_phone: {
                            phoneUS: jQuery.format("Please use a valid phone number")
                        }
               }
               
    	   });
        }     
  
    //step 1
    
    $('#p-button').click(function(){
        
        
        var house_type = $('select[name="type_of_house"]').val();
        var house_purpose = $('select[name="purpose_of_house"]').val();
        
        if(house_type == '' || house_purpose == ''){
            return false;
        }
                
        query = '';
        
        $('#side_bar_form select, #side_bar_form input').each(function(){
             var name = $(this).attr('name');
             var value = $(this).val();
             if(name != undefined){
                query += '&' + name + '=' + value;
             }
        });
        
        $.ajax({
            type: 'GET',
            url: '/forms/mortgage/ajax-form/step2.php?' + query,
            success: function(data){
                scrolltop = $(window).scrollTop();
                scrolltop += 100;
                $('body').prepend(data);
                $('#mortgage_pop_container').css('top', scrolltop + 'px');
                doc_height = $(document).height();
                $('#mortgage_pop_bg').height(doc_height);
                $('#mortgage_pop_bg').fadeIn(function(){
                    $('#mortgage_form_pop').fadeIn();
                });
                
                $('#pop_exit').click(function(){
                    $('#mortgage_pop_bg, #mortgage_pop_container').fadeOut(function(){
                        $('#mortgage_pop_bg, #mortgage_pop_container').remove();
                    }); 
                });
                
                va_eligible();
                
                    /* 
                    * disables the second mortgage elements
                    */
                    $('#second_mortgage_balance_field, #second_mortgage_rate_field').find('select, input').attr('disabled', 'disabled');
                    
                    /*
                     If user checks 'Yes' for second_mortgage then the second mortgage questions
                     will slide down. If they are not visible they are also disabled so 
                     that they are not submitted.
                     */
                    
                    $('#second_mortgage, input:checkbox[name="have_second_mortgage"]').change(function(){
                        var checked = $('input:checkbox[name="have_second_mortgage"]').is(":checked");
                        if(checked){
                            $('#second_mortgage_balance_field, #second_mortgage_rate_field').slideDown();
                            $('#second_mortgage_balance_field, #second_mortgage_rate_field').find('select, input').removeAttr('disabled');
                        } else {
                            $('#second_mortgage_balance_field, #second_mortgage_rate_field').slideUp();
                            $('#second_mortgage_balance_field, #second_mortgage_rate_field').find('select, input').attr('disabled', 'disabled');
                        }
                        
                    });
                    
                    /*
                     If user checks 'Yes' for va_mortgage_eligible then the existing_va
                     question will slide down. If it is not visible it is also disabled so 
                     that it is not submitted.
                     */
                    $('#existing_va_mortgage_field').hide();
                    $('.va_mortgage_eligible').change(function(){
                        
                        var va_value = $('input:radio[name=va_mortgage_eligible]:checked').val();
                        if(va_value == 'Yes'){
                            $('#existing_va_mortgage_field').slideDown();
                            $('#existing_va_mortgage_field').children('input').removeAttr('disabled');
                        } else {
                            $('#existing_va_mortgage_field').slideUp();
                            $('#existing_va_mortgage_field').children('input').attr('disabled', 'disabled');
                        }
                        
                    });
                
                $('select[name="purchase_price"], select[name="estimated_down_payment"], select[name="subject_property_value"]').bind('change', ltv_purchase);
                 $('select[name="subject_property_value"], select[name="first_mortgage_balance"]').bind('change', ltv_refi);
                 $('input[name="first_mortgage_rate"]').bind('focusout', mortgage_rate);
        
                
                /////////////////////
                // STEP 3     
                /////////////////////
                
                $('select[name="estimated_down_payment"]').change(function(){
                    if(!down_payment){
                        return false;
                    }else{
                        $('.down').parent('.field').remove();
                    }
                });
                
                $('select[name="subject_property_value"]').change(function(){
                    if(!property_value){
                        return false;
                    }else{
                        $('.property_value').remove();
                    } 
                });
                
                $('.step2_pop').click(function(){ 
                    
                    $('.error').remove();                    
                    mortgage_rate();
                    property_value();
                    first_mortgage();
                    if(!ltv_purchase()){return false};
                    if(!ltv_refi()){return false};
                    if(!mortgage_rate()){return false};
                    if(!down_payment()){return false};
                    if(!first_mortgage()){return false};
                    
                    $('#mortgage_pop_container').fadeOut();
                    
                    //query = '';
            
                    $('#mortgage_pop_container select, #mortgage_pop_container input').each(function(){
                         var name = $(this).attr('name');
                         var value = $(this).val();
                         if(name != undefined && name != 'mortgage_goal' && name != 'purpose_of_house' && name != 'type_of_house'){
                            query += '&' + name + '=' + value;
                         }
                    });
            
                     $.ajax({
                        type: 'GET',
                        url: '../forms/mortgage/ajax-form/step3.php?' + query,
                        success: function(data){
                            $('#mortgage_form_pop').html(data);
                            $('#mortgage_pop_container').css('top', scrolltop + 'px');
                            doc_height = $(document).height();
                            $('#mortgage_pop_bg').height(doc_height);
                            $('#mortgage_pop_container').fadeIn();
                            $('#mortgage_pop_bg').fadeIn(function(){
                                $('#mortgage_form_pop').fadeIn();
                            });
                            
                            personal_info();
                            /////////////////////
                            // Submit    
                            /////////////////////
                            
                            $('.step3_pop').click(function(){
                                
                                if(!$('#mortgage_form').valid()){
                                    return false;
                                };
                            
                                $('#mortgage_pop_container').fadeOut();
                                
                                query = '';
                                
                                $('#mortgage_pop_container select, #mortgage_pop_container input').each(function(){
                                     var name = $(this).attr('name');
                                     var value = $(this).val();
                                     if(name != undefined ){
                                        query += '&' + name + '=' + value;
                                     }
                                });
                                
                                $.ajax({
                                    type: 'GET',
                                    url: '../forms/leadsubmit.php?' + query,
                                    success: function(data){
                                        $('#mortgage_form_pop').html(data);
                                        doc_height = $(document).height();
                                        $('#mortgage_pop_bg').height(doc_height);
                                        $('#mortgage_pop_container').fadeIn();
                                        $('#mortgage_pop_bg').fadeIn(function(){
                                            $('#mortgage_form_pop').fadeIn(); 
                                        });
                                    }
                                }); 
                            
                            });
                        } 
                    });
                });
                
            } 
        });
        
    });
    
});

