/**************************************************
	Plug-ins
**************************************************/
$.fn.hasParent = function(objs) {
	objs = $(objs); // ensure that objs is a jQuery array
	var found = false;
	$(this[0]).parents().andSelf().each(function() {
		if ($.inArray(this, objs) != -1) {
			found = true;
			return false;
		}
	});
	return found;
};

/**************************************************
	Settings and global variables
**************************************************/
soundManager.url = Podpoesi.templateurl + 'swf';
soundManager.debugMode = false;
/**************************************************
	Controllers
**************************************************/
var owc_podpoesi_player = { // Fueld by SoundManager2 - http://www.schillmania.com/projects/soundmanager2/
	track_id		: 'nothingz0r', // Gotta be something, but at the same time nothing
	track_pos		: 0,
	track_dur		: 0,
	buffer_el		: '',
	progress_el	: '',
	init: function() {
		
		$('.play_pause').click(function(e) {
			e.preventDefault();
			
			if ( $(this).hasClass('playing') ) {
				owc_podpoesi_player.pause( $(this) );
			} else {
				owc_podpoesi_player.play( $(this) );
			}
		});
		
		$('.player_wrapper .play').click(function() { // Additional play button - just a trigger
			$(this).parent('.player_wrapper').siblings('.play_pause').trigger('click');
		});
		
		$('.progress_wrapper').click(function(e) { // Set position
			owc_podpoesi_player.set_position($(this), e);
		});
		
	},
	play: function(_this) {
		
		if ( _this.attr('id') !== owc_podpoesi_player.track_id ) { // If it's a new track
			owc_podpoesi_player.destroy();
		}
		
		owc_podpoesi_player.track_id = _this.attr('id');
		
		if ( _this.hasParent('.block') ) { // Player in the grid
			owc_podpoesi_player.progress_el = _this.siblings('.name_wrapper').find('.progress');
			owc_podpoesi_player.buffer_el = _this.siblings('.name_wrapper').find('.buffer');
			_this.addClass('playing').siblings('.name_wrapper').children('.progress_wrapper').show();
		} else { // Player elsewhere
			owc_podpoesi_player.progress_el = _this.siblings('.player_wrapper').find('.progress');
			owc_podpoesi_player.buffer_el = _this.siblings('.player_wrapper').find('.buffer');
			_this.addClass('playing').siblings('.player_wrapper').find('.progress_wrapper').show();
			$('.work li, .tracks li').removeClass('open');
			_this.parent().addClass('open').addClass('playing');
		}
		
		var track = soundManager.createSound({
			id	: owc_podpoesi_player.track_id,
			url	: _this.attr('href')
		});
		
		soundManager.play(owc_podpoesi_player.track_id, {
			whileloading: function(){
				owc_podpoesi_player.buffer_el.width( (this.bytesLoaded / this.bytesTotal) * 100 + '%' );
			},
			whileplaying: function() {
				owc_podpoesi_player.track_pos = this.position;
				owc_podpoesi_player.track_dur = this.durationEstimate;
				owc_podpoesi_player.progress_el.width( (this.position / this.durationEstimate) * 100 + '%' );
			},
			onfinish: function() {
				// Finnished
			}
		});
		
		owc_open_graph.action('listen', 'track', _this.data('url'));
	},
	pause: function(_this) {
		_this.removeClass('playing').parent().removeClass('playing');
		soundManager.pause(owc_podpoesi_player.track_id);
	},
	set_position: function(_this, e) {
		var width = _this.width();
		var x = e.pageX - _this.offset().left;
		var set_pos = ( x / width ) * owc_podpoesi_player.track_dur;
		
		soundManager.setPosition(owc_podpoesi_player.track_id, set_pos);
	},
	destroy: function() {
		// Destroy the sound, freeing up memory etc.
		soundManager.destroySound(owc_podpoesi_player.track_id);
		
		var _this = $('#'+owc_podpoesi_player.track_id);
		
		// Restore elements
		if ( _this.hasParent('.block') ) { // Player in the grid
			_this.removeClass('playing').siblings('.name_wrapper').find('.progress_wrapper').hide();
		} else { // Player elsewhere
			_this.removeClass('playing').siblings('.player_wrapper').find('.progress_wrapper').hide();
		}
		
	}
};

var owc_open_graph = {
	namespace: 'podpoesi',
	action: function( action, object, url ) {
		var api = '/me/' + owc_open_graph.namespace + ':' + action;
		var data = {};
		data[object] = url;
		//console.log(api);
		//console.log(data);
		FB.api( api, 'post', data, function(response) {
			console.log(response);
		});
	}
};

var owc_block_hover = {
	fade_time	: 200,
	init: function() {
		$('.block.has_colored').hover(function() {
			$(this).find('.color').stop(true, true).fadeIn(owc_block_hover.fade_time);
		}, function() {
			$(this).find('.color').stop(true, true).fadeOut(owc_block_hover.fade_time);
		});
	}
};

var owc_plugins = {
	masonry: function() {
		var speed = 500;
		$('#main.grid').masonry({
			animate: true,
			animationOptions: {
				duration: speed
			}
		}, function() {
			setTimeout(function() {
				owc_glitch.grid_bg_pos();
			}, speed);
		});
	},
	placeholder: function() {
		$('input[placeholder], textarea[placeholder]').placeholder();
	}
};

var owc_glitch = {
	grid: function() {
		
		var number_of_glitches;
		var glitch_class;
		
		$('#main .block').not('#poet_list').each(function() {
			number_of_glitches = Math.floor(Math.random()*3);
			
			for (var i=0; i < number_of_glitches; i++) {
				glitch_class = 'glitch' + Math.floor(Math.random()*4+1);
				$(this).prepend('<div class="glitch '+glitch_class+'"></div>');
			}
			
		});
		
		//owc_glitch.grid_bg_pos();
		
	},
	grid_bg_pos: function() {
		$('#main .block .glitch').each(function() {
			var offset = $(this).offset();
			$(this).css( 'background-position', '-'+ Math.round(offset.left) +'px -'+ Math.round(offset.top) +'px');
		});
	},
	poet: function() {
		$('#poet .work > h1').each(function() {
			$(this).prepend('<div class="glitch" style="background-position: 0 -'+ Math.random() * 1000 +'px;" />');
		});
		$('#poet .work > .col1').each(function() {
			$(this).prepend('<div class="glitch1" style="height: '+ Math.random() * 100 +'px;" /><div class="glitch2" style="width: '+ Math.random() * 200 +'px; height: '+ Math.random() * 30 +'px;" />');
		});
	}
};

var owc_tracks = {
	max_w : 0,
	slide_speed : 2000,
	init: function() {
		owc_tracks.max_w = $('.tracks > li').width();
		
		$('.tracks > li > a').hover(function() {
			$('span', this).width() > owc_tracks.max_w ? owc_tracks.slide( $('span', this) ) : false;
		}, function() {
			owc_tracks.reset( $('span', this) );
		});
	},
	slide: function(_this) {
		var remaining = _this.width() - owc_tracks.max_w;
		_this.animate({
			left: -remaining
		},{
			duration	: owc_tracks.slide_speed, 
			easing		: 'linear',
			complete	: function() {
				// Finnished
			}
		});
	},
	reset: function(_this) {
		_this.stop(true, true).css('left',0);
	}
};

var owc_favorites = {
	init: function() {
		$('.fb_not_connected .my_favourites a, #header_profile .connect').live('click', function(e) {
			e.preventDefault();
			owc_facebook_connect.prompt(function(response){
				
			console.log(response);
				document.location.href = Podpoesi.settings.favorites;
			});
		});
		
		$('.favourite a').live('click', owc_favorites.add);
		$('.delete-favorite').live('click', owc_favorites.remove);
		
		if ( owc_helpers.is_touch() ) {
			
			$('.delete').css('display','inline-block');
			
		} else {
			
			$('.tracks li, #collections li, #poets li').hover(function() {
				$('.delete', this).css('display','inline-block');
			}, function() {
				$('.delete', this).hide();
			});
			
		}
		
	},
	add: function(e){
		e.preventDefault();
		var t = this;
		var el = $(t);
		var url = el.attr('href');
		
		if ( $('body').hasClass('fb_connected') ) {
			el.parent().removeClass().addClass('loading');
		}
		
		$.getJSON(url, { ajax: true }, function(data) {
			if ( data.success ) {
				owc_favorites.added(el, data);
			} else {
				owc_facebook_connect.prompt( function(){
					owc_favorites.add.call(t, e);
				});
			}
		});
	},
	added: function(el, data) {
		
		el.parent().removeClass('loading').addClass('favourite').end().before('<span>' + Podpoesi.settings.text.added_to_favorites + '</span>').remove();
		/*FB.api('/me/feed', 'post', data.facebook, function(response) {
			if (!response || response.error) {
				//alert('Error occured');
			} else {
				//alert('Post ID: ' + response.id);
			}
		});*/
		owc_open_graph.action('favorite', data.facebook.type, data.facebook.link);
	},
	remove: function(e){
		e.preventDefault();
		var el = $(this);
		var url = el.attr('href');
		$.getJSON(url, { ajax: true }, function(data) {
			if ( data.success ) {
				el.parent().fadeOut(200, function() {
					$(this).remove();
				});
			}
		});
	}
};

var owc_facebook_connect = {
	init: function(){
		FB.init({
			appId: Podpoesi.settings.app_id,
			channelUrl: Podpoesi.templateurl + 'channel.php',
			cookie: true,
			xfbml: true
		});
		
		FB.getAuthResponse(function(response) {
			if (response.authResponse ) {
				$('body').removeClass('fb_not_connected').addClass('fb_connected');
			}
		});
		owc_facebook_connect.parse();
		
		$('.disconnect').click(function(e){
			e.preventDefault();
			FB.logout(function(){
				window.location.reload();
			});
		});
	},
	prompt: function( success ){
		var cl = $('body').crosslog({
			content	: Podpoesi.settings.text.fb_promt
		});
		FB.Event.subscribe('auth.login', success );
		FB.Event.subscribe('auth.login', function(response){
			console.log(response);
			$('body').removeClass('fb_not_connected').addClass('fb_connected');
			$('.crosslog_close').trigger('click');
		});
		owc_facebook_connect.parse();
	},
	parse: function(){
		$('.fb_login:not(.parsed)').addClass('parsed').wrapInner('<fb:login-button scope="publish_stream,publish_actions"></fb:login-button>');
		FB.XFBML.parse();
	}
};

var owc_browser = {
	ie7: function() {
		$('#main.grid .name_wrapper').each(function() {
			$('.progress_wrapper', this).width( $(this).width() - 8 ); // - 8 for borders
		});
	}
};

/**************************************************
	Helpers
**************************************************/
var owc_helpers = {
	is_touch: function(){
		return (
			(navigator.platform.indexOf("iPhone") != -1) ||
			(navigator.platform.indexOf("iPod") != -1) ||
			(navigator.platform.indexOf("iPad") != -1)
		);
	}
};

/**************************************************
	DOM Ready
**************************************************/
$(function() {
	
	owc_podpoesi_player.init();
	owc_block_hover.init();
	owc_plugins.masonry();
	owc_plugins.placeholder();
	owc_glitch.grid();
	owc_glitch.poet();
	owc_tracks.init();
	owc_favorites.init();
	//owc_facebook_connect.init();
	
	if ( $('html').hasClass('ie7') ) {
		owc_browser.ie7();
	}
	
});
