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

$(function init(){
	homeCarousel.init( $('#homeCarousel') );
	
	videoPlayer.init();
	
	printPage.init();
	
	expand.init();
});

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);
}