function beautifyPassageReferenceText(startPassage, endPassage) {
  var startBook, endBook, startChapter, endChapter, startVerse, endVerse;
  if (startPassage) {
    var components = startPassage.split(",");
    startBook = components[0];
    startChapter = components[1];
    startVerse = components[2];
  }
  if (endPassage) {
    var components = endPassage.split(",");
    endBook = components[0];
    endChapter = components[1];
    endVerse = components[2];
  }
  if (startBook && endBook && startBook === endBook) {
    if (startChapter === endChapter) {
      if (startVerse === endVerse) {
        return startBook + " " + startChapter + ":" + startVerse;
      } else {
        return startBook + " " + startChapter + ":" + startVerse + "-" + endVerse;
      }
    } else {
      return startBook + " " + startChapter + ":" + startVerse + "-" + endChapter + ":" + endVerse;
    }
  } else if (startBook && endBook) {
    return startBook + " " + startChapter + ":" + startVerse + "-" + endBook + " " + endChapter + ":" + endVerse;
  } else {
    return "Various scripture";
  }
}

function resetStartingPointMessages() {
  var target = $('#startingPointMessagesList');
  target.html('Loading...');
}

var startingPointMessagesCache;
function fetchStartingPointMessages() {
  var display = function(json) {
      startingPointMessagesCache = json;
      var target = $('#startingPointMessagesList');
      target.empty();
      $.each(json, function(i, item) {
        var pubDate = new Date(item.datetime*1000);
        var tmpMonthDay = dateFormat(pubDate, "mmm dd");
        var tmpYear = dateFormat(pubDate, "yyyy");
        var html = "<li class='ditem'><span>"+tmpMonthDay+"<br/><strong>"+tmpYear+"</strong></span><a href='http://www.sovgracefrederick.org/media/"+encodeURI(item.file_name)+"'>"+item.title+"</a><em>"+item.preacher+"</em><br/>"+beautifyPassageReferenceText(item.start_passage, item.end_passage)+" (Part of the "+item.series_name+" series)</li>";
        target.append(html);
      });
    };
  if (!startingPointMessagesCache) {
    $.ajax({
      type: "GET",
      url: "/sermons.php?f=starting-point",
      dataType: "json",
      success: display
    });
  } else {
    display(startingPointMessagesCache);
  }
}

function resetSundayMessages() {
  var target = $('#sundayMessagesList');
  target.html('Loading...');
  sundayMessagesCache = [];
}

var sundayMessagesCache = [];
var sundayMessagesAreLoading = false;
function fetchSundayMessages(page) {
  var display = function(json) {
    sundayMessagesCache = sundayMessagesCache.concat(json);
    sundayMessagesAreLoading = false;
    var target = $('#sundayMessagesList');
    target.empty();
    $.each(sundayMessagesCache, function(i, item) {
      if (item) {
        var pubDate = new Date(item.datetime*1000);
        var tmpMonthDay = dateFormat(pubDate, "mmm dd");
        var tmpYear = dateFormat(pubDate, "yyyy");
        var html = "<li class='ditem'><span>"+tmpMonthDay+"<br/><strong>"+tmpYear+"</strong></span><a href='http://www.sovgracefrederick.org/media/"+encodeURI(item.file_name)+"'>"+item.title+"</a><em>"+item.preacher+"</em><br/>"+beautifyPassageReferenceText(item.start_passage, item.end_passage)+" (Part of the "+item.series_name+" series)</li>";
        target.append(html);
      }
    });
    if (json.length > 0) {
      $("<a></a>").html("More").attr('href','javascript:void(0)')
        .click(function(){
		if (!sundayMessagesAreLoading) {
			sundayMessagesAreLoading = true;
			$(this).addClass("disabled");
			fetchSundayMessages(page+1);
		}
	}).appendTo($("<li></li>").addClass("pagingItem").appendTo(target));
    }
  };
  $.ajax({
    type: "GET",
    url: "/sermons.php?f=list&r=10&p="+page,
    dataType: "json",
    success: display
  });
}

function resetFindASermonMessages() {
  var search = function() {
    if (!findASermonMessagesAreLoading) {
      findASermonMessagesCache = [];
      findASermonMessagesAreLoading = true;
      fetchFindASermonMessages(0);
    }
  };
  findASermonMessagesAreLoading = false;
  $('#findASermonMessagesList').empty();
  $('#findASermonSearchButton').click(search);
  $('#findASermonFilter').keyup(function(e){if (13 == e.keyCode){search();}}).val('').focus();
}

var findASermonMessagesAreLoading = false;
var findASermonMessagesCache = [];
function fetchFindASermonMessages(page) {
  var display = function(json) {
    findASermonMessagesCache = findASermonMessagesCache.concat(json);
    findASermonMessagesAreLoading = false;
    var target = $('#findASermonMessagesList');
    target.empty();
    if (findASermonMessagesCache.length > 0) {
      $.each(findASermonMessagesCache, function(i, item) {
        if (item) {
          var pubDate = new Date(item.datetime*1000);
          var tmpMonthDay = dateFormat(pubDate, "mmm dd");
          var tmpYear = dateFormat(pubDate, "yyyy");
          var html = "<li class='ditem'><span>"+tmpMonthDay+"<br/><strong>"+tmpYear+"</strong></span><a href='http://www.sovgracefrederick.org/media/"+encodeURI(item.file_name)+"'>"+item.title+"</a><em>"+item.preacher+"</em><br/>"+beautifyPassageReferenceText(item.start_passage, item.end_passage)+" (Part of the "+item.series_name+" series)</li>";
          target.append(html);
        }
      });
      if (json.length > 0) {
        $("<a></a>").html("More").attr('href','javascript:void(0)')
          .click(function(){
		if (!findASermonMessagesAreLoading) {
			findASermonMessagesAreLoading = true;
			$(this).addClass("disabled");
			fetchFindASermonMessages(page+1);
		}
	}).appendTo($("<li></li>").addClass("pagingItem").appendTo(target));
      }
    } else {
      target.html('<em>We couldn\'t find any sermons that match your search.</em>');
    }
  };
  var textQuery = $('#findASermonFilter').val();
  $.ajax({
    type: "GET",
    url: "/sermons.php?f=search&q="+encodeURIComponent(textQuery)+"&r=5&p="+page,
    dataType: "json",
    success: display
  });
}

$(function(){
  /* NAVIGATION */
  $("#container").append('<a class="select-slide" id="bottom-left-select-1" href="#/resources">Select</a>');
  $("#container").append('<div class="overlay" id="bottom-left-overlay-1"></div>');
  $("#container").append('<a class="select-slide" id="bottom-left-select-2" href="#/resources">Select</a>');
  $("#container").append('<a class="select-slide" id="middle-left-select" href="#/stories">Select</a>');
  $("#container").append('<a class="select-slide" id="middle-rght-select" href="#/about">Select</a>');
  $("#container").append('<a class="select-slide" id="bottom-rght-select-1" href="#/church-life">Select</a>');
  $("#container").append('<a class="select-slide" id="bottom-rght-select-2" href="#/church-life">Select</a>');
});

var int = self.setInterval("navigate()",1000);
var initiated = false;
$(document).trigger("ready");

function subnavigate(section, subsection) {
  if (subsection == "starting-point-messages")
    resetStartingPointMessages();
  if (subsection == "sunday-messages")
    resetSundayMessages();
  if (subsection == "find-a-sermon")
    resetFindASermonMessages();
  tabClick = $('a[href$="' + subsection + '"]');
  $("ul.tabs li a").removeClass("selected-tab-link");
  tabClick.addClass("selected-tab-link");
  tabname = subsection;
  tabClick.parent().parent().parent().children("div.tab-content").children("div.selected-tab").fadeOut(200, function() {
    $(this).removeClass("selected-tab");
    $("div#" + tabname).fadeIn(300, function() {
      $(this).addClass("selected-tab");
      if (subsection == "starting-point-messages")
        fetchStartingPointMessages();
      if (subsection == "sunday-messages")
        fetchSundayMessages(0);
    });
  });
};

function navigate() {
    
    url = location.href;
    if(url.search("#") > -1) {
      url = url.split("#/");
      // If there's a subsection
      if(url[1]) {
        if(url[1].search("/") > -1) {
              
          url = url[1].split("/");
          section = url[0];
          subsection = url[1];
        // If there's only a top-level section
        } else {
          section = url[1];
          subsection = false;
        };
        
        // Animate primary section
        if($('a[href$="' + section + '"]').length > 0 ) {
          moveToBack = $("div.selected").attr("id");
          moveToFront = $('a[href$="' + section + '"]');
              
          front = $("#" + section + " div.shadow div.fade").html();
          back = $("div.selected div.shadow div.fade").html();
          
          $("#" + section + " div.shadow div.fade").fadeOut(200, function() {
            $("div.selected").attr("id",section);
            $("#" + section + " div.shadow div.fade").html(back);
            $("#" + section + " div.shadow div.fade").fadeIn(300);
          });
          $("div.selected div.shadow div.fade").fadeOut(200, function() {
            $("#" + section).attr("id",moveToBack);
            $("div.selected div.shadow div.fade").html(front);
            $("div.selected div.shadow div.fade").fadeIn(300, function() {
              if(subsection) {
                subnavigate(section, subsection);
              };
            });
            $(document).trigger("ready");
          });
              
          moveToFront.attr("href","#/" + moveToBack);
              
          window.clearInterval(int);
          initiated = true;        
          
        };

        if(subsection) {
          subnavigate(section, subsection);
        } else if (section == "resources") {
          subnavigate(section, "sunday-messages");
        };
      };

    } else {
      window.clearInterval(int);
      initiated = true;
    };
};

$.address.init(function(event) {
}).change(function(event) {
  if(initiated == true) {
    navigate();
  };
});



