var SwapComment = Class.create();

//Binds the SwapComment control to an element and shows/hides the comments when element is clicked
//If a parentElement is passed in it will look only for the this.options.bindTo elements that are children of that element.
//If no parentElement is passed in the entire contents of the page will be search for this.options.bindTo elements.
SwapComment.bindOnClick = function(parentElement, options){	
	var defaultOptions = SwapComment.defaultOptions;
	Object.extend(defaultOptions, options || {});	
	
	var me = this;
	var elementsToBind = (parentElement != undefined)? parentElement.select(defaultOptions.bindTo) : $$(defaultOptions.bindTo);
	
	elementsToBind.each(function(item){		
		var metaData = item.readAttribute(defaultOptions.idAttribute).split("||");		
		var metaDataList = metaData[1].split("|");
		var lastCommentId = 0;
		var otherUser = '';
		var isFriend = false;
		
		if(metaDataList.length ==6){
			lastCommentId = metaDataList[3];
			otherUser = metaDataList[4];
			isFriend = metaDataList[5];
		} else if(metaDataList.length == 4){
			lastCommentId = metaDataList[3];
		}

		var swapComment = new SwapComment(defaultOptions, metaDataList[0], metaDataList[1], metaDataList[2], lastCommentId, otherUser, isFriend);
		
		item.observe('click', function(event){ swapComment.getComments(true); });
		item.setAttribute(defaultOptions.idAttribute, metaData[0]);						
	});
}

SwapComment.staticSaveComment = function(userActionId, toUsername, commentType, comment, displayType, isPublic, showLogin, onSuccess, onFailure, onLoginFailure){
	if(comment.length == 0) { return; }
	
	new Ajax.Request(baseUrl + 'AjaxSaveComment.aspx', 
			{	method: 'post', 
				onSuccess : function(resp) { 
								if(resp.responseText.indexOf("login") > -1) { 
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											SwapComment.staticSaveComment(userActionId, toUsername, commentType, comment, displayType, isPublic, false, onSuccess, onFailure, onLoginFailure);
										});
										openLightView(baseUrl + 'WebFrmSecureLogin.aspx?OnlyHide=1', 274, 260, "member login", "please log in to submit a comment");
									} else {
										document.stopObserving('lightview:hidden');
										onLoginFailure();
									}									
								} else if(resp.responseText != "failed") {
									document.stopObserving('lightview:hidden');
									onSuccess(resp);
								} else {
									document.stopObserving('lightview:hidden');
									onFailure('failed');
								}							
							},
				parameters : "uaid=" + userActionId + "&dtype=" + displayType + "&user=" + toUsername + "&ctype=" + commentType + "&comment=" + escape(comment) + "&ispublic=" + isPublic + "&cb=" + Math.random()
			});
}

SwapComment.defaultOptions = {
	bindTo: '.swapComment',
	idAttribute: 'rev',
	defaultCommentText: 'write a comment...',
	expandTextBox: true,
	displayType: 'dynamic',
	insertPostion: 'bottom',
	pluralCountText: 's ',
	isCommenterFriendWithActionOwner: false,
	onlyPublicComments: false
}

SwapComment.prototype = {
	userActionId: null,
	actionId: null,
	owner: null,
	lastCommentId: 0,	
	container: null,
	textBox: null,
	options: SwapComment.defaultOptions,
	dType: null,
	onlyPublicComments: false,
	otherUser: '',
	isFriend: false,
	
	initialize: function(defaultOpts, userActionId, actionId, owner, lastCommentId, otherUser, isFriend) {
		Object.extend(this.options, defaultOpts || {});	

		this.userActionId = userActionId;
		this.actionId = actionId;
		this.owner = owner;
		this.dType = this.options.displayType;
		this.onlyPublicComments = this.options.onlyPublicComments;
		this.otherUser = otherUser;
		this.isFriend = isFriend;
											
		if(lastCommentId != undefined && lastCommentId != 0){
			this.lastCommentId = lastCommentId;
		} else {
			//even though something else may be specified, you can't do anything else but dynamic w/o lastcommentid
			this.dType = 'dynamic'
		}
		
		if(this.dType == 'dynamicRolledUp'){					
			var me = this;
			this.container = $("comment" + this.userActionId);
			this.bindFormEvents();
			var commentLink = this.container.select('.lnkRolledComment');
			
			if(commentLink.length > 0){
				commentLink[0].observe('click', function(event){ me.getRolledUpComments(true); });
			}					
		}		
	},
	
	expandCommentForm: function(){
		if(this.textBox.value != this.options.defaultCommentText){
			return;	
		}
		
		this.textBox.value = '';		
		this.container.select('.formFields')[0].show();
				
		if(this.options.expandTextBox){
			this.textBox.style.height='33px';
			this.textBox.style.width='346px';
			this.textBox.style.color='#4d4d4d';
			this.container.select('.commentFields')[0].setStyle({width:'354px'});
			this.container.select('.commentProfile')[0].show();	
		}
	},
	
	resetCommentForm: function(){
		if(this.textBox.value.length > 0){
			return;
		}
		
		this.textBox.value=this.options.defaultCommentText;
			
		if(this.options.expandTextBox && this.getCommentCount() > 0){
			this.container.select('.formFields')[0].hide();
			this.container.select('.commentProfile')[0].hide();	
			this.textBox.style.height='16px';
			this.textBox.style.width='385px';			
			this.container.select('.commentFields')[0].setStyle({width:'395px'});
		}		
	},
	
	getComments: function(showLogin){	
		if (this.container != undefined && this.container.style.display != 'none'){
			Effect.BlindUp(this.container, {duration:0.6});
			return;
		}

		var me = this;
		new Ajax.Request(baseUrl + 'AjaxGetComments.aspx', 
						{	method: 'post', 
							onSuccess : function(response){
								if(me.trim(response.responseText) == "login") { 
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											me.getComments(false);
										});
										me.showLogin("please log in to view comments");
									} else {
										document.stopObserving('lightview:hidden');
									}									
								} else if(response.responseText != "failed") {
									document.stopObserving('lightview:hidden');
									me.displayComments(response.responseText);									
								}								
							},
							parameters : "uaid=" + this.userActionId + "&op=" + ((this.onlyPublicComments)?"1":"0") + "&type=" + this.dType + "&aid=" + this.actionId + "&friend=" + ((this.options.isCommenterFriendWithActionOwner) ? "1" : "0") + "&owner=" + this.owner + "&cb=" + Math.random()
						});
	},
	
	saveComment: function(showLogin){
		var errorMsg = this.container.select('.spanCommentErrorMsg');
		
		if(this.textBox.value == '' || this.textBox.value == this.options.defaultCommentText){
			errorMsg[0].show();	
			return;
		}
		if (errorMsg[0] && errorMsg[0].visible()) {
			errorMsg[0].hide();	
		}
		
		var me = this;
		var commentType = "action";
		var isPublic = 1;
		var optionList = this.container.select('input[type="radio"]');

		if(optionList.length == 2 && optionList[0].checked){
			if(this.actionId == 21){
				commentType = "user";				
			}
			isPublic = 0;
		}

		new Ajax.Request(baseUrl + 'AjaxSaveComment.aspx', 
			{	method: 'post', 
				onSuccess : function(resp) { 
								if(me.trim(resp.responseText) == "login") { 
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											me.saveComment(false);
										});
										me.showLogin("please log in to submit a comment");
									} else {
										document.stopObserving('lightview:hidden');
									}									
								} else if(resp.responseText != "failed") {
									document.stopObserving('lightview:hidden');
									
									//Set up delete click event
									var newComment = new Element("div").update(resp.responseText).firstDescendant();								
									newComment.select('.lnkDelete').each(function(item){			
										var metaData = item.readAttribute(me.options.idAttribute).split("||");				
										item.observe('click', function(event){ me.deleteComment(metaData[1],true); });
										item.setAttribute(me.options.idAttribute, metaData[0]);						
									});
									
									//Append new comment to list
									var position = { 'bottom' : newComment };
									if(me.options.insertPosition == 'top'){
										position = { 'top' : newComment };
									}
									me.container.select('.commentList')[0].insert(position);
									
									//update label
									me.updateCommentCountLabel(1);
									
									//reset comment box
									me.textBox.value = '';
									me.resetCommentForm();
								}								
							},
				parameters : "uaid=" + this.userActionId + "&dtype=" + this.dType + "&user=" + this.owner + "&ctype=" + commentType + "&comment=" + escape(this.textBox.value) + "&ispublic=" + isPublic + "&cb=" + Math.random()
			});
	},
	
	deleteComment: function(commentId,showLogin){
		var me = this;
		new Ajax.Request(baseUrl + 'AjaxDeleteComment.aspx', 
			{	method: 'post', 
				onSuccess : function(resp) { 							
								if(me.trim(resp.responseText) == "login") { 
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											me.deleteComment(commentId,false);
										});
										me.showLogin("please log in to delete a comment");
									} else {
										document.stopObserving('lightview:hidden');
									}									
								} else if(resp.responseText != "failed") {
									document.stopObserving('lightview:hidden');
									$('commentItem' + commentId).remove();									
									me.updateCommentCountLabel(-1);
									if(me.options.expandTextBox && me.getCommentCount() == 0){
										me.expandCommentForm();
									}
								}								
							},
				parameters : "id=" + commentId + "&cb=" + Math.random()
			});
	},
	
	updateCommentCountLabel: function(incrementBy){
		//Updates comment count label
		if($('commentCount' + this.userActionId) != undefined){
			var count = $('commentCount' + this.userActionId).innerHTML;
			count = count.replace(/s|\(|\)|\s/gi, "");
			count = ((count == "") ? 0 : parseInt(count)) + incrementBy;

			if(count > 0){
				$('commentCount' + this.userActionId).innerHTML = this.options.pluralCountText + '(' + count + ')';
			} else {
				$('commentCount' + this.userActionId).innerHTML = '';
			}								
		}
	},
	
	displayComments: function(commentHtml){	
		if (commentHtml.length > 0) 
		{	
			if (this.container != undefined){
				this.container.remove();
			}
			
			this.container = new Element("div", { id: "comment" + this.userActionId, style: 'display:none' });	
			this.container.className="comments";
			this.container.style.width="405px";											
			this.container.innerHTML = commentHtml;
														
			this.bindFormEvents();
			
			if(this.getCommentCount() == 0){
				this.expandCommentForm();
			}
			
			$('commentsContainer' + this.userActionId).insert(this.container);
			Effect.BlindDown(this.container, {duration:0.6});
		}
	},
	
	bindFormEvents: function(){
		//attach click event handler to save button
		var addCommentLink = this.container.select('.lnkAddComment');
		
		if(addCommentLink.length > 0){
			var me = this;			
			addCommentLink[0].observe('click', function(event){ me.saveComment(true); });
			
			//attach focus/blur event handlers to textbox
			this.textBox = this.container.select('textarea[name="txtComment"]')[0];		
			this.textBox.observe('focus', function(event){ me.expandCommentForm(); });
			
			if(!(this.actionId == 18 || this.actionId == 21 || this.actionId == -18)){
				this.textBox.observe('blur', function(event){ me.resetCommentForm(); });
			}		
			
			if($('lnkShowMoreComments')){			
				$('lnkShowMoreComments').observe('click', function(event){ me.getMoreComments(this, true); });
			}				
		}
		
		//attach click event handler to delete buttons
		this.bindDeleteEvent(this.container);						
	},
	
	bindDeleteEvent: function(parentElement){
		var me = this;
		parentElement.select('.lnkDelete').each(function(item){			
			var metaData = item.readAttribute(me.options.idAttribute).split("||");	
			if(metaData[1].split("|").length != 2){			
				item.observe('click', function(event){ me.deleteComment(metaData[1],true); });					
			} else {
				item.observe('click', function(event){ me.toggleDeleteMenu($(this)); });
			}
		});	
	},
	
	toggleDeleteMenu: function(elem){
		var me = this;
		var menu = $('delMenuC' + this.userActionId);	
		if(!menu.visible()){					
			menu.clonePosition(elem,{setWidth:false, setHeight:false, offsetTop:16, offsetLeft:-130}); 
			var metaData = elem.readAttribute(me.options.idAttribute).split("||");	
			menu.select('.delComment')[0].observe('click', function(event){ me.deleteComment(metaData[1].split("|")[0],true); });

			var menuLink = menu.select('#lnkRemoveFriend')[0];
			var qsPosition = location.href.indexOf('?');
			var url = (qsPosition > -1) ? location.href.substr(0, qsPosition) : location.href;
			
			if(this.isFriend=='false'){			
				menuLink.href = url + '?friendonly=1&user=' + this.otherUser;
				menuLink.innerHTML = 'delete all conversations with user and only allow friends to contact me';
			} else {
				menuLink.href = url + '?friend=' + this.otherUser;
				menuLink.innerHTML = 'delete all conversations and remove user as my friend'
			}
		}
		menu.toggle();  
	},
	
	getCommentCount: function(){
		return this.container.select('.commentList .commentBox').length;
	},
	
	getRolledUpComments: function(showLogin){	
		var me = this;
		
		//hide all possible open delMenu boxes so poitioning doesn't get messed up
		var arrDelMsgMenus = $$('div[class="delMenu"]');
		for(var i = 0; i < arrDelMsgMenus.length; i++) {
			arrDelMsgMenus[i].hide();
		}
		var arrParenDelMsgMenus = $$('div[class="delMenu delMsgMenu"]');
		for(var i = 0; i < arrParenDelMsgMenus.length; i++) {
			arrParenDelMsgMenus[i].hide();
		}

		new Ajax.Request(baseUrl + 'AjaxGetComments.aspx', 
			{	method: 'post', 
				onSuccess : function(response) { 					
								if(me.trim(response.responseText) == 'login'){
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											me.getRolledUpComments(false);
										});
										me.showLogin("please log in to view more comments");
									} else {
										document.stopObserving('lightview:hidden');
									}	
								} else if(response.responseText == ""){
									document.stopObserving('lightview:hidden');
									$('commentList').insert("no more comments");																
								} else if(response.responseText != "failed") {
									document.stopObserving('lightview:hidden');

									var comments = new Element("div").update(response.responseText);
									me.bindDeleteEvent(comments);

									me.container.select('.commentList')[0].insert({ 'top' : comments });
									me.container.select('.rolledCommentCount')[0].hide();
								}
							},
				parameters : "uaid=" + this.userActionId + "&commentid=" + this.lastCommentId + "&op=" + ((this.onlyPublicComments)?"1":"0") + "&type=" + this.dType + "&aid=" + this.actionId + "&friend=" + ((this.options.isCommenterFriendWithActionOwner) ? "1" : "0") + "&owner=" + this.owner + "&cb=" + Math.random()
			});
	},
		
	trim: function(text){
		return text.replace(/^\s+|\s+$/g,"");
	}, 
	
	showLogin: function(text){
		openLightView(baseUrl + 'WebFrmSecureLogin.aspx?OnlyHide=1', 274, 260, "member login", text);
	}
};