fw.Libs.load([
	'http://link.members.freewebs.com/JS/checkLogin.jsp',
	'http://images.freewebs.com/JS/mootools.js',
	'http://images.freewebs.com/JS/bbBox.js',
	'http://images.freewebs.com/JS/fwPaging.js'
]);

/* Comment Posting System */
var fwComments = new Class({
	ii: 0,
	type: 'fwComments',
	initialize: function(containerID, listID, userID, options){
		if(fw.Instances.get(containerID)) return;
		this.userIsOwner = (userID == fwuser.id);
		this.containerID = containerID;
		this.listID = listID;
		this.userID = userID;
		this.options = {
			page: 1,
			width: 450,
			limit: 10,
			startHidden: false,
			startPostClosed:true,
			duration: 0,
			hideAfterPost: true,
			showRatings: false,
			showDate:false,
			showIP:false,
			showEmail:false,
			alignNavRight:false,
			draw: true,
			onLoad: null,
			disablePost: false,
			showLogin: true,
			showPostHide: true,
			showHideLink: true,
			postText: 'Post a Comment',
			commentCountText: '',
			showLowerPaging: false,
			parent: null,
			isGuestbook: false,
			isEditable: false,
			requireLogin: false
		}
		Object.extend(this.options, options || {});
		
		var loc = (location.href+'');
		if(loc.indexOf('freewebs.com')>-1 && loc.indexOf('EditPage')>-1){
			this.options.isEditable = true;
		}
		
		if(!this.options.showPostHide)
			this.options.showRatings = false;

		if(this.options.requireLogin && !this.options.disablePost && !fwuser.loggedIn){
			this.options.disablePost = 'Please <a href="http://link.members.freewebs.com/relogin.jsp?ownerID=' + this.userID + '&amp;next=' + escape(window.location) + '">log in</a> to post.';
		}
		
		if(this.options.isGuestbook)
			this.options.showEmail = true;
		
		this.prepare();
		if(this.options.draw)
			this.draw();
		this.instance = fw.Instances.add(this);
	},
	prepare: function(){
		id = this.containerID;
		this.pageNumbers = new fwPaging(id+'nav', {write:false, breaks:5, selectedPageStyle:'font-size:1.2em; font-weight:bold;'});
		if(this.options.showLowerPaging)
			this.lowerPageNumbers = new fwPaging(id+'lnav', {write:false, breaks:5, selectedPageStyle:'font-size:1.2em; font-weight:bold;'});
		this.bbBox = new bbBox(id+'-post2',{
			showActionButtons: true,
			hideTabs: false,
			width: this.options.width,
			height: 130,
			style: true,
			showName: true,
			showLogin: fwuser.loggedIn ? true : this.options.showLogin,
			showEmail: this.options.showEmail,
			emailDesc: ' (Will be kept private)',
			onPost: function(){
				this.postComment();
			}.bind(this),
			onCancel: this.togglePostDivFx.bind(this),
			draw: false
		});
		
		this.hideCommentHTML = this.options.showHideLink ? '<img style="border:0; margin-right:2px; vertical-align:middle;" src="http://images.freewebs.com/Images/arrowRight.gif">Hide Comments' : '';
		this.showCommentHTML = '<img style="border:0; margin-right:2px; vertical-align:middle;" src="http://images.freewebs.com/Images/arrowDown.gif">Show Comments';

		this.HTML = ''
		+'<div class="fwComments" id="fwCom'+id+'" style="clear:both;">'
			+(this.options.showPostHide
				?'<div style="font-weight:bold; font-size:1.1em; padding-left:5px;">'
				+(!this.options.disablePost
					?'<a id="'+id+'-postLink" style="font-size:14px;" href=""><img style="border:0; margin-right:5px; vertical-align:middle;" src="http://images.freewebs.com/Images/tinyBubble.gif">'+this.options.postText+'</a>  '
					:this.options.postText+'&nbsp')
				+'<a id="'+id+'-comLink" href="" style="font-size:14px;">'
				+(this.options.startHidden
					?this.showCommentHTML
					:this.hideCommentHTML)
				+'</a>'
				+' (<span id="'+id+'-cCount" style="font-weight:bold;">-</span>'+this.options.commentCountText+')'
				+'</div>'
				+'<div id="'+id+'-post" style="margin-bottom:10px;">'+(this.options.disablePost ? this.options.disablePost : this.bbBox.HTML)+'</div>'
				: '<div>(<span id="'+id+'-cCount" style="font-weight:bold;">-</span>) Comments Total</div>')
			+'<div id="'+id+'-lowerDiv" '+(this.options.alignNavRight ? 'style="text-align:right;"' : '')+'>'
				+this.pageNumbers.HTML
				+'<div style="text-align:left; width:100%;" class="fwCommentsCom fw-even" id="'+id+'-com"></div>'
				+(this.options.showLowerPaging
					?this.lowerPageNumbers.HTML
					:'')
			+'</div>'
		+'</div>';
		fw.Css.load('http://images.freewebs.com/Styles/fwComments.css');
	},
	draw: function(){
		document.write(this.HTML);
		this.activate();
	},
	activate: function(){	
		//inject modded moofx for nodoctypes
		if(document.compatMode && document.compatMode == "BackCompat")
		Object.extend(fx.Height.prototype, {
			increase: function() {
				this.el = this.element || this.el;
				this.el.style.height = (this.now < 1 ? 1 : this.now) + "px";		
			},
			toggle: function() {
				this.el = this.element || this.el;
				if (this.el.offsetHeight > 1) this.custom(this.el.offsetHeight, 0);
				else this.custom(0, this.el.scrollHeight);
			}
		});
		
		id = this.containerID;
		this.container = $('fwCom'+id);
		this.navDiv = $(id+'-nav');
		this.lowerDiv = $(id+'-lowerDiv');
		this.cCount = $(id+'-cCount');
		this.commentDiv = $(id+'-com');
		
		if(this.options.showPostHide){
			this.postDiv = $(id+'-post');
			this.comLink = $(id+'-comLink');
			this.postDiv.style.marginLeft = '6px';
		}

		if(this.options.showPostHide){
			this.lowerDiv.fx = new fx.Height(this.lowerDiv, {duration:300, onComplete:function(){ if(this.lowerDiv.fx.now>0) this.lowerDiv.style.height='auto';    this.comLink.innerHTML = ( this.lowerDiv.fx.now>0 ? this.hideCommentHTML : this.showCommentHTML) }.bind(this)});
			this.postDiv.fx = new fx.Height(this.postDiv, {duration:300});
			this.postDiv.fade = new fx.Opacity(this.postDiv, {duration:300});
			this.comLink.onclick = function(){ this.lowerDiv.fx.toggle(); return false; }.bind(this);
		}
		this.pageNumbers.activate();
		this.pageNumbers.options.onClick = this.requestComments.bind(this);
		
		if(this.options.showLowerPaging){
			this.lowerPageNumbers.activate();
			this.lowerPageNumbers.options.onClick = this.requestComments.bind(this);
		}
		
		if(this.options.showPostHide && !this.options.disablePost){
			this.postLink = $(id+'-postLink');
			this.postLink.onclick =  function(){ this.togglePostDivFx(); return false; }.bind(this);
			this.bbBox.activate();
			if(this.options.startPostClosed){
				this.postDiv.fx.hide();
				this.postDiv.fade.custom(1, .5);
			}
		}
		
		if(this.options.startHidden && this.options.showPostHide){
			this.lowerDiv.fx.hide();
		}
		
		this.requestComments(this.options.page || 1);
	},
	togglePostDivFx: function(){
		this.postDiv.fx.toggle();
		if(this.postDiv.fade.now<=.9)
			this.postDiv.fade.custom(.5, 1)
		else
			this.postDiv.fade.custom(1, .5)
	},
	makeButtons: function(){
		this.pageNumbers.setPageCount(this.pageCount);
		this.pageNumbers.writePages();
		
		if(this.options.showLowerPaging){
			this.lowerPageNumbers.setPageCount(this.pageCount);
			this.lowerPageNumbers.writePages();
		}
	},
	postComment: function(){
		if(this.commentRequest)
			return alert('Please wait for us to finish processing.');
		if(!this.bbBox.getText())
			return alert('Please enter a message!');
		if(!this.bbBox.getName())
			return alert('Please enter your name!');
		this.bbBox.toggleProcessing();
		fw.jjax.req('http://link.members.freewebs.com/Members/Comments/postComment.jsp', {
			appendTo: this.postDiv,
			postBody: {
				userID: this.userID,
				commentSettingID: this.listID,
				name: this.bbBox.getName() || '',
				email: this.options.showEmail ? this.bbBox.getEmail() : '',
				body: escape(this.bbBox.getText()),
				next: 'callback',
				callback: 'fw.Instances.get("'+this.containerID+'").postCommentCallback',
				rand: Math.random()
			}});
	},
	postCommentCallback: function(error, errorMsg){
		this.bbBox.toggleProcessing();
		if(error)
			alert(errorMsg)
		else{
			if(this.options.hideAfterPost)
				this.togglePostDivFx();
			if(this.lowerDiv.fx.now==0)
				this.lowerDiv.fx.toggle();  
			this.requestComments(1);
			this.bbBox.setText('');
		}
	},
	setCommentCount: function(count){
		this.commentCount = count;
		this.cCount.innerHTML = count;
	},
	requestComments: function(page, message){
		if(this.commentRequest) return;
		this.Notify.show(message ? message : "Loading Messages...", true);
		this.commentRequest = true;
		this.page = page;
		this.pageNumbers.setPage(page);
		if(this.options.showLowerPaging)
			this.lowerPageNumbers.setPage(page);
		
		fw.jjax.req('http://link.members.freewebs.com/Members/Comments/listPagedCommentsJS.jsp', {
			appendTo: this.container,
			postBody: {
				userID: this.userID,
				limit: this.options.limit,
				pageNumber: page,
				commentSettingID: this.listID,
				callBack: 'fw.Instances.get("'+this.containerID+'").populateCommentDiv',
				loadRatings: this.options.showRatings,
				ratingCallback: 'fw.Instances.get("'+this.containerID+'").instance.parent.getRatingCallback',
				rand: Math.random(),
				repeatLimit: 40
			}});
	},
	populateCommentDiv: function(comments, commentCount){
		this.setCommentCount(commentCount);
		this.pageCount = Math.ceil(commentCount / this.options.limit);
		var oldComments = newComments = hideComments = [];
		var allNew = true;
		var cPrefix = this.containerID + '-c-';

		//get the IDs of all the current comments
		if(this.commentDiv.hasChildNodes()){
			allNew = false;
			$A(this.commentDiv.childNodes).each(function(n){
				if(comments.length < this.options.limit && this.page > 0)
					n.fx.toggle();
				else
					oldComments[n.id] = true;
			}.bind(this));
		} else if(this.options.onLoad){
			this.options.onLoad();
			if(commentCount==0){
				comments[0] = [this.listID, -1, '', 'There are no comments yet. Be the first to post!', '', '0']
			}
		}

		//get the IDs of the new comments (skip ones that are already present)
		$A(comments).each(function(comment){
			var c = this.newComment(comment);
			if(allNew || !oldComments[cPrefix + c.commentID]){
				oldComments[cPrefix + c.commentID] = null;
				newComments.push(c);
			}
		}.bind(this));
		
		//slide in the new comments
		var lastChild = null;
		var myDuration = this.options.duration;
		newComments.reverse().each(function(c){
			var div = document.createElement('div');
			div.id = cPrefix + c.commentID;
			
			var starRating = {};
			if(this.options.showRatings){
				if(c.rating)
					starRating = new fwStarRating(cPrefix+c.commentID+'-sr', {rating:c.rating, starsOnly:true, draw:false});
				else
					starRating.HTML = '<span style="font-size:.9em;">No&nbsp;Rating</span>';
			}
			else
				starRating.HTML = '';

			div.innerHTML = ''
			+'<table '+(!this.options.showDate ? 'title="posted '+c.time+'"' : '') + ' class="commentTable '+(this.ii++%2 ? 'fw-odd' : 'fw-even')+'"><tr>'
			+'<td><b>' + (c.name ? c.name+':' : '') + '</b> <br>' + c.message + '</td>'
			+(this.options.showRatings
				?'<td style="width:90px;">' + starRating.HTML + '</td>'
				:'')
			+(this.options.showDate || this.options.showIP
				?'<td style="width:100px;"><div class="fwComTimeStamp">'
					+(this.options.showDate
						?c.time.replace(' ', '&nbsp;') + '</div>'
						:'')
					+(this.options.showIP && c.IP
						?'<div class="fwComIP">'+c.IP+'</div>'
						:'')
					+'</td>'
				:'')
			+(this.userIsOwner && this.options.isEditable
				?'<td style="width:30px;" align="center"><a id="del-'+c.commentID+'" href=""><img title="Delete Comment" src="http://images.freewebs.com/Images/FileManager/icon-delete.gif"></a></td>'
				:'')
			+'</tr></table>';
			
			div.fx = new fx.Height(div, {duration: myDuration+=this.options.duration/2, onComplete:function(){ this.style.height=''; if(this.fx.now==0) {this.fx = null; this.parentNode.removeChild(this)} }.bind(div)});
			
			//insert this comment on top
			if(!this.commentDiv.hasChildNodes() || this.deleteMode)
				this.commentDiv.appendChild(div);
			else
				this.commentDiv.insertBefore(div,this.commentDiv.firstChild);

			if(this.userIsOwner && this.options.isEditable){
				$('del-'+c.commentID).onclick = function(){
					if(!confirm('Are you sure you want to delete this comment?'))
						return false;
					this.Notify.show('Deleting Message...', true);
					$('del-'+c.commentID).onclick = null;
					
					div.fade = new fx.Opacity(div, {duration:300});
					div.fade.custom(1, .1);
					
					fw.jjax.req('http://link.members.freewebs.com/Members/Comments/deleteComment.jsp',{
						postBody: {
							next: 'hidden',
							callback: 'fw.Instances.get("'+this.containerID+'").deleteCallback',
							section: 'usercomment',
							action: 'deleteComment',
							listID: this.listID,
							commentID: c.commentID
						}});
					return false;
				}.bind(this);
				
				/*
				$('ban-'+c.commentID).onclick = function(){
					if(!confirm('Are you sure you want to ban this user?'))
						return false;
						
					fw.jjax.req('http://link.members.freewebs.com/Members/Dispatcher.jsp',{
						postBody:{
							next: 'hidden',
							callback: 'fw.Instances.get("'+this.containerID+'").banCallback',
							section: 'usercomment',
							action: 'banPoster',
							listID: this.listID,
							commentID: c.commentID
						}});
					return false;
				}.bind(this);
				*/
			}

			//if the new comments are not the initial comments, use an effect when they are added
			if(!allNew){
				div.fx.hide();
				div.fx.toggle();
				if(!lastChild)
					lastChild = this.commentDiv.lastChild;
				lastChild.fx.toggle();
				lastChild = lastChild.previousSibling;
			}
			
			this.deleteMode = false;
		}.bind(this));
		
		this.makeButtons();
		this.Notify.hide();
		window.setTimeout(function(){this.commentRequest = false; }.bind(this), myDuration);
	},
	banCallback: function(error, response){
		if(error){
			alert(response);
			return;
		}
		alert(error + response);
	},
	deleteCallback: function(error, response){
		this.Notify.hide();
		if(error){
			alert(response);
			return;
		}
		$(this.containerID + '-c-' + response).fx.toggle();
		this.deleteMode = true;
		if(this.pageCount > 1)
			this.requestComments(this.page);
		else
			this.setCommentCount(--this.commentCount);
	},
	newComment: function(comment){
		if(!comment)
			return false;
		return {
			listID: comment[0],
			commentID: comment[1],
			name: comment[2],
			message: comment[3],
			time: comment[4],
			rating: comment[5],
			IP: comment[6]
		};
	},
	Notify: {
		show: function(){
		},
		hide: function(){
		}
	}
});