(function() {

var xmlHttp;
var timer;
var timerContainerid;
var loadingText;
var timerDelay    = 1000;    //milliseconds between loadingTimer updates 1000 = 1 sec
var timerAddOn    = '.';     //text added onto loadingText for every loadingTimer update

function getXmlHttpObject() {
	var xmlHttp = null;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function register(wpurl, action, id, link) {
	xmlHttp = getXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Oop! Browser does not support HTTP Request.")
		return;
	}

	var url = wpurl;
	url += "?action=stsp_ajax";
	url += "&stsp_action=" + action;
	url += "&stsp_id=" + id;

	var containerid = 'stsp';
	if(link.length > 1) {
	    xmlHttp.onreadystatechange = function(){delayedRedirect(link)};
	} else {
	    startLoadingTimer(containerid, "Loading Story Spotlight...");
	    xmlHttp.onreadystatechange = function(){loadContent(containerid)};
	}
	
	try {
    	xmlHttp.open("GET", url, true);
    	xmlHttp.send(null);
    } catch(e) {
        stopLoadingTimer();  //stop this in case it had been started
        var errorText = "<span style='color:red;font-weight:bold;'>AJAX error connecting to : </span><br>" + 
            url + '<br><a href="javascript:void(0);" onClick="' + 
            "STSPJS.register('" + wpurl + "', '" + action + "', '" + id + "', '" + link + "');" + 
            '">Click here to try again...</a>';
        showContent(containerid, errorText);
    }
        
}

function delayedRedirect(link) {
    if (xmlHttp.readyState < 4) {
		document.body.style.cursor = 'wait';
	} else if (xmlHttp.readyState == 4 || xmlHttp.readyState=="complete") {
		document.location.href = link;
	}
}

function loadContent(containerid) {
	if (xmlHttp.readyState < 4) {
		document.body.style.cursor = 'wait';
		loadingText += timerAddOn;
		showContent(containerid, loadingText);
	} else if (xmlHttp.readyState == 4 || xmlHttp.readyState=="complete") {
	    stopLoadingTimer();
	    showContent(containerid, xmlHttp.responseText);
		document.body.style.cursor = 'auto';
	}
}

function startLoadingTimer(containerid, loading) {
    timerContainerid = containerid;
    loadingText = (loading == undefined) ? "Loading..." : loading ;
    loadingTimer();
}

function stopLoadingTimer() {
    clearTimeout(timer);
}

function loadingTimer() {
    showContent(timerContainerid, loadingText);
    loadingText += timerAddOn;
    timer = setTimeout("STSPJS.loadingTimer()", 1000);
}

function showContent(containerid, body) {
    var container = document.getElementById(containerid);
    container.innerHTML = body;
}


    
    

window['STSPJS'] = {};
window['STSPJS']['register']     = register;
window['STSPJS']['loadingTimer'] = loadingTimer;

})();

