var rpcURL = '../rpc.asp';
var saveURL = '../save_lecture.asp';

function cloneInput(src,tgt){
	src.keyup(function(){
		tgt.html($(this).val());
	});
}

function showPane(tgt){
	$('#speakers_bottom div.pane').hide();
	tgt.show();
	updateTinyMCE();
	
	return true;
}

function drawPreloader(class_IN){
	var html = '';
	html += '<div class="preloader';
	if(class_IN!=undefined) html += ' '+class_IN;
	html += '">Please Wait...</div>';
	
	return html;
}

function clearTinyMCE(){
	if(window.tinyMCE){
		tinyMCE.execCommand("mceRemoveControl", false, 'iLectureDesc');
		tinyMCE.execCommand("mceRemoveControl", false, 'iTranscript');
	}
}

function updateTinyMCE(){
	clearTinyMCE();
	if(window.tinyMCE){
		if($('div.desc').css('display')=='block'){
			tinyMCE.execCommand("mceAddControl", false, 'iLectureDesc');
		}else if($('div.transcript').css('display')=='block'){
			tinyMCE.execCommand("mceAddControl", false, 'iTranscript');
		}
	}
}

function updateTitleDates(){
	var startDate = null;
	var endDate = null;
	$('#speakers_top a.active').each(function(i){
		if($('small.date',this).html()!=''){
			if(i==0){
				startDate = $('small.date',this).html();
			}else{
				endDate = $('small.date',this).html();
			}
		}
		return true;
	});

	var output = '';
	if(startDate!=null){
		if(endDate!=null){
			startDate = startDate.split(' ');
			startDate[1] = startDate[1].substr(0,3);
			if(Number(endDate.split(' ')[2])==Number(startDate[2])) startDate.pop();
			startDate = startDate.join(' ');
		}
		output += startDate;
		if(endDate!=null){
			output += ' - ';
			endDate = endDate.split(' ');
			endDate[1] = endDate[1].substr(0,3);
			endDate = endDate.join(' ');
			output += endDate;
		}
	}
	$('#seriesDates').html(output);
}

function drawLectureTop(id,active,name,speaker,date){
	var output = '';
	output += '<a id="spk_'+id+'" class="bDesc';
	if(active) output += ' active';
	output += '" style="display:none;" href="">';
	output += '<div><span>';
	output += '<strong class="name">'+name+'</strong>';
	output += '<small class="speaker">'+speaker+'</small>';
	output += '<small class="date">'+date+'</small>';
	output += '</span></div>';
	output += '</a>';
	return output;
}

function drawPaneNav(editMode,hasVideo,hasTranscript,commentsActive){
	var html = '';
	html += '<div class="lectureNav">';
		if(hasVideo||editMode) html += '<a class="bWatch" href="">Watch</a>';
		if(hasTranscript||editMode) html += '<a class="bRead" href="">Read</a>';
		if(commentsActive||editMode) html += '<a class="bDebate" href="">Debate</a>';
	html += '</div>';
	
	return html;
}

function drawVideoPlayer(id){
	var html = '';
	if(id==undefined) id = Number($('div.videoPlayer input').val());
	if(id!=0){
		html += '<object width="100%" height="100%">';
		html += '<param name="allowfullscreen" value="true" />';
		html += '<param name="allowscriptaccess" value="always" />';
		html += '<param name="wmode" value="transparent" />';
		html += '<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id='+id+'&amp;server=www.vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1" />';
		html += '<embed src="http://www.vimeo.com/moogaloop.swf?clip_id='+id+'&amp;server=www.vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" wmode="transparent" width="100%" height="100%">';
		html += '</embed>';
		html += '</object>';
	}
	
	$('div.videoPlayer object').remove();
	$('div.videoPlayer').prepend(html);
	$('div.videoActions').removeClass('full').removeClass('corner');
	if(id!=0){
		$('div.videoActions').addClass('corner');
	}else{
		$('div.videoActions').addClass('full');
	}
}

function drawData(data){
	var html = '';
	html += drawPaneNav(data.editMode,data.output.video!=0,(data.output.transcript!=''||data.output.transcriptFile!=''),data.output.commentsActive!=0);
	if(data.editMode){
		html += '<div class="admin_bar">';
		html += '<h2>Lecture Settings</h2>';
		html += '<div class="content">';
		html += '<div class="input name">';
		html += '<label for="iLectureTitle">Lecture Name: </label>';
		html += '<input type="text" name="iLectureTitle" value="'+data.output.name+'" />';
		html += '</div>';
		html += '<div class="input date">';
		html += '<label for="iLectureDate">Lecture Date: </label>';
		html += '<input type="text" name="iLectureDate" value="'+data.output.date+'" />';
		html += '</div>';
		html += '<div style="clear:both;"></div>';
		html += '<div class="input speaker">';
		html += '<label for="iLectureSpeaker">Speaker Name: </label>';
		html += '<input type="text" name="iLectureSpeaker" value="'+data.output.speaker+'" />';
		html += '</div>';
		html += '<div class="input active">';
		html += '<label for="iLectureActive">Lecture Active: </label>';
		html += '<input type="checkbox" name="iLectureActive" value="1"';
		if(data.output.active==1) html += ' checked="checked"';
		html += '/>';
		html += '</div>';
		html += '<div class="input actions">';
		html += '<input type="submit" value="Save" />';
		if($('#speakers_top a').length > 1) html += '<input type="button" class="bDeleteLecture" value="Delete" />';
		html += '</div>';
		html += '<div style="clear:both;"></div>';
		html += '<input type="hidden" name="iLectureID" value="'+((data.output.id!=undefined)?data.output.id:'')+'" />';
		html += '</div>';
		html += '</div>';
	}
	html += '<div class="pane desc">';
	if(data.editMode) html += '<textarea name="iLectureDesc" id="iLectureDesc">';
	html += (data.output.desc!=undefined)?data.output.desc:'';
	if(data.editMode) html += '</textarea>';
	html += '</div>';
	html += '<div class="pane video" style="display:none;">';
	html += '<div class="videoPlayer">';
	if(data.editMode){
		html += '<input type="hidden" name="iLectureVideo" value="'+((data.output.video!=undefined && data.output.video!='')?data.output.video:'')+'" />';
		html += '<div class="videoActions"><a class="bSelectVideo" href="">[select video]</a> <a class="bRemoveVideo" href="">[remove video]</a></div>';
	}
	html += '</div>';
	html += '</div>';
	html += '<div class="pane transcript" style="display:none;">';
	html += '<h3>Transcript</h3>';
	html += '<div class="transcriptFile">';
	if(data.output.transcriptFile!=undefined && data.output.transcriptFile!='') html += '<a target="_blank" href="'+data.output.transcriptFile+'">Download this transcript</a>';
	if(data.output.transcriptFile!=undefined && data.output.transcriptFile!='' && data.editMode) html += '<input type="button" class="bRemoveTranscript" value="Remove" />';
	if(data.editMode){
		html += '<input type="file" name="iTranscriptFile" size="50" value="" />';
	}
	html += '</div>';
	html += '<div class="transcriptHTML">';
	if(data.editMode) html += '<textarea name="iTranscript" id="iTranscript">';
	html += (data.output.transcript!=undefined)?data.output.transcript:'';
	if(data.editMode) html += '</textarea>';
	html += '</div>';
	html += '</div>';
	if(data.output.commentsActive!=0||data.editMode){
		html += '<div class="pane comments" style="display:none;">';
		html += '<h3>Your Comments</h3>';
		if(!data.editMode) html += '<a class="bAddComment" href="">Add your Comment</a>';
		if(data.editMode){
			html += '<div class="dEnableComments"><label for="iCommentsActive">Enable Comments:</label><input type="checkbox" name="iCommentsActive" value="1" /></div>';
		}
		html += '<div style="clear:both;"></div>';
		html += '<div class="commentList">';
		html += '</div>';
		if(!data.editMode){
			html += '<div class="commentForm">';
			html += '<h3>Join the debate about this lecture</h3>';
			html += '<form method="post" action="../add_comment.asp" id="add_comment">';
			html += '<fieldset>';
			html += '<label for="name">Name</label><input type="text" name="name" class="commentName"/>';
			html += '<label for="place">City/Country</label><input type="text" name="place" class="commentPlace"/>';
			html += '<label for="email">Email</label><input type="text" name="email" class="commentEmail"/>';
			html += '<label for="comment">Comment: <small>(maximum 1000 characters)</small></label><textarea name="comment" class="commentText" />';
			html += '<input type="hidden" name="lectureID" value="'+data.output.id+'" />';
			html += '<input type="submit" value="Add comment" name="submit" id="submit" class="bSubmit"/>';
			html += '</fieldset>';
			html += '</form>';
			html += '</div>';
		}
		html += '</div>';
	}
	
	$('#speakers_bottom').html(html);
	
	updateTinyMCE();
	
	$('input.bDeleteLecture').click(function(){
		if(confirm('Are you sure you want to delete this lecture?\r\n\r\nPress OK to Delete\r\nPress Cancel to return to the editor')){
			var lectureID = String($('#speakers_top a.current').attr('id')).split('_')[1];
			$.ajax({
				url:rpcURL,
				type:'POST',
				data:{action:'deleteLecture',id:lectureID},
				dataType:'text',
				success:function(data){
					if(data=='true'){
						$('#speakers_top a.current').remove();
						arrangeLectures();
						updateTitleDates();
						getData($('#speakers_top a:last'));
					}
				}
			});
		}
		return false;
	});
	$('#speakers_top a.bDesc').click(function(){return !showPane($('#speakers_bottom div.desc'));});
	$('#speakers_bottom div.lectureNav a.bWatch').click(function(){return !showPane($('#speakers_bottom div.video'));});
	$('#speakers_bottom div.lectureNav a.bRead').click(function(){return !showPane($('#speakers_bottom div.transcript'));});
	$('#speakers_bottom div.lectureNav a.bDebate').click(function(){return !showPane($('#speakers_bottom div.comments'));});
	if(data.editMode){
		cloneInput($('div.name input'),$('a.current strong.name'));
		cloneInput($('div.speaker input'),$('a.current small.speaker'));
		$('div.active input').click(function(){
			if(this.checked){
				$('a.current').addClass('active');
			}else{
				$('a.current').removeClass('active');
			}
			updateTitleDates();
		});
		$('div.date input').datepicker({
			dateFormat:'d MM yy',
			onClose:function(newDate){
				$('#speakers_top a.current').attr('timestamp',Date.parse(newDate));
				$('#speakers_top a.current small.date').html(newDate);
				$('div.active input').triggerHandler('click');
				sortLectures();
			}
		});
	}
	
	drawVideoPlayer(data.output.video);
	if(data.editMode){
		$('div.videoPlayer a.bSelectVideo').click(drawVideoPopup);
		$('div.videoPlayer a.bRemoveVideo').click(function(){
			$('div.videoPlayer input').val('');
			drawVideoPlayer();
			return false;
		});
	
		$('div.transcriptFile input.bRemoveTranscript').click(function(){
			$.ajax({
				url:rpcURL,
				type:'POST',
				data:{action:'deleteAttachment',id:data.output.id},
				dataType:'text',
				success:function(data){
					if(data=='true'){
						$('div.transcriptFile a').remove();
						$('div.transcriptFile input.bRemoveTranscript').remove();
					}
				}
			});
		});
	}
	
	if(data.output.commentsActive!=0||data.editMode){
		$('div.commentList').html(drawPreloader());
		$.ajax({
				url:rpcURL,
				type:'POST',
				data:{action:'getComments',id:(data.output.id!=undefined)?data.output.id:0},
				dataType:'json',
				success:function(data){
					var html = '';
					if(data.commentsActive) $('.dEnableComments input').val(['1']);
					if(data.output.length>0){
						for(var i=0;i<data.output.length;i++){
							var comment = data.output[i];
							html += '<div class="comment" id="comment_'+comment.id+'">';
							html += '<div class="header">';
							html += '<span class="author"><strong>';
							if(data.editMode) html += '<a href="mailto:'+comment.email+'">';
							html += comment.name;
							if(data.editMode) html += '</a>';
							html += '</strong> from <strong>'+comment.place+'</strong></span>';
							html += '<span class="date">'+comment.date+'</span>';
							html += '</div>';
							html += '<div class="body';
							if(data.editMode) html += (comment.enabled)?' enabled':' disabled';
							html += '">';
							html += String(comment.comment).replace(/\r\n/g,'<br />');
							html += '</div>';
							html += '</div>';
						}
					}else{
						html = '<p>There are currently no comments</p>';
					}
					$('div.commentList').html(html);
					if(data.editMode){
						var html = '';
						html += '<div class="actions">';
						html += '<input class="bEditComment" type="button" value="Edit" />';
						html += '<input class="bSaveComment" type="button" value="Save" style="display:none;" />';
						html += '<input class="bCancelComment" type="button" value="Cancel" style="display:none;" />';
						html += '<input class="toggleComment bEnableComment" type="button" value="Enable" style="display:none;" />';
						html += '<input class="toggleComment bDisableComment" type="button" value="Disable" style="display:none;" />';
						html += '</div>';
						$('div.commentList div.comment').each(function(i){
							$(this).append(html);
							if($('div.body', this).hasClass('enabled')){
								$('input.bDisableComment', this).show();
							}else{
								$('input.bEnableComment', this).show();
							}
							return true;
						});
						
						$('div.commentList div.comment input.toggleComment').click(function(){
							var commentDiv = $(this).parent().parent();
							var commentId = String(commentDiv.attr('id')).split('_')[1];
							$.ajax({
								url:rpcURL,
								type:'POST',
								data:{action:'toggleComment',id:commentId},
								dataType:'text',
								success:function(data){
									if(data=='true'){
										$('div.body', commentDiv).removeClass('disabled');
										$('div.body', commentDiv).addClass('enabled');
										$('input.bEnableComment', commentDiv).hide();
										$('input.bDisableComment', commentDiv).show();
									}else{
										$('div.body', commentDiv).removeClass('enabled');
										$('div.body', commentDiv).addClass('disabled');
										$('input.bEnableComment', commentDiv).show();
										$('input.bDisableComment', commentDiv).hide();
									}
								}
							});
							return false;
						});
						
						$('div.commentList div.comment input.bEditComment').click(function(){
							var commentDiv = $(this).parent().parent();
							$('input.toggleComment',commentDiv).hide();
							$('input.bEditComment',commentDiv).hide();
							$('input.bSaveComment',commentDiv).show();
							$('input.bCancelComment',commentDiv).show();
							var text = $('div.body',commentDiv).html();
							$('div.body',commentDiv).html(text.replace(/<br>/g,'\r\n'));
							$('div.body',commentDiv).wrapInner('<textarea></textarea>');
							return false;
						});
						
						$('div.commentList div.comment input.bCancelComment').click(function(){
							var commentDiv = $(this).parent().parent();
							if($('div.body',commentDiv).hasClass('enabled')){
								$('input.bDisableComment',commentDiv).show();
							}else{
								$('input.bEnableComment',commentDiv).show();
							}
							$('input.bEditComment',commentDiv).show();
							$('input.bSaveComment',commentDiv).hide();
							$('input.bCancelComment',commentDiv).hide();
							var text = $('textarea',commentDiv).val();
							$('div.body',commentDiv).html(text.replace(/\n/g,'<br />'));
							return false;
						});
						$('div.commentList div.comment input.bSaveComment').click(function(){
							var commentDiv = $(this).parent().parent();
							var commentId = String(commentDiv.attr('id')).split('_')[1];
							if($('div.body',commentDiv).hasClass('enabled')){
								$('input.bDisableComment',commentDiv).show();
							}else{
								$('input.bEnableComment',commentDiv).show();
							}
							$('input.bEditComment',commentDiv).show();
							$('input.bSaveComment',commentDiv).hide();
							$('input.bCancelComment',commentDiv).hide();
							var text = $('textarea',commentDiv).val();
							$.ajax({
								url:rpcURL,
								type:'POST',
								data:{action:'saveComment',id:commentId,text:$('textarea', commentDiv).val()},
								dataType:'text',
								success:function(data){
									$('div.body', commentDiv).html(String(data).replace(/\n/g,'<br />'));
								}
							});
							return false;
						});
					}
				}
		});
		
		$('a.bAddComment').click(function(){
			scrollTo(0,100000);
			return false;
		});
		
		$("#add_comment").validate({
		  submitHandler: function(form) {
			$(form).ajaxSubmit({
				success:addCommentResult,
				clearForm:true
			})
		  },
			rules: {
				name: {
					required: true,
					minlength: 2
				},
				place: {
					required: true,
					minlength: 1
				},  			
				email: {
					required: true,
					email: true
				},
				comment: {
					required: true,
					maxlength: 1000
				}  			
			},
			messages: {
				name: {
					required: "Please enter your name",
					minlength: "Please enter something longer than 2 letters"
				},
				place: {
					required: "Please enter a city/country",
					minlength: "Please enter something longer than 1 letters"
				},
				email: {
					required: "Please enter your email",
					email: "Please enter a valid Email (eg. joe.bloggs@gmail.com)"
				},
				comment: {
					required: "Please enter your comment",
					maxlength: "Please enter something less than 1000 letters"
				}
			}
		});
	}
}

function addCommentResult(result){
}

function drawVideoPopup(){
	if($('#videoBrowser').length==0){
		var popup = $('<div></div>');
		popup.attr('id','videoBrowser');
		var html = '';
		html += '<div class="admin_bar">';
		html += '<h2>Album Selection</h2>';
		html += '<div class="content">';
		html += '<div class="input albumSelect">';
		html += '<label>Album:</label><select id="iAlbumSelect"></select>';
		html += '</div>';
		html += '<div class="input actions">';
		html += '<input type="button" class="bClosePopup" value="Close" />';
		html += '</div>';
		html += '<div style="clear:both;"></div>';
		html += '</div>';
		html += '</div>';
		html += '<div id="videoList">';
		html += '</div>';
		popup.html(html);
		
		popup.dialog({
			modal:true,
			width:700,
			height:580
		});
		$('#videoBrowser input.bClosePopup').click(function(){
			$('#videoBrowser').dialog('close');
		});
		$.ajax({
			url:rpcURL,
			type:'POST',
			data:{action:'getAlbums'},
			dataType:'json',
			success:function(data){
				drawAlbums(data);
			}
		});
	}else{
		$('#videoBrowser').dialog('open');
	}
	return false;
}

function drawAlbums(data){
	var html = '';
	for(var i=0;i<data.length;i++){
		html += '<option value="'+data[i].id+'">'+data[i].description+'</option>';
	}
	$('#iAlbumSelect').html(html);
	$('#iAlbumSelect').change(function(){
		$('#videoList').html(drawPreloader('PrlPopup'));
		$.ajax({
			url:rpcURL,
			type:'POST',
			data:{action:'getVideos',album:$(this).val()},
			dataType:'json',
			success:function(data){
				drawVideos(data);
			}
		});
	});
	$('#iAlbumSelect').triggerHandler('change');
}

function drawVideos(data){
	var html = '';
	for(var i=0;i<data.length;i++){
		html += '<a class="videoThumb" id="video_'+data[i].id+'" href="">';
		html += '<h3>'+data[i].title+'</h3>';
		html += '<img src="'+data[i].thumbnail_medium+'" alt="'+data[i].description+'" />';
		html += '</a>';
	}
	$('#videoList').html(html);
	$('a.videoThumb').click(function(){
		var id = String($(this).attr('id')).split('_')[1];
		$('div.videoPlayer input').val(id);
		drawVideoPlayer();
		$('#videoBrowser').dialog('close');
		return false;
	});
}

function getLectures(){
	$.ajax({
			url:rpcURL,
			type:'POST',
			data:{action:'getLectures'},
			dataType:'json',
			success:function(data){
				html = '';
				for(var i=0;i<data.output.length;i++){
					var lecture = data.output[i];
					html += drawLectureTop(lecture.id,lecture.active,lecture.name,lecture.speaker,lecture.date);
				}
				if(data.output.length==0 && data.editMode){
					html += drawLectureTop(0,false,'','','');
				}
				$('#speakers_top').html(html);
				if(data.editMode){
					$('#speakers_top a').each(function(i){
						var date = $('small.date', this).text();
						if(date!='') $(this).attr('timestamp',Date.parse(date));
						return true;
					});
				}
				arrangeLectures();
				
				getData();
			}
	});
}

function bLectureBind(){
	if(!$(this).hasClass('current')){
		if($('a.bAddLecture').length==1){
			saveData($(this));
		}else{
			getData($(this));
		}
	}
	return false;
}

function arrangeLectures(){
	var fullWidth = $('#speakers_top').width();
	boxCount = $('#speakers_top a').length;
	if(boxCount>0){
		var minWidth = Math.floor(fullWidth / boxCount);
		var maxWidth = minWidth + (fullWidth - (minWidth * boxCount));
	}else{
		var minWidth = 0;
		var maxWidth = 0;
	}
	$('#speakers_top a').css('width',minWidth+'px');
	$('#speakers_top a:eq('+(boxCount-1)+')').css('width',maxWidth+'px');
	$('#speakers_top a').show();
	$('#speakers_top a').unbind('click');
	$('#speakers_top a').click(bLectureBind);
}

function sortLectures(){
	var tmpArr = new Array();
	$('#speakers_top a').each(function(i){
		tmpArr.push($(this));
		return true;
	});
	tmpArr.sort(function(a,b){
		return a.attr('timestamp') - b.attr('timestamp');
	});
	$('#speakers_top').empty();
	for(var i=0;i<tmpArr.length;i++){
		$('#speakers_top').append(tmpArr[i]);
	}
	$('#speakers_top a').click(bLectureBind);
}

function saveData(speaker){
	$('#edit_lecture').ajaxSubmit({
		url:$('#edit_lecture').attr('action')+'?rpc',
		success:function(result){
			$('#speakers_top a.current').attr('id','spk_'+result);
			getData(speaker);
		}
	});
}

function getData(speaker){
	if(speaker==undefined){
		speaker = $('#speakers_top a:first');
	}
	speakerId = String(speaker.attr('id')).split('_')[1];
	$('#speakers_top a').removeClass('current');
	clearTinyMCE();
	$('#speakers_bottom').html(drawPreloader());
	$.ajax({
		url:rpcURL,
		type:'POST',
		data:{action:'getData',id:((speakerId!=undefined)?speakerId:0)},
		dataType:'json',
		success:function(data){
			speaker.addClass('current');
			drawData(data);
		}
	});
}

$(document).ready(function(){
	$('#lectureBrowser select').change(function(){
		if($('option:selected',this).val()!=''){
			window.location.href = '../'+$('option:selected',this).val();
		}
	});
	
	$('a.bAddLecture').click(function(){
		$('#speakers_top').append(drawLectureTop(0,false,'','',''));
		arrangeLectures();
		return false;
	});
	
	getLectures();

    Shadowbox.init({
        loadingImage:'/img/loadingW.gif',
        resizeLgImages:true,
        handleUnsupported:'remove',
        keysClose:['c', 27], // c or esc
        autoplayMovies:false
    });
	
	$('#edit_lecture input:submit').click(function(){
		var buttonPressed = $(this);
		if(buttonPressed.val()=='Delete'){
			if(confirm('Are you sure you want to delete this series of lectures?\r\n\r\nPress OK to Delete\r\nPress Cancel to return to the editor')){
				buttonPressed.unbind('click');
				buttonPressed.click();
			}
		}else{
			$.ajax({
				url:rpcURL,
				type:'POST',
				data:{action:'checkSlug',slug:$('#edit_lecture div.slug input').val()},
				dataType:'text',
				success:function(data){
					if(data=='true'){
						buttonPressed.unbind('click');
						buttonPressed.click();
					}else{
						alert('This URL is already in use. Please choose another one.');
						$('#edit_lecture div.slug input').val(data);
					}
				}
			});
		}
		return false;
	});
});
