(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;

          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
	// smartresize
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('scroll', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartscroll');



/**
 * Loads a list of properties, taking account of offset as required
 **/
function loadProperties(params)
{

    // default blockUI to no css
    $.blockUI.defaults.css = {}

    // Block UI
    // different styles for infinite loading, or filters
    if (params['infinite']) {
        $('#page').block({
            message: 'Loading more properties...',
            css: {
                top: '90%',
                left: '480px'
            },
            overlayCSS: {
                backgroundColor: '#ccc',
                opacity:         0.3
            },
            fadeIn: 0,
            fadeOut: 500,
            centerY: false,
            centerX: false
        });
    }
    else {
        $('#page').block({
            message: 'Updating property list...',
            overlayCSS:  {
                backgroundColor: '#ccc',
                opacity:         0.5
            },
            fadeIn: 0,
            fadeOut: 500
        });
    }



    $.getJSON(
        '/incs/ajax/property_list.php',
        {
            listOffset: params['offset'],
            fname:      params['filterName'],
            fvalue:     params['filterVal']
        },

        function(data) {

            if (data.resTotal == 0) {
                
                $('#property_list').remove();

                // if no match p doesn't exist
                if ($('p.no_match').length < 1) {
                    $('<p></p>').attr('class','no_match').html('No properties match your filters').appendTo('#property_list_container');
                }

                $('p.showing').hide();
                $('#page').unblock();
            }

            else {
                
                $('p.showing').show();

                $('p.no_match').remove();
                
                if($('#property_list').length < 1) {
                    var listHTML = $('<ul></ul>').attr('id','property_list');
                    $('#property_list_container p.show_top').after(listHTML);
                    //appendTo('#property_list_container p.show_top');
                }

                $.each(data.items, function(i,item){

                    var itemID = 'property_' + (params['offset'] + i + 1);

                    var listItem = $("<li></li>")
                                   .attr("id", itemID)
                                   .addClass('clearfix')
                                   .addClass(item.status.query);

                    listItem
                        .html(
                            '<a class="property_thumb" href="' + item.url + '">' + item.thumb +
                            '<em>' + item.status.title + '</em>' + '</a>' +
                            '<div class="property_details">' +
                            '<h3 class="clearfix"><a href="' + item.url + '">' +
                            item.title + '</a><strong>' + item.price_string + '</strong></h3>' +
                            '<p><strong>' + item.bedrooms + ' Bedrooms, ' + item.type + '</strong></p>' +
                            '<p>' + item.desc + '</p>' +
                            '</div>'
                        );

                    listItem.appendTo("#property_list");

                });

                // remove loading message
                $('#loader').remove();

                // Figure out showing total
                var showingNum = data.perPage + params['offset'];
                if (showingNum > data.resTotal) {
                    showingNum = data.resTotal;
                }

                // if showing element does exist, update
                if ($("p.showing").length > 0) {

                    var showString = 'Showing: <strong>' + showingNum + '</strong> (of ' + data.resTotal + ') properties matching your filters';

                    $('p.showing').show().find('span').html(showString);


                }

                // if end of the line, add element
                if(data.items.length >= data.resTotal || (params['offset'] + data.perPage) >= data.resTotal) {
                    var endSpan = $('<span></span>').attr('id','propertyEnd');
                    $("#property_list_container").append(endSpan);
                }
                else {
                    $("#propertyEnd").remove();
                }

                $('#page').unblock();
            }
        }
    );

}


function infiniteScroll() {

    if ($("#propertyEnd").length == 0) {

        var offset = parseInt(0);
        // get id of last item
        offset = parseInt($('#property_list li:last').attr('id').replace(/\D/g,''));

        params = {
            'offset': offset,
            'filterName': false,
            'filterVal': false,
            'infinite': true
        };

        loadProperties(params);
    }
}

$(window).smartscroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()){
        infiniteScroll();
    }
});


$(document).ready(function() {

    $('p.paging').remove();
    $('#property_filters button').remove();

    $('#property_filters select').change( function() {

        var filterName = $(this).attr('name').replace('filters_','');
        var filterVal = $(this).val();

        var offset = parseInt(0);

        // mark label as active

        if (filterName=='sort_by') {
            $(this).parent().addClass('active');
        }
        else {
            var selIndex = $(this).get(0).selectedIndex;

            if (selIndex != 0) {
                $(this).parent().addClass('active');
            }
            else {
                $(this).parent().removeClass('active');
            }
        }
        
       // var selectedOption = $(this).find('option:selected')
        //alert($(this).find('option:selected').html());

        $('#property_list li').remove();
        $("#propertyEnd").remove();

        params = {
            'offset': offset,
            'filterName': filterName,
            'filterVal': filterVal
        };

        loadProperties(params);

    });

    $('p.showing a').click(function(){

        window.scrollTo(0,0);
        return false;
    });
});
