/**
	Loads the JSON file and initializes the loader
**/
function loadTsa(url, locale) {
	new Ajax.Request(url, {
		method: 'get',
		onSuccess : function(transport) {
			var theData = transport.responseText;
			var jsonData = eval('(' + theData + ')');

			var finalData;
			if (typeof(jsonData['data'][locale]) == 'object') {
				localizedData = jsonData['data'][locale];
			} 
			else if (typeof(jsonData['data']['en_US']) == 'object') {
				localizedData = jsonData['data']['en_US'];
			}
			else if (typeof(jsonData[locale]) == 'object') {
				localizedData = jsonData[locale];
			}
			else if (typeof(jsonData['en_US']) == 'object') {
				localizedData = jsonData['en_US'];
			}
			var loader = new tsaLoader(localizedData);
		}
	});
}


var tsaLoader = Class.create({

	initialize : function(localizedData) {
		this._decorate();
		tsaLoader.curPage = 1;
		this.pageObject = localizedData;
		this.parentObject = parent;
		this.visitedSections = new Array();

		this.buildStages();				//Creates the first page, and the container which holds the sections
		this.buildMenu();				//Creates the navigation and events
		this.markChecks();				//Marks the checks read from the cookie

		//
		var homeSection = Builder.node('div', { id : 'page_0', className : 'page', style : 'display:none;'} , [
			Builder.node('h2', this.pageObject.stageTitle),
			Builder.node('div', { className : 'blurb'}),
			Builder.node('div', { className : 'image'}, [
				Builder.node('img', { src : this.pageObject.stageImg })
			]),
			Builder.node('div', { className : 'sectionbottom' }, [
			//Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, 'Begin' )
			Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, this.pageObject.navBegin )
			])
		]);

		$('tsamain').appendChild(homeSection);

		Event.observe($('page_0').getElementsByClassName('nextlink')[0], 'click', this.showSection.bind(this, 1));

		homeSection.getElementsByClassName('blurb')[0].innerHTML = this.pageObject.stageText;

		this.buildSections();			//Builds out each section from the JSON file
		var modules = $$('.module');
		this.stageModule = modules[0];
		this.tsaModule = modules[1];
		this.findFirstPage();			//Find out where the user wants to go

		//Init Hash handling
		window.setInterval(this.handleHistory.bind(this), 500);
		//Begin	button... 
		for ( i in this.pageObject.otherLinks ) {
			var link = Builder.node('a', { className : 'more grey', href : this.pageObject.otherLinks[i].linkHref }, this.pageObject.otherLinks[i].linkTitle);
			$('otheroptions').appendChild(Builder.node('br'));
			$('otheroptions').appendChild(link);
		}
	},

	/*	Load Helpers 	*/

	buildStages : function() {
		$('heading').innerHTML = this.pageObject.title;		//Currently not displayed

		this.tsaContainer = Builder.node('div', { id : 'tsainner', className : 'grid2cold' }, [
			Builder.node('div', { id : 'subnav', className : 'column first' }),
			Builder.node('div', { id : 'otheroptions'}),
			Builder.node('div', { id : 'tsamain', className : 'column last'})
		]);
		$('tsa').appendChild(this.tsaContainer);
	},

	buildMenu : function() {
		var ul = Builder.node('ul');
		var li, curClass;

		$('subnav').appendChild(ul);
		for (i in this.pageObject.pages) {
			li = Builder.node('li', { id : 'l_' + i}, [
				Builder.node('a', { href : 'javascript:;' }, this.pageObject.pages[i].menuTitle)
			] );
			ul.appendChild(li);
			var p = i;
			Event.observe(li,'click', this.showSection.bind(this, p));
		}
	},

	buildSections : function() {

		for (var i in this.pageObject.pages) {
			new tsaSection(this.pageObject.pages[i], i, this.pageObject);

			if (parseInt(i) >= this.pageObject.lastPage) {
//				var lastPage = Builder.node('div', { className : 'sectionbottom'}, [ Builder.node('h3') ]);

				var lastPage = Builder.node('div', { className : 'sectionbottom' }, [
					//Builder.node('a', { href : 'javascript:;', className : 'prevlink' }, 'Back' )
					Builder.node('a', { href : 'javascript:;', className : 'prevlink' }, this.pageObject.navBack )
				]);

				var finalThought = Builder.node('div', { className : 'finalthought'}, [ Builder.node('h3') ]);
				finalThought.getElementsByTagName('h3')[0].innerHTML = this.pageObject.finishedTitle;


				var span = Builder.node('div');
				finalThought.appendChild(span);


				span.innerHTML = this.pageObject.finishedText;
				$('page_' + i).appendChild(lastPage);
				$('page_' + i).appendChild(finalThought);
				Event.observe(lastPage.getElementsByTagName('a')[0], 'click', this.showSection.bind(this, parseInt(i)-1));

			} else {
				if ( parseInt(i) > 1 ) {
					var bottomArea = Builder.node('div', { className : 'sectionbottom' }, [
						//Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, 'Next' ),
						//Builder.node('a', { href : 'javascript:;', className : 'prevlink' }, 'Back' )
						Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, this.pageObject.navNext ),
						Builder.node('a', { href : 'javascript:;', className : 'prevlink' }, this.pageObject.navBack )
					]);
					Event.observe(bottomArea.getElementsByTagName('a')[1], 'click', this.showSection.bind(this, parseInt(i)-1));
				} else {
					var bottomArea = Builder.node('div', { className : 'sectionbottom' }, [
						//Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, 'Next' )
						Builder.node('a', { href : 'javascript:;', className : 'nextlink' }, this.pageObject.navNext )
					]);
				}
				$('page_' + i).appendChild(bottomArea);
			}
			var nextSection = (parseInt(i)+1);
			Event.observe(bottomArea.getElementsByTagName('a')[0], 'click', this.showSection.bind(this, nextSection));
		}
	},

	/* Module decorator script for support... was conflicting when done externally */

	_decorate : function() {
		var inputs=document.getElementsByTagName('div');
		for(var i=0;i<inputs.length;i++){
			if(Element.hasClassName(inputs[i],'module')){
				var original = inputs[i];
				original.className = original.className.replace('module', 'br');
				var mo = document.createElement('div');
				mo.className = 'module';
				original.parentNode.replaceChild(mo, original);
				var tl = document.createElement('div');
				tl.className = 'tl';
				var tr = document.createElement('div');
				tr.className = 'tr';
				var bl = document.createElement('div');
				bl.className = 'bl';
				mo.appendChild(tl);
				tl.appendChild(tr);
				tr.appendChild(bl);
				bl.appendChild(original);
			}
		}
	},

	markChecks : function() {
		var visitedString = this._readCookie(this.pageObject.tsaId + '_ph');
		if (visitedString != null ) {
			visitedString = visitedString.replace("--", "-");
			if (visitedString.length > 1) {
				var visitedArray = visitedString.split("-");
				this.visitedSections = visitedArray;
				for (var i = 0; i < visitedArray.length; i++) {
					if (visitedArray[i] != '' && visitedArray[i] != 'undefined') {
						var myLink = $('l_' + visitedArray[i] ).select('a').first();
						myLink.addClassName('seen');
					}
				}
			}
		}
	},

	clearChecks : function() {
		var seenElements = $$('.seen');
		for (var i = 0; i < seenElements.length; i++) {
			seenElements[i].removeClassName('seen');
		}
		this.visitedSections = new Array();

		this._eraseCookie(this.pageObject.tsaId + '_lv');
		this._eraseCookie(this.pageObject.tsaId + '_ph');
	},

	/*	Navigation	*/

	begin : function() {
		this.stageModule.hide();
		this.tsaModule.show();
		this.showSection(1, true);
		clearInterval(this.wInterval);
	},

	startOver : function(){
		this.clearChecks();
		this.showSection(1);
	},

	showSection : function(p, force, builder) {
		if ($('page_0') != null) { $('page_0').hide(); }
		if( p <= this.pageObject.lastPage ) {
			if( !builder ){	
				if ($('returnhud') != null) { $('returnhud').hide(); }
				if ($('overlay') != null) { $('overlay').hide(); }
			}
			if(  p != tsaLoader.currentSection || force == true ) {
				if ($('page_' + tsaLoader.curPage) != null) { $('page_' + tsaLoader.curPage).hide(); }
				if ($('page_' + p) != null) { $('page_' + p).show(); }
				$('l_' + tsaLoader.curPage).down('a').removeClassName('selected');
				$('l_' + tsaLoader.curPage).removeClassName('selected');
				$('l_' + p).down('a').addClassName('selected');
				$('l_' + p).addClassName('selected');
				window.location.hash = 'section_' + p;
				this.addVisited(p);
				tsaLoader.curPage = p;
			}
		}
	},

	addVisited : function(pageNum) {
		var visitedString = this.visitedSections.join("-")
		visitedString = visitedString.substr(0, visitedString.length-1);
		this._createCookie(this.pageObject.tsaId + '_lv', pageNum);
		 if (visitedString.indexOf(parseInt(pageNum)) == -1 ) {
		 	this.visitedSections[this.visitedSections.length] = parseInt(pageNum);
			$('l_' + parseInt(pageNum)).select('a').first().addClassName('seen');
		 	this._createCookie(this.pageObject.tsaId + '_ph', visitedString + '-' + pageNum);
		 }
	},

	/*	Hash / Cookie Handling */

	handleHistory : function () {
		 if ( window.location.hash != this.expectedHash) {
		   	this.expectedHash = window.location.hash;
		    if (this.expectedHash.indexOf('_') != -1) {
				var newoption = this.expectedHash.split("_")[1];
		 		this.showSection(newoption, null, true);
			}
		 }			  
		 return true;
	},

	findFirstPage : function() {
		var lastVisited = this._readCookie(this.pageObject.tsaId + '_lv');
		if (lastVisited && lastVisited != 1) {
			this.showSection(lastVisited, true);
			this.displayHud(lastVisited);
		 }	else {
			$('page_0').show();
		}
	},

	_createCookie : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},

	_readCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},

	_eraseCookie : function(name) {
		this._createCookie(name,"",-1);
	},

	/*	HUD */
	displayHud : function(x) {
		if (x < this.pageObject.lastPage) {
			var thisSection = x;
			var nextSection = ( parseInt(x)+1 );

			Event.observe($('returnhud').select('a').first(), 'click', this.showSection.bind(this, thisSection));
			Event.observe($('returnhud').select('a')[1], 'click', this.startOver.bind(this));

			var width = document.viewport.getWidth();
			//Set a timer that will fix the hud when window resizes
			this.wInterval = setInterval(function() {
				var docheight = document.body.clientHeight
				var winheight = document.viewport.getHeight();
				height = winheight > docheight ? winheight : docheight + 100;
				$('overlay').style.height = height + 'px';
			}, 500);

			$('returnhud').style.left = (width / 2 - 260) + 'px' ;
			//Show the hud
			new Effect.Appear('overlay', { duration : .5});
			$('returnhud').show();
		} else {
			var firstPage = 1;
			Event.observe($('returnhud').select('a')[1], 'click', this.showSection.bind(this, firstPage));
			$('returnhud').select('a').first().remove();
			$('returnhud').show();
		}
	},
	_getKeys : function(o) {
		var a = new Array();
		for(var i in o){
			a[a.length] = i;
		}
		return a;
	}
});

var tsaSection = Class.create({

	initialize : function(section, sectionId, pageObject) {
		this.pageObject = pageObject;
		this.section = section;
		this.sectionId = sectionId;

		if (typeof(tsaLoader.loadedSections) == 'undefined') {
			tsaLoader.loadedSections = new Array();
		}

		var newSection = Builder.node('div', { id : 'page_' + sectionId, className : 'page', style : 'display:none;' } );
		newSection.appendChild(Builder.node('h3', section.pageTitle));

		$('tsamain').appendChild(newSection);

		for (var row in this.section.sectionRows) {
			newSection.appendChild(this.createRow(this.section.sectionRows[row], row));
		}

		section.notes = section.notes == undefined ? '' : section.notes;

		var notes = Builder.node('div', { className : 'notes' } );
		notes.innerHTML = section.notes;
		newSection.appendChild(notes);

	},

	createRow: function(row, x) {
		var newRow = Builder.node('div', { id : 'row_' + this.sectionId + '_' + x, className : 'row ' + row.className } );
		for (var i in row) {
			if ( i == 'text' ) {
				var blurb = Builder.node('div', { className : 'blurb' } );
				if ( blurb != null ) { newRow.appendChild(blurb); blurb.innerHTML = row[i][1] }
			} else if ( i == 'images' ) {
				var images = this.buildImages(row[i]);
			} else if ( i == 'imageSwap' ) {
				var swapObj = new tsaSwap(row[i]);
				var images = swapObj.getSwapper();
			}
		}

		if ( images != null ) { newRow.appendChild(images) }
		newRow.appendChild(Builder.node('div', { style : 'clear:both;' } ));
		return newRow;
	},

	buildImages : function(images) {
		var imageContainer = Builder.node('div', { className : 'image' });
		for(var i in images) {
			var imageHref = this._getKeys(images[i]);
			var imageAlt = images[i][imageHref];
			var imageNode = Builder.node('img', { src : imageHref, alt : imageAlt } );
			imageContainer.appendChild(imageNode);
		}
		return imageContainer;
	},

	_getKeys : function(o) {
		var a = new Array();
		for(var i in o){
			a[a.length] = i;
		}
		return a;
	}
});

var tsaSwap = Class.create({

	currentId : null,

	initialize : function(swapObject) {
		if(tsaSwap.curKey == undefined) {
			tsaSwap.curKey = 0;
		} else {
			tsaSwap.curKey++;
		}
		this.instanceKey = tsaSwap.curKey;
		this.swapObject = swapObject;
		this.swapChunk = this.buildOptions();

		//Fix swapper offset
		var linkDivs = $$('.links');
		for (var i = 0; i < linkDivs.length; i++) {
			links = linkDivs[i].getElementsByTagName('a');
			if( links[links.length-1] ) {
				links[links.length-1].addClassName('last');
			}
		} 
	},

	buildOptions : function() {
		var newSwap = Builder.node('div', { className : 'image' });
		var sView = Builder.node('div', { id : 'swapview' });
		var sLinks = Builder.node('div', { className : 'links' });

		// Check if this is an OS swap by looking for 'mac'
		var isOS = false;
		for (i in this.swapObject) {
			if (this.swapObject[i][3] == 'mac') {
				isOS = true;
				break;
			}
		}


		var curOs = this._getOS();

		for (i in this.swapObject) {
			var imageHref = this.swapObject[i][1];
			var linkTitle = this.swapObject[i][2];
			var boundOs = this.swapObject[i][3] != undefined ? this.swapObject[i][3] : null;
			var isDefault = false;

			if (isOS == true) {
				if (boundOs == curOs) isDefault = true;		// for OS swaps, default image is the one that matches detected OS
			} else {
				if (i == 1) isDefault = true;				// for generic swaps, default image is the first image
			}

			if (isDefault == true) {
				var curImage = Builder.node('img', { id : 'img_' + this.instanceKey + '_' + i, src : imageHref });
				var curLink = Builder.node('a', { id : 'link_' + this.instanceKey + '_' + i, href : 'javascript:;', className : 'current' }, linkTitle);
				this.currentId = i;
			} else {
				var curImage = Builder.node('img', { id : 'img_' +  + this.instanceKey + '_' + i, src : imageHref, style : 'display:none;' } );
				var curLink = Builder.node('a', { id : 'link_' + this.instanceKey + '_' + i, href : 'javascript:;' }, linkTitle);
			}

			this._addShowEvent(curLink, i);

			sView.appendChild(curImage);
			sLinks.appendChild(curLink);
			//Append to the dom.
		}

		newSwap.appendChild(sView);
		newSwap.appendChild(sLinks);
		return newSwap;
	},

	getSwapper : function() {
		return this.swapChunk;
	},

	_getOS : function() {
		var userAgent = navigator.userAgent;
		if (userAgent.indexOf("Windows NT 6.0") > -1) {
			return "vista";
		} else if (userAgent.indexOf("Windows NT 5.1") > -1 ) {
			return "xp";
		} else {
			return "mac";
		}
	},

	_addShowEvent : function(link, id) {
		Event.observe(link, 'click', this.showOption.bind(this, id));
	},

	showOption : function(id) {
		if (id != this.currentId) {
			$('link_' + this.instanceKey+ '_' + this.currentId).removeClassName('current');
			$('link_' + this.instanceKey+ '_' + id).addClassName('current');
			$('img_' + this.instanceKey+ '_'+ id).show();
			$('img_' + this.instanceKey+ '_' + this.currentId).hide();
			this.currentId = id;
		}
	}
});