/*********************** OOPSTUDIOS ***********************\
 OOPStudios is not your typical "structured" site like many
  due to the developmental nature of many of my projects.
 As such it's not database driven but rather file driven,
  and I can create a structured look and feel with clever
  use of javascript as well as making it easy to update at
  any time! Bombaclaat!
 This file is the backbone to the site, it should always be
  included with all pages...
\**********************************************************/

  // The main site object
  SITE = {};
  
  // Loads a CSS, JS or JSON file into the head,
  //  or any other file into a specified element
  SITE.include = function (path, id, callback) {
    // Determine the type
    var ext = path.split ("?");
    ext = ext[0].split (".");
    ext = ext[(ext.length-1)];
    ext = ext.toLowerCase ();
    if (!ext) {
      return false;
    }
    // CSS, JS and JSON
    if (ext == "css" || ext == "js" || ext == "json") {
      // OK, add the file to the document...
      if (ext == "css") {
        // CSS
        var ref = document.createElement ("link");
        ref.setAttribute ("rel", "stylesheet");
        ref.setAttribute ("type", "text/css");
        ref.setAttribute ("href", path);
      } else {
        // JS
        var ref = document.createElement ("script");
        ref.setAttribute ("type", "text/javascript");
        ref.setAttribute ("src", path);
      }
      // Write it
      var head = document.getElementsByTagName ("head")[0];
      head.appendChild (ref);
      // Done
      return true;
    // All other files load into the specified element
    } else if (id) {
      // Get the element
      el = document.getElementById (id);
      // Save the callback function?
      if (callback) {
        el.callback = callback;
      }
      // Build a very simple "AJAX" object
      var req = SITE.createXMLHTTPObject ();
      if (!req) {
        return;
      }
      // Request the page
      req.el = el;
      req.open ("GET", path, true);
      req.setRequestHeader ("User-Agent", "XMLHTTP/1.0");
      req.onreadystatechange = function () {
        if (req.readyState != 4) {
          return;
        }
        if (req.status != 200 && req.status != 304) {
          return;
        }
        // Cool, wrie the response into the element
        req.el.innerHTML = req.responseText;
        // Callback?
        if (req.el.callback) {
          req.el.callback (el);
        }
      }
      if (req.readyState == 4) {
        return;
      }
      req.send (null);
    }
  };
  
  // Returns an XMLHTTP object (thanks quirksmode!)
  SITE.XMLHttpFactories = function () {
	  return [
		  function () {return new XMLHttpRequest ()},
		  function () {return new ActiveXObject ("Msxml2.XMLHTTP")},
		  function () {return new ActiveXObject ("Msxml3.XMLHTTP")},
		  function () {return new ActiveXObject ("Microsoft.XMLHTTP")}
	  ];
  };
  SITE.createXMLHTTPObject = function () {
	  var xmlhttp = false;
	  var factories = SITE.XMLHttpFactories ();
	  for (var i=0; i<factories.length; i++) {
		  try {
			  xmlhttp = factories[i] ();
		  }
		  catch (e) {
			  continue;
		  }
		  break;
	  }
	  return xmlhttp;
  };
  
  // Creates a compatibility table
  SITE.compatibility = false;
  // List of browsers
  SITE.browser = {
    FF: ["Firefox",   "firefox"],
    IE: ["MSIE",      "explorer"],
    OP: ["Opera",     "opera"],
    SF: ["Safari",    "safari"],
    CH: ["Chrome",    "chrome"],
    KQ: ["Konqueror", "konqueror"]
  };
  // Statuses
  SITE.statuses = {
    "-1": "broken",
    "0":  "kinda",
    "1":  "works",
    "2":  "degrades"
  }
  // Rating
  SITE.medals = {
    "3": "bronze",
    "2": "silver",
    "1": "gold"
  }
  // Parses an object into a table...
  SITE.loadCompatibility = function () {
    // We got the data?
    if (SITE.compatibility == false) {
      // Nerp
      alert ("This page doesn't have a compatibility table.\n\nIf you think it should, write a comment and tell me so!");
    } else {
      // Get started
      var html = "<h3>Compatibility table</h3>";
      // Is there a note?
      var notes = SITE.compatibility["NOTES"];
      if (notes) {
        html += notes;
      }
      // Open the table
      html += "<table class=\"compatibility\">";
      // Browsers
      for (b in SITE.browser) {
        var browser = SITE.browser[b];
        var compatibility = SITE.compatibility[b];
        // Status & notes
        var status = "unknown";
        var notes = "";
        if (compatibility) {
          if (compatibility["C"] != null) {
            status = SITE.statuses[compatibility["C"]];
          }
          if (compatibility["N"]) {
            notes = compatibility["N"];
          }
        }
        // The row
        html += "<tr>";
        html += "<th><img src=\"/site/browser/" + browser[1] + ".png\" width=\"48\" height=\"48\"><br />" + browser[0] + "</th>";
        html += "<td class=\"" + status + "\"><p>Status: <strong>" + status + "</strong></p>" + notes + "</td>";
        html += "</tr>";
      }
      // Is there a rating?
      var rating = SITE.compatibility["RATING"];
      if (rating) {
        var medal = SITE.medals[rating["C"]];
        var notes = rating["N"] || "";
        // The row
        html += "<tr>";
        html += "<th><img src=\"/site/" + medal + ".png\" width=\"48\" height=\"48\"><br />" + medal + "</th>";
        html += "<td><p>Overall rating: <strong>" + medal + "</strong></p>" + notes + "</td>";
        html += "</tr>";
      }
      // Close the table
      html += "</table>";
      html += "<p><strong>Note:</strong> If you have <em>any</em> comments or criticism about this table, please do write me a comment!</p>";
      // Write it
      var el = document.getElementById ("feedback");
      el.innerHTML = html;
      // Run DLINK
      DLINK.highlight (el);
    }
    // Get your linky hands off me...
    return false;
  };
  
  // Highlight the <pre> tags
  SITE.highlight = function () {
    // Is DLITE loaded?
    if (window.DLITE) {
      // Get all the <pre> tags...
      var pres = document.getElementsByTagName ("PRE");
      for (p=0; p<pres.length; p++) {
        var pre = pres[p];
        // Highlight?
        if (pre.className) {
          var hl = DLITE.highlightString (pre.innerHTML, pre.className);
          pre.innerHTML = "<div>" + hl + "</div>" ;
        } else {
          pre.className = "generic";
          pre.innerHTML = "<div>" + pre.innerHTML + "</div>" ;
        }
      }
    }
  };
  
  // Adds in analytics to the page
  //   Kinda from http://beepinteractive.com/2008/07/02/adding-google-analytics-onload/
  SITE.addGA = function () {
    if (location.host == "oopstudios.com") {
      var gaJsHost  = "https:" == document.location.protocol ? "https://ssl." : "http://www.";
      SITE.include (gaJsHost + "google-analytics.com/ga.js");
      function run_ga () {
        if (typeof _gat == "object") {
          pageTracker = _gat._getTracker ("UA-284758-4");
          // pageTracker._setAllowLinker (true); 
          pageTracker._initData ();
          pageTracker._trackPageview ();
        } else if (i < 20) {
          i++;
          setTimeout (run_ga, 500);
        }
      }
      var i = 0;
      run_ga();
    }
  };
  
  // Comment functions
  SITE.loadComments = function () {
    // Load the comments
    SITE.include ("/site/comments.php?uri=" + location.pathname + "&do=view", "feedback", SITE.onLoadComments);
    // Animation
    var el = document.getElementById ("feedback");
    el.innerHTML = '<p style="text-align: center;"><img src="/site/loading.gif" width="32" height="32" /></p>';
    // No linky!
    return false;
  };
  SITE.onLoadComments = function () {
    // Run DLINK
    var el = document.getElementById ("comment_response");
    DLINK.highlight (el);
    // Run DCODE
    DCODE.removeTag ("LARGE");
    DCODE.removeTag ("HR");
    DCODE.removeTag ("IMG");
    DCODE.removeTag ("YOUTUBE");
    DCODE.activate ("commentBody");
  };
  SITE.onAddComments = function (el) {
    // Get the iframe document
    if (el.contentDocument) {
      iframeDoc = el.contentDocument;
    } else {
      iframeDoc = document.frames["commentFrame"].document;
    }
    // Create an element from its content
    var e = document.createElement ('DIV');
    e.innerHTML = iframeDoc.body.innerHTML;
    // Run DLINK on it
    DLINK.highlight (e);
    // Append it to the comments
    var el = document.getElementById ("comment_response");
    el.appendChild (e);
    // Clear or remove the form?
    var el = document.getElementById ("commentBody");
    el.value = "";
  };
  
  // Add some things before onload
  SITE.include ("/site/doghouse_reset.css");
  SITE.include ("/site/site.css");
  SITE.include ("/dlink/dlink.js"); // See http://oopstudios.com/dlink.php for info
  SITE.include ("/stuff/dlite/dlite/highlight.js");
  SITE.include ("/dcode/dcode/dcode.css");
  SITE.include ("/dcode/dcode/dcode.js");
  
  // Initialises the site "onload"
  SITE.init = function () {
    // If we're in fancy index mode
    var fancyindex = document.getElementById ("fancyindex");
    if (fancyindex) {
      // Append "?dir" to all the folder links
      links = fancyindex.getElementsByTagName ("A");
      for (n=0; n<links.length; n++) {
        link = links[n];
        if (link.href.substring ((link.href.length-1)) == "/") {
          link.href += "?dir";
        }
      }
      // Modify the title
      var tmp = unescape (window.location.pathname);
      document.title = "Index of " + tmp.replace (/\//g, " / ");
      var h1 = document.getElementsByTagName ("h1")[0];
      h1.innerHTML = document.title;
      // For the nav part (think speed)
      fancyindex = true;
    } else {
      // Set the body id
      var body = document.getElementsByTagName ("body")[0];
      body.id = "fileMode";
    }
    // If the nav element exists
    var nav = document.getElementById ("nav");
    if (nav) {
      // Break the path into breadcrumbs
      var loc = unescape (window.location.pathname);
      var tmp = loc.split ("/");
      var path = "/";
      var breadcrumbs = "";
      // Home (folder)
      breadcrumbs += "<img src=\"/dlink/gfx/web.png\" alt=\"Home\" height=\"16\" width=\"16\" /> <a href=\"/\" title=\"Home (homepage)\">homepage</a> / ";
      breadcrumbs += "<img src=\"/site/fancyindexing_folder.png\" alt=\"Home\" height=\"16\" width=\"16\" /> <a href=\"/?dir\" title=\"Home (folder view)\">root</a>";
      for (b=1; b<tmp.length; b++) {
        // Link?
        if (b < (tmp.length - 1)) {
          path += tmp[b] + "/";
          breadcrumbs += " / <img src=\"/site/fancyindexing_folder.png\" alt=\"Home\" height=\"16\" width=\"16\" /> <a href=\"" + path + "?dir\">" + tmp[b] + "</a>";
        } else {
          // Last one a file? or empty (folder)
          breadcrumbs += " / ";
          if (tmp[b] != "") {
            breadcrumbs += tmp[b] + " (viewing file)";
          }
        }
      }
      // Insert the breadcrumbs and room for the loaded nav:
      nav.innerHTML = "<p>OOPStudios.com - talk is cheap, show me the code</p><p>" + breadcrumbs + "</p>";
    }
    // If the footer element exists load the footer
    var footer = document.getElementById ("footer");
    if (footer) {
      // For the "addthis" link
      addthis_pub  = "oopstudios";
      SITE.include ("http://s7.addthis.com/js/152/addthis_widget.js");
      // The footer itself
      SITE.include ("/site/footer.html", "footer");
    }
    // Add the favicon
    var ref = document.createElement ("link");
    ref.setAttribute ("rel", "shortcut icon");
    ref.setAttribute ("href", "/favicon.ico");
    ref.setAttribute ("type", "image/x-icon");
    var head = document.getElementsByTagName ("head")[0];
    head.appendChild (ref);
    // Add the RSS feeds
    var ref = document.createElement ("link");
    ref.setAttribute ("rel", "alternate");
    ref.setAttribute ("href", "/site/feed.rss");
    ref.setAttribute ("type", "application/rss+xml");
    ref.setAttribute ("title", "All OOPStudios Comments (RSS)");
    head.appendChild (ref);
    var ref = document.createElement ("link");
    ref.setAttribute ("rel", "alternate");
    ref.setAttribute ("href", "/site/feed.rss?uri=" + location.pathname);
    ref.setAttribute ("type", "application/rss+xml");
    ref.setAttribute ("title", "This Pages Comments (RSS)");
    head.appendChild (ref);
    var ref = document.createElement ("link");
    ref.setAttribute ("rel", "alternate");
    ref.setAttribute ("href", "http://twitter.com/statuses/user_timeline/18031588.rss");
    ref.setAttribute ("type", "application/rss+xml");
    ref.setAttribute ("title", "Twitter microblog (RSS)");
    head.appendChild (ref);
    // Can we load some feedback?
    var page = document.getElementById ("page");
    if (page) {
      // Create the el
      var ref = document.createElement ("div");
      // And the 2 buttons
      var HTML = "";
      HTML += '<a id="comments" href="#" class="no_dlink" onclick="return SITE.loadComments ();"><img src="/site/comments.png" /> Comments (<span id="comment_num">--</span>)</a>';
      HTML += '<a id="compatibility" href="#" class="no_dlink' + (SITE.compatibility == false ? ' inactive' : '') + '" onclick="return SITE.loadCompatibility ();"><img src="/site/browser/browsers.png" /> Browser compatibility</a>';
      HTML += '<div id="feedback"></div>';
      // Et viola!
      ref.innerHTML = HTML;
      page.appendChild (ref);
      // Er, load up the number of comments
      SITE.include ("/site/comments.php?uri=" + location.pathname + "&do=num", "comment_num");
    }
    // Double check DLINK has run:
    if (window.DLINK) {
      DLINK.init ();
    }
    // Add analytics
    SITE.addGA ();
    // Code highlighting?
    if (!fancyindex) {
      SITE.highlight ();
    }
  };
  
  // Add the event
  if (window.attachEvent) window.attachEvent ("onload", SITE.init);
  else window.addEventListener ("DOMContentLoaded", SITE.init, false);
  
