/**
 * Creates an instance of a Page class. This class throws an error if
 * it is passed a JSON object without the necessary attributes. These are
 * defined as a static property called elements. This array is publicly available so the application
 * can simply redefine the elements array to fit the circumstances.
 * The legacy array is: 		
 * 		"leftheader",
		"leftblock",
		"rightheader",
		"rightblock",
		"bottomheader",
		"bottomblock"		
		The new layouts system gets its data from the layouts.js file
		Added in 7.3: Starting to accommodate the new application form for translators
		I want links to json files to be handled by the AJAX application, but links to aspx files
		to be followed to open the aspx page.
 */
YAHOO.si.Page = function()
{
	this.contentbox = {};
	this.controller = YAHOO.si.Controller;
	var Layouts = new YAHOO.si.Layouts();
	this.layouts = Layouts.layouts;
	this.ready = false;
	this.textboxes = [
		"leftheader",
		"rightheader",
		"bottomheader"
	];
	this.divs = [
		"leftblock",
		"rightblock",
		"bottomblock"			
	];
	this.elements = this.textboxes.concat(this.divs);
	this.domelements = this.elements;
	/**
	 * This is the div element in the centre of the page where we render the 
	 * page contents from json data.
	 */
	this.contentbox = {};
	/**
	 * This is crucial for links.  We need to catch the default event of links
	 * embedded in the elements in contentbox and run a click handler to retrieve the 
	 * relevant json data for the page the link points to and then render the page.
	 */
	this.schemehost = {};
	/**
	 * This handles the click event from any links embedded in contentbox.
	 */
	this.handleClick = function(ev,url)
	{
		try
		{
			var ext = url.substring(url.length-4,url.length);
			//If the link has a json extension then it's one of our special pages
			if(ext==="json")
			{
		     	YAHOO.util.Event.stopEvent(ev);   
		     	//var language = YAHOO.si.HistoryManager.language;
		     	var pageid = urllookup[url].pageid;
		     	var areaid = urllookup[url].areaid;
				var language = urllookup[url].language;
		     	var state = {"language":language,"areaid":areaid,"pageid":pageid};
				YAHOO.si.HistoryManager.multiNavigate(state);
				YAHOO.si.Controller.topNavBar.setSelected(url);
				//YAHOO.si.Controller.leftMenu.setSelected(url);			
			}
			//otherwise just follow the link - it's probably a pdf or doc file which we
			//want to download.
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
 	};	
	this.addLinkClickHandlers = function()
	{
		try
		{	
			if(YAHOO.util.Dom.inDocument("schemehost"))
			{
				var schemehost = document.getElementById("schemehost");
				var index = schemehost.value.length;
				//var page = this;
				if(YAHOO.util.Dom.inDocument("contentbox"))
				{
					var contentbox = document.getElementById("contentbox");
					var links = contentbox.getElementsByTagName("a");
					if(links.length>0){
						//alert(links[0].href.substring(index));	
						for(var i = 0;i<links.length;i++)
						{
							var href = links[i].href;
							if(href.indexOf("json")!==-1 )
							{
								var url = links[i].href.substring(index);
								YAHOO.util.Event.addListener(links[i],"click", this.handleClick, url, this);						
							}
						}
					}
				}
				else
				{
					alert("contentbox is not in the document.");
				}			
			}
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
	};
	this.renderPostVer6 = function(json)
	{
		
		try
		{
			this.currentLayout = this.layouts[json.layout];
			this.contentbox.innerHTML = "";//this.currentLayout.type;
			var textblocks = this.currentLayout.textblocks;
			//this.clearTextBlocks(this.currentLayout);
 			//this.contentbox.innerHTML = null;
			for(var i = 0; i < textblocks.length; i++)
			{
				var _textblock = textblocks[i];
				var textblock = document.createElement("div");
				textblock.id = _textblock.id;
				textblock.className = _textblock.className;
				textblock.innerHTML = json[_textblock.id];
				this.contentbox.appendChild(textblock);			
			}
			if(json.pageid != YAHOO.si.Sitemap.pageid)
			{
				//alert("adding click handlers");
				//Don't add these listeners if it's the sitemap
				this.addLinkClickHandlers();					
			}
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
	};
	this.renderPreVer6 = function(json)
	{
		//alert("replacing legacy block");
		this.contentbox = document.getElementById("contentbox");
		//this.contentbox.innerHTML = null;
		this.contentbox.innerHTML = "";
		//These are the containers for the headers and blocks of the 6 legacy elements.
		var containers = ["leftbox","rightbox","bottomblockcontainer"];
		for(var i = 0; i < 3;i++)
		{
			
			var container = {};
			var header = {};
			var block = {};
			if(!YAHOO.util.Dom.inDocument(containers[i]))
			{
				container = document.createElement("div");
			}
			else
			{
				container = document.getElementById(containers[i]);
			}
			container.id = containers[i];
			if(!YAHOO.util.Dom.inDocument(this.textboxes[i]))
			{
				header = document.createElement("h1");
			}
			else
			{
				header = document.getElementById(this.textboxes[i]);
			}
			header.id =  this.textboxes[i];
			//I think you have to set the innerHTML within the same code block
			//as replacing the legacy blocks.
			header.innerHTML = json[this.textboxes[i]];
			if(!YAHOO.util.Dom.inDocument(this.divs[i]))
			{
				block = document.createElement("div");
			}
			else
			{
				block = document.getElementById(this.divs[i]);
			}
			block.id = this.divs[i];
			block.innerHTML = json[this.divs[i]];	
			//for testing only:			
			//block.style.border ="solid 2px green";
						
			container.appendChild(header);
			container.appendChild(block);
			this.contentbox.appendChild(container);
		}			
	};
	this.render = function(json)
	{
		/*
		var test = "";
		for(obj in json)
		{
				test += obj + json[obj] + "<BR>";
		}
		alert(test);
		*/ 
		try
		{
			if(json.layout)
			{
					this.renderPostVer6(json);
			}
			else
			{
				this.renderPreVer6(json);
			}
			return;
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
	};
	/**
	 * This method sets the document title.
	 */
	this.setPageDetails = function(url,text)
	{
		try
		{
			this.url = url;
			this.text =text;
			document.title = this.text;
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
	};
	this.getPageContents = function()
	{
    	var page = this;
        var handleSuccess = function(o) {
			try
			{		
	            var response = o.responseText;
	            if(YAHOO.si.isZeroLengthString(response))
	            {
	            	var text = "The page has no data.";
	            	YAHOO.si.Progress.show(text,false);
	            	var layouts = new YAHOO.si.Layouts(); 
	            	var layout = layouts.SINGLE_BOX_LAYOUT;           	
	            	var json = {"layout":layout,"textblock_0":text,"pageid":"-1"};
	            	
	            	page.render(json);
	            }
	            else
	            {
		           	var contents = YAHOO.lang.JSON.parse(response);
		           	if(contents.error)
		           	{
		           		YAHOO.si.Progress.show( "contents error: " + contents.error,false);
		           	}
		           	else
		           	{
		           		page.render(contents);
		           		YAHOO.si.Progress.show("Page loaded",false);
		           	}
	            }
			}
			catch(e)
			{
				e.contextMessage = response + "\n\r";
				e.contextMessage += "The YUI json module may be missing.";
				YAHOO.si.handleErrors( e);
			}
			return false;
        };
        var handleFailure = function(o) {
        	try
        	{
	        	throw new Error("Failed to get page contents. Click the refresh button on your browser and try again.");
        	}
        	catch(e)
        	{
        		var msg = "";
        		for(var obj in o)
        		{
        			if(o[obj])
        			{
	        			msg += obj +":" + o[obj];
        			}
        		}
        		e.contextMessage = msg;
        		YAHOO.si.handleErrors(e);	
        	}
        };

        var callback = {
            success: handleSuccess,
            failure: handleFailure
        };
        try
        {
        	//alert(this.url);
	        if(this.url.substring(this.url.length - 13)=="/sitemap.json")
	        {
	        	//We need to generate a sitemap from the /pagedata/rendersitemap.js file.
	        	//Don't go to the server to request a standard page.
	        	//alert("trying to get sitemap");
	        	var json = YAHOO.si.Sitemap.getSitemap();
				this.render(json);
				
	        }
			else
			{	
		        var data = 'url=' + encodeURIComponent(this.url);
		        window.setTimeout(function() {
			        YAHOO.si.Progress.show("Loading Page Data...",true);
		            var sUrl = "/GetPageData.aspx";
		            var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback,data);
		       }, 200);
			}
        }
        catch(e)
        {
        	YAHOO.si.handleErrors(e);
        }
        return false;
	};
	this.translate = function()
	{
		try
		{
			var translation =  translations[this.state.pageid + "-4"];
			var typetransid = translation["type-transid"];
			var transid = typetransid.substring(0,typetransid.indexOf("-"));
			return transid;
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
	};
	this.reload = function(pageid)
	{
		try
		{		
			//alert("reloading " + pageid);
			var json = {};
			if(pageid===YAHOO.si.Sitemap.pageid)
			{
				//alert(YAHOO.si.Sitemap.pageid + ": is pageid" );
				//It's the Sitemap
				json = YAHOO.si.Sitemap.getSitemap();
				//alert(json);
				this.render(json);
				YAHOO.si.Sitemap.addListeners(this.contentbox);
			}
			else
			{
				json = pagelookup[pageid];
				this.reloadFromUrl(json.url);
			}
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
		/*
		this.pageid = pageid;
		if(fromHistory)
		{
		}
		else
		{
		}
		this.language = YAHOO.si.Controller.language;
		this.areaid = YAHOO.si.Controller.areaid;
		var jsonFromPageLookup = pagelookup[this.pageid];
		this.url = jsonFromPageLookup["url"];
		//YAHOO.si.Controller.topNavBar.repaint();
		//YAHOO.si.Controller.leftMenu.repaint();
		this.getPageContents();		
		return false;
		*/ 
	};
	this.reloadFromUrl = function(url)
	{
		try
		{
			var json = urllookup[url];
			this.setPageDetails(url,json.text);			
			this.getPageContents();
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);	
		}
	};
	/**
	 * The state object has 3 properties:
	 * language
	 * areaid
	 * pageid
	 * @param Object state
	 */
	this.init = function()
	{
		//init definitely only fires once when the page is reloaded. It doesn't
		//fire between clicks from the client-side.
		try
		{
			YAHOO.si.Progress.show("Loading Page...",true);
			this.contentbox = document.getElementById("contentbox");
			this.schemehost = document.getElementById("schemehost");
			var pageid = this.controller.historyManager.pageid;
			var json = {};
			if(pageid===YAHOO.si.Sitemap.pageid)
			{
				json = YAHOO.si.Sitemap.getSitemap();
			}
			else
			{
				json = 	pagelookup[pageid];	
			}
			this.setPageDetails(json.url,json.text);		
			this.getPageContents();
		}
		catch(e)
		{
			YAHOO.si.handleErrors(e);
		}
		return this;
	};
	
	this.toString = function()
	{
		return "YAHOO.si.Page";
	};
	
};
