var objHtmlBox;
var uploadID;
var isAdmin = false;
var save_tool = {
	icon:"save.gif",
	tooltop:"Save the feedback",
	command: function(){uploadResponse(objHtmlBox.get_html());}
};

function uploadResponse(strData) {
	$.ajax({
		url: '/vle/assignments/feedback.asp',
		dataType: 'html',
		type: 'POST',
		data: { u: uploadID, fb: strData },
		success: function(data){
			if (data === 'success') {
				alert("Your feedback has been receved and saved.");
				$('#responseContainer').dialog('close');
			} else {
				alert("There was a problem saving your feedback, please try again.");
			}
		}
	});
}
$(document).ready(function () {
	
	$('#editPupilPage').live('click', function(e){
		$("#pupilPageInfo").unbind('edit-postSet.e4e').bind('edit-postSet.e4e',function() {
			strPostURL = "/vle/savePupilPage.asp";
			aryPostData = "itemTitle="+escape($('h1.cms-title').text())+"&itemContent="+escape($('#pupilPageInfo').html())+"&intReviewerID="+$('#intReviewerID').text()+"&intPageParentID="+$('#intPageParentID').text()+"&intItemID="+$('#intItemID').text()+"&pageStyleSheet="+escape($('#pageStyleSheet').text())+"&commentsOn="+$('#commentsOn').text();
			$.e4eLoaderScreen.show("Sending your page for approval", undefined, undefined, true);
			$.e4eLoaderScreen.setProgress(50);
			$.ajax({
				url: strPostURL,
				data: aryPostData,
				type: 'POST',
				dataType: 'json',
				success: function (data) {
					$.e4eLoaderScreen.setProgress(100);
					window.location.reload();
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					var errorMessage = 'Sorry, there was a problem saving this item. <br />Please close this message and try again.';
					$.e4eLoaderScreen.setProgress('error', errorMessage);
				}
			});
			$.e4eLoaderScreen.hide();
		});
		var strPupilPageHTML = $('#pupilPageInfo').clone();
		$('.vle-clearer',strPupilPageHTML).remove();
		$(strPupilPageHTML).e4eDialog({
			diagTitle: 'Edit page',
			bind: false,
			editor: true,
			resizeable: false,
			sourceID: '#pupilPageInfo',
			toolBarSet: 'VLEPupil'
		});
	});
	$('#editPupilDraftPage').live('click', function(e){
		strPostURL = "/vle/getPupilDraftPage.asp";
		aryPostData = "intItemID="+$('#intItemID').text();
		$.ajax({
			url: strPostURL,
			data: aryPostData,
			type: 'POST',
			dataType: 'html',
			success: function (retdata) {
				$("#pupilPageInfo").html(retdata);
				$("#pupilPageInfo").unbind('edit-postSet.e4e').bind('edit-postSet.e4e',function() {
					strPostURL = "/vle/savePupilDraftPage.asp";
					aryPostData = "itemTitle="+escape($('h1.cms-title').text())+"&itemContent="+escape($('#pupilPageInfo').html())+"&intReviewerID="+$('#intReviewerID').text()+"&intPageParentID="+$('#intPageParentID').text()+"&intItemID="+$('#intItemID').text()+"&intItemLiveID="+$('#intItemLiveID').text()+"&pageStyleSheet="+escape($('#pageStyleSheet').text())+"&commentsOn="+$('#commentsOn').text();
					$.e4eLoaderScreen.show("Sending your page for approval", undefined, undefined, true);
					$.e4eLoaderScreen.setProgress(50);
					$.ajax({
						url: strPostURL,
						data: aryPostData,
						type: 'POST',
						dataType: 'html',
						success: function (retdata) {
							$.e4eLoaderScreen.setProgress(100);
							window.location.reload();
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							var errorMessage = 'Sorry, there was a problem saving this item. <br />Please close this message and try again.';
							$.e4eLoaderScreen.setProgress('error', errorMessage);
						}
					});
				});
				var strPupilPageHTML = $('#pupilPageInfo').clone();
				$('.vle-clearer',strPupilPageHTML).remove();
				$(strPupilPageHTML).e4eDialog({
					diagTitle: 'Edit Draft Page',
					bind: false,
					editor: true,
					resizeable: false,
					sourceID: '#pupilPageInfo',
					toolBarSet: 'VLEPupil'
				});
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert('Sorry, there was a problem getting the contents of your draft page, please close this message and try again.');
			}
		});
	});
	$('#deletePupilDraftPage').live('click', function(e){
		var blnConfirm = confirm("Are you sure you wish to delete this draft?");
		if (blnConfirm) {
			strPostURL = "/vle/deletePupilDraftPage.asp";
			aryPostData = "intItemID="+$('#intItemID').text();
			$.e4eLoaderScreen.show("Deleting your draft page", undefined, undefined, true);
			$.e4eLoaderScreen.setProgress(50);
			$.ajax({
				url: strPostURL,
				data: aryPostData,
				type: 'POST',
				dataType: 'json',
				success: function (data) {
					$.e4eLoaderScreen.setProgress(100);
					window.location.reload();
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					var errorMessage = 'Sorry, there was a problem deleting the item. <br />Please close this message and try again.';
					$.e4eLoaderScreen.setProgress('error', errorMessage);
				}
			});
		}
	});
	$('.pupil-avatar-container').hover(function () {
		$('a.change-student-avatar', this).stop(true, true).fadeIn(300);
	}, function () {
		$('a.change-student-avatar:not(.clicked)', this).stop(true,true).fadeOut(300);
	});
	$('a.change-student-avatar').click(function (e) {e.preventDefault();}).focus(function (e) {
		e.preventDefault();
		$(this).addClass('clicked');
		$('.available-avatars-container').remove();
		var c = $('<div class="available-avatars-container" />'),
			ic = $('<div class="available-avatars" />'),
			a = $('<div class="available-avatars-arrow" />'),
			self = this;
		ic.addClass('loading')
		c.append(a).append(ic).appendTo('body').css({
			'top' : $(this).offset().top + $(this).outerHeight(true) - $(a).outerHeight(true) * 0.5 - 2,
			'left' : ($(this).offset().left + $(this).outerWidth(true) * 0.5) - c.outerWidth(true) * 0.5
		});
		$.ajax({
			url:'/admin/vle/avatar.list.json.asp',
			dataType:'json',
			success:function (data) {
				ic.removeClass('loading');
				if($.type(data.avatars) == 'array' && data.avatars.length > 0) {
					for(var i = 0; i < data.avatars.length; i++) {
						ic.append('<div class="available-avatar"><img src="/vle/_includes/images/avatars/' + data.avatars[i] + '" alt="" /><a href="#" class="select-avatar-link">Select this</a></div>')
					}
					ic.width($('.available-avatar:first').outerWidth(true) * (data.avatars.length + 1));
					c.animate({'width' : ic.outerWidth(true), 'left' : ($(self).offset().left + $(self).outerWidth(true) * 0.5) - ic.outerWidth(true) * 0.5})
					$('.available-avatar').click(function (e) {
						e.preventDefault()
						if(!$(this).hasClass('selected')) {
							var newSrc = $(this).find('img').attr('src');
							$('.pupil-avatar-container img').attr('src', newSrc);
							$.ajax({
								url:'/admin/vle/avatar.set.json.asp',
								data : {'image' : newSrc}
							});
							
						}
					})
				}
			}
		})
	}).blur(function () {
		setTimeout(function () {
			$('.available-avatars-container').remove();
			$('a.change-student-avatar').removeClass('clicked').stop(true,true).fadeOut(300);
		}, 200)
		
	})
	$('#assignmentsUploadsContainer a#btnContainer').click(function (e) {
		e.preventDefault();
		SWFUploadObject.cancelQueue();
	})
	
	$('.assignmentList li').each(function () {
		$(this).not(':contains("View Response")').append('<div class="delete-submission-container"><a href="#" class="delete-submission"><span>Delete</span></a></div>');
		if($(this).index() %2 == 0) $(this).addClass('odd');
	}).find('a.delete-submission').click(function (e) {
		e.preventDefault();
		$(this).hide();
		var con = $(this).parent();
		con.append('<p>are you sure you want to delete this?</p><a href="#" class="cancel-delete-sbumission">No</a><a href="#" class="confirm-delete-sbumission">Yes</a>').addClass('confirm-delete');
		$('.confirm-delete-sbumission', con).click(function (e) {
			e.preventDefault();
			con.closest('li').slideUp(300);
			var submissionLink = con.closest('li').find('a:first').attr('href');
			$.ajax({
				url:'/admin/vle/submission.remove.json.asp',
				data : {
					submissionID : submissionLink.substr(submissionLink.indexOf('submissionID=') + 13),
					pid : intCurrentItemID
				},
				success : function () {
					con.remove();
				}
				
			});
		});
		$('.cancel-delete-sbumission', con).click(function (e) {
			e.preventDefault();
			con.find('>*:not(.delete-submission)').fadeOut(200, function () {
				$(this).remove();
				$('.delete-submission', con).show();
				con.removeClass('confirm-delete')
			});
		});
	})
	$('#pupilHomeworkContainer li, #classNewsContainer li, #schoolNewsContainer li, #classHomeworkContainer li').each(function () {
		if($(this).index() %2 == 0) $(this).addClass('odd');
	})
	$('.ajaxLoadResponse').live('click',function(event){
		event.preventDefault();
		$this = $(this);
		var strHref = $this.attr("href");
		if($this.closest('li').next('li').hasClass('response-holder')) {
			if($this.hasClass('open')) {
				$this.closest('li').next('li.response-holder').slideUp(300);
				$this.removeClass('open');
				$this.text('View Response');
			} else {
				$this.closest('li').next('li.response-holder').slideDown(300);
				$this.addClass('open');
				$this.text('Hide Response');
			}
			
		} else {
			if (strHref != '') {
				uploadID = $this.attr("rel");
				$.ajax({
					url: strHref,
					dataType: 'html',
					success: function(data){
						var response = $('<li class="response-holder ' + ($this.closest('li').hasClass('odd') ? 'odd' : '') + '">' + data + '</li>');
						$this.closest('li').after(response);
						$this.addClass('open');
						$this.text('Hide Response');
						response.slideDown(300);
						if (isAdmin) {
							objHtmlBox = $("#responseContainer", response).htmlbox({
								skin: "orange",
								about: false,
								idir: "/vle/_includes/js/htmlbox/images/",
								toolbars:[
									[save_tool,"separator","bold","italic","underline"]
								]
							});
						}
					},
					error: function(){				
						alert('There was a problem retrieving the teachers response, please try again.');
					}
				});
			}
		}
		
	});
});
