(function ($) {
    $.fn.rmx_listing = function (options) {
        var settings = $.extend({
            id: null,                                  // [integer or array]  broker id or ids
            lang: 'fr',
            url: '/webservice/KModRemax_Listing.axd',
            showSold: false,
            completed: function () { }
        }, options);

        function _build_listing_url() {
            return settings.url + "?id=" + settings.id + "&lang=" + settings.lang.toUpperCase();
        }

        function _build_inscription_html(elm) {
            return ($('<li>').attr('id', $(elm).find('ID').text())
                                .attr('href', $(elm).find('DetailURL').text())
                                .attr('price', $(elm).find('Price').text())
                                .attr('bedrooms', $(elm).find('Bedrooms').text())
                                .attr('bathrooms', $(elm).find('Bathrooms').text())
                                .attr('waterrooms', $(elm).find('Waterrooms').text())
                                .attr('genre', $(elm).find('Field[key=genrefield]').text())
                                .attr('city', $(elm).find('Field[key=cityfield]').text())
                                .attr('picture', $(elm).find('Picture').text().replace('107X75', 'lightbox'))
                                .attr('class', 'listing-property')
                    .append(
                        $('<div>').attr('class', 'description').append($(elm).find('Description').text())
                    )
                    );

        }

        return this.each(function (i, widget) {
            $.ajax({
                url: _build_listing_url(),
                type: 'GET',
                dataType: 'xml',
                success: function (data, textStatus, jqXhr) {
                    //alert(data);
                    $(widget).append('<ul></ul>')
                    $(data).find('Inscription').each(function (index, elm) {
                        if (!settings.showSold) {
                            if ($(elm).find('MetaData').attr('isSold') == 'true') {
                                return
                            }
                        }
                        $(widget).children(0).append(_build_inscription_html(elm));
                    });

                    settings.completed();
                }
            });

        });
    }
})(jQuery);

