/*
 *
 * jQuery queued ajax
 * requires jQuery ajaxQueue
 *
 * jQueryDate: 12:05 PM 11/17/2010
 * jQueryAuthor: Greg Henle
 *
 */
(function($){
  var feedIdx = 0;
  var tweetIdx = 0;
  var latestTweetId = null;

  function formatText(index, panel)
  {
    return index + "";
  };
  function newsFeedSuccess(xml)
  {
    var html = '';

    switch( $(xml).children('feed').children('title').text() )
    {
      case "The Director's Blog":
        var title = "Director's Blog";
        break;
      case "News":
        var title = "Newsroom";
        break;
      default:
        var title = $(xml).children('feed').children('title').text();
        break;
    }

    html += '<h3><a href="' + $(xml).children('feed').children('link[rel="alternate"]').attr('href') + '" target="_blank">' + title + '</a></h3><hr style="margin:0" />';
    $(xml).find('entry:eq(' + feedIdx + ')').each(function() {
      // right now, we are assuming +0000 UTC
      var d1 = $(this).find('updated').text().match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).+/i);
      var d2 = new Date();
      d2.setUTCFullYear( parseInt( d1[1] ));
      d2.setUTCMonth( parseInt( d1[2] )-1 ); // src:1-12, arg:0-11
      d2.setUTCDate( parseInt( d1[3] ));
      d2.setUTCHours( parseInt( d1[4] ));
      d2.setUTCMinutes( parseInt( d1[5] ));
      d2.setUTCSeconds( parseInt( d1[6] ));

      var txt = $(this).find('summary').text();

      html += '<div class="latest_news_block">';
      html += '<div class="latest_news_headline"><a href="' + $(this).find('link').attr('href') + '">' + $(this).find('title').text() + '</a></div>';
      html += '<div class="latest_news_news">' + ((txt.length>140)? txt.substring(0,140)+'...':txt) + '</div>';
      html += '<div class="latest_news_date">' + d2.toLocaleDateString().replace(/^[^,]+,\s/, '') + '</div>';
      html += '</div>';
    });
    $('#latest_news_body').append(html);
    return true;
  };
  function tweetFeedSuccess(json)
  {
    if( typeof(json.results[tweetIdx])=='undefined' )
      tweetIdx = 0;

    if( typeof(json.results[0])!='undefined' && json.results[0].id!=latestTweetId)
    {
      tweetIdx = 0;
      latestTweetId = json.results[0].id;
    }

    if( typeof(json.results[tweetIdx])!='undefined' )
    {
      var d2 = new Date(json.results[tweetIdx].created_at);


      var html = '';
      html += '<h3><a href="http://twitter.com/uscensusbureau" target="_blank">Twitter</a></h3><hr style="margin:0" />';
      html += '<div class="latest_news_block">';
      html += '<div class="latest_news_headline"><a href="http://twitter.com/uscensusbureau/status/' + json.results[tweetIdx].id_str + '">' + json.results[tweetIdx].text + '</a></div>';
      html += '<div class="latest_news_date">' + d2.toLocaleDateString().replace(/^[^,]+,\s/, '') + '</div>';
      html += '</div>';
      $('#latest_news_body').append(html);
    }
    return true;
  };
  function sliderFeedSuccess(xml)
  {
    $("#slider").append('<ul></ul>');

    $(xml).find("slide").each(function() {
      $("#slider ul").append( "\n" + '<li><img src="' +
        $(this).children("image").text() + '" alt="' +
        $(this).children("headline").text() + '" /><span class="infoBox"><h3>' +
        $(this).children("headline").text() + '</h3>' +
        $(this).children("description").text() + '<br /><br /><a href="' +
        $(this).children("link").text() + '"><img src="img/see_more_arrow.jpg" alt="Read More" style="border:none;" /></a></span></li>'
      );
    });

    $('.anythingSlider').anythingSlider({
      easing: "easeInOutExpo",        // Anything other than "linear" or "swing" requires the easing plugin
      autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
      delay: 8000,                    // How long between slide transitions in AutoPlay mode
      startStopped: false,            // If autoPlay is on, this can force it to start stopped
      animationTime: 900,             // How long the slide transition takes
      hashTags: true,                 // Should links change the hashtag in the URL?
      buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
      pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
      navigationFormatter: formatText, // Details at the top of the file on this use (advanced use)
      forwardText: "&gt;",            // Link text used to move the slider forward
      backText: "&lt;"                // Link text used to move the slider back
    });
  }

  $(document).ready(function() {
    $('#slider').data('ajaxQueue',[
      {
        type: 'POST',
        url: 'xml/slideshow.xml',
        dataType: 'xml',
        cache: false,
        success: sliderFeedSuccess
      }
    ]).ajaxQueue();

    $('#latest_news_body').data('ajaxQueue',[
      {
        type: 'GET',
        url: 'http://search.twitter.com/search.json?q=from%3Auscensusbureau&callback=?',
        dataType: 'json',
        cache: false,
        success: tweetFeedSuccess
      },
      {
        type: 'POST',
        url: '/news/atom.xml',
        dataType: 'xml',
        cache: false,
        success: newsFeedSuccess
      }
    ]).ajaxQueue({
      refresh:true,
      refresh_fn:function(){
        feedIdx = ++feedIdx%5;
        tweetIdx = ++tweetIdx%5;
      },
      spinner:'/2010census/img/spinner.gif'
    });
  });
})(jQuery);
