(function($){  
    $.fn.lb_result_getter = function(search_string, options) {

        var defaults = {  
            sites       : [
                { id : 'waitrose', title: 'Waitrose', div : '#waitrose-results', img : 'http://www.waitrosewine.com/jl_assets/header/wwd-logo.gif', url:"http://www.waitrosewine.com/Search/Search.aspx?SearchTerm=", 'match': /found (\d+) products/, matchlocation: 1, xpath: "//span[@id='lblSearchResultsFound']" },
                { id : 'tesco', title: 'Tesco', div : '#tesco-results', img : '/img/tesco.png', url:"http://www.tesco.com/wine/product/search/default.aspx?searchBox=", 'match': /We found * (\d+)/, matchlocation: 1, xpath: "//h2[@class='searchResults']" },
                { id : 'sainsburys', title : 'Sainsbury\'s', div : '#sainsburys-results', img : '/img/sainsburys.png', url : 'http://www.sainsburys.co.uk/sol/global_search/global_result.jsp?bmForm=global_search&GLOBAL_DATA._searchType=0&GLOBAL_DATA._search_term1=german%20wine%20', match : /\<strong>(\d+)\<\/strong>/, matchlocation: 1, xpath: "//div[@class='panelContentHeader clearFloat']/p/strong[1]"},
                { id : 'majestic', title: 'Majestic', div : '#majestic-results', img : 'http://www.majestic.co.uk/assets/majestic/images/logo.gif', url:"http://www.majestic.co.uk/find/category-is-Wine/category-is-Germany/keyword-is-", xpath : "//div[@class='paging clearfix']/div[1]/p", 'match': /There are (\d+) products/, matchlocation: 1 },
                { id : 'oddbins', title : 'Oddbins', div : '#oddbins-results', img : 'http://www.oddbins.com/images/logoXmas.gif', url : 'http://www.oddbins.com/products/advancedSearch.asp?SearchPriceFrom=&SearchPriceTo=&GroupCode1=WIN&GroupCode2=&SearchType=advsearch&x=47&y=9&Search=', xpath: "//div[@id='contentCentered']/div[2]/h3", match : / produced (\d+)/, matchlocation: 1},
                { id : 'averys', title : 'Averis Wine Merchants', div : '#averys-results', img : 'http://www.averys.com/images/averys/logo.png', url : 'http://www.averys.com/search.pasp?showresults=straight&find_fine=false&ff=false&find_type=&find_style=&find_gen_region=GER&find_region=&find_price=&find_grape=&find_vintage=&find_food=&brand=AVERYS&mscssid=1B533F659C3F4B81BB7090CC750A43AF&find_spec=', xpath : '//td/h3', match : /We have found (\d+)/, matchlocation: 1},
                { id : 'laithwaites', title : 'Laithwaites Wine', div : '#laithwaites-results', img : 'http://www.laithwaites.co.uk/images/LAIT/brand.gif', url : 'http://www.laithwaites.co.uk/searcharticles.aspx?brand=LAIT&mscssid=BE4710B0CF2E44078E715170AB0BDE98&find_spec=german+wine+', xpath : "//div[@class='prodimg']", only_count : true },
                { id : 'marksandspencer', title : 'Marks and Spencer', div : '#marksandspencer-results', img : '', url : 'http://www.marksandspencer.com/gp/search?node=&x=0&y=0&field-keywords=', 'match' : /(\d+) results in/, matchlocation : 1, xpath: "//span[@class='big padLeft10px']" }
                //{ id : 'berry' , title : 'Berry Bros', url : 'http://www.bbr.com/shopping/list?narrow_F=Y&clear_form_F=Y&search_type_F=keyword-search&search_both_F.x=0&search_both_F.y=0&keywords_F=', xpath : "//ul[@id='searchResultSummary']/li[1]" }
               ],
            output_format : '[%result%] results <a href="[% url %]" target="_blank">View wines</a>',
            show    : ['waitrose', 'tesco', 'sainsburys', 'majestic', 'oddbins', 'averys', 'laithwaites', 'marksandspencer']
        };

        options     = $.extend(defaults, options);
        
        var obj = '';
        
        function write_html($site, $results) {

            var text = '';        

            if( typeof($site.div) != 'undefined' ) {
                text = options.output_format.replace('[%result%]', $results);
                text = text.replace('[% url %]',$site.url);
                
                $($site.div).html(text);
                
            if( $results < 1 ) {
                $($site.div).parent().slideUp(300);
            }

            } else {
                text = options.output_format.replace('[%result%]', $results);
                
                if( typeof($site.img) != 'undefined' )
                    text = text.replace('[%img%]', '<img src="' + $site.img + '" alt="' + $site.title + '" />');
                else
                    text = text.replace('[%img%]', $site.title + ' ');
    
                text = text.replace('[%title%]', $site.title);
    
                obj.append(text);
            }
        }
        
        function parse($site) {
            var url     = $site.url + search_string.replace(/ /gi, '%20').replace('"', '\"');

            $site.url = url;

            var query   = 'SELECT * FROM html WHERE url="' + url + '"';
            
            if ( typeof($site.xpath) != undefined ) query += ' AND xpath="' + $site.xpath + '"';

            $.ajax({
                type        : 'get',
                url         : 'http://query.yahooapis.com/v1/public/yql?format=xml&q=' + escape(query) + '&callback=?',
                dataType    : 'jsonp',
                success     : function(data, textStatus) {    
                    var results = 0;

                    if( typeof(data.results[0]) != 'undefined' ) {
                        var target  = data.results[0].replace('\n', ' ');
                        
                        if( typeof($site.only_count) && $site.only_count )
                            results = data.results.length;
                        else {
                            results     = target.match($site.match);

                            if( results == null ) results = 0;
                            else results     = eval(results[$site.matchlocation]);
                        }
                    }

                    write_html($site, results);
                },
                error       : function() {
                    write_html($site, 0);
                }
            });
            
        }   // end parse function

        return this.each(function() {
            obj = $(this);  
            var body = obj.html();

            for ( var k = 0; k < options.show.length; k++) {
                var site_id = options.show[k];

                for( var j = 0; j < options.sites.length; j++ ) {
                    if( site_id == options.sites[j].id )
                        parse(options.sites[j]);
                }
            }

        });

    };
})(jQuery);