window.onload = startList;

function startList() {
	checkAnchor();
	populate();
}

var storyId = null;

function showNews(id) {
    storyId = id;
    document.getElementById('display').style.display = 'block';
    if (!xmlBusy) {
        var url = 'action.php?actionId=getStory&storyId=' + storyId;
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = displayNews;
        xmlHttp.send(null);
        xmlBusy = true;
    } else {
        setTimeout("showNews(" + storyId + ")", 500);
        if (loadCount < 5) {
            loadCount = 0;
            xmlBusy = false;
        } else {
            loadCount++;
        }
    }
}

function displayNews() {
    if (xmlHttp.readyState == 4) {
        var text = xmlHttp.responseText;
        document.getElementById('storyContent').innerHTML = text.substring(text.indexOf(':')+1,text.indexOf('^'));
        xmlBusy = false;
        getStoryTitle(storyId);
    }
}

function getStoryTitle(id) {
    if (!xmlBusy) {
        var url = 'action.php?actionId=getTitle&storyId=' + id;
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = displayTitle;
        xmlHttp.send(null);
        xmlBusy = true;
    } else {
        setTimeout("getStoryTitle(" + storyId + ")", 500);
        if (loadCount < 5) {
            loadCount = 0;
            xmlBusy = false;
        } else {
            loadCount++;
        }
    }
}

function displayTitle() {
    if (xmlHttp.readyState == 4) {
        var text = xmlHttp.responseText;
        document.getElementById('storyTitle').innerHTML = text.substring(text.indexOf(':')+1,text.indexOf('^'));
        xmlBusy = false;
    }
}

function closeNews() {
    document.getElementById('storyContent').innerHTML = '<span style="color: white;"><i>Loading news story...</i></span>';
    document.getElementById('storyTitle').innerHTML = '';
    document.getElementById('display').style.display = 'none';
}

function checkAnchor() {
    var url = document.location.href;
    if (url.indexOf('#') != -1) {
        var aId = url.substring(url.indexOf('#')+1, url.length);
        showNews(aId);
    }
}