/*
 * Script used by all MFM pages
 */


/**
 * Toggles help panel between open and closed states
 * 
 * @deprecated keeping as this may be useful for the tutorial panel
 */
function toggleHelp() {
	if(helpOn) {
		//switch help off
		//removeToolTips();
		helpOn = false;
		$('helpLinkItem').set('text', 'Help');
		myTips.tip.fade('out');
	} else {
		//create tooltips
		if(!toolTipsCreated) {
			$('helpLinkItem').set('text', 'Starting Help');
			addAllToolTips();
			toolTipsCreated = true;
		}
		
		//switch help on
		helpOn = true;
		$('helpLinkItem').set('text', 'Help Activated');
		myTips.tip.fade('in');
	}
}

/**
 * Add the tool tip code - this can take 5-6 seconds on IE7
 */
function addAllToolTips() {
	//add the common set of tool tips
	addCommonToolTips();
	
	//add page specific tool tips if they exist
	if(typeof addToolTips == 'function') {
		addToolTips();
	}
}

/**
 * Adds all common help tool tips.
 * 
 * For an element to have a tooltip it must use class 'tooltip' and a class to use a reference.
 * 
 * Only elements that occur on multiple pages should be added here. Otherwise add them in a function called
 * addToolTips() on the required page.
 */
function addCommonToolTips() {
	addToolTip('.tutorialLink', 'Tutorial', 'Click here to open the tutorial, which will guide you through setting up a new team and show you how to become an expert Monkey Football manager. <br/><br/>The tutorial will open in a popup window so you may need to tell your browser to allow this.');
	addToolTip('.faqLink', 'FAQs', 'Click here to open the FAQ screen, which provides answers to common questions on how to manage your team.');
	addToolTip('.pitch', 'Pitch View', 'The pitch view shows your squad (in blue) and your next opposition (in red) in playing formations. Select a player by clicking on them on the pitch. The selected player is shown on the left. This allows details such as the player\'s skill, health, style and bonuses to be seen.');
	addToolTip('.loginForm', 'Login', 'Enter your manager name and password if you are already signed up. Otherwise click the register menu option to register as a new manager and start playing the game!');
	addToolTip('.homeLink', 'Home', 'Click here to go to the Home page.');
	addToolTip('.loginLink', 'Login', 'Click here to login if you\'ve already registered.');
	addToolTip('.registerLink', 'Register', 'Click here to register as a new manager.');
	addToolTip('.faqLink', 'FAQs', 'Click here to view the list of Frequently Asked Questions.');
	addToolTip('.menuLink', 'Menu', 'Click here to go to the main manager menu.');
	addToolTip('.teamLink', 'Team', 'Click here to view and edit your team.');
	addToolTip('.fixturesLink', 'Fixtures', 'Click here to view and arrange matches.');
	addToolTip('.transfersLink', 'Transfers', 'Click here to buy and sell players.');
	addToolTip('.financeLink', 'Finance', 'Click here to view your team finances.');
	addToolTip('.chartLink', 'Chart', 'Click here to view the team valuation chart. This aim of the game is to get to the top.');
	addToolTip('.logoutLink', 'Log Out', 'Click here to log out.');
	addToolTip('.playerName', 'Player Name', 'This is the name of the player. Every player in Monkey Football Manager has a unique name.');
	addToolTip('.skill', 'Skill', 'A player\'s skill indicates how well they can play. Younger players will increase their skill by playing matches. This is the most important statistic a player has, but it can be influenced by other statistics. For example, a player with 5 skill stars with low health will not play as well as one with good health.');
	addToolTip('.health', 'Health', 'A player\'s health indicates how fit the player is. Try to keep this as high as possible by resting players and feeding them bananas. Health drops when players are injured during matches, and a player will die if they have no health.');
	addToolTip('.position', 'Position', 'A player\'s position indicates the playing position that they should play in, for example players with position Goal should be positioned to be the goal keeper. If you don\'t position players in their natural playing position they\'ll perform very badly.');
	addToolTip('.age', 'Age', 'When a player is young they will increase in skill as they play matches, but the older a monkey gets the slower they learn. Eventually very old players will start to loose skill and health.');
	addToolTip('.style', 'Style', 'A player\'s playing style is very important when deciding on match tactics. There are four playing styles; <b>Star, Speedy, Angry and Cheat</b>. Each playing style performs very well against one other style and very badly against another style as described below.'
			+ '<table><tr>'
			+ '<th>Player\'s Style</th><th>Good Against</th><th>Bad against</th>'
			+ '</tr><tr>'
			+ '<td><span class=\"styleStar\"/>Star</span></td><td><span class=\"styleSpeedy\"/>Speedy</span></td><td><span class=\"styleCheat\"/>Cheat</span></td>'
			+ '</tr><tr>'
			+ '<td><span class=\"styleSpeedy\"/>Speedy</span></td><td><span class=\"styleAngry\"/>Angry</span></td><td><span class=\"styleStar\"/>Star</span></td>'
			+ '</tr><tr>'
			+ '<td><span class=\"styleAngry\"/>Angry</span></td><td><span class=\"styleCheat\"/>Cheat</span></td><td><span class=\"styleSpeedy\"/>Speedy</span></td>'
			+ '</tr><tr>'
			+ '<td><span class=\"styleCheat\"/>Cheat</span></td><td><span class=\"styleStar\"/>Star</span></td><td><span class=\"styleAngry\"/>Angry</span></td>'
			+ '</tr></table>'
			+ 'For example, if you have a Speedy player in Goal they will perform much better against an opposition forward who\'s style is Angry, and much worse against an opposition forward who\'s style is Star.'
			+ '<br/><br/>Styles also effect how well players in your team work together as players of the same style perform much better together than players of different styles.');
	addToolTip('.playerStats', 'Player Details', 'This panel shows the selected player\'s skill, health, style and bonuses.');
	addToolTip('.selectJoiningFee', 'Joining Fee', 'Each team that enters a league pays the entrance fee. You much have enough money available to pay this fee if you want to join a league. <br/><br/>When all matches in the league are played the team in first place gets 75% of the prize fund, and the team in second place gets 25%.');
	addToolTip('.selectNumberOfTeams', 'Number of Teams', 'This is the number of teams in a league. <br/><br/>Leagues with 4 teams play each team twice so they have 6 matches in total. <br/><br/>Leagues with 8 teams play each team once so they have 7 matches in total.');
	addToolTip('.playerNumber', 'Player Number', 'This is the player\'s number within your team.');
	addToolTip('.valuation', 'Value', 'This is the player\'s valuation, which is an indication of how much the player could be sold for on the transfer market.');
}

/**
 * Adds a single tool tip
 */
function addToolTip(elementName, title, text) {
	$$(elementName).each( function(item) {
		item.store('tip:title', title);
		item.store('tip:text', text);
	});
}


/**
 * Display the help link
 */
function showHelpLink() {
	$('helpLink').setStyle('visibility', 'visible');
}

/**
 * Open the tutorial window
 */
function openTutorial() {
	window.open('/MFM/tutorial/index.jsp','Tutorial','left=20,top=20,width=520,height=500,toolbar=0,resizable=0,location=0,menubar=0,scrollbars=1');
}

/**
 * Call from tutorial window links to redirect main window
 * 
 * @param url URL to redirect to
 */
function redirectMainWindow(url) {
	opener.location = url;
}

/**
 * Copy the colour from the calling input's value to the style of the specified object
 * 
 * @param copyToId ID of the object to copy the colour to
 * @return
 */
function copyColour(copyFromId, copyToId) {
	newColour = $(copyFromId).get('value');
	$(copyToId).setStyle('background-color', '#' + newColour);
}

/**
 * Start the timer - debug helper function to monitor JS execution time
 */
function timerStart() {
	timer = new Date;
}

/**
 * Stop the timer - debug helper function to monitor JS execution time
 */
function timerEnd() {
	var diff = new Date - timer;
	alert('Timer: ' + diff + 'ms');
}

//Class for pulsing highlight borders
//Removed from team management as it uses too much CPU on browser and made debugging difficult
var PulseFade = new Class({
	
	//implements
	Implements: [Options,Events],

	//options
	options: {
		min: '#ffffff',
		max: '#000000',
		duration: 200,
		times: 5
	},
	
	//initialization
	initialize: function(el,options) {
		//set options
		this.setOptions(options);
		this.element = $(el);
		this.times = 0;
	},
	
	//starts the pulse fade
	start: function(times) {
		if(!times) times = this.options.times * 2;
		this.running = 1;
		this.fireEvent('start').run(times -1);
	},
	
	//stops the pulse fade
	stop: function() {
		this.running = 0;
		this.fireEvent('stop');
	},
	
	//runs the shizzle
	run: function(times) {
		//make it happen
		var self = this;
		
		var to = self.options.min;
		if(times % 2 == 0) {
			var to = self.options.max;
		}
		
		self.fx = new Fx.Tween(self.element,{
			duration: self.options.duration / 2,
			transition: Fx.Transitions.Quad.easeInOut,
			onComplete: function() {
				self.fireEvent('tick');
				if(self.running)
				{
					self.run(times-1);
				}
				else
				{
					self.fireEvent('complete');
					self.element.setStyle('border-color', '#222222');
				}
			}
		}).start('border-color',to);
	}
});

/*
 * Global vars
 */
var helpPanelSlideFx;
var helpOn = false;
var timer;

// = true only after the tool tips have been created
toolTipsCreated = false;

/*
 * Called before page init, when the DOM is ready
 */
window.addEvent('domready', function() {
	//setup tooltip help system
	myTips = new Tips($$('.tooltip'));
	myTips.addEvents({  
	    'show': function(tip) {
			if(helpOn) {
				tip.fade('in');  
			}
	    },  
	    'hide': function(tip) {  
	        tip.fade('out');  
	    }  
	}); 
	myTips.tip.fade('hide');
	
	//add help tooltip separately as it need to be created before the hover event triggers on clicking the help link
	addToolTip('.helpLink', 'Help Activated', 'The help system is now on. Hover the mouse over any item to view help information.<br/><br/><b>Click here again to switch help off.</b>');
});
