/* fwComments.js - Comments widget
 *
 * @Author: Ryan McGrath (redux version, library agnostic), Some other guy did the original (no clue who ;P)
 * @Requires http://images.webs.com/JS/fw.js ;P
 */

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

/* Comment Posting System */
var fwComments = new CompatClass({
	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
		}
		fw.CompatExtend(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.webs.com/reloginLite.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 ? false : this.options.showLogin,
			showEmail: this.options.showEmail,
			emailDesc: ' (Will be kept private)',
			onPost: function(){
				this.postComment();
			}.CompatBind(this),
			onCancel: this.togglePostDivFx.CompatBind(this),
			draw: false
		});
		
		this.hideCommentHTML = this.options.showHideLink ? '<img style="border:0; margin-right:2px; vertical-align:middle;" src="http://images.webs.com/Images/arrowRight.gif">Hide Comments' : '';
		this.showCommentHTML = '<img style="border:0; margin-right:2px; vertical-align:middle;" src="http://images.webs.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.webs.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.webs.com/Styles/fwComments.css');
	},

	draw: function(){
		document.write(this.HTML);
		this.activate();
	},

	activate: function(){	
		id = this.containerID;
		this.container = document.getElementById('fwCom'+id);
		this.navDiv = document.getElementById(id+'-nav');
		this.lowerDiv = document.getElementById(id+'-lowerDiv');
		this.cCount = document.getElementById(id+'-cCount');
		this.commentDiv = document.getElementById(id+'-com');
		
		if(this.options.showPostHide){
			this.postDiv = document.getElementById(id+'-post');
			this.comLink = document.getElementById(id+'-comLink');
			this.postDiv.style.marginLeft = '6px';
			
			this.comLink.onclick = function() { 
				if(this.lowerDiv.style.display != "none") {
					this.lowerDiv.style.display = "none";
					this.comLink.innerHTML = this.showCommentHTML;
				} else {
					this.lowerDiv.style.display = "block";
					this.comLink.innerHTML = this.hideCommentHTML;
				}
				return false;
			}.CompatBind(this);
		} 
		this.pageNumbers.activate();
		this.pageNumbers.options.onClick = this.requestComments.CompatBind(this);
		
		if(this.options.showLowerPaging){
			this.lowerPageNumbers.activate();
			this.lowerPageNumbers.options.onClick = this.requestComments.CompatBind(this);
		}
		
		if(this.options.showPostHide && !this.options.disablePost){
			this.postLink = document.getElementById(id+'-postLink');
			this.postLink.onclick = function() { this.togglePostDivFx(); return false; }.CompatBind(this);
			this.bbBox.activate();
			if(this.options.startPostClosed) {
				this.postDiv.style.display = "none";
			}
		}
		
		if(this.options.startHidden && this.options.showPostHide){
			this.lowerDiv.style.display = "none";
		}
		
		this.requestComments(this.options.page || 1);
	},
	togglePostDivFx: function() {
		if(this.postDiv.style.display != "none") this.postDiv.style.display = "none";
		else this.postDiv.style.display = "block";
	},
	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!');
        if(this.bbBox.getName().length > 50)
            return alert('Please shorten your entered name.  Maximum length of the name field is 50 characters.')
        this.bbBox.toggleProcessing();
		fw.jjax.req('http://link.members.webs.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();
			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.webs.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;
			var chiNodes = this.commentDiv.childNodes;
			/* Uber magic hack beware */
			this.commentDiv.innerHTML = "<!-- LOL -->";
			/* for(var i = 0; i < chiNodes.length; i++) {
				this.commentDiv.removeChild(chiNodes[i]);
				/*
				if(comments.length < this.options.limit && this.page > 0) {
					if(chiNodes[i].style.display != "none") chiNodes[i].style.display = "none";
					else chiNodes[i].style.display = "block";
				} else {
					oldComments[chiNodes[i].id] = true;
				}
			} */
		} 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)
		for(var i = 0; i < comments.length; i++) {
			var c = this.newComment(comments[i]);
			if(allNew || !oldComments[cPrefix + c.commentID]){
				oldComments[cPrefix + c.commentID] = null;
				newComments.push(c);
			}
		}
		
		//slide in the new comments
		var lastChild = null;
		var myDuration = this.options.duration;
		var newCommentsReversed = newComments.reverse();

		for(var i = 0; i < newCommentsReversed.length; i++) {
			var div = document.createElement('div');
			div.id = cPrefix + newCommentsReversed[i].commentID;
			var starRating = {};
			if(this.options.showRatings){
				if(newCommentsReversed[i].rating)
					starRating = new fwStarRating(cPrefix+newCommentsReversed[i].commentID+'-sr', {rating:newCommentsReversed[i].rating, starsOnly:true, draw:false});
				else
					starRating.HTML = '<span style="font-size:.9em;">No Rating</span>';
			}
			else
				starRating.HTML = '';

			div.innerHTML = ''
			+'<table '+(!this.options.showDate ? 'title="posted '+newCommentsReversed[i].time+'"' : '') + ' class="commentTable '+(this.ii++%2 ? 'fw-odd' : 'fw-even')+'"><tr>'
			+'<td><b>' + (newCommentsReversed[i].name ? newCommentsReversed[i].name+':' : '') + '</b> <br>' + newCommentsReversed[i].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
						?newCommentsReversed[i].time.replace(' ', '&nbsp;') + '</div>'
						:'')
					+(this.options.showIP && c.IP
						?'<div class="fwComIP">'+newCommentsReversed[i].IP+'</div>'
						:'')
					+'</td>'
				:'')
			+(this.userIsOwner && this.options.isEditable
				?'<td style="width:30px;" align="center"><a id="del-'+newCommentsReversed[i].commentID+'" href=""><img title="Delete Comment" src="http://images.webs.com/Images/FileManager/icon-delete.gif"></a></td>'
				:'')
			+'</tr></table>';
			
			div.style.display = "block";
			
			//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){
				document.getElementById('del-'+newCommentsReversed[i].commentID).setAttribute("rel", newCommentsReversed[i].commentID);
				document.getElementById('del-'+newCommentsReversed[i].commentID).onclick = function(e) {
					if(!confirm('Are you sure you want to delete this comment?'))
						return false;
					this.Notify.show('Deleting Message...', true);
					
					/*	This is a complete and utter hack to get around the idiotic amount of scope-binding that's being done in here.
					 *	We get the event of this onclick event, get the element that was clicked, and strip out our friggin' commentID.
					 */
					if(!e) var e = window.event;

					var ourcommentIDToStrip = (e.target ? e.target : e.srcElement);
					//return false;
					
					document.getElementById('del-'+c.commentID).onclick = null;
					
					div.style.display = "none";
					fw.jjax.req('http://link.members.webs.com/Members/Comments/deleteComment.jsp',{
						postBody: {
							next: 'hidden',
							callback: 'fw.Instances.get("'+this.containerID+'").deleteCallback',
							section: 'usercomment',
							action: 'deleteComment',
							listID: this.listID,
							commentID: parseInt(ourcommentIDToStrip.parentNode.getAttribute("rel"))
						}
					});
					return false;
				}.CompatBind(this);
			}
		
			this.deleteMode = false;
		}
		
		this.makeButtons();
		this.Notify.hide();
		window.setTimeout(function(){this.commentRequest = false; }.CompatBind(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;
		}
		var lol = document.getElementById(this.containerID + '-c-' + response);
		if(lol.style.display != "none") lol.style.display = "none";
		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(){
		}
	}
});
