

function newMovie() {
	if ( $.browser.msie){
		document.location = "/movieIE/addAudio"
			return
	}
	
	if ((movieId && confirm("Do you want to create a movie ? You will lose all the data of your current project.")) || !movieId){
		$('#control').block()
		$.ajax({
			url : "/movie/create/",
			dataType : "JSON",
			success : showMovie
		})
	}
}

$(document).ready(function(){
	createImageUploader()
	createAudioUploader()
	buttonover('#buttons input')
	if (movieId != ""){
		if ( $.browser.msie)
			document.location = "/movieIE/addAudio"
			else loadMovie(movieId)
	}
	else
		createNewMovie()
		
})

function createNewMovie(){
	$.unblockUI()
	$('#control').block({message:"<a href='#' onclick='newMovie();return false'>Click here to create a new movie</a>"})
	
}


function loadMovie(id, message,nofreeze){
	if (!nofreeze)
		$('#control').block({message: (message==undefined)? message : "Loading"})
	$.ajax({
		url : "/movie/load/"+id,
		dataType : "JSON",
		success : showMovie,
		error: createNewMovie
	})
}
function showMovie(data){
	movieId=data.id
	$('#audio ul li').remove()
	$('#images ul li').remove()
	if (data.audio){
		$('#audio ul').append("<li>"+data.audio+" <b>OK</b></li>")
	}
	if (data.images){
		for (var i in data.images){
			var image = data.images[i]
			$('#images ul').append("<li><span class='name'>"+image+ "</span> <a href='#' onclick='return removeImg(\""+image+"\")'>x</a> <b>OK</b></li>")
		}
	}
	$("#name").val(data.name)
	$("#description").val(data.description)
	$("#keywords").val(data.keywords)
	$("#category :selected").removeAttr("selected")
	$('#category input[value='+data.category+']').attr("selected","selected")
	if (data.privatevid) $('#privatevid').attr('checked','checked')
	else $('#privatevid').removeAttr('checked')
	if (data.hd) $('#hd').attr('checked','checked')
	else $('#hd').removeAttr('checked')
	
	
	if (data.queued || data.processing){
		showPane(2)
		$('#newButton').attr('disabled','disabled')
		$('#tab1').addClass('inactive')
		$('#tab2').removeClass('inactive')
		$('#tab3').addClass('inactive')
		if (data.queued)
			$('.pane2 span').text("Your file is currently in queue, please wait")
		else
			$('.pane2 span').text("Your file is now being generated by our servers")
		setTimeout(function(){
			loadMovie(data.id, null,true)
		},3000)
	} else if (data.videoCreated || data.failed){
		$('#newButton').removeAttr('disabled')
		showPane(3)
		$('#tab1').addClass('inactive')
		$('#tab2').addClass('inactive')
		$('#tab3').removeClass('inactive')
		
		if (data.youtubeId)
			$('.pane3').html("Your video is now created. You can watch it here : <a href='http://www.youtube.com/watch?v="+data.youtubeId+"'>here</a>"+
					"<br><br>Your video is now being processed by Youtube, this can take several minutes.<br><br>"+
					"Click on the 'New' button to create a new video")
		else if (data.videoURL)
			$('.pane3').html("Your video is now created. You can download it <a href='"+data.videoURL+"'>by clicking here</a>.<br/>This download link is valid for two hours.<br><br>"+
					"Click on the 'New' button to create a new video")
		else if (data.failed){
			
			var errmsg = "There was a problem in creating your video<br>"
				if (data.failed) errmsg+= data.failed+ "<br>"
				errmsg +=	"<br>Click on the 'New' button to create a new video"
				$('.pane3').html(errmsg)
		}
	} else {
		$('#newButton').removeAttr('disabled')
		$('#tab1').removeClass('inactive')
		$('#tab2').addClass('inactive')
		$('#tab3').addClass('inactive')
		showPane(1)
	} 
	
	$('#control').unblock()
}

function showPane(id, that){
	if (that && $(that).hasClass('inactive'))
		return false
	$('.selec').removeClass('selec')
	$('#tab'+id).addClass('selec')
	for (var i = 1;i<4;i++){
		if (id==i)
			$('.pane'+i).show()
		else
			$('.pane'+i).hide()
	}
		
	return false
}

function removeImg(name){
	$.ajax({
		url: '/imageFile/remove/'+name,
		success: function() {
			$('#images li').each(function(){
				if (!$(this).text().indexOf(name))
					$(this).remove()
			})
		}
	})
	return false
}

//CAPTCHA
function _validate(func){
	$('#control').block({message:"Loading"})
	$.ajax({url:'/movie/isSessionSolved',dataType:'JSON',
		success: function(data){
			if (data.solved==false){
				$.ajax({
					url: '/movie/solveMedia',
					success: function(data){
						$('#control').unblock()
						$.blockUI({message:data})
					    ACPuzzle.create('wTBLlAm2DaKeREByda4Q1NLlRMcQgooe', 'solvemedia', {});
						$('#buttons2 input').click(function(){
							var inp = $('input[name=adcopy_response]').val()
							$.ajax({
								url: '/movie/solveMedia',
								type: 'POST',
								dataType: 'JSON',
								data: $('#solvemedia').serialize(),
								success: function(data){
									if (data.ok){
										$.unblockUI()
										func()
									}
									else if (data.error){
										$('#solvemediaerror').html(data.error)
										ACPuzzle.reload('')
									}
								}
							})
						})
					},
					error: function(){
						$('#control').unblock()
					}
				})
			} else {
				func()
			}
		}
		
	})
	
}

function validate(youtube) {
	$('#control').block({message:"Loading"})
	var data = $('#movieform').serialize()
	if (youtube){
		data += "&youtube=true"
	}
	$.ajax({
		url: "/movie/validate",
		type: "POST",
		data: data,
		dataType: "JSON",
		success: function(data){
			$('#control .errors').remove()
			if (data.errors && !data.errors.youtube){
				if(data.errors.images || data.errors.audio){
					if (data.errors.images)
						error('#images', data.errors.images)
					if (data.errors.audio)
						error('#audio', data.errors.audio)
				}
				if (data.errors.meta){
					for (var i in data.errors.meta){
						error('#'+i, data.errors.meta[i],"after")
					}
				}
				if (data.errors.other){
					error('#movieform', data.errors.other,true)
				}
				$('#control').unblock()
			} else {
				_validate(function(){
					if (data.errors && data.errors.youtube){
						alert ("You will now be redirected to Youtube for authentication.")
						window.location = authSubURL;
						return;
					}
					else {
						$.ajax({
							url:'/movie/queue',
							success: function() { loadMovie(movieId) },
							error: function() { loadMovie(movieId) }
						})
					}
				})
			}
			
		}
	}) 
	return false
}

function createImageUploader() {
	buttonover('#imageup')
	var uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight',
		browse_button : 'imageup',
		container : 'parentimage',
		max_file_size : '10mb',
		file_data_name: 'photo',
		url : '/imageFile/upload',
		flash_swf_url : '/js/plupload/js/plupload.flash.swf',
		silverlight_xap_url : '/js/plupload/js/plupload.silverlight.xap',
		filters : [ {
			title : "Image files",
			extensions : "jpg,gif,png"
		} ]
		/*resize : {
			width : 320,
			height : 240,
			quality : 90
		}*/
	});
	
	uploader.init();
	uploader.bind('FilesAdded', function(up, files) {
		$.each(files, function(i, file) {
			var li 
			$('#images ul li').each(function(){
				if ($(this).find('.name').text() == file.name)
					$(this).remove()
					return
			})
			$('#images ul').append(
				'<li id="' + file.id + '">' +
				"<span class='name'>" + file.name + "</span> " + ' <img src="/images/6.gif" alt="" /> (' + plupload.formatSize(file.size) + ') <b></b>' +
			'</div>');
		});
		uploader.start()
		up.refresh(); // Reposition Flash/Silverlight
	});
	
	uploader.bind('UploadProgress', function(up, file) {
		$('#' + file.id + " b").html(file.percent + "%");
		$('#' + file.id + " img").remove()
	});
	
	uploader.bind('Error', function(up, err) { apperrors('#images',up,err)});
	
	uploader.bind('FileUploaded', function(up, file, resp) {
		ttt = resp
		$('#' + file.id).html("<span class='name'>" + file.name + "</span> <a href='#' onclick='return removeImg(\""+file.name+"\")'>x</a> <b>OK</b>");
	});
}

var upgradeToPremium = function(){
	
}

var apperrors = function(sel, up, err) {
	if (err.status==403){
		err.message = "You cannot upload more than 1 image file in the free version. Please upgrade to premium to add more images."
		upgradeToPremium()
	} else if (err.code==-600){
		if (!premium)
		err.message = "File size is limited to 10 mo in the free version.<br> You can upgrade to premium to raise the limit"
		else
			err.message = "You have reached maximum file size."
	}
	$(sel + " ul li").each(function(){
		if ($(this).find('.name').text() == err.file.name)
					$(this).remove()
	})
	error(sel, err.message + "<br/> " + 
			(err.file ? "File: " + err.file.name : ""))
	
	up.refresh(); // Reposition Flash/Silverlight
}

function error(sel,message,prepend){
	var test = $("<div class='errors'><ul><li>" + 
			message +
			"</li></ul></div>"
		);
		if(prepend && prepend=="after")
			$(sel).after(test)
		else if (prepend)
			$(sel).prepend(test)
		else
			$(sel).append(test)
		
	setTimeout(function(){
		test.animate({opacity:0,height:"0px",padding:0,margin:0}, 500, function() {
			test.remove()
		})
	},6000)
}

function buttonover(that){
	$(that).mouseover(function(){
		$(this).css({
			background:'white',
			color: '#67B4DE'})
		}).mouseout(function(){
			$(this).css({
				background:'#67B4DE',
				color:'white'})
			})
	
}

function createAudioUploader() {
	buttonover('#audioup')
	var mfs = (premium) ? '650mb': '10mb',
			exts = (premium) ? 'wav,mp3' : 'mp3'
	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight',
		browse_button : 'audioup',
		container : 'parentaudio',
		max_file_size : mfs,
		file_data_name: 'audio',
		url : '/audioFile/upload',
		flash_swf_url : '/js/plupload/js/plupload.flash.swf',
		silverlight_xap_url : '/js/plupload/js/plupload.silverlight.xap',
		filters : [ {
			title : "Sound file",
			extensions : "wav,mp3"
		} ]
	});
	
	uploader.init();
	uploader.bind('FilesAdded', function(up, files) {
		$.each(files, function(i, file) {
			$('#audio ul').html(
				'<li id="' + file.id + '">' +
				file.name + ' <img src="/images/6.gif" alt="" /> (' + plupload.formatSize(file.size) + ') <b></b>' +
			'</div>');
		});
		uploader.start()
		up.refresh(); // Reposition Flash/Silverlight
	});
	
	uploader.bind('UploadProgress', function(up, file) {
		$('#' + file.id + " b").html(file.percent + "%");
	});
	
	uploader.bind('Error', function(up, err) {
		aaa = (err)
		apperrors('#audio',up,err)
	});
	
	uploader.bind('FileUploaded', function(up, file) {
		$('#' + file.id).html("<span class='name'>" + file.name + "</span> <b>OK</b>");
	});
}

