jQuery.fn.exists = function(){return jQuery(this).length>0;}

$(document).ready(function(){
    var $randnum = Math.floor(Math.random()*11);
    //    alert($randnum);
    switch($randnum){
        case 1:
            $("#img").html('<img src="/images/pic4.jpg" alt="FHA Duplex" />');
            break;
        case 2:
            $("#img").html('<img src="/images/pic3.jpg" alt="FHA Fixed Rate Mortgage Programs" />');
            break;
        case 3:
            $("#img").html('<img src="/images/pic5.jpg" alt="FHA Triplex (3 Unit) Mortgage Loans" />');
            break;
        case 4:
            $("#img").html('<img src="/images/pic6.jpg" alt="FHA Services" />');
            break;
        case 5:
            $("#img").html('<img src="/images/pic7.jpg" alt="FHA Streamline Refinance Mortgage" />');
            break;
        case 6:
            $("#img").html('<img src="/images/pic8.jpg" alt="FHA insured second mortgage up to $25,000" />');
            break;
        case 7:
            $("#img").html('<img src="/images/pic9.jpg" alt="Mortgage Refinance using FHA Loan Program" />');
            break;
        case 8:
            $("#img").html('<img src="/images/pic10.jpg" alt="Officer Next Door Program" />');
            break;
        case 9:
            $("#img").html('<img src="/images/pic1.jpg" alt="Buying a Home with an FHA Loan" />');
            break;
        default:
            $("#img").html('<img src="/images/pic2.jpg" alt="Single Family Home" />');
            
    
    }
      
    var $form = $("#fha-request"); //This is where the name of the form goes.  

    $form.find("input[name=phone]").mask("?(999) 999-9999").val('(Ph #)   -');
    
    $form.find('input').each(function(){
        
        $(this).data('i',$(this).val());
        
        $(this).focus(function(){
            $(this).removeClass('error');
            if($(this).val() == $(this).data('i')){
                $(this).val('');
            }
        });
        
        $(this).blur(function(){
            if($(this).val() == ''){
                $(this).val($(this).data('i'));
            }
        });
    });
    
    $form.submit( function(){
        $("#error_area").empty(); //This clears the error_area or the area where error messages will be displayed
        var $error = false; //If $error remains false the form will validate and submit
        $(this).find(".form").each(function(){
            $(this).removeClass('error'); //removes the error class from the input elements while we try validation
            var $rule = $(this).attr('validation'); //This is the attribute added to each of the input elements that specifies what rules they must have
            var $string = $(this).val();
            if(!validate($string,$rule) || $string == $(this).data('i')){
                    $(this).addClass('error');
                    $error = true;
            }
        });
        $(this).find(".checkbox").each(function(){
            if($(this).attr('validation') == 'required'){
                
            }
        });
        if(!$error){
            //check if there is a default action first and if there is
            if($form.attr('action')){
                return true;
            }else{
                $.post('MAILER_FILE',$(this).serialize(),function(data){  //this $.post function is what happens when the form validates as true
                    if(data == 'success'){
                          window.location = 'thank-you.php' //currently setup for a redirect if the mailer is sent successfully
                    }else{
                        alert(data); //alerts if there is an error
                    }
                }); 
            }   
        }else{
            $("#error_area").html('There were some problems with the form, they have been highlighted'); //sets the error-area to display errors with the form
        }
        
        return false;
    });
    
    // ======================== FHA LIMITS SCRIPTS =======================
    if($('#limits').exists()){
        $('.state').change(function(){
            if($('.state').find('option:first').text() == "- select -"){ //gets rid of the option - select -
                $('.state').find('option:first').remove();
            } 
           $state = $(".state :selected").val();
           $('.county').empty(); //empties the county select box just in case something is in there
           $.post('ajax/getLimits.php',{"state":$state},function($data){  // ajax call to the php that will return all the counties in selected state
                $data = $data.split(';'); //would rather have used JSON, but jQuery and JSON don't seem to play nice some times
                $.each($data, function($i,$item){
                    if($item != ""){
                        $item = normalCase($item);
                        $('.county').append( //this adds items to the county select box
                            $('<option></option>').val($item).html($item)
                        );
                    }
                });
                $('#county').show();
           });
        });
        $('.county').change(function(){
            $state = $(".state :selected").val();
            $county = $(".county :selected").text();  
            $.getJSON('ajax/getLimits.php',{"state":$state,"county":$county},function($data){  // ajax call to the php that will return all the counties in selected state
                $countyName = normalCase($data.county);
                $('#limitRow').empty().append('<td>'+$countyName+'</td><td>'+$data.oneUnit+'</td><td>'+$data.twoUnit+'</td><td>'+$data.threeUnit+'</td><td>'+$data.fourUnit+'</td>');
                 $('#results').show();     
           });  
        });
    }
    
    // ==================== SIMPLE MORTGAGE CALCULATOR ===================
    if($('#simple_mortgage').exists()){
        $('#simple_mortgage').submit(function(){
            $L = parseInt($(this).find('input[name=amount]').val());
            $n = parseInt($(this).find('input[name=term]').val()) * 12;
            $c = parseFloat($(this).find('input[name=rate]').val()) / (12 * 100);
            
            $monthly = $L * ($c / (1 - (1 / Math.pow((1 + $c),($n) ) ) ) ); //equation to calculate montly payments
            
            $monthly = Math.round($monthly*100) / 100; //rounds to 2 decimal places
            
            $total = $monthly * $n; //calculates the actual price of the loan
            
            $total = Math.round($total*100) / 100; //rounds to 2 decimal places
            
            //$(this).find('table').append('<tr><td>$L</td><td>'+$L+'</td></tr>');
//            $(this).find('table').append('<tr><td>$n</td><td>'+$n+'</td></tr>');
//            $(this).find('table').append('<tr><td>$c</td><td>'+$c+'</td></tr>');
//            $(this).find('table').append('<tr><td>$P</td><td>'+$monthly+'</td></tr>');
            $(this).find('.monthly').empty().html('<td>Monthly Payment:</td><td><input type="text" value="'+$monthly+'" disabled="disabled" /></td>');
            $(this).find('.total').empty().html('<td>Total Payments:</td><td><input type="text" value="'+$total+'" disabled="disabled" /></td>');
            
            return false;
        
        });    
        
    }

    // ==================== SIMPLE MORTGAGE CALCULATOR ===================
    if($('#can_afford').exists()){
        $('#can_afford').submit(function(){
            $I = parseInt($(this).find('input[name=income]').val());
            $L = parseInt($(this).find('input[name=amount]').val());
            $n = parseInt($(this).find('input[name=term]').val()) * 12;
            $c = parseFloat($(this).find('input[name=rate]').val()) / (12 * 100);
            
            $monthly = $L * ($c / (1 - (1 / Math.pow((1 + $c),($n) ) ) ) ); //equation to calculate montly payments
            
            $monthly = Math.round($monthly*100) / 100; //rounds to 2 decimal places
            
            $total = $monthly * $n; //calculates the actual price of the loan
            
            $total = Math.round($total*100) / 100; //rounds to 2 decimal places
            
            $(this).find('.desired').show();
            $(this).find('.monthly').empty().html('<td>Monthly Payment:</td><td><input type="text" value="'+$monthly+'" disabled="disabled" /></td>');
            $(this).find('.total').empty().html('<td>Total Payments:</td><td><input type="text" value="'+$total+'" disabled="disabled" /></td>');
            
            $afford_monthly =  ($I / 12) * .33; 
            
            $afford_amount = ($afford_monthly) / ($c / (1 - (1 / Math.pow((1 + $c),($n) ) ) ) );
            
            $afford_amount = Math.round($afford_amount/1000) * 1000; //rounds to 2 decimal places
            
            $afford_monthly = Math.round($afford_monthly*100) / 100; //rounds to 2 decimal places 
            
            $afford_total = $afford_monthly * $n;  
            
            $(this).find('.affordable').show();
            $(this).find('.afford_amount').empty().html('<td>Mortgage Amount:</td><td><input type="text" value="'+$afford_amount+'" disabled="disabled" /></td>');
            $(this).find('.afford_monthly').empty().html('<td>Monthly Payment:</td><td><input type="text" value="'+$afford_monthly+'" disabled="disabled" /></td>');
            $(this).find('.afford_total').empty().html('<td>Total Payments:</td><td><input type="text" value="'+$afford_total+'" disabled="disabled" /></td>');
            
            if($afford_monthly > $monthly){
                $outcome = "<b>Congratulations, you can afford more than what you were looking for.</b>";
            }else{
                $outcome = "<b>Based off of your current income, you cannot afford the monthly payments for the the desired mortgage that you entered.</b>";
            }
            
            $(this).find('.outcome').empty().html('<td colspan="2">'+$outcome+'</td>');
            
            return false;
        
        });    
        
    }
    
    
    // ============================ FUNCTIONS ============================
    function validate($string,$rule){   //function that validates data - always returns true if their are no validation requirements
            switch($rule){
                case 'alpha':
                    var $regex ='[a-zA-Z ]+';
                    break;
                case 'alphanum':
                    var $regex ='[a-zA-Z0-9 ]+';
                    break;
                case 'num':
                    var $regex ='[0-9] +';
                    break;
                case 'zip':
                    var $regex ='[0-9]{5}';
                    break;
                case 'email':
                    var $regex = '[a-zA-Z0-9\.\-\_]+@[a-zA-Z0-9\.\-]+[.][a-zA-Z]{2,3}';
                    break;
                case 'phone':
                    var $regex = "[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}";
                    break;
                case 'date':
                    $array = $string.split('/'); //first we split the string to make sure that it has all its parts
                    if($array.length = 3){ //if the array doesn't have 3 parts, it auto fails
                        if($array[0] > 12){ // if the month is greater than 12 it fails
                            return false;
                        }else if($array[1] > 31){ //if the day is greater than 31 it fails
                            return false;
                        }else if($array[2] < 2010){ //if the date is less than 2010 it fails -- only for this id
                            return false;
                        }
                    }else{
                        return false;
                    }
                    var $regex = "[0-1]{1}[0-9]{1}[/][0-3]{1}[0-9]{1}[/][0-9]{4}";
                    break;
                case 'select':
                    if($string == ''){ //this assusmes that the default select option will have no value
                        return false;
                    }else{
                        return true;
                    }
                    break;
                case 'required':
                    if($string == ''){ //this assusmes that the default select option will have no value 
                        return false;       
                    } 
                    break;
                default:
                    return true;
            }
            if($string.search($regex) < 0){
                return false;
            }else{
                return true;
            }
}
    function normalCase($string){
        $string = $string.toLowerCase();
        $first = $string.charAt(0);
        $string = $string.replace($first,'');
        $first = $first.toUpperCase();
        $string = $first+$string;
        return $string;    
    }

    
     
});
