/**
 * Factory for creating pages.
 * @param url
 * @return
 */
function HttpPageFactory() {
	var cachedPages = [];
	this.actionMgr = new ActionManager();
	
	/**
	 * Returns the requested page. (Cached or not)
	 */
	this.CreatePage = function(url, state, firstTime) {
		if ( typeof url != 'string') {
			//alert('invalid url: ' + url + " (Type: " + (typeof url) + ")");
			//throw 'Invalid URL: ' + url;
			return false;
		} else {
			var cache = getCachedPage(url, state);
			if ( ! cache ) {
				var data = $.ajax({
					  url: AbsPath + 'index.php?state='+state+'&firsttime='+firstTime+'&getURL=' + $.base64Encode(url) + '&currentURL=' + $.base64Encode(window.location.href),
					  async: false,
					  timeout: 5
				 });
				if ( data.status == 200 || data.status == 304 ) {
					try {
						var result = eval("(" + data.responseText + ")");
						if ( this.validateData(result) ) {
							var page = new HttpPage(url, this.actionMgr, result, state);
							if ( result.cache == true ) {
								cachedPages.push(page);
							} // else: do not cache, not requested.
							return page;
						} else {
							throw 'Data did not validate.';
							return false;
						}
					} catch ( e ) {
						alert("Error while evaluating received code: " + data.responseText);
					}
				} else {
					throw 'Invalid httprequest state: ' + result.status;
					return false;
				}
			} else {
				// page was cached, so return this page.
				return cache;
			}
		}
	};
	
	function getCachedPage(url, state) {
		for ( var i = 0; i < cachedPages.length; i++ ) {
			if ( cachedPages[i].url == url && cachedPages[i].state == state ) 
				return cachedPages[i];
		}
		return false;
	};
	
	this.validateData = function(data) {
		return true;
	};
}

function HttpPage(url, actionMgr, data, state) {
	this.data = data;
	this.url = url;
	this.actionMgr = actionMgr;
	this.state = state;
}

HttpPage.prototype = {
		show: function() {
			//alert('Show: ' + this.url);
			this.executeActions();
		},
		
		executeActions: function() {
			this.actionMgr.clear();
			var actions = this.data.actions;
			for ( var i = 0; i < actions.length; i++ )
				this.actionMgr.addAction(actions[i]);
			
			this.actionMgr.start();
		}
};