/* 2009-2010(c) Jflesch, under GPLv3 */

google.load("yui", "2.8.0r4");

var lastDiv = null;

function setFloatToNone(div) {
    div.style.cssFloat = "none";
    div.style.styleFloat = "none";
    lastDiv = null;
}

function doZoom(id, bigImage, x, y, move) {
    var div = document.getElementById("thumb-div-" + id);
    var lnk = document.getElementById("thumb-lnk-" + id);
    var img = document.getElementById("thumb-img-" + id);

    lnk.href = "javascript:doZoom('"+id+"', '"+img.src+"', "+img.width+", "+img.height+", '"+move+"')";
    img.src = bigImage;

    if ( x < 0 || y < 0 )
    {
	/* retry guessing the image size */
	var newImg = new Image();
	newImg.src = img.src;
	y = newImg.height;
	x = newImg.width;

	/* fallback behavior */
	if ( x <= 0 || y <= 0 )
	    document.location.href = img.src;
    }

    if (div)
    {
	/* Mozilla */
	if (div.style.cssFloat)
	{
	    if (div.style.cssFloat == "none")
		div.style.cssFloat = move;
	    else
	    {
		if (lastDiv == null)
		{
		    lastDiv = div;
		    setTimeout("setFloatToNone(lastDiv)", 500);
		}
	    }
	}

	/* IE */
	if (div.style.styleFloat)
	{
	    if (div.style.styleFloat == "none")
		div.style.styleFloat = move;
	    else
	    {
		if (lastDiv == null)
		{
		    lastDiv = div;
		    setTimeout("setFloatToNone(lastDiv)", 500);
		}
	    }
	}

	if (!div.style.styleFloat && !div.style.cssFloat)
	{
	    /* mozilla gives both empty, but accepts the modification */
	    if (lastDiv == null)
	    {
		lastDiv = div;
		setTimeout("setFloatToNone(lastDiv)", 500);
	    }
	}
    }

    var animImg =
	new YAHOO.util.Anim("thumb-img-" + id,
			    {
				width: { to: x },
				height: { to: y }
			    }, 0.3 /* time */, YAHOO.util.Easing.easeOut);

    animImg.animate();
}


function unhide(hiddingDiv)
{
    var animUnhidding =
	new YAHOO.util.Anim("hiddingDiv",
			    {
				width: { to: 0 },
			    }, 0.3 /* time */, YAHOO.util.Easing.easeOut);
    animUnhidding.onComplete.subscribe(function()
				       {
					   document.body.removeChild(hiddingDiv);
				       });
    animUnhidding.animate();
}

/* I've never seen this function being called, so I basically have no idea what the output looks like :( */
function loadingFailed(o)
{
    var body = document.getElementById('body'); /* it's actually a div */
    var url = o.argument[0];
    body.innerHtml = "<p><a href=\"doLoad('" + url + "'\">"
	+ '<img src="http://www.emarketool.fr/wp-content/uploads/2009/09/mire1.jpg" width="320" height="200" alt="" />'
	+ '<br/>'
	+ 'Sorry, transmission was interrupted. Please click to retry.</a></p>';
    unhide(o.argument[1]);
}

function loadingSuccessful(o)
{
    var body = document.getElementById('body'); /* it's actually a div */
    var url = o.argument[0];
    body.innerHTML = o.responseText;
    o.argument[1].style.height = (document.height || document.body.offsetHeight) + "px";
    reinitJS(url);
    unhide(o.argument[1]);
}

function doLoad(url) {
    /* just having fun with the YUI toolkit :) */

    var body = document.body;
    var menu = document.getElementById('menu');

    var hiddingDiv = document.createElement("DIV");

    hiddingDiv.id = "hiddingDiv";
    hiddingDiv.style.position = "absolute";
    hiddingDiv.style.styleFloat = "right";
    hiddingDiv.style.cssFloat = "right";
    hiddingDiv.style.right = "5px";
    hiddingDiv.style.width = "0px";
    hiddingDiv.style.zIndex = "128";
    hiddingDiv.style.backgroundColor = "#eeeeee";
    hiddingDiv.style.border = "1px solid black";
    hiddingDiv.style.height = (document.height || document.body.offsetHeight) + "px";

    body.insertBefore(hiddingDiv, body.childNodes[0]);
/*
    hiddingDiv.innerHTML = "<p style=\"text-align: center;\">Loading ...</p>";
    */
    var newWidth = (document.width || document.body.offsetWidth);
    newWidth -= 240;

    var animHidding =
	new YAHOO.util.Anim("hiddingDiv",
			    {
				width: { to: newWidth },
			    }, 0.1 /* time */, YAHOO.util.Easing.easeOut);

    var loadingCallback = {
	success: loadingSuccessful,
	failure: loadingFailed,
	argument: [ url, hiddingDiv ],
    };
    YAHOO.util.Connect.asyncRequest('GET', url + "?noheader=1", loadingCallback, null);

    animHidding.animate();
}

function getTagRecursively(rootTag, tagName, callback, depth) {
    for ( var i = 0 ; i < rootTag.childNodes.length ; i++ )
    {
	var child = rootTag.childNodes[i];
	if ( child.nodeName == tagName )
	    callback(child);
	getTagRecursively(child, tagName, callback, depth+1);
    }
}

function makeZoomable(imgNode) {
    if ( !(imgNode.parentNode instanceof HTMLAnchorElement) )
	return;
    if ( !(imgNode.parentNode.parentNode instanceof HTMLDivElement) )
	return;

    var aNode = imgNode.parentNode;
    var divNode = imgNode.parentNode.parentNode;

    if ( aNode.href.substr(0, 4) == "java" )
	return;

    var imgSrc = aNode.href;

    /* the move argument is useless most of the time, so we can just guess
     * and forget about it
     */
    var move = "left";
    if ( divNode.className == "thumb-right" )
	move = "right";

    /* we create a new image to get its real size */
    var newImg = new Image();
    newImg.src = imgSrc;
    var realHeight = newImg.height;
    var realWidth = newImg.width;

    if ( !realHeight || !realWidth )
    {
	realHeight = -1;
	realWidth = -1;
    }

    aNode.href = "javascript:doZoom('" + imgSrc + "', '" + imgSrc + "', "
	+ realWidth + ", " + realHeight + ", '" + move + "')";
    aNode.id = "thumb-lnk-" + imgSrc;
    imgNode.id = "thumb-img-" + imgSrc;
}

function modifyZoomableImageLinks() {
    getTagRecursively(document, "IMG", makeZoomable, 0);
}

function makeAjaxLink(aNode) {
    /* look for an IMG at the first level of this node, if found, drop it, it's a zoomable image */
    for ( var i = 0 ; i < aNode.childNodes.length ; i++ )
    {
	var child = aNode.childNodes[i];
	if ( child.nodeName == "IMG" )
	    return;
    }

    if ( aNode.href.indexOf("?") >= 0 || aNode.href.substr(0, 4) == "java" ) /* wow, too hardcore for us */
	return;

    var server = document.URL.split("/")[2];

    var href = aNode.href;
    var urlHeaderLng = 7 + server.length;

    if ( href.substr(0, urlHeaderLng) == "http://" + server )
    { /* absolute url not going out of this website */
	href = href.substr(urlHeaderLng, href.length - urlHeaderLng);
    }
    else if ( href.substr(0, 4) == "http" )
	return; /* external link : do not touch */

    aNode.href = "javascript:doLoad(\"" + escape(href) + "\")";
}

function modifyNormalLinks() {
    getTagRecursively(document, "A", makeAjaxLink, 0);
}

function modifyPermaLink(url) {
    var link = document.getElementById("permalink");
    link.href = url;
}

function reinitJS(url) {
    /* modifyNormalLinks(); */
    modifyZoomableImageLinks();
    /*    modifyPermaLink(url); */
}

function loadYahooStuff() {
    /* See http://developer.yahoo.com/yui/articles/hosting/ to generate these code pieces
     */
    var loader = new YAHOO.util.YUILoader({
        base: "http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/",
        require: [ "animation" ],
        loadOptional: false,
        combine: false,
        filter: "MIN",
        allowRollup: true,
        onSuccess: function() {
	    modifyZoomableImageLinks();
        }
    });
    loader.insert();
    /*
    loader = new YAHOO.util.YUILoader({
        base: "http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/",
        require: [ "connection", "connectioncore", "json" ],
        loadOptional: false,
        combine: false,
        filter: "MIN",
        allowRollup: true,
        onSuccess: function() {
		modifyNormalLinks();
        }
    });
    loader.insert();
    */
}

google.setOnLoadCallback(loadYahooStuff);
