﻿/*
 * Javascript LOADBLOG 0.2
 * Copyright (c) 2009 Michael Suodenjoki, michael@suodenjoki.dk, http://www.suodenjoki.dk/
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

(function()
{
  function createXHR() 
  {
    var request = false;
    try 
    {
      request = new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (err2) 
    {
      try 
      {
        request = new ActiveXObject('Microsoft.XMLHTTP');
      }
      catch (err3) 
      {
        try 
        {
          request = new XMLHttpRequest();
        }
        catch (err1) 
        {
          request = false;
        }
      }
    }
    return request;
  }

  //
  // 'getBody'
  //
  // Searches for body element and extracts and return the content.
  //
  function getBody(sURL,content) 
  {
    test = content.toLowerCase(); // to eliminate case sensitivity
    var x = test.indexOf("<blogpost");
    if(x == -1) return "";
    
    x = test.indexOf(">", x);
    if(x == -1) return "";
    
    var y = test.lastIndexOf("</blogpost>");
    if(y == -1) y = test.lastIndexOf("</html>");
    if(y == -1) y = content.length;    // If no HTML then just grab everything till end
    
    content = content.slice(x + 1, y);
//    return content;
    
    // Update relative links 
    // src=""
    // href=""
    
    
    var sURLfolder = sURL.match(/.*[\/\\]/);
    //alert(sURLfolder);
    //var sURLfolder = "archive";
    
    // URL pattern regular expression source is taken from http://www.codinghorror.com/blog/archives/000245.html
    // (but it is converted from the .NET language into the Javascript language).
    var sURLPattern = "(href|src|background)\s*?=\s*?([\"\'])(?!#|http|ftp|mailto|javascript)/([^\"\']+)([\"\'])";
    // $1 group is capturing e.g. href src background
    // $2 group is capturing start-delimiter e.g. ", ', \
    // $3 group is capturing the url  (with the prefix e.g. #, http, ftp, mailto, javascript)
    // $4 group is capturing end-delimiter, e.g. ", ', \

    // Create regular expression object - with url pattern and ignore case ("i") and multiline ("m") flags.
    var re = new RegExp(sURLPattern.replace("/",""), "gim" );
    
    // -- href="anything" to href="http://www.web.com/folder/anything"
    content = content.replace( re, "$1=$2" + sURLfolder + "$3$4");
    
    return content;   
  } 

  //
  // 'loadHTML'
  //
  // Loads a HTML page.
  // Put the content of the body tag into the current page.
  // 
  // Arguments:
  //   sURL    [string]    - the url of the page to load.
  //   oTarget [HTML elem] - a HTML element object, receiving the loaded content (body element content).
  //
  function loadHTML( sURL, oTarget)
  {
    var xhr = createXHR();
    xhr.onreadystatechange=function()
    { 
      if(xhr.readyState == 4)
      {
        //if(xhr.status == 200)
        {
          //alert("oTarget,id" + oTarget.id);
          oTarget.innerHTML = getBody(sURL,xhr.responseText);
        }
      } 
    }; 
    //xhr.open("GET", sURL, false);
    xhr.open("GET", sURL, true);
    try
    {
      xhr.send(null); 
    }
    catch(e)
    {
      oTarget.innerHTML = "<p>Error: Cannot load '" + sURL + "'</p>";
    }
  } 

  //
  // 'loadBlog'
  //
  // Loads the blog entries into the current page.
  //
  // <div class="blogentry" id="<blogentryfilename>"/>
  //
  function loadBlog( fncCallback )
  {
    var cElems = document.getElementsByTagName("div");
    for( var i = 0; i < cElems.length; i++ ) 
    {
      var oElem = cElems[i];
      if( oElem && oElem.className == "blogentry" )
      {
        // Load HTML from page
        var sFileURL = oElem.id + ".htm";
        loadHTML(sFileURL,oElem);
      }
    }

    var cElems = document.getElementsByTagName("a");
    //for( var i = 0; i < cElems.length; i++ ) 
    for( var i = cElems.length-1; i > 0; i-- ) 
    {
      var oElem = cElems[i];
      if( oElem && oElem.className == "blogentry" )
      {
        // Create a new div element      
        var oBlogElem = document.createElement("div");
        
        // Replace the anchor element (oElem) with div element (oBlogElem).
        var elem = oElem.parentNode.replaceChild( oBlogElem, oElem );
        elem = null;
        
        // Get the href attribute value (giving us the source HTML file to load from)
        var sFileURL = oElem.href.replace( /about:/,"");

        //oBlogElem.innerHTML = "<i>Loading..." + sFileURL + "</i>";

        //alert( "file url = " + sFileURL );
        loadHTML(sFileURL,oBlogElem);
      }
    }
    
    if( fncCallback )
      fncCallback();
  }


  function dostuff()
  {
    //loadBlog( addCaps );
    loadBlog();
    // Note: To get around FireFox DOM update problem, addCaps() is called with a delay
    //       so that the DOM tree is properly updated (i.e. images inserted etc) before
    //       calling addCaps(). 
    // Tip found at: http://www.west-wind.com/WebLog/posts/5782.aspx
    window.setTimeout("addCaps()",50);
    window.setTimeout("loadAllImages()",50);
  }

  function addEvent(oElement, strEvent, fncHandler) 
  {
    if (oElement.addEventListener) { 
      oElement.addEventListener(strEvent, fncHandler, false); 
    } else if (oElement.attachEvent) { 
      oElement.attachEvent("on" + strEvent, fncHandler); 
    }
  }
  
  addEvent(window, "load", dostuff );

})();

  function addcap( oImg )
  {
    if( !!!oImg ) return;
    //if( oImg.className.search("addexifcap") >= 0 )
    {
      addCaption(oImg,true);
    }
  }

  function loadAllImages() 
  {
    var aImages = document.getElementsByTagName("img");
    for( var i=0;i<aImages.length;i++ )
    {
      //if( aImages[i].getAttribute("exif") == "true" )
      if( aImages[i].className.search("addexifcap") >= 0 )
      {
        //alert("in here");
  
        if( !aImages[i].complete )
        {
          addEvent(aImages[i], "load", 
            function() {
              EXIF.getData(this,addcap);
            }
          ); 
        } 
        else 
        {
          EXIF.getData(aImages[i],addcap);
        }
      }
    }
  }
