/************************************************/
/* IPB3 Javascript								*/
/* -------------------------------------------- */
/* ips.forums.js - Forum view code				*/
/* (c) IPS, Inc 2008							*/
/* -------------------------------------------- */
/* Author: Rikki Tissier						*/
/************************************************/

var _forums = window.IPBoard;

_forums.prototype.forums = {
	totalChecked: 0,
	showMod: [],
	fetchMore: {},
	
	init: function()
	{
		Debug.write("Initializing ips.forums.js");

		document.observe("dom:loaded", function(){
			ipb.forums.initEvents();
		});
	},
	initEvents: function()
	{
		if( $('forum_load_more') ){
			$('forum_load_more').observe('click', ipb.forums.loadMore);
			$('more_topics').show();
		}
		
		/* Set up mod checkboxes */
		if( $('tmod_all') )
		{ 
			ipb.forums.preCheckTopics();
			$('tmod_all').observe( 'click', ipb.forums.checkAllTopics );
		}
		
		if ( $("moderator_toggle") )
		{
			$("moderator_toggle").on( 'click', ipb.forums.openModPanel );
		}
		
		ipb.delegate.register(".topic_mod", ipb.forums.checkTopic );
		ipb.delegate.register(".t_rename", ipb.forums.topicRename );
	},
	
	loadMore: function(e)
	{
		Event.stop(e);		
		if( !ipb.forums.fetchMore ){ return; }
				
		ipb.forums.fetchMore['st'] = parseInt(ipb.forums.fetchMore['st']) + parseInt(ipb.forums.fetchMore['max_topics']);
		
		var url = ipb.vars['base_url'] + "app=forums&module=ajax&section=forums&do=getTopics&md5check="+ipb.vars['secure_hash'] + "&" + $H(ipb.forums.fetchMore).toQueryString();
		Debug.write( url );
		new Ajax.Request( url.replace(/&amp;/g, '&'),
						{
							method: 'get',
							evalJSON: 'force',
							onSuccess: function(t){
								Debug.dir( t.responseJSON );
								if( t.responseJSON['topics'] == '' )
								{
									$('forum_load_more').replace("<span class='desc lighter'>"+ipb.lang['no_more_topics']+"</span>");
									return;
								}
								$$('tbody.dynamic_update').invoke("removeClassName", "dynamic_update");
								var newtbody = new Element("tbody", {'class': 'dynamic_update'});
								$('forum_table').select('tbody:last')[0].insert({ 'after': newtbody});
								newtbody.update( t.responseJSON['topics'] );
								$$('.pagination').invoke("replace", t.responseJSON['pages']);
								
								if( t.responseJSON['topics'] == '' || t.responseJSON['hasMore'] == false)
								{
									$('forum_load_more').replace("<span class='desc lighter'>"+ipb.lang['no_more_topics']+"</span>");
									return;
								}								
							}
						});
	},
	
	submitModForm: function(e)
	{
		// Check for delete action
		if( $F('mod_tact') == 'delete' ){
			if( !confirm( ipb.lang['delete_confirm'] ) ){
				Event.stop(e);
			}
		}
		
		// Check for merge action
		if( $F('mod_tact') == 'merge' ){
			if( !confirm( ipb.lang['delete_confirm'] ) ){
				Event.stop(e);
			}
		}
	},

	topicRename: function(e, elem)
	{
		if( DISABLE_AJAX ){
			return false;
		}
		
		Event.stop(e);
		
		// We need to find the topic concerned
		var link = $(elem).up('.__topic').down('a.topic_title');
		if( $( link ).readAttribute('showingRename') == 'true' ){ return; }
		
		// Create elements
		var temp = ipb.templates['topic_rename'].evaluate( { 	inputid: link.id + '_input',
																submitid: link.id + '_submit',
																cancelid: link.id + '_cancel',
																value: link.innerHTML.unescapeHTML().replace( /'/g, "&#039;" ).replace( /</g, "&lt;" ).replace( />/g, "&gt;" ) } );
																
		$( link ).insert( { before: temp } );
		
		// Event handlers
		$( link.id + '_input' ).observe('keydown', ipb.forums.saveTopicRename );
		$( link.id + '_submit' ).observe('click', ipb.forums.saveTopicRename );
		$( link.id + '_cancel' ).observe('click', ipb.forums.cancelTopicRename );	
		
		$( link ).hide().writeAttribute('showingRename', 'true');
	},
	
	cancelTopicRename: function(e)
	{
		var elem = Event.element(e);
		if( !elem.hasClassName( '_cancel' ) )
		{
			elem = Event.findElement(e, '.cancel');
		}
		
		try {
			var tid = elem.up('tr').id.replace( 'trow_', '' );
		} catch(err){ Debug.write( err ); return; }
		
		var linkid = 'tid-link-' + tid;
		
		if( $(linkid + '_input') ){ 
			$( linkid + '_input' ).remove();
		}
		
		if( $( linkid + '_submit' ) ){
			$( linkid + '_submit' ).remove();
		}
		
		$( linkid + '_cancel' ).remove();
		
		$( linkid ).show().writeAttribute('showingRename', false);
		
		Event.stop(e);		
	},
	
	saveTopicRename: function(e)
	{
		elem = Event.element(e);
		if( e.type == 'keydown' )
		{
			if( e.which != Event.KEY_RETURN )
			{
				return;
			}
		}
		
		try {
			tid = elem.up('tr').id.replace( 'trow_', '' );
		} catch(err){ Debug.write( err ); return; }
		
		new Ajax.Request( ipb.vars['base_url'] + "app=forums&module=ajax&section=topics&do=saveTopicTitle&md5check="+ipb.vars['secure_hash']+'&tid='+tid,
						{
							method: 'post',
							evalJSON: 'force',
							parameters: {
								'name': $F('tid-link-' + tid + '_input').replace( /&#039;/g, "'" ).encodeParam()
							},
							onSuccess: function(t)
							{
								if( Object.isUndefined( t.responseJSON ) )
								{
									alert( ipb.lang['action_failed'] );
								}
								else if ( t.responseJSON['error'] )
								{
									alert( ipb.lang['error'] + ": " + t.responseJSON['error'] );
								}
								else
								{
									$('tid-link-' + tid ).update( t.responseJSON['title'] );
									$('tid-link-' + tid ).href = t.responseJSON['url'];
								}
								
								$('tid-link-' + tid + '_input').hide().remove();
								$('tid-link-' + tid + '_submit').hide().remove();
								$('tid-link-' + tid + '_cancel').hide().remove();
								$('tid-link-' + tid).show().writeAttribute('showingRename', false);
							}
						});
	},

	preCheckTopics: function()
	{	
		if( !$('selectedtids') ){ return; }
		
		topics = $F('selectedtids').split(',');
		
		if( topics )
		{
			topics.each( function(check){
				if( check != '' )
				{
					if( $('tmod_' + check ) )
					{
						$('tmod_' + check ).checked = true;
					}
					
					ipb.forums.totalChecked++;
				}
			});
		}
		
		ipb.forums.updateTopicModButton();
	},				
	checkAllTopics: function(e)
	{
		Debug.write('checkAllTopics');
		check = Event.findElement(e, 'input');
		toCheck = $F(check);
		ipb.forums.totalChecked = 0;
		toRemove = new Array();
		selectedTopics = $F('selectedtids').split(',').compact();
		
		$$('.topic_mod').each( function(check){
			if( toCheck != null )
			{
				check.checked = true;
				selectedTopics.push( check.id.replace('tmod_', '') );
				ipb.forums.totalChecked++;
			}
			else
			{
				toRemove.push( check.id.replace('tmod_', '') );
				check.checked = false;
			}
		});
		
		selectedTopics = selectedTopics.uniq();
		
		if( toRemove.length >= 1 ){
			for( i=0; i<toRemove.length; i++ ){
				selectedTopics = selectedTopics.without( parseInt( toRemove[i] ) );
			}
		}
		
		selectedTopics = selectedTopics.join(',');
		ipb.Cookie.set('modtids', selectedTopics, 0);
		
		$('selectedtids').value = selectedTopics;
		
		ipb.forums.updateTopicModButton();
		ipb.forums.openModPanel();
	},
	checkTopic: function(e)
	{
		remove = new Array();
		check = Event.findElement( e, 'input' );
		selectedTopics = $F('selectedtids').split(',').compact();
		
		if( check.checked == true )
		{
			selectedTopics.push( check.id.replace('tmod_', '') );
			ipb.forums.totalChecked++;
		}
		else
		{
			remove.push( check.id.replace('tmod_', '') );
			ipb.forums.totalChecked--;
		}
		
		selectedTopics = selectedTopics.uniq().without( remove ).join(',');		
		ipb.Cookie.set('modtids', selectedTopics, 0);
		
		$('selectedtids').value = selectedTopics;

		ipb.forums.updateTopicModButton();
		ipb.forums.openModPanel();
	},
	openModPanel: function( e )
	{
		if( e ){
			Event.stop(e);
		}
		
		if( $('topic_mod') && $('moderator_toggle') && ! $('topic_mod').visible() ){
			$('moderator_toggle').up('li').hide();
			new Effect.BlindDown( $('topic_mod'), { duration: 0.3 } );
		}
	},
	updateTopicModButton: function( )
	{
		if( $('mod_submit') )
		{
			var _v = $('mod_tact').options[ $('mod_tact').selectedIndex ].value;
			
			if ( _v.match( /^t_/ ) )
			{
				$('mod_submit').disabled = false;
				$('mod_submit').value    = ipb.lang['justgo'];
			}
			else
			{
				if( ipb.forums.totalChecked == 0 ){
					$('mod_submit').disabled = true;
				} else {
					$('mod_submit').disabled = false;
				}
			
				$('mod_submit').value = ipb.lang['with_selected'].replace('{num}', ipb.forums.totalChecked);
			}
		}
	},
	
	retrieveAttachments: function( id )
	{
		url = ipb.vars['base_url'] + "&app=forums&module=ajax&secure_key=" + ipb.vars['secure_hash'] + '&section=attachments&tid=' + id;
		popup = new ipb.Popup( 'attachments', { type: 'pane', modal: false, w: '500px', h: '600px', ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
		return false;
	},
	
	retrieveWhoPosted: function( tid )
	{
		if( parseInt(tid) == 0 )
		{
			return false;
		}
		
		url = ipb.vars['base_url'] + "&app=forums&module=ajax&secure_key=" + ipb.vars['secure_hash'] + '&section=stats&do=who&t=' + tid;
		popup = new ipb.Popup( 'whoPosted', { type: 'pane', modal: false, w: '500px', h: 400, ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
		return false;
	}
};

ipb.forums.init();
