jQuery(document).ready(function(){
	jQuery('.reply-link').click(function(){
		var comment_id = (jQuery(this).attr('comment_id'));
		var holder = $(this).parents('.comment-holder').find('.resp-form-holder');
		msg_form(holder,comment_id);
		return false;
	});
	
	jQuery('.arrow,.arrow-opened').click(function(){
		jQuery(this).next('.comment-title').click();
	});
	
	jQuery('.comment-title').click(function(){
		var comment_id = jQuery(this).attr('id').split('_').slice(-1);
		jQuery('#comment_content_' + comment_id).slideToggle();
		jQuery(this).prev('.arrow,.arrow-opened').toggleClass('arrow').toggleClass('arrow-opened');
	});
	
	jQuery('.close-comment').click(function(){
		jQuery(this).parents('.comment-content').slideUp('slow');
	});
	
	jQuery('.new_thread').click(function(){
		msg_form($('.msg-form-holder'),0);
	});
	
	jQuery('.join-forum').click(function(){
		var forumId = $(this).attr('forum_id');
		var isRemove = $(this).attr('remove');
		$(this).html('אנא המתן...');
		jQuery.ajax({
			url:forum_url,
			success:function(data){
				if(data == 1){
					document.location.reload();
				}else{
					alert('אירעה שגיאה.');
				}
				
			},
			data:{
				forum_id:forumId,
				action:'join',
				remove:isRemove
			}
		});
	});
	
});


function msg_form(holder,reply_to_id){
	if($(holder).html()!=''){
		$(holder).find('.msg_form').slideUp('slow',function(){
			$(this).remove();
			holder.hide();
		});
		return true;				
	}
	if(typeof(reply_to_id) == 'undefined')
	{
		reply_to_id = 0;
	}
	holder.show();
	var html = $('.form-template').html();
	var title = 'הוספת הודעה';
	if(reply_to_id > 0){
		title = 'הוספת תגובה';
	}
	html = html.replace(/\[title\]/i,title);

	var div = $('<div></div>').attr('id','msg_form').addClass('msg_form').html(html);
	div.find('form').submit(function(){
		var name  = $(this).find('[name=author]');
		var email = $(this).find('[name=email]');
		var subject = $(this).find('[name=subject]');
		var comment = $(this).find('[name=comment_area]');
		
		
		if(name.val() == ''){
			alert('יש להזין שם');
			name.focus();
			return false;
		}
		
		
		if(email.val() == ''){
			alert('יש להזין כתובת אי-מייל');
			email.focus();
			return false;
		}
		
		
		if(subject.val() == ''){
			alert('יש להזין נושא');
			subject.focus();
			return false;
		}
		var new_val = subject.val() + "\n" + comment.val();
		$(this).find('[name=comment]').val(new_val);
		return true;
	});
	
	div.find('[name=comment_parent]').val(reply_to_id);
	
	div.appendTo(holder);
	
	div.slideDown('slow').find('.close-frm').click(function(){
		$(this).parents('.msg_form').slideUp('slow',function(){
			$(this).remove();
		});
	});
}
