(function($) {

   $.fn.pipe = function(options) {

      var opts = $.extend({modal: false, path: 'value.items'}, $.fn.pipe.defaults, options);

      return this.each(function() {
         var $this = $(this);
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

         if (o.id) o.url = o.url + '?_id=' + o.id + '&_render=json&_callback=?';

         $this.html('<div class="loading"><img src="/img/app.labore/loading.gif"/></div>');

         //$.getJSON(o.url + '?_id=' + o.id + '&_render=json&_callback=?', function (rss) {
         $.getJSON(o.url, function (rss) {   
     		   //$(rss.value.items).each(function (index) {
     		   var data = rss;
     		   if (o.path) {
     		      var path = o.path.split('.');                 		      
     		      $(path).each(function(index) {           
     		         if (data[path[index]]) data = data[path[index]];
     		      });
  		      }                                                      
            $(data).each(function (index) {
               var item = this;
               var template = o.template;
               var pattern = new RegExp('{[a-z0-9\:\._?]+}', 'gi');
               var matches = o.template.match(pattern);
               var param = '';
               $(matches).each(function(index) {
                  pattern = new RegExp('[a-z0-9\:\._?]+');
                  param = pattern.exec(matches[index]);
                  param += ''; // to string
                  var value = item[param];
                  var splitted = param.split('.');
                  if (splitted.length > 1) {
                     value = item;
                     $(splitted).each(function(index) {
                        value = value[splitted[index]]
                     });             
                  }
                  template = template.replace('{' + param + '}', value);
               });  
               $('div.loading', $this).remove();
               $this.append(template);
               if (o.modal) {
                  $('a[rel=modal]').fancybox({
                     'zoomSpeedIn': 0,
                     'zoomSpeedOut': 0,
                     'hideOnContentClick': true
                  });                  
               }
     	      });
         });
      });
   };

   $.fn.pipe.defaults = {
      url: 'http://pipes.yahoo.com/pipes/pipe.run',
      render: 'json',
      callback: '?'
   };

})(jQuery);
