// from: http://delusion.fi/twitter.js
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];

  var parsed_date = Date.parse(time_value);

  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);

  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if(delta < 60) {
     return 'less than a minute ago';
  } else if(delta < 120) {
     return 'about a minute ago';
  } else if(delta < (45*60)) {
     return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (90*60)) {
     return 'about an hour ago';
  } else if(delta < (24*60*60)) {
     return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
     return '1 day ago';
  } else {
     return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

$(document).ready(function() {
  $("#carousel").cycle();

  // shows the apple marker for the currently selected item or its ancestor
  var imageMapping = {
    "Nutrition": 'yellow-pear.png',
    "Our Promise": 'fat-red-apple.png',
    "About Us": 'yellow-pear.png',
    "Kidfresh Cares": 'green-apple.png',
    "News": 'yellow-pear.png',
		"Our Blog": 'red-apple.png',
    "Contact Us": 'fat-red-apple.png',
    'default': 'red-apple.png'
  };

  $("#main-navigation .current_page_item, #main-navigation .current_page_ancestor").each(function() {
    var title = $(this).find('a').attr('title');

    var imageSrc = $("#main-navigation").attr('data-selected-image-prefix');
    imageSrc += (imageMapping[title] == undefined) ? imageMapping['default'] : imageMapping[title];

    $(this).prepend('<img src="' + imageSrc + '">');
  });
  $("#main-navigation img").load(function() {
    $(this).css({ 'position': 'absolute', 'top': '5px', 'padding-left': $(this).parent().width()/2 - $(this).width()/2 }).show();
  });

  // automatically build in-page navigation from section headers
  $("#in-page-navigation").each(function() {
    var nav = $(this);
    $("article h2").each(function() {
      var id = $(this).text().replace('!','').replace(/[^A-Za-z0-9]/g,'-').toLowerCase();
      $(this).attr('id', id);
      nav.append('<li><a href="#' + id + '">' + $(this).text() + '</a></li>');
    })
  });

  // load latest 3 tweets on the news page
  $.jTwitter('Kidfreshfoods', 3, function(posts) {
    for(var ii = 0; ii < posts.length; ii++) {
      $('#twitter-list').append('<li><em>' + relative_time(posts[ii].created_at) + '</em><br>' + posts[ii].text + '</li>');
    }
  });

  // support for lightboxing, and also some custom code to reposition the 'close' box for the mailing list signup
  $("a[rel^='prettyPhoto']").prettyPhoto({
    changepicturecallback: function() {
      $(".pp_content:contains(Email)").css({ height: (parseInt($(".pp_content").height()) - 35) + 'px' }).find(".pp_details").css({ position: 'absolute', top: 0 });
    }
  });

  // if we're loading the news page, let's fill in the passed in zip code and submit the form
  setTimeout(function() {
    var zipCode;
    if (zipCode = $.query.get('zipCode')) {
      $("#addressInput").val(zipCode);
      searchLocations();
    }
  }, 2000);

  // add 'Search' text as placeholder to search form (done this way so we don't have to override WP function)
  $("#s").attr('placeholder', 'Search')

  // fancy tooltips for KF promises
  $('#sidebar-promise-content.promise-list a[title]').qtip({
    style: {
      width: 150,
      background: "#f79d34",
      color: "#fff",
      tip: true,
      border: { radius: 5, color: "#f79d34" }
    },
    position: {
      corner: { target: 'leftMiddle', tooltip: 'rightMiddle' }
    }
  });

  // IE!
  $(":last-child").addClass('last-child');
  $(":first-child").addClass('first-child');

  // placeholder support
  $("input[type=text]").placeholder();

  // placeholder for emailing with 'share this'
  $(".at15t_email").live('click', function() {
    $("#at_msg").val("I thought that you might be interested by this: " + window.location.href);
    return true;
  });

  // open facebook URLs in new window.
  $(".widget_rss a").attr('target', '_blank');
});

