/** Siemens - Stroke For Stroke Javascript - Author: TWB **/
document.write("<link rel=\"StyleSheet\" href=\"../strokeForStrokeAssets/css/strokeForStrokeJavascript.css\" type=\"text/css\" media=\"screen\" />");

// Global Variables
var iepc,firefox,ns7,ns8,mozilla,safari,OS;
function fnBrowser() {	
	var ua = navigator.userAgent.toLowerCase();

	iepc = (((ua.indexOf("msie 8") != -1)||(ua.indexOf("msie 7") != -1)||(ua.indexOf("msie 6") != -1)||(ua.indexOf("msie 5.5") != -1))&&(ua.indexOf("windows") != -1)&&(ua.indexOf("opera") == -1))? true:false;
	firefox = ua.indexOf("firefox") != -1 ? true:false; // pc or mac
	ns7 = ua.indexOf("netscape/7") != -1 ? true:false; // firefox mode
	ns8 = ua.indexOf("netscape/8") != -1 ? true:false; // firefox mode
	mozilla = (ua.indexOf("gecko") != -1) && (ua.indexOf("netscape") == -1) ? true:false; 
	safari = ua.indexOf("safari") != -1 ? true:false;
	OS = ua.indexOf("windows") != -1? "PC":"MAC";		
	opera = ua.indexOf("opera/9") != -1 ? true:false;
	if (iepc||firefox||ns7||ns8||mozilla||safari||opera) {
		return true;
	} else {
		return false;
	}
}
fnBrowser(); // run on load;

// Flash detect. boolean true/false if installed and version number accessed via flash.version
var flash = new Object();	
flash.installed = false;

if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x < navigator.plugins.length; x++) {
		
		if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {		
			flash.installed = true;					
			flash.version = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);					
			break;
		}
	}
}
else if (window.ActiveXObject) {
	for (x = 2; x <= 20; x++) {
		try {
			oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
			if(oFlash) {		
				flash.installed = true;	
				flash.version = x;
			}
		}
		catch(e) {}
	}
}

/********************************************************************************

Name: 				Flash embed
Description:		Writeout flash code. Fixes Eolas update for IE as well.
@param	swf			String path to swf file
@param	width		Number value of movie width
@param	height		Number value of movie height

*********************************************************************************/
flash.insert = function(swf,width,height,flashVer,nonFlashId) {	
		
	if(!flashVer){
		minVer = 8;
	}
	else {
		minVer = flashVer;
	}

// Handle errors
	var errMsg ="";
	if (!fnBrowser()) { // NOT supported browser
		errMsg += '<p class="err">Unfortunately, this website cannot be viewed by your browser. Please go to <a href="http://www.getfirefox.com">www.getfirefox.com</a> or <a href="http://www.microsoft.com/windows/ie/">www.microsoft.com/</a> to download a recommended browser.</p>';
	} 
	if (!flash.installed) { // NOT flash
		errMsg += '<p class="err">This website requires the adobe&trade; Flash player. Go to the adobe website to install the <a href="http://www.adobe.com/products/flashplayer/">latest version of flash</a></p>';
	} 
	
	swf = swf.replace(/\./g,"%2E"); // encode periods as %2e	
	
	if(flash.installed && fnBrowser() && flash.version >= minVer) {		
		document.write('<embed src="'+swf+'" menu="false" width="'+width+'" height="'+height+'" scale="noscale" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowFullScreen="true" />');	
		fnHide(nonFlashId);
	}
};

function fnHide(id) {
	if(!document.getElementById(id)){return false;};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "absolute";
	oTarg.top = "-5000px";
	oTarg.left = "0";
}

function fnShow(id) {
	if(!document.getElementById(id)){return false;};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "static";
	oTarg.top = "";
	oTarg.left = "";
}

/* SIFR Initiation */
	var siemensslab = {
	src: '../strokeForStrokeAssets/flash/siemensslab.swf'    
	};

	// You probably want to switch this on, but read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad> first.
	sIFR.useStyleCheck = true;
	sIFR.activate();
	
	// h1
	sIFR.replace(siemensslab, {
		selector: 'h1'
		,css: {
			'.sIFR-root': { 
				'background-color': '#a0b6c0',  		      	
		      	'color': '#FFFFFF',
		      	'font-size' : '12px',
		      	'padding' : '0'
	      	}			
		}		
	});	
	// top right strap-line
	sIFR.replace(siemensslab, {
		selector: '#strap'
		,css: {
			'.sIFR-root': {				
				'background-color' :'#a0b6c0',
				'color' : '#FFFFFF', 
				'font-size' : '18px'
			}
		}
	});
	// message box
	sIFR.replace(siemensslab, {
		selector: '.msgBox .sIFR p'
		,css: {
			'.sIFR-root': {				
				'background-color' :'#a0b6c0',
				'color' : '#FFFFFF', 
				'font-size' : '18px'
			}
		}
	});
		
	// Do stuff when the document is loaded.
	$(document).ready(function() {
		
		if($(".sIFR-active").length > 0){
			var s = $(".tipBoxR h3.sIFR span").prepend('<br />');
		}		
		// 
		sIFR.replace(siemensslab, {
			selector: '.tipBoxR h3.sIFR'
			,css: {
				'.sIFR-root': {				
					'background-color' :'#a0b6c0',
					'color' : '#FFFFFF', 
					'font-size' : '18px'
				}
			}
		});
		
		if($("#rowOMeter").length > 0){
			
			// hide the game area so jQuery can animate it back in later
			$(".raceGame").hide();	
			
			// *** convert form	***
			var oForm,oRows,oLists,oBtn;
			var racedBefore = false;
			
			oForm 	= 	$(".crewPicker:first");
			oRows 	= 	$(".row",oForm);			
			oLists 	= 	$("select:first",oRows);			
			oBtn 	= 	$("#race:first");
			
			// add id to form for styles to kick in			
			oForm.attr("id","js");			
			// replace default button with a pretty image one
			oBtn.replaceWith('<input type="image" src="../strokeForStrokeAssets/images/btnRace.gif" class="btn" name="race" value="Race" id="race" alt="Race">');			
			// replace selects with text bosxes and add choose button
			oLists
				.each(function(index) {
					index++;
					$(this)
						.after(' <input type="image" src="../strokeForStrokeAssets/images/btnChoose.gif" name="chooseCrew'+index+'" value="Crew '+index+'" id="chooseCrew'+index+'" alt="Crew '+index+'" class="chooseBtn">')
						.replaceWith('<input type="text" name="crew'+index+'" id="crew'+index+'" class="txt">');
				});	
			// line it up			
			$('.row:odd')
				.css({
					paddingLeft: '0', 
					marginLeft: '22px'					
				});
			// add links
			$(".clr",oRows).before('<div class="links"><a href="#" title="Change crew" class="change">Change crew</a><a href="#" title="Clear crew" class="clear">Clear crew</a></div>');
				
			// *** turn select boxes into list for overlay ***
			function fnBuildOverlayList() {
				theOverLayList = 	'<div class="overlay"><div class="overInr"><div class="top"><h3>Choose your crew name by region<\/h3><a href="#" class="close">Close<\/a><div class="clr"><\/div></div><div class="list"><ul>';				
				$("optgroup",oLists[0]) 				
					.each(function() {
						var html;
						html = '<li><h4>'+$(this).attr("label")+'</h4>';
						$(this).find("option")
							.each(function() {
								html+='<ul>';
								$(this).each(function(){
									html+='<li><a href="#" title="'+ $(this).attr("title") +'">' + $(this).text()+ '</a></li>';
								});
								html+='</ul>';								
							});	
						html +=	'</li>';
						theOverLayList += html;
					});				
				theOverLayList +=	'<\/ul><div class="clr"><\/div><\/div><div class="clr"><\/div><\/div><\/div>';
				return theOverLayList;
			};
			fnBuildOverlayList();
				
			// launch overlay	
			$('input.chooseBtn')
				.click(function() {					
					// disable default styles and use custom styles 
					$.blockUI.defaults.css = {};
					$.blockUI({
						message:  theOverLayList,
						// styles for the overlay 
						overlayCSS:  {  
						    backgroundColor:'#FFF',  
						    opacity:'0.8',
						    padding:'0 0 800px' 
					    	}
						});
					fnSetCloseEvent();
					fnSetChosenCrew($(this));
					return false;
				});
			
			// array of boats for racing later
			var boats = [];						
			// set up boats			
			function boat(lane) {
				this.lane = lane;
				this.crew = '';
				this.region = '';
				this.km = '';
				this.pounds = '';
				this.htmlOut = '';
				this.rank = '';
			} 			
			boats[0] = new boat(1);
			boats[1] = new boat(2);
			boats[2] = new boat(3);
			boats[3] = new boat(4);
				
			function fnSetChosenCrew(obj){
				$('.list li a').click(function() {
					
					// set up boat to race later					
					var crewName = $(this).text();							
					
					// find region
					var reg = $(this).parent().parent().parent().find("h4:first").text();
					
					// get the info from the title
					var info = $(this).attr("title");			
					info = info.split(" ");
					var donations = info[0].substr(1);// take characters after 1st (£) - put back in later
					donations = $.trim(donations);
					var distance = info[1];
					distance = distance.substr(0,distance.length-2);
					distance = $.trim(distance);
					
					// find number from id to assign to boat number 1,2,3 or 4					
					var str = $(obj).attr("id");								
					var num = str.substring(10); // split on string 
					num--; // adjust for array position					
					
					boats[num].crew 	=	crewName;
					boats[num].pounds 	= 	donations;
					boats[num].km 		=	distance;
					boats[num].region 	= 	reg;
					
					// create boat html									
					html = '<div class="lane" id="lane';
					html += boats[num].lane+'"><div class="place"><div class="posBox"><div class="posBoxInr"><h4>';
					html += boats[num].crew + '</h4><p><span class="hide">Donations pledged: </span><span class="donations">&pound;';
					html += boats[num].pounds + '</span></p><p><span class="hide">Distance: </span><span class="distance">';
					html += boats[num].km + ' KM</span></p><p><span class="hide">Region: </span><span class="region">';
					html += boats[num].region + '</span></p><div class="clr"></div></div></div><div class="clr"></div></div></div>';
										
					boats[num].htmlOut 	= 	html;
					
					// add name to text box
					$(obj)
						.parents(".row")
							.find("input.txt")
								.attr('value', crewName);

					// release the page
		            $.unblockUI({
		            	fadeOut: 0		            	
		            }); 
		            return false; 
		        }); 
			}
			
			function fnSetCloseEvent(){
				$('a.close').click(function() { 					
		            $.unblockUI({
		            	fadeOut: 0		            	
		            }); 
		            return false; 
		        }); 
			}
								
			// clone click event for change crew from 'choose'
			$('.links a.change')
				.click(function() {					
					// disable default styles and use custom styles 
					$.blockUI.defaults.css = {};
					$.blockUI({
						message:  theOverLayList,
						// styles for the overlay 
						overlayCSS:  {  
						    backgroundColor:'#FFF',  
						    opacity:'0.6'  
					    	}
						});
					fnSetCloseEvent();
					fnSetChosenCrew($(this).parents(".row").find("input.chooseBtn")); // go through same route as clicking button to choose
					return false;
				});
				
			// clear the crew from the field
			$('.links a.clear')
				.click(function() {					
					
					fnClearBoat($(this));
					
					$(this)						
						.parents(".row")
							.find("input.txt")
								.attr('value', '');								
						return false;	
				});
			
			function fnClearBoat(obj){
				// passes jquery object				
				var boatNum = $(obj)
						.parents(".row")
							.find("input.txt")
								.attr('id');
				boatNum = boatNum.substr(4);
				boatNum--; // adjust for array index
				// reset all object variables			
				boats[boatNum].km ='';
				boats[boatNum].pounds ='';
				boats[boatNum].region ='';
				boats[boatNum].crew ='';
				boats[boatNum].htmlOut ='';
				// boats[boatNum].lane ='';
			}
			
			// RACE!
			// check how many crews are chosen			
			function fnRace(){
				
				// check if there are boats selected
				var racers = 0;
				for (var i=0; i < boats.length; i++) {
					if(boats[i].crew != ''){
						racers++;
					}
				};				
				if(racers < 2){
					alert("Please select at least 2 crews to race");
				}
				
				else{
					// find race type - default to distance pledged	
					var input = $("#rowOMeter form input.rad:checked");
					var raceType = '';
					
					if(!input.length > 0){					
						input.attr("checked","checked");
						raceType = 'km';						
					}
					else{
						raceType = input.attr("id");
					
						if ((raceType.indexOf("money") != -1) || (raceType == null) || (raceType == '')) {
							raceType = 'pounds';						
						} else {
							raceType = 'km';
						}	
						
					}
	
					// sort boats to pick winner
					var rank = [];
					// remove previous crews html					
					$(".raceGame .lane").remove();
					
					// loop boats
					for (var i = boats.length - 1; i >= 0; i--){
						if(boats[i].crew && boats[i].crew != null && boats[i].crew != ''){									
							// inject html for new/updated crews
							$(".raceGame").prepend(boats[i].htmlOut);				
										
							if(raceType == 'km'){
								rank[i] = [boats[i].lane,boats[i].km];										
								$(".lane .distance").wrapInner("<em></em>");
							}
							else if(raceType == 'pounds'){								
								rank[i] = [boats[i].lane,boats[i].pounds];																																					
								$(".lane .donations").wrapInner("<em></em>");		
							}						
						}										
					};						
					rank.sort(sortNumber);
					
					for (var i=0; i < rank.length; i++) {
						if(typeof(rank[i])!= 'undefined'){						
							laneNum = rank[i][0];
							pos = "place"+(i+1);
							$("#lane"+laneNum+" .place").attr("class",pos);		
						}
					};
					
					
					// prep for animation
					$(".lane .place1 .posBox").css('background', 'url(../strokeForStrokeAssets/images/posBoxBot.gif) 0 100% no-repeat');
					
					$(".lane")
						.each(function() {												
							$(this).find("div:first").animate({width: '250px'}, 250);									
						});
						
					$(".raceGame").slideDown(400, fnWaitToRace);					
				}
			}
			
			function fnWaitToRace(){					
				// wait for a bit then do the animations
				window.location.hash="rowOMeter";	
				// setTimeout(function(){$(".raceGame .msg").fadeOut(500);}, 500);	
				setTimeout(fnAnimate, 500);
			}
			
			function fnAnimate(){
				// alert('might do some animation');					
				$(".lane div")
					.each(function() {												
						h = $(this).height();
						$(this).css('height', h+'px');
					});	
				
				setTimeout(function(){
					
					if($("#facebook").length>0){
						$(".place1").animate({width: "759px"}, 500);										
					}else{
						$(".place1").animate({width: "596px"}, 500);											
					}
					
					
				},1400);
					
				setTimeout(function(){
					$(".place2").animate({width: "536px"}, 500);
				},1000);
				
				setTimeout(function(){
					$(".place3").animate({width: "409px"}, 500);
				},600);
				
				setTimeout(function(){
					$(".place4").animate({width: "322px"}, 500);
				},200 );
				
				setTimeout(function(){
					$(".place1 .posBoxInr").prepend('<div id="rosette"><strong>First place</strong></div>');
					$("#rosette").hide();
					$("#rosette").fadeIn(800);
				},2000);		
				
				previousRace = true;		
			}

			
			// function that sorts the array numerically descending
			function sortNumber(a,b) {
				return b[1] - a[1];
			}
			
			$("input#race").click(function(){
				fnRace();
				return false;
			});
			
		};
		
		// 
		if($("#editCrew").length > 0){
			$(".showHide").hide();
			$(".msgRight a")
				.click(function() {
					$(this)
						.parents("fieldset:first")
							.find(".showHide").toggle();
					return false;
				});
			
		}
	
		
		/****	league table sorting and pagination	****/ 
		
		// set up parser for km column		
		
		if($('#leagueTable').length>0){
			$.tablesorter.addParser({ 
		        // set a unique id 
		        id: 'km', 
		        is: function(s) { 
		            // return false so this parser is not auto detected 
		            return false; 
		        }, 
		        format: function(s) { 
		            // format your data for normalization 
		            return s.toLowerCase().replace(/ km/,'');
		        }, 
		        // set type, either numeric or text 
		        type: 'numeric' 
		    });	
		    
		    var pager = '<div id="pager" class="pager"><form><img src="../strokeForStrokeAssets/images/pagerFirst.gif" class="first" alt="First page"/> <img src="../strokeForStrokeAssets/images/pagerPrev.gif" class="prev" alt="Previous page" /> <input type="text" class="pagedisplay"/> <img src="../strokeForStrokeAssets/images/pagerNext.gif" class="next" alt="Next page" /> <img src="../strokeForStrokeAssets/images/pagerLast.gif" class="last" alt="Last page" /> <label for="pagerSize">Results shown on page</label> <select class="pagesize" id="pagerSize"> <option selected="selected" value="20">20</option><option value="40">40</option><option value="60">60</option><option  value="80">80</option><option  value="100">100</option></select></form></div>';

			$('#leagueTable').append(pager);
			$('#leagueTable table').addClass('tablesorter');
			$("#leagueTable table").tablesorter({
			    widthFixed: true, 
			       // pass the headers argument
			        headers: { 
			        // assign the secound column (we start counting zero) 
			            1: { 
			                // set the sorter to our custom parser 'km'
			                sorter: 'km'
			            }
			        } 
			    }).tablesorterPager({container: $("#pager"), positionFixed: false, size:20 });
		    
			/* Colorise the top row on any interaction*/
		   
			$("#leagueTable table")
			    .bind("sortStart",function() { 
			      fnColorizeRow();
			    }).bind("sortEnd",function() { 
			     fnColorizeRow();
			});
		
			$('#pager img').click(
			    	function(){
			    		 fnColorizeRow();
			    });
			    	
			$('#pager .pagesize').change(
				function(){
					 fnColorizeRow();
				});
		}
		
		
		
        /**** View all training schedules sorting and pagnation ******/
           
        if($('#allTrainingSchedules').length>0){
        
		    var pager = '<div id="pager" class="pager"><form><img src="../strokeForStrokeAssets/images/pagerFirst.gif" class="first" alt="First page"/> <img src="../strokeForStrokeAssets/images/pagerPrev.gif" class="prev" alt="Previous page" /> <input type="text" class="pagedisplay"/> <img src="../strokeForStrokeAssets/images/pagerNext.gif" class="next" alt="Next page" /> <img src="../strokeForStrokeAssets/images/pagerLast.gif" class="last" alt="Last page" /> <label for="pagerSize">Results shown on page</label> <select class="pagesize" id="pagerSize"> <option selected="selected" value="20">20</option><option value="40">40</option><option value="60">60</option><option  value="80">80</option><option  value="100">100</option></select></form></div>';
        
		    $('#allTrainingSchedules').append(pager)
		    $('#allTrainingSchedules table').addClass('tablesorter');
		    $("#allTrainingSchedules table").tablesorter({
		        widthFixed: true, 
		           // pass the headers argument
		            headers: { 
		                3: { 
		                    // don't sort by this field (download)
		                    sorter: false
		                }
		            } 
		        }).tablesorterPager({container: $("#pager"), positionFixed: false, size:20 });
	    }
           
		
		
	}); // ready
	
	/* For league table pager/sorter */  
	function fnColorizeRow(){
		var page = $('.pagedisplay').attr('value').split('/');
		if(page[0] == 1){
	 		//we are on the first page
	 		$('#leagueTable table tbody tr').removeClass('topRow');
	 		$('#leagueTable table tbody tr:first').addClass('topRow');
	 	}else{
	 		$('#leagueTable table tbody tr').removeClass('topRow');
 		}
	}