/**
 * Product Title:		Tutorials
 * Product Version:		1.3.0
 * Author:				Michael McCune
 * Website:				Invision Focus
 * Website URL:			http://invisionfocus.com/
 * Email:				michael.mccune@gmail.com
 */

var _tut = window.IPBoard;

_tut.prototype.tutorials = {
	postcache: '',
	copycats: null,
	movecats: null,
	postcats: null,
	totalChecked: 0,
	showMod: [],
	
	init: function()
	{
		Debug.write("Initializing ips.tutorials.js");
		
		document.observe("dom:loaded", function()
		{
			/* Set up mod checkboxes */
			if ( $('check_all') )
			{ 
				ipb.tutorials.preCheckArticles();
				$('check_all').observe( 'click', ipb.tutorials.checkAllArticles );
			}
			
			$$('.article_mod').each
			(
				function( check )
				{
					check.observe( 'click', ipb.tutorials.checkArticle );
				}
			);
			
			ipb.delegate.register( '.delete_article', ipb.tutorials.confirmDeleteArticle );
			ipb.delegate.register( '.view_more_link', ipb.tutorials.showHiddenContent );
			ipb.delegate.register( '.toggle_article', ipb.tutorials.toggleArticleApprove );
			ipb.delegate.register( '.edit_article'  , ipb.tutorials.editArticleShow );
			ipb.delegate.register( '.copy_article'  , ipb.tutorials.getCopyLocations );
			ipb.delegate.register( '.move_article'  , ipb.tutorials.getMoveLocations );
			ipb.delegate.register( '.t_rename', ipb.tutorials.articleRename );
			ipb.delegate.register( '.t_delete', ipb.tutorials.confirmDeleteArticle );
			
			$$( ".tutorialButton" ).each( function( elem )
			{
				$( elem ).identify();
				$( elem ).show();
				$( elem ).observe( 'click', ipb.tutorials.copyPost );
			});
			
			if ( $('mem_name') )
			{
				new ipb.Autocomplete( $('mem_name'), { multibox: false, url: ipb.vars['base_url'] + 'app=core&module=ajax&section=findnames&do=get-member-names&secure_key=' + ipb.vars['secure_hash'] + '&name=', templates: { wrap: ipb.templates['autocomplete_wrap'], item: ipb.templates['autocomplete_item'] } } );
			}
			
			$$('.post').each( function(elem){
				ipb.global.findImgs( $( elem ) );
			});
			
			if ( $('cat') )
			{
				$('cat').observe( "change", ipb.tutorials.jumpToCategory );
				$('cat_jump_submit').hide();
			}
			
			if ( $('show_filters') )
			{
				$('show_filters').observe('click', ipb.tutorials.toggleFilters );
				$('filter_form').hide();
			}
			
			if ( !Object.isUndefined( ipb.hoverCard ) )
			{
				var ajaxUrl = ipb.vars['base_url'] + '&app=tutorials&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=articles&do=preview';
				ipb.hoverCardRegister.initialize( 'articlePreview', { 'w': '400px', 'delay': 750, 'position': 'auto', 'ajaxUrl': ajaxUrl, 'getId': true } );
			}
		});
	},
	
	articleRename: function(e, elem)
	{
		/* No ajax? */
		if ( DISABLE_AJAX )
		{
			return false;
		}
		
		Event.stop(e);
		
		/* We need to find the article concerned */
		var link = $(elem).up('.__article').down('a.article_title');
		if( $( link ).readAttribute('showingRename') == 'true' ){ return; }
		
		/* Create elements */
		var temp = ipb.templates['article_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.tutorials.saveArticleRename );
		$( link.id + '_submit' ).observe('click', ipb.tutorials.saveArticleRename );
		$( link.id + '_cancel' ).observe('click', ipb.tutorials.cancelArticleRename );	
		
		$( link ).hide().writeAttribute('showingRename', 'true');
	},
	
	cancelArticleRename: 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);		
	},
	
	saveArticleRename: function(e)
	{
		elem = Event.element(e);
		
		if ( e.type == 'keydown' )
		{
			if ( e.which != Event.KEY_RETURN )
			{
				return;
			}
		}
		
		try
		{
			id = elem.up('tr').id.replace( 'trow_', '' );
		}
		catch( err )
		{
			Debug.write( err );
			return;
		}
		
		new Ajax.Request
		(
			ipb.vars['base_url'] + "app=tutorials&module=ajax&section=articles&do=saveTutorialTitle&md5check="+ipb.vars['secure_hash']+'&id='+id,
			{
				method: 'post',
				evalJSON: 'force',
				parameters:
				{
					name: $F('tid-link-' + id + '_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-' + id ).update( t.responseJSON['title'] );
						$('tid-link-' + id ).href = t.responseJSON['url'];
					}
					
					$('tid-link-' + id + '_input').hide().remove();
					$('tid-link-' + id + '_submit').hide().remove();
					$('tid-link-' + id + '_cancel').hide().remove();
					$('tid-link-' + id).show().writeAttribute('showingRename', false);
				}
			}
		);
	},
	
	editArticleShow: function( e, elem )
	{
		/* No ajaxiness? */
		if ( DISABLE_AJAX )
		{
			return false;
		}
		
		/* If user is holding ctrl or command, just submit since they want to open a new tab */
		if ( e.ctrlKey == true || e.metaKey == true || e.keyCode == 91 )
		{
			return false;
		}
		
		/* INIT */
		Event.stop(e);
		var edit = [];
		
		/* Who's got the button? */
		edit['button'] = elem;
		if ( !edit['button'] ){ return; }
		
		/* Set some vars */
		edit['aid'] = edit['button'].id.replace('edit_article_', '');
		edit['post'] = $( 'article_' + edit['aid'] ).down('.post');
		
		/* Find post content */
		ipb.tutorials.postcache = edit['post'].innerHTML;
		url = ipb.vars['base_url'] + 'app=tutorials&module=ajax&section=articles&do=editBoxShow&id=' + edit['aid'];
		
		/* Scrollage */
		if ( Prototype.Browser.IE7 )
		{
			window.location = '#article_' + edit['aid'];
		}
		else
		{
			new Effect.ScrollTo( edit['post'], { offset: -50 } );
		}
		
		/* DO TEH AJAX LOL */
		new Ajax.Request
		(
			url, 
			{
				method: 'post',
				parameters:
				{
					md5check: ipb.vars['secure_hash']
				},
				onSuccess: function(t)
				{
					/* Errors */
					if ( t.responseText == 'no_article' || t.responseText == 'no_edit_article' )
					{
						alert( ipb.lang['no_permission'] );
						return;
					}
					if ( t.responseText == 'error' )
					{
						alert( ipb.lang['action_failed'] );
						return;
					}
					
					/* Put it in */
					edit['post'].update( t.responseText );
					edit['aid'] = 'e' + edit['aid'];
					
					/* Set up events */
					if ( $('edit_save_' + edit['aid'] ) )
					{
						$('edit_save_' + edit['aid'] ).observe('click', ipb.tutorials.ajaxEditSave );
					}
					if ( $('edit_switch_' + edit['aid'] ) )
					{
						$('edit_switch_' + edit['aid'] ).observe('click', ipb.tutorials.ajaxEditSwitch );
					}
					if ( $('edit_cancel_' + edit['aid'] ) )
					{
						$('edit_cancel_' + edit['aid'] ).observe('click', ipb.tutorials.ajaxEditCancel );
					}
				}
			}
		);
	},
	
	ajaxEditSave: function(e)
	{
		/* INIT */
		Event.stop(e);
		var elem = Event.element(e);
		var postid = elem.id.replace('edit_save_e', '');
		var pageno = $('article_page').value;
		if ( !postid ) { return; }
		
		var Post = ipb.textEditor.getEditor().getText();
		
		/* Blank?  Well, that won't work... */
		if ( Post.blank() )
		{
			alert( ipb.lang['post_empty'] );
			return;
		}
		
		/* HTML? */
		var post_htmlstatus = '';
		
		if ( $('post_htmlstatus') )
		{
			post_htmlstatus = $F('post_htmlstatus');
		}
		
		/* Urly burly */
		var url = ipb.vars['base_url'] + 'app=tutorials&module=ajax&section=articles&do=editBoxSave&id=' + postid + '&_st=' + pageno;
		
		/* Ajaxy bajaxy? */
		new Ajax.Request
		(
			url,
			{
				method: 'post',
				evalJSON: 'force',
				encoding: ipb.vars['charset'],
				parameters:
				{
					md5check: ipb.vars['secure_hash'],
					Post: Post.encodeParam(),
					post_htmlstatus: post_htmlstatus
				},
				onSuccess: function(t)
				{
					if ( t.responseJSON['error'] )
					{
						alert( t.responseJSON['error'] );
						return false;
					}
					else
					{
						ipb.textEditor.getEditor().remove();
						
						/* Update post */
						$('article_' + postid).down('.post').update( t.responseJSON['successString'] );
						
						/* Set the pagination */
						if ( t.responseJSON['pages'] )
						{
							if ( $('article_pages') )
							{
								$('article_pages').update( t.responseJSON['pages'] );
							}
							else
							{
								var _pages = new Element( 'div', { name: 'article_pages' } );
								_pages.update( t.responseJSON['pages'] );
								$('article_' + postid).down('.post').insert( {after : _pages} );
							}
						}
						else if ( $('article_pages') )
						{
							$('article_pages').remove();
						}
						
						/* Cleanup */
						ipb.global.findImgs( $( 'article_' + postid ).down('.post') );										
						prettyPrint();
					}
				}
			}
		);
	},
	
	ajaxEditSwitch: function(e)
	{
		/* INIT */
		Event.stop(e);
		var elem = Event.element(e);
		var postid = elem.id.replace('edit_switch_e', '');
		if ( !postid ){ return; }		
		var url = ipb.vars['base_url'] + 'app=tutorials&module=post&section=submit&do=edit_tutorial&id=' + postid + '&_from=quickedit';
		
		var Post = ipb.textEditor.getEditor().CKEditor.getData();
		
		/* Setup inline form elements */
		form = new Element('form', { action: url, method: 'post' } );
		textarea = new Element('textarea', { name: 'Post' } );
		md5check = new Element('input', { type: 'hidden', name: 'md5check', value: ipb.vars['secure_hash'] } );
		
		/* Opera needs "value", but don't replace the & or it will freak out at you */
		if ( Prototype.Browser.Opera )
		{
			textarea.value = Post;
		}
		else
		{
			textarea.value = Post.replace( /&/g, '&amp;' );
		}
		
		/* Add the form */
		form.insert( md5check ).insert( textarea ).hide();
		$$('body')[0].insert( form );
		
		/* Submit it */
		form.submit();
	},
	
	ajaxEditCancel: function(e)
	{
		/* INIT */
		Event.stop(e);
		var elem = Event.element(e);
		var postid = elem.id.replace('edit_cancel_e', '');
		if ( !postid ) { return; }
		
		/* Got saved text?  Put it back then */
		if ( ipb.tutorials.postcache )
		{
			ipb.textEditor.getEditor().remove();
			
			$( 'article_' + postid ).down('.post').update( ipb.tutorials.postcache );
			ipb.editors[ postid ] = null;
		}
		
		return;
	},
	
	toggleArticleApprove: function(e, elem)
	{
		if ( DISABLE_AJAX )
		{
			return false;
		}
		
		Event.stop(e);
		
		var artid = elem.id.replace( 'toggle_', '' );
		if ( !artid ){ return; }
		
		var toDo = ( $('article_' + artid).hasClassName( 'moderated' ) ) ? 'approve' : 'unapprove';
		var url = ipb.vars['base_url'] + 'app=tutorials&module=ajax&section=moderate&do=' + toDo + '&id=' + artid;
		
		new Ajax.Request
		(
			url,
			{
				method: 'post',
				evalJSON: 'force',
				parameters: {
					md5check: ipb.vars['secure_hash']
				},
				onSuccess: function(t)
				{
					if ( t.responseJSON['error'] )
					{
						switch ( t.responseJSON['error'] )
						{
							case 'noarticle':
								alert( ipb.lang['no_permission'] );
							break;
							case 'nopermission':
								alert( ipb.lang['no_permission'] );
							break;
						}
					}
					else
					{
						if ( toDo == 'approve' )
						{	
							$('article_' + artid).removeClassName( 'moderated' ).addClassName('ipsBox_container');
							$('toggle_text').update( ipb.lang['unapprove'] );
						}
						else
						{
							$('article_' + artid).addClassName( 'moderated' ).removeClassName('ipsBox_container');
							$('toggle_text').update( ipb.lang['approve'] );
						}
					}
				}
			}
		);
	},
	
	retrieveAttachments: function( id )
	{
		url = ipb.vars['base_url'] + "&app=tutorials&module=ajax&secure_key=" + ipb.vars['secure_hash'] + '&section=attachments&id=' + id;
		popup = new ipb.Popup( 'attachments', { type: 'pane',
												modal: true,
												w: '500px',
												h: '600px',
												ajaxURL: url,
												hideAtStart: false,
												close: 'a[rel="close"]'
											  }
							 );
		
		return false;
	},
	
	showHiddenContent: function( e, elem )
	{
		id = elem.id.match( 'showHiddenContent_([0-9]+)' )[1];
		Event.stop(e);
		popup = new ipb.Popup( 'hiddenContentPopup', { type: 'pane',
													   modal: true,
													   hideAtStart: false,
													   w: '600px',
													   initial: $('hiddenContent_' + id).innerHTML,
													   close: 'a[rel="close"]'
													 }
							 );
		return false;
	},
	
	preCheckArticles: function()
	{
		articles = $F('selectedaids').split(',');
		
		if ( articles )
		{
			articles.each( function(check)
			{
				if ( check != '' )
				{
					if ( $('amod_' + check ) )
					{
						$('amod_' + check ).checked = true;
					}
					
					ipb.tutorials.totalChecked++;
				}
			});
		}
		
		ipb.tutorials.updateArticleModButton();
	},				
	
	checkAllArticles: function(e)
	{
		Debug.write('checkAllArticles');
		check = Event.findElement(e, 'input');
		toCheck = $F(check);
		ipb.tutorials.totalChecked = 0;
		toRemove = new Array();
		selectedArticles = $F('selectedaids').split(',').compact();
		
		$$('.article_mod').each( function(check)
		{
			if ( toCheck != null )
			{
				check.checked = true;
				selectedArticles.push( check.id.replace('amod_', '') );
				ipb.tutorials.totalChecked++;
			}
			else
			{
				toRemove.push( check.id.replace('amod_', '') );
				check.checked = false;
			}
		});
		
		selectedArticles = selectedArticles.uniq();
		
		if ( toRemove.length >= 1 )
		{
			for( i=0; i<toRemove.length; i++ )
			{
				selectedArticles = selectedArticles.without( parseInt( toRemove[i] ) );
			}
		}
		
		selectedArticles = selectedArticles.join(',');
		ipb.Cookie.set('modaids', selectedArticles, 0);
		
		$('selectedaids').value = selectedArticles;
		
		ipb.tutorials.updateArticleModButton();
	},
	
	checkArticle: function(e)
	{
		remove = new Array();
		check = Event.findElement( e, 'input' );
		selectedArticles = $F('selectedaids').split(',').compact();
		
		if ( check.checked == true )
		{
			selectedArticles.push( check.id.replace('amod_', '') );
			ipb.tutorials.totalChecked++;
		}
		else
		{
			remove.push( check.id.replace('amod_', '') );
			ipb.tutorials.totalChecked--;
		}
		
		selectedArticles = selectedArticles.uniq().without( remove ).join(',');		
		ipb.Cookie.set('modaids', selectedArticles, 0);
		
		$('selectedaids').value = selectedArticles;

		ipb.tutorials.updateArticleModButton();		
	},
	
	updateArticleModButton: function( )
	{
		if ( $('mod_submit') )
		{
			var _v = $('mod_aact').options[ $('mod_aact').selectedIndex ].value;
			
			if ( ipb.tutorials.totalChecked == 0 )
			{
				$('mod_submit').disabled = true;
			}
			else
			{
				$('mod_submit').disabled = false;
			}
			
			$('mod_submit').value = ipb.lang['with_selected'].replace('{num}', ipb.tutorials.totalChecked);
		}
	},
	
	submitModForm: function(e)
	{
		/* Check for delete action */
		if ( $F('mod_aact') == 'delete' )
		{
			if ( !confirm( ipb.lang['delete_confirm'] ) )
			{
				Event.stop(e);
			}
		}
	},
	
	/* Delete confirmation (article) */
	confirmDeleteArticle: function(e, elem)
	{
		if ( !confirm( ipb.lang['delete_article_confirm'] ) )
		{
			Event.stop(e);
		}
	},
	
	/* Show who gave reputation */
	repPopUp: function( e, postID )
	{
		url = ipb.vars['base_url'] + "&app=tutorials&module=ajax&secure_key=" + ipb.vars['secure_hash'] + '&section=reputation&art=' + postID;
		popup = new ipb.Popup( 'attachments', { type: 'balloon',
												stem: true,
												attach: { target: e, position: 'auto' },
												hideAtStart: false,
												ajaxURL: url,
												w: '300px',
												h: '400px'
											  }
							 );
		
		return false;
	},
	
	/* Jump to a specific category */
	jumpToCategory: function(e)
	{
		Event.stop(e);
		
		$('cat_jump').submit();
		
		return false;
	},
	
	/* Copy post to a new article */
	copyPost: function( e )
	{
		elem = Event.findElement( e, 'li' );
		postWrapper = elem.up( '.post_block' );
		postID = postWrapper.id.replace( 'post_id_', '' );
		elem.down('a').setAttribute( 'id', 'copy_post_' + postID );
		
		ipb.tutorials.catDropdown( e, postID, 'post' );
	},
	
	/* Build a dropdown of categories to copy to */
	getCopyLocations: function( e, elem )
	{
		ipb.tutorials.catDropdown( e, elem.id.replace('copy_article_', ''), 'copy' );
	},
	
	/* Build a dropdown of categories to move to */
	getMoveLocations: function( e, elem )
	{
		ipb.tutorials.catDropdown( e, elem.id.replace('move_article_', ''), 'move' );
	},
	
	/* REusable function to build the dropdowns */
	catDropdown: function( e, object_id, type )
	{
		/* Set our changeable replacements */
		if ( type == 'copy' )
		{
			var _marker = ipb.tutorials.copycats;
			var _anchor = 'copy_article_';
			var _doCode = 'getCopyCats';
		}
		else if ( type == 'move' )
		{
			var _marker = ipb.tutorials.movecats;
			var _anchor = 'move_article_';
			var _doCode = 'getMoveCats';
		}
		else
		{
			var _marker = ipb.tutorials.postcats;
			var _anchor = 'copy_post_';
			var _doCode = 'getPostCats';
		}
		
		/* Only run AJAX call once.  Cache and use the cache for subsequent requests. */
		if ( !_marker )
		{
			var url = ipb.vars['base_url'] + 'app=tutorials&module=ajax&section=articles&do=' + _doCode + '&id=' + object_id;
			
			new Ajax.Request
			(
				url,
				{
					method: 'post',
					evalJSON: 'force',
					parameters: {
						secure_key: ipb.vars['secure_hash']
					},
					onSuccess: function(t)
					{
						if ( t.responseJSON['error'] )
						{
							alert( t.responseJSON['error'] );
						}
						else
						{
							_marker = true;
							
							$(_anchor + object_id).addClassName('ipbmenu');
							$('ipboard_body').insert( t.responseJSON['html'] );
							
							var _newMenu = new ipb.Menu( $(_anchor + object_id), $( _anchor + object_id + '_menucontent' ) );
							_newMenu.doOpen();
						}
					}
				}
			);
		}
		
		Event.stop(e);
		return false;
	},
	
	toggleFilters: function(e)
	{
		if ( $('filter_form') )
		{
			Effect.toggle( $('filter_form'), 'blind', {duration: 0.2} );
			Effect.toggle( $('show_filters'), 'blind', {duration: 0.2} );
		}
	},
	
	catMarkRead: function(elem, e)
	{
		Event.stop(e);
		
		var id = $(elem).readAttribute("data-cid");
		if( !id ){ return; }
		
		var url = ipb.vars['base_url'] + '&app=tutorials&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=markasread&catid=' + id;
	
		/* Send AJAX request */
		new Ajax.Request
		(
			url,
			{
				method: 'get',
				evalJSON: 'force',
				onSuccess: function(t)
				{
					/* Remove elements */
					$$('.__article').each( function( art )
					{
						if ( $(art).hasClassName('unread') )
						{
							var aid = $(art).readAttribute("data-aid");
							
							if ( aid )
							{
								ipb.tutorials.articleRemoveUnreadElements( aid );
							}
						}
					} );
				}
			}
		);
	},
	
	articleRemoveUnreadElements: function( aid )
	{
		$('trow_' + aid).removeClassName('unread').down('.col_f_icon').select('a img').invoke('remove');
	}
}

ipb.tutorials.init();
