/***********************************/
/* Code by Joseph Taylor in 2006   */
/* joekarma@gmail.com              */
/***********************************/

//
// Edit this!  This is the url at which
// the "rotated" directory is located.
//
// Note that it must be *your* server -
// external urls aren't allowed in most
// browsers for security reasons.

BASE_HREF = "http://"+window.location.hostname;


//
// Global variables
//

categories = window['categories'] ? categories : "";
categories += getDefaultCategory();

//
// Program Core
//

function RandomFileGetter() {
	var me = this; // Variable scope fix
	
	this.http = null;
	this.http2 = null;
	this.file = null;
	this.updateDiv = $('myOutputText');
	this.baseDir = BASE_HREF;
	
	this.assemblehttp = function() {
		try {
			this.http = new XMLHttpRequest();
			this.http2 = new XMLHttpRequest();
		} catch (e) {
			try {
				this.http = new ActiveXObject("Microsoft.XMLHTTP");
				this.http2 = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
					this.http = new ActiveXObject("Msxml2.XMLHTTP");
					this.http2 = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					return false;
				}
			}
		}
		
		me.http.onreadystatechange = function() {
			if (me.http.readyState == 4) {
				if (me.http.status == 200) {
					me.getRandomPage(me.http.responseText);
				}
			}
		}
		
		me.http2.onreadystatechange = function() {
			if (me.http2.readyState == 4) {
				if (me.http2.status == 200) {
					me.updateDiv.innerHTML = me.http2.responseText;
				}
			}
		}
		
		return true;
	}
	
	this.getRandomPage = function(t) {
		this.file = t.ultratrim();
		try {
			me.http2.open("GET", me.baseDir + "/rotate/" + me.file, true);
			me.http2.send(null);
		} catch (e) {}
	}
	
	this.getRandomFile = function() {
		try {
			this.http.open("GET", me.baseDir + "/rotate/glob.php?categories=" + escape(categories), true);
			this.http.send(null);
		} catch (e) {}
	}
}

function getDefaultCategory() {
		return "";
}

//
// Utility Functions and Extensions
//

function $(id) {
	return typeof id == "string" ? document.getElementById(id) : id;
}

Array.prototype.random = function() {
	return this[Math.floor(Math.random() * this.length)];
}

String.prototype.ultratrim = function() {
	var s = this;
	while (s.charAt(0).match(new RegExp("\\s"))) s = s.substring(1, s.length);
	while (s.charAt(s.length - 1).match(new RegExp("\\s"))) s = s.substring(0, s.length - 1);
	return s;
}

//
// Execution
//

var fg1 = new RandomFileGetter();
if (fg1.assemblehttp()) {
	fg1.getRandomFile();
}
