/* stop caching this */
/* Globals & Initializers */
var dataStore = new Hash();
var id = 1;

var twitterLogin = "cdownie";
var bloggerLogin1 = "devChrisDev";
var bloggerLogin0 = "chrisCourier";
var twitterDataSuffix  = "_td";
var twitterErrorSuffix = "_te";
var bloggerDataSuffix  = "_bd";
var bloggerErrorSuffix = "_be";
var dataLoadedEvent = "custom:dataLoaded";
var tabNames = [ "quick", "twitter", "blog", "dev", "resources", "about" ];

google.load("gdata", "1.x");
google.setOnLoadCallback(powerOn);
helpWindowContents = [ {"title":"About the Quick Feed", 
                        "content":"This shows all of the most recent blog entries, twitter updates, and general content I've created on the internet."},
                       {"title":"About Twitter",
                        "content":"These are my 10 most recent twitter entries."},
                       {"title":"About The Chris Courier",
                        "content":"These are my 5 most recent entries in my personal blog, The Chris Courier."},
                       {"title":"About DevChrisDev",
                        "content":"These are my 5 most recent entries in the developer blog of this site."},
                       {"title":"About Resources",
                        "content":"This section will be a resource for all things I'm experienced enough in to be a resource for. You might think that's everything, but everything is a lot to write about. So it will be start off being limited to Ultimate Frisbee and Mafia. When I implement it. I mean."},
                       {"title":"About About",
                        "content":"This section doesn't need explanation. Because it's the one that explains everything. And here I am explaining that. Just so we're clear.<br><br>I mean I will do that once I implement this section."} ];

/* DOM-dependent funciton calls */
// creates a window on the page.
function createWindow(titleText, contentText, linkText, linkUrl) {
  if(titleText == "") {
    titleText = "&nbsp;";
  }
  var window = new Element('div', {'class':'window', 'id':('window' + id++)});
  var topPart = new Element('div', {'class':'top'});
  var titleArea = new Element('div', {'class':'text'});
  var linkArea = new Element('span', {'class':'from'}).update("from ");
  if(linkText != "" && linkUrl != "") {
    linkArea.insert({bottom:new Element('a', {'href':linkUrl, 'target':'_blank'}).update(linkText) });
  }
  titleArea.insert({bottom:new Element('span', {'class':'title'}).update(titleText)});    
  if(linkText != "" && linkUrl != "") {
    titleArea.insert({bottom:linkArea});
  }
  // maybe put title in span, content in p? 
  topPart.insert({bottom:new Element('div', {'class':'left'}) });
  topPart.insert({bottom:new Element('div', {'class':'right'}) });
  topPart.insert({bottom:titleArea});
  window.insert({bottom:topPart});
  window.insert({bottom:new Element('div', {'class':'content'}).update(contentText) });
  window.insert({bottom:new Element('div', {'class':'bottomBar'}) });
  
  $$("#magicContainer .righthalf").first().insert({bottom:window});
  return window;  
}

/* Blogger section */
// Gets a BloggerService Object
var bloggerServiceObject = false;
function setupMyService() {
  if (bloggerServiceObject) {
    return bloggerServiceObject;
  }
  google.gdata.client.init(handleInitError)
  bloggerServiceObject = new google.gdata.blogger.BloggerService("downchrisdownmainsite");
  return bloggerServiceObject;
}

// How to fail if google's lib doesn't support the given browser
function handleInitError(error) {
  if(navigator.userAgent.include("Safari") ||
     navigator.userAgent.include("Opera")) {
    return;
  }
  alert(error.message)
}

function loadBloggerData(id, uri) {
  setupMyService().getBlogFeed(
    uri,
    function(entryRoot) {
      dataStore.set(id+bloggerDataSuffix, entryRoot);
      dataStore.set(id+bloggerErrorSuffix, null);
      document.fire(dataLoadedEvent);
      //createBloggerWindow(id);
    },
    function(error) {
      dataStore.set(id+bloggerDataSuffix, null);
      dataStore.set(id+bloggerErrorSuffix, error);
      document.fire(dataLoadedEvent);
    });
}


/* Twitter section */
// get Twitter data in the store.
function loadTwitterData(id) {
  var requestUrl = "/py/command.py?cmd=tw";
  new Ajax.Request(requestUrl, {
    method: 'get',
    onSuccess: function(transport) {
      dataStore.set(id+twitterDataSuffix, eval(transport.responseText));
      document.fire(dataLoadedEvent);
      //createTwitterWindow(id);
    },
    onFailure: function(transport) {
      dataStore.set(id+twitterErrorSuffix, transport);
      document.fire(dataLoadedEvent);
    }
  });
}


// loads all data into the dataStore
function loadAllData() {
  var devChrisDevUri = "http://www.blogger.com/feeds/8420677910741044237/posts/default";
  var chrisCourierUri = "http://www.blogger.com/feeds/23088588/posts/default";
  loadTwitterData(twitterLogin);
  loadBloggerData(bloggerLogin0, chrisCourierUri);
  loadBloggerData(bloggerLogin1, devChrisDevUri);
}

// Page has loaded, Google has loaded, initialize the page!
function powerOn() {
  // connect events to navigation window
  connectNavigation();
  connectImages();

  // set up a listener to the custom event

  // enable to start doing stuff on load.  !@#$%
  document.observe(dataLoadedEvent, funnelCatcher)
  loadAllData();
}

// fill the window if we have all the data, or if it errored out
function funnelCatcher(event) {
  if(!dataStore.get(twitterLogin + twitterDataSuffix) && !dataStore.get(twitterLogin + twitterErrorSuffix)) {
    return;
  }
  if(!dataStore.get(bloggerLogin0 + bloggerDataSuffix) && !dataStore.get(bloggerLogin0 + bloggerErrorSuffix)) {
    return;
  }
  if(!dataStore.get(bloggerLogin1 + bloggerDataSuffix) && !dataStore.get(bloggerLogin1 + bloggerErrorSuffix)) {
    return;
  }
  
  loadTabFromUrl();
}

function createTwitterWindows(twitterLogin, count) {
  var twitterData = dataStore.get(twitterLogin + twitterDataSuffix);
  if(twitterData) {
    for(var i = 0; i < count && i < twitterData.size(); ++i) {
      createWindow("Current Status", twitterData[i].text, "Twitter", "http://twitter.com/cdownie")
    }
  }
}

function createBloggerWindows(bloggerLogin, count) {
  var bloggerData = dataStore.get(bloggerLogin + bloggerDataSuffix);
  if(bloggerData) {
    var devEntries = bloggerData.feed.getEntries();
    for(var i = 0; i < count && i < devEntries.size(); ++i) {
      var entry = devEntries[i];
      var win = createWindow(entry.getTitle().getText(), 
                    entry.getContent().getText(),
                    bloggerData.feed.getTitle().getText(),
                    bloggerData.feed.getHtmlLink().getHref());
      var bottomBar = win.down(".bottomBar");
      var links = entry.getLinks();
      for (var j = 0; j < links.size(); ++j) {
        if(links[j].getType() == "text/html") {
          var thisLink = links[j];
          var linkText = (thisLink.getRel() == "alternate" ? "Permalink" : thisLink.getTitle());
          bottomBar.insert({bottom:new Element('a', {'href':thisLink.getHref(), 'class':thisLink.getRel()}).update(linkText)});
        }
      }
      // add stuff to the comments section
      /*
      var comments = win.down(".comments");
      comments.insert({bottom:new Element('span', {'class':'commentCount'}).update('2 comments') })
      comments.insert({bottom:new Element('input', {'type':'text', 'class':'textbox', 'disabled':'disabled', 'value':'Comments currently disabled.'}) });
      var commentButton = new Element('input', {'type':'submit', 'class':'button', 'value':'Comment'});
      commentButton.observe("click", function(e){addComment(entry, "testing the comments");})
      comments.insert({bottom: commentButton});
      */
    }
  }

}

/* Populate Window Section */
/* Each of these funcitons will fill the window with appropriate data */
// populate the main window with data.
function fillWindow() {
  createTwitterWindows(twitterLogin, 1);
  createBloggerWindows(bloggerLogin0, 1);
  createBloggerWindows(bloggerLogin1, 1);
}

function fillTwitterWindows() {
  createTwitterWindows(twitterLogin, 10);
}
function fillPersonalBlogWindows() {
  createBloggerWindows(bloggerLogin0, 5);
}
function fillDevBlogWindows() {
  createBloggerWindows(bloggerLogin1, 5);
}

/* Layout Switcher section */
// Switches between the various css styles.
function toggleLayout() {
  var xpStyle = "css/xp.css";
  var osxStyle = "css/osx.css";
  var linkNode = $("layoutStyle");
  if(linkNode.href.endsWith(osxStyle)) {
    linkNode.href = xpStyle;
  } else {
    linkNode.href = osxStyle;
  }
}

/* Navigation Hooks */
function connectNavigation() {
  pageList = $$("#nav0 .content ul li");
  for (var i = 0; i < pageList.size(); i++) {
    pageList[i].observe("click", function(e){selectNavLink(e.element());})
  }
}
function selectNavLink(navLink) {
  $$("#nav0 .content ul li.selected")[0].removeClassName("selected");
  navLink.addClassName("selected");
  loadTab(navLink.previousSiblings().size());
}
function selectNavByIndex(index) {
  var navSet = $$("#nav0 .content ul li");
  if (index < navSet.size()) {
    selectNavLink(navSet[index]);
  }
} 

function loadTab(index) {
  chosenHelpWindow = helpWindowContents[index];
  allWindows = $$("#magicContainer .righthalf .window");
  for(var windex = 0; windex < allWindows.size(); windex++) {
    allWindows[windex].remove();
  }
  var newWindow = createWindow(chosenHelpWindow.title, chosenHelpWindow.content, "", "");
  newWindow.id = "helpWindow";
  switch(index) {
    case 0: fillWindow(); break;
    case 1: fillTwitterWindows(); break;
    case 2: fillPersonalBlogWindows(); break;
    case 3: fillDevBlogWindows(); break;
    default:
      break;
  } 
  updateUrlData(index);
}

/* Static image hooks */
function connectImages() {
  $("gamercard").observe('click', function(e) {location.href = "http://profile.mygamercard.net/El+Fireberto";});
  $("cssCard").observe('click', function(e) {location.href = "http://jigsaw.w3.org/css-validator/";});
  $("xhtmlCard").observe('click', function(e) {location.href = "http://validator.w3.org/check?uri=referer";});
}

/* Handles exposing state in the URL */
function loadTabFromUrl() {
  var targetTab = getTabNumber(window.location.hash)
  
  if(targetTab != 0) {
    selectNavByIndex(targetTab);
  } else {
    loadTab(targetTab);
  }
}

// given a string of query paramaters, returns the tab that it specifies.
function getTabNumber(hashData) {
  if (hashData.blank() || hashData == "#") {
    return 0;
  }
  if (hashData[0] == "#") {
    hashData = hashData.substring(1);
  }
  
  var dataObject = hashData.toQueryParams();
  
  if (dataObject.tab == null) {
    return 0;
  }
  
  // tab can either be a number or a word.
  var tabIndex = parseInt(dataObject.tab);
  
  if (tabIndex.toString() == "NaN") {
    tabIndex = tabNames.indexOf(dataObject.tab.toLowerCase());
  }
  
  if (tabIndex < 0 || tabIndex > tabNames.size()) {
    return 0;
  }
  return tabIndex;
}

function updateUrlData(tabNumber) {
  var tabString = "";
  
  if (tabNumber < 0) {
    tabString = tabNames.first();
  } else if (tabNumber > tabNames.size()) {
    tabString = tabNames.last()
  } else {
    tabString = tabNames[tabNumber];
  }
  
  window.location.hash = "tab=" + tabString;
}

