var version = "2.013 [2010-07-15]";

var isIE = (new RegExp('internet explorer','gi')).test(navigator.appName);
var isFlash;

var volumeLocation = "";

var isInit = true;
var initVolume;
var initPage;
var currentPage = "";

	
var footer1= "";
var footer2= "";
var footer3= "";
var footer4= "";
	
var timer = null; //after demanded page is loaded timer starts the transformation of the rest 

var objSerializer;

var xmlHttp;
var xslWeb;
var xslMetadata;
var xmlData;



function redirectToStaticContent()
{
	//tested with:
	// Firefox 2.0 (XP)
	// Netscape 7.1 (Windows XP), Netscape 4.8 (Windows 2000), Netscape 6.2 (Windows XP)
	// Opera 6.0.1 (Windows XP)
	// TODO: more tests

	var encodedLocation = new String(window.location);
	// search for '?page='
	
	var i = encodedLocation.indexOf("?page=");
	if (i < 0)
	{
		window.location = "../index.html";
		return
	}
	
	// goes to static/Japanese_About_BB.htm
	var serializedStateObject = encodedLocation.slice(i + 6);
	var decodedStateObject = unescape(serializedStateObject);
	
	// get volume
	var volume = decodedStateObject.split(" ")[0];
	var pageID = decodedStateObject.split(" ")[1];
	var staticURL = "static/" + volume + "/" + volume + "_" + pageID + ".html";
	location.replace(staticURL);
}



   
function fileURL(dataVolume)
{
	if (dataVolume == 'Global')
	{
		return("global.xml")
	}
	else
	{
		return("Web/Web_" + dataVolume + ".xml")
	}
}
















function getVolume(pageName)
{
	// slices first word
	var volume = pageName.slice(0,pageName.indexOf(" "));
	return (volume == "")?"English":volume;

	/*if (volume == "")
	{
		return "English"
	}
	else
	{
		return volume
	}*/
}







		
function checkAvailability(pageName)
	{		
		//checks if the page is available
		//divCollection holds the collection of DIVs of all pages incl. menu
		var divCollection = document.getElementById("data").childNodes;

		for (i=0; i<divCollection.length; i++)
		{
			//if so function ends 
			//HACK: IE allows divCollection(i), Firefox not
			if (divCollection[i].id == pageName)
			{
				return(pageName)
			}
		}	
		//alert("Missing page: " + pageName);
		// goes to English Homepage
		return "English Homepage"
	}	






// HACK: History object cannot be read directly, we use IFRAME with loaded "back.htm"
function saveHistory(pageName)
{
	var serializedStateObject;

	// TODO: add volume - so far the decision is load only one volume at time
	// so changing the volume (language to be correct) goes to its starting static page
	// the reason behing is also indexing of the homepages in each language by the robots

	document.getElementById("backDebugFrom").innerHTML = pageName;
	
	// serialize
	// encode space and underscore characters
	serializedStateObject = encodeURI(pageName);
		
	// "back.htm" needs to be where the "system.htm" is
	// otherwise the full path is neccessary
	// "back/back.htm" doesn't work properly
	backIframe.location="back.htm?page=" + serializedStateObject;
}

/*function encodeHack(plainText)
{
	// implements encodeURI missing in IE5.0, escape() is considered obsolite
	var strChar;
	var strOut = "";
	var intAsc;

	for (i=0; plainText.length > i; i++)
	{
		strChar = plainText.charAt(i);
		intAsc = plainText.charCodeAt(i);
		if ((intAsc >= 48 && intAsc <= 57) || (intAsc >= 97 && intAsc <= 122) || (intAsc >= 65 && intAsc <= 90))
		{
			strOut += strChar
		}
		else
		{
			strOut += escape(strChar);
		}
	}
	//alert("IE50 encodeURI: " + strOut + "\nIE55 encodeURI: " + encodeURI(plainText));
	return strOut
}*/

/*function decodeHack(encodedText)
{
	return unescape(encodedText)
}*/


function switchBack(encodedLocation)
{
	var pageName = getPageNameFromURL(encodedLocation);

	//alert("Switch Back is triggered.\nCurrent Page: " + currentPage + "\nDeserialized Page: " + pageName);

	if (pageName == "")
	{
		// This happens when first loading application
		// In would be also a case of comming forward after previously left application
		// using back button though then the switchBack is not even triggered

		document.getElementById("backDebugTriggered").innerHTML = "Crossing initialization state";

		switchLayout(initPage);
	}
	else if(pageName == currentPage)
	{
		// This one means the displayed page is the expected one
		// because it was triggered by navigating inside application
		// which always call saveHistory which in turn causes triggering switchBack.
		// This case effectively means "do nothing"
		document.getElementById("backDebugTriggered").innerHTML = "Navigating inside application";

		//TODO: check if not redundant here
		switchLayout(pageName);
	}
	else
	{
		// This was trigerred by back/forward button or another history navigation
		document.getElementById("backDebugTriggered").innerHTML = "Back/Forward button or other History navigating";

		//TODO: check if not redundant here
		switchLayout(pageName);
	}
}

function getPageNameFromURL(objLocation)
{
	// search '?page='
	var encodedLocation = new String(objLocation);
	var i = encodedLocation.indexOf("?page=");
	if (i < 0)
	{
		return "";
	}
	else
	{
		var serializedStateObject = encodedLocation.slice(i + 6);
		// decode space and underscore characters
		// deserialize
		return decodeURI(serializedStateObject);
	}
}


function switchPage(pageName)
	{
		//alert("Switch Page: " + pageName);
		if (pageName == "English Homepage")		window.location = "../index.html";	
		else if (pageName == "French Homepage")		window.location = "../index-f.html";
		else if (pageName == "Czech Homepage")		window.location = "../index-cz.html";
		else if (pageName == "Spanish Homepage")	window.location = "../e/index.html";
		else if (pageName == "German Homepage")		window.location = "../index-g.html";
		else if (pageName == "Italian Homepage")	window.location = "../index-i.html";
		else if (pageName == "Japanese Homepage")	window.location = "../index-j.html";
		else if (pageName == "Taiwanese Homepage")	window.location = "../index-t.html";
		else if (pageName == "Portuguese Homepage")	window.location = "../index-p.html";
		else if (pageName == "Korean Homepage")		window.location = "../k/index.html";
		else
		{
			if (pageName == currentPage)
			{
				//alert("Switching to currentPage.\nNo action.");
				return;
			}
			if (pageName == "#") return;
			if (pageName.indexOf("http:") > -1)
			{
				window.open(pageName,"_blank","height=600,width=800,top=10,left=10,location=1,status=1,titlebar=1,menubar=1,resizable=1,directories=1,toolbar=1");
				return
			}
			if (pageName.indexOf("mailto:") > -1)
			{
				window.open(pageName + "?subject=From the user of BBELS","_blank","height=600,width=800,top=10,left=10,location=1,status=1,titlebar=1,menubar=1,resizable=1,directories=1,toolbar=1");
				return
			}

			// syntax of PageName: 'English Homepage', 'English Surfing'
			pageName = checkAvailability(pageName);
		
			switchLayout(pageName);

			if (isInit)
			{
				isInit = false;
			}
			else
			{
				saveHistory(pageName);
			}
		}
	}


function switchLayout(pageName)
{
	//divCollection holds the collection of DIVs with the pages incl. menu
	var divCollection = document.getElementById("data").childNodes;
	var ColLength = divCollection.length;

	for (i=0; i<ColLength; i++)
	{
		//Firefox is strict and includes text (3) and comment (8) nodes
		if (divCollection[i].nodeType != 3 && divCollection[i].nodeType != 8 && divCollection[i].id.slice(0,6) != 'system')
		{
			divCollection[i].style.display = (divCollection[i].id == pageName)?'block':'none';
		}
	}
}






function switchLanguage(volume)
{
	if (volume == "English") 		window.location = "../index.html";
	else if (volume == "Czech")		window.location = "../index-cz.html";
	else if (volume == "French")		window.location = "../index-f.html";
	else if (volume == "German")		window.location = "../index-g.html";
	else if (volume == "Spanish")		window.location = "../e/index.html";
	else if (volume == "Portuguese")	window.location = "../index-p.html";
	else if (volume == "Italian")		window.location = "../index-i.html";
	else if (volume == "Korean")		window.location = "../k/index.html";
	else if (volume == "Japanese")		window.location = "../index-j.html";
	else if (volume == "Taiwanese")		window.location = "../index-t.html";
	else
	{
		window.location = "../index.html";
	}

}
	


function openPhotoLink(noFlashLink, flashLink)
{
	window.open(isFlash?flashLink:noFlashLink, 'null', 'height=600, width=980, top=10, left=10, location=1, status=1, titlebar=1, menubar=1, resizable=1, scrollbars=yes, directories=1, toolbar=1');				
}





function processXmlRest()
{
   try
   {
	timer = null;

  	var htmlData;

	if(isIE)
	{
		//TODO: Optimize - put xslProc at global level, use reset()
		var xslProc;
		xslProc = xslWeb.createProcessor();
		xslProc.input = xmlData;

		xslProc.addParameter("pageName",initPage);
		xslProc.addParameter("isFirst","false");
		xslProc.addParameter("footer1",footer1);
		xslProc.addParameter("footer2",footer2);
		xslProc.addParameter("footer3",footer3);
		xslProc.addParameter("footer4",footer4);

		xslProc.transform();
        	htmlData = xslProc.output;
		xslProc = null;
	}
	else
	{		
		xslWeb.setParameter(null,"isFirst","false");
	
		htmlData = objSerializer.serializeToString(xslWeb.transformToFragment(xmlData, document));
	}

	document.getElementById("data").innerHTML += htmlData;
	document.getElementById("loading").style.display = "none";
	xslWeb = null;
	xmlData = null;
	xmlMetadata = null;
	objSerializer = null;
  
	// hack: load SexyLightBox after all transformation
	new SexyLightBox({color:'black'});
 }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'processXMLRest()' modul.");
	redirectToStaticContent();
   }
}

function processXmlData()
{
   try
   {
	if(xmlHttp.readyState == 4)
	{
	  	var htmlData;

		if(isIE)
		{
			//xmlData = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
	        	xmlData.loadXML(xmlHttp.responseText);
			//alert(xmlData.xml);

			xslWeb = new ActiveXObject("Msxml2.XSLTemplate.3.0");
	        	xslWeb.stylesheet = xslMetadata;

			var xslProc;
			xslProc = xslWeb.createProcessor();
			xslProc.input = xmlData;

			xslProc.addParameter("pageName",initPage);
			xslProc.addParameter("isFirst","true");
			xslProc.addParameter("footer1",footer1);
			xslProc.addParameter("footer2",footer2);
			xslProc.addParameter("footer3",footer3);
			xslProc.addParameter("footer4",footer4);

			xslProc.transform();

			// For reusing possibly needed reset()
			//xslProc.reset();

	        	htmlData = xslProc.output;
		}
		else
		{
	        	xmlData = xmlHttp.responseXML;
			//alert(objSerializer.serializeToString(xmlData));

			//HACK: xsl:if test(concat(../@volume,' ',@id)=$pageName)
			xslWeb.setParameter(null,"pageName",initPage);
			xslWeb.setParameter(null,"isFirst","true");
			xslWeb.setParameter(null,"footer1",footer1);
			xslWeb.setParameter(null,"footer2",footer2);
			xslWeb.setParameter(null,"footer3",footer3);
			xslWeb.setParameter(null,"footer4",footer4);
	
			htmlData = objSerializer.serializeToString(xslWeb.transformToFragment(xmlData, document));
		}

		document.getElementById("data").innerHTML += htmlData;

		// expected initPage was extracted from URL in startMe()
		// if the initPage is empty or non-existent
		// default init is "English Homepage";
		switchPage(checkAvailability(initPage));

		document.getElementsByTagName("body")[0].style.cssText = "BACKGROUND-COLOR: #FFFFFF;";

		timer = setTimeout(processXmlRest, 300);
	}
	
   }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'processXMLData()' modul.");
	redirectToStaticContent();
   }
}






function processXmlGlobal()
{
   try
   {
	if(xmlHttp.readyState == 4)
	{
		if (!isIE)
		{
			//Global doesn't use transformation, it traverses xml manualy
			xmlData = xmlHttp.responseXML;
			//alert(objSerializer.serializeToString(xmlData));

			footer1 = xmlData.getElementsByTagName("TT3")[0].firstChild.nodeValue;
			footer2 = xmlData.getElementsByTagName("T3")[0].firstChild.nodeValue;
			footer3 = xmlData.getElementsByTagName("T3")[1].firstChild.nodeValue;
			footer4 = xmlData.getElementsByTagName("T3")[2].firstChild.nodeValue;

			var colLanguages = xmlData.getElementsByTagName("languages")[0].childNodes;
		}
		else
		{
			xmlData = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
			xmlData.loadXML(xmlHttp.responseText);
			//alert(xmlData.xml);
			footer1 = xmlData.childNodes(1).childNodes(1).childNodes(0).text;
			footer2 = xmlData.childNodes(1).childNodes(1).childNodes(1).text;
			footer3 = xmlData.childNodes(1).childNodes(1).childNodes(2).text;
			footer4 = xmlData.childNodes(1).childNodes(1).childNodes(3).text;
			
			var colLanguages = xmlData.childNodes(1).childNodes(0).childNodes;
		}

		var s = "<select onchange='switchLanguage(this.options[this.selectedIndex].value)' style='WIDTH: 150px; HEIGHT: 20px;' type='select-one'>";

		for (i=0; i < colLanguages.length; i++)
		{
			// IE filters out text and comment nodes by itself, others not
			if (isIE || (colLanguages[i].nodeType != 3 && colLanguages[i].nodeType != 8))
			{
				if (isIE)
				{
					var lang = colLanguages[i].text;
				}
				else
				{
					var lang = colLanguages[i].firstChild.nodeValue;
				}

				s += "<option " + ((lang==initVolume)?"selected":"") + " value='" + lang + "'>&nbsp;&nbsp;&nbsp;" + lang + "</option>";
			}
		}

		s += "</select>";

		document.getElementById("menuLanguages").innerHTML = s;

		loadVolume(initVolume);
	}
   }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'processXMLGlobal()' modul.");
	redirectToStaticContent();
   }
}








// dataVolume: "Global", "English", "Czech", ...
function loadVolume(dataVolume)
{
   try
   {
	if (!isIE)
	{
		//xmlHttp = new XMLHttpRequest(); //not needed already in place
	}
	else
	{
		xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
	}

	if (dataVolume == "Global")
	{
		xmlHttp.onreadystatechange = processXmlGlobal;
	}
	else
	{
		xmlHttp.onreadystatechange = processXmlData;
	}

	xmlHttp.open("GET",fileURL(dataVolume),true);
	xmlHttp.send(null);

	// optimalization
	if (dataVolume != "Global")
	{
		if (!isIE)
		{
			//xslWeb = new XSLTProcessor(); //see optimalization in init()
			xslWeb.importStylesheet(xslMetadata);
		}
	}
   }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'loadVolume()' modul.");
	redirectToStaticContent();
   }

}












//get called upon 'web.xsl' has been loaded
function startMe()
{	
	// gets intended page and language from URL
	document.getElementById("initLocation").innerText = window.location; //debug and hack
	initPage = getPageNameFromURL(document.getElementById("initLocation").innerText);

	initVolume = getVolume(initPage);

	// loads global containing languages etc. and then calls loadVolume(volume) twice
	loadVolume("Global");
}











function processXslMetadata()
{
   try
   {
	if(xmlHttp.readyState == 4)
	{
		if(isIE)
		{
			xslMetadata = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
	        	xslMetadata.loadXML(xmlHttp.responseText);
			//alert(xslMetadata.xml);
		}
		else
		{
			xslMetadata = xmlHttp.responseXML;
			//alert(objSerializer.serializeToString(xslMetadata));
		}
		startMe();
	}
   }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'processXslMetadata()' modul.");
	redirectToStaticContent();
   }
}









function init()
{
   try
   {
	// downloads stylesheet asynchronously using XMLHTTP
	if (!isIE)
	{
		xmlHttp = new XMLHttpRequest();
	}
	else
	{
		xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
	}


	xmlHttp.onreadystatechange = processXslMetadata;
	xmlHttp.open("GET","system/web.xsl",true);
	xmlHttp.send(null);

	// optimalization: creates objects while awaiting the stylesheet
	// beware though: unexpected but potential timing issue
	if(!isIE)
	{
		xslWeb = new XSLTProcessor();
		objSerializer = new XMLSerializer();
	}
	isFlash = (com.deconcept.FlashObjectUtil.getPlayerVersion()['major'] >= 6);
   }
   catch(e)
   {
	alert("Tip: Use the most current version of the browser\n"
		+ "to assure our server is serving the actual data\n\n\n"
		+ "Minor: Issue in 'init()' modul.");
	redirectToStaticContent();
   }
}

//init() starts everything
init();