var CCA;

CCA = {
	setSortableCols: function() {
	
		$('div.column').Sortable({
			accept: 'box',
			helperclass: 'sortHelper',
			activeclass : 	'sortableactive',
			hoverclass : 	'sortablehover',
			handle: 'div.boxheader',
			tolerance: 'pointer',
			opacity: 0.9,
			onChange : function(ser){

			},
			onStart : function(){
				$.iAutoscroller.start(this, document.getElementsByTagName('body'));
			},
			onStop : function(){
				$.iAutoscroller.stop();
				serialize();
			}
		});
	},
	comments: function() {
		var articleId = $('.comm_article').attr("id").split('_')[1];
		$.getJSON('data/comments_json.js',{article_id:articleId},function(json){
			var elemnts = $('div.comm_article .boxbody').children();
			$.each(json.allcomments, function(i,commnts){

				//can i extract the comment markup??
				var comments_html = '';
				$(commnts.blockcomments).each(function(i){
					comments_html += '<li><b>' + this.user + '</b> on ' + this.date + '<br /><i>' +  this.comment + '</i></li>';
				});

				$(elemnts[commnts.elem_pos]).before('<div class="comment_block">\
				<a href="#" class="comment_count" id="comments_'+i+'"><span>' + (commnts.count) + '</span> comments</a>\
				<div class="comments_popup"><div class="comments_popup_header"><a href="#" class="close">close</a></div><div class="comments_container"><ol>'+ comments_html +'</ol></div></div>\
				</div>');		
			});
			//now create some html elems for other elemnts with no comments yet
			$(elemnts).each(function(i){
				if($(this).prev('.comment_block').length < 1){
					$(this).before('<div class="comment_block">\
					<a href="#" class="comment_count" id="comments_'+i+'"><span>0</span> comments</a>\
					<div class="comments_popup"><div class="comments_popup_header"><a href="#" class="close">close</a></div><div class="comments_container"><ol></ol></div></div>\
					</div>');
					//'+ CCA.createCommentsForm(articleId,i) +'
				}
			});
			
			//register event for closing popup
			$('a.close').click(function(){
				$(this).parents('.comments_popup').hide();
				return false;
			});

			//outsource this
			CCA.popups(articleId);
			
/*
			$('form.comment_form').submit(function(){
			
				$.post("serversidephp.html",
				  { user: "John", comment: "hello, my name is earl" },
				  function(data){
					alert("Data Loaded: " + data);
				  }
				);			
			});
*/


		});
	
	},
	
	createCommentsForm: function(article_id,pos){
		//create a generic form into which can be injected id's, node position etc.
		var form_html = '<form action="submit_comment" class="comment_form">\
		<input type="hidden" name="user_id" value="' + current_user + '"/>\
		<input type="hidden" name="todays_date" value="' + today + '"/>\
		<input type="hidden" name="article_id" value="' + article_id + '"/>\
		<input type="hidden" name="element_pos" value="' + pos + '"/>\
		<label>Add your comment:</label>\
		<textarea name="comment_text"></textarea><br />\
		<button type="submit">Post Comments</button></form>';
		return form_html;
	},

	removeCommentsForm: function(){
		$('#comment_form').remove();
	},

	submitCommentsData: function(){

	},
	popups: function(articleId){
	
		$("a.comment_count").hover(function(){
			$(this).parent('.comment_block').next().addClass("hover");
		},function(){
			$(this).parent('.comment_block').next().removeClass("hover");
		});		
	
		$('a.comment_count').click(function(){
			//close any other open comment boxes
			$('div.comments_popup').not($(this).siblings('div.comments_popup')).hide();
			
			//then toggle visibility of this one
			$(this).siblings('div.comments_popup').toggle();
			
			//if one doesnt already exist generate form for comments
			if($(this).siblings('div.comments_popup').find('form.comment_form').length < 1){
				var nodenumber = $(this).attr("id").split('_')[1];
				$(this).siblings('div.comments_popup').children('div.comments_container').append(CCA.createCommentsForm(articleId,nodenumber));
				
				//register submit event for form
				$('form.comment_form').submit(CCA.handleFormSubmit);

			}
			return false;
		});
	},
	handleFormSubmit: function(){
		if($(this).children('textarea').val() == ''){
			//show an error message if one doesnt already exist
			if($(this).children('strong.error').length < 1){
				$(this).prepend('<strong class="error">Please enter a comment</strong>');
			}
			return false;
		}else{
			$(this).children('strong.error').remove();
			//submit form data to server using ajax post
			var postData = $(this).children('form.comment_form :input').serialize();
			//$.post('serversidecode.php', postData, function(data){

			//});
	
			//must move into $.post above so its reliant on the callback method  
			//render comment in list so dont have to refresh page
			$(this).siblings('ol').append('<li><b>' + $(this).children('input[@name=user_id]').val() +'</b> on ' + $(this).children('input[@name=todays_date]').val() + '<br /><i>' + $(this).children('textarea').val().replace(new RegExp( "\\n", "g" ),'<br />') + '</i></li>');
			//update number of comments displayed
			$(this).parents('div.comments_popup').siblings('.comment_count').children('span').text(parseInt($(this).parents('div.comments_popup').siblings('.comment_count').children('span').text()) + 1);
			//clear textarea for next comment
			$(this).children('textarea').val('');
			return false;
		}
	}
}



$(document).ready(function(){

	//homepage
	if(document.getElementById('sort1')){
		CCA.setSortableCols();
	}
	
	//members lpc report
	$('#lpc_meeting_report select#commitee').change(function(){
		$.getJSON('data/members_json.js',{lpc_group_id:"1234"},function(json){
			$('#lpc_group_members ul.checkboxes').empty();
			$.each(json.members, function(i,member){
				$('#lpc_group_members ul.checkboxes').append('<li><input type="checkbox" value="' + member.member_id + '" \/> <label>' + member.usersname + '<\/label><\/li>');
			});
		});
	});

	$('#wk_to').change(function(){
		if($(this).val() == '0'){
			$('#year_to').val('0');
		}
	});
	
	if($('.dateinput').length){
		$(".dateinput").datepicker({speed:''});
	}

	$('#all_lpc_groups, #all_cats, #all_peeps').click(function(){
		if(this.checked == true){
			$('.lpc, .cat, .peep').attr('checked','true');
		}
		else{
			$('.lpc, .cat, .peep').attr('checked','');
		}
	});

	$('.lpc, .cat, .peep').click(function(){
		if(this.checked == false){
			$('#all_lpc_groups, #all_cats, #all_peeps').attr('checked','');
		}
	});
	
	//$('div#group_mngmt').hide();	
	
	$('a#show_group_mngmt').click(function(){
		$('div#group_mngmt').toggle();
	});

	$('a#close_group_mngmt').click(function(){
		$('div#group_mngmt').hide();
	});

	$('#forum_board table tbody tr, #forum_home table tbody tr').hover(function(){
		$(this).css('cursor','pointer').css('background-color','#d3eae3');
	},function(){
		$(this).css('cursor','default').css('background-color','transparent');
	});
	
	$('#forum_board table tbody tr, #forum_home table tbody tr').click(function(){
		window.location.href = $(this).find('a').attr('href');
		//console.log($(this).find('a'));
	});
	
	
	$('a.users_groups_edit').click(function(){
		$(this).parent().find('div.users_groups').toggle();
		return false;
	});

	$('.users_groups input').click(function(){
		//post value to server with add or remove instruction
		console.log($(this).val());
		//when getting response from server post 'saved' message which flashes and fades
		$(this).parent().parent().append('<div>saved</div>');
	});
	
	$('div#admin_register #lpc_groups').hide();
	$('#lpc_member').click(function(){
		//$('div#adminregister #lpc_groups').toggle();
		if(this.checked == true){
			$('div#admin_register #lpc_groups').show();
		}
		else{
			$('div#admin_register #lpc_groups').hide();
		}
	});
	

	/* comments system */

	if($('.comm_article').length > 0){
		//if article page, get json object of comments	
		CCA.comments();
	}


});

function serialize(s)
{
	serial = $.SortSerialize(s);
	//console.log(serial.hash);
	//alert(serial.hash);
};
