var api;
var AllowExt = [];
var fileList = [];

$(document).ready(function() {
	UpdateMedia();
});

function ChangeTo(module) {
	if (module == '') { module = 'all';	}
	$('#content').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'media/'+module+'/xhr',
		success: function(msg){
			$('#content').unblock();
			$('#content').html(msg);
			UpdateInterface();
			UpdateMenuLink(module);
			UpdateMedia(module);
			document.title = winTitle+' > '+ ucfirst(module);
		}
	});
}

function SubCat(module, sub_cat) {
	$('#show_more').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'media/'+module+'/cat/'+sub_cat+'/xhr',
		success: function(msg){
			$('#show_more').unblock();
			$('#content').html(msg);
			UpdateInterface();
			UpdateMenuLink(module);
			UpdateMedia(sub_cat);
			document.title = winTitle+' > '+ ucfirst(module) + ' > ' + $('#media_top_link_'+sub_cat).text();
		}
	});
}

function UpdateMedia(module) {
	$('.content_control > a').removeClass("selected");
	if (typeof(module) != 'undefined') {
		if ($('#media_top_link_'+module).length) {
			$('#media_top_link_'+module).addClass("selected");
		} else {
			$('#media_top_link_all').addClass("selected");
		}
	} else {
		var result = UrlParse(window.location.href, 2);
		var ActivPage = '#media_top_link_'+result;
		if ($(ActivPage).length) {
			$(ActivPage).addClass("selected");
		} else {
			$('#media_top_link_all').addClass("selected");
		}
	}
	if ($("div.scrollable").length > 0) {
		UpdateScrollable();
	}
	if ($('#media_manage_box').length > 0) {
		$('#media_manage_box').hide();
	}
	if ($('#media_user_box').length > 0) {
		$('#media_user_box').hide();
	}
	if ($('#media_love_box').length > 0) {
		$('#media_love_box').hide();
	}
	if ($('#share_fav').length > 0) {
		$('#share_fav').jFav();
	}
	if ($('#share_link').length > 0) {
		$('#share_link > li').hover(
			function() { $('ul', this).css('visibility', 'visible'); },
			function() { $('ul', this).css('visibility', 'hidden'); }
		);
	}
}

function LoadImage(image_src) {
	var imgTesting = new Image();
	function CreateDelegate(contextObject, delegateMethod) {
		return function() {
			return delegateMethod.apply(contextObject, arguments);
		};
	}

	function imgTesting_onload() {
		$("#picture_wrap img").attr("src", this.src);
		$("#picture_wrap .container").height(this.height + 13);		// add border,margin and padding
		$("#picture_wrap .container").width(this.width + 8);			//  **little wired**
		UdpdateNav();
	}
	imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
	imgTesting.src = image_src;
}

function UpdateScrollable() {
	api = $("div.scrollable").scrollable({size: 5, api: true, keyboard: false});
	$("div.scrollable").navigator();

	$(".items img").click(function() {
		var video_key = $(this).attr("src").substring($(this).attr("src").lastIndexOf('/') + 1);
		var key = $(this).attr("id");
		if ($('#video_scroll').length > 0) {
			$.getJSON('/media/'+key+'/action/get_video/video_id/'+video_key+'/xhr', function(data) {
				if (data !== null) {
					p_image = data.link+'image/video/preview/'+video_key;
					p_video = data.link+'player/video/play/'+video_key;
					p_link = data.link+'media/'+key;
					var flashvars = {
						image: p_image,
						file: p_video,
						duration: data.duration,
						description: data.description,
						title: data.title,
						author: data.author,
						date: data.date,
						type: "http",
						provider: "http",
						autostart: false,
						width: "640",
						height: "480",
						plugins: "viral-2",
						"viral.embed": "<embed src='"+data.link+"flash/video.swf' height='480' width='640' allowscriptaccess='always' allowfullscreen='true' flashvars='"+encodeURIComponent("author="+data.author+"&description="+encodeURIComponent(data.description)+"&date="+data.date+"&duration="+data.duration+"&file="+p_video+"&image="+p_image+"&plugins=viral-2&title="+data.title+"&viral.link="+p_link+"&viral.onpause=false&viral.oncomplete=true&viral.email_footer=--%5CnTalawa.fr%5CnShare your vibes&type=http")+"' />",
						"viral.oncomplete": true,
						"viral.onpause": false,
						"viral.email_footer": "--\r\nTalawa.fr\r\nShare your vibes",
						"viral.link": p_link
					};
					var params = {};
					params.wmode = "opaque";
					params.allowfullscreen = "true";
					if ($('#video_delete').length > 0) {
						$('#video_delete').click(function() { DeleteFile(key, video_key); });

						//.attr("href", "javascript:DeleteFile('"+key+"', '"+video_key+"');");
					}
					$("#video_wrap").html('<div style="display:block;width:640px;height:480px;" id="video_player"></div>');
					swfobject.embedSWF("/flash/video.swf", "video_player", "640", "504", "9.0.0", "/flash/expressInstall.swf", flashvars, params);
				}
			});
		} else if ($('#picture_scroll').length > 0) {
			if ($(this).attr("src").indexOf('audio') > 0) {
				LoadImage('/image/audio/cover/'+video_key);
			} else {
				LoadImage('/image/picture/cover/'+video_key);
			}
		}
	}).filter(":first").click();
	if ($('#picture_scroll').length > 0) {
		$("#picture_wrap img").click(function() { NextOnClick(); });
		$('.container').hover(function(){ $('.cover').fadeIn('fast'); }, function() {	$('.cover').fadeOut('fast'); });
	}
}

function NextOnClick() {
	if (api.getClickIndex() + 1 < api.getSize()) {
		api.click(api.getClickIndex() + 1);
		var url = $('.items .active').attr("src");
		var key = url.substring(url.replace("/xhr", "").lastIndexOf('/') + 1).replace("/xhr", "");
		if (url.indexOf('audio') > 0) {
			LoadImage('/image/audio/cover/'+key);
		} else {
			LoadImage('/image/picture/cover/'+key);
		}
	}
}

function PrevOnClick() {
	if (api.getClickIndex() > 0) {
		api.click(api.getClickIndex() - 1);
		var url = $('.items .active').attr("src");
		var key = url.substring(url.replace("/xhr", "").lastIndexOf('/') + 1).replace("/xhr", "");
		if (url.indexOf('audio') > 0) {
			LoadImage('/image/audio/cover/'+key);
		} else {
			LoadImage('/image/picture/cover/'+key);
		}
	}
}

function UdpdateNav() {
	if (api.getClickIndex() + 1 < api.getSize()) {
		$('.gonext').show();
	} else {
		$('.gonext').hide();
	}
	if (api.getClickIndex() > 0) {
		$('.goprev').show();
	} else {
		$('.goprev').hide();
	}
}

function DisplayCover(key) {
	var imgTesting = new Image();
	function CreateDelegate(contextObject, delegateMethod) {
		return function() {
			return delegateMethod.apply(contextObject, arguments);
		};
	}

	function imgTesting_onload() {
		$('#dialog_box').dialog('option', 'buttons', { });
		$('#dialog_box').dialog('option', 'title', '');
		$('#dialog_box').html('<img src="'+this.src+'"/>');
		$('#dialog_box').dialog('option', 'bgiframe', true);
		$('#dialog_box').dialog('option', 'width', this.width + 21);
		$('#dialog_box').dialog('option', 'height', this.height + 57);
		$('#dialog_box').dialog('open');
		$(document).click(function() { $('#dialog_box').dialog('close'); $(document).unbind("click"); });
		$('#dialog_box').click(function(e) {e.stopPropagation();});
		$('#content').unblock();
	}
	$('#content').block({ message: null, overlayCSS: { backgroundColor: '#FFF' } });
	imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
	imgTesting.src = '/image/audio/cover/'+key;
}

function Show(key) {
	$('#content').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'media/'+key+'/xhr',
		success: function(msg){
			$('#content').unblock();
			$('#content').html(msg);
			UpdateInterface();
			UpdateMenuLink($('#crumbs li:eq(2)').text().toLowerCase());
			UpdateMedia($('#crumbs li:eq(2)').text().toLowerCase());
			if ($('#media_user_box').length > 0) {
				UpdateUserMenu(key);
			}
			if ($('#media_manage_box').length > 0) {
				UpdateManageMenu(key);
			}
			if ($('#media_love_box').length > 0) {
				UpdateLoveBox(key);
			}
			document.title = winTitle +' > ' + $('#crumbs li:last').text();
		}
	});
}

function UpdateUserMenu(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/user_menu/xhr',
		success: function(msg){
			if (msg.length > 0) {
				$('#media_user_link').html(msg);
				$('#media_user_box').show();
			}
		}
	});
}

function UpdateLoveBox(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/love_box/xhr',
		success: function(msg){
			if (msg.length > 0) {
				$('#media_love_link').html(msg);
				$('#media_love_box').show();
			} else {
				$('#media_love_box').hide();
			}
		}
	});
}

function UpdateManageMenu(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/manage_menu/xhr',
		success: function(msg){
			if (msg.length > 0) {
				$('#media_manage_link').html(msg);
				$('#media_manage_box').show();
			}
		}
	});
}

function SendToFav(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/favorite/xhr',
		success: function(msg){
			if ($("#savtofav").html().indexOf('Add') === 0) {
				$("#savtofav").html('Remove from favorites');
			} else {
				$("#savtofav").html('Add to favorites');
			}
			UpdateLoveBox(key);
		}
	});
}

function FollowComments(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/follow/xhr',
		success: function(msg){
			if ($("#follow_comments").html().indexOf('Follow') === 0) {
				$("#follow_comments").html('Unfollow users comments');
			} else {
				$("#follow_comments").html('Follow users comments');
			}
		}
	});
}

function ShowMore(module, sub_cat, page) {
	$('#show_more').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'media/'+module+'/cat/'+sub_cat+'/page/'+page+'/xhr',
		success: function(msg){
			$('#show_more').unblock();
			$('#show_more_botton').remove();
			$('#show_more').append(msg);
			UpdateInterface();
		}
	});
}

function GoPage(key, page) {
	if (!$('#last_comments').length) {
		Show(key);
	}
	$('#last_comments').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/comments/page/'+page+'/xhr',
		success: function(msg){
			$('#last_comments').unblock();
			$('#last_comments').html(msg);
			UpdateInterface();
		}
	});
}

function EditMedia(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/edit/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Edit this media');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Save Changes": function() { SubmitEdit(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
		}
	});
}

function EditFileName(file) {
	if ($('#'+file).length > 0) {
		$('#'+file+' > a').hide();
		$('#'+file+' > form').show();
		$(document).click(function() { $('#'+file+' > form').hide(); $('#'+file+' > a').show(); $(document).unbind("click"); });
		$('#'+file).click(function(e) { e.stopPropagation(); });
	}
}

function SubmitEditFile(key) {
	DeasactiveForm($('#'+key+' > form'));
	$('#'+key+' > form').submit();
}

function SendMediaComment() {
	DeasactiveForm('#comment_form');
	$('#comment_form').submit();
}

function SubmitDelete() {
	if (confirm("Sure ?")) {
		DeasactiveForm('#delete_form');
		$('#delete_form').submit();
	}
}

function SubmitEdit() {
	DeasactiveForm('#edit_form');
	$('#edit_form').submit();
}

function UpdatePostedForm(formType, msg, key) {
	if (formType == 'delete') {
		if (msg.indexOf('error:') > -1) {
			ActiveForm('#delete_form');
			DisplayError($('#delete_form_error'), msg);
		} else {
			window.location="/media";
		}
	} else if (formType == 'edit') {
		if (msg.indexOf('error:') > -1) {
			ActiveForm('#edit_form');
			DisplayError($('#edit_form_error'), msg);
		} else {
			window.location.reload(true);
		}
	} else if (formType == 'comment') {
		ActiveForm('#comment_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#comment_form_error'), msg);
		} else {
			$('#body').val('Write something...');
			GoPage(msg+'-'+key, -1);
		}
	} else if (formType == 'add_files') {
		window.onbeforeunload = null;
		$('#dialog_box').unbind('dialogbeforeclose');
		window.location.reload(true);
	} else if (formType == 'file_edit' && key != '' && $('#'+key+' > form').length > 0) {
		ActiveForm($('#'+key+' > form'));
		if (msg.indexOf('error:') > -1) {
			alert(msg);
			$('#'+key+' > form > input[name="file_name"]').focus();
		} else {
			$('#'+key+' > a').text($('#'+key+' > form > input[name="file_name"]').val());
			$('#'+key+' > form').hide();
			$('#'+key+' > a').show();
		}
	} else {
		alert(msg);
	}
}

function SetupAutocomplete() {
	$('.autocomplete input').each(function (obj) {
		link = $(this).attr('name').substring($(this).attr('name').lastIndexOf('_') + 1);
		if (link.lastIndexOf('[') >= 0) {
			link = link.substring(0, link.length - 2);
		}
		$(this).autocomplete("/", { extraParams: { 'share':link, 'xhr': 'on' } });
	});
}

function DeleteMedia(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/delete/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Delete this media');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'buttons', { "Yes, delete It !": function() { SubmitDelete(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
		}
	});
}

function AddMediaFiles(key) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/add_files/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Add files to this media');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Upload It !": function() { BeginUpload($('#upload_form_error')); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			$('#dialog_box').bind('dialogbeforeclose', function(event, ui) { document.title = oldTitle; });
			UpdateInterface();
			document.title = sufTitle+' | Upload';
			$(window).unbind("ajaxStart");
			$(window).unbind("ajaxStop");
			$("body").css("cursor", "auto");
			$("#progressbar").progressbar({ value: 0 });
			if ($('#type').val() == 'audio') {
				AllowExt = ["wav", "mp3", "ogg", "wma"];
			} else if ($('#type').val() == 'video') {
				AllowExt = ["avi", "mpg", "mpeg", "flv", "asf", "asx", "wmv", "mov", "mp4", "qt", "rm"];
			} else if ($('#type').val() == 'picture') {
				AllowExt = ["jpg", "jpeg", "gif", "png"];
			} else if ($('#type').val() == 'other') {
				AllowExt = ["pdf", "doc", "txt"];
			}
		}
	});
}

function CheckAddedFile(obj) {
	link = $(obj).parent().attr('id').substring($(obj).parent().attr('id').lastIndexOf('_') + 1);
	var ext = (/[.]/.exec($(obj).val().toLowerCase())) ? /[^.]+$/.exec($(obj).val().toLowerCase()) : undefined;
	if (!in_array(ext, AllowExt)) {
		msg = "This file's extension is not allowed for upload.\nYour file have to be one of those :\n";
		for (i=0; i<AllowExt.length; i++) {
			msg += AllowExt[i]+", ";
		}
		msg = msg.substring(0, (msg.lastIndexOf(','))) + '.';
		alert(msg);
		$('#upload_file_'+link).html($('#upload_file_'+link).html());
		return;
	}
	AddFile(link+1);
}

function CheckEditedFile(obj) {
	var TestExt = ["jpg", "jpeg", "gif", "png"];
	var ext = (/[.]/.exec($(obj).val().toLowerCase())) ? /[^.]+$/.exec($(obj).val().toLowerCase()) : undefined;
	if (!in_array(ext, TestExt)) {
		ext = '';
		for (i=0; i < TestExt.length; i++) {
			ext += TestExt[i]+", ";
		}
		ext = ext.substring(0, (ext.lastIndexOf(','))) + '.';
		alert("This file's extension is not allowed for the flyer.\nYour file have to be one of those :\n"+ext);
		$('#flyer_div').html($('#flyer_div').html());
		return false;
	}
}

function DownloadMedia(title, file_name) {
	$('#content_download').html('');
	if (file_name) {
		$('#content_download').attr('src', '/media/'+title+'/action/download/file_id/'+file_name+'/xhr');
	} else {
		$('#content_download').attr('src', '/media/'+title+'/action/download/xhr');
	}
}

function PlaySong(file_name) {
	var playerWin = window.open("/player/audio/file/"+file_name, 'audio_player_win', 'height=390, width=440, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
	if (!playerWin) {
		 alert("A popup blocker has been detected, please turn it off for listen to music !");
	}
}

function PlayAllSong(short_name) {
	var playerWin = window.open("/player/audio/playlist/"+short_name, 'audio_player_win', 'height=390, width=440, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
	if (!playerWin) {
		 alert("A popup blocker has been detected, please turn it off for listen to music !");
	}
}

function customHistory(hash) {
	var tableau=hash.split('/');
	if (tableau.length == 1) {
		if (is_webid(tableau[0])) {
			Show(tableau[0]);
		} else {
			ChangeTo(tableau[0]);
		}
	} else if (tableau.length >= 2) {
		if (tableau[1] == 'cat' && tableau[2] !== null) {
			SubCat(tableau[0], tableau[2]);
		} else if (tableau[1] == 'page' && tableau[0] !== null && tableau[2] !== null) {
			GoPage(tableau[0], tableau[2]);
		}
	}
}

function DeleteMessage(key, id) {
	$.ajax({
		url: '/',
		data: 'media/'+key+'/action/delete_com/com_id/'+id+'/xhr',
		success: function(msg){
			GoPage(key, 1);
		}
	});
}

function AddToFavorite(url, title) {
	var e;
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if (window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	}	else if (window.opera && window.print) { // Opera Hotlist
		e = document.createElement('a');
		e.setAttribute(url, self.location);
		e.setAttribute(title, document.title);
		e.setAttribute('rel','sidebar');
		e.click();
	} else {
		e = document.createElement("A");
		e.setAttribute('href', self.location);
		e.setAttribute('title',document.title);
		e.setAttribute('rel','sidebar');
		document.location.href = self.location;
		return true;
	}
}

function DeleteFile(key, file_name) {
	if (confirm("Sure ?")) {
		$.ajax({
			url: '/',
			data: 'media/'+key+'/action/delete_file/file_id/'+file_name+'/xhr',
			success: function(msg){
				window.location.reload(true);
			}
		});
	}
}
