var dd_reg = new Array();
function dd_register(abbr, ref)
{
  dd_reg[abbr] = ref;
}

function dd_ajax_callback(result)
{
  p = dd_reg[result.extra.data];
  p.populate(result, p);
}

function dd_user_query(_abbr, _query)
{
  p = dd_reg[_abbr];
  p.dd_query(p.abbr, _query, p);
}


function dd_browser(_id, _abbr, _query)
{
  dd_register(_abbr, this);
  
  this.id = _id;
  this.abbr = _abbr;
  this.query = _query;
  
  this.img_w = 120;
  this.img_h = 90;
  
  this.loading = false;
  
  ///////////////////
  
  this.dd_refresh = function(p)
  {
    if (p.loading)
      jQuery(p.id+" .dd_loading").show();
    else
      jQuery(p.id+" .dd_loading").hide();
  }
  
  ///////////////////
  
  this.dd_query = function (_abbr, _query, p)
  {
    p.loading = true;
    p.abbr = _abbr;
    p.query = _query;
    
    jQuery(p.id+' .dd_results').empty();
    p.dd_refresh(p);
    
    var url = '/?pf='+p.query+'&img_w='+p.img_w+'&img_h='+p.img_h+'&extra='+_abbr;
    jQuery.getJSON(url, dd_ajax_callback);
    
  }
  
  
  this.populate = function(data, p)
  {
    // mcam - p is the trouble here as the async ajax return is anonymous
    p.loading = false;
    
    jQuery(p.id+' .dd_results').empty();
    
    jQuery.each(data, function(i,item){
      
      if (item.id != "HIDDEN" && item.id != "EXTRA" && item.id != "SKIP")
      {
        var r = "";
        r += "<div class='dd_item' id='dd_item_"+item.id+"'>";
        r += "  <div class='thumb'>";
        r += "    <a href='" + item.prod_url + "'>" + item.img_hero + "</a>";
        r += "  </div>";
        r += "  <div class='title'>"+item.title+"</div>";
        r += "  <div class='blurb'>"+item.blurb+"</div>";
        r += "  <div class='link'><a href='" + item.prod_url + "'>Read More</a></div>";
        r += "</div>";
        
        jQuery(r).appendTo(p.id+' .dd_results');
      }
      
    });
    
    p.dd_refresh(p);
  }
  
  this.dd_query(this.abbr, this.query, this);
  
}


