/************
 *	Jquery social Videos : Generates Thumbnail Bloc from Video URL
 *  Supported Services : Vimeo, Youtube, Dailymotion
 *	@params : Video url (jQuery String)
 *	@params : Thumbnail bloc (jQuery selector)
 *	
 *	Dev : Stephane Rouillé & Adrien Tichoux & retournage par Max La Menace et Francky la gachette
 */

var intervalle = 0;

// Build HTML Snippet from Data.
function vidDataToHtml( socialVid ){
	str = jQuery.trim(socialVid.vOwner);

	if (socialVid.vOwner) {
		var html = '<table class="tableVideo" id="' + socialVid.localId + '"><tr><td><a href="' + socialVid.vEmbedPlayer + '" title="Voir la vid\351o : '+ socialVid.vTitle +'" class="jSocialVid_Thumb">';
		html += '<img src="' + socialVid.vThumbUrl + '" width="120" height="90" /></a>';
		html += '<a href="' + socialVid.vEmbedPlayer + '" title="Voir la vid\351o : '+ socialVid.vTitle +'" class="jSocialVid_Title" >' + socialVid.vTitle + '</a><br />';
		html += '<small class="jSocialVid_Desc">' + socialVid.vDesc + '</small>';
		html += '<small class="jSocialVid_Owner">Propos\351 par : ' + socialVid.vOwner + '</small></td></tr></table>';

		$('a.jSocialVid_Title').live('click', function(event) {
			event.preventDefault();
			$(this).nyroModalManual();
			return false;
		});

		$('a.jSocialVid_Thumb').live('click', function(event) {
			event.preventDefault();
			$(this).nyroModalManual();
			return false;
		});

		$(socialVid.thumbBlocSelector).find('p.loading_h').remove();
		$(socialVid.thumbBlocSelector).append(html);
		$(socialVid.thumbBlocSelector).find('table').fadeIn();

	} else {
		socialVid.thumbBlocSelector.html( '<p class="error">GROSSE Erreur, aucune vidéo à cette adresse.</p>' );
	}
}


// YOUTUBE : Parsing du JSON associé.
function getYtVidData(data , socialVid ) {

	// Definition des Variables 
	data = data;

	author = data.entry['author'];
	socialVid.vOwner = author[0].name.$t;
	media = data.entry['media$group'];

	try {
		content = media['media$content'][0];
	} catch( Exception ) {
		content = '';
	}

socialVid.vDirectUrl = content.url;
thumbUrlObj = media['media$thumbnail'][0];
//thumbUrlObj = media['media$thumbnail'];
socialVid.vThumbUrl = thumbUrlObj.url;
nameObj = media['media$title'];
socialVid.vTitle = nameObj.$t;
descriptionObj = media['media$description'];
socialVid.vDesc = descriptionObj.$t;
socialVid.vEmbedPlayer = 'http://www.youtube.com/v/' + socialVid.vId;
//socialVid.videoExist=true;alert('video exist');
// Envoi pour formattage HTML 
vidDataToHtml( socialVid );

/*
	socialVid.vDirectUrl = content.url;
	thumbUrlObj = media['media$thumbnail'][0];
	socialVid.vThumbUrl = thumbUrlObj.url;
	nameObj = media['media$title'];
	socialVid.vTitle = nameObj.$t;
	descriptionObj = media['media$description'];
	socialVid.vDesc = descriptionObj.$t;
	socialVid.vEmbedPlayer = 'http://www.youtube.com/v/' + socialVid.vId;
	//socialVid.videoExist=true;alert('video exist');
	// Envoi pour formattage HTML 
	vidDataToHtml( socialVid );
*/
}


// DAILYMOTION : Extraction de l'id de la Video et parsing du JSON associé.
function getDmVidData( data, socialVid ) {
	// Definition des Variables 
	data=data;
	socialVid.vDirectUrl = data.url;
	socialVid.vTitle = data.title;
	socialVid.vDesc = data.description;
	socialVid.vThumbUrl = data.thumbnail_url;
	socialVid.vOwner = data.owner_screenname;
	socialVid.vEmbedPlayer = 'http://www.dailymotion.com/swf/' + socialVid.vId;
	socialVid.videoExist=true;
	// Envoi pour formattage HTML 
	vidDataToHtml( socialVid );
}



// VIMEO : Extraction de l'id de la Video et parsing du JSON associé.
function getViVidData( data, socialVid ){
	// Definition des Variables 
	data = data;
	socialVid.vDirectUrl	=	data[0].url;
	socialVid.vTitle		=	data[0].title;
	socialVid.vDesc			=	data[0].description;
	socialVid.vThumbUrl		=	data[0].thumbnail_small;
	socialVid.vOwner		=	data[0].user_name;
	socialVid.vEmbedPlayer	=	'http://vimeo.com/moogaloop.swf?clip_id=' + socialVid.vId + '&fullscreen=1' ;
	socialVid.videoExist	=	true;

	// Envoi pour formattage HTML 
	vidDataToHtml( socialVid );
}



// Validation de l'URL
function validateURL(url) {
	lengthValue = jQuery.trim(url);
	lengthValue = lengthValue.length;

	if( lengthValue > 0 ) {
		var j = new RegExp();
		j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
		lengthValue = jQuery.trim(url);
		if (!j.test(lengthValue)) {
			return false;				
		}
		return true;
	} else {
		return false;
	}
}


function stopTimer( url, socialVid ) {
	$(socialVid.thumbBlocSelector).find('p.loading_h').remove();
	$(socialVid.thumbBlocSelector).append('<p class="error">Erreur, aucune vidéo à cette adresse : ' + url + '</p>');
}


$.extend({

	jSocialVid: function( targetUrl, targetBlock, localId ) {
		var socialVid = new Object();
		targetBlock.find('.error').remove();

		if (validateURL(targetUrl)) {

			var intervalle = setTimeout(function() {stopTimer( targetUrl, socialVid )}, 7500);
			var myId = '';
			if( localId != "undefined" && localId != undefined ) {
				myId = localId;
			}

 			// Création de l'objet Social Video
			socialVid.localId = myId;
			socialVid.thumbBlocSelector = targetBlock;
			socialVid.vUrl = targetUrl;
			socialVid.videoExist = false;

			// Préparaton du bloc pour le Thumb
			socialVid.thumbBlocSelector.html('<p class="loading_h" style="height:20px" />').slideDown('slow');

			// Detection du service depuis l'URL de la video
			socialVid.vService = socialVid.vUrl.match("[a-z0-9]+\.([a-z0-9]+)\.[a-z]{2,4}.*")[1];

			if( socialVid.vService.length == 1 ) {
				socialVid.vService = socialVid.vUrl.match("([a-z0-9]+)\.[a-z]{2,4}.*")[1];
			}

			// Extraction de l'ID de la vidéo et Aiguillage vers les bons parsers
			var vid;
			var results;

//alert('social vid vService : ' + socialVid.vService);

			switch (socialVid.vService) {
				case 'dailymotion' :
					results = socialVid.vUrl.match("[a-z0-9]+\.([a-z0-9]+)\.[a-z]{2,4}.([a-z0-9]+)\.([a-z0-9]+)");
					socialVid.vId = ( results === null ) ? socialVid.vUrl  : results[3];

					$.ajax({
						type		:	"GET",
						url			:	"http://www.dailymotion.com/json/video/" + socialVid.vId,
						dataType	:	"jsonp",
						success		: function(data, textStatus) {
							clearInterval(intervalle);
							getDmVidData( data, socialVid );
							
						}
					});
					break;


				case 'youtube' :
					results = socialVid.vUrl.match("[\\?&]v=([^&#]*)");
					socialVid.vId = ( results === null ) ? socialVid.vUrl  : results[1];

					$.ajax({
						type		:	"GET",
						url			:	"http://gdata.youtube.com/feeds/api/videos/" + socialVid.vId + "?alt=json-in-script&v=2",
						dataType	:	"jsonp",
						success		: function(data, textStatus) {
//		alert('text statut : ' + textStatus + ' et data : ' + data );
							clearInterval(intervalle);
							getYtVidData( data, socialVid );
						}
					});

//					$.getScript('http://gdata.youtube.com/feeds/api/videos/' + socialVid.vId + '?alt=json-in-script&v=2&callback=getYtVidData');
					break;



				case 'vimeo' :
					results = socialVid.vUrl.match("[a-z0-9]+\.([a-z0-9]+)\.[a-z]{2,4}.([a-z0-9]+)");
					socialVid.vId = ( results === null ) ? socialVid.vUrl  : results[2];
					//$.getScript('http://www.vimeo.com/api/v2/video/' + socialVid.vId + '.json?callback=getViVidData');
//alert('vId : ' + socialVid.vId );
					$.ajax({
						type		:	"GET",
						url			:	"http://www.vimeo.com/api/v2/video/" + socialVid.vId + ".json",
						dataType	:	"jsonp",
						success		: function(data, textStatus) {
							clearInterval(intervalle);
							getViVidData( data, socialVid );
						}
					});
					break;


				default :
					socialVid.thumbBlocSelector.html( '<p class="error">Erreur, aucune vidéo à cette adresse.</p>' );
					clearInterval(intervalle);
					break; 
			}
			return true;
		} else {
			clearInterval(intervalle);
			targetBlock.html( '<p class="error">Erreur, aucune vidéo à cette adresse.</p>' );
			targetBlock.fadeIn();
			return false;
		}
	}
});


