var contentDiv = null;
var currentContent = location.href;
var nextContent = null;
var xmlHttp = null;

var lowerPos = null;
var upperPos = null;

var upInc = 50;
var upDelay = 50;
var downInc = 20;
var downDelay = 50;
var middleDelay = 300;
var checkAjaxWait = 10;

var timer = null;
var timeWaited;
var contentDivId = "contentWrap";
var messageDiv = document.getElementById('messageDiv');
var contentShown = true;

/* Matches a URL
 * 1: http://www.domain.com
 * 2: /path/to/document.html
 * 3: ?queryString=value&etc
 * 4: #hashLocation
 */
var URL_EXP = /^(http:\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;

// Store this for comparision with link hrefs to see if they're local links or not
var SITE_HOST = URL_EXP.exec(location)[1];

function swapDiv(href) {
    // Don't start swapping if one is already in progress
    if (!nextContent) {
        nextContent = href;
        var urlParts = URL_EXP.exec(href);
        // Pull out the path
        var page = urlParts[2];
        // Pull out the query string
        var query = urlParts[3];
        // Make sure the path has the PHP document name on the end
        if (page.indexOf(".php") == -1) {
            page += "index.php";
        }
        requestUrl = "/system/ajax.php?page=" + page;
        // Add the query string, if any
        if (query && query.length > 1) {
            requestUrl += "&" + query.substr(1);
        }
        makeAjaxRequest(requestUrl);
        timer = setInterval("moveDivUp()",checkAjaxWait);
    }
    return false; // Cancel link click
}

function fixLinks(containerDiv) {
    var links = containerDiv.getElementsByTagName("a");
    var linkUrl;
    for (var i=0;i<links.length;++i) {
        // Only set the onclick event for local links that don't already have an onclick set
        // Also, don't use AJAX system for downloads!
        if ((linkUrl = links[i].href) && !links[i].onclick
          && linkUrl.indexOf("/userFiles/") == -1 && URL_EXP.exec(linkUrl)[1] == SITE_HOST) {
            links[i].onclick = function () { return swapDiv(this.href); };
        }
    }
}

function makeAjaxRequest(url) {
    xmlHttp = HttpObj();
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function toggleShow() {
	contentDiv.style.top = (upperPos) + 'px';
    return false;
}

function moveDivUp() {
    var divPos = parseInt(contentDiv.style.top);
    // Move the current div up
    if (divPos > upperPos) {
        divPos -= upInc;
        if (divPos < upperPos) {
            divPos = upperPos;
        }
        contentDiv.style.top = divPos+"px";
    }
    // Move the next div down when finished
    else {
        currentContent = nextContent;
        timeWaited = 0;
        clearInterval(timer);
        timer = setInterval("swapContent()",checkAjaxWait);
    }
}

function swapContent() {
    timeWaited += checkAjaxWait;
    if (timeWaited >= middleDelay) {
        if (xmlHttp.readyState == 4) {
            var contentTarget = document.getElementById("content");
            setContent(contentTarget,xmlHttp);
            fixLinks(contentTarget);
            contentTarget.scrollTop = 0;
            clearInterval(timer);
            timer = setInterval("moveDivDown()",downDelay);
        }
        else if (messageDiv.style.display != "block") {
            messageDiv.style.display = "block";
        }
    }
}

function moveDivDown() {
	contentDiv.style.visibility = "visible";
    var divPos = parseInt(contentDiv.style.top);
    messageDiv.style.display = "none";
    if (divPos < lowerPos) {
        divPos += downInc;
        if (divPos > lowerPos) {
            divPos = lowerPos;
        }
        contentDiv.style.top = divPos+"px";
    }
    else {
        clearInterval(timer);
        xmlHttp = null;
        nextContent = null;
    }
}

function getTop(element) {
    var top = 0;
    while (element) {
        top += element.offsetTop;
        element = element.offsetParent;
    }
    return top;
}

function calcSizes() {
    // Get the content div
    contentDiv = document.getElementById(contentDivId);
    // IE has a weird bug with the absolute positioning where it makes the contentDiv
    // way too wide, but Firefox doesn't render well with relative positioning, so...
    if (document.all) {
        // Store the current position
        lowerPos = 0;
        // Calculate how to get the bottom of the div 10px off the top of the screen
        upperPos = - getTop(contentDiv) - contentDiv.offsetHeight;
        // Set top position
        contentDiv.style.position = "relative";
        contentDiv.style.top = "0px";
    }
    else {
        // Store the current position
        lowerPos = getTop(contentDiv);
        // Calculate how to get the bottom of the div 10px off the top of the screen
        upperPos = - contentDiv.offsetHeight;
        // Set top position
        contentDiv.style.position = "absolute";
        contentDiv.style.top = lowerPos + "px";
        contentDiv.style.marginTop = "0";
    }
}

function showString(n) {
    hoverImgDiv.style.backgroundImage = "url('" + strings[n].src + "')";
}

function hideString(n) {
    hoverImgDiv.style.backgroundImage = "none";
}

function addXButton() {
    var xDiv = document.createElement("div");
    xDiv.setAttribute("id","controlDiv");
    var xButton = document.createElement("img");
    xButton.setAttribute("src","/pics/x.png");
    xButton.onclick = function () {return toggleShow();};
    xDiv.appendChild(xButton);
    contentDiv.insertBefore(xDiv,contentDiv.firstChild);
}

//=== Add event handlers ===//

var strings = Array();
var menuItems = document.getElementById("menuDiv").getElementsByTagName("a");
for (var i=0;i<menuItems.length;++i) {
    strings.push(new Image());
    strings[i].src = "/pics/string"+i+".png";
    menuItems[i].onclick = function () {return swapDiv(this.href);};
    menuItems[i].onmouseover = new Function("showString("+i+");");
    menuItems[i].onmouseout = new Function("hideString("+i+");");
}

var wrapDiv = document.getElementById("wrapDiv");
calcSizes();
addXButton();
var hoverImgDiv = document.createElement("div");
hoverImgDiv.setAttribute("id","hoverImgDiv");
wrapDiv.insertBefore(hoverImgDiv,wrapDiv.firstChild);

if (document.getElementById('emptyContent')) {
    contentDiv.style.top = (upperPos) + 'px';
}

