/* Author: 

*/

var backgroundLogo = {
	containerLogo: null,
	containerSpot: null,

	init: function() {
		this.containerSpot = $('#background_spot');
		this.containerLogo = $('#background_logo');
	},

	introAnimation: function(callback) {
		backgroundLogo.containerSpot.fadeIn(500, function(){
			backgroundLogo.containerLogo.fadeOut(300, function(){
				callback && callback();
			});
		});
	}
};


var squares = {
	containerSquares: null,
	squareA: null,
	squareB: null,
	squareC: null,
	
	init: function() {
		this.containerSquares = $('#squares_container');
	},
	
	hideAll: function() {
		if (this.containerSquares.hasClass('showing')) {
			this.containerSquares.removeClass('showing').addClass('hiding').hide();
		}
	},

	showAnimation: function(callback) {
		this.containerSquares.fadeIn(1200, function(){
			callback && callback();
			squares.containerSquares.removeClass('hiding').addClass('showing');
		});
	},

	showAll: function() {
		if (this.containerSquares.hasClass('displaynone')) {
			if (backgroundLogo.containerLogo.hasClass('displaynone')) {
				// if background shouldn't be animated (non-startpage)
				squares.containerSquares.removeClass('hiding').addClass('showing').show();
			} else {
				// if background should be animated (startpage)
				backgroundLogo.introAnimation(function() {
					squares.showAnimation(function() {
						newsScroller.startCycling();
					});
				});
			}
		}
	}
};


var newsScroller = {
	newsArticlesContainer: null,
	newsMediasContainer: null,
	newsArticles: null,
	newsMedias: null,
	newsCycleTimer: null,
	currentIndex: 0,
	

	init: function() {
		this.newsArticlesContainer = $('ul.news_items.news_article');
		if (this.newsArticlesContainer.length) {
			this.newsArticles = $('>li', this.newsArticlesContainer);
			this.newsMediasContainer = $('ul.news_items.news_media');
			this.newsMedias = $('>li', this.newsMediasContainer);
		}
	},

	startCycling: function() {
		if (this.newsArticlesContainer.length) {
			this.newsArticlesContainer.css({position: 'relative'});
			this.newsMediasContainer.css({position: 'relative'});
			this.newsArticles.css({position: 'absolute', top: 0, left: 0}).hide();
			this.newsMedias.css({position: 'absolute', top: 0, left: 0}).hide();

			// remove initial .displaynone
			this.newsArticlesContainer.removeClass('displaynone');
			this.newsMediasContainer.removeClass('displaynone');

			var $currArticle = $(newsScroller.newsArticles[newsScroller.currentIndex]);
			$currArticle.fadeIn(600);

			var $currMedia = $(newsScroller.newsMedias[newsScroller.currentIndex]);
			$currMedia.fadeIn(600);

			this.newsCycleTimer = window.setInterval(newsScroller.showNext, 7200);
		}
	},

	showNext: function() {
		var $currArticle = $(newsScroller.newsArticles[newsScroller.currentIndex]);
		var $currMedia = $(newsScroller.newsMedias[newsScroller.currentIndex]);

		/* RANDOM */
		/*
		// next index should be random
		var newRandomIndex = 0;
		// there is a possibility to have endless loop here, if Math.wandom will return same number again and again. LOL.
		while (newRandomIndex == newsScroller.currentIndex) {
			newRandomIndex = parseInt(Math.floor(Math.random() * newsScroller.newsArticles.length), 10);
		}
		nextIndex = newRandomIndex;
		*/

		/* SEQUENTIAL */
		nextIndex = newsScroller.currentIndex + 1;
		if (nextIndex >= newsScroller.newsArticles.length) {
			nextIndex = 0;
		}

		var $nextArticle = $(newsScroller.newsArticles[nextIndex]);
		var $nextMedia = $(newsScroller.newsMedias[nextIndex]);

		$currArticle.fadeOut(600, function(){
			$nextArticle.fadeIn(600);
		});

		$currMedia.fadeOut(600, function(){
			$nextMedia.fadeIn(600);
		});

		newsScroller.currentIndex = nextIndex;
	}
};


var mediaPlayer = {
	$div: null,
	iScroller: null,
	player: null,

	init: function() {
		// init special links to the video
		$('a.mmedia_link, a.mmedia_link_from_menu').click(this.onClick);
	},
	
	onClick: function(e) {
		e.preventDefault();
		e.stopPropagation();
		var target = $(e.currentTarget);
		var mmedia = target.attr('href');

		var www = $(window).width() - 80;
		var hhh = $(window).height() - 80;

		var playerContainer = null;

		if ($('html').hasClass('no-video')) {
			playerContainer = $(
						'<object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">'+
							'<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />'+
							'<param name="allowFullScreen" value="true" />'+
							'<param name="wmode" value="transparent" />'+
							'<param name="flashVars" value=\'config={"canvas":{"backgroundGradient":"none","backgroundColor":"#000000"},"clip":{"scaling":"fit"},"playlist":[{"url":"'+encodeURIComponent(mmedia)+'", "autoPlay":true}]}\' />'+
							'Video will not play, <a href="'+mmedia+'">download it</a>.'+
						'</object>'
				);
		} else {
			playerContainer = $(
					'<video class="player_container" preload="auto" controls="controls">'+
						'<source src="' + mmedia + '" type="video/mp4" />'+
						'<source src="' + mmedia.replace(/\.mp4$/, '.ogv') + '" type="video/ogg" />'+
					'</video>'
				);
		}

		mediaPlayer.$div = $('#videoplayer_container');
		var $div_centered = $('<div id="videoplayer_centered"></div>');
		$div_centered.append(playerContainer);
		mediaPlayer.$div.empty().append($div_centered);

		// destroy iScrolls, if any
		textHoverScroller.destroyAll();

		var $div_square = $('<div />').addClass('square player_square');
		var $div_text = $('<div />').addClass('player_square_text');
		// workaround for touch devices
		if ($('html').hasClass('touch')) {
			// iDevices
			mediaPlayer.player = playerContainer[0];
			mediaPlayer.player.addEventListener('ended', function(e){
//				mediaPlayer.onBackClick(e);
				e.preventDefault();
				e.stopPropagation();
				mediaPlayer.player.pause();
				$div_centered.hide();
				$div_text.stop(true, true).fadeIn();
			}, false);
			mediaPlayer.player.addEventListener('pause', function(e){
//				mediaPlayer.onBackClick(e);
				e.preventDefault();
				e.stopPropagation();
				mediaPlayer.player.pause();
				$div_centered.hide();
				$div_text.stop(true, true).fadeIn();
			}, false);
		} else {
			// Desktops
			mediaPlayer.player = playerContainer[0];
		}

		var the_text = '';
		if (target.hasClass('from_news')) {
			var $art_parent = target.parent();
			var art_text_id = $art_parent.attr('id');
			art_text_id = art_text_id.replace('_media_', '_text_');
			the_text = $('#' + art_text_id).parent().html();
		} else if (target.hasClass('mmedia_link_from_menu')) {
			var link_id = target.attr('id');
			link_id = link_id.replace('_url_', '_text_');
			the_text = $('#' + link_id).html();
		} else if (target.hasClass('from_director')) {
			var $cloned_obj = $('section.copytext', target.parent()).clone();
			the_text = $('<article />').append($cloned_obj);
		}

		$div_text.append($('<div class="videoiscroll" />').append(the_text));

		// back / click to play link
		var $back_link = $('<a />');
		var $bottom_links = $('<div />').addClass('bottom_link');
		$back_link.html('back');
		$back_link.click(mediaPlayer.onBackClick);

		var $fb_link = $('<a />').addClass('facebook_video_link').attr({href: 'http://www.facebook.com/sharer/sharer.php?u=' + $(location).attr('href'), target: '_blank'});
		var $tw_link = $('<a />').addClass('twitter_video_link').attr({href: 'http://twitter.com/intent/tweet?source=webclient&text=' + $(location).attr('href'), target: '_blank'});
		var $email_link = $('<a />').addClass('email_video_link').attr({href: 'mailto:?subject=motionblur&body=' + $(location).attr('href')});
		$bottom_links.append($fb_link);
		$bottom_links.append($tw_link);
		$bottom_links.append($email_link);
		$bottom_links.append('<br />');
		$bottom_links.append($back_link);

		$div_text.append($bottom_links);

		$div_square.append($div_text);

		$div_square.hover(
			function() {
				$div_text.stop(true, true).fadeIn();
			},
			function() {
				$div_text.stop(true, true).fadeOut();
			}
		);
		mediaPlayer.$div.append($div_square);
		mediaPlayer.$div.fadeIn(400, function(){
			if (!$('html').hasClass('no-video')) {

				// start player
				mediaPlayer.player.play();

				// hide info box on timeout
				var tmr = setTimeout(function(){
					clearTimeout(tmr);
					$div_text.stop(true, true).fadeOut();
				}, 400);

			}
			// TODO: do not init iScroll if there is no need.
			var $th = $('div.videoiscroll');
			if ($th.height() < $th.children().first().outerHeight()) {
				mediaPlayer.iScroller = new iScroll($th[0], { hScrollbar: false, vScrollbar: false });
				$th.addClass('active');
			}
		});
	},
	
	onBackClick: function(e) {
		$(window).unbind('click');
		e.preventDefault();
		e.stopPropagation();
		if (!$('html').hasClass('no-video')) {
			mediaPlayer.player.pause();
		}
		mediaPlayer.$div.fadeOut(400, function() {
			if (mediaPlayer.iScroller != null) {
				mediaPlayer.iScroller.destroy();
				mediaPlayer.iScroller = null;
			}
			mediaPlayer.$div.empty();
			$('div.videoiscroll').removeClass('active');
			textHoverScroller.init();
		});
	}

};


var textHoverScroller = {
	texthoverscrollers: null,
	iScrollers: [],

	init: function() {
		textHoverScroller.texthoverscrollers = $('div.texthoverscroller');
		textHoverScroller.texthoverscrollers.each(function() {
			var $th = $(this);
			if ($th.height() < $th.children().first().outerHeight()) {
				textHoverScroller.iScrollers.push(new iScroll(this, { hScrollbar: false, vScrollbar: false }));
				$th.addClass('active');
			}
		})
	},

	destroyAll: function() {
		var len;
		for ( var i = 0, len = textHoverScroller.iScrollers.length; i < len; ++i ) {
			textHoverScroller.iScrollers[i].destroy();
			textHoverScroller.iScrollers[i] = null;
		}
		$('div.texthoverscroller').removeClass('active');
		textHoverScroller.iScrollers = [];
	}
};


function isiPad() {
    return (navigator.platform.indexOf("iPad") != -1);
}

/*******************************************
 * iphone/ipad utilities
 * 
 *******************************************/
var iPhoneUtil = {
	
	/**
	 * updates an orientation of the device
	 * 
	 */
	'updateOrientation': function() {
		document.body.className = (window.orientation == 0 || window.orientation == 180) ? "portrait" : "landscape";
	},
	
	
	/**
	 * initializes the device orientation tracking
	 * 
	 */
	'initOrientationTracking': function() {
		this.updateOrientation();
		var t = this;
		window.onorientationchange = function() {
			t.updateOrientation();
			setTimeout(t.hideURLBar, 50);
		}
	},

	
	/**
	 * hides the URL and Debug bar of the browser window
	 *  
	 */
	'hideURLBar': function() {
		setTimeout(function() { scrollTo(0, 1); }, 100);
	},
	

	/**
	 * slides the top URL and Debug bars away from the screen on start
	 * 
	 */
	'hideURLBarOnLoad': function() {
		$(window).load($.proxy(function() {
			this.hideURLBar();
		}, this));
	},
	
	
	/**
	 * preliminary initialization of the application before the document load
	 * 
	 */
	'appPreLoadInitialization': function() {
		this.hideURLBarOnLoad();
	},
	

	/**
	 * on document ready initialization of the application
	 * 
	 */
	'appPostLoadInitialization': function() {
		this.initOrientationTracking();
	}

};

iPhoneUtil.appPreLoadInitialization();

$(function() {

	// init localScroll
	$.localScroll({
		target: '#square_a', // could be a selector or a jQuery object too.
		duration: 0,
		hash: true,
		onBefore:function( e, anchor, $target ){
			// The 'this' is the settings object, can be modified
			var $ct = $(e.currentTarget);
			$('a.director_mmedia_link').removeClass('current');
			$ct.addClass('current');
		},
//		onAfter:function( anchor, settings ){
//			// The 'this' contains the scrolled element (#content)
//		}
	});

	if (document.location.hash.length) {
		$('a[href$="'+document.location.hash+'"]').addClass('current');
	}
	$('.initdisplaynone').removeClass('initdisplaynone').hide();

	backgroundLogo.init();
	squares.init();
	newsScroller.init();
	squares.showAll();

	// after all transitions
	mediaPlayer.init();
	textHoverScroller.init();

	iPhoneUtil.appPostLoadInitialization();
//	alert($(window).height());


});

