/**
 * MIKEWEBB.js
 * http://mikewebb.tv
 * 
 * Updated: 2011-09-23
 * Author: Mark Nauroth
 * 
 * Basic functionality for MikeWebb.tv
 * 
 */ 

$(function(){
	
	
	/****** FACEBOOK SDK SETUP *****/
	FB.init({
		appId: '120105591395628', // Foothill Family Id
		status: false,
		cookie: false,
		xfbml: true
	});
	FB.XFBML.parse();
	
	
	/******** POPUP PLAYER *******/
	// Launch the media player in a popup window
	function init_player(event) {
		
		// Is there a video on the page?
		if ($('#jw').length > 0) {
			// Pause the video if one is playing
			var player_state = jwplayer().getState();
			if (!(player_state == 'PAUSED' || player_state == 'IDLE')) {
				jwplayer().pause();
			}
			
			// Save the timecode as a session variable if the video is playing
			var timecode = jwplayer().getPosition();
			if (timecode > 0) {
				// Get the id of the video
				var id = $(this).attr('id');
				
				// Send the timecode to the server
				$.ajax({
					type: 'POST',
					url: '/episodes/timecode',
					data: 'timecode='+ timecode +'&id='+ id
				});
			}
			
			/*
			// Set a cookie with the current timecode if a video is playing
			var timecode = jwplayer().getPosition();
			if (timecode > 0) {
				$.cookie('timecode', timecode, {
					path: '/'
				});
			}
			*/
		}
		
		// Load popup
		var href = $(this).attr('href');
		href = 'http://mikewebb.cake'+ href;
		
		if (timecode && timecode > 0) {
			href = href +'&seek='+ timecode;
		}
		//console.log(href);
		
		$(this).popupWindow({
			height:256,
			width:464,
			centerScreen:1,
			status:0,
			windowName: 'media_player',
			windowURL: href
		});
		
		
		// No default click action
		return false;
	}
	
	// Bind the play function to all elements with the '.play' class
	$('.play').live('click', init_player);
	
	
	
	/********* PLAY BUTTONS *********/
	// Show the buttons
	function button_show() {
		var buttons = $(this).find('.buttons');
		if (buttons.length > 0) {
			buttons.show();
		}
		
		var play = $(this).find('.thumb .play');
		if (play.length > 0) {
			play.css({'visibility':'visible'})
		}
	}
	
	// Hide the buttons
	function button_hide() {
		var buttons = $(this).find('.buttons');
		if (buttons.length > 0) {
			buttons.hide();
		}
		
		var play = $(this).find('.thumb .play');
		if (play.length > 0) {
			play.css({'visibility':'hidden'})
		}
	}
	
	// Bind button hover actions
	$('#episodes .block li').hover(button_show, button_hide);
	$('#playlist .item').hover(button_show, button_hide);
	$('.recent_episodes li').not('.featured').hover(button_show, button_hide);
	
	// Series index hover styles
	$('#series .product').hover(function(){
		var artwork = $(this).find('.artwork');
		artwork.find('div').show();
	}, function(){
		var artwork = $(this).find('.artwork');
		artwork.find('div').hide();
	});
	
	// Recommended series hover styles
	$('#single #recommended li').hover(function(){
		var artwork = $(this).find('.related_artwork');
		artwork.find('div').show();
	}, function(){
		var artwork = $(this).find('.related_artwork');
		artwork.find('div').hide();
	});
	
	
	
	/******* jQUERY TOOLS TABS ********/
	// Tabs for player
	if ($('#player .tabs').length > 0) {
		var player_tabs = $('#player .tabs').tabs('#player .panes > div').data('tabs');
	}
	
	// Tabs for playlist
	if ($('#playlist .tabs').length > 0) {
		var playlist_tabs = $('#playlist .tabs').tabs('#playlist .panes > div').data('tabs');
		var selected_tab_index = $('.tabs .selected').index();
		playlist_tabs.click(selected_tab_index);
	}
	
	
	/******* jQUERY TOOLS SCROLLABLE *******/
	// Single service scrollables
	var sunday_scrollable = $('#recent_sunday_mornings').scrollable({
		vertical: true,
		mousewheel: true,
		size: 1,
		next: '#sunday_down',
		prev: '#sunday_up'
	}).data('scrollable');
	
	var healing_scrollable = $('#recent_healing_schools').scrollable({
		vertical: true,
		mousewheel: true,
		size: 1,
		next: '#healing_down',
		prev: '#healing_up'
	}).data('scrollable');
	
	var midweek_scrollable = $('#recent_midweeks').scrollable({
		vertical: true,
		mousewheel: true,
		size: 1,
		next: '#midweek_down',
		prev: '#midweek_up'
	}).data('scrollable');
	
	// Single episodes scrollable
	var episode_scrollable = $('.episodes #playlist .scrollable').scrollable({
		vertical: true,
		mousewheel: true,
		size: 1
	}).data('scrollable');
	
	// Testimonies scrollable
	if ($('#testimonies').length > 0) {
		var testimonies_scrollable = $('#testimonies .scrollable').scrollable({
			vertical: false,
			circular: true
		}).autoscroll({
			interval: '7500'
		}).data('scrollable');
	}
	
	
	/******* SERIES USEABILITY ********/
	// Series archive click functionality
	$('.package img').click(function(e){
		var href = $(this).parents('.product').find('a').attr('href');
		window.location = href;
	});
	
	
	/********* SERIES & EPISODE SEARCH **********/
	// Determine if the mouse is inside or outside the search results element 
	var mouse_is_inside = false;
	$('#search #results').hover(function(){
		mouse_is_inside = true;
	}, function() {
		mouse_is_inside = false;
	});
	
	// Search functionality
	if ($('#search').length > 0) {
		var default_search_value = $('#search input').attr('rel');
		
		$('#search input').val(default_search_value).focus(function(){
			var current_search_value = $(this).val();
			
			// Apply active class
			$(this).addClass('active');
			
			if (current_search_value == default_search_value) {
				// Clear the default text
				$(this).val('');
			} else if (current_search_value.length > 0) {
				// Select the text in the form
				$(this).select();
				
				// Show the results
				$('#results').show();
			}
		}).blur(function(e){
			var current_search_value = $(this).val();
			
			if (!mouse_is_inside) {
				// Hide results
				$('#results').hide();
				
				// Remove active class
				$(this).removeClass('active');
				
				if (current_search_value.length < 1) {
					// Restore the default text
					$(this).val(default_search_value);
				}
			}
		}).keyup(function(keys){
			var current_search_value = $(this).val();
			
			if (current_search_value.length > 0) {
				
				if (keys.keyCode == '38') {
					// Page up
					var current = $('#search .selected');
					var current_index = current.index();
					
					// Move the selector up unless the first element is already selected
					if (!(current_index) == '0') {
						current.removeClass('selected');
						var prev = current.prev('li');
						prev.addClass('selected');
					}
					
					// Is the currently selected element in the browser's view?
					var browser_top = $(window).scrollTop();
					var browser_bottom = browser_top + $(window).height();
					
					if (prev) {
						var prev_top = prev.offset().top;
						var prev_bottom = prev_top + prev.height();
						
						if (!(prev_top <= browser_top && prev_bottom >= browser_bottom)) {
							// The current selction is not visible; scroll to it
							$.scrollTo(prev, 250, {
								offset: {
									top: -50,
									left: 0
								}
							});
						}
					}
					
				} else if (keys.keyCode == '40') {
					// Page down
					var current = $('#search .selected');
					var current_index = current.index();
					
					// Move the selector down unless the last element is already selected
					var total = $('#search li').length - 1;
					if (!(current_index == total)) {
						current.removeClass('selected');
						var next = current.next('li');
						next.addClass('selected');
					}
					
					// Is the currently selected element in the browser's view?
					var browser_top = $(window).scrollTop();
					var browser_bottom = browser_top + $(window).height();
					
					if (next) {
						var next_top = next.offset().top;
						var next_bottom = next_top + next.height();
						
						if (!(next_top >= browser_top && next_bottom <= browser_bottom)) {
							// The current selction is not visible; scroll to it
							$.scrollTo(next, 250, {
								offset: {
									top: -50,
									left: 0
								}
							});
						}
					}
					
				} else if (keys.keyCode == '13') {
					// Enter
					var url = $('#search .selected a').attr('href');
					window.location = url;
				} else {
					// Search
					$('#results').show();
					
					var model = window.location.pathname;
					model = model.split('/');
					
					$.ajax({
						type: 'POST',
						url: '/'+ model[1] +'/search',
						data: 'needle='+ current_search_value,
						dataType: 'json',
						success: function(response) {
							if (response) {
								if (response['status'] == 'success') {
									var results = response['results'];
									var html = '';
									for (var i = 0; i < results.length; i++) {
										var id = results[i]['id'];
										var title = results[i]['title'];
										var aired = results[i]['aired'];
										var description = results[i]['description'];
										var product_small = results[i]['product_small'];
										var selected = '';
										if (i == 0) {
											selected = 'class="selected"';
										}
										
										html += '<li '+ selected +'>';
										if (product_small) {
											html += product_small;
										}
										html += '<div';
											if (model[1] == 'series') {
												html += ' class="cont" ';
											} 
										html += '><a href="/'+ model[1] +'/single/'+ id +'"><h4>'+ title +'</h4>';
										if (model[1] == 'series' && description) {
											html += '<p>'+ description +'</p>';
										} else if (model[1] == 'episodes') {
											html += '<p>'+ aired +'</p>';
										}
										html += '</a></div></li>';
									}
									if (html) {
										$('#results').html(html);
									}
								} else {
									var html = '<li><h4>'+ response['msg'] +'</h4></li>';
									$('#results').html(html);
								}
							}
						}
					})
				}
			
			} else {
				// Hide results
				$('#results').hide();
			}
		});
	}
	
	
	
	/********** eCOMMERCE ************/
	// The purchase overlay
	if ($.browser.msie) {
		// Dark background for Internet Explorer (because there's no drop shadow
		var mask_color = '#000';
		var mask_opacity = '0.4';
	} else {
		// White background for the cool people
		var mask_color = '#fff';
		var mask_opacity = '0.6';
	}
	var purchase_overlay = $('#purchase_options').overlay({
		close: '.cancel',
		fixed: false,
		mask: {
			opacity: mask_opacity,
			color: mask_color
		},
		onLoad: function() {
			if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
				var culprit = this.getOverlay().get(0);
				culprit.style.removeAttribute('filter');
			}
		},
		onClose: function() {
			// Clear the purchase options after the overlay closes
			$('.cart ol').empty();
			cart_preview();
		}
	}).data('overlay');
	
	// Product selector
	$('#product_selector').change(function(){
		// Get the new purchase url from the selector
		var href = $(this).val();
		
		// Append the FoxyCart session id
		var fcsid = fcc.session_get();
		href = href + fcsid;
		
		// Update the url of the purchase button
		$('.buy').attr('href', href);
		
	});
	
	// Custom FoxyCart process
	$('#purchase_options .button').click(function(e){
		e.preventDefault();
	});
	
	fcc.events.cart.process.add(function(e) {
		// Set the cart url
		var href = '';
		if (e.tagName == 'A') {
			// Submitted from a link
			href = e.href;
		} else if (e.tagName == 'FORM') {
			// Submitted from a form
			href = 'https://'+storedomain+'/cart?'+jQuery(e).serialize();
		}
		
		if (href.match("cart=(checkout|updateinfo)") || href.match("redirect=")) {
			return true;
		} else {
			// Load the cart in the jQuery Tools overlay
			/*
			$('#purchase_options .cart').empty().html('<iframe src="'+ href +'" frameBorder="0"></iframe>');
			console.log('add');
			*/
			
			// Hide the loading animation
			/*
			if ($('#purchase_options .loading').is(':visible')) {
				$('#purchase_options .loading').hide();
			}
			*/
			
			purchase_overlay.load();
			$('#purchase_options .cart').empty().html('<iframe src="'+ href +'" frameBorder="0"></iframe>');
			
			// We don't want the iframe to add another product to the cart
			return false;
		}
	});
	
	// Shopping cart
	function cart_preview() {
		jQuery.getJSON('https://foothillfamily.foxycart.com/cart?'+fcc.session_get()+'&output=json&callback=?', function(cart){
			if (cart.product_count > 0) {
				
				// Cart has items in it
				var num = cart.product_count;
				if (num == 1) {
					var plural = 'item ';
				} else {
					var plural = 'items ';
				}
				
				$('#cart_contents span').text(num +' '+ plural);
				
				if ($.cookie('cart_visible') == '1') {
					$('#header_header').height('30px');
					$('#controls').height('40px');
				} else {
					$('#header_header').animate({
						'height': '30px'
					}, 400);
					$('#controls').animate({
						'height': '40px'
					}, 400)
					
					// Set a cookie so the bar doesn't animate again
					$.cookie('cart_visible', '1', {
						path: '/'
					});
				}
				
			} else {
				// Cart is empty; is the admin cookie set?
				if ($.cookie('admin_visible') == '1') {
					// Display the admin controls
					$('#header_header').height('30px');
					$('#controls').height('40px');
					
					// Default cart text 
					$('#cart_contents span').text('nothing');
				} else {
					$('#header_header').animate({
						'height': '0px'
					}, 400);
					$('#controls').animate({
						'height': '0px'
					}, 400)
					
					// Delete the cookie
					$.cookie('cart_visible', null, {
						path: '/'
					})
				}
			}
		});
	}	
	cart_preview();
	
	// HTML for product purchasing options
	function product(title, format, units, price) {
		var plural = null;
		if (units > 0) {
			plural = 's';
		}
		var simple_price = jQuery.trim(price.replace(/\$\W*/, ''));
		var purchase_url = 'https://foothillfamily.foxycart.com/cart?name='+ encodeURI(title) +'&price='+ simple_price +'&format='+ format.toUpperCase() +'&discs='+ units;
		var html = '<li><h3>'+ title +'<h3><p>'+ units +' '+ format + plural +' for '+ price +'</p><a href="'+ purchase_url +'" class="button">Add to Cart</a></li>';
		return html;
	}
	
	
	/************ ADS ****************/
	$('.edit').click(function(e){
		e.preventDefault();
		alert('You\'re lame.');
	});
	
	
	/************ EVENTS ************/
	$('a.more').toggle(function(){
		// Change the button text
		$(this).text('Less');
		
		// Show the additional content
		var more = $(this).parents('.cont').find('div.more');
		more.slideDown();
		
	}, function(){
		// Change the button text back
		$(this).text('More');
		
		// Hide the additional content
		var more = $(this).parents('.cont').find('div.more');
		more.slideUp();
	});

	
});
