// Custom font replacement - http://wiki.github.com/sorccu/cufon/usage
if (typeof Cufon !== 'undefined') {
	Cufon.replace('h1');
	Cufon.replace('h2:not(.tabHeader)');
}

$(function init(){
	tabs();
	// adding JWT media player to show grierson video from ChilliBean
	
	var videoLink = $('a.playVideo');
	if (videoLink.length !== 0) {
		var header = $('#header');
		var logo = $('#logo');
		var menu = $('#navigation .menu');
		var content = $('#content .content');
		
		videoLink.click(function(e) {
			var t = $(this);
			var file = t.attr('href');
			if (!header.hasClass('playerActive')) {
				logo.css({height: 50});
				menu.css({marginTop: 105});
				menu.animate({marginTop: 510}, 400);
				header.animate({height: 550}, 400, function() {
					header.addClass('playerActive');	
					// IE rendering hack
					content.css({clear: 'left'});
				});
				header.append($('<div id="headerPlayer"></div>'));				
				var image = t.parent().find('img').attr('src').replace('small', 'large');
				jwplayer("headerPlayer").setup({
					flashplayer: "assets/flash/player.swf", 
					file: file,
					image: image,
					height: 550, 
					width: 980,
					events: { onReady: function() { 
							jwplayer().play();
							$('body, html').animate({scrollTop: 0}, 200, function() {
								
							});
						}
					}
				});
			} else {
				jwplayer().load(file);
				jwplayer().play();
				$('body, html').animate({scrollTop: 0}, 200, function() {
					
				});
			}

			e.preventDefault();
		});
	}

	
	homeCarousel.init( $('#homeCarousel') );
	
	videoPlayer.init();
	
	printPage.init();
	
	expand.init();
	
	// save the state in the cookie
	// restore the state between pages
	// style the collapse button
	// sponsors - remove the bottom border

	// var s = $('#sponsors');
	// if (s.length == 1) {
	// 	var a = $('<a href="#toggle" class="toggle expanded">toggle</a>');
	// 	s.append(a);
	// 	var wrapper = s.find('div.sponsors-wrapper');
	// 	a.click(function(e) {
	// 		var t = $(this);
	// 		if (t.hasClass('expanded')) {
	// 			wrapper.slideUp();
	// 		} else {
	// 			wrapper.slideDown();
	// 		}
	// 		t.toggleClass('expanded');
	// 		s.toggleClass('expanded');
	// 		e.preventDefault();
	// 	});
	// }
	
	var b = $('div.nominations-collapse');
	if (b.length == 1){
		$('h2').addClass('nominations-hidden');
		$('ul.categories-list').addClass('nominations-hidden');
		var h3 = $('h3');
		h3.each(function() {
			var t = $(this);
			t.wrapInner('<a href="#expand-collapse"></a>').addClass('collapsed');
			var c = $('<a href="#collapse" class="js-hide">Collapse</a>');
			var next = t.next();
			next.wrap('<div class="nominations-hidden"></div>');
			next.after(c);
			
			t.click(function(e) {
				if (t.hasClass('collapsed')) {
					t.next().slideDown(function() {
						$.scrollTo(t, 500);
					});
				} else {
					t.next().slideUp();
				}
				t.toggleClass('collapsed');
				e.preventDefault();
			});
			
			c.click(function(e) {
				var t = $(this);
				t.parent().prev().addClass('collapsed');
				t.parent().slideUp();
				e.preventDefault();
			});
		});
		
		// check for # in the URL, when present try to open the relevant tab
		var loc = window.location.toString();
		var id = loc.split('#');
		if (id.length == 2) {
			var el = $('#' + id[1]);
			el.parent().prev().find('a').click();
		}
		
	}
	/*
	var imageGallery = $('#imageGallery');
	if (imageGallery.length === 1) {
		var itemTemplate = '<li><a href="{$link}"><img src="{$src}" alt="" width="90" height="90" /></a></li>';
		$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=55987060@N08&lang=en-us&display_all=1&format=json&jsoncallback=?", function(data){
			$.each(data.items, function(i,item){
				var d = {link: item.link, src: item.media.m.replace('_m.jpg', '_s.jpg')};	// replace source from medium to small image
				var img = $(itemTemplate.tpl(d));
				imageGallery.append(img);
			});
		});
	}
	*/


});

var expand = {
	init: function() {
		var exp = $('div.expand');
		if (exp.length == 0 ) return;
		
		exp.each(function() {
			var $this = $(this);
			$this.hide();
			var link = $(config.expandLink.html);
			link.click(function(e) {
				var a = $('a', link);
				if (a.hasClass('expanded')) {
					a.attr('href', '#show');
					a.html(config.expandLink.show);
					$this.slideUp('fast');
				} else {
					a.attr('href', '#hide');
					a.html(config.expandLink.hide);
					$this.slideDown('fast');
				}
				a.toggleClass('expanded')
				e.preventDefault();
			});
			$this.after(link);
		});
	}
}

//add print functionality
var printPage = {
	init: function() {
		var p = $(config.printLink)
		p.click(function(e) {
			e.preventDefault();
			window.print();
		});
		$('#header').append(p);
	}
}

// Video player in overlay
var videoPlayer = {
	init: function() {
		var m = $('#modal');
		var that = this;
		
		var initializeModal = function() {
			$('#modal div.overlay, #modal-close').click(function(e) {
				homeCarousel.play();
				hideModal();
				e.preventDefault();
			});

			//for keyboard navigation - bring the focus back
			$('#modal-close').blur(function() {
				$('#window').attr('tabindex', '-1').focus();
			});
		};
		
		var hideModal = function(fn) {
			fn = fn || function() {};
			// $('#flashContent').hide();
			m.fadeOut('fast', function() {
				$('#window div.innerContent').html('<div id="flashContent"></div>');  //remove flash object
				fn();
			});
		};

		var showModal = function(fn) {
			fn = fn || function() {};
			m.fadeIn('fast', function() {
				fn();
				$('#flashContent').show();
			});
		};
				
		var showVideo = function($this) {
			homeCarousel.stop();
			var url = $this.attr('href');
			showModal(function() {
				var flashvars = {};
				var params = {
					menu: "false",
					allowfullscreen: "true",
					bgcolor: "#000000" 
				};
				swfobject.embedSWF(url, "flashContent", "560", "312", "9.0.0", "expressInstall.swf", flashvars, params);
			});
			$('#window').attr('tabindex', '-1').focus();	
		};
		
		$('a.play-video').click(function(e) {
			var $this = $(this);
			if (m.length == 0) {
				$.get(config.modalUrl, {}, function(data) {
					$('#wrapper').after(data);
					m = $('#modal');
					initializeModal();
					showVideo($this);
				});
			} else {
				showVideo($this);
			}
			e.preventDefault();
		});

	}
}

// Home Carousel functionality - singleton
var homeCarousel = {
	o: {
		initialized: false,		//flag that the carousel has been initialze
		timer: { stop: function(){}}, 	//timer reference
		delay: 5000,
		trans: false,	//flag on when transition is in progress
		current: null,	//current element
		c: null,		//keep reference to the carousel
		li: null		//keep reference to the li items of the carousel
	},
	init: function(carousel) {
		if (carousel.length !== 1 ) return;
		this.o.c = carousel;
		this.o.li = $('li', carousel);
		this.o.current = this.o.li.length - 1;
		this.o.li.not(':eq(' + this.o.current + ')').css({
			'z-index': 1, 
			display: 'none' 
		});
		this.addControls();
		
		this.o.initialized = true;		//the carousel is ready to be used
		carousel.addClass('enabled');
		
		if (config.homeCarousel.autoplay) {
			this.play();
		}
	},
	addControls: function() {
		controls = $(config.controls)
		this.o.c.append(controls);
		$('a', controls).click(function(e) {
			homeCarousel.stop();
			if (homeCarousel.o.trans) return false
			if ($(this).parent().hasClass('right')) {
				homeCarousel.goNext();
			} else {
				homeCarousel.goPrevious();
			}
			e.preventDefault();
		});
	},
	goNext: function() {
		var active = this.o.current;
		this.o.current++;
		if (this.o.current == this.o.li.length ){
			this.o.current = 0;
		}
		this.transition(active);
	},
	goPrevious: function() {
		var active = this.o.current;
		this.o.current--;
		if (this.o.current < 0 ){
			this.o.current = this.o.li.length - 1;
		}
		this.transition(active);
	},
	transition: function(active) {
		var makeActive = this.o.current;
		this.o.li.eq(active).css({
			'z-index': 1 
		});
		this.o.trans = true;
		this.o.li.eq(makeActive).css({ 'z-index': 2 }).fadeIn('slow', function() {
			//hide previous active element
			homeCarousel.o.li.eq(active).css({
				display: 'none' 
			});
			homeCarousel.o.trans = false;
		});
	},
	stop: function() {
		if (!this.o.initialized) return;
		homeCarousel.o.timer.stop();
	},
	play: function() {
		if (!this.o.initialized) return;
		this.o.timer = $.timer(this.o.delay, function(t) {
			homeCarousel.goNext();
		});
	}
}


/*
*	jQuery Timer plugin v0.1
*	Matt Schmidt [http://www.mattptr.net]
*/
jQuery.timer = function (interval, callback) {
	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
};

/* simple template */
String.prototype.tpl = function (o) {
    return this.replace(/{\$([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );

};


/* test for empty object */
function emptyObject(o) {
	for (var i in o) { 
		return false;
	}
	return true;
}

/* link blurring extends jQ */
$.fn.nb = function() {
	this.blur();
	return this.focus(function(){
		this.blur();
	});
}

/* replaces DOM element and returns the new jQuery object*/
jQuery.fn.replace = function() {
    var stack = [];
    return this.domManip(arguments, true, 1, function(a){
        this.parentNode.replaceChild( a, this );
        stack.push(a);
    }).pushStack( stack );
};

function preloadImages() {
	var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = a.length -1; i >= 0; i--) {
		$("<img>").attr("src", a[i]);
	}
}

function log(a) {
	console.log(a);
}

//simpleCookies - utility to work with cookies courtesy to John Hunter
var simpleCookies = { 
	set: function (name, value, hours, path) {
		var expires = this.getHoursFromNow(24);
		if (hours) expires = this.getHoursFromNow(hours);
		path = path || '/';			
		var sd = document.location.hostname;
		sd = sd.substr(sd.indexOf('.'));
		document.cookie = name +'='+ escape(value) +'; domain='+ sd +'; expires='+ expires +'; path='+ path;
	},
	getHoursFromNow: function (hours) {
		return new Date(new Date().getTime() + hours * 3600000);
	},
	get: function (name) {
		name += '=';
		var c, cs = document.cookie.split(';');
		for (var i = 0, len = cs.length; i < len; i++) {
			c = cs[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(name) == 0) {
				return unescape(c.substring(name.length, c.length));
			}
		}
	}
}

var tabs = function() {
	
	var content = $('.tabbedContent');
	if (content.length === 0) {
		return;
	}

	// get all H2 elements if any
	var sections = content.find('h2');
	if (sections.length === 0) {
		return;
	}

	content.addClass('tabbedContentActive');
	
	var allChildren = content.find('> *');
	var tabs = $('<ul></ul>');
	var length = allChildren.length - 1;
	var section = $('<div class="orphanSection"></div>');		// create empty section for articles starting without header	
	content.append(section);

	content.append(tabs);
	tabs.wrap('<div class="tabs"></div>')

	for (var i = 0; i <= length; i++) {
		var element = $(allChildren[i]);
		if (element.is('h2')) {
			createTab(element, i);
			var section = $('<div class="section" style="display:none" id="section' + i + '"></div>');;
			content.append(section);
		}
		section.append(element);
	}


	tabs.find('li:first').addClass('active');
	content.find('div.section:first').show();
	
	tabs.delegate('li', 'click', function(e) {
		e.preventDefault();
		var link = $(this);
		if (link.hasClass('active')) {
			return;
		}
		var section = content.find('div.section:visible');
		var showSection = $('#section' + link.data('tabid') );
		section.fadeOut(100, function() {
			showSection.fadeIn(100);
			showSection.focus();
		});
		tabs.find('li').removeClass('active');
		link.addClass('active');
	});
	
	function createTab(element, i) {
		var li = $('<li><a href="#section' + i + '"><span>' + element.html() + '</span></a></li>');
		li.data('tabid', i);	// add tab id value
		tabs.append(li);
	}
	return {};
};
