document.observe('dom:loaded', function() {
	
	/**
	* Makes word wrapping work correctly on all elements with class "word-wrap".
	* Elements with class "word-wrap" must contain only text.
	* @param none.
	* @return {string} contains breaks in appropriate places to simulate word-wrapping
	*/
	function wordwrap(str,int_width,str_break,cut) { 
    var m = ((arguments.length >= 2) ? arguments[1] : 75);
    var b = ((arguments.length >= 3) ? arguments[2] : "\n");
    var c = ((arguments.length >= 4) ? arguments[3] : false); 
    var i, j, l, s, r; 
    str += ''; 
    if (m < 1) {
    	return str;
    } 
    for (i = -1, l = (r = str.split(/\r\n|\n|\r/)).length; ++i < l; r[i] += s) {
    	for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
      	j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    	}
    }    
    return r.join("\n");
	}
	
	/**
	* Truncates file names at 16 characters and replaces the rest with an ellipsis.
	* File names must be in a container with class "truncate".
	* @param none.
	* @return {void} file name has been truncated to fit in its container element. 
	*/
	var truncateFileNames = function() {
		var fileNameElements = $$('.truncate');
		var newString;
		fileNameElements.each(
			function(el, index) {
				el.style.fontSize = '8pt';
				if (el.innerHTML.length > 13) {
					newString = el.innerHTML.substr(0, 13);
					el.innerHTML = newString + '...';
				}
			}
		)
	}
	
	/**
	* Resizes (if nesscessary) the thumbnail image of each file.
	* Images must be assigned the class "file-thumb".
	* @param none.
	* @return {void} all file thumbnails have been resized to fit. 
	*/
	var fixThumbs = function() {
		var thumbs = $$('.file-thumb');
		thumbs.each(
			function(el, index) {
				if (el.getWidth() > 100) {
					el.style.width = '100px';
				}
				el.style.height = '64px';
				el.style.marginTop = 0;
			}
		)
	}
	
	//get query string; if any sorting has occurred, highlight the table cell with the requested sorting
	var cells = $('sort-row').childElements();
	var activeIndex = 0;
	if (window.location.search.substring(1) != '') {
		var queryString = window.location.search.substring(1);
		var temp = queryString.split('=',2);
		activeIndex = parseInt(temp[1]);		
	}
	for (var i = 0; i < cells.length; i++) {
		if (i == activeIndex) {
			cells[i].className = 'active-cell';
			cells[i].style.borderTop = '1px solid #96d9f9';
		}
	}
	
	//highlight sorting cell onmouseover and make them link to correct place
	var cells = $('sort-row').childElements();
	var baseClass;
	cells.each(
		function(el, index) {
			el.observe('mouseover',
				function() {
					el.addClassName('hover-cell');
				}
			)	
		}	
	)
	cells.each(
		function(el, index) {
			el.observe('mouseout',
				function() {
					el.removeClassName('hover-cell');
				}
			)	
		}	
	)
	cells.each(
		function(el, index) {
			el.observe('click',
				function() {
					document.location = '?sort=' + index;
				}
			)
		}
	)
	
	//highlight file onmouseover
	var files = $$('.file');
	files.each(
		function(el, index) {
			el.observe('mouseover',
				function() {
					el.addClassName('hover-file');
				}
			)	
		}	
	)
	files.each(
		function(el, index) {
			el.observe('mouseout',
				function() {
					el.removeClassName('hover-file');
				}
			)	
		}	
	)
	
	//call wordwrap for all elements with class word-wrap
	var theStrings = $$('.word-wrap');
	theStrings.each (
		function(el, i) {
			el.innerHTML = wordwrap(el.innerHTML, 11, '\n', true);
		}
	)
	
	//truncate file names
	truncateFileNames();
	
	fixThumbs();
	
	//enable/disable comments	
		//must be inside a dom:loaded event
	modComments = Class.create({
		initialize: function(containerId, subjectId, loggedInUserId, loggedInUserPic, isOwner) {			
			that = this;
			this.container = $(containerId);
			this.subjectId = subjectId;
			this.loggedInUserId = loggedInUserId;
			this.loggedInUserPic = loggedInUserPic;
			this.isOwner = isOwner;
			this.count = 0;
			
			//check if comments are allowed
			var parameters = '["' + this.subjectId + '"]';
			callStringMethod(
					'doesAllowComments',
					parameters,
					function (response) { //success
						if (typeof response[0] == 'string') {
							that.container.update('<span class="info-message-small">'+response[0]+'</span>');
						} else {
							that.allowComments = response[0];			
							that.get();	
						}
					},
					function(error) { //error
						that.commentsBody.update('<span class="info-message-small">'+error+'</span>');
					},
					function() { //create
						
					}
			)
			
			
		
		},
		get: function() {
			that = this;
			this.commentsHeader = new Element('div', { id: 'comments-header' });
			this.commentsHeaderText = new Element('span').update('Comments <span id="comment-count">('+this.count+')</span>');			
			this.commentsBody = new Element('div', { id: 'comments-body' });
	
			this.commentsHeader.appendChild(this.commentsHeaderText);
			this.container.appendChild(this.commentsHeader);
			this.container.appendChild(this.commentsBody);
			
			//allow comments toggle
			if (this.isOwner) {
				allowCommentsContainer = new Element('span', { id: 'allow-comments-container' });
				allowCommentsLabel = new Element('label', { 'for': 'allow-comments' }).update('Allow new comments?');
				this.allowCommentsToggle = new Element('input', { 'type': 'checkbox', 'name': 'allow-comments', id: 'allow-comments', 'value': 'true' });
				if (this.allowComments) this.allowCommentsToggle.checked = 'checked';
				allowCommentsContainer.appendChild(this.allowCommentsToggle);
				allowCommentsContainer.appendChild(allowCommentsLabel);
				this.commentsHeader.appendChild(allowCommentsContainer);
				
				allowCommentsLabel.observe('click', function() {
					that.updateAllowComments();
				});
				that.allowCommentsToggle.observe('click', function() {
					that.updateAllowComments();
				});
			}
						
			this.commentsHeaderText.observe('click', function() {
				Effect.toggle(that.commentsBody, 'blind', { duration: 0.5 });
				if (that.commentsBody.style.display == 'none') {
					that.commentsHeader.removeClassName('comments-collapsed');
				} else {
					that.commentsHeader.addClassName('comments-collapsed');
				}
			});
			
			var parameters = '["' + this.subjectId + '"]';
			callStringMethod(
					'getComments',
					parameters,
					function (response) { //success
						if (typeof response[0] == 'string') {
							that.commentsBody.update('<span class="info-message-small">'+response[0]+'</span>');
						} else {
							that.build(response[0]);
						}
					},
					function(error) { //error
						that.commentsBody.update('<span class="info-message-small">'+error+'</span>');
					},
					function() { //create
						
					}
			)
		},
		build: function(data) {
			that = this;
			this.data = data;
			if (this.data.length > 0) {				
				this.data.each(function(el, i) {
					that.add(el.id, el.commenter_id, el.commenter, el.date, el.comment, el.commenterProfVol);
				});
			}
			
			if (this.allowComments) {
				this.commentsForm = new Element('div', { 'id': 'new-comment', 'class': 'comment-row' });
				this.newCommentLeft = new Element('div', { 'class': 'comment-left' });
				this.newCommentRight = new Element('div', { 'class': 'comment-right' });
				this.commentsForm.appendChild(this.newCommentLeft);
				this.commentsForm.appendChild(this.newCommentRight);
				
				if (this.loggedInUserId == null || this.loggedInUserPic.length == 0) {
					this.commenterAvatar = new Element('img', { 'src' : '/images/face5.png', 'alt': '', 'class': 'comment-avatar' });	
				} else {
					this.commenterAvatar = new Element('img', { 'src' : '/dyn/pic/'+this.loggedInUserId+'m/'+this.loggedInUserPic, 'alt': 'This is you', 'class': 'comment-avatar' });
				}
				
				this.newCommentLeft.appendChild(this.commenterAvatar);
				this.newCommentLeft;
				
				this.commentsFormBody = new Element('textarea', { 'class': 'comment-textarea blurred', 'maxlength': '255' }).update('Leave a comment...');			
				this.commentsFormSubmit = new Element('button', { 'class': 'comment-submit' }).update('Comment');
				
				this.newCommentRight.appendChild(this.commentsFormBody);
				this.newCommentRight.appendChild(this.commentsFormSubmit);
				
				this.container.appendChild(this.commentsForm);
				this.commentsForm.appendChild(this.newCommentLeft);
				this.commentsForm.appendChild(this.newCommentRight);
				this.commentsForm.appendChild(new Element('div', { 'class': 'clear' }));
				
				this.commentsFormBody.observe('focus', function() {
					if (this.value == 'Leave a comment...') {
						this.value = '';
						this.removeClassName('blurred');
					}
				});
							
				this.commentsFormBody.observe('blur', function() {
					if (this.value.length == 0) {
						this.addClassName('blurred');
						this.value = 'Leave a comment...';
					}
				});
				
				this.commentsFormSubmit.observe('click', function() {
					that.submitComment();
				});
			}
		},
		add: function (theId, commenter_id, theCommenter, theDate, comment, profVol) {
			that = this;
			
			this.count++;
			$('comment-count').update('('+this.count+')');
			//containers
			row = new Element('div', { 'id': theId, 'class': 'comment-row' });
			leftSide = new Element('div', { 'class': 'comment-left' });
			rightSide = new Element('div', { 'class': 'comment-right' });
			row.appendChild(leftSide);
			row.appendChild(rightSide);
			//commenter avatar			
			if (commenter_id == 'anonymous' || commenter_id == 'deleted') {
				commenterAvatar = new Element('img', { 'src' : '/images/face5.png', 'alt': '', 'class': 'comment-avatar' });
				leftSide.appendChild(commenterAvatar);
			} else if (profVol == null) {
				commenterAvatar = new Element('img', { 'src' : '/images/face5.png', 'alt': theCommenter, 'class': 'comment-avatar' });
				anchor = new Element('a', { 'href': '/dyn/prof/'+commenter_id, 'title': theCommenter });
				anchor.appendChild(commenterAvatar);
				leftSide.appendChild(anchor);
			} else {
				commenterAvatar = new Element('img', { 'src' : '/dyn/pic/'+commenter_id+'m/'+profVol, 'alt': theCommenter, 'class': 'comment-avatar' });
				anchor = new Element('a', { 'href': '/dyn/prof/'+commenter_id, 'title': theCommenter });
				anchor.appendChild(commenterAvatar);
				leftSide.appendChild(anchor);
			}
			//name
			nameContainer = new Element('div', { 'class': 'commenter' });
			if (commenter_id == 'anonymous' || commenter_id == 'deleted') {
				nameContainer.update(commenter_id);
			} else {				
				nameAnchor = new Element('a', { 'href': '/dyn/prof/'+commenter_id, 'title': theCommenter }).update(theCommenter);
				nameContainer.appendChild(nameAnchor);
			}
			rightSide.appendChild(nameContainer);
			//entry
			entry = new Element('div', { 'class': 'comment-entry' }).update(comment);
			rightSide.appendChild(entry);
			//entry date
			entryDate = new Element('div', { 'class': 'entry-date' }).update(getFormattedDate(theDate));
			//entryDate = new Element('div', { 'class': 'entry-date' });
			rightSide.appendChild(entryDate);
			//clear row
			row.appendChild(new Element('div', { 'class': 'clear' }));
			this.commentsBody.appendChild(row);
			
			//delete comment
			if (this.isOwner) {
				deleteEntry = new Element('a', { 'href': 'javascript:void(0)', 'class': 'delete-entry' }).update('Delete');
				entryDate.appendChild(deleteEntry);
				deleteEntry.observe('click', function() {
					var proceed = confirm("Are you sure you want to delete this comment?");
					if (proceed) {
						parameters = '["' + theId + '"]';
						callStringMethod(
							'deleteComment',
							parameters,
							function (response) { //success
								if (typeof response[0] == 'string' && response[0] != 'Success') {
									alert(response[0]);
								} else {
									Effect.Fade($(theId), { duration: 0.5 });
								}
							},
							function(error) { //error
								alert(error);
							},
							function() { //create
							}
						);
					}	
				});
			}
		},
		remove: function() {
			
		},
		submitComment: function() {
			that = this;
			strComment = addSlashes(this.commentsFormBody.value);
			parameters = '["' + this.subjectId + '","' + strComment + '"]';
			callStringMethod(
					'addComment',
					parameters,
					function (response) { //success
						if (typeof response[0] == 'string') {
							alert(response[0]);
							that.commentsFormSubmit.disabled = false;
							that.commentsFormBody.disabled = false;
						} else {
							that.add(response[0].id, response[0].commenter_id, response[0].commenter, response[0].date, response[0].comment, response[0].commenterProfVol);
							that.commentsFormBody.addClassName('blurred');
							that.commentsFormBody.value = 'Leave a comment...';
							setTimeout(function() {
								that.commentsFormBody.disabled = false;
								that.commentsFormSubmit.disabled = false;
							}, 1000);
						}
					},
					function(error) { //error
						alert(error);
						that.commentsFormSubmit.disabled = false;
						that.commentsFormBody.disabled = false;
					},
					function() { //create
						that.commentsFormSubmit.disabled = true;
						that.commentsFormBody.disabled = true;
					}
			);
		},
		updateAllowComments: function() {
			that = this;			
			parameters = '["' + this.subjectId + '",' + this.allowCommentsToggle.checked + ']';
			callStringMethod(
					'setAllowComments',
					parameters,
					function (response) { //success
						if (typeof response[0] == 'string' && response[0] != 'Success') {
							alert(response[0]);
						} else {
							if (that.allowCommentsToggle.checked) {
								window.location.reload();
							} else {
								Effect.BlindUp($('new-comment'), { duration: 0.5 });
							}
						}
					},
					function(error) { //error
						alert(error);
					},
					function() { //create
					}
			);	
		}
	});
	var comments = new modComments('comments', subjectId, loggedInUserId, loggedInUserPic, isOwner);
	
});
