// ---------- start of jQuery document.ready() ----------
  
$(document).ready(function() {   

  // Fade In Content
  $("#content").fadeIn(1500);

  // Slider
  var $slider = $("#slider");
  if ($slider[0]) {
    $slider.nivoSlider({
      effect: 'fade',
      startSlide: 0,
      directionNav: false,
      keyboardNav: false,
      pauseOnHover: false
    });
  }

  // Carousel
  var $carousel = $("#carousel");
  if ($carousel[0]) {
    $carousel.jcarousel({ scroll: 4 });
  }

  // External Links
  $("a[rel=externo]").live('click', function() {
    window.open(this.href);
    return false;
  });

  // Action Form Contact
  $(".contact-us > form").submit(function() {
    return sendContact();
  });

  // Latest tweets
  var twitterAccounts = ['zigotto', 'marcelofraga', 'jtadeulopes', 'edercosta', 'fdantas87', 'greboide'];

  $.each(twitterAccounts, function() {
    var twitter = this;
    var feed = "http://twitter.com/statuses/user_timeline/"+ twitter +".rss";
    var query = "select * from feed where url='"+ feed +"' LIMIT 1";
    var url   = "http://query.yahooapis.com/v1/public/yql?q="+ encodeURIComponent(query) +"&format=json&callback=?"; // Forming the URL to YQL

    $.getJSON(url, function(data) {
      var tweet = data.query.results.item;
      var link = $("<a>").attr({ href: "http://twitter.com/"+ twitter, rel: "externo" }).text("@"+ twitter).addClass("label").addClass("twitter");
      var text = $("<p>").text(tweet.description.replace(twitter +": ", ""));
      $(".latest-"+ twitter).append(link).append(text);
    });
  });

  // Latest blogs updates
  $blogsContent = $(".blogs");
  if ($blogsContent[0]) {
    var blogs = ['http://jlopes.zigotto.com.br/feed']; // Blogs
    var feeds = []; // Feeds

    $.each(blogs, function(i) {
      var query = "select * from feed where url='"+ this +"' LIMIT 5"; // Forming the query
      var url   = "http://query.yahooapis.com/v1/public/yql?q="+ encodeURIComponent(query) +"&format=json&callback=?"; // Forming the URL to YQL
    
      $.getJSON(url, function(data) {
        // Item exists in RSS and entry in ATOM feeds
        $.each(data.query.results.item || data.query.results.entry, function() {
          feeds.push(this);
        });

        // Sort entry feeds
        feeds.sort(function(a, b) {
          var a = new Date(a.pubDate).format('timeStamp');
          var b = new Date(b.pubDate).format('timeStamp');

          if (a > b)
            return -1;
          if (a < b) 
            return 1;

          return 0;
        });

        if (blogs.length == (i + 1)) {
          $.each(feeds, function(i) {
            if (i < 5) {
              var $link = $('<a>').attr({ href: this.link, rel: "externo" }).text(this.title);
              var $h2 = $('<h2>').append($link);
              $blogsContent.append($h2);
            }  
          });
        }
      });
    });
  }


});

// ---------- end of jQuery document.ready() ----------

