/* Version: 1.05 : Revision: 5 - 12/03/2009 */

document.observe('dom:loaded', sacftf08_init);

var sacftf08_Server = null;

function sacftf08_init()
{
	var nsFrame = 'sacftf08_';
	sacftf08_Server = new sacftf08_ClientServer(nsFrame);
}

function sacftf08_CallForNavigation(navObject)
{
	if (sacftf08_Server)
	{
		if (false == navObject)
		{
			return sacftf08_Server.getNavObjects();
		} else {
			var eventType = navObject.eventType;
			var parentIndex = navObject.parentIndex;
			var navIndex = (navObject.navIndex  || navObject.navIndex == 0) ? navObject.navIndex : null;
			var URL = (navObject.href) ? navObject.href : null;
	
			sacftf08_Server.callForNavigation(eventType, parentIndex, navIndex, URL);
		}
	}
}

function sacftf08_getMoodPlayerFile()
{
	if (sacftf08_Server)
	{
		var file = sacftf08_Server.collectMoodFile();
		return file;
	}
}

function sacftf08_resetFlashHeader()
{
	if (sacftf08_Server)
	{
		sacftf08_Server.resetFlashHeader();
	}
}

function sacftf08_controlOverflow(data)
{
	if (sacftf08_Server)
	{
		var overflowHeight = sacftf08_Server.flashHeightDefault + (data - 91);
		sacftf08_Server.controlFlashOverflow(overflowHeight);
	}
}

//----------------------------------------[ CLASS: CLIENT SERVER ]
var sacftf08_ClientServer = Class.create
({
	initialize: function(frame)
	{
		this.nsPrefix = frame;
		this.hoverNavElement = null;
		this.activatedNavElement = null;
		this.contentClass = '.' + this.nsPrefix + 'page_content';
		this.scratchID = this.nsPrefix + 'scratch';
		this.frame = $(frame + 'frame');
		this.moodFile = null;
		this.adjustEnvironment();
		this.XHR = null;
		this.setupXHRSupport();
		
		this.siteNavElements = new Array();
		this.siteIndexURL = null;
		this.activeNavIndex = null;
		this.rmlsMap = null;

		this.flashHeader = null;
		this.flashCheck = null;
		this.checkCount = 0;
		this.flashHeightDefault = 364;
		this.setupFlashHeader();

		this.privilegedOptions = {};
		this.setupPrivilegedContent();
	},

	adjustEnvironment: function()
	{
		var flashVersion = swfobject.getFlashPlayerVersion();
		
		if (this.frame)
		{
			var parentTable = this.frame.up('table');
			if (null != parentTable)
			{
				parentTable.cellSpacing = 0;
				parentTable.cellPadding = 0;
			}
			if (0 != flashVersion.major)
			{
				this.removeEUEMessage();
				this.backFillHeader();
				this.allowSpaceForFlash();
				this.checkForMood();
			}
		}
	},

	setupXHRSupport: function()
	{
		if (this.frame) this.XHR = new sacftf08_XHRSupport(this.frame);
	},

	removeEUEMessage: function()
	{
		var message = $('non_enhanced_message');
		if (message) message.hide();
	},
	
	backFillHeader: function()
	{
		var backFill = document.createElement('div');
		Element.extend(backFill);
		backFill.addClassName('back_fill');
		this.frame.insert({ top: backFill });
	},
	
	allowSpaceForFlash: function()
	{
		var column2 = this.frame.down('div.column_2');
		if (column2) column2.addClassName('dynamic2');
	},
	
	setupPrivilegedContent: function()
	{
		this.XHR.postURL = sacftf08_systemVars.privilegedContentPage;
		this.XHR.read(null, this.onReadPrivilegedPage.bind(this));
	},
	
	onReadPrivilegedPage: function(transport)
	{
		if (transport.responseText)
		{
			this.privilegedOptions.title = this.getPageTitle(transport.responseText);
			var content = this.stripScripts(transport.responseText);
			var scratch = this.setupScratchArea();
			if (scratch)
			{
				scratch.update(content);
				this.collectPageCompElements(this.privilegedOptions, scratch);
				scratch.remove();
			}
		}
	},

	collectPageCompElements: function(obj, scratch)
	{
		if (obj && scratch)
		{
			var form = scratch.down('form', 1);
			obj.form = (form) ? form.name : false;
			var input = form.down('input', 1);
			obj.input = (input) ? input.name : false;
		}
		return obj;
	},
	
	getPageTitle: function(data)
	{
		var code = false;
		if (Object.isString(data))
		{
			var regex = /<title>(.*)<\/title>/i
			var search = data.match(regex);
			if (search) code = search[1];
		}
		return code;
	},
	
	stripScripts: function(data)
	{
		var code = false;
		if (Object.isString(data))
		{
			var regex = /<script\s.*<\/script>/gi
			code = data.replace(regex, '');
		}
		return code;
	},
	
	setupFlashHeader:function()
	{
		var handler = this.checkFlashLoaded.bind(this);
		new PeriodicalExecuter(handler, 0.5);
	},
	
	checkFlashLoaded: function(flashCheck)
	{
		this.checkCount ++;
		this.flashHeader = $(this.nsPrefix + 'flash_header');
		if (this.flashHeader)
		{
			flashCheck.stop();
			this.allowSpaceForFlash();
			this.setupNavigation();
		}
		if (this.checkCount >= 20)
		{
			flashCheck.stop();
		}
	},
	
	flashInstallTerminated: function()
	{
		var bf = this.frame.down('.back_fill');
		if (bf) bf.remove();
		$('non_enhanced_message').show();
		var column2 = this.frame.down('div.column_2');
		if (column2) column2.removeClassName('dynamic2');
		swfobject.expressInstallCallback();
	},
	
	setupNavigation: function()
	{
		this.registerSiteIndex();
		var navBlock = $(this.nsPrefix + 'navigation');
		var link = new sacftf08_NaviElement(navBlock, 0, null);
		this.siteNavElements[0] = link.getNavObject();
		
		var siteLocationParams = document.location.href.toQueryParams();
		if (siteLocationParams.sacftf08_ref)
		{
			this.siteNavElements[0].navBack = siteLocationParams.sacftf08_ref;
		}
		this.repurposeInternalLinks();
		this.repurposeVideoLinks();
	},

	getNavObjects: function()
	{
		var code = false;
		if (this.siteNavElements.length) code = this.siteNavElements;
		return code;
	},
	
	registerSiteIndex: function()
	{
		var location = document.location.href;
		var params = location.toQueryParams();
		var regex = /^(.*)\?(.*)$/;
		var base = regex.exec(location);
		this.siteIndexURL = (base && base.length) ? base[1] + '?cref=' + params.cref : location;
	},

	repurposeInternalLinks: function()
	{
		if (this.frame)
		{
			var links = this.frame.down(this.contentClass).select('A.' + this.nsPrefix + 'internal');
			if (0 < links.length)
			{
				var handler = this.onInternalLink.bind(this);
				var disable = function(){ return false; }
				links.each(function(link)
				{
					link.onclick = disable;
					link.observe('click', handler);
				});
			}
			var swfLink = this.frame.down(this.contentClass).down('A.swf_link');
			if (swfLink)
			{
				swfLink.onclick = function(){ return false; }
				var handler = this.openSWFWindow.bind(this);
				swfLink.observe('click', handler);
			}
		}
	},
	
	onInternalLink: function(event)
	{
		event.stop();
		var element = event.element();
		if ('A' == element.tagName)
		{
			var regex = /^(.*)index\.html$/
			if (regex.match(element.href)) element.href = this.siteIndexURL;
			this.requestSitePage(element.href);
		}
	},
	
	openSWFWindow: function(event)
	{
		var swfLink = event.element();
		if ('A' == swfLink.tagName)
		{
			var windowOptions = 'width=780, height=510, location=no, menubar=no, resizable=no, scrollbars=no, status=no, toolbar=no, left=60, top=60';
			var swfWindow = window.open(swfLink.href, 'sacftf08_swf', windowOptions);
		}
	},
	
	callForNavigation: function(eventType, parentIndex, navIndex, URL)
	{
		switch (eventType)
		{
			case 1 :
				this.hoverNavElement = this.siteNavElements[0].subLevel[parentIndex];
				this.hoverNavElement.hoverOn();
				break;
			case 2 :
				this.hoverNavElement.hoverOff();
				break;
			case 3 :
				var pointer = 0;
				var elements = this.siteNavElements[0].subLevel;
				elements.each(function(element)
				{
					element.clickOn(pointer == parentIndex);
					pointer ++;
				});
				this.activatedNavElement = this.siteNavElements[0].subLevel[parentIndex];
				this.activeNavIndex = navIndex;
				this.requestSitePage(URL);
				break;
			case 4 :
				this.requestSitePage(this.siteIndexURL);
				break;
			case 5 :
				this.requestSitePage(URL);
				break;
		}
	},
	
	requestSitePage: function(URL)
	{
		var scratch = this.setupScratchArea();
		var handler = this.onCompleteTransport.bind(this);
		var lcURL = URL.toLowerCase();
		var lcIndex = this.siteIndexURL.toLowerCase();
		if (lcURL === lcIndex && this.activatedNavElement)
		{
			this.flashHeader.homePageCalled();
			this.activatedNavElement.clickOn(false);
		}
		this.XHR.requestToGetURL(scratch, URL, handler);
	},
	
	setupScratchArea: function()
	{
		var code = false;
		if (!$(this.scratchID))
		{
			var scratchElement = document.createElement('div');
			Element.extend(scratchElement);
			scratchElement.id = this.scratchID;
			scratchElement.hide();
			this.frame.appendChild(scratchElement);
			code = scratchElement;
		} else {
			code = $(this.scratchID);
		}
		return code;
	},
	
	onCompleteTransport: function(transport)
	{
		var status = transport.status;
		var scratch = $(this.scratchID);
		switch (status * 1)
		{
			case 404 : this.displayPageNotFound();
				break;
				
			default :
				var privilegedPage = this.checkForPrivilegedPage(transport.responseText, scratch);
				if (!privilegedPage && scratch)
				{
					var content = scratch.down(this.contentClass);
					if (content)
					{
						var contentTarget = this.frame.down(this.contentClass);
						contentTarget.hide();
						contentTarget.update(content.innerHTML);
						scratch.remove();
						scratch = null;
						this.removeEUEMessage();						
						this.allowSpaceForFlash();
						this.repurposeInternalLinks();
						this.checkForLearningSpacesMap();
						this.repurposeVideoLinks();
						this.checkForMood();
						contentTarget.show();
						this.resetFlashHeader();

					} else {
						this.displayPageNotFound();
					}
					
				} else {
					var siteParams = this.siteIndexURL.toQueryParams();
					if (siteParams)
					{			
						if (siteParams.cref)
						{
							var QS = encodeURIComponent('cref=' + siteParams.cref + '&sacftf08_ref=' + this.activeNavIndex);
							var redirect = sacftf08_systemVars.privilegedContentLoginPage + '?URL=/Generic.asp&inpOriginalProtocol=http&QS=' + QS;

							if (redirect) document.location.href = redirect;
						}
					}
				}
				break;
		}
		if (scratch) scratch.remove();
		transport = null;
	},
	
	checkForPrivilegedPage: function(data, scratch)
	{
		var code = false;
		if (Object.isString(data) && scratch)
		{
			var pageComp = {};
			pageComp.title = this.getPageTitle(data);
			pageComp = this.collectPageCompElements(pageComp, scratch);
			
			var values  = Object.values(pageComp);
			var options = Object.values(this.privilegedOptions);
			var pointer = 0;
			var matched = 0;
			values.each (function(value)
			{
				if (options[pointer] == value) matched ++;
			});
			if (values.length = matched) code = true;
		}
		return code;
	},
	
	repurposeVideoLinks: function()
	{
		var resourceLists = null;
		resourceLists = this.frame.select('.resource_list');
		var vHandler = this.loadVideo.bind(this);
		resourceLists.each( function(list)
		{
			var videos = list.select('.video');
			if (0 < videos.length)
			{
				var disable = function(){ return false; }
				videos.each( function(video)
				{
					var vLinks = video.select('a');
					vLinks.each(function(vLink)
					{
						vLink.onclick = disable;
						vLink.observe('click', vHandler);
					});
				});
			}
		});
	},
	
	checkForMood: function()
	{
		var mood = this.frame.down('#' + this.nsPrefix + 'moodFile');
		if (mood)
		{
			var moodData = {};
			moodData.moodFile = mood.value;
			var link = this.frame.down('#' + this.nsPrefix + 'moodLink');
			moodData.moodLink = (link) ? link.value : false;
			var linkInternal = this.frame.down('#' + this.nsPrefix + 'moodLinkInternal');
			if (linkInternal)
			{
				moodData.linkInternal = ('true' == linkInternal.value) ? true : false;
			} else {
				moodData.linkInternal = false;
			}
			this.setMoodFile(moodData);
			moodData = null;
		}
	},
	
	setMoodFile: function(fileName)
	{
		this.moodFile = fileName;
	},
	
	collectMoodFile: function()
	{
		var code = null;
		if (this.moodFile)
		{
			code = this.moodFile;
		}
		return code;
	},
	
	passMoodFile: function()
	{
		var file = this.collectMoodFile();
		if (file) this.flashHeader.passMoodFile(file);
	},
	
	loadVideo: function(event)
	{
		event.stop();
		var vLink = event.element();
		if ('A' != vLink.tagName) vLink = event.findElement('A');
		if (vLink)
		{
			var query = vLink.href.toQueryParams();
			if (this.flashHeader)
			{
				var videoResourceID = encodeURI(query.sacftf08_video).replace(/%20/g, '_');
				this.flashHeader.loadVideoFile(videoResourceID);
			}
		}
	},
	
	resetFlashHeader: function()
	{
		if (this.flashHeader)
		{
			this.flashHeader.resetMoodPlayer();
			var height = this.getFlashHeaderHeight();
			if (height != this.flashHeightDefault)
			{
				this.delayedHeaderReset(this.flashHeightDefault);
			}
		}
	},
	
	getFlashHeaderHeight: function()
	{
		var code = false;
		if (this.flashHeader)
		{
			code = this.flashHeader.getStyle('height').replace('px', '');
		}
		return code;
	},
	
	delayedHeaderReset: function(value)
	{
		var toHandler = this.setFlashHeaderHeight.bind(this);
		var handler = function(){ toHandler(value); }
		setTimeout(handler, 600);
	},
	
	controlFlashOverflow: function(value)
	{
		if (this.flashHeader)
		{
			var height = this.getFlashHeaderHeight();
			if (height > value)
			{
				this.delayedHeaderReset(value);
			} else {
				this.setFlashHeaderHeight(value);
			}
		}
	},
	
	setFlashHeaderHeight: function(value)
	{
		if (this.flashHeader)
		{
			this.flashHeader.setStyle({ height: value + 'px' });
		}
	},
	
	checkForLearningSpacesMap: function()
	{
		var rmLS = $(this.nsPrefix + 'learning_spaces');
		if (rmLS)
		{
			this.rmlsMap = null;
			this.rmlsMap= new sacftf08_LearningSpaces(this);
		}
	},
	
	displayPageNotFound: function(message)
	{
		if (!message)
		{
			message = '<p>We are sorry but the page you requested has not been found.</p>';
		}
		this.frame.down(this.contentClass).update(message);
	}
});

//----------------------------------------[ CLASS: XHR SUPPORT ]
var sacftf08_XHRSupport = Class.create
({
	initialize: function(environment)
	{
		this.environment = environment;
		this.postURL = null;
		this.progress = null;
		this.method = 'get';
		this.evalJS = false;
		this.setupProgressIcon();
	},
	
	setupProgressIcon: function()
	{
		this.progress = document.createElement('div');
		Element.extend(this.progress);
		this.progress.id = 'xhr_progress';
		this.progress.hide();
		this.environment.appendChild(this.progress);
		Ajax.Responders.register(this.XHRProgress);
	},

	XHRProgress: 
	{
		onCreate: function()
		{
			$('xhr_progress').show('block');
		},
	
		onComplete: function()
		{
			$('xhr_progress').hide();
		}
	},
	
	requestToGetURL: function(receiver, URL, complete)
	{
		if (receiver && URL)
		{
			this.postURL = URL;
			this.readAndUpdate(receiver, null, complete);
		}
	},
	
	readAndUpdate: function(receiver, serialized, complete)
	{
		var xhrPrefix = '';
		var options = xhrPrefix + serialized;
		var request = new Ajax.Updater(receiver, this.postURL, { parameters: options, method: this.method, evalScripts: this.evalJS, onComplete: complete });
		request = null;
	},
	
	read: function(serialized, success)
	{
		var xhrPrefix = '';
		var options = xhrPrefix + serialized;
		var request = new Ajax.Request(this.postURL, { method: this.method, parameters: options, evalJS: false, onSuccess: success });
		request = null;
	},
		
	setXHRMethod: function(method)
	{
		if ('post' === method || 'get' === method)
		{
			this.method = method;
		}
		return this.method;
	}	
});

//------------------------------------------------[ CLASS: NAVIGATION ELEMENT ]
var sacftf08_NaviElement = Class.create
({
	initialize: function(element, index, clientServer)
	{
		this.element = element;
		this.index = index.toString();
		this.linkHREF = null;
		this.label = null;
		this.subLevel = null;
		this.setupNaviElement();
		this.server = clientServer;
		this.activated = false;
	},

	getNavObject: function()
	{
		var nav = new Object();
		nav.label = this.label;
		nav.href = this.linkHREF.toString();
		nav.subLevel = this.subLevel;
		nav.hoverOn = this.onCloneOver.bind(this);
		nav.hoverOff = this.onCloneOut.bind(this);
		nav.clickOn = this.onCloneClick.bind(this);
		return nav;
	},

	setupNaviElement: function()
	{
		var lHandler = function(){ return false; };
		if ('DIV' == this.element.tagName || 'LI' == this.element.tagName)
		{
			var link = this.element.down('A');
			link.onclick = lHandler;
			this.linkHREF = link.href;
			this.label = link.innerHTML;
			this.checkForSubLevel();
		}
	},

	checkForSubLevel: function()
	{
		var list = this.element.down('UL');
		if (list)
		{
			var children = list.childElements();
			var pointer = 0;
			var index = this.index;
			var subLevel = new Array();
			children.each( function(item)
			{
				itemIndex = index + pointer.toString();
				var navObj = new sacftf08_NaviElement(item, itemIndex, null);
				subLevel.push(navObj.getNavObject());
				pointer ++;
			});
			this.subLevel = subLevel;
		}
	},

	onCloneOver: function()
	{
		this.element.addClassName('over');
	},

	onCloneOut: function()
	{
		this.setNavElementClass('over', this.activated);
	},

	onCloneClick: function(activeState)
	{
		this.setActiveState(activeState);
	},
	
	setActiveState: function(activeState)
	{
		this.activated = activeState;
		this.setNavElementClass('over', this.activated);
	},
	
	setNavElementClass: function(className, state)
	{
		(true == state) ? this.element.addClassName(className) : this.element.removeClassName(className);
	},
	
	getNavElementHREF: function()
	{
		if (this.linkHREF) return this.linkHREF;
	},
	
	getNavLabel: function()
	{
		if (this.label) return this.label;
	},
	
	getSubLevel: function()
	{
		if (this.subLevel) return this.subLevel;
	}
});

//----------------------------------------[ CLASS: LEARNING SPACES ]
var sacftf08_LearningSpaces = Class.create
({
	initialize: function(cServer)
	{
		this.server = cServer;
		this.frame = cServer.frame;
		this.ls = $(cServer.nsPrefix + 'learning_spaces');
		this.imageURL = '_RMVirtual/Media/Images/';
		this.repurposeMapLinks();
		this.buildMapImages();
	},
	
	repurposeMapLinks: function()
	{
		var mapLinks = this.frame.select('.learning_space');
		if (mapLinks)
		{
			var disable = function(){ return false; }
			var mOverHandler = this.onMouseOver.bind(this);
			var mOutHandler = this.onMouseOut.bind(this);
			var onClick = this.onClick.bind(this);
			mapLinks.each( function(link)
			{
				link.onclick = disable;
				link.observe('mouseover', mOverHandler);
				link.observe('mouseout', mOutHandler);
				link.observe('click', onClick);
			});
		}
	},
	
	onMouseOver: function(event)
	{
		event.stop();
		var target = event.element();
		if (target)
		{
			if (!target.hasClassName('learning_space')) target = target.up('.learning_space');
			var classNames = $w(target.className)
			var map = $(classNames[1]);
			if (map) map.show();
		}	
	},

	onMouseOut: function(event)
	{
		event.stop();
		var target = event.element();
		if (target)
		{
			if (!target.hasClassName('learning_space')) target = target.up('.learning_space');
			var classNames = $w(target.className)
			var map = $(classNames[1]);
			if (map) map.hide();
		}
	},
	
	onClick: function(event)
	{
		event.stop();
		var target = event.element();
		if (target)
		{
			if (!target.hasClassName('learning_space')) target = target.up('.learning_space');
			if (target)
			{
				if (target.href)
				{
					var location = target.href;
				} else if (target.down('A')) {
					var location = target.down('A').href;
				}
				if (location) this.server.requestSitePage(location);
			}
		}
	},
	
	buildMapImages: function()
	{
		var mapTerms = this.frame.down('div.column_2').select('dt');
		if (mapTerms)
		{
			var parent = this.ls;
			var prefix = this.server.nsPrefix;
			var imageURL = this.imageURL;
			mapTerms.each( function(term)
			{
				var classNames = $w(term.className)
				var image = document.createElement('img');
				Element.extend(image);
				image.id = classNames[1];
				image.className = prefix + 'map';
				var mapNum = classNames[1].replace('map_', '');
				var imageURI = imageURL + prefix + 'ls-map-' + mapNum + '.png';
				image.src = imageURI;
				image.alt = 'RM Learning Spaces - floor plan';
				image.useMap = '#' + prefix + 'ls_map';
				image.hide();
				parent.insert({ top: image });
			});
		}
	}
});
