/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


var HFRFC = {
	
	Page: {

		init: function() {		
			var self = this;
			
			this.resizePageWrapper();
			this.inputLabels();
			
			if ($.browser.msie && $.browser.version == 6) {
				$('body').attr('style', '');
			}

			var s = $('#secondary');
			var t = $('#tertiary');
			if (s.children().length == 0) s.remove();
			if (t.children().length == 0) t.remove();		

			// open external links in a new window
			$("#primary a[href^='http'], #primary a[rel='external'], #secondary a[rel='external']").attr('target','_blank');
			
			$('#footer .coming-soon a').bind('click', function(e) { e.preventDefault(); });
			
			$('.tweet').each(function() {
				var p = $(this).find('p:first');
				var text = p.text();
				text = text.parseURL().parseUsername().parseHashtag();
				p.html(text);
			});
			
			var items = $('.main-content .item');
			if (items.length == 1) {
				items.css({ 'margin-bottom': '0' })
			}
			
			$('body#index ul.events li, .promo-white-with-photo').each(function() {
				var a = $(this).find('a:first');
				var img = $(this).find('img:first');
				if (a.length) {
					var h2 = $(this).find('h2:first');
					img
					.addClass('clickable')
					.attr('title', h2.text() + ' »')
					.bind('click', function() {
						window.location.href = a.attr('href');
					})
				}
			});
			
			$('#home-custom-pngs .promo').each(function() {
				var a = $(this).find('a:first');
				var promo = $(this);
				if (a.length) {
					var h2 = $(this).find('h2:first');
					a.bind('click', function(e) { e.preventDefault(); });
					promo
					.addClass('clickable')
					.attr('title', h2.text() + ' »')
					.bind('click', function() {
						window.location.href = a.attr('href');
					});
				}
			});
			
			var league_table = $('.promo-league-table table');
			league_table.find('thead td').each(function(i) {
				var text = $(this).text().toLowerCase().replace(/ /gi,'');
				if(text == 'f' || text == 'a' || text == 'diff' || text == 'bpts' || text == 'adjust') {
					self.removeTableColumn(league_table, i);
				}
			});
			league_table.find('tbody tr:even').addClass('alt');
			league_table.find('tr').each(function() {
				$(this).find('td:first').addClass('first');
				var text = $(this).text();
				if(text.indexOf('Hammersmith') != -1) $(this).addClass('home');
			});

			var body_id = $('body').attr('id');
			var action = body_id.replace(/^([a-z]{1})/,function(letter) {return letter.toUpperCase();}).replace(/-([a-z]{1})/, function(letter) {return letter.replace(/-/,'').toUpperCase();});
			
			var action_name = 'action' + action;
			if (typeof this[action_name] != 'undefined') {
				this[action_name]();
			}
			
			var user_navigation = $.get('/login/user-navigation/', function(response) {
				// user is signed in
				if($(response).length > 2) {
					$('#user').hide().html(response).fadeIn();
					var availability = $('#user a.availability').attr('href');
					$('#footer li.members').html('<a href="'+availability+'">Member Login</a>');
				}
				// not signed in
				else {
					
				}
			});
	
			var lightbox = $('#force-lightbox');
			if(lightbox.length) lightbox.click();
			
		},
		
		redirectToSection: function(section) {
			if(section == 'mens') window.location.href = '/?team=mens';
			if(section == 'ladies') window.location.href = '/?team=ladies';
			if(section == 'youth') window.location.href = '/youth/';
			return false;
		},
		
		removeTableColumn: function(table, index) {
			table.find('tr').each(function() {
				$(this).find('td').each(function(i) {
					if(i == index) $(this).hide();
				})
			});
		},

		resizePageWrapper: function() {
			if ($('body.print').length) return;
			$('#wrapper-outer').width($('body').width() + 'px');
		},
		
		inputLabels: function() {
		    $(".toggle-text")
			.each(function() {  if(this.value == '') this.value = this.title; })
			.focus(function() { if(this.value == this.title) this.value = ''; })
		    .blur(function() { if(this.value == '') this.value = this.title; });
		},
		
		actionYouth: function() {
			this.actionHome();
		},

		actionHome: function() {
			
			var cookie_name = 'hfrfc_section';
			var section = $.cookie(cookie_name);
			
			if(section == null) {
				tb_show('', '#TB_inline?height=600&width=984&inlineId=welcomeligthbox-container&modal=true');

				$('#TB_window').css('background', 'transparent');

				$('#welcomeligthbox a').each(function() {
					$(this).find('img').stop().css({ 'opacity': 0.4 });
					$(this).hover(function() {
						$(this).find('img').stop().animate({ 'opacity': 1 }, 'fast');
					}, function() {
						$(this).find('img').stop().animate({ 'opacity': 0.4 }, 'fast');
					});
					$(this).click(function(e) {
						e.preventDefault();
						var section = $(this).parents('li:first').attr('class');
						$.cookie(cookie_name, section, { expires: 14, path: '/' });
						HFRFC.Page.redirectToSection(section);
					});
				});
			}
			
			$('#primary a.watch').bind('click', function(e) {
				e.preventDefault();
			});
			
			/*$('#primary .promo-video').each(function() {
				var overlay = $(this).find('.overlay');
				overlay
				.hover(function() {
					$(this).addClass('overlay-hover');
				}, function() {
					$(this).removeClass('overlay-hover');
				})
				.bind('click', function(e) {
					e.preventDefault();
					var hero = $(this).parents('.promo');
					hero.find('div.image > img').hide();
					hero.find('div.overlay').hide();
					hero.find('div.video').css('position', 'static').css('top', '0').css('left', '0');
				});
			});*/
			
			var original_state = null;
			$('#chalk-results ul.tabs a').bind('click', function(e) {
				e.preventDefault();
				if ($(this).parent().attr('class') == 'fixtures') {
					$('#chalk-results div.fixtures').show();
					$('#chalk-results div.results').hide();
					original_state = original_state.replace(/results/,'fixtures');
				} else {
					$('#chalk-results div.fixtures').hide();
					$('#chalk-results div.results').show();
					original_state = original_state.replace(/fixtures/,'results');
				}
			});
			
			$('#chalk-results ul.tabs a')
			.bind('mouseover', function() {
				original_state = $('#chalk-results').attr('class');
				$('#chalk-results').attr('class', $(this).parent().attr('class'));
			})
			.bind('mouseout', function() {
				$('#chalk-results').attr('class', original_state);
			});
			
			var today = $('#day-of-week').text();
			if (
				($('body').attr('id') == 'home' && (today == 'sun' || today == 'mon')) || 
				($('body').attr('id') == 'youth' && (today == 'mon' || today == 'tue'))
			) {
				original_state = 'results';
				$('#chalk-results li.results a').click();
			}
			
			// new homepage — carousel
			var animating = false;
			var fader = $('#home-carousel-fade').hide();
			
			var auto_click = false;
			var interval = setInterval(function() {
					var index = 0;
					$('#home-carousel div.label').each(function(i) {
						var li = $(this).parent();
						if (li.hasClass('selected')) index = (i + 1);
					});
					if (index == 4) index = 0;
					auto_click = true;
					$('#home-carousel div.label:eq('+index+') a').click();
				}, 5000);
			
			$('#home-carousel .slide').each(function() {
				var a = $(this).find('a:first');
				if (!a.length || $(this).find('.video').length) return;
				$(this).addClass('clickable').bind('click', function() {
					window.location.href = a.attr('href');
				});
			});
			
			$('#home-carousel .label a').bind('click', function(e) {
			
				var li = $(this).parents('li');
			
				if (animating == true || li.hasClass('selected')) return;
				animating = true;
				
				li.parent().find('li').removeClass('selected');
				li.addClass('selected');
				
				fader.fadeIn('slow', function() {
					$('#home-carousel li.show-slide').removeClass('show-slide');
					li.addClass('show-slide');
					fader.fadeOut('slow', function() {
						animating = false;
					});
				});
				
				e.preventDefault();
			});
			
			$('#home-carousel').bind('click', function() {
				if (!auto_click) {
					clearInterval(interval);
					interval = null;
				}
				auto_click = false;
			});
			
			// new homepage — stream
			var see_more = $('#see-more').hide();
			$('#latest-news .nav a').bind('click', function(e) {
				$(this).parents('ul').find('li').removeClass('selected');
				var li = $(this).parent();
				var type = li.attr('class');
				$(this).parent().addClass('selected');
				if (type == 'all') {
					$('#latest-news .item').show().removeClass('last');
					see_more.hide();
				} else {
					$('#latest-news .item').hide().removeClass('last');
					$('#latest-news div.' + type).show();
					see_more.show();
					see_more.find('a').hide();
					see_more.find('a.' + type).show();
				}
				$('#latest-news .item:visible:last').addClass('last');
				e.preventDefault();
			});
			$('.full-image').wrap('<div class="full-image-wrapper item"></div>').find('.item').removeClass('.item');
			$('#latest-news .item').filter(':gt(12)').hide();
			$('#latest-news .item:visible:last').addClass('last');
		},

		actionNews: function() {
			$('#tertiary .search .cta').bind('click', function(e) {
				e.preventDefault();
				$(this).parents('form').submit();
			});
		},

		actionFixtures: function() {
						
			var width = $('#primary').width();
			var exclude = $('#primary .header li:visible a[rel="little-hammers"]');
			if (exclude.length) {
				width = width - (exclude.width() + parseInt(exclude.css('padding-left')) + parseInt(exclude.css('padding-right')));
			}
			var teams = $('#primary .header li:visible a:not([rel="little-hammers"])');
			teams.width(Math.floor(width / teams.length) - 2).css('padding-left', 0).css('padding-right', 0);
			
			$('#primary .header select').bind('change', function() {
				var team = $(this).parents('.header').find('li.selected a').attr('rel');
				window.location.href = $('#seasons-url').val() + team + '/' + $(this).val() + '/';
			}).show();
		},

		actionReports: function() {
			var teams = $('#tertiary > ul');
			teams.find('> li.selected ul').show();
			$('a.team', teams).bind('click', function(e) {
				e.preventDefault();

				var clicked = $(this).parent();

				if (clicked.hasClass('selected')) return;

				var selected = teams.find('> li.selected');			
				selected.removeClass('selected').find('ul').slideUp();

				clicked.addClass('selected').find('ul').slideDown();

			});
			
			$('select#seasons').bind('change', function() {
				window.location.href = $('#seasons-url').val() + '?season=' + $(this).val();
			});

			$("ul.photos a[rel='gallery']").colorbox();
		},

		actionMembers: function() {
			$('.main-content a.cta').bind('click', function(e) {
				e.preventDefault();
				$(this).parent('form').submit();
			});
		},
		
		clubhouseLightsOut: function() {
			$('a.disabled').bind('click', function(e) {
				e.preventDefault();
			});
			$('#lamp a').bind('click', function(e) {
				e.preventDefault();
				var overlay = $('#lamp-overlay');
				var body = $('body');
				if (overlay.length) {
					body.removeClass('no-glow');
					$(this).parent().css('opacity', 1);
					overlay.remove()
				} else {
					$(this).parent().css('opacity', 0.4);			
					body.addClass('no-glow').append('<div id="lamp-overlay"></div>');
					$('#lamp-overlay')
						.width(body.width() + 'px')
						.height((body.height() + parseInt(body.css('padding-bottom')) + parseInt(body.css('padding-top'))) + 'px');
				}
			});
		},

		actionAwards: function() {
			this.clubhouseLightsOut();
		},
		
		actionHonours: function() {
			$('.main-content p:first').css({ 'margin-top' : '-2px' });
			$('.main-content ul:last').css({ 'padding-bottom' : '15px', 'margin-bottom' : 0 });
			
			this.clubhouseLightsOut();
		},
		
		actionHistory: function() {
			this.clubhouseLightsOut();
		},
		
		actionCommittee: function() {
			this.clubhouseLightsOut();
			$('.committee-type:last').addClass('committee-type-last');
		},

		actionFindUs: function() {
			var latlng = new google.maps.LatLng(51.476,-0.2);
			var map = new google.maps.Map($('#map').get(0), {
				zoom: 14,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				scrollwheel: false
			});
			var marker_social = new google.maps.Marker({
				clickable: false,
				position: new google.maps.LatLng(51.47782,-0.201885),
				map: map,
				icon: '/workspace/assets/images/marker-social.png'
			});
			var marker_playing = new google.maps.Marker({
				clickable: false,
				position: new google.maps.LatLng(51.469512,-0.200951),
				map: map,
				icon: '/workspace/assets/images/marker-playing.png'
			});
		},

		actionIndex: function() {
			$('#fields-per-page').bind('change', function() {
				window.location.href = $('#social-url').val() + '?fields[per-page]=' + $(this).val();
			})
			var events = $('#primary ul.events li');
			for(var i=0; i < events.length; i++) {
				if (i == 0 || i % 3 == 0) {
					var triplet = events.filter(':eq('+i+'), :eq('+(i+1)+'), :eq('+(i+2)+')');
					var max_height = 0;
					triplet.each(function() {
						var this_height = $(this).height();
						if (this_height > max_height) max_height = this_height;
					}).height(max_height);
				}
			}
		},

		actionCalendar: function() {
			var calendar = $('table#social-calendar').addClass('js');

			calendar.find('tbody tr').each(function() {

				var calendar_max_height = $(this).height();

				$(this).find('div.day').each(function() {
					var day = $(this);
					var events = day.find('.event');

					day.height(calendar_max_height);

					var event_height = calendar_max_height / events.length;
					events.height(event_height);

					events.each(function() {
						var height = $(this).height();
						var text_height = $(this).find('div').height() + parseInt($(this).find('div').css('padding-top')) + parseInt($(this).find('div').css('padding-bottom'));

						if (text_height < height) {
							$(this).find('div').css('padding-top', (height - text_height));
						}

						var a = $(this).find('a:first');
						if (a.length) {
							$(this).hover(function() {
								$(this).addClass('hover');
							}, function() {
								$(this).removeClass('hover');
							}).bind('click', function(e) {
								e.preventDefault();
								window.location.href = a.attr('href');
							});
						}						
					});


				});

			});
			
			calendar.find('tbody td').each(function() {
				var day = $(this).find('div.day');
				var text = $(this).find('span.day');
				var w = day.width();
				var h = day.height();
				var text_w = text.width();
				var text_h = text.height();
				text.css({
					'top': ((h/2) - (text_h/2)) + 'px',
					'left': ((w/2) - (text_w/2)) + 'px'
				})
			});
		},

		actionJoinUs: function() {
			var form = $('#form');		
			var postback = form.find('.validation-summary').length;

			var title = form.find('#fields-title');
			if (!postback) title.find('option[value="Mr"]').attr('selected', 'selected');
		},
		
		recountAvailabilityTotal: function() {
			var columns = [{yes:0,no:0,unknown:0},{yes:0,no:0,unknown:0},{yes:0,no:0,unknown:0},{yes:0,no:0,unknown:0}];
			
			$('tbody tr').each(function() {
				$('td.fixture', this).each(function(i) {
					var availability = $('a', this).attr('class');
					switch(availability) {
						case 'unknown':	columns[i].unknown = columns[i].unknown + 1; break;
						case 'yes':	columns[i].yes = columns[i].yes + 1; break;
						case 'no':	columns[i].no = columns[i].no + 1; break;
					}
					
				});
			});
			
			$('tr.footer td').each(function(i) {
				$('span.yes', this).text(columns[i].yes);
				$('span.no', this).text(columns[i].no);
				$('span.unknown', this).text(columns[i].unknown);
			});
			
		},
		
		actionAvailability: function() {
			var self = this;
			
			var promos = $('#secondary .promo');
			if(promos.length) {
				var sidebar = $('.split .secondary');
				promos.appendTo(sidebar);
				$('#secondary').remove();
			}
			
			self.recountAvailabilityTotal();
			
			$('input.export').bind('click', function(e) {
				e.preventDefault();
				var url = window.location.href.replace(/availability\//, 'availability/csv/');
				window.open(url);
			});
			                    
			if($('.header-grey').length > 1) $('.header-grey:last label').remove();
			
			$('form.fixtures-select select').bind('change', function() {
				$(this).parents('form').submit();
			});
			
			var fixtures = $('table td.fixture a');
			var save = $('#save span');
			var saving = 0;
			
			fixtures.bind('click', function(e) {
				e.preventDefault();
				
				var availability = $(this).attr('class');
				var member = $(this).attr('member');
				var fixture = $(this).attr('fixture');
				
				switch(availability) {
					case 'unknown':	availability = 'yes'; break;
					case 'yes':	availability = 'no'; break;
					case 'no':	availability = 'unknown'; break;
				}
				$(this).attr('class', availability);
				
				$(this).unbind('mouseout').bind('mouseout', function() {
					save.addClass('active').html('Saving...');
					var a = $(this);
					saving++;
					$.post(
						'/login/availability/ajax/',
						{
							availability: availability,
							member: member,
							fixture: fixture
						},
						function(response) {
							a.unbind('mouseout');
							saving--;
							self.recountAvailabilityTotal();
							if (saving == 0) {
								save.animate({'opacity': 1}, 750, function() {
									save.removeClass('active').html('');
								});
							}
						}
					);
				});
				
			});
		}
	},
	
	Slideshow: {

		delay: 5000,
		fade: 1000,

		slide_button_opacity: 0.2,

		animate: true,
		is_animating: false,

		container: null,
		controls: null,
		interval: null,
		items: null,

		current_item_index: null,
		current_item: null,

		init: function(container) {
			var self = this;

			this.container = $(container);		
			if (!this.container.length) return false;
			
			var custom_delay = this.container.attr('class').match(/delay-([0-9])/);
			if (custom_delay && custom_delay.length == 2) this.delay = custom_delay[1] * 1000;

			this.items = $('li', this.container);

			this.current_item = this.items.find(':first');
			this.current_item_index = 0;

			this.items.filter(':not(:first)').css({
				'opacity': 0,
				'z-index': 0
			});

			this.controls = $('<div class="controls"><ul><li class="previous"><a href="#" title="Previous">Previous</a></li><li class="next"><a href="#" title="Next">Next</a></li></ul></div>');
			this.items.each(function(i) {
				self.controls.find('.next').before('<li class="slide slide-' + i + '"><a href="#">Slide #' + (i + 1) + '</a></li>')
			});
			this.controls.find('li.slide:first').css('opacity', 1);

			this.controls.find('li').hover(function() {
				if ($(this).css('opacity') != '1') $(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			});

			this.container.append(this.controls);

			this.controls.find('a').bind('click', function(e) {
				e.preventDefault();

				if (self.is_animating == true) return false;

				var slide = $(this).parent().attr('class');

				self.stopTimer();
				self.animate = false;

				if (slide == 'next') {
					self.next();
				}
				else if (slide == 'previous') {
					self.previous();
				}
				else {
					var slide_index = parseInt(slide.replace('slide slide-','').replace('hover','').replace(' ',''));
					self.is_animating = true;
					self.current_item.css('z-index', 1);
					self.current_item = self.items.filter(':eq(' + slide_index + ')');
					self.current_item_index = slide_index;
					self.fadeInCurrent();
				}
			});

			var controls_width = 0;
			this.controls.find('li').each(function() {
				controls_width += $(this).width() + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
			});
			this.controls.find('ul').width(controls_width);

			this.controls.width(this.container.width());

			if (this.items.length <= 1) {
				this.controls.remove();
			} else {
				this.startTimer();
			}

			this.container.hover(function() {
				//self.stopTimer();
			}, function() {
				if (self.items.length > 1) {
					self.animate = true;
					self.startTimer();
				}
			})

		},

		startTimer: function() {
			var self = this;

			this.stopTimer();

			this.interval = setTimeout(function() {
				self.next();
			}, self.delay);		

		},

		stopTimer: function() {
			clearTimeout(this.interval);
			this.interval = null;
		},

		next: function() {
			var self = this;

			self.is_animating = true;

			this.current_item.css('z-index', 1);

			// get the next image
			if ((this.current_item_index + 1) == this.items.length) {
				this.current_item = this.items.filter(':first');
				this.current_item_index = 0;
			} else {
				this.current_item_index++;
				this.current_item = this.items.filter(':eq(' + this.current_item_index + ')');
			}		

			this.fadeInCurrent();

		},

		previous: function() {
			var self = this;

			self.is_animating = true;

			this.current_item.css('z-index', 1);

			// get the previous image
			if (this.current_item_index == 0) {
				this.current_item = this.items.filter(':last');
				this.current_item_index = this.items.length - 1;
			} else {
				this.current_item_index--;
				this.current_item = this.items.filter(':eq(' + this.current_item_index + ')');
			}

			this.fadeInCurrent();

		},

		fadeInCurrent: function() {
			var self = this;

			// push current image to the top
			this.current_item.css('z-index', 2);
			// start fading it in
			this.current_item.animate({ opacity: 1 }, self.fade, function() {
				// push all other images to the back
				self.items.filter(':not(:eq('+ self.current_item_index +'))').css({
					'opacity': 0,
					'z-index': 0
				});
				self.is_animating = false;

				if (self.animate) self.startTimer();

			});

			this.controls.find('li.slide').filter(':not(.slide-'+this.current_item_index+')').animate({'opacity': self.slide_button_opacity}, 250);
			this.controls.find('li.slide-' + this.current_item_index).animate({'opacity': 1}, 250);

		}

	}
}

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
		return url.link(url);
	});
};

String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		return u.link("http://twitter.com/"+username);
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};

$(window).resize(function() {
	HFRFC.Page.resizePageWrapper();
});

$(document).ready(function() {
	HFRFC.Slideshow.init('#gallery');
	HFRFC.Page.init();
});
