//NOTE: requires jquery

function am_getRecords() {
  //TODO: make this
  var result = $.ajax({
    url: 'http://www.inglisforcongress.com/imanager/proxy/Articles.getArticles',
    data: {},
    type: 'POST',
    async: false
  });
   var articles = eval(result.responseText);
  
  //sort articles descending
  articles.sort(function(a,b) { 
    var aD = Date.parse(a.date); 
    var bD = Date.parse(b.date); 
    return aD > bD ? -1 : (aD < bD ? 1 : 0); });
  
  return articles;
}

/**
 * Show the top x articles
 * @param obj the selector or object to use as the container 
 * @param num The number of articles to show
 * @return
 */
function am_showResults(obj, num) {
  //set the container
  var container = obj;
  if( typeof obj == 'string' ) {
    container = document.getElementById(obj);
    if( !container ) {
      container = $(obj)[0];
    }
  }
  
  //get the data from the server
  var articles = am_getRecords();
  
  //clear the container
  container.innerHTML = '';
  
  for( var i = 0; i < articles.length && (i < num || num == 0); i++ ) {
    var a = articles[i];
    
    var disp = $(['<div class="am_news">',
                    '<h3 class="am_title"><a></a></h3>',
                    '<div class="am_pubdate">',
                      '<span class="publisher"></span>',
                      '<span class="separator"> - </span>',
                      '<span class="date"></span>',
                    '</div>',
                    '<div class="am_content"></div>',
                  '</div>'].join(''));
    
    //get the date
    var HOUR = 60*60*1000;
    var now = new Date();
    var d = Date.parse(a.date)
    var diff = now.getTime() - d;
    if( diff < HOUR ) {
      //show minutes
      var displayDate = parseInt(diff / (60 * 1000)) + ' minutes ago'
    } else if( diff < 24 * HOUR ) {
      //show hours
      displayDate = parseInt(diff/HOUR);
      if( displayDate == 1 ) {
        displayDate += ' hour ago'
      } else {
        displayDate += ' hours ago'
      }
    } else {
      //show the date
      var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      var date = new Date(d);
      displayDate = MONTHS[date.getMonth()] +' '+ date.getDate() +', '+ date.getFullYear();
    }
    
    //populate the stuff
    disp
      .find('.am_title a')
        .html(a.title)
        .attr('href', a.url)
        .attr('target', '_blank')
      .end()
      .find('.publisher')
        .html(a.publisher)
      .end()
      .find('.date')
        .html(displayDate)
      .end()
      .find('.am_content')
        .html(a.description);
    
    $(container).append(disp);
  }
}
