// http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
(function($) {
  var cache = [];
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

jQuery(document).ready(function() {
  // Random image
  jQuery.preLoadImages(
    "assets/website/layouts/images/splash1.jpg",
    "assets/website/layouts/images/splash2.jpg",
    "assets/website/layouts/images/splash3.jpg",
    "assets/website/layouts/images/splash4.jpg"
  );
  
  var urls = ["research-services","custom-research","telecom-resources","telecom-maps"];
  var randy = Math.floor(Math.random()*4) + 1;
  jQuery("div.splash img").attr("src", "assets/website/layouts/images/splash"+randy+".jpg").click(function() {
    location.href = urls[randy-1];
  });
  
  // CommsUpdate feed
  jQuery.getJSON('/products/commsupdate/assets/comms_update/homepage.js', { format: "json" }, function(data) {

    jQuery('.headlines').append(jQuery('<p/>').text(data.article_date + " | ").append(jQuery('<a/>').attr(
      'href','/products/commsupdate/').text("Today's Headlines")
      ).append(' | ').append(jQuery('<a/>').attr(
        'href','/subscribe/').text('Subscribe'))
      );
    
    jQuery.each(data.articles, function(i,item){

      flags = jQuery("<div/>").attr("class", "flags");
      
      jQuery("<div/>").attr("class", "headline").append(
          jQuery("<div/>").attr("class", "title").append(jQuery("<a/>").attr("href",item.href).text(item.headline))
        ).prepend(flags).appendTo(".headlines");
      
      jQuery.each(item.country, function(index,country){
        flags.append(jQuery("<a/>").attr("href","/products/commsupdate/lists/country/" + country.slug).attr(
          "title", country.name
        ).append(
          // /products/commsupdate/assets/comms_update/images/flags/
          // jQuery("<img/>").attr("src","/products/commsupdate/assets/comms_update/images/flags/" + country.iso + ".png"
        // ).attr("alt", country.name).attr("width","16").attr("height","11")
        jQuery("<div/>").attr("class","flag-" + country.iso)
        ));
      });

    });
    
    jQuery('.headlines').append(
      jQuery('<div/>').attr("class","homepage-more-news").append(
        jQuery("<a/>").attr("href","/products/commsupdate/").text("More News")
      )
    );
    
  });
  
  // Tumblr feed
  jQuery.getJSON('assets/website/tumblr-homepage.js', { format: "json" }, function(data) {
    tumblr_image = data.posts[0];
    jQuery('.tumblr').append(jQuery('<div/>').attr("class", "image").append(
      jQuery("<a/>").attr("href",tumblr_image['url-with-slug']).append(jQuery('<img/>').attr("width","250").attr("height", Math.round(tumblr_image['height'] / 2)).attr("src", tumblr_image['photo-url-250']).attr("alt", tumblr_image['slug']).attr("border", "0"))
    ));
  });
  
});

