$(function(){
    /*-----------------------------------------------------
    // Global Variables
    //=====================================================
    // Unfortunately we have to use some global variables to keep track
    // of what's going on 
    // but it works 
    //-----------------------------------------------------*/

    var search_ad = false;
    var search_ad_price = 0;
    var promo_code = false;
    var zip_counter = 1;
    var amount_remaining = 0;
    var promo_type = "";
    var promo_value = 0;
    
    /*----------------------------------------------
    // Price Handling
    //----------------------------------------------*/
    function set_price(new_price) {
        $('.total_price').text(new_price);
        $("#total").val(new_price);
    }

    function calculate_and_set_price(){
      
        var new_price = extract_price($("input[name='price']:checked").val());
        
        if(search_ad){
            new_price += $("#advertising_cost").val() * 1;
        }
        
        if(promo_code){
            new_price = calculate_discount(new_price)
        }
        
        set_price(new_price);
    }
    
    function extract_price(value){
        var price = value.replace(/ - *.*/, "");
        price = price * 1;
        return price;
    }

    /*----------------------------------------------
    // Zip Codes
    //----------------------------------------------*/
    // Creates an HTTP request for the zip code entered in the form
    // and adds an additional zip search field
    function get_zip_areas(zip_form){

        //Gets the zip form based on user input
        $.get('/products/_zip_code/'+zip_form.val()+'/', function(html){
            var budget = zip_form.parent("p").next(".budget");
            var addendum = $('<p class="other_zip">Distribute your budget to other areas by entering another <label for="zip"> zip code</label><input type="text" class="zip" name="zip_'+zip_counter+'" size="5" maxlength="5" /></p><div class="budget"></div>');

            budget.html(html);

            //Checks to see if a zip form has already been loaded
            if(!zip_form.parent('p').next().next().hasClass("other_zip")){
                budget.after(addendum);
            }
            $('.zip_price').bind("blur", function(e){
                var we_good = minimum_balance($(this));
                if(!this.oldprice){
                    this.oldprice = 0;
                }
                if(we_good || we_good === 0){
                    if(this.oldprice > we_good){
                        we_good =  this.oldprice - we_good;
                        amount_remaining += we_good;
                    } else if(this.oldprice < we_good){
                        we_good = we_good - this.oldprice;
                        amount_remaining -= we_good;
                    }
                    
                    if(amount_remaining < 0){
                        $('.zip_amount_remaining').css("color", "red");
                    } else {
                        $('.zip_amount_remaining').css('color', "#000");
                    }
                    
                    $('.zip_amount_remaining').text(amount_remaining);
                    this.oldprice = $(this).val() * 1;
                }
            })
            $(".zip_amount_remaining").text(amount_remaining);
            zip_counter += 1;
        })
    }

    /*----------------------------------------------
    // Promo Code
    //----------------------------------------------*/
    function set_promo_code(object){
        var price = object.find('#discount').text();
        var type = object.find(".type").text(); 
        var total = $(".total_price").val() * 1;

        if(!type && object.find('#expired').length > 1 ){
            form_error(object, 'This code is expired')
            return false;
        } else if (!type) {
            form_error(object, 'This is not a promotional code');
            return false;
        }
        
        if(type === "Other"){
            var message = $(object).find("#message");
            $('.promotional_code').after(message);
            $('.promotional_code').hide();
            return false;
        }

        if(!promo_code){
            switch(type){
                case 'Dollar':
                     promo_code = true;
                     promo_type = "dollar";
                     promo_amount = price;
                     $('.promo_discount').text(price);
                break;
                case 'Percentage':
                    $("#discount_type").text("");
                    text_price = price.replace('0.', "");
                    $('.promo_discount').text(text_price + "%");
                     promo_code = true;
                     promo_type = "percentage";
                     promo_amount = price;
                break;
            }
            
            calculate_and_set_price();
            $('#promo_code').hide();
        }
     }


    //This calculates the discount 
    function calculate_discount(price){
        var new_price = 0;
        switch (promo_type){    
            case 'percentage':
              new_price = price - promo_amount * price;
            break;
            case 'dollar':
              new_price = price - promo_amount;
            break;
        }
        return new_price;
    }
    
    function set_amount_remaining(price){
        if(search_ad_price < price){
            amount_remaining += price - search_ad_price; 
        } else if (search_ad_price > price){
            amount_remaining -= search_ad_price - price;
        }
        
        if(amount_remaining < 0){
            $('.zip_amount_remaining').css("color", "red");
        } else {
            $('.zip_amount_remaining').css('color', "#000");
        }
        
        $(".zip_amount_remaining").text(amount_remaining);
        search_ad_price = price;
        
    }


            //Checks to see if the state element is available
            if($("#state").length >= 1){

                /*------------------------------------------
                // Disabling and hiding forms for usability
                /------------------------------------------*/

                //Disable certain forms
                $("#search_adverising_zip, #advertising_cost, #MLS").attr("disabled", "disabled");
                //Hide others
                $("#budget, .third p:eq(1)").hide();
                $(".zip, #promo_code").val("");
                $('#promo_code').removeAttr("disabled");
                $("#search_advertising_zip, #search_advertising").removeAttr("checked");

                /*------------------------------------------
                // Error Handling
                /------------------------------------------*/
                
                //Determines if a field is at minimum balance
                //For two areas, the area_advertising
                //and the zip distribution
                function minimum_balance(object){
                    var name = "";
                    var default_value = 0;
                    var min_balance = 100;
                    var value = object.val() * 1;

                    if(object.attr("id") === 'advertising_cost'){
                        name = "search advertising";
                        default_value = 100;
                    } else if (object.hasClass("zip_price")){
                        name = "this area";
                        if(!object.oldprice){
                            default_value = 0;
                        } else {
                            default_value = this.oldprice;
                        }
                    }

                    if(isNaN(value)){
                        object.val(default_value);
                        zip_error(object, "Please enter a number");
                        return false;
                    }
                    if(value > 0 && value < 100){
                        zip_error(object, "There is a minimum of $"+min_balance+" required for "+name+"");
                        object.val(default_value);
                        return false;
                    }  else if(value < 0) {
                        zip_error(object, "There is a minimum of $"+min_balance+" required for "+name+"");
                        object.val(default_value);
                        return false;
                    } else {
                        return value;
                    }
                }
                
                //This is a special error function for handling
                // errors that occur in the zip table
                function zip_error(object, message){
                    var error = $('<tr class="error_message"><td colspan="2">'+message+'</td></tr>');
                    object.parents("tbody").prepend(error);
                    object.css("background-color", "yellow"); 
                    error.slideDown("slow");

                    setTimeout(function(){
                        error.fadeOut(3000, function(){
                            $(this).remove();
                            object.css("background-color", "#FFF");
                        });
                        }, 2000)
                }
                

                //This function abouts an error for any item in the form
                // and then highlights the form field
                function form_error(object, message){
                    var error = $('<p class="error_message">'+message+'</p>'); 
                    object.parents("p").after(error);
                    object.css("background-color", "yellow");
                    setTimeout(function(){
                        error.fadeOut(3000, function(){
                            $(this).remove();
                            object.css("background-color", "#FFF");
                        });
                        }, 2000)
                }

                // Form Submission for landing page
                $("form").submit(function(){
                    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

                    if($("#email").val().length === 0){
                        form_error($("#email"), "Please enter an email address");
                        $("#email").focus();
                        return false;
                    }
                    if(reg.test($("#email").val()) === false){
                        form_error($("#email"), "Please enter a valid email address");
                        $("#email").focus(); 
                        return false;
                    }
                    if($("#MLS").val() === ""){
                        form_error($("#MLS"), "Please choose your state and then an MLS");
                        return false;
                    }
                    if(amount_remaining < 0) {
                        form_error($("#advertising_cost"), "You currently have more money distributed then you have budgeted for, please correct this to move forward");
                        $(".zip_amount_remaining").css("background-color", "yellow");
                        setTimeout(function(){$(".zip_amount_remaining").css("background-color", "#FFF")}, 5000);
                        return false;
                    }

                });




                /*------------------------------------------
                // Events
                /------------------------------------------*/
                
                // Error checking for the zip
                $("#advertising_cost").bind("blur", function(){
                    minimum_balance($(this));
                    calculate_and_set_price();
                    set_amount_remaining($(this).val() * 1);
                });
                

                //Loads the MLS list per state
                $("#state").change(function(){
                    var mls_state = $("#state").val();
                    $("#MLS").load("/products/_mls_list/"+mls_state+"/ option");
                    $("#MLS").removeAttr("disabled");
                }); 

                //If search advertising is clicked adds the cost
                $("#search_advertising").click(function(){
                    if($("#search_advertising:checked").length > 0){
                        $(".third p:eq(1)").slideDown();
                        $("#advertising_cost").removeAttr("disabled");
                        search_ad = true;
                        search_ad_price = $("#advertising_cost").val() * 1;
                        calculate_and_set_price();
                        amount_remaining = $("#advertising_cost").val() * 1;
                    } else {
                        $("#advertising_cost").attr("disabled", "disabled");
                        $(".budget table").slideUp().remove();
                        $(".budget").next(".other_zip").remove();
                        $(".third p:eq(1)").slideUp().attr("checked", "");
                        search_ad = false;
                        calculate_and_set_price();
                        amount_remaining = 0;
                    }
                })

                //IF Distribute your budget by search is clicked 
                //this function enables the zip search form
                $("#search_advertising_zip").click(function(){
                    if($("#search_advertising_zip:checked").length > 0){
                        $(this).parent("p").find('.zip').removeAttr("disabled");

                    } else {

                        $(this).parent("p").find('.zip').attr("disabled", "disabled");
                    }   
                });


                //Attaches the zip functionality to the keyup event
                //on each subsquent zip search field creation
                $('.zip').live("keyup", function(){
                    if(this.zip !== $(this).val()){
                        if($(this).val().length * 1 === 5){
                            this.zip = $(this).val();
                            get_zip_areas($(this));
                            $(this).attr("disabled", "disabled");
                        }
                    }
                });

                //Switches the price based on the option selected
                $("input[name='price']").click(function(){
                    calculate_and_set_price();
                });


                //The get request for the promo code
                //case insensitive
                $("#promo_code").bind("keypress", function(){
                    setTimeout(function(){
                        if($("#promo_code").val().length === 7 && promo_code !== true){
                            var code = $("#promo_code").val();
                            code = code.toUpperCase();
                            $.get("/products/_promotional_code/"+$("#url_title").text()+"/"+code+"/", function(html){
                                set_promo_code($(html));
                            });
                        }
                        }, 5);
                    })

                    /*-----------------------------------
                    // These functions compensate for Firefox which keeps values 
                    // filled in
                    //------------------------------------*/

                    //This makes sure that if something stick around on the form
                    // that everything is setup correctly
                    $(".total_price").text(extract_price($("input[name='price']:checked").val()));
                    $("#total").val(extract_price($("input[name='price']:checked").val()));


                    if($("#state").val() !== ""){
                        var mls_state = $("#state").val();
                        $("#MLS").load("/products/_mls_list/"+mls_state+"/ option");
                        $("#MLS").removeAttr("disabled");
                    }

                };
                $("#print_receipt").click(function(){window.print();});
            }); 