var AjaxContent = Class.create({
	initialize: function(container) {
		
		// Get options
		this.options = Object.extend({
			urlPostfix:			'',
			catchSameUrl:		false,
			initAnchor:			false,
			useAnchor:			false,
			useAnalytics:		false,
			titlePrefix:		null,
			titleSeperator:		' | ',
			loadingDiv:			null,
			loadDelay:			800,
			
			// Callback functions
			preCallback:		null,
			postCallback:		null,
			anchorCallback:		null
		}, arguments[1] || {} );
		
		// Set member variables
		this.container = container;
		this.isRunning = false;
		this.loadTimer = null;
		this.url = null;
		this.debug = false;
		// Check for an initail anchor
		if(this.options.initAnchor == true && this.options.useAnchor == true) {
			this.getAnchor(); }
	},
	
	// Place the contents of the url into this.element
	getContent: function(url) {
		if (this.debug) console.log('AjaxContent.getContent: '+url);
		// Don't do anything if url is blank
		if(!url) { return; }

		// Don't reload the same thing
		if(this.url == url && this.options.catchSameUrl == true) {
			return; }
		this.url = url;

		// Check isRunning
		if(this.isRunning == true) {
			return; }
		this.isRunning = true;

		// Call the pre callback
		if(this.options.preCallback != null) {
			this.options.preCallback(this); }
		
		// Start a timer to perform an action on a long load time
		this.startLoad();
		
		// Make a this object
		var thisObj = this;
		
		// Start the AJAX request
		new Ajax.Request(url + this.options.urlPostfix, {
			onFailure: function(req) {
				
				// Cancel the load delay timer
				thisObj.finishLoad();
					
				// Show an error
				thisObj.displayContent('Page not found.');
					
				// Set the anchor to 'error'
				if(thisObj.options.useAnchor == true) {
					thisObj.setAnchor('error'); }
					
				// Send the page to analytics so we can track the ajax page changes
				if(thisObj.options.useAnalytics == true) {
					pageTracker._trackPageview("/error.php"); }
			},
			onSuccess: function(req) {
				
				// Cancel the load delay timer
				thisObj.finishLoad();
				
				// Check for JSON response
				if(req.responseJSON) {
					thisObj.displayContent(req.responseJSON); }
				
				// Check for XML response, if no XML send the text
				else if(!req.responseXML) {
					thisObj.displayContent(req.responseText); }
				else if(!req.responseXML.documentElement) {
					thisObj.displayContent(req.responseText); }
				
				// Else, parse the xml
				else
				{
					// Get the xml response
					var xmlRoot = req.responseXML.documentElement;
					
					// Show the content
					var contentStr = thisObj.parseContent(xmlRoot, 'content', true);
					if(contentStr != null) {
						thisObj.displayContent(contentStr); }
					
					// Check for a specific title tag
					if(thisObj.options.titlePrefix != null)
					{
						document.title = thisObj.options.titlePrefix;
						var titleTag = xmlRoot.getElementsByTagName('title');
						if(titleTag.length > 0)
						{
							var specificTitle = titleTag[0].getAttribute('name');
							if(specificTitle != null) {
								document.title += thisObj.options.titleSeperator + specificTitle; }
						}
					}
				}
				
				// Get the page from the url
				var page = thisObj.getPage(url);
				
				// Set the anchor to the current page
				if(thisObj.options.useAnchor == true) {
					thisObj.setAnchor(page); }
					
				// Send the page to analytics so we can track the ajax page changes
				if(thisObj.options.useAnalytics == true) {
					pageTracker._trackPageview("/" + page); }
			}
		});
	},
	
	parseContent: function(xmlRoot, tagName, required)
	{
		// This check will only work in ie
		// Need to check for parseerror in firefox
		//if(xmlRoot == null) {
		//	return false; }
		
		var contentTag = xmlRoot.getElementsByTagName(tagName);
		var xmlString = "";
		
		// Write the content to the document
		if(contentTag.length > 0)
		{
			if(contentTag[0].xml)
			{
				for(node_i = 0; node_i < contentTag[0].childNodes.length; node_i++) {
					xmlString += contentTag[0].childNodes[node_i].xml; }
			}
			else
			{
				for(node_i = 0; node_i < contentTag[0].childNodes.length; node_i++) {
					xmlString += (new XMLSerializer()).serializeToString(contentTag[0].childNodes[node_i]); }
			}
			
			xmlString = xmlString.strip();
			if(xmlString != "") {
				return xmlString; }
		}
		else if(required == true) {
			this.displayContent('Required tag, ' + tagName + ', not found.'); }
			
		return null;
	},
	
	// Call the success callback
	displayContent: function(text) {
		if(typeof(this.options.postCallback) == 'function') {
			this.options.postCallback(this, text); }
		else
		{
			$(this.container).update(text);
			this.isRunning = false;
		}
	},
	
	// Start a timer to perform an action on a long load time
	startLoad: function() {
		var div;
		if( this.options.loadingDiv != null && (div = $(this.options.loadingDiv)) )
		{
			//var dims = document.viewport.getDimensions();
			var dims = $(document.body).getDimensions();
			div.setOpacity(loadingOpacity);
			div.setStyle({width: dims.width + 'px', height: dims.height + 'px'});
			this.loadTimer = setTimeout(function(){div.show()}, this.options.loadDelay);
		}
	},
	
	// Cancel the load delay timer
	finishLoad: function() {
		if(this.loadTimer != null)
		{
			clearTimeout(this.loadTimer);
			this.loadTimer = null;
			$(this.options.loadingDiv).hide();
		}
	},
	
	// Take an anchor from the address bar
	getAnchor: function() {
		var anchor = window.location.hash;
		var pageMatch = /^#(.+)$/;
		var pageArray = pageMatch.exec(anchor);
		
		if(pageArray)
		{
			var anchorStr = pageArray[1] + '.php';
			
			if(this.options.anchorCallback != null) {
				this.options.anchorCallback(anchorStr); }
			
			this.getContent(anchorStr);
		}
	},
	
	// Put the page in the hash for bookmarks and navigation
	setAnchor: function(page) {
		window.location.hash = "#" + page;
	},
	
	getPage: function(url) {
		var pageMatch = /^(?:[^\/]*\/)*([^\.]+)\.php$/;
		var pageArray = pageMatch.exec(url);
		
		if(pageArray) {
			return pageArray[1]; }
		else {
			return null; }
	}
});