// text replacement
Cufon.replace('#slideshowText', {
	fontStyle: 'italic',
	fontWeight: '900',
	fontStretch: 'expanded',
	fontSize: '20px',
	textShadow: '#000 1px 1px'
});

Cufon.replace('#milestone strong', {
	fontStyle: 'italic',
	fontWeight: '900',
	fontStretch: 'expanded',
	fontSize: '20px'
});

Cufon.replace('.shadow', {
	fontStyle: 'italic',
	fontWeight: '900',
	fontStretch: 'expanded',
	fontSize: '18px',
	textShadow: '#444 2px 2px'
});

	Cufon.replace('.cufon', {fontFamily: 'Helvetica Neue LT Std', hover: true});
	Cufon.replace('#topNav li a', { hover: true, fontFamily: 'Helvetica Neue LT Std' });
	Cufon.replace('#subBanner', {fontFamily: 'Helvetica Neue LT Std', textShadow: '#000 1px 1px'});


$(function() {
	   
// randomise left hand nuggets 
	$('ul#nuggets').shuffle();
	
// randomise left hand nuggets - academy page
	$('ul.academyNuggets').shuffle();


// adds classes to external links
	$('a[href^="http://"]' )
	//$("a:not([href^=http://twitter.com])").not("[href^=#]")
	  .attr("title", "Link opens in a new window")
	  .attr("target", "_blank")
	  .addClass('externalLink');
		  
		  
// Add pdf icons to pdf links
	$("a[href$='.pdf']")
	.addClass("pdf")
	.attr("title", "Adobe Acrobat document");
 
// Add txt icons to document links (doc, rtf, txt)
	$("a[href$='.doc'], a[href$='.txt'], a[href$='.rft']").addClass("txt");
 
// Add zip icons to Zip file links (zip, rar)
	$("a[href$='.zip'], a[href$='.rar']").addClass("zip"); 
 
// Add email icons to email links
	$("a[href^='mailto:']")
	.addClass("email")
	.attr("title", "Send an email to this address");
 
 	$("#center img").removeAttr("border");

// Milestones slideshow 	
	$('#milestone').cycle({ 
		fx:         'fade', 
		timeout:     8000, 
		pager:      '#milestonenav', 
		activePagerClass: 'activeSlide',
		pagerAnchorBuilder: function(idx, slide) {
			var year = $(slide).find("strong").html();
			return '<li id="milestone'+year+'"><a href="#">'+year+'</a></li>'; 
		}	
	});




// homepage sliders

// the large image
	$('#slideshow').before('<div id="slideshowNavContainer"><ul id="slideshowNav">').cycle({
		speed:  1000,
		timeout: 6000,
		pager:  '#slideshowNav',
		pagerClick: function(idx, slide) {
			$('#slideshowText').cycle(idx);
			return false;
		},
		pagerAnchorBuilder: function(idx, slide) {
			return '<li><a href="#"><img src="' + slide.src + '" width="48"  /></a></li>';
		}
	});

// the text for the large image
	$('#slideshowText').cycle({
		fx:     'blindY',
		speed:  1000,
		timeout: 6000,
		cleartype: !$.support.opacity, 
		cleartypeNoBg: true
	});

// the small slider on the right of the large image
	$('#slider').cycle({
		fx:     'scrollHorz',
    	prev:   '#prev',
		next:   '#next',
		speed: 	 400,
		timeout: 0,
		cleartype: !$.support.opacity, 
		cleartypeNoBg: true
	});

// sub pages

// the large image at the top
	$('#subImage img:first').fadeIn(1000, function() {
        $('#subImage').cycle({
			speed:  'fast',
			speed:  1000,
			timeout: 6000
		});
    });
	
// academy slider
	if($("#acadSlider").length > 0) {
		$("#acadSlider").easySlider({
			speed: 600,
			pause: 10000,
			continuous: false,
			auto: true,
			numeric: true
		});		
	}
	
// athlete slider
	if($("#athleteSlider").length > 0) {
		$("#athleteSlider").easySlider({
			speed: 600,
			pause: 10000,
			continuous: false,
			auto: true,
			numeric: true
		});		
	}
	
// athlete news from Yahoo Pipes (JSON)
	var feedUrl = 'http://pipes.yahoo.com/pipes/pipe.run?_id=9d84f90b879a8d1917b8fd8d27cf7b13&_render=json';
	
	var athleteNameString = '';
	var athleteSportString = '';
	var additionalFeed1String = '';
	var additionalFeed2String = '';
	if ($('#athleteName').length > 0) athleteNameString = '&AthleteName=' + $('#athleteName').val().replace(' ','+');
	if ($('#athleteSport').length > 0) athleteSportString = '&AthleteSport=' + $('#athleteSport').val().replace(' ','+');
	if ($('#additionalFeed1').length > 0) additionalFeed1String = '&AdditionalFeed1=' + $('#additionalFeed1').val().replace(/\//g,'%2F').replace(':','%3A');
	if ($('#additionalFeed2').length > 0) additionalFeed2String = '&AdditionalFeed2=' + $('#additionalFeed2').val().replace(/\//g,'%2F').replace(':','%3A');
	
	// make sure these values are not empty
	if ($('#athleteName').length > 0 || $('#athleteSport').length > 0) {
		// again, make sure these values are not empty
		if ($('#athleteName').val().length > 0 || $('#athleteSport').val().length > 0) {
			
			// create a loading spinner image and add it to the news div
			var $loading = $(document.createElement('div'));
			$loading.html('<p><img src="assets/images/ajax-loader.gif"></p>').appendTo('#first');

			// use jQuery json GET with a URL we're building from feedURL and strings derived from hidden input elements
			$.getJSON(feedUrl + athleteNameString + athleteSportString + additionalFeed1String + additionalFeed2String + "&_callback=?", function(json) {
																																				  
				var results = [];
				var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
				
				$.each(json, function(i, res) {
					if(typeof(res) == 'object') {
						for (j = 0; j < res.items.length; j++) {
							var result = res.items[j]
							if (result) {
								var source = '';
								var dformat = '';
	
								// format title to split into title and source -- FOR GOOGLE FEED ONLY
								var splitTitle = result.title.split(' - ');
								var title = '';
								var source = '';
								var dformat = '';
								
								if (splitTitle.length == 1) {
									title = splitTitle[0];
									if (result.source) source = result.source.content;
								} else {
									for (k = 0; k < splitTitle.length; k++) {
										if (k == splitTitle.length - 1) {
											source = splitTitle[k];
										} else {		
											if (k > 0) title += ' - ';
											title+=splitTitle[k];
										}
									}
								}
								
								// correct an error on the Dunfermline Press site
								if (source == 'Dunferline Press') source = 'Dunfermline Press';
								
								// if there's a pubDate in the feed, format it for display to the user
								if (result.pubDate) {
									
									
									// there are multiple date formats:
									// 2011-03-15T10:59:04Z
									
									// Mon, 14 Mar 2011 12:34:17 GMT+00:00
									// Thu, 28 Oct 2010 13:35:00 +0100
									// Sun, 02 Aug 2009 17:08:53 GMT
									
									// need to reformat as DDD, MM YYYY
									var pubDate = result.pubDate;
									
													
									if (pubDate.match(/\d{4}-\d{2}-\d{2}/)) {
										var d = new Date(pubDate.substring(0,4),(pubDate.substring(5,7)-1),pubDate.substring(8,10));
									} else if (pubDate.match(/\w{3}, \d{2} \d{2}/)){
										var d = new Date(pubDate.substring(8,11) + ' ' + (pubDate.substring(5,7)) + ' ' + pubDate.substring(12,16));
									} else {
										var d = new Date(result.pubDate);
									}
									
																		
									var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
									var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
	
								
									pubDate = days[d.getDay()] + ', ' + months[d.getMonth()] + ' ' + d.getDate() + ' ' + (d.getFullYear()) + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
									pubDate = pubDate.split(' ');
								
    								var day = pubDate[2];
									
									if (day.substring(0,1) == '0') day = day.substring(1,2);
									
									// format the day from e.g. "21" to "21st"
									switch(day) {
										case '1' :
										case '21':
										case '31':
											day = day + 'st';
											break;
										case '2' :
										case '22':
											day = day + 'nd';
											break;;
										case '3' :
										case '23':
											day = day + 'rd';
											break;
										default:
											day = day + 'th';
											break;
									}
									
									var month = pubDate[1];
									// format month to full month name
									switch(month) {
										case 'Jan':
											month = 'January';
											break;
										case 'Feb':
											month = 'February';
											break;
										case 'Mar':
											month = 'March';
											break;
										case 'Apr':
											month = 'April';
											break;
										case 'May':
											month = 'May';
											break;
										case 'Jun':
											month = 'June';
											break;
										case 'Jul':
											month = 'July';
											break;
										case 'Aug':
											month = 'August';
											break;
										case 'Sep':
											month = 'September';
											break;
										case 'Oct':
											month = 'October';
											break;
										case 'Nov':
											month = 'November';
											break;
										case 'Dec':
											month = 'December';
											break;
									}
									// create a string containing the correctly formatted date
									dformat = ' | ' + day + ' ' + month + ' ' + pubDate[3];
									if (isNaN(pubDate[3])) dformat = '';
								}
								// prepare the news item for the news div
								results.push('<div class="news"><h2><a href="'+result.link+'" target="_blank">'+title+'</a></h2>~ <span>'+ source + dformat +'</span></div>');
							}
						}
					}
				});
				// in case there are no results
				results.length == 0 ? $loading.html('<p>No news stories available.</p>') : $loading.remove();
				
				// build div.athlete-news and fill it with the news items; add it to the news container (#first)
				$('<div/>', {
					'class': 'athlete-news',
					html: results.join('')
				}).appendTo('#first');
			});
		}
	}
	
// accordions for athlete name/sport/region
	if ($('#accordionContainer').hasClass('region')) {
        createLists('region');
	} else if ($('#accordionContainer').hasClass('sport')) {
		createLists('sport');
	} else if ($('#accordionContainer').hasClass('surname')) {
		createLists('surname');
	}
	
	
// break region news into slides of n items
	var $newsItems = $('.regNewsItem');
	var itemsPerSlide = 3;
	var slide = [];
	var $newsSlide;
	
	for (i = 0; i < $newsItems.length; i++) {
		if(i % itemsPerSlide == 0) {
			$newsSlide = $(document.createElement('div'));
			$newsSlide
				.addClass('newsSlide')
				.addClass('active')
				.appendTo('#regionNews');
		}
		$newsSlide.append($newsItems[i]);
	}
	
	// show only the first slide
	$('.newsSlide:not(:first)')
		.removeClass('active')
		.hide();
	// because IE is dim, explicitly show the first one
	$('.newsSlide:first').show()
	
	if ($('.newsSlide').length > 1) {
		// build slide nav
		var $ul = $(document.createElement('ul'));
		var $page = $(document.createElement('li'));
		$page.text('Page:').addClass('page').appendTo($ul);
		$ul
			.appendTo('#regionNews')
			.addClass('regionNewsNav');
		$('.newsSlide').each(function(){
			var $thisSlide = $(this);
			var $li = $(document.createElement('li'));
			var $navLink = $(document.createElement('button'));
			$navLink
				.text(parseInt($thisSlide.prevAll('.newsSlide').length) + 1)
				.val($thisSlide.prevAll('.newsSlide').length + 1)
				.click(function(){
					if($($('.newsSlide')[parseInt($(this).val()) - 1]).hasClass('active')) return false;
					$('.newsSlide').slideUp(300).removeClass('active');
					$thisSlide.slideDown(300).addClass('active');
				})
				.appendTo($li);
			$li.appendTo($ul);
			$ul.find('li:not(:last):not(.page)').css('border-right','1px solid #fff');
		});
	}

});

/* params:
TheArr: array to sort
u,v,w,x,y,z: indexes of columns to sort (i.e. up to six);
*/
function SortIt(TheArr,u,v,w,x,y,z){

  if(u==undefined){TheArr.sort(Sortsingle);} // this is a simple array, not multi-dimensional, ie, SortIt(TheArr);
  else{TheArr.sort(Sortmulti);}

  function Sortsingle(a,b){
    var swap=0;
    if(isNaN(a-b)){
      if((isNaN(a))&&(isNaN(b))){swap=(b<a)-(a<b);}
      else {swap=(isNaN(a)?1:-1);}
    }
    else {swap=(a-b);}
    return swap;
  }

 function Sortmulti(a,b){
  var swap=0;
    if(isNaN(a[u]-b[u])){
      if((isNaN(a[u]))&&(isNaN(b[u]))){swap=(b[u]<a[u])-(a[u]<b[u]);}
      else{swap=(isNaN(a[u])?1:-1);}
    }
    else{swap=(a[u]-b[u]);}
    if((v==undefined)||(swap!=0)){return swap;}
    else{
      if(isNaN(a[v]-b[v])){
        if((isNaN(a[v]))&&(isNaN(b[v]))){swap=(b[v]<a[v])-(a[v]<b[v]);}
        else{swap=(isNaN(a[v])?1:-1);}
      }
      else{swap=(a[v]-b[v]);}
      if((w==undefined)||(swap!=0)){return swap;}
      else{
        if(isNaN(a[w]-b[w])){
          if((isNaN(a[w]))&&(isNaN(b[w]))){swap=(b[w]<a[w])-(a[w]<b[w]);}
          else{swap=(isNaN(a[w])?1:-1);}
        }
        else{swap=(a[w]-b[w]);}
        if((x==undefined)||(swap!=0)){return swap;}
        else{
          if(isNaN(a[x]-b[x])){
            if((isNaN(a[x]))&&(isNaN(b[x]))){swap=(b[x]<a[x])-(a[x]<b[x]);}
            else{swap=(isNaN(a[x])?1:-1);}
          }
          else{swap=(a[x]-b[x]);}
          if((y==undefined)||(swap!=0)){return swap;}
          else{
            if(isNaN(a[y]-b[y])){
              if((isNaN(a[y]))&&(isNaN(b[y]))){swap=(b[y]<a[y])-(a[y]<b[y]);}
              else{swap=(isNaN(a[y])?1:-1);}
            }
            else{swap=(a[y]-b[y]);}
            if((z=undefined)||(swap!=0)){return swap;}
            else{
              if(isNaN(a[z]-b[z])){
                if((isNaN(a[z]))&&(isNaN(b[z]))){swap=(b[z]<a[z])-(a[z]<b[z]);}
                else{swap=(isNaN(a[z])?1:-1);}
              }
              else{swap=(a[z]-b[z]);}
              return swap;
} } } } } } }

function createLists(mode) {
    var array, array2D = new Array;
	$.get('assets/csv/athletes.csv', function(data) {
		array = data.split(/\n/);

		for (i=0;i<array.length;i++) {
            temparray = array[i].split(',')
			//array2D.push({region:temparray[0]/*.replace(/\sinstitute of sport/i,'')*/,sport:temparray[1],firstName:temparray[2],lastName:temparray[3]});
            array2D.push(temparray);
		}

        if (mode == 'region') {
            SortIt(array2D,0,3);
        } else if (mode == 'sport') {
            SortIt(array2D,1,3);
        } else if (mode == 'surname') {
            SortIt(array2D,3);
        }
        
		for (i=0;i<array2D.length;i++) {
            // give logical names to array parts
			var region = $.trim(array2D[i][0]);
            var sport = $.trim(array2D[i][1]);
            var firstName = $.trim(array2D[i][2]);
            var lastName = $.trim(array2D[i][3]);
            
			// if we have any blank fields, don't display an item
			if (sport.length != 0 && region.length != 0 && firstName.length + lastName.Length != 0 && region != 'Scottish Institute of Sport') {
			
				// trim "institute of sport" from region names where appropriate
				if (region != 'Scottish Institute of Sport') {
					region = region.replace(' Institute of Sport', '');
				}
				
				// idstub is used for the ID of generated UL elements
				// description is a string we insert after the athlete's name in each list item and differs based on the mode
				var idstub, description;
				if (mode == 'region' && region != 'Scottish Institute of Sport') {
					idstub = region.replace(/[\s\/]/g,'-').toLowerCase();
					description = ', ' + sport;
				} else if (mode == 'sport') {
					idstub = sport.replace(/[\s\/]/g,'-').toLowerCase();
					description = '';
				} else if (mode == 'surname') {
					idstub = lastName.substring(0,1).toLowerCase();
					description = ', ' + sport; //+ ' &mdash; ' + region;
				}
				
				// find an existing UL for this item	
				var $ul = $('ul#' + idstub)
				// if there's no UL, create a new one and a H"
				if($ul.length == 0) {
					// create a header
					$header = $(document.createElement('h2'));
					if (mode == 'region') {
						$header.text(region)
					} else if (mode == 'sport') {
						$header.text(sport);
					} else if (mode == 'surname') {
						$header.text(lastName.substring(0,1))
					}
					$header.appendTo('#accordionContainer');
					// create a ul element
					$ul = $(document.createElement('ul'));
					$ul.attr('id',idstub).css('display','none').appendTo('#accordionContainer');
				}
	
				// create the list item, set its text, and append it to the UL
				var $li = $(document.createElement('li'));
				$li.html(firstName + ' ' + lastName + description)
					.appendTo($ul);
				

			}
		}
	});
}

