﻿(function ($) {

    var methods = {

        //
        //  INIT SEARCH
        //

        init: function (options) {

            return this.each(function () {

                var $this = $(this),
                    data = $this.data('homeSearch');


                //  plugin hasn't been initialized 
                if (!data) {

                    //
                    //  SETTINGS
                    //

                    //  default settings
                    var settings = {
                        search_results: '.home_results',
                        search_box: '.home_search',
                        update: true
                    };

                    //  merge settings if available
                    if (options)
                        $.extend(settings, options);

                    //
                    //  SEARCH DATA
                    //            

                    $this.data('homeSearch', {
                        target: $this,
                        settings: settings,
                        priceFrom: 140,
                        priceTo: 300,
                        bedrooms2: false,
                        bedrooms3: false,
                        bedrooms4plus: false,
                        bathrooms1: false,
                        bathrooms2: false,
                        bathrooms3: false,
                        singleStorey: false,
                        doubleStorey: false,
                        lotWidthFrom: 7,
                        lotWidthTo: 25,
                        singleGarage: false,
                        doubleGarage: false,
                        hideInvalid: false
                    });
                    var data = $this.data('homeSearch');

                    //
                    //  INITIALISE SLIDERS
                    //

                    var min_price = Number($(data.settings.search_box).find('.slider_min_price').val());
                    var max_price = Number($(data.settings.search_box).find('.slider_max_price').val());
                    
                    $(data.settings.search_box).find('.slider_price').slider({
                        from: min_price,
                        to: max_price,
                        step: 1000,
                        limits: false,
                        dimension: 'K',
                        skin: 'round_plastic',
                        calculate: function (value) {
                            return '$' + value.toString().substring(0, 3);
                        },
                        onstatechange: function (value) {

                            var values = value.split(';');

                            //  check if values have changed
                            if (data.priceFrom != values[0] ||
                                data.priceTo != values[1]) {

                                //  update hidden field
                                $('.slider_price').parent().find("input[type='hidden']:first").val(value);

                                //  update values and render results
                                data.priceFrom = values[0];
                                data.priceTo = values[1];
                                $this.homeSearch('render');

                            }
                        }
                    });

                    //  initialise lot width
                    $(data.settings.search_box).find('.slider_lot_width').slider({
                        from: 7,
                        to: 25,
                        step: 1,
                        limits: false,
                        dimension: 'm',
                        skin: 'round_plastic',
                        onstatechange: function (value) {

                            var values = value.split(';');

                            //  check if values have changed
                            if (data.lotWidthFrom != values[0] ||
                                    data.lotWidthTo != values[1]) {

                                //  update hidden field
                                $('.slider_lot_width').parent().find("input[type='hidden']:first").val(value);

                                //  update values and render results
                                data.lotWidthFrom = values[0];
                                data.lotWidthTo = values[1];
                                $this.homeSearch('render');

                            }

                        }
                    });

                    //
                    //  INITIALISE CHECKBOXES
                    //

                    //  bedrooms checkboxes
                    var change_bedrooms = function () {

                        var quantity = $(this).parent().find('label').text();

                        //  update values
                        switch (quantity) {
                            case "2": data.bedrooms2 = $(this).is(':checked'); break;
                            case "3": data.bedrooms3 = $(this).is(':checked'); break;
                            case "4+": data.bedrooms4plus = $(this).is(':checked'); break;
                        }

                        //  render results
                        $this.homeSearch('render');

                    };
                    $(data.settings.search_box).find('.checkboxes_bedrooms :checkbox').bind('click', change_bedrooms);

                    //  bedrooms checkboxes
                    var change_bathrooms = function () {

                        var quantity = $(this).parent().find('label').text();

                        //  update values
                        switch (quantity) {
                            case "1": data.bathrooms1 = $(this).is(':checked'); break;
                            case "2": data.bathrooms2 = $(this).is(':checked'); break;
                            case "3": data.bathrooms3 = $(this).is(':checked'); break;
                        }

                        //  render results
                        $this.homeSearch('render');

                    };
                    $(data.settings.search_box).find('.checkboxes_bathrooms :checkbox').bind('click', change_bathrooms);

                    //  stories checkboxes
                    var change_storeys = function () {

                        var quantity = $(this).parent().find('label').text();

                        //  update values
                        switch (quantity) {
                            case "Single": data.singleStorey = $(this).is(':checked'); break;
                            case "Double": data.doubleStorey = $(this).is(':checked'); break;
                        }

                        //  render results
                        $this.homeSearch('render');

                    };
                    $(data.settings.search_box).find('.checkboxes_storeys :checkbox').bind('click', change_storeys);


                    //  garages checkboxes
                    var change_garages = function () {

                        var quantity = $(this).parent().find('label').text();

                        //  update values
                        switch (quantity) {
                            case "1": data.singleGarage = $(this).is(':checked'); break;
                            case "2": data.doubleGarage = $(this).is(':checked'); break;
                        }

                        //  render results
                        $this.homeSearch('render');

                    };
                    $(data.settings.search_box).find('.checkboxes_garages :checkbox').bind('click', change_garages);

                }

            });



        },

        //
        //  DATA ACCESS
        //

        setValue: function (key, value) {
            $(this).data('homeSearch')[key] = value;

            switch (key) {
                case '':

                    break;
            }

        },

        getValue: function (key) {
            return $(this).data('homeSearch')[key];
        },

        //
        //  DATA ACCESS
        //

        hideInvalid: function (key, value) {
            $(this).homeSearch('setValue', 'hideInvalid', true);
            $(this).homeSearch('render');
        },

        showInvalid: function (key) {
            $(this).homeSearch('setValue', 'hideInvalid', false);
            $(this).homeSearch('render');
        },

        //
        //  RENDER RESULTS
        //

        render: function () {

            var $this = $(this),
                data = $this.data('homeSearch');

            if (data.settings.update) {

                var results = $(data.settings.search_results).find('li.result');
                if (results.length) {

                    //
                    //  CRITERIA PREPARATION
                    //

                    //  prepare bedroom criteria
                    var bedroom_criteria = new Object();
                    if (data.bedrooms2 || data.bedrooms3 || data.bedrooms4plus) {
                        if (data.bedrooms2) bedroom_criteria.has2 = true;
                        if (data.bedrooms3) bedroom_criteria.has3 = true;
                        if (data.bedrooms4plus) bedroom_criteria.has4 = true;
                        bedroom_criteria.filtered = true;
                    }

                    //  prepare bathroom criteria
                    var bathroom_criteria = new Object();
                    if (data.bathrooms1 || data.bathrooms2 || data.bathrooms3) {
                        if (data.bathrooms1) bathroom_criteria.has1 = true;
                        if (data.bathrooms2) bathroom_criteria.has2 = true;
                        if (data.bathrooms3) bathroom_criteria.has3 = true;
                        bathroom_criteria.filtered = true;
                    }

                    //  prepare storey criteria
                    var storey_criteria = new Object();
                    if (data.singleStorey || data.doubleStorey) {
                        if (data.singleStorey) storey_criteria.hasSingle = true;
                        if (data.doubleStorey) storey_criteria.hasDouble = true;
                        storey_criteria.filtered = true;
                    }

                    //  prepare garage criteria
                    var garage_criteria = new Object();
                    if (data.singleGarage || data.doubleGarage) {
                        if (data.singleGarage) garage_criteria.hasSingle = true;
                        if (data.doubleGarage) garage_criteria.hasDouble = true;
                        garage_criteria.filtered = true;
                    }

                    //
                    //  RESULTS DISPLAY
                    //

                    //  hide / show results based  on search criteria
                    results.each(function () {

                        var unavailable = false;
                        var price = Number($(this).attr('price'));
                        var bedrooms = Number($(this).attr('bedrooms'));
                        var bathrooms = Number($(this).attr('bathrooms'));
                        var garages = Number($(this).attr('garages'));
                        var storeys = Number($(this).attr('storeys'));
                        var studies = Number($(this).attr('studies'));
                        var lotWidth = Number($(this).attr('lot_width'));

                        //  filter out prices
                        if (Number(data.priceFrom) > price || Number(data.priceTo) < price)
                            unavailable = true;

                        //  filter out bedrooms
                        if (bedroom_criteria.filtered) {
                            switch (bedrooms) {
                                case 2:
                                    if (bedroom_criteria.has2 == null)
                                        unavailable = true;
                                    break;
                                case 3:
                                    if (bedroom_criteria.has3 == null)
                                        unavailable = true;
                                    break;
                                case 4:
                                    if (bedroom_criteria.has4 == null)
                                        unavailable = true;
                                    break;
                            }
                        }

                        //  filter out bathrooms
                        if (bathroom_criteria.filtered) {
                            switch (bathrooms) {
                                case 1:
                                    if (bathroom_criteria.has1 == null)
                                        unavailable = true;
                                    break;
                                case 2:
                                    if (bathroom_criteria.has2 == null)
                                        unavailable = true;
                                    break;
                                case 3:
                                    if (bathroom_criteria.has3 == null)
                                        unavailable = true;
                                    break;
                            }
                        }

                        //  filter out storeys
                        if (storey_criteria.filtered) {
                            switch (storeys) {
                                case 1:
                                    if (storey_criteria.hasSingle == null)
                                        unavailable = true;
                                    break;
                                case 2:
                                    if (storey_criteria.hasDouble == null)
                                        unavailable = true;
                                    break;
                            }
                        }

                        //  filter out storeys
                        if (garage_criteria.filtered) {
                            switch (garages) {
                                case 1:
                                    if (garage_criteria.hasSingle == null)
                                        unavailable = true;
                                    break;
                                case 2:
                                    if (garage_criteria.hasDouble == null)
                                        unavailable = true;
                                    break;
                            }
                        }

                        //  filter out prices
                        if (Number(data.lotWidthFrom) > lotWidth || Number(data.lotWidthTo) < lotWidth)
                            unavailable = true;

                        //
                        var price = Number($(this).attr('price'));

                        // fade out if required
                        if (unavailable) {

                            if (!$.browser.msie) {
                                if (!data.hideInvalid)
                                    $(this).addClass('result_disabled').show().css({ opacity: 0.2 });
                                else
                                    $(this).addClass('result_disabled').hide();
                            } else {
                                if (!data.hideInvalid)
                                    $(this).addClass('result_disabled').show().find('.invalid_result').show().css({ opacity: 0.8 });
                                else
                                    $(this).addClass('result_disabled').hide();


                            }


                            //  add link handler
                            $(this).find('a.name, a.facade').bind('click', function (e) {
                                e.preventDefault();
                                $(this).blur();
                                return false;
                            });

                        } else {


                            if (!$.browser.msie) {
                                if (!data.hideInvalid)
                                    $(this).removeClass('result_disabled').css({ opacity: 1 });
                                else
                                    $(this).removeClass('result_disabled').css({ opacity: 1 }).show();
                            } else {

                                if (!data.hideInvalid)
                                    $(this).removeClass('result_disabled').find('.invalid_result').hide();
                                else
                                    $(this).removeClass('result_disabled').show().find('.invalid_result').hide();
                            }

                            //  remove link handler
                            $(this).find('a.name, a.facade').unbind('click');

                        }


                    });

                    //
                    //  RESULT COLUMNS
                    //

                    var current_column = 1;

                    //  no longer need to reindex as hide invalid option removed
                    if (false) {
                        if (data.hideInvalid) {

                            //  reindex visible items
                            results.each(function () {
                                $(this).removeClass('column_1 column_2 column_3');
                                if ($(this).is(":visible")) {
                                    $(this).addClass('column_' + current_column);
                                    current_column++;
                                    if (current_column == 4) current_column = 1;
                                }
                            });

                        } else {

                            //  reindex all items
                            results.each(function () {
                                $(this).removeClass('column_1 column_2 column_3');
                                $(this).addClass('column_' + current_column);
                                current_column++;
                                if (current_column == 4) current_column = 1;
                            });

                        }
                    }

                    //  update available designs
                    var available_designs = $(data.settings.search_results).find('li:not(.result_disabled)').length;
                    if (available_designs == 0)
                        $('.design_count').html('0 Home Designs Available. Use the filter options to refine your search');
                    else if (available_designs != 1)
                        $('.design_count').html(available_designs + ' Home Designs Available');
                    else
                        $('.design_count').html('1 Home Design Available');

                }
            }

        }

    };

    $.fn.homeSearch = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.homeSearch');
        }

    };

})(jQuery);
