var heparxml = null;
$.ajax({
  async: false,
  url: '/data/hepar.xml',
  type: 'GET',
  dataType: 'xml',
  success: function(xml){ heparxml = xml }
});

function fetchXml(xml)
{
  var params = $(xml).find('params');
  var items = $(xml).find('item');
  
  $('#discover_all_advice_list li').remove();
  
  var healthy_advice_items = [];
  var html = '';
  $(params).find('category').each(function(loop){
    here = $(this);
    var itemsMenu = $(items).filter(function(){
       return $('category', this).attr('id') == here.attr('id');
    });
    healthy_advice_items = $.merge(healthy_advice_items, itemsMenu);
    

    html      += '<li class="' + ((loop%2) ? 'odd' : 'even') + '" id="list_'+ here.attr('id') +'">';
    html      += '  <h3>';
    html      += '    <img src="' + here.attr('src') + '" class="png_fix" alt="' + here.text() + '" />';
    html      += '  </h3>';
   
    if ('true' === $(params).find('random').attr('value'))
    {
      itemsMenu = $.makeArray(itemsMenu).sort(function() {return 0.5 - Math.random()}).slice(0, $(params).find('visible').attr('value'));
    }
    if ($(params).find('visible').attr('value') > 0)
    {
      itemsMenu = $.makeArray(itemsMenu).slice(0, $(params).find('visible').attr('value'));
    }
    
    if (itemsMenu.length > 0)
    {
      html    += '  <ul>';
      
      $(itemsMenu).each(function(){
        
         html += '    <li class="png_fix">';
         html += '      <a href="' +  $(this).find('link').attr('href') + '">';
         html += '        ' + $(this).find('title').text();
         html += '      </a>';
         html += '    </li>';
        
      });
      
      html    += '  </ul>';
    }
    html      += '</li>';
    
    $('#discover_all_advice_list').html(html);

  });

  var item = healthy_advice_items[Math.floor(Math.random()*(healthy_advice_items.length-1))];
  $('#healthy_advice_block .healthy_advices_subtitle').text($(item).find('title').text());
  $('#healthy_advice_block .healthy_advices_citation p').text($(item).find('text').text());
  //$('#healthy_advice_block .bottom_button a span span span span').text($(item).find('link').text());
  $('#healthy_advice_block .bottom_button a').attr('href', $(item).find('link').attr('href'));

}


(function($){
  $(document).ready(function(){
    fetchXml(heparxml);
    heparxml = null;
  });
})(jQuery);


