/*
 * ImageMontage
 * 
 *    Gets the image data for displaying the tiled images on the home page.
 *
 * Tom Coppeto
 * 10 May 2007
 */


function ImageMontage() {
    var across       = 3;
    var frames       = null;
    var cur_frame    = 0;
    var next_frame   = -1;
    var frameRequest = null;
    var tile         = null;
    var timeout      = null;
    var utils        = new DisplayUtils();

    this.Start = Start;

    function Start() {
	cur_frame  = 0;
	next_frame = -1;
	
	if (window.XMLHttpRequest){
	    // If IE7, Mozilla, Safari, etc: Use native object
	    frameRequest = new XMLHttpRequest();	
	} else if (window.ActiveXObject){
	    // ...otherwise, use the ActiveX control for IE5.x and IE6
	    frameRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
	}

	try {
	    frameRequest.open("GET", "/json/config/montage/montage.xml", true);
	    frameRequest.onreadystatechange = changeFrameHandler;
	    frameRequest.send(null);
	} catch (err) {
	    timeout = setTimeout(function() { Start() }, 10000);
	}
    }
    
    
    function changeFrameHandler() {
	try {
	    if (frameRequest.readyState == 4) {
		var ret = eval("(" + frameRequest.responseText + ")");
		frames = ret.frames.frame;
		changeFrame();
	    }
	} catch (err) {
	    timeout = setTimeout(function() { Start() }, 10000);
	}
    }
    

    function changeFrame() {	
	if(timeout) {
	    clearTimeout(timeout);
	}

	tile = 0;

	var e = getElementsByClassName("tile");
	for (i = 1; i <= e.length; i++) {
	    utils.FadeOut("tile" + i, 99);
	}

	if (next_frame == -1) {
	    preload();
	} else {
	    cur_frame = next_frame;
	}

	timeout = setTimeout(function() { changeTile() }, 2000);
	return;
    }
    
    
    function changeTile() {
	try {
	    var src      = frames[cur_frame].tile[tile].src["$"];

	    var img = new Image();
	    img.src = src;
	    if (!img.complete) {
		timeout = setTimeout(function() { changeTile() }, 1000);
		return;
	    }

	    var title    = frames[cur_frame].tile[tile].title["$"];
	    var slot     = parseInt(frames[cur_frame].tile[tile].slot["$"]);
	    var width    = parseInt(frames[cur_frame].tile[tile].width["$"]);
	    var height   = parseInt(frames[cur_frame].tile[tile].height["$"]);
	    var duration = parseInt(frames[cur_frame].tile[tile].duration["$"]);

	    var initialX = slot % across;
	    var initialY = slot / across; 
	    var curSlot  = slot;

	    for (y = 0; y < height; y++) {
		for (x = 0; x < width; x++) {
		    var e = document.getElementById("tile" + curSlot);
		    if (e) {
			var offsetX = -(e.offsetWidth * x);
			var offsetY = -(e.offsetHeight * y);
			e.style.backgroundImage = "url(" + src + ")";
			e.style.backgroundPosition = offsetX + "px  " + offsetY + "px";
			
			/* sweet titles - update the title if
			 * we are currently displaying a tooltip 
			 * this image. Use the anchor id. */
			var anch = document.getElementById("btile" + curSlot);
			if (anch && anch.getAttribute("tip")) {
			    anch.setAttribute("tip", title);
			    sweetTitles.tipUpdate("btile" + curSlot);
			}

			utils.FadeIn("tile" + curSlot, 5);
		    }
		    
		    curSlot = curSlot + 1;
		    if ((curSlot - ((slot/across + y) * across)) > across) {
			break;
		    }
		}
		curSlot = slot + across;
	    }
	    
	    tile = tile + 1;
	    if (tile < frames[cur_frame].tile.length) {
		timeout = setTimeout(function() { changeTile() }, duration);
	    } else {
		setTimeout(function() { preload() }, 100);
		timeout = setTimeout(function() { changeFrame() }, duration);
	    }
	} catch(err) {
	    timeout = setTimeout(function() { Start() }, 10000);
	}
    }

    
    function preload() {
	var r;
	if (frames.length > 0) {
	    while (1) {
		r = Math.floor(Math.random() * frames.length);
		if (r != cur_frame) {
		    break;
		}
	    }
	}

	next_frame = r;
	for (var i = 0; i < frames[next_frame].tile[i].length; i++) {
            var img = new Image();
	    img.src = frames[next_frame].tile[tile].src["$"];
	}

	return;
    }
}
/*
 * History
 * 
 *    Manages the "This Day In History" content.
 *
 * Tom Coppeto
 * 25 March 2008
 */


function History() {
    var parent_div = null;
    var left_div = null;
    var right_div = null;
    var entries = null;
    var eindex = 0;
    var request = null;

    this.Start = Start;

    var skin = getCookie("skin");
    if (!skin) {
	skin = "default";
    }

    function Start(div) {
	if (!document.getElementById) {
            return;
	}

	parent_div = document.getElementById("historyEntry");
	left_div = document.getElementById("historyLeft");
	right_div = document.getElementById("historyRight");

	if (!parent_div) {
            return;
	}

        send_request(display_history);
        return;
    }


    function send_request(func) {

        if (window.XMLHttpRequest) {
            request = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }

        try {
            request.open("GET", "/history/json", true);
            request.onreadystatechange = func;
            request.send(null);
        } catch (err) {
            alert ("unable to send requst: " + err);
	}
    }


    function display_history() {

        if (request.readyState != 4) {
            return;
        }

        var ret = "";
        try {
            ret = eval("(" + request.responseText + ")");
        } catch (err) {
	    alert(err);
            return;
	}
	
	entries = ret.entries;
	entries.sort(entry_cmp);
	eindex = Math.floor(Math.random() * ret.entries.length);
	update();
	return;
    }


    function entry_cmp(a, b) {

	if (a["@year"] < b["@year"]) {
	    return (-1);
	}

	if (a["@year"] > b["@year"]) {
	    return (1);
	}

	if (a["@month"] < b["@month"]) {
	    return (-1);
	}

	if (a["@month"] > b["@month"]) {
	    return (1);
	}

	if (a["@day"] < b["@day"]) {
	    return (-1);
	}

	if (a["@day"] > b["@day"]) {
	    return (1);
	}

	return (0);
    }


    function update() {
	
	deleteChildren(parent_div);
	if (left_div) {
	    deleteChildren(left_div);
	}

	if (right_div) {
	    deleteChildren(right_div);
	}

	if ((eindex < 0) || (eindex >= entries.length)) {
	    eindex = 0;
	}

	var entry = entries[eindex];

	var node = document.createElement("div");
	node.className = "entry";

	var link = document.createElement("a");
	link.href = "/library/day_in_history/";
	link.title = "Read about this day in history database.";
        link.innerHTML = "In " + entry["@year"] + " - " + entry["$"];

	node.appendChild(link);
	parent_div.appendChild(node);

	if (eindex > 0) {
	    node = document.createElement("a");
	    node.title = "Previous history entry for today.";
	    node.onclick = prev;
	    var arrow = document.createElement("img");
	    arrow.src = "/images/" + skin + "/icons/arrow-left16.png";
	    arrow.alt = "prev";
	    node.appendChild(arrow);
	    if (left_div) {
		left_div.appendChild(node);
	    }
	}

	if (eindex < entries.length - 1) {
	    node = document.createElement("a");
	    node.title = "Next history entry for today.";
	    node.onclick = next;
	    var arrow = document.createElement("img");
	    arrow.src = "/images/" + skin + "/icons/arrow-right16.png";
	    arrow.alt = "next";
	    node.appendChild(arrow);
	    if (right_div) {
		right_div.appendChild(node);
	    }
	}

	return;
    }


    function prev() {
	eindex = eindex - 1;
	update();
	return;
    }


    function next() {
	eindex = eindex + 1;
	update();
	return;
    }
}
/*
 * DisplayUtils
 * 
 *    A collection of miscellaneous web page frobs.
 *
 * Tom Coppeto
 * 10 May 2007
 */


function DisplayUtils() {

    this.FadeIn  = FadeIn;
    this.FadeOut = FadeOut;
    this.SetOpacity = SetOpacity;

    
    function SetOpacity(targetName, opacity) {
	
	if(navigator && navigator.userAgent) {
	    /* avoid mac anti-alias thing */
	    if ((navigator.userAgent.indexOf("Macintosh") >= 0) &&
		(navigator.userAgent.indexOf("Mozilla") >= 0) &&
		(navigator.userAgent.indexOf("Safari") < 0) &&
                (navigator.userAgent.indexOf("Firefox/3") < 0)) {
		return;
	    }		
	}

	target = document.getElementById(targetName);
	if (!target) {
	    return;
	}
    
	/* omni needs - .0001 for main image only */
	/* safari & opera ok */
	/* netscape, seamonkey, mozilla disable or .0001 */

	if (target.style) {
	    target.style.opacity = (opacity/100) -.00001;
	    target.style.filter = "alpha(opacity=" + opacity + ")";
	}
    }


    function FadeIn(targetName, opacity) {

	if(navigator && navigator.userAgent) {
	    /* avoid mac anti-alias thing */
	    if ((navigator.userAgent.indexOf("Macintosh") >= 0) &&
		(navigator.userAgent.indexOf("Mozilla") >= 0) &&
		(navigator.userAgent.indexOf("Safari") < 0) &&
                (navigator.userAgent.indexOf("Firefox/3") < 0)) {
		return;
	    }		
	}

	if (opacity <= 100) {
	    SetOpacity(targetName, opacity);
	    opacity += 2;
	    setTimeout(function() { FadeIn(targetName, opacity) }, 30);
	}
    }


    function FadeOut(targetName, opacity) {
	/* avoid mac anti-alias thing */
	if(navigator && navigator.userAgent) {
	    if ((navigator.userAgent.indexOf("Macintosh") >= 0) &&
		(navigator.userAgent.indexOf("Mozilla") >= 0) &&
		(navigator.userAgent.indexOf("Safari") < 0) &&
                (navigator.userAgent.indexOf("Firefox/3") < 0)) {
		return;
	    }
	}

	if (opacity < 5) {
	    opacity = 3;
	}

	SetOpacity(targetName, opacity);
	opacity -= 5;
	if (opacity >= 3) {
	    setTimeout(function() { FadeOut(targetName, opacity) }, 30);
	}
    }

   
    function SetInnerHTML(node, text) {
	if (node) {
	    if (node.childNodes[0]) {
		node.childNodes[0].nodeValue = text;
	    } else if (node.value) {
		node.value = text;
	    } else {
		node.innerHTML = text;
	    }
	}
    }
}



function getCookie(name) {
    var dc = document.cookie;
    if (!document.cookie) {
	return; 
    }

    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
	begin = dc.indexOf(prefix);
	if (begin != 0) {
	    return null;
	}
    } else
	begin += 2;

    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
	end = dc.length;
    }
    return (unescape(dc.substring(begin + prefix.length, end)));
}


function getElementsByClassName(className) {
    var all = document.all ? document.all : document.getElementsByTagName('*');
    var elements = new Array();

    for (var e = 0; e < all.length; e++) {
	if (all[e].className == className) {
	    elements[elements.length] = all[e];
	}
    }

    return (elements);
}


function createElement(element) {
    if ((navigator && navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0)) {	
	    return (document.createElement(element));
    } else {
	    return (document.createElementNS("http://www.w3.org/1999/xhtml", element));
    }
}


function deleteNode(node) {

    if (node) {
	deleteChildren(node); 
	gEVENTS.removeBuiltinListener(node);
	if (typeof node.outerHTML !== 'undefined')
	    node.outerHTML = ''; //prevent pseudo-leak in IE
	else
	    if(node.parentNode) //if the node has a parent
		node.parentNode.removeChild(node); //remove the node from the DOM tree
	delete node; //clean up just to be sure
    }

    return;
}


function deleteChildren(node) {

    if (node) {
	for (var x = node.childNodes.length - 1; x >= 0; x--) { 
	    var childNode = node.childNodes[x];
	    if (childNode.hasChildNodes()) {
		deleteChildren(childNode);
	    }

	    node.removeChild(childNode); //remove the child from the DOM tree
	    delete childNode; //clean up just to be sure
	}
    }
    
    return;
}


String.prototype.escapeHTML = function () {
    return (this.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/\"/g,'&quot;'));
}


String.prototype.unescapeHTML = function () {
    return (this.replace(/&amp;/g,'&').replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'\"'));
}