﻿var homeSearch =
{
    city: null,
    communityID: null,
    home_selected: false,
    elevation_selected: false,
    communities: {},
    elevations: {},
    home: {},
    reload_enabled: true,
    ajax_results: false,
    results_by_model_id: {},
    homes_on_page: 8,
    first_run: true,
    init: function() {
        $("#ctl00_Main_city_select").change(function() {
            if ($(this).val() != "none") {
                homeSearch.city = $(this).val();

                homeSearch.communityID = null;
                homeSearch.getCommunities();
                homeSearch.reloadData();
            }
            else {
                homeSearch.city = null;
            }
        });

        // sort change reload
        $('#sort').val('price').change(function() {
            homeSearch.reloadData();
        });

        // process the city if the user reloaded
        // if ($("#ctl00_Main_city_select").val() != "none") {
        homeSearch.city = $("#ctl00_Main_city_select").val();
        // check if community is selected
        //alert(SelectedCommunity);
        if (SelectedCommunity != 0) {
            homeSearch.communityID = SelectedCommunity;
        }
        homeSearch.getCommunities();
        homeSearch.reloadData();
        //        }
        //        else {//none selected - get all


        //        }
        $("#community_select").change(function() {
            if ($(this).val() != "all") {
                homeSearch.communityID = $(this).val();
            }
            else {
                homeSearch.communityID = null;
            }
            homeSearch.reloadData();
        });
        // Prepare price range slider
        $("#price-slider-range").slider({
            range: true,
            min: 150,
            max: 900,
            values: [150, 900],
            slide: function(event, ui) {
                $("#price_range").val('$' + ui.values[0] + 'k - $' + ui.values[1] + 'k');
            },
            change: function() {
                homeSearch.reloadData();
            }
        });

        $("#price_range").val('$' + $("#price-slider-range").slider("values", 0) + 'k - $' + $("#price-slider-range").slider("values", 1) + 'k');


        // Prepare sq ft slider
        $("#size-slider").slider({
            //range: true,
            min: 700,
            max: 3000,
            value: 700,
            slide: function(event, ui) {
                $("#size").val(ui.value);
            },
            change: function() {
                homeSearch.reloadData();
            }
        });
        $("#size").val($("#size-slider").slider("value"));

        // radio button click handlers       
        $('input[type=radio]').click(function() {
            homeSearch.reloadData();
        });



        // next step button - check if home has been selected
        $('.next_step a').click(function(e) {
            if (!homeSearch.home_selected) {
                e.preventDefault();
                $('#error_message').text('Please select a home before going to the next step.').slideDown('fast');
            }
        });
    },
    reloadData: function() {
        // only do a reload on the first run. This prevents a reload when we set the default values for the sliders
        //if (!c_step2.reload_enabled) return;

        // set home selected to false so user can't go to next step
        //c_step2.home_selected = false;

        $('#initial_msg').hide();
        $('#available_options_info').show();

        //if (homeSearch.city == null)// || homeSearch.communityID==null)
        //    return; //don't bother if city & community have not been selected

        // fade out the homes, show the loader
        $('#quick_homestyles').fadeOut('fast');
        $('#loading').show();

        // clear the home count
        $('#available_options').text(0);


        var homeType = $('input[name=home_type]:checked').val();
        if (homeType == "All")
            homeType = "";
        // put our data into an object to send via ajax
        data = {
            city: '',
            projectID: '',
            priceFrom: '150000',
            priceTo: '900000',
            bedrooms: $('input[name=bedrooms]:checked').val(),
            bathrooms: $('input[name=bathrooms]:checked').val(),
            home_type: homeType,
            size: $('#size').val(),
            sort: $('#sort').val()
        };

        if (homeSearch.city != null && homeSearch.city != 'none')
            data.city = homeSearch.city;

        if (homeSearch.communityID != null)
            data.projectID = homeSearch.communityID;

        // grab the price and format as int
        var price = $('#price_range').val().replace(/k/g, '').replace(/$/g, '').replace(' ', '').split('-');
        if (price[0] != null && price[0] != '' && price[0] != undefined) {
            data.priceFrom = price[0] + '000';
        }
        if (price[1] != null && price[1] != '' && price[1] != undefined) {
            data.priceTo = price[1] + '000';
        }
        data.priceFrom = data.priceFrom.replace('$', '');
        data.priceTo = data.priceTo.replace('$', '');

        // Get sort info
        var sort = $('#sort').val();
        if (sort != '-1')
            data.sort = sort;

        // send our request and then process the data when it's successful 
        $.ajax({
            url: '/AjaxServices.asmx/GetQPHomesByFilter',
            type: "POST",
            cache: false,
            dataType: 'json',
            data: (!data ? "{}" : JSON.stringify(data)),
            contentType: "application/json; charset=utf-8",
            success: homeSearch.processResults,
            cache: false
        });

        //console.log(priceFrom, priceTo, bedrooms, bathrooms, home_style);
    },
    processResults: function(msg) {
        var data = msg.d;
        homeSearch.ajax_results = data;

        homeSearch.results_by_model_id = {};

        // add data to our results array so we can look up easier later
        $.each(data, function(i, o) {
            homeSearch.results_by_model_id[o.ModelID] = o;
        });

        // hide loading gif
        $('#loading').hide();

        // unbind click handlers
        $('.select a').unbind();

        // remove the homes
        $('#quick_homestyles').empty();

        // set the number of homes returned
        $('#available_options').text(data.length);

        // if no results, then write a message about that
        if (data.length == 0) {
            $('#error_message').text('The search return 0 results. Please try adjusting the filter options.').fadeIn();
            //$('#results').append('<p class="error">The search returned 0 results. Try adjusting the filter on the right. </p>');
        }
        /*else if (data.length > 500) // if more than 500 results then something is wrong. too many to display, anyways.
        {
        $('#results').append('<p class="error">The search returned ' + data.length + ' results. That is way too many to display here. Try adjusting the filter on the right to narrow down the results. </p>');
        }*/
        else // process the home results
        {

            $('#error_message').hide();

            var c = 0;

            while (c < homeSearch.homes_on_page) {
                if (data[c] == undefined) {
                    // skip it!
                }
                else {
                    // render the home
                    $('#quick_homestyles').append(homeSearch.renderHome(data[c]));

                    // if the home has been selected (saved in session) then add the selected class
                    //                        if (data[c].Selected != undefined)
                    //                            $('#h_' + data[c].ModelID).addClass('selected');

                }

                c++;
            }
        }

        $('#quick_homestyles a').click(homeSearch.selectHome);

        // render pagination based on home data
        homeSearch.renderPagination(data);

        $('#loading').hide();
        $('#quick_homestyles').show();
        $('#elevation_results').hide(); //hide elevations when we get a new home list..
    },
    renderHome: function(home) {
        // home template
        var html = '<li id="h_' + home.ModelID + '"><a style="color:Black" href="Summary.aspx?qp=' + home.QPHomeID + '" id="' + home.ModelID + '"><img src="/home_images/thumbs/' + home.HomeCode + '.jpg" onerror="this.onerror=null;this.src=\'/home_images/thumbs/noimage.jpg\'">' +
                        '<h3 class="model_name">' + home.Name + '</h3>' +
                        '<p class="info"><strong></strong></p>' +
                        '<p>$' + parseInt(home.Price).formatMoney(0, '.', ',') + '</p>' +
                        '<p><strong>Style:</strong> ' + home.HomeType + '</p>' +
                        '<p><strong>Sq Footage:</strong> ' + home.SqFootage + '</p>' +
                        '<p><strong>Bathrooms:</strong> ' + home.Bathrooms + '</p>' +
                        '<p><strong>Bedrooms:</strong> ' + home.Bedrooms + '</p>' +
                        '<p style="height:50px;"><strong>Community:<br></strong> ' + home.Community + '</p></a></li>'; // +
						//'<p><a href="Summary.aspx?qp=' + home.QPHomeID + '" class="button_sml" id="' + home.ModelID + '"><span>View Home</span></a></p></li>';

        return html;
    },
    renderPagination: function(home_list) {
        $('#quick_homestyles_pagination a').unbind();
        $('#quick_homestyles_pagination').empty();

        // get number of pages
        var pages = Math.ceil(home_list.length / homeSearch.homes_on_page);

        if (pages < 1) {
            // don't show any pagination
        }
        else {
            // write out the links to the broweser
            for (i = 1; i <= pages; i++) {
                var pageLink = '<a href="javascript:;" id="p_' + i + '"';
                if (i == 1) {
                    pageLink += 'class="page_selected"';
                }
                pageLink += ' >' + i + '</a> ';
                $('#quick_homestyles_pagination').append(pageLink);
            }
        }

        // pagination click handler
        $('#quick_homestyles_pagination a').click(function(e) {
            e.preventDefault();

            // remove select class from previous one and add to the one that was just clicked
            $('#quick_homestyles_pagination a.page_selected').removeClass('page_selected');
            $(this).addClass('page_selected');

            // get the page # clicked
            var page = $(this).attr('id').replace('p_', '');
            $('#quick_homestyles').hide();
            $('#quick_homestyles').empty();

            // render homes for that page
            var c = homeSearch.homes_on_page * page - homeSearch.homes_on_page;
            var data = homeSearch.ajax_results;

            $('.select a').unbind();

            for (i = c; i < c + homeSearch.homes_on_page; i++) {
                if (data[i] == undefined) {
                    // skip it!
                }
                else {

                    $('#quick_homestyles').append(homeSearch.renderHome(data[i]));

                    // if that home was selected then add a selected class to it
                    if (data[i].selected != undefined)
                        $('#h_' + data[c].ModelID).addClass('selected');
                }
            }

            $('#quick_homestyles a').click(homeSearch.selectHome);

            $('#quick_homestyles').fadeIn();
        });
    },
    getCommunities: function() {
        if (homeSearch.city != "none") {
            $.ajax({
                url: '/AjaxServices.asmx/GetCommunitiesByCity',
                data: "{city:'" + homeSearch.city + "'}",
                type: "POST",
                cache: false,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function(msg) {
                    var data = msg.d;
                    homeSearch.communities = data;
                    $("#community_select").html("");
                    var emptyOption = '<option value="all">All</option>';
                    $("#community_select").append(emptyOption);
                    $.each(data, function(i, o) {
                        var option = '<option value="' + o.ProjectID + '">' + o.Name + '</option>';
                        $("#community_select").append(option);
                    });


                    // check if community is selected
                    if (SelectedCommunity != 0) {
                        $('#community_select').val(SelectedCommunity);
                    }
                },
                error: function(xhr, status, error) {
                    //console.log(xhr, status, error);
                }
            });
        }
        else {
            $("#community_select").html("");
        }
    }
};

// money formatter
Number.prototype.formatMoney = function(c, d, t){var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); };
