$j(document).ready(function(){
	if ($j("#notice-board-min").length > 0) {
		$j("#notice-board-min").fadeIn("slow").find("a").click(function(){
			$j("#notice-board-min").slideUp("fast", function(){
				$j("#notice-board").slideDown().find("a#close-link").click(function(){
					$j("#notice-board").slideUp("normal", function(){
						$j("#notice-board-min").slideDown();
					});
				});
			});
		});
	}
	// set pagination
	Notices.setLinkObservers();
});

var Notices = {
	getPage: function(page) {
		new Ajax.Request('./notice-board/ajax/' + page + '/', {
			method: 'get',
			onSuccess: function(transport) {
				var response = transport.responseJSON;
				if (response.msg!='OK') {
					alert(response.msg);
				}
				
				// Rattle through our response and pop it in
				$('notice-list').update('');
				
				for (var i = 0; i < response.data.length; i++) {
					var notice = new Element('div', {'class':'notice'});
					if (i%2!=0) notice.addClassName('notice-alt');
					if (response.data[i].sticky == 1) notice.addClassName('sticky');
					var title = new Element('h3');
					title.update(new Element('a', {'href':'./notice-board/' + response.data[i].url + '/'}).update(response.data[i].title));
					title.insert(new Element('span', {'class':'light'}).update('Posted @ ' + response.data[i].created));
					notice.update(title);
					
					var para = new Element('p').update(response.data[i].content);
					var link = new Element('a', {'href':'./notice-board/' + response.data[i].url + '/'}).update('read more &raquo;');
					para.insert(link);
					notice.insert(para);
					
					$('notice-list').insert(notice);
				}
				
				// Update the pagination and the showing message
				$('notice-pagination').update('');
				for (var i = 1; i < response.max+1; i++) {
					if (response.current == i) {
						$('notice-pagination').insert(new Element('span').update(i));
					} else {
						$('notice-pagination').insert(new Element('a', {'href':'javascript://'}).update(i));
					}
					$('notice-pagination').insert(' ');
				}
				$('showing-msg').update('(showing ' + response.showing + ')');
				
				Notices.setLinkObservers();
			}
		});
	},
	setLinkObservers: function() {
		if ($j("#notice-pagination").length > 0) {
			$j("#notice-pagination a").each(function(){
				$j(this).unbind("click").click(function(){
					$j("#notice-list").html("<div id=\"loading\" style=\"background:#fff;border-left:1px solid #000033;border-right:1px solid #000033;text-align:center;padding-top:10px;padding-bottom:10px;\">"+
					"<img src=\"images/ajax-loader.gif\" alt=\"loading...\" style=\"vertical-align:middle;\" /><br/>loading..."+
					"</div>");
					Notices.getPage($j(this).html());
				});
			});
		}
	}
};