// WikiPaths
// http://www.playwikipaths.com
// version 1.0 BETA!
// Alex Abreu, Tim Szetela
// WikiPaths and it's data are licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
// http://creativecommons.org/licenses/by-nc-sa/3.0/us/
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// For more information and a step by step guide to installation please visit: http://www.playwikipaths.com
//
// Feel free to contact us at team [at] playwikipaths [dot] com
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// To uninstall, go to Tools/Manage User Scripts,
//
// The WikiPaths team would like to thank Master Wiki, Stephen Dolan, for his amazing Six Degress of Wikipedia research.
// He can be reached at: mu [at] netsoc [dot] tcd [dot] ie
// Check out his site at: http://www.netsoc.tcd.ie/~mu/wiki/
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          WikiPaths
// @namespace     http://www.alexabreu.com/wiki
// @description   WikiPaths is a hyperlink scavenger hunt played on top of Wikipedia.
// @include       http://www.en.wikipedia.org/wiki/*
// @include       http://en.wikipedia.org/wiki/*
// @require   	  http://www.alexabreu.com/wiki/js/mootools-1.2.1.js
// @require   	  http://www.alexabreu.com/wiki/js/mootools-1.2-more.js
// @require   	  http://www.alexabreu.com/wiki/js/squeezebox.js
// @require   	  http://www.alexabreu.com/wiki/js/loadexternalfile.js
// @require   	  http://www.alexabreu.com/wiki/js/utilities.js
// @require   	  http://www.alexabreu.com/wiki/js/login.js
// @require   	  http://www.alexabreu.com/wiki/js/register.js

// ==/UserScript==

var PATHS_PER_GAME = 1;
var STARTING_SCORE = 0;
var VERSION = 1.0;

var roundCounter = 0;
var allAnchors;
var endPage = '0';
var currentPage = '1';
var pathScore = STARTING_SCORE;
var timeCounter = 0;
var timeString = "";
var nodeToolTips;
var goalToolTips;
var wikipediaPath = "http://en.wikipedia.org/wiki/";
var wikipathsURL = "http://en.wikipedia.org/wiki/path";
var gameDomainPath = "http://www.alexabreu.com/wiki/"
var shortestPathURL = "http://www.netsoc.tcd.ie/~mu/cgi-bin/shortpath.cgi";
var linkCounter = 0;
var gameStarted = false;


var leftPanel = new Element('div', {'id':'left-panel'});
var topFrame = new Element('div', {'id':'top-frame'});
var goalFrame = new Element('div', {'id':'goal-frame'});
var winFrame = new Element('div', {'id':'win-frame'});

var loaderWrapper = new Element('div', {'id':'loader-wrapper'});
var loaderContainer = new Element('div', {'id':'loader-container', 'text' : 'Loading Wikipedia article...'});

var playButton = new Element('div',{'id':'play-button'});
var playKey = new Element('li',{'id':'play-key', 'class':'generated-sidebar portlet', 'html':"<h5>WikiPaths</h5>"});
var playBox = new Element('div',{'id':'play-box', 'class':'pBody'});
var playLink = new Element('div',{'id':'play-link', 'html':"Play WikiPaths"});
var delay = null;


window.addEvent('keyup', function(e) {
	if (e.key == 'esc') {
		processGiveUp();
	}
	if (e.key == 'q') {
		post(gameDomainPath + '/php/win.php', '', processWin, 'html');
	}
	if (e.key == 't') {
		toggleTimeDisplay();
	}
});


window.addEvent('keydown', function(e) {
	//console.log(e.key);
});

window.addEvent('domready', function() {
	loadExternalFile(gameDomainPath + "css/wikipaths.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/sidemenu.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/topmenu.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/splash.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/goal.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/win.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/login.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/register.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/instructions.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/gamemode.css", "css"); ////dynamically load and add this .css file
	loadExternalFile(gameDomainPath + "css/squeezebox.css", "css"); ////dynamically load and add this .css file
	loadExternalFile("http://www.google.com/jsapi", "js");
	loadExternalFile(gameDomainPath + "js/mootools.js", "js");
	var favIcon = new Element('link', {'rel' : "SHORTCUT ICON", 'href' : gameDomainPath + "favicon.ico"});
	
	var browserPage = window.location.toString().toLowerCase();
	
	//if on Wikipedia article on "Path"
	if (browserPage == wikipathsURL) {
		var headTag = document.getElementsByTagName('head')[0];
		headTag.appendChild(favIcon);
		document.body.style.background = "url('')";
		document.body.style.background = "#FFFFFF";
		$('content').set('styles', {'margin-top' : '60px', 'margin-left' : '180px', 'width' :'84%'});
		$('content').set('class', 'ajax-loading');
		$('content').set('text', 'Transforming Wikipedia...');
	
		loadGUI();
	}
	else {			
		$('p-search').adopt(playKey);
		
		playKey.adopt(playBox);
		playBox.adopt(playLink);
		playBox.adopt(playButton);
        
		playButton.addEvent('click', function() {
			window.open(wikipathsURL, 'WikiPaths');
		});
		
		playLink.addEvent('click', function() {
			window.open(wikipathsURL, 'WikiPaths');
		});
	}
});

var checkForUpdate = function () {
	post(gameDomainPath + '/php/updater.php', 'user_version=' + VERSION, checkForUpdateCallback, '');
}

var checkForUpdateCallback = function (jsonObject) {
	console.log('user version: ' + VERSION);
	console.log('server version: ' + jsonObject[0].number );
	if  (jsonObject[0].number != null) {
		$('game-menu').setStyle('width', '600px');
		$('update-item').setStyle('display', 'inline');
		$('update-button').set('href', jsonObject[0].path);
		
		$('update-button').addEvent('click', function() {
			$('update-item').setStyle('display', 'none');
			$('game-menu').setStyle('width', '400px');
		});	
	}
}

var loadGUI = function () {
	document.body.appendChild(leftPanel);
	document.body.appendChild(topFrame);
	document.body.appendChild(goalFrame);
	loaderWrapper.adopt(loaderContainer);
	document.body.appendChild(loaderWrapper);
	
	post(gameDomainPath + '/php/sidemenu.php', '', initializeLeftPanel, 'html');
	post(gameDomainPath + '/php/topmenu.php', '', initializeTopFrame, 'html');
	post(gameDomainPath + '/php/goal.php', '', initializeGoalFrame, 'html');
	post(gameDomainPath + '/php/splash.php', '', initializeSplash, 'html');
}

var initializeSplash = function(responseObject) {
	$('content').set('html', responseObject.responseText);
	console.log(GM_getValue('last_game_type'));
	if (GM_getValue('last_game_type') != undefined && GM_getValue('last_game_type') != 0 && GM_getValue('logged_in') == 1 ) {
		$('user-container').setStyle('display', 'block');
		switch(GM_getValue('last_game_type')) {
			case 1:
				$('last-game-type').set('text', 'Time Trial');
			break;
			case 2:
				$('last-game-type').set('text', 'Distance');
			break;
			case 3:
				$('last-game-type').set('text', 'Biathlon');
			break;
		}
		$('last-game-score').set('text', GM_getValue('last_game_score'));
		$('last-game-links').set('text', GM_getValue('last_game_links'));
		$('last-game-time').set('text', GM_getValue('last_game_time'));
	}
	else {
		$('user-container').setStyle('display', 'none');
	}
}


var initializeLeftPanel = function(responseObject) {
	var leftPanelMorph = new Fx.Morph('left-panel', {duration: 'long', transition: Fx.Transitions.Bounce.easeOut});
	
	$('left-panel').set('html', responseObject.responseText);
	
	leftPanelMorph.start({
		'left': '0px',
	});
	
	delay = calculateTime.delay(0, {time : 0});
}


var initializeTopFrame = function(responseObject) {
	var topFrameMorph = new Fx.Morph('top-frame', {duration: 'long', transition: Fx.Transitions.Bounce.easeOut});
	
	$('top-frame').set('html', responseObject.responseText);
	
	topFrameMorph.start({
		'top': '0px',
	});
	
	checkForUpdate();
	
	toggleAuthenticationOptions();
	
	$('instructions-button').addEvent('click', function() {
		post(gameDomainPath + '/php/instructions.php', '', showInstructions, 'html');
	});
	
	$('show-login').addEvent('click', function() {
		post(gameDomainPath + '/php/loginhtml.php', '', showLogin, 'html');
	});
	
	$('show-register-window').addEvent('click', function() {
		post(gameDomainPath + '/php/registerhtml.php', '', showRegister, 'html');
	});
	
	$('logout').addEvent('click', function() {
		logout();
	});
	
	$('start-button').addEvent('click', function() {
		processGiveUp();
	});

	
	SqueezeBox.initialize({
        size: {x: 400, y: 300}
    });
   	SqueezeBox.assign($$('a[rel=boxed][href^=#]'), {});
} 


var initializeGoalFrame = function(responseObject) {
	$('goal-frame').set('html', responseObject.responseText);
	
	$('goal-toggle').addEvent('click', function() {
		toggleGoalPosition();
	});
	$('goal-maximize').addEvent('click', function() {
		toggleMaximize();
	});
}

var logout = function () {
	GM_setValue('username', '');
	GM_setValue('user_id', 0);
	GM_setValue('logged_in', 0);
	GM_setValue('last_game_type', 0);
	toggleAuthenticationOptions();
}

var toggleAuthenticationOptions = function () {	
	if (GM_getValue('logged_in') == undefined || GM_getValue('logged_in') == 0) {
		$('username').set('text', 'guest!');
		$('show-login').setStyle('display', 'block');
		$('show-register-window').setStyle('display', 'block');
		$('logout').setStyle('display', 'none');
		GM_setValue('username', '');
		GM_setValue('user_id', 0);
		GM_setValue('logged_in', 0);
		GM_setValue('game_type', 3);
	}
	else {
		$('username').set('text', GM_getValue('username') + '!');
		console.log(GM_getValue('user_id'));
		$('show-login').setStyle('display', 'none');
		$('show-register-window').setStyle('display', 'none');
		$('logout').setStyle('display', 'block');
	}
}

var toggleTimeDisplay = function () {
	if ( $('timer-container').getStyle('display') == 'block')  {
		$('timer-container').setStyle('display', 'none');
	}
	else {
		$('timer-container').setStyle('display', 'block');
	}
}

var showLogin = function (responseObject) {
	var loginContainer = new Element('div', {});
	loginContainer.set('html', responseObject.responseText);
	initializeLoginWindow(loginContainer);
	SqueezeBox.fromElement(loginContainer,{handler: 'adopt', size: {x: 500, y: 300}});
}

var showRegister = function (responseObject) {
	var registerContainer = new Element('div', {});
	registerContainer.set('html', responseObject.responseText);
	initializeRegisterWindow(registerContainer);
	SqueezeBox.fromElement(registerContainer,{handler: 'adopt', size: {x: 500, y: 325}});
}

var showInstructions = function (responseObject) {
	var instructionsContainer = new Element('div', {});
	instructionsContainer.set('html', responseObject.responseText);
	console.log(instructionsContainer);
	SqueezeBox.fromElement(instructionsContainer,{handler: 'adopt', size: {x: 600, y: 400}});
}

var showGameModes = function (responseObject) {
	var gameModesContainer = new Element('div', {});
	gameModesContainer.set('html', responseObject.responseText);
	gameModesContainer.getElement('div[id=button-time]').addEvent('click', function() {
		SqueezeBox.close();
		startNewGame(1);
	});
	gameModesContainer.getElement('div[id=button-links]').addEvent('click', function() {
		SqueezeBox.close();
		startNewGame(2);
	});
	gameModesContainer.getElement('div[id=button-both]').addEvent('click', function() {
		SqueezeBox.close();
		startNewGame(3);
	});
	SqueezeBox.fromElement(gameModesContainer,{handler: 'adopt', size: {x: 500, y: 300}});
}

function toggleGoalPosition(width, height) {
	var toggleGoalPositionEffect = new Fx.Morph('goal-frame', {duration: 'short', transition: Fx.Transitions.Back.easeOut});
	
	if ( (width != undefined) && (height != undefined) ) {
		toggleGoalPositionEffect.start({
				'height': height,
				'width': width
			});
	}
	else {
		if ($('goal-frame').getStyle('height') != '55px') {
			toggleGoalPositionEffect.start({
				'height': '55px',
				'width': '500px'
				
			});
		}
		else {
			toggleGoalPositionEffect.start({
				'height': '200px',
				'width': '500px'
			});
		}
	}
	$('goal').scrollTo(0,0);
}


function toggleMaximize() {
	var toggleGoalSizeEffect = new Fx.Morph('goal-frame', {duration: 'short', transition: Fx.Transitions.Back.easeOut});
	
	if ($('goal-frame').getStyle('height') != '450px') {
		toggleGoalSizeEffect.start({
			'height': '450px',
			'width': '800px'
		});
	}
	else {
		toggleGoalSizeEffect.start({
			'height': '200px',
			'width': '500px'
		});
	}
	$('goal').scrollTo(0,0);
}

function startNewGame (gameType) {	
	if (gameStarted) {
		processGiveUp();
	}
	else {
		GM_setValue('game_type', gameType);
		//console.log("starting game type : " + GM_getValue('game_type', gameType));
		startGame(gameType);	
	}
}


var startGame = function (gameType) {
	var delay = calculateTime.delay(0, {time : 0});
	initializeScoring();
	$('path-items').empty();
	$('origin-item').setStyle('display', 'none');
	var originPathItem = $('origin-item').getElement('div[class=path-item]');
	if (originPathItem != null) {
		originPathItem.destroy();
	}
	getWikiPage('');
	//getWikiPage('http://en.wikipedia.org/wiki/Penguin');
	getRandomEndPage();
	createNewGame(gameType);
	roundCounter = roundCounter + 1;
	gameStarted = true;
}

function createNewGame(gameType) {
	console.log('creating game...');
	post(gameDomainPath + 'php/newgame.php', "user_id=" + GM_getValue('user_id') + "&game_type=" + gameType, saveGameLocally);
}


var saveGameLocally = function(jsonObject) {
	GM_setValue('game_id', jsonObject[0].game_id);
	GM_setValue('path_id', jsonObject[0].path_id);
}

var saveNodeID = function(jsonObject) {
	GM_setValue('node_id', jsonObject[0].node_id);
}

function hide(element) {
	element.set('styles', {'visibility':'hidden'});
}

function show(element) {
	element.set('styles', {'visibility':'visible'});
}

function getWikiPage(wikiURL) {
	var container = $('column-content').getElementById('content');
	var startNode = false;
	if (wikiURL == "") {
		wikiURL = "http://en.wikipedia.org/wiki/Special:Random";
		startNode = true;
	}
	var request = new Request.HTML({
								   	 url:wikiURL,
									 onRequest: function () { 
									 	container.set('text', '');
  										container.addClass('ajax-loading');
										$('loader-wrapper').setStyle('display', 'block');
										$(window).scrollTo(0,0);
										calculateLinks(undefined, "Looking for a path...");
									 },
									 onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
												responseElements.each(function(element) {
													  if(element.get('id') == 'content') {
														  	$('loader-wrapper').setStyle('display', 'none');
															element.set('styles', {'margin-top' : '60px', 'margin-left' : '185px', 'width' :'84%'});
															element.addClass('ajax-loading');
															element.replaces(container);
															
	
															currentPage = element.getElementById('firstHeading').get('text');
															if (startNode) {
																post(gameDomainPath + 'php/savepathstart.php', "game_id=" + GM_getValue('game_id') + "&start_link=" + escape(currentPage) );
																post(gameDomainPath + 'php/addnode.php', "path_id=" + GM_getValue('path_id') + "&node_id=" + 'start' + "&link_name=" + escape(currentPage) + "&link_url=" +  wikipediaPath + escape(currentPage), saveNodeID);
															}
															else {
																post(gameDomainPath + 'php/addnode.php', "path_id=" + GM_getValue('path_id') + "&node_id=" + GM_getValue('node_id') + "&link_name=" + escape(currentPage) + "&link_url=" +  wikipediaPath + escape(currentPage), saveNodeID);
															}
															var nodesToChange = $('path-items').getElements('div.node-end');
															nodesToChange.each(function(element) {
																element.set('class', 'node-middle');
															});
															
															var pathItem = new Element ('div', {'class': 'path-item'});
															var pathNode = new Element ('div', {'class': 'node-end', 'href': wikipediaPath + escape(currentPage), 'html':'&nbsp;'});
															var pathLink = new Element ('div', {'class': 'link'});
															var pathLinkText = new Element ('a', {'href': wikipediaPath + escape(currentPage), 'text': currentPage});
															pathLinkText.addEvent('click', function(e) {
																e.stop();
																getWikiPage($(e.target).get('href'));
															});
															pathNode.addEvent('click', function(e) {
																e.stop();
																getWikiPage($(e.target).get('href'));
															});
															pathLink.adopt(pathLinkText);
															pathItem.adopt(pathNode);
															pathItem.adopt(pathLink);
															pathItem.inject($('path-items'), 'top');
															linkCounter = linkCounter + 1;

															if (linkCounter == 1) {
																var originPathItem = pathItem.clone()
																originPathItem.getElement('a').addEvent('click', function(e) {
																	e.stop();
																	getWikiPage($(e.target).get('href'));
																});
																originPathItem.getElement('div.node-end').addEvent('click', function(e) {
																	e.stop();
																	getWikiPage($(e.target).get('href'));
																});
																var node = originPathItem.getElement('div.node-end');
																node.set('class', 'node-middle');
																$('origin-item').adopt(originPathItem);
																
															}
															
															if (linkCounter > 6) {
																var lastNode = $('path-items').getLast();
																lastNode.destroy();
																$('origin-item').setStyle('display', 'block');
															}
													
															if (currentPage == endPage) {
																post(gameDomainPath + 'php/savedistance.php', "node_id=" + GM_getValue('node_id') + "&distance=0"  );
																processWin();
															}
															if (endPage != '0') {
																getShortestPath();
															}
													  }
    											});
												redefineLinkEvent.delay(100, {isGoal : 0});
									 },
									 onFailure: function (responseTree, responseElements, responseHTML, responseJavaScript) {
			  									console.log('Unable to resolve wiki page.');
									 }
								   });
	request.send();

}

var initializeScoring = function() {
	linkCounter = 0;
	timerCounter = 0;
	pathScore = STARTING_SCORE;
	GM_setValue('path_score', '0');
}

var processWin = function(responseObject) {
	post(gameDomainPath + "/php/win.php", "path_id=" + GM_getValue('path_id'), displayWin, "html");
}

var displayWin = function(responseObject) {
	//Score Processing
	gameStarted = false;
	
	pathScore = GM_getValue('path_score');
	if (pathScore < 0) {
		pathScore = 0;
	}
	delay = calculateTime.delay(0, {time : 0});
	
	//Win Display
	var winContainer = new Element('div', {'id' : 'win-container'});
	winContainer.set('html', responseObject.responseText);
	document.body.appendChild(winContainer);
	$('win-score').set('text',pathScore);
	$('win-time').set('text',timeString);
	$('win-links').set('text',linkCounter);	
	GM_setValue( 'last_game_type', GM_getValue('game_type') );
	GM_setValue( 'last_game_score', pathScore );
	GM_setValue( 'last_game_links', linkCounter );
	GM_setValue( 'last_game_time', timeString );
	SqueezeBox.fromElement(winContainer,{handler: 'adopt', size: {x: 850, y: 550}});
	winContainer.setStyle('display', 'block');
	loadExternalFile(gameDomainPath + "js/visualization.js", "js");
	
	
	//Save Data
	post(gameDomainPath + 'php/pathwin.php', "path_id=" + GM_getValue('path_id') + "&path_score=" + pathScore );
	//console.log('path id : ' + GM_getValue('path_id'));
	
	if (roundCounter >= PATHS_PER_GAME) {
		post(gameDomainPath + 'php/gamewin.php', "game_id=" + GM_getValue('game_id') );
		roundCounter = 0;
		//console.log('game id : ' + GM_getValue('game_id'));
	}
};


var processGiveUp = function(gameType) {
	if (gameStarted) {
		gameStarted = false;
		
		post(gameDomainPath + 'php/pathgiveup.php', "path_id=" + GM_getValue('path_id') );
		post(gameDomainPath + 'php/gamegiveup.php', "game_id=" + GM_getValue('game_id') );
	}
	if (GM_getValue('logged_in') == 1 ) {
		post(gameDomainPath + '/php/gamemode.php', '', showGameModes, 'html');
	}
	else {
		startNewGame(3);
	}
};

var calculateTime = function() {
	$clear(delay);
	if (gameStarted) {
		this.time = this.time + 1;
		timeCounter = this.time;
		var minutes = Math.floor(this.time / 60);
		var seconds = this.time % 60;
		if (minutes < 10) {
			minutes = "0" + minutes;
		}
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
		var timer = "";
		if (this.time < 60) {
			if (this.time < 10) {
				timer = "<p class='heavy'>" + "00" + "</p><p> : </p><p class='heavy'>" + "0" + this.time + "</p>";
				timeString = "00 : 0" + this.time;
			}
			else {
				timer = "<p class='heavy'>" + "00" + "</p><p> : </p><p class='heavy'>" + this.time + "</p>";
				timeString = "00 : " + this.time;
			}
		}
		else {
			timer = "<p class='heavy'>" + minutes + "</p><p> : </p><p class='heavy'>" + seconds + "</p>";
			timeString = minutes + " : " + seconds; 
		}
		$('timer-text').set('html',timer);
		var score = '';
		switch( GM_getValue('game_type') ) {
			case 1 :
				score = Math.round((this.time / 60) * 100)/100;
			break;
			
			case 2 :
				score = linkCounter;
			break;
			
			case 3 :
				score = (Math.round((this.time / 60) * 100)/100) * linkCounter;
			break;
		}
		GM_setValue('path_score', score.toString());
		$('score-text').set('html', "<p class='heavy'>" + GM_getValue('path_score') + "</p>");
		$('link-count').set('html', "<p class='heavy'>" + linkCounter + "</p>");
	}
	else {
		this.time = 0;
		timer = "<p class='heavy'>00</p> <p>:</p> <p class='heavy'>00</p>";
		$('timer-text').set('html', timer);
		$('score-text').set('html', "<p class='heavy'>" + 0 + "</p>");
		$('link-count').set('html', "<p class='heavy'>" + 0 + "</p>");
	}
	delay = calculateTime.delay(1000, {time : this.time});
};



//display shortest path in goal bar
var calculateLinks = function(linkCount, message) {
		if (linkCount != undefined) {
			var linkEstimaterText = "Master Wiki can get here in <p>" + linkCount + "</p> links.";						
			$('goal-bar-text').set('html',linkEstimaterText);
		}
		if (message != undefined) {
			$('goal-bar-text').set('html', message+'<p> </p>');
		}
};


var redefineLinkEvent = function() {
  	var isGoal = this.isGoal;
	var container;
  	if (isGoal) {
		container = $('goal');
	}
	else {
		container = $('content');
	}
	//allAnchors = $(document.body).getElements('a');
	allAnchors = container.getElements('a');
	allAnchors.each(function(element) {
		element.addEvent('click', function(e) {
			e.stop();
			if ( !element.get('href').contains('#') && !element.get('href').contains('redlink') && (element.get('class') != 'external text') ) {
				if (!isGoal) {
					//console.log('node');
					getWikiPage(element.get('href'));	
				}
				else {
					//console.log('goal');
					element.addClass('goal-tool-tip');
				}
			}
			else {
				//element.addClass('node-tool-tip');
				//element.store('tip:title', "Oops. Can't click here.");
				var scrollToID = element.get('href');
				scrollToID = scrollToID.replace("#", "");
				var scrollCoordinates = $(scrollToID).getCoordinates();
				
				if (isGoal) {
					container.scrollTo(0, scrollCoordinates.top - 200);
					//container.getElementById('content-goal').highlight('#FFD33E', '#FFFFFF');
				}
				else {
					$(window).scrollTo(0, scrollCoordinates.top);
					//container.highlight('#66CCCC', '#FFFFFF');
				}
			}
		});
	});
	//nodeToolTips = new Tips('.node-tool-tip');
	//goalToolTips = new Tips('.goal-tool-tip');
};

var getShortestPath = function() {
	post(shortestPathURL, "from=" + escape(currentPage) + "&to=" + escape(endPage), processShortestPath, 'html');
};

var processShortestPath = function(responseObject) {
	var response = responseObject.responseText;
	var regex = /(\d+ click)/i;
	if (response.test(regex)) {
		var linkCount = response.match(regex);
		var regex = /(\d+)/i;
		linkCount = linkCount[0].match(regex);
		calculateLinks(linkCount[0]);
		post(gameDomainPath + 'php/savedistance.php', "node_id=" + GM_getValue('node_id') + "&distance=" + linkCount[0] );
	}
	else {
		calculateLinks(undefined, "Master Wiki can't find a path.");
	}
};

var getRandomEndPage = function() {
	//var randomURL = "http://en.wikipedia.org/wiki/Pop_Tarts";
	var randomURL = "http://en.wikipedia.org/wiki/Special:Random";

	var request = new Request.HTML({
								   	 url:randomURL,
									 onRequest: function () { 
										$('goal').scrollTo(0,0);
									 },
									 onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
												responseElements.each(function(element) {
													  if(element.get('id') == 'content') {
													  	//element.set('styles', {'margin':'0px', 'padding':'0px 5px 0px 5px', 'background':'#FFFFFF'});
														
														$('goal').set('text', "");
														$('goal').set('html', "");
														element.set('id', 'content-goal');
														$('goal').adopt(element);
														$('goal-frame').setStyle('display', 'block');

														toggleGoalPosition('500px', '200px');
													  }
													  else if (element.get('id') == 'firstHeading') {
													  	endPage = element.get('text');
														post(gameDomainPath + 'php/savepathend.php', "game_id=" + GM_getValue('game_id') + "&end_link=" + escape(endPage) );
														
														
													  }
													  
    											}); 
												redefineLinkEvent.delay(0, {isGoal : 1});
									 },
									 onFailure: function (responseTree, responseElements, responseHTML, responseJavaScript) {
			  									console.log('Unable to resolve end page.');
									 }
								   });
	request.send();
};
