var Groups = Class.create();

Groups.prototype = {
	showDelete: false,
	
	initialize: function() {
		this.idArray = new Array();		
		this.arrayEventToday = new Array();
		this.lang = new Array();
                document.observe("dom:loaded", function() {
			groups.attachMouseEvent();
                });
	},

        attachMouseEvent: function() {
				groups.showDelete = true;
                if ($('subject_container') != null)
                {
                    var eventDivs = $('subject_container').select('div[data]');
                    eventDivs.each(function(item) {
                        groups.attachEvent0(item);
                    });
                }
	},
	attachEvent0: function(item) {
		var feedData = item.readAttribute('data').evalJSON();
                if(feedData.topicId > 0) {
			var deleteButton = $('my_close_button_' + feedData.topicId);
			if(deleteButton == null) return false;
			Event.observe(item, 'mouseover', function() {
				//deleteButton.absolutize();
				//deleteButton.style.width = 9 + 'px';
				//deleteButton.style.height = 9 + 'px';
				//deleteButton.style.left = (item.getWidth() - 10) + 'px';
				deleteButton.show();
			});
			Event.observe(item, 'mouseout', function() {
				deleteButton.hide();
			});
		}
	},

	inviteFriends: function (groupId) {
		var friendsIds = new Array(this.idArray);
		new Ajax.Request(PUBLIC_URL+'ajax/group-invite-friends',
		{
			method: 'post',
			postBody: Object.toQueryString({friendsIds:friendsIds, groupId:groupId}),
			onSuccess: function(transport) {
				document.location = PUBLIC_URL+'group/'+groupId+'/invite-friends';
			}
		});	
	},
	
	inviteInGroup: function (friendId, username){
       	this.idArray.push(friendId);
		$('groupInviteFriends').innerHTML += '<li id="padding_' + friendId + '" class="clear"><span class="decl_inv">|<a href="javascript:void(0)" onclick="groups.removePadding(' + friendId + ')">' + this.lang['21597_photos_cancel'] + '</a></span><a class="female_cl" href="'+ PUBLIC_URL+'user/'+username+'" target="_blank">' +username+ '</a></li>';
		function callback() {
						$('friendIds_' + friendId).style.display = 'none';
					}
		callback();
		$('sendBtn').style.display = 'block';
		$('emptyLi').style.display = 'none';
	},
	
	removePadding: function (friendId){
		this.idArray = this.idArray.without(friendId);
		function callback() {
				$('padding_'+friendId).remove();
				$('friendIds_' + friendId).style.display = 'block';
				if ($('groupInviteFriends').childNodes.length == 3)
				{
					$('sendBtn').style.display = 'none';
					$('emptyLi').style.display = 'block';
				}
		}
		new Effect.BlindUp('padding_'+friendId, {duration: 1, delay: 0.2, afterFinish: callback});
		
		
		return false;
	},
	
	deleteMember: function(groupId, userId) {
		function callback(){
			$('member_' + userId).remove();
		}
		new Ajax.Request(PUBLIC_URL+'group/'+groupId+'/delete-member',
		{
			method: 'post',
			postBody: Object.toQueryString({userId:userId}),
			onSuccess: function(transport) {
				new Effect.BlindUp('member_' + userId, {duration: 1, delay: 0.2, afterFinish: callback});
			}
		});	
	},
	
	selectCheckBoxes: function(formName, select){
			Form.getInputs(formName, 'checkbox').each(function(el) {
				if (select) {
					el.checked = true;
				} else {
					el.checked = false;
				}
			})
	},
	
	acceptRejectRequests: function(groupId, accept) {
		postData = Form.serializeElements(Form.getInputs('requests', 'checkbox'));
		if (accept) {
			postData += '&accept=1';
		} else {
			postData += '&accept=0';
		}
		
		new Ajax.Request(PUBLIC_URL+'group/'+groupId+'/accept-reject-requests', {
			method: 'post',
			postBody: postData,
			evalJS: 'force',
			onSuccess: function(transport) {
				Form.getInputs('requests', 'checkbox').each(function(el) {
					if (el.checked) {
						function callback()
						{
							$('user'+el.value).remove();
						}
						new Effect.Fade('user'+el.value, {duration: 1, delay: 0.2, afterFinish: callback});
						$('requestsCount').innerHTML = parseInt($('requestsCount').innerHTML) - 1;
					}
				});
			}
		});
	},
	
	countRemainingChars: function(maxLength)
	{
		currentLength = $('subject').value.length;

		if (!currentLength)
			return false;

		if (currentLength > maxLength) {
		//set to 0
		$('remainingChars').value = 0;

		if (!$('subjSendBtn').disabled)
			$('subjSendBtn').disabled = true;
		} else {
			//update
			$('remainingChars').value = maxLength - currentLength;

			if ($('subjSendBtn').disabled)
			$('subjSendBtn').disabled = false;
		}
	},
	
	removePost: function(postId, topicId, groupId)
	{
		new Ajax.Request(PUBLIC_URL+'ajax/remove-post-from-list',
		{
			method: 'post',
			postBody: Object.toQueryString({ groupId: groupId, topicId: topicId, postId: postId}),
                        evalJS: 'force',
			onSuccess: function(transport) {
				function callback() {
						$('post_'+postId).style.display='none';
					}
				new Effect.BlindUp('post_'+postId, {duration: 1, delay: 0.2, afterFinish: callback});
			}
		});
	},
	
	removeTopic: function(groupId, topicId)
	{
		new Ajax.Request(PUBLIC_URL+'ajax/remove-topic-from-list',
		{
			method: 'post',
			postBody: Object.toQueryString({ groupId: groupId, topicId: topicId}),
			onSuccess: function(transport) {
				function callback() {
					$('topic_'+topicId).style.display='none';
				}				
				new Effect.BlindUp('topic_'+topicId, {duration: 1, delay: 0.2, afterFinish: callback});
			}
		});
	},
	
	changeMemberType: function(groupId, userId)
	{
			new Ajax.Request(PUBLIC_URL+'ajax/change-member-type',
	{
		method: 'post',
		postBody: Object.toQueryString({groupId: groupId, userId: userId}),
		onSuccess: function(transport) {
			$('typeMember_' + userId).innerHTML = transport.responseText;
		}
	});
	},
		
	exitMemberGroup: function(groupId, userId) {
		var lang = this.lang; 
		new Ajax.Request(PUBLIC_URL+'group/'+groupId+'/exit-member-group',
		{
			method: 'post',
			postBody: Object.toQueryString({userId:userId}),
			onSuccess: function(transport) {
				document.location = PUBLIC_URL+'groups/index/showmsg/1';
			}
		});	
	},
	
	addPost: function(groupId, userId, positionInBlock) {
		var lang = this.lang; 
		if (userId == 0) {
			document.location = PUBLIC_URL+'signin';
		}
		if (!$('subject').value) {
			return false;
		}
		new Ajax.Request(PUBLIC_URL+'ajax/add-post',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId:groupId, userId:userId, topicId:$('topicId').value, subject:$('subject').value, postId:$('postId').value, isMaster:$('isMaster').value}),
			onSuccess: function(transport) {
				if (positionInBlock == 'bottom') { 
					$('postsBlock').insert({top: transport.responseText});
					$('header_block').scrollTo();
				} else if (positionInBlock == 'top') {
					$('postsBlock').insert({bottom: transport.responseText});
				}
				$('subject').value = '';
				$('postId').value = '';
							
				systemMessenger.set(lang['24600_comment_added_succes'],1);
				systemMessenger.display();
				return false;			
			}
		});
	},
	
	blockMember:  function(groupId, userId){
		var lang = this.lang; 
		var blockDays;
		if($('day3_' + userId).checked == true) {
			blockDays = 3;
		} else if($('day7_' + userId).checked == true) {
			blockDays = 7;
		} else if($('day30_' + userId).checked == true) {
			blockDays = 30;
		} else {
			blockDays = 10000;
		}
		new Ajax.Request(PUBLIC_URL+'ajax/block-member',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId:groupId, userId:userId, blockDays:blockDays}),
			onSuccess: function(transport) {
				$('boxesMod_' + userId).style.display = 'none';
				$('block_' + userId).style.zIndex = 1;
				$('grey_block').style.display = 'none';
				$('img_' + userId).innerHTML = transport.responseText;
				systemMessenger.set(lang['25238_success_block'], 1);
				systemMessenger.display();
				return false;
			}
		});
	},
	
	unblockMember:  function(groupId, userId){
		var lang = this.lang; 
		new Ajax.Request(PUBLIC_URL+'ajax/unblock-member',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId:groupId, userId:userId}),
			onSuccess: function(transport) {
				$('img_' + userId).innerHTML = transport.responseText;
				systemMessenger.set(lang['25239_success_unblock'], 1);
				systemMessenger.display();
				return false;
			}
		});
	},
	
	boxBlocked: function(userId) {
		if ($('boxesMod_' + userId).style.display == 'block') {
			$('boxesMod_' + userId).style.display = 'none';
			$('block_' + userId).style.zIndex = 1;
			$('grey_block').style.display = 'none'
		} else {
			$('block_' + userId).style.zIndex = 2;
			if (navigator.appName == 'Netscape') { // Mozilla Firefox Bookmark
				$('grey_block').style.height = document.height + 'px';
			}
			$('grey_block').style.display = 'block';
			$('boxesMod_' + userId).style.display = 'block';
		}
	},
	
	stickyTopic: function(groupId, topicId, sticky)
	{
		var lang = this.lang; 
		new Ajax.Request(PUBLIC_URL+'ajax/sticky-topic',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId: groupId, topicId: topicId, sticky: sticky}),
			onSuccess: function(transport) {
				if (!sticky) {
					$('sticky_' + topicId).innerHTML = '<img class="clb_close_img" src="' + staticContentImages + 'clubs/pin_icon2.jpg" alt="' + lang['25409_sticky'] + '" title="' + lang['25409_sticky'] + '" width="25" height="20" onclick="groups.stickyTopic(' + groupId + ', ' + topicId + ', 1);" />';
					$('strong_' + topicId).style.color = '#0079B8';
				} else {
					function callback1() {
						$('topic_'+topicId).style.display='none';
						$('sticky_' + topicId).innerHTML = '<img class="clb_close_img" src="' + staticContentImages + 'clubs/pin_icon.jpg" alt="' + lang['25410_not_sticky'] + '" title="' + lang['25409_sticky'] + '" width="25" height="20" onclick="groups.stickyTopic(' + groupId + ', ' + topicId + ', 0);" />';
						$('strong_' + topicId).style.color = '#00005C';
						$('blockTopics').insert({top: $('topic_' + topicId)});
						new Effect.BlindDown('topic_'+topicId, {duration: 2, delay: 0.2, afterFinish: callback2});
					}
					function callback2() {
						$('topic_' + topicId).style.display = 'block';
					}
					new Effect.BlindUp('topic_'+topicId, {duration: 1, delay: 0.2, afterFinish: callback1});
					
				}
			}
		});
	},
	
	rejectInvitation: function(groupId, invitationNo)
	{
		new Ajax.Request(PUBLIC_URL+'ajax/reject-group-invitation',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId: groupId, invitationNo: invitationNo}),
			onSuccess: function(transport) {
				function callback1() {
					$('group_invitation_'+invitationNo).innerHTML = transport.responseText;
					if($('group_invitation_'+invitationNo).innerHTML)
					{
						new Effect.BlindDown('group_invitation_'+invitationNo, {duration: 1, delay: 0.2});
					}
					if((!$('group_invitation_1') || $('group_invitation_1').innerHTML == '') && (!$('group_invitation_2') || $('group_invitation_2').innerHTML == ''))
					{
						new Effect.BlindUp('groupInvitations', {duration: 1, delay: 0.2});
					}
				}
				new Effect.BlindUp('group_invitation_'+invitationNo, {duration: 1, delay: 0.2, afterFinish: callback1});
				$('clubInvitationsCount').innerHTML = Math.max(parseInt($('clubInvitationsCount').innerHTML) - 1, 0);
				$('clubInvitationsCount2').innerHTML = Math.max(parseInt($('clubInvitationsCount2').innerHTML) -1, 0);
			}
		});
	},
	
	acceptInvitation: function(groupId, invitationNo)
	{
		new Ajax.Request(PUBLIC_URL+'ajax/accept-group-invitation',
		{
			method: 'post',
			postBody: Object.toQueryString({groupId: groupId, invitationNo: invitationNo}),
			onSuccess: function(transport) {
				function callback1() {
					$('group_invitation_'+invitationNo).innerHTML = transport.responseText;
					if($('group_invitation_'+invitationNo).innerHTML)
					{
						new Effect.BlindDown('group_invitation_'+invitationNo, {duration: 1, delay: 0.2});
					}
					if((!$('group_invitation_1') || $('group_invitation_1').innerHTML == '') && (!$('group_invitation_2') || $('group_invitation_2').innerHTML == ''))
					{
						new Effect.BlindUp('groupInvitations', {duration: 1, delay: 0.2});
					}
				}
				new Effect.BlindUp('group_invitation_'+invitationNo, {duration: 1, delay: 0.2, afterFinish: callback1});
				$('clubInvitationsCount').innerHTML = Math.max(parseInt($('clubInvitationsCount').innerHTML) - 1, 0);
				$('clubInvitationsCount2').innerHTML = Math.max(parseInt($('clubInvitationsCount2').innerHTML) -1, 0);
			}
		});
	},
        moreSubjects: function(lastID, pageNum, groupID, lastDate)
        {
            pageNum=parseInt(pageNum)>0 ? pageNum : 0;
            $('more_container_'+lastID).style.display='none';
            $('feedLoadImg_'+lastID).style.display='block';
            new Ajax.Request(PUBLIC_URL + 'group/more-topics',
            {
                method: 'post',
                parameters: {num: pageNum, ID: groupID, lastTopic: lastDate },
                onSuccess: function(transport) {
                    $('subject_container').innerHTML+=transport.responseText;
                    $('feedLoadImg_'+lastID).style.display='none';
                    if(groups.showDelete)groups.attachMouseEvent();
                }
            });
        },
        fitToText: function (textArea)
        {
            textArea.style.height = 36+"px";
            if(textArea.scrollHeight < 36){
                textArea.style.height = 36+"px";
            } else {
		textArea.style.height = textArea.scrollHeight+"px";
            }
        },
        setDefaultText: function(defaultText, textEl) {
            if (textEl.value == "") {
		textEl.value = defaultText;
            }
	},
	resetDefaultText: function(defaultText, textEl) {
            if (textEl.value == defaultText) {
		textEl.value = "";
            }
	},
        emoticon: function(text, txtarea, defaultText) {
            if (txtarea.value == defaultText) {
		txtarea.value = "";
            }
            text = ' ' + text + ' ';
            if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
		txtarea.scrollTop = txtarea.scrollHeight;
            } else {
		txtarea.value  += text;
		txtarea.focus();
		txtarea.scrollTop = txtarea.scrollHeight;
            }
	},
        addComment: function(groupID, topicID, userID, master, defaultText){
            var lang = this.lang;
            if (userID == 0) {
		document.location = PUBLIC_URL+'signin';
            }
            if ((!$('popup_text_'+topicID).value) || ($('popup_text_'+topicID).value==defaultText)) {
		return false;
            }
            new Ajax.Request(PUBLIC_URL + 'group/add-post',
            {
                method: 'post',
                parameters: {groupId: groupID, topicId: topicID, postId: 0, subject: $('popup_text_'+topicID).value, isMaster: master },
                onSuccess: function(transport) {

                    $('subject_comment_'+topicID).insert({ top: transport.responseText});
                    $('popup_text_'+topicID).value='';
                    $('comment_popup_'+topicID).style.display='none';

                    return false;
                }
            });
        },
        addSubject: function(groupID, defaultText){
            if ($('form_text').value==defaultText)
                return false;
            new Ajax.Request(PUBLIC_URL + 'group/add-topic',
            {
                method: 'post',
                parameters: {groupId: groupID, subject: $('form_text').value },
                onSuccess: function(transport) {
                    $('subject_container').insert({top: transport.responseText });
                    $('more_container_'+transport.headerJSON.myTopicId).style.display='none';
                    $('form_text').value='';
                }

            });
        },
        countRemainingChars: function(maxLength)
	{
		var text = $('form_text');
		text.style.height = 36+"px";
		if(text.scrollHeight < 36){
			text.style.height = 36+"px";
		} else {
			text.style.height = text.scrollHeight+"px";
		}
		currentLength = text.value.length;
		if (!currentLength)
			return false;

		if (currentLength > maxLength) {
			$('characters_left').innerHTML = 0;
			text.value = text.value.substring(0, maxLength);
		} else {
			$('characters_left').innerHTML = maxLength - currentLength;
		}
	},
        showConfirmBoxDeleteComment: function(groupId, topicId) {
		Event.stopObserving('my_close_button_'+topicId, 'click');
		var confirmBox = $('popupBoxConfirmComment_delete');

		var xCenter = Math.round(document.viewport.getWidth() / 2);
		var yCenter = Math.round(document.viewport.getHeight() / 2) + document.viewport.getScrollOffsets().top;
		var boxW = Math.round(confirmBox.getWidth() / 2);
		var boxH = Math.round(confirmBox.getHeight() / 2);

		confirmBox.absolutize();
		confirmBox.style.left = (xCenter - boxW)  + 'px';
		confirmBox.style.top = (yCenter - boxH) + 'px';
		confirmBox.show();
		Event.observe(document, 'keypress', function(event) {
			if(event.keyCode == Event.KEY_ESC) {
				groups.hideConfirmBoxComment();
			}
		});
		Event.observe($('okConfirmBtn_delete'), 'click', function() {
			groups.removeTopic(groupId,topicId);
                        groups.hideConfirmBoxComment();
		});
	},
        hideConfirmBoxComment: function() {
		Event.stopObserving('okConfirmBtn_delete', 'click');
		Event.stopObserving(document, 'keypress');
		$('popupBoxConfirmComment_delete').hide();
	},
        addNewPost: function(groupID, topicID, userId, master){
            var lang = this.lang;
            if (userId == 0) {
		document.location = PUBLIC_URL+'signin';
            }
            if (!$('form_text').value) {
		return false;
            }
            new Ajax.Request(PUBLIC_URL + 'group/add-post',
            {
                method: 'post',
                parameters: {groupId: groupID, topicId: topicID, postId: 0, subject: $('form_text').value, isMaster: master, source: 'post'},
                onSuccess: function(transport) {

                    $('topic_post_container').insert({ top: transport.responseText});
                    $('form_text').value='';
                    return false;
                }
            });
        }
}

var groups = new Groups();
