/*	FWShoutbox
 *
 *	@Author: Dave Maestri (Original version, Mootools/Prototype reliant)
 *	@Author: Ryan McGrath (Refactored/current version, library-agnostic)
 *
 *	@Requires: Nothing, except your undying love and affection
 */

function toggleVisible(s) {
    var d = document.getElementById(s);
    d.style.display = (d.style.display == 'block') ? 'none' : 'block';
}

function appendToRecentComments(c) {
    if (recentComments.length < 10) {
        this.recentComments.push(c);
    } else {
        recentComments.shift();
        recentComments.push(c);
    }
}

function fillMuteList(r) {
    var s = '<table width="290px">'
            +'<tr>'
            +'<td width="250px; style="float: left;"><a href="#" onclick="clearMuteList(); toggleVisible(\'muteList\'); return false;">unmute all</a></td>'
            +'<td><span style="float: right;"><a href="#" onclick="toggleVisible(\'muteList\'); fillMuteList(); return false;">close&nbsp;</a></span></tr>'
            +'</tr>'
            +'<tr><td colspan="2"><hr/></td></tr>';
    for(var i = 0; i < r.length; i++) {
        s += '<tr>'
            +'<td><div style="width: 250px; overflow: hidden;">' + r[i].name + '</div></td>'
            +'<td><a href="#" onclick="addMutedID(' + r[i].posterID + '); return false;">mute</a></td>'
            +'</tr>'
            +'<tr><td colspan="2"><hr/></td></tr>';
    }
    s += '</table>';

    document.getElementById('muteList').innerHTML = s;
}

function addMutedID(id) {
    this.mutedIDs.push(id);
    toggleVisible('muteList');
}

function clearMuteList() {
    this.mutedIDs = [];
}

function isMuted(c) {
    for (var i = 0; i < mutedIDs.length; i++) {
        if (mutedIDs[i] == c.posterID) { return true;}
    }
    return false;
}

if(!fwShoutBox) {
	var fwSbTimeout;
	var fwSbInterval = 4000;
	var fwSbIDs = [];
	var fwSbLastIds = [];
	var fwSbUserIDs = [];
    var recentComments = [];
    var mutedIDs = [];
}


/* Basic compatibility layer... */
var fwShoutBox = function() { this.initialize.apply(this, arguments); };

fwShoutBox.prototype = {
	defaultInterval: 4000,
	initialize: function(listID, ownerID, disablePost, options){
	    this.listID = listID;
	    this.ownerID = ownerID;
	    this.options = options || {};
	    this.containerID = 'fw-sb-'+listID;
	    this.defaultAdHeight = this.options.isPremium ? -10 :  (this.options.upperAdHeight || 90);
	    this.height = (this.options.height > 250) ? this.options.height : 250;
	    this.width = (this.options.width > 250) ? this.options.width : 250;
	    this.isIframe = this.options.iframe ? true : false;
	    this.isPopup = this.options.popup ? true : false;
	    this.isDeleted = this.options.isDeleted || false;
	    this.windowTopURL = this.options.windowTopURL || window.location;
	    this.adHeight = this.isPopup ? this.defaultAdHeight : 0;
		this.postHeight = this.options.postHeight || 83;
		this.heightAdjust = this.postHeight + 5 + this.adHeight + (this.options.lowerAdHeight || 0);
		this.disablePost = disablePost;
		this.backgroundURL = this.options.backgroundURL || false;
		this.upperAdContent = this.options.upperAdContent || '<br><br>This ShoutBox Powered By Webs.com<br><a target="_blank" href="http://webs.com/s/signup?referer=shoutBoxTop&profileOnly=1">Get Your Own Free Website and ShoutBox Here</a>';
		this.upperAdStyle = this.options.upperAdStyle || 'text-align:center;';
		var loginTarget =  this.isPopup ? ' target="_blank"' : '';
	    
	    //avoid multiple of the same shoutbox list per page
		if(document.getElementById(this.containerID)) return;

		// add id to the list of shoutboxes to check
		this.refID = fwSbIDs.length;
		fwSbIDs[fwSbIDs.length] = listID;
		fwSbUserIDs[fwSbUserIDs.length] = ownerID;
	    fwSbLastIds[fwSbLastIds.length] = 0;
		
		//add stylesheets
		var skinName = (!options || !options.skin) ? "light" : options.skin;
		var mainStyle = document.createElement('link');
		var skinStyle = document.createElement('link');
		skinStyle.rel = mainStyle.rel = 'stylesheet';
	    skinStyle.type = mainStyle.type = 'text/css';
		mainStyle.href = 'http://images.freewebs.com/Members/Comments/fw.shoutbox.css';
		skinStyle.href = "http://link.members.webs.com/Members/Comments/loadSkinCSS.jsp?skin="+skinName;
		document.getElementsByTagName('head')[0].appendChild(mainStyle);
        document.getElementsByTagName('head')[0].appendChild(skinStyle);

		//write containers
		document.write(''
		+'<div class="fw_shoutbox skin_'+skinName+'" id="'+this.containerID+'" style="width:'+this.width+'px;">'
			+((!this.options.isPremium && this.isPopup)
				?'<div class="fw_upperAd" style="border-top-width:2px; height:'+this.adHeight+'px; '+this.upperAdStyle+'">'+this.upperAdContent+'</div>'
				:'')
			+'<div class="fw_comments" id="fw-sb-com'+this.listID+'" style="height:'+(this.height-this.heightAdjust)+'px;">'
			+((this.isDeleted)
				?'<div style="height:40%;"></div><div style="height:60%; padding:0 10% 0 10%; text-align:center;">This ShoutBox has been deleted.<br><a target="_blank" href="http://webs.com/s/signup?referer=shoutBoxTop&profileOnly=1">Get Your Own Free Website and ShoutBox Here</a></div>'
				:'')
			+'</div>'
			+'<div class="fw_postcomment" id="fw-sb-post'+this.listID+'" style="height:'+this.postHeight+'px;' + (this.backgroundURL ? ' background-image: url(' + this.backgroundURL + ')' : '') + '">'
				+'<div class="fw_postleft">'
					+((!disablePost)
						?'<div>Name:</div>'
						:'')
					+((!disablePost)
						?'<div>Comment:</div>'
						:'')
				+'</div>'
				+'<div class="fw_postright"><div>'
					+((!this.isDeleted)
						?(((!disablePost && fwuser.loggedIn)
							?'<i>'+fwuser.alias+'</i>'
							:(!disablePost ? ' <input maxlen="50" type="text" id="fw-sb-username'+this.listID+'" />' : ''))
							+((!disablePost)
								?'<textarea maxlen="255" id="fw-sb-txt'+this.listID+'"></textarea>'
								:'<div style="width:100%; text-align:left;">'+disablePost+'</div>'))
						:'')
						+((!disablePost)
							?'<input id="fw-sb-send-'+this.listID+'" class="fw_sendbutton" value="Send" type="submit">'
							:'')
				+'</div>'
                +'<div id="muteList" style="display: none; width: 300px; background-color: #BDBDBD; position: absolute; top: -510px; z-index: 100000;">'
                +'</div>'
                +'</div>'
				+((!this.isDeleted)
					?('<div class="fw_sb_links">'
					+((!fwuser.loggedIn)
						?'<a href="http://link.members.webs.com/reloginLite.jsp?next='+escape(this.windowTopURL)+'&amp;shoutBoxOwnerID='+this.ownerID+''+(this.isPopup ? '&amp;generic=1' : '')+'" target="_top">Login</a>'
						:'<a href="http://link.members.webs.com/s/login/logout?next='+escape(this.isPopup ? window.location : this.windowTopURL)+'" target="_top">Logout</a>')
					+((!this.isPopup)
						?' | <a href="" onclick="window.open(\'http://link.members.webs.com/Members/Comments/viewshoutbox.jsp?shoutBoxOwnerID='+ownerID+'&listID='+listID+'&skinName='+skinName+'&popup=1\', \'_blank\', \'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width='+this.width+',height='+(this.height+this.defaultAdHeight)+'\'); return false;">Popout</a>'
						:'')
					+((this.isPopup)
						?' | <a href="'+this.options.ownerURL+'" target="_blank">Visit My Site</a>'
						:'')
                    +' | <a href="#" onclick="toggleVisible(\'muteList\'); fillMuteList(recentComments); return false;">Mute</a>'
                    +'<span id="fw-sb-status'+this.listID+'"> | loading...</span>'
					+'</div>')
					:'')
				+(this.options.skinLink
					?'<a class="skinLink" href="' + this.options.skinLink + '" target="_blank"></a>'
					:'')
			+'</div>'
			+((this.options.lowerAdContent && !this.options.isPremium)
				?'<div class="fw-sb-lowerad fw_comments" style="height:'+this.options.lowerAdHeight+'px;'+(this.options.lowerAdStyle || 'text-align:center;')+'">'
					+this.options.lowerAdContent
				+'</div>'
				:'')
			+(this.options.trackerPixel ? this.options.trackerPixel : '')
		+'</div>'
		);

		//set container references
		this.container = document.getElementById(this.containerID);
		this.commentContainer = document.getElementById('fw-sb-com'+this.listID);
		this.postContainer = document.getElementById('fw-sb-post'+this.listID);
		this.statusContainer = document.getElementById('fw-sb-status'+this.listID);
		this.inputBox = document.getElementById('fw-sb-username'+this.listID);

		//store this object in its main container div
		this.container.fwShoutBox = this;
		
		//attach post actions
		if (!disablePost) {
			this.textarea = document.getElementById('fw-sb-txt'+this.listID);
			
			// The event listeners below need to be refactored... perhaps a singular event model?

			this.textarea.onkeypress = function(e){
				if(this.isEnter(e))
					if(e.preventDefault) e.preventDefault();
					else e.returnValue = false;
			}.CompatBindAsEventListener(this);
			
			this.sendButton = document.getElementById('fw-sb-send-'+this.listID);
			this.sendButton.onclick = function(){
				this.postComment()
			}.CompatBindAsEventListener(this);
		}
		
		//set dimensions
		if(this.isPopup){
			this.container.style.width = this.container.style.height = '100%';
			window.onresize = this.resize.CompatBind(this);
			window.setTimeout(this.resize.CompatBind(this), 200);
		}

		//load messages for this shoutbox only
		this.initialLoad = true;
		if(this.isDeleted)
			this.setStatus('This ShoutBox is inactive.');
		else 
			this.checkMessages(true);
	},
	resize: function(){
		var offsetHeight = window.innerHeight || document.documentElement.offsetHeight;
		this.width = window.innerWidth || document.documentElement.offsetWidth;
	    this.commentContainer.style.height = ((this.isPopup ? offsetHeight : this.container.offsetHeight) - this.heightAdjust) + 'px';
		this.commentContainer.scrollTop = 99999;
		this.lastScroll = this.commentContainer.scrollTop;
	},
	resetInterval: function(time) {
		fwSbInterval = time ? time : this.defaultInterval;
	},
	addInterval: function() {
	    if (fwSbInterval < 1000*60*5)
		   fwSbInterval = Math.floor(fwSbInterval * 1.25);
	},
	scheduleCheck: function(time){
		if(fwSbTimeout)
			clearTimeout(fwSbTimeout);
		fwSbTimeout = window.setTimeout(function(){this.checkMessages()}.CompatBind(this), time ? time : fwSbInterval);
	},
	isEnter: function(event) {
		var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keycode == 13 || keycode == 3) {
			this.postComment();
			return true;
		}
		return false;
	},
	checkMessages: function(init) {
		//send request to retrieve comment list for ALL shoutboxes
	    jjax.req(
	        "http://link.members.webs.com/Members/Comments/listCommentsJS.jsp", {
	         postBody: {
	            minIDs: init ? fwSbLastIds[this.refID] : fwSbLastIds.toString(),
	            IDs: init ? this.listID : fwSbIDs.toString(),
	            userIDs: init ? this.ownerID : fwSbUserIDs.toString(),
	            rand: Math.random(),
	            //callback this shoutbox's readmessages function
	            callBack: 'document.getElementById("'+this.containerID+'").fwShoutBox.readMessages'
	        },
	        appendTo: this.container
	    });
	},
	readMessages: function(comments){
		if (comments.length > 0) {
			//go through each comment in reverse order
			for (var i = comments.length-1; i >= 0; i--) {
				//represent the comment as an object
				if(Comment = this.newComment(comments[i])){
					//go through each shoutbox
					for(var j=0; j<fwSbIDs.length; j++) {
						//if this comment belongs in this shoutbox, add it, but only if it is new
						if(fwSbIDs[j] == Comment.listID && fwSbLastIds[j] < Comment.commentID && isMuted(Comment) == false) {
                            appendToRecentComments(Comment);
                            this.addMessage((comments[i-1] && comments[i-1][0] != Comment.listID) || i==0, Comment);
							fwSbLastIds[j] = Comment.commentID;
							break;
						}
					}
				}
			}
			this.setStatus('');
			//there is an active shoutbox on the page, reset check interval
			this.resetInterval();
			this.scheduleCheck();
			
			if(this.initialLoad)
				window.setTimeout(function(){ this.commentContainer.scrollTop = 99999; }.CompatBind(this), 400);
		} else {
			//shoutbox was just loaded, and there are no new comments
			if(this.initialLoad)
				this.addMessage(false, {
					listID: this.listID,
					commentID: -1,
					name: '',
					message: 'No comments yet. Be the first to post!',
					time: 'Just Now'
				});
			this.setStatus('');
			//there are no active shoutboxes, increase time between checks
			this.addInterval();
			this.scheduleCheck();
		}
		this.initialLoad = false;
	},
	newComment: function(comment){
		if(!comment)
			return false;
		return {
			listID: comment[0],
			commentID: comment[1],
			name: comment[2],
			message: comment[3],
			time: comment[4],
			posterID: comment[5]
		};
	},
	setStatus: function(txt){
		if(!this.options.isPremium && !txt)
			txt = '<a class="fw_link" title="Get you own customized shoutbox from Webs.com!" href="http://webs.com/s/signup/newAccounts.jsp?referer=getShoutBox&profileOnly=1">Get one!</a>';
		if(txt)
			txt = '&nbsp;|&nbsp;' + txt;
		this.statusContainer.innerHTML = txt;
	},
	postComment: function() {
		var message = this.trim(this.textarea.value);
		if (message == '') return;
		
		//cancel any currently scheduled comment checks
		clearTimeout(fwSbTimeout);
		this.setStatus('sending message...');
		this.textarea.value = '';

	    this.lastMessage = message;
		jjax.req(
	        "http://link.members.webs.com/Members/Comments/postComment.jsp", {
	         postBody: {
	            userID: this.ownerID,
				commentSettingID: this.listID,
	            body: encodeURIComponent(message),
	            name: fwuser.loggedIn ? fwuser.alias : encodeURIComponent(this.trim(this.inputBox.value)),
	            next: 'callback',
				callback: 'document.getElementById("'+this.container.id+'").fwShoutBox.postCommentCallback',
	            rand: Math.random()
	        }});
	},
	postCommentCallback: function(error, errorMsg){
		//output any errors to the user
		if(error){
			this.textarea.value = this.lastMessage;
			this.setStatus(errorMsg);
			this.scheduleCheck(5000);
		}
		else{
			this.setStatus('loading messages...');
			this.checkMessages(true);
		}
	},
	//add a new message to the bottom of the shoutbox, add effects if "fade" is true
	addMessage: function(fade, Comment) {
		var commentDiv = document.getElementById('fw-sb-com' + Comment.listID);
	
		//remove first fake comment
		if(commentDiv.firstChild && commentDiv.firstChild.firstChild.commentID == -1)
			commentDiv.removeChild(commentDiv.firstChild);
		
		var currentScroll = commentDiv.scrollTop;
		var textDiv = document.createElement('div');
		textDiv.commentID = Comment.commentID;
		textDiv.innerHTML = '<b class="fw_comUserInfo">'+Comment.name+'</b>: ' + Comment.message;//posts here! --neil
		//textDiv.style.className = ((this.ownerID==posterID) ? 'owner' : '');
		var wrapperDiv = document.createElement('div');
		wrapperDiv.title = 'Posted ' + Comment.time;
		firstDiv = commentDiv.getElementsByTagName("div");

		if (firstDiv.length > 0)
		   textDiv.className = (firstDiv[firstDiv.length-1].className == "alt") ? "" : "alt";

	    var clr = document.createElement('i');
	    clr.className = "clear";
	    textDiv.appendChild(clr);
		wrapperDiv.appendChild(textDiv);

		/*	...Yeah, this code is just not needed. These fx() properties don't even work properly in IE8 because they're so outdated.
		 *
		 *	if (fade){
	     *	wrapperDiv.fx=newfx.Height(wrapperDiv,{duration:this.initialLoad?0:250,onComplete:function(){if(!this.lastScroll||(commentDiv.scrollTop>this.lastScroll))this.lastScroll=commentDiv.scrollTop}.bindAwesome(this)});
  	     *	wrapperDiv.fx.parentDiv = commentDiv;
		 *	wrapperDiv.fx.doScroll = this.initialLoad || (this.lastScroll!='undefined' && (commentDiv.scrollTop+50 >= this.lastScroll));
		 *	wrapperDiv.fx.increase = function() {
		 *		this.element.style.height = this.now + "px";
		 *		if(this.now > 1) this.element.style.display = "block";
		 *		if(this.doScroll)
		 *			this.parentDiv.scrollTop = 99999;
		 *	}.bindAwesome(wrapperDiv.fx);
		 *	wrapperDiv.fx.now = 0;
	     *	wrapperDiv.fx_fade = new fx.Opacity(wrapperDiv, {duration: this.initialLoad ? 0 : 350});
	     *	if(!this.initialLoad) wrapperDiv.fx_fade.hide();
		 *	} 
		 */
	    commentDiv.appendChild(wrapperDiv);
	    commentDiv.scrollTop = commentDiv.scrollTop + 50;
		/*if(fade){
	    	wrapperDiv.style.height = wrapperDiv.offsetHeight + 'px';
			var originalHeight = wrapperDiv.offsetHeight;
			wrapperDiv.style.display = "none";
	    	wrapperDiv.fx.custom(0, originalHeight);
	    	if(!this.initialLoad) wrapperDiv.fx_fade.toggle();
	    } */
	},
	
	trim: function(str) { return str.replace(/^\s+|\s+$/g, ""); }
}
