/**
 * Product Title:		(IM) Tutorials
 * Product Version:		1.1.1
 * Author:				Michael McCune
 * Website:				Coders Refuge
 * Website URL:			http://www.codersrefuge.com/
 * Email:				michael.mccune@gmail.com
 */

var _tut = window.IPBoard;

_tut.prototype.tutorials = {
	postcache: '',
	
	init: function()
	{
		Debug.write("Initializing ips.tutorials.js");
		
		document.observe("dom:loaded", function(){
			ipb.tutorials.initEvents();
			ipb.delegate.register( '.delete_article', ipb.tutorials.confirmDeleteArticle );
			ipb.delegate.register( '.delete_comment', ipb.tutorials.confirmDeleteComment );
			ipb.delegate.register( '.multiq_comment', ipb.tutorials.toggleMultimod );
			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 );
			
			$$( ".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 ) );
			});
		});
	},
	
	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'];
					
					/* Init the editor */
					ipb.editors[ edit['aid'] ] = new ipb.editor( edit['aid'], USE_RTE );
					
					/* 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', '');
		if ( !postid ) { return; }
		
		try
		{
			/* Need to update for submit manually in this case */
			ipb.editors[ 'e' + postid ].update_for_form_submit();
			var Post = $F( 'e' + postid + '_textarea' );
		}
		catch(err)
		{
			Debug.error( err );
			Debug.dir( ipb.editors );
			return;
		}
		
		/* 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;
		
		/* 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
					{
						/* 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&id=' + postid;
		
		try
		{
			/* Need to update for submit manually in this case */
			ipb.editors[ 'e' + postid ].update_for_form_submit();
			var Post = $F( 'e' + postid + '_textarea' );
		}
		catch(err)
		{
			Debug.error( err );
			return;
		}
		
		/* Setup inline form elements */
		form = new Element('form', { action: url, method: 'post' } );
		textarea = new Element('textarea', { name: 'ajax_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 )
		{
			$( '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' );
							$('toggle_text').update( ipb.lang['unapprove'] );
						}
						else
						{
							$('article_' + artid).addClassName( 'moderated' );
							$('toggle_text').update( ipb.lang['approve'] );
						}
						
						if ( $('pendCount') )
						{
							$('pendCount').update( t.responseJSON['count'] );
							
							if ( $('pendButton').hasClassName( 'closed' ) && t.responseJSON['count'] == 0 )
							{
								$('pendButton').removeClassName( 'closed' );
							}
							else if ( !$('pendButton').hasClassName( 'closed' ) && t.responseJSON['count'] > 0 )
							{
								$('pendButton').addClassName( 'closed' );
							}
						}
					}
				}
			}
		);
	},
	
	setPostHidden: function(id)
	{
		if( $( 'cid_' + id ).select('.post_wrap')[0] )
		{
			$( 'cid_' + id ).select('.post_wrap')[0].hide();
			
			if( $('unhide_post_' + id ) )
			{
				$('unhide_post_' + id).observe('click', ipb.tutorials.showHiddenPost );
			}
		}
	},
	
	showHiddenPost: function(e)
	{
		link = Event.findElement(e, 'a');
		id = link.id.replace('unhide_post_', '');
		
		if( $('cid_' + id ).select('.post_wrap')[0] )
		{
			elem = $('cid_' + id ).select('.post_wrap')[0];
			new Effect.Parallel( [
				new Effect.BlindDown( elem ),
				new Effect.Appear( elem )
			], { duration: 0.5 } );
		}
		
		if( $('cid_' + id ).select('.post_ignore')[0] )
		{
			elem = $('cid_' + id ).select('.post_ignore')[0];
			elem.hide();
		}
		
		Event.stop(e);
	},
	
	add_bookmark: function( title, url )
	{
		if ( window.sidebar )
		{
			window.sidebar.addPanel( title, url, "" );
		}
		else if ( window.opera && window.print )
		{
			var elem = document.createElement( 'a' );
			elem.setAttribute( 'href', url );
			elem.setAttribute( 'title', title );
			elem.setAttribute( 'rel', 'sidebar' );
			elem.click();
		}
		else if (document.all)
		{
			window.external.AddFavorite( url, title );
		}
		else
		{
			alert( ipb.lang['bookmark_unsupported'] );
		}
	},
	
	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;
	},
	
	/* Init events for cat listing */
	initEvents: function()
	{
		/* Checkboxes in moderation panel */
		$$('.check_all').each( function(check){
			check.observe( 'click', ipb.tutorials.checkAllInForm );
		} );
		
		$$('.topic_moderation').each( function(check){
			check.observe( 'click', ipb.tutorials.checkModfile );
		} );
	},
	
	/* 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_', '' );
		
		Event.stop(e);
		
		window.location = ipb.vars['base_url'] + 'app=tutorials&module=post&section=submit&do=copyPost&pid=' + postID;
	},
	
	/* Multi-quote */
	toggleMultimod: function(e)
	{
		Event.stop(e);
		elem = Event.element(e);
		
		if ( !elem.hasClassName( 'multiquote' ) )
		{
			elem = $( Event.element(e) ).up('.multiquote');
		}
		
		/* Get list of already quoted posts */
		try
		{
			quoted = ipb.Cookie.get( 'tutorials_pids' ).split(',').compact();
		}
		catch(err)
		{
			quoted = $A();
		}
		
		id = elem.id.replace( 'multiq_', '' );
		
		/* Hokay, are we selecting/deselecting? */
		if ( elem.hasClassName( 'selected' ) )
		{
			elem.removeClassName( 'selected' );
			quoted = quoted.uniq().without( id ).join(',');
		}
		else
		{
			elem.addClassName('selected');
			quoted.push( id );
			quoted = quoted.uniq().join(',');
		}
		
		/* Save cookie */
		ipb.Cookie.set('tutorials_pids', quoted, 0);			
	},
	
	/* Check all the files in this form */			
	checkAllInForm: function(e)
	{
		checked	= 0;
		check	= Event.findElement(e, 'input');
		toCheck	= $F(check);
		form	= check.up('form');
		
		form.select('.selectedarticleids').each( function(field){
			selectedTopics	= field.value.split(',').compact();
		});
		
		toRemove		= new Array();
		
		form.select('.topic_moderation').each( function(check){
			if ( toCheck != null )
			{
				check.checked = true;
				selectedTopics.push( check.id.replace('tut_', '') );
				checked++;
			}
			else
			{
				check.checked = false;
				toRemove.push( check.id.replace('tut_', '') );
			}
		});
		
		selectedTopics = selectedTopics.uniq().without( toRemove ).join(',');

		form.select('.submit_button').each( function(button)
		{
			if ( checked == 0 ){
				button.disabled = true;
			} else {
				button.disabled = false;
			}
		
			button.value = ipb.lang['with_selected'].replace('{num}', checked);
		});
		
		form.select('.selectedarticleids').each( function(hidden)
		{
			hidden.value = selectedTopics;
		});
	},
	
	checkModfile: function(e)
	{
		check	= Event.findElement(e, 'input');
		toCheck	= $(check);
		form	= check.up('form');
		
		var checkboxesOnPage	= 0;
		var checkedOnPage		= 0;
		
		form.select('.selectedarticleids').each( function(field){
			selectedTopics	= field.value.split(',').compact();
		});
		remove			= new Array();

		form.select('.topic_moderation').each( function(check){
			checkboxesOnPage++;
			
			if( check.checked == true )
			{
				checkedOnPage++;
				selectedTopics.push( check.id.replace('tut_', '') );
			}
			else
			{
				remove.push( check.id.replace('tut_', '') );
				form.select('.check_all')[0].checked = false;
			}
		} );
		
		if( checkedOnPage == checkboxesOnPage )
		{
			form.select('.check_all')[0].checked = true;
		}

		selectedTopics = selectedTopics.uniq().without( remove ).join(',');

		form.select('.submit_button').each( function(button)
		{
			if( checkedOnPage == 0 ){
				button.disabled = true;
			} else {
				button.disabled = false;
			}
		
			button.value = ipb.lang['with_selected'].replace('{num}', checkedOnPage);
		});
		
		form.select('.selectedarticleids').each( function(hidden)
		{
			hidden.value = selectedTopics;
		});
	},
	
	/* Delete confirmation (article) */
	confirmDeleteArticle: function(e, elem)
	{
		if ( !confirm( ipb.lang['delete_article_confirm'] ) )
		{
			Event.stop(e);
		}
	},
	
	/* Delete confirmation (comment) */
	confirmDeleteComment: function(e, elem)
	{
		if ( !confirm( ipb.lang['delete_comment_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;
	}
}

ipb.tutorials.init();

_tut.prototype.favorite = Class.create({
	options: 		{},
	_prevFaveText: 	'',
	events: 		{click: []},

	/* Constructor */
	initialize: function( options )
	{
		this.options = Object.extend({
			img_off: 			ipb.vars['fave_img_off'],
			img_on: 			ipb.vars['fave_img_on'],
			text: 				{
									added: 	ipb.lang['remove_from_favorites'],
									removed: ipb.lang['add_to_favorites']
								},
			fave_text_id: 		'fave_text'
		}, arguments[0] || {});
		
		if ( !this.options['url'] )
		{
			Debug.error( ipb.lang['debug_error'] );
		}
		
		if ( !$( this.options.fave_text_id ) )
		{
			return false;
		}
		
		this.options['url']	= this.options['url'].replace( /&amp;/g, '&' );
		this._prevFaveText = $( this.options.fave_text_id ).innerHTML;
		this._setUpToggle();
	},
	
	/* Sets up event handlers on rating images */
	_setUpToggle: function()
	{
		this.events['click'][1] = this._faveClick.bindAsEventListener( this );
		$('fave_toggle').observe('click', this.events['click'][1] );
	},
	
	/* Click event event */
	_faveClick: function(e)
	{
		this.sendRating();
		Event.stop(e);
	},
	
	/* Sends the rating to the server */
	sendRating: function()
	{
		if( DISABLE_AJAX )
		{
			return false;
		}
		
		new Ajax.Request( this.options.url, {
			method: 'post',
			evalJSON: 'force',
			onSuccess: function(t)
			{
				if ( Object.isUndefined( t.responseJSON ) )
				{
					alert( ipb.lang['rating_failed'] );
					return;
				}
				
				if ( t.responseJSON['result'] == 'added' )
				{
					$( this.options.fave_text_id ).update( this.options.text.added );
					$( 'fave_img' ).src = this.options.img_on;
				}
				else
				{
					$( this.options.fave_text_id ).update( this.options.text.removed );
					$( 'fave_img' ).src = this.options.img_off;
				}
			}.bind(this)
		});
	}
});
