/*****************************
	FitImage Plugin (c) Tumblecloud
******************************/
(function($){
	$.fn.fitImage = function(fromOnLoad){
		// If we're calling fitImage from an image's onLoad attribute
		if(fromOnLoad){
			computeAspectRatio.call(this)
		}else{
			this.unbind("load").load(computeAspectRatio).each(function(){if (this.complete) {$(this).trigger('load')}});
		}
		function computeAspectRatio()
		{
			var parentDim = {width: $(this).closest('div').width(), height: $(this).closest('div').height()},
			parentRatio = parentDim.height / parentDim.width,
			imgRatio = this.naturalHeight / this.naturalWidth;
			
			if(imgRatio > parentRatio){ // "Taller" image
				$(this)
					.css("position", "relative")
					.css("height", "auto")
					.css("width", parentDim.width)
					.css("top", -(imgRatio * parentDim.width - parentDim.height)/2 );
			}else{ // "Wider" image
				$(this)
					.css("position", "relative")
					.css("height", parentDim.height)
					.css("width", "auto")
					.css("left", -(parentDim.height/imgRatio - parentDim.width)/2 );
			}
		}
		return this;
	}
})(jQuery);


// Global Constants Object
var G = {
	base_url: '//beta.tumblecloud.com',
	column_width : 4, // defines how many tiles wide are clickable
	tile_width: 239,  // tile width in px
	tile_height: 130, // tile height in px
	num_dynamic: 3,
	types: ['recent','popular','showcase','tutorials'],
	showcaseIDs: [507,471,527,522],
	tutorialIDs: [1545,3206],
	clouds: {}
}
G.webservice_url = G.base_url+'/services/json/';
G.object_url = G.base_url+'/obj_services/content_delivery.php';


/*****************************
	jQuery OnReady
******************************/
$(function(){
	

	$(".act_select_item:not(.tutorial)").click(function(evt){
		var txt = $(this).text().trim();
		$(".act_select_item").removeClass("selected");
		$(this).addClass("selected");
		$.when(data[txt]()).done(function(x){
			populateCloudBlock(x);
		})
	});
	
	$(".act_select_item.tutorial").click(function(){
		$(".act_select_item").removeClass("selected");
		$(this).addClass('selected');
		
		$(".act_view.cloud").hide();
		$(".act_view.tutorial").show();
	});
	
	$(".act_view.tutorial .cloud_unit").click(function(){
		var my_video_path = $(this).attr("data-videoPath");
		if (my_video_path)
		{
			try{
				jwplayer('tutorial_video_container').setup({
					'modes': [
						{type: 'html5'},
						{type: 'flash', src: './lib/js/mediaplayer-5.8/player.swf'},
						{type: 'download'}
					    ] ,
					width: 580,
					//streamer: "http://b1.tccdn.net/tutorials/",
					file: my_video_path,
					provider: 'video',
					stretching: "fill",
					skin: './lib/js/mediaplayer-5.8/skins/nemesis/nemesis.xml'
				});
				
				jwplayer().play();

				$("#single_video_container p.ggs span").text($(this).find('.item').attr('tooltip'));
				$("#single_video_container").show();
				$("#modalMask").show();
			}
			catch (err){
				//console.log(err);
			}
		}
	});
	$("#single_video_container .rht").click(function(){
		try{
			jwplayer().stop();
		}
		catch(e){}
		$("#single_video_container").fadeOut();
	});
	
	$(".act_select_item").eq(1).click();
	
	
	$(".request_invite_link").click(show_request_invite)
	$(".invite_blob .invite_email").keyup(function(evt){
		if(evt.keyCode == 13)
		{
			submit_request_invite();
			$(this).blur();
		}
	})
	
	// Bind the event.
	$(window).hashchange( function(e){
		// Alerts every time the hash changes!
		if( location.hash == "#invite")
		{
			show_request_invite();
		}
	})

	// Trigger the event (useful on page load).
	$(window).hashchange();

	$(".invite_blob .button").click(function(evt){
		submit_request_invite();
	});
	
	$("#learnMore").on("click",function(){
		$('html,body').animate({scrollTop: $("#learnMore").offset().top - 40},1000, "easeInOutExpo");
	})
})

/*****************************
	Data Functions
******************************/

var data = {
	"popular" : function(){
		return $.ajax({
		 url: G.webservice_url+'getRecentlyPopularClouds',
		 // todo: take out jsonp once backend looks for 'callback' as it should
		 data:{limit:G.num_dynamic,days:7,attributes:"id,title,comment,thumbnail_object_id,user_givenname,user_surname",additional_attributes:"comments"},
		 dataType:'jsonp',
		 jsonpCallback: 'jsonpGetPopular'
		});
	},
	"recent" : function(){
		return $.ajax({
		 url:G.webservice_url+'getRecentlyPublishedClouds',
		 data:{limit:G.num_dynamic,attributes:"id,title,comment,thumbnail_object_id,user_givenname,user_surname",additional_attributes:"comments"},
		 dataType:'jsonp',
		 jsonpCallback: 'jsonpGetRecent'
		});
	},
	"showcase": function(){
		return $.ajax({
		 url:G.webservice_url+'getCloud',
		 data:{cloud_id:G.showcaseIDs.join(','),attributes:"id,title,comment,thumbnail_object_id,user_givenname,user_surname",additional_attributes:"comments"},
		 dataType:'jsonp',
		 jsonpCallback: 'jsonpGetShowcase'
		});
	},
	"tutorials": function(){
		return $.ajax({
		 url:G.webservice_url+'getCloud',
		 data:{cloud_id:G.tutorialIDs.join(','),attributes:"id,title,comment,thumbnail_object_id,user_givenname,user_surname",additional_attributes:"comments"},
		 dataType:'jsonp',
		 jsonpCallback: 'jsonpGetTutorials'
		});
	}
	
}

/*****************************
	View Functions
******************************/
function populateCloudBlock(o)
{
	var source = $("#tmpl-cloud_unit").html();
	var template = Handlebars.compile(source);
	$(".act_view.cloud").children().remove();
	$.each(o.clouds, function(count, context_object){
		context_object.thumb_url = G.object_url+"?byId="+context_object.thumbnail_object_id+"&cloudId="+context_object.id+"&format=small_preview";
		context_object.cloud_url = 'http://beta.tumblecloud.com/cloudpage/?cloud=' + context_object.id;
		var html = template(context_object);
		var $obj = $(html);
		$obj.find("img").fitImage();
		$(".act_view.cloud").append($obj);
	})
	$(".act_view.cloud").show();
	$(".act_view.tutorial").hide();
}
function submit_request_invite(){	
	$.get("request.php", { em : $(".invite_blob .invite_email").val() }, function(e){
		$(".invite_blob .button, .invite_blob .invite_email").hide();
		$(".invite_blob .text").show();
	});
}
function show_request_invite(evt){
	$(".car_module").not(".stage").animate({"left": "1000"}, 1400)
	$(".car_module.stage").animate({"right":"1000"}, 1400)
	$(".invite_blob").fadeIn();
}

