/**
 * Developer: Aishwar Muthuraman
 * Web: http://www.ai-projects.info
 * Create Date: Dec 31, 2008
 * Version 1.0.1 Update Date: April 21, 2009
 * Version 2.0 Beta Update Date: May 24, 2009
 *
 * Version 2.0
 * =============
 * 1. Changed the mechanism through which the 'box' is created
 * 2. Absolutely no external files needed! - The javascript file is completely self sufficient.
 *    Two other image files were needed before. Overall combined file size is smaller (6.8KB Vs
 *    13.8KB).
 * 3. White border area around the images now - looks nicer :)
 * 4. Proper resizing of images - if the image was bigger than the screen size, previously the
 *    image would be clipped. Now proper resizing is done, so the entire image is visible
 * 5. Close button available - looks nicer :) (any mouse click/key press still closes the box)
 * 6. Image auto-caption mechanism available - Uses the image name to print out image caption
 *    below the image in the box. For e.g. the picture "Vacation_in_Bali.jpg" wouldbe
 *    automatically given the caption "Vacation in Bali" - easy way to have captions without
 *    doing edit HTML!
 * 7. Easy to edit options to control: white-bordering size of the box, caption on/off, close
 *    button on/off and colors.
 *
 * Description:
 * ===========
 * Script that would produce a lightbox type effect without
 * the html code changes needed to be implemented in blogger
 * posts to accomodate it
 */
/*
 * Editable Options to control behaviour of AiBloggerBox
 */
var AiBloggerBox_numberOfLoadingBoxes = 6;

var AiBloggerBox_topWhiteSpace = 30;
var AiBloggerBox_bottomWhiteSpace = 10;
var AiBloggerBox_sideWhiteSpace = 10;

var AiBloggerBox_closeButtonColor = "#ff6600";
var AiBloggerBox_closeButtonText = "close x";
var AiBloggerBox_showCloseButtom = 1;

var AiBloggerBox_captionColor = "#444444";
var AiBloggerBox_showCaption = 0;

/*
 * Shows the loading animation inside divId
 */
function showLoadingImage(divId){
    var nBar = AiBloggerBox_numberOfLoadingBoxes;
    var i;
    var container = document.getElementById(divId);
    var loader = document.createElement("div");
    loader.id = "AiBloggerBox_loader";
    loader.style.margin = "0px auto";
    loader.style.width = AiBloggerBox_numberOfLoadingBoxes * 40 + "px";
    loader.style.position = "relative";
    loader.style.zIndex = "150";
    loader.style.top = "45%";
    container.appendChild(loader);
    for (i = 1; i <= nBar; i++) {
        var lbar = document.createElement("div");
        lbar.id = "AiBloggerBox_lbar_" + i;
        lbar.style.backgroundColor = "#555555";
        lbar.style.margin = "0px 10px";
        lbar.style.width = "20px";
        lbar.style.height = "20px";
        lbar.style.cssFloat = "left";
        lbar.style.styleFloat = "left";
        loader.appendChild(lbar);
    }
}

function animateLoadingImage(){
    var i = 1;
    var element;
    for (i = 1; i <= AiBloggerBox_numberOfLoadingBoxes; i++) {
        element = document.getElementById("AiBloggerBox_lbar_" + i + "s");
        if (element) 
            break;
    }
    if (!element) 
        element = document.getElementById("AiBloggerBox_lbar_1");
    element.style.backgroundColor = "#555555";
    var num = parseInt(element.id.substr(element.id.length - 1));
    if (isNaN(num)) 
        num = parseInt(element.id.substr(element.id.length - 2));
    element.id = "AiBloggerBox_lbar_" + num;
    if (i >= AiBloggerBox_numberOfLoadingBoxes) 
        i = 1;
    else 
        i++;
    element = document.getElementById("AiBloggerBox_lbar_" + i);
    element.id = "AiBloggerBox_lbar_" + i + "s";
    element.style.backgroundColor = "#AFAFAF";
}

var AiBloggerBox_loadingAnimation = null;

function beginAnimation(){
    AiBloggerBox_loadingAnimation = setInterval('animateLoadingImage()', 250);
}

function stopAnimation(){
    clearInterval(AiBloggerBox_loadingAnimation);
}

/*
 * Removes the loading animation from the document
 */
function hideLoadingImage(divId){
    if (AiBloggerBox_loadingAnimation) 
        stopAnimation();
    var container = document.getElementById(divId);
    var loader = document.getElementById("AiBloggerBox_loader");
    loader.parentNode.removeChild(loader);
}

/*
 * Darkens the background
 */
function darkenBackground(){
    var topLayer = document.createElement("div");
    var fakeTop = document.createElement("div");
    topLayer.id = "AiBloggerBox_topLayer";
    fakeTop.id = "AiBloggerBox_fakeTop";
    var body = document.getElementsByTagName("body")[0];
    topLayer.style.background = "#000000";
    topLayer.style.opacity = "0.75";
    topLayer.style.filter = "alpha(opacity=75)";
    topLayer.style.zIndex = "100";
    fakeTop.style.zIndex = "120";
    topLayer.style.width = "100%";
    fakeTop.style.width = "100%";
    topLayer.style.height = "100%";
    fakeTop.style.height = "100%";
    topLayer.style.position = "fixed";
    fakeTop.style.position = "fixed";
    topLayer.style.top = "0px";
    fakeTop.style.top = "0px";
    topLayer.style.left = "0px";
    fakeTop.style.left = "0px";
    
    topLayer.onclick = fakeTop.onclick = function(e){
        toggleImage(e);
        return false;
    };
    topLayer.onclick = fakeTop.onclick = function(e){
        toggleImage(e);
        return false;
    };
    body.insertBefore(fakeTop, body.firstChild);
    body.insertBefore(topLayer, body.firstChild);
}

function undarken(){
    var body = document.getElementsByTagName("body")[0];
    if (body.firstChild.id == "AiBloggerBox_topLayer") 
        body.removeChild(body.firstChild);
    if (body.firstChild.id == "AiBloggerBox_fakeTop") 
        body.removeChild(body.firstChild);
}

/*
 * Function that actually shows the image with the effect
 * Makes calls to all the above functions
 */
function toggleImage(e){
    if (!e) 
        e = window.event;
    var image = document.getElementById("AiBloggerBox_imageShowing");
    if (image !== null) {
        // Hide Image
        undarken();
    }
    else {
        // Show Image
        undarken();
        darkenBackground();
        if (e.srcElement) 
            var source = e.srcElement;
        else 
            var source = e.target;
        var body = document.getElementsByTagName("body")[0];
        showLoadingImage("AiBloggerBox_fakeTop");
        beginAnimation();
        
        // Create the image
        var newimg = new Image();
        newimg.onload = function(){
            stopAnimation();
            hideLoadingImage("AiBloggerBox_fakeTop");
            var darkBg = document.getElementById("AiBloggerBox_fakeTop");
            var newimgLayer = document.createElement("div");
            newimgLayer.id = "AiBloggerBox_imageShowing";
            darkBg.insertBefore(newimgLayer, darkBg.firstChild);
            
            var newimg_w = newimg.width;
            var newimg_h = newimg.height;
            if (window.innerHeight) {
                var screen_w = window.innerWidth;
                var screen_h = window.innerHeight;
            }
            else 
                if (document.documentElement) {
                    var screen_w = document.documentElement.clientWidth;
                    var screen_h = document.documentElement.clientHeight;
                }
                else {
                    var screen_w = document.body.clientWidth;
                    var screen_h = document.body.clientHeight;
                }
            var sideBuffer = AiBloggerBox_sideWhiteSpace;
            var topBuffer = AiBloggerBox_topWhiteSpace;
            var bottomBuffer = AiBloggerBox_bottomWhiteSpace;
            var safetyBuffer = 0;
            var ratio = newimg_w / newimg_h;
            if (newimg_w + 2 * sideBuffer + 2 * safetyBuffer > screen_w) {
                left = 0;
                newimg_w = screen_w - 2 * sideBuffer - 2 * safetyBuffer;
                newimg_h = newimg_w / ratio;
            }
            if (newimg_h + topBuffer + bottomBuffer + 2 * safetyBuffer > screen_h) {
                top = 0;
                newimg_h = screen_h - topBuffer - bottomBuffer - 2 * safetyBuffer;
                newimg_w = newimg_h * ratio;
            }
            var top = (screen_h - newimg_h - topBuffer - bottomBuffer - 2 * safetyBuffer) / 2;
            var left = (screen_w - newimg_w - 2 * sideBuffer - 2 * safetyBuffer) / 2;
            
            newimg.width = newimg_w;
            newimg.height = newimg_h;
            
            var outliner = document.createElement("div");
            outliner.style.background = "#FFFFFF";
            outliner.style.width = newimg_w + "px";
            outliner.style.height = newimg_h + "px";
            outliner.style.paddingTop = topBuffer + "px";
            outliner.style.paddingLeft = outliner.style.paddingRight = sideBuffer + "px";
            outliner.style.paddingBottom = bottomBuffer + "px";
            outliner.style.margin = "0px"
            outliner.style.position = "relative";
            outliner.style.top = top + "px";
            outliner.style.left = left + "px";
            
            var closeButton = document.createElement("div");
            closeButton.style.cssFloat = "right";
            closeButton.style.styleFloat = "right";
            closeButton.style.fontSize = parseInt(topBuffer * 0.5) + "px";
            closeButton.style.color = "#cccccc";
            closeButton.style.margin = closeButton.style.padding = "0px";
            closeButton.style.marginTop = "-" + topBuffer + "px";
            closeButton.innerHTML = "<a style=\"color:" + AiBloggerBox_closeButtonColor + "; text-decoration:none; font-family:Arial, Helvetica, sans-serif; letter-spacing:-1px; font-weight:bold;\" href=\"#\";>" + AiBloggerBox_closeButtonText + "</a>";
            
            var imageText = document.createElement("div");
            imageText.width = "90%";
            imageText.style.fontSize = parseInt(bottomBuffer * 0.3) + "px";
            imageText.style.color = AiBloggerBox_captionColor;
            imageText.style.overflow = "hidden";
            imageText.innerHTML = decodeURI(newimg.src.substr(newimg.src.lastIndexOf("/") + 1));
            imageText.innerHTML = imageText.innerHTML.substr(0, imageText.innerHTML.lastIndexOf("-")).replace(/_/g, " ").replace(/\-/g, " ");
            imageText.style.marginTop = "10px";
            
            if (AiBloggerBox_showCloseButtom) 
                outliner.appendChild(closeButton);
            outliner.appendChild(newimg);
            if (AiBloggerBox_showCaption) 
                outliner.appendChild(imageText);
            newimgLayer.appendChild(outliner);
            return false;
        }
        if (source.nodeName == "A") 
            var parentHref = source;
        else 
            var parentHref = source.parentNode;
        
        if (parentHref.toString().search(/blogspot\.com/) > 0) 
            newimg.src = parentHref.toString().replace(/\-h/, '');
        else 
            newimg.src = parentHref;
    }
}

/*
 * Binds all images with the code to do the
 * "lightbox-type" effect
 */
function bindImages(){
    var images = document.getElementsByTagName("img");
    var i;
    for (i = 0; i < images.length; i++) {
        var parent = images[i].parentNode;
        if (parent.nodeName == "A" && parent.onblur != null) {
            parent.onclick = function(e){
                if (!e) 
                    e = window.event;
                toggleImage(e);
                return false;
            }
            parent.onkeypress = function(e){
                if (!e) 
                    e = window.event;
                if (e.keyCode == 13) {
                    toggleImage(e);
                    return false;
                }
            }
        }
    }
}

if (window.addEventListener) 
    window.addEventListener('load', bindImages, false);
else 
    window.attachEvent('onload', bindImages);
