/* Author: 

*/

(function($) {

	/**
	 * types of images to allow switching of lightbox types based on file extension
	 */
	var imageTypes = "jpg png gif tif eps pdf".split(' ');
	var fancyboxOpts = {
		'inline'		: true,
		'overlayShow'	: true,
		'transitionIn'	: 'fade',
		'transitionOut'	: 'fade',
		'autoScale'		: false,
		'overlayColor' : '#000000',
		'enableEscapeButton' : true,
		'hideOnOverlayClick': true,
		'overlayOpacity': '0.8',
		'scrolling'		: 'no',
		'autoDimensions': false,
		'padding'		: '0',
		'margin' : '0',
		'showCloseButton' : false,
		'onClosed': clearFancyContent
	};

	var imagePreview = _.template('<div class="preview image"><p class="title"><%= title %></p>' +
			'<div class="img-wrap"><img src="<%= preview %>" alt="<%= title %> Preview"></div>' +
			'<div class="button-wrap"><div class="button"><a target="_blank" class="button-download" href="<%= download %>" title="Click to download this item"></a></div></div>' +
			'</div>');
	var videoTemplate = $('#videojsTemplate');
	var videoPreview = (videoTemplate.length) ? _.template(videoTemplate.html()) : null;

	/**
	 * Clears fancybox content node in order to prevent leaks and other issues with IE
	 * See http://code.google.com/p/fancybox/issues/detail?id=10
	 */
	function clearFancyContent() {
		//empty the video wrapper. was using "empty" but IE doesn't like emptying out the div with a flash object in it, but html('') works
		$('#fancy-content').html('');
	}
	
	$('.lightbox').click(
			/**
			 * Triggers lightbox and switches type of lightbox depending on extension of file
			 */
			function showPreview(e) {
				e.preventDefault();
				var target = $(e.currentTarget);
				var item = target.parentsUntil('.item').parent();
				var download = target.data('download');
				/**
				 * file extension
				 */
				var ext = download.split('.').pop().toLowerCase();
				var kind = (imageTypes.indexOf(ext) != -1) ? 'image' : 'video';
				var title = item.find('.title').text();
				var data = null, html = null, preview = target.attr('href');
				switch (kind) {
					case 'image':
						data = {title: title, preview: preview, download: download };
						html = imagePreview(data);
						$.fancybox(_.extend(fancyboxOpts, {
							'content': html,
							'width' : 844,
							'height' : 1100
						}));
						break;
					case 'video':
						var width = 784, height = 490;
						data = { vidHeight: height, vidWidth: width, vidThumb: preview, vidFile: download, title: title, download: download};
						html = videoPreview(data);
						$.fancybox(_.extend(fancyboxOpts, {
							'content': html,
							'width' : 845,
							'height' : 591,
							'onComplete': function setup() {
								VideoJS.setup("lightbox_video");
							}
						}));
						break;
				}
			}
	);
})(jQuery);

/* --------------------------- Confirmation Alert box */

function confirmationAlert(title, message) {
	$('#confirmation #confirm-title').html(title);
	$('#confirmation #confirm-body').html(message);
	$('#confirmation #confirm-yes').html('OK').click($.fancybox.close);
	$('#confirmation #confirm-cancel').html('Close').click($.fancybox.close);	

	$("#hidden-trigger-confirmation").fancybox({
		modal: true, 
		padding: 0,
		margin: 0,
		overlayColor: '#000000'
	}).trigger('click');	
}

/* --------------------------- Facebook fun */

function _authenticatedUpdateFacebookStatus(statusMessage) {
	FB.api('/me/feed', 'post', { message: statusMessage }, function(response) {
		$('div.user-toolkit-content div.col1 div.facebook a.btn-post').show();
		$('div.user-toolkit-content div.col1 div.facebook div.loading').hide();


	  if (!response) {
		log('The response...was less than overwhelming. And quite null.');		
	    confirmationAlert('Just a moment...', 'We could not update your Facebook status because Facebook started speaking gibberish. Please try again later.');		
	  } else if(response.error) {
		if( response.error.message == "(#506) Duplicate status message") {
	    	confirmationAlert('Just a moment...', 'Your status has already been updated, please wait awhile longer before posting again.');
		} else {
	    	confirmationAlert('Just a moment...', 'We could not update your Facebook status, Facebook said:<br /><br /><em>'+response.error.message+'</em><br /><br />. Please try again later.');		
		}
	  } else {
	    confirmationAlert('Success!', 'Your Facebook status has been updated. Thanks for sharing DIRECTV4Schools!');
	  }			
	});	
}

function updateFacebookStatus(statusMessage) {	
	$('div.user-toolkit-content div.col1 div.facebook a.btn-post').hide();
	$('div.user-toolkit-content div.col1 div.facebook div.loading').show();
	
	FB.init({ 
	   appId:FACEBOOK_APP_ID, cookie:true, 
	   status:true, xfbml:true, oauth: true
	});
	
	FB.getLoginStatus(function(response) {
	  if (response.session) {
		_authenticatedUpdateFacebookStatus(statusMessage);
	  } else {
	    FB.login(function(response) {
			if (response.authResponse) {
				_authenticatedUpdateFacebookStatus(statusMessage);
			} else {
			  log('User cancelled login or did not fully authorize.');
				$('div.user-toolkit-content div.col1 div.facebook a.btn-post').show();
				$('div.user-toolkit-content div.col1 div.facebook div.loading').hide();
			
			}
		}, {scope: 'publish_stream'});
	  }
	});	
}
	
	// FB.ui({ 
	// 		method: 'feed', 
	// 		description: statusMessage
	// 	});
	
//  FB.ui(
//    {
//      method: 'feed',
//      name: 'DIRECTV4Schools',
//      link: 'http://'+document.domain+'/',
//      picture: 'http://'+document.domain+'/media/img/logo-350x305.png',
//      caption: 'Reference Documentation',
//      description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
//      message: 'Facebook Dialogs are easy!'
//    },
//    function(response) {
//      if (response && response.post_id) {
//        alert('Post was published.');
//      } else {
//        alert('Post was not published.');
//      }
//    }
//  );	
//}


/* --------------------------- Initialization */

jQuery(document).ready(function () {
	$(' [placeholder] ').defaultValue();
	//initVerticalCenter();
	
	
	$(".user-logged-in-box a[title], #user-nav .group-left a[title]").tooltip({
			'effect': 'fade', 
			'delay': 100, 
			'position': 'top right', 
			'offset': [10, -45]
	}); 	
});

