/************************************************/
/* IPB3 Javascript								*/
/* -------------------------------------------- */
/* acp.uagents.js - User agent mapping			*/
/* (c) IPS, Inc 2008							*/
/* -------------------------------------------- */
/* Author: Rikki Tissier 						*/
/************************************************/

var _ccs = window.IPBACP;
_ccs.prototype.ccs = {
	
	/*
	 * Init function
	 */
	init: function()
	{
		Debug.write("Initializing acp.ccs.js");
		
		document.observe("dom:loaded", function(){
			if( $('template-tags-link') )
			{
				$('template-tags-link').observe('click', acp.ccs.showTemplateTags );
			}
			
			if( $('inline-template-tags-link') )
			{
				$('inline-template-tags-link').observe('click', acp.ccs.showInlineTemplateTags );
			}
			
			if( $('inline-db-tags-link') )
			{
				$('inline-db-tags-link').observe('click', acp.ccs.showDatabaseTags );
			}
			
			if( $('page-tags-link') )
			{
				$('page-tags-link').observe('click', acp.ccs.showPageTags );
			}
			
			$$('.block-preview-link').each( function(elem){
				$(elem).observe('click', acp.ccs.showBlockPreview );
			});
			
			if( $('uploadForm') )
			{
				$('uploadForm').hide();
				$('uploadTrigger').observe('click', acp.ccs.showUploadForm );
			}
			
			if( $('field_type') )
			{
				$('field_type').observe('change', acp.ccs.showAppropriateFields );
				
				acp.ccs.showAppropriateFields();
			}
			
			if( $('validator_custom') )
			{
				// Hide by default
				if( $F('field_validator') != 'custom' )
				{
					$('validator_custom').hide();
				}
				
				// Then add handler
				$('field_validator').observe('change', acp.ccs.showValidatorStuff );
			}
			
			if( $('moderator_member') )
			{
				this.autoComplete = new ipb.Autocomplete( $('moderator_member'), { multibox: false, url: acp.autocompleteUrl, templates: { wrap: acp.autocompleteWrap, item: acp.autocompleteItem } } );
			}
			
			$$('.ttype').each( function(elem){
				$(elem).observe('click', acp.ccs.showDatabaseVariables );
			});
		});
	},
	
	/*
	 * Show template diff report popup
	 */
	viewCompare: function( url )
	{
		new Ajax.Request( url + '&secure_key=' + ipb.vars['md5_hash'],
						  {
							method: 'get',
							onSuccess: function (t)
							{
								popup = new ipb.Popup('diffPopUp', { type: 'pane', modal: false, hideAtStart: true, w: '800px', h: '600px', initial: t.responseText } );
								popup.show();
							}
						  } );

		return false;
	},
	
	/*
	 * Show and hide validator fields for "custom" type
	 */
	showValidatorStuff: function( e )
	{
		var fieldValue	= $F('field_validator');
		
		if( fieldValue =='custom' )
		{
			$('validator_custom').show();
		}
		else
		{
			$('validator_custom').hide();
		}
	},
	
	/*
	 * Handles showing database variables for different database templates
	 */
	showDatabaseVariables: function( e )
	{
		Event.stop(e);
		var elem	= Event.findElement(e, 'span' );
		
		if( elem.id == 'type-categories' )
		{
			$('db-tags-listing').hide();
			$('db-tags-display').hide();
			$('db-tags-categories').show();
		}
		else if( elem.id == 'type-listing' )
		{
			$('db-tags-categories').hide();
			$('db-tags-display').hide();
			$('db-tags-listing').show();
		}
		else
		{
			$('db-tags-listing').hide();
			$('db-tags-categories').hide();
			$('db-tags-display').show();
		}

		return false;
	},
	
	/*
	 * Opens new window with database template tag help
	 */
	showDatabaseTags: function( e )
	{
		Event.stop(e);
		
		var dbType	= Event.findElement( e, 'a' ).rel;
		
		acp.openWindow( ipb.vars['base_url'] + "&app=ccs&module=templates&section=help&type=" + dbType, 1024, 600, "dbHelp" )
		
		return false;
	},
	
	/*
	 * Alter new field form appropriately based on field type
	 */
	showAppropriateFields: function(e)
	{
		var fieldValue	= $F('field_type');
		
		$$('.field_type_wrapper').each( function(elem) {
			$(elem).hide();
		});
		
		$('field_truncate_li').show();
		
		if( fieldValue == 'input' )
		{
			$('field_required_li').show();
			$('field_length_li').show();
			$('field_html_li').show();
			$('field_formatopts_li').show();
			$('field_validator_li').show();
		}
		else if( fieldValue == 'textarea' || fieldValue == 'editor' )
		{
			$('field_required_li').show();
			$('field_length_li').show();
			$('field_html_li').show();
			$('field_validator_li').show();
		}
		else if( fieldValue == 'checkbox' || fieldValue == 'radio' || fieldValue == 'select' || fieldValue == 'multiselect' || fieldValue == 'date' )
		{
			$('field_required_li').show();
			$('field_extra_li').show();
		}
		else if( fieldValue == 'member' )
		{
			$('field_required_li').show();
		}
		else if( fieldValue == 'relational' )
		{
			$('field_reltype_li').show();
			$('field_required_li').show();
			
			acp.ccs.fieldFormRelational();
		}
		else if( fieldValue == 'attachments' )
		{
			
		}
		else if( fieldValue == 'upload' )
		{
			$('field_extra_li').show();
			$('field_required_li').show();
		}
		else
		{
			// @see	http://community.invisionpower.com/index.php?app=tracker&showissue=20456
			//$$('.field_type_wrapper').each( function(elem) {
			//	$(elem).show();
			//});
		}

		if( fieldDescriptions.get( fieldValue ) )
		{
			$('extra_options_text').update( fieldDescriptions.get( fieldValue ) );
		}
		else
		{
			$('extra_options_text').update( fieldDescriptions.get('standard') );
		}
	},
	
	/*
	 * Extra handling for relational database fields
	 */
	fieldFormRelational: function()
	{
		var url = ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=fields&do=fetchDatabases";
		
		new Ajax.Request(	url,
							{
								method: 'post',
								parameters: {
									md5check: 	ipb.vars['md5_hash'],
									field:		$F('field_edit_id')
								},
								onSuccess: function(t)
								{
									$('field_databases_li').show();
									$('field_databases_select').update( t.responseText );
									
									if( t.responseText.indexOf( "selected='selected'" ) )
									{
										acp.ccs.fetchRelationalFields();
										
										$('field_databases_select').observe( 'change', acp.ccs.fetchRelationalFields );
									}
								}
							}
						);
	},
	
	/*
	 * Fetch fields for a specific database
	 */
	fetchRelationalFields: function()
	{
		var url = ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=fields&do=fetchFields";
		
		new Ajax.Request(	url,
							{
								method: 'post',
								parameters: {
									md5check: 	ipb.vars['md5_hash'],
									field:		$F('field_edit_id'),
									database:	$F('field_databases_select')
								},
								onSuccess: function(t)
								{
									$('field_fields_li').show();
									
									$('field_fields_select').update( t.responseText );
								}
							}
						);
	},
	
	/*
	 * Show the upload form
	 */
	showUploadForm: function( e )
	{
		Event.stop(e);
		popup = new ipb.Popup( 'dlestimates', { type: 'pane', modal: false, w: '500px', initial: $('uploadForm').innerHTML, hideAtStart: false, close: 'a[rel="close"]' } );
		
		return false;
	},

	/*
	 * Show block preview
	 */
	showBlockPreview: function( e )
	{
		Event.stop(e);
		var elem	= Event.findElement(e, 'a' );
		var id		= elem.id.replace( '-blockPreview', '' );
		var url		= ipb.vars['base_url'] + "&app=ccs&module=ajax&section=blocks&secure_key=" + ipb.vars['md5_hash'] + '&do=preview&id=' + id;
		
		popup = new ipb.Popup( 'blockPreview', { type: 'pane', modal: false, w: '600px', h: '450px', ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
		return false;
	},

	/*
	 * Show inline template tag help
	 */
	showInlineTemplateTags: function( e )
	{
		Event.stop(e);
		
		if( $('template-tags') )
		{
			$('template-tags').show();
			$('content-label').addClassName( 'withSidebar' );
		}
		else
		{
			var inlineDiv	= new Element( 'div', { 'id': 'template-tags', 'class': 'templateTags-container' } );
			
			$('content-label').addClassName( 'withSidebar' );
			$('content-label').insert( { before: inlineDiv } );
			
			new Ajax.Updater( 'template-tags', ipb.vars['base_url'] + "&app=ccs&module=ajax&section=templates&secure_key=" + ipb.vars['md5_hash'] + '&do=showtags&inline=1', { evalScripts: true } );
		}
		
		if( window.resizeEditor )
		{
			resizeEditor();
		}
		
		return false;
	},
	
	/*
	 * Close the inline help
	 */
	closeInlineHelp: function( e )
	{
		if( $('template-tags') )
		{
			$('template-tags').hide();
			$('content-label').removeClassName( 'withSidebar' );
			
			if( window.restoreResizeEditor )
			{
				restoreResizeEditor();
			}
		}
	},
	
	/*
	 * Show full template tag help popup
	 */
	showTemplateTags: function( e )
	{
		Event.stop(e);

		var url = ipb.vars['base_url'] + "&app=ccs&module=ajax&section=templates&secure_key=" + ipb.vars['md5_hash'] + '&do=showtags';
		
		popup = new ipb.Popup( 'templateTags', { type: 'pane', modal: false, w: '600px', h: '450px', ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
		return false;
	},
	
	/*
	 * Show the page tags
	 */
	showPageTags: function( e )
	{
		Event.stop(e);

		if( $('template-tags') )
		{
			$('template-tags').show();
			$('content-label').addClassName( 'withSidebar' );
		}
		else
		{
			var inlineDiv	= new Element( 'div', { 'id': 'template-tags', 'class': 'templateTags-container' } );
			
			$('content-label').addClassName( 'withSidebar' );
			$('content-label').insert( { before: inlineDiv } );
			
			new Ajax.Updater( 'template-tags', ipb.vars['base_url'] + "&app=ccs&module=ajax&section=templates&secure_key=" + ipb.vars['md5_hash'] + '&do=taghelp&inline=1', { evalScripts: true } );
		}

		return false;
	},
	
	/*
	 * Show all of the page tags
	 */
	showFullPageTags: function( e )
	{
		Event.stop(e);

		var url = ipb.vars['base_url'] + "&app=ccs&module=ajax&section=templates&secure_key=" + ipb.vars['md5_hash'] + '&do=taghelp';
		
		popup = new ipb.Popup( 'templateTags', { type: 'pane', modal: false, w: '600px', h: '450px', ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
		return false;
	},
	
	/*
	 * Block categorization
	 */
	initBlockCategorization: function( categoryIds )
	{
		categoryReorder = function( draggableObject, mouseObject )
		{
			var options = {
							method : 'post',
							parameters : Sortable.serialize( 'category-containers', { tag: 'div', name: 'category' } )
						};
		 
			new Ajax.Request( ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=blocks&do=reorderCats&md5check=" + ipb.vars['md5_hash'], options );
		
			return false;
		};
			
		for( var i=0; i < categoryIds.length; i++ )
		{
			if( $( categoryIds[ i ] ) )
			{
				Sortable.create( categoryIds[ i ], { 
						containment: categoryIds, 
						dropOnEmpty: true, 
						revert: 'failure', 
						format: 'record_([0-9]+)', 
						handle: 'draghandle',
						onUpdate: function( draggableObject, mouseObject )
						{
							if( $('record_00' + parseInt( draggableObject.id.replace( "sortable_handle_", "" ) ) ) )
							{
								draggableObject.removeChild( $('record_00' + parseInt( draggableObject.id.replace( "sortable_handle_", "" ) ) ) );
							}
							else
							{
								if( parseInt( draggableObject.childElements().length ) == 0 )
								{
									// Create empty row
									var temp = ipb.templates['cat_empty'].evaluate( { category: parseInt( draggableObject.id.replace( "sortable_handle_", "" ) ) } );
																							
									draggableObject.innerHTML = temp;
								}
							}
	
							new Ajax.Request( ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=blocks&do=reorder&category=" + draggableObject.id.replace( "sortable_handle_", "" ) + "&md5check=" + ipb.vars['md5_hash'], {
												method : 'post',
												parameters : Sortable.serialize( draggableObject.id, { tag: 'li', name: 'block' } )
											} );
						
							return false;
						}  
				} );
				
				if( categoryIds[ i ] == 0 )
				{
					return true;
				}
			}
		}
		
		Sortable.create( 'category-containers', { tag: 'div', revert: 'failure', format: 'container_([0-9]+)', onUpdate: categoryReorder, handle: 'draghandle' } );
		
		if( $('container_0') )
		{
			$('container_0').down('.draghandle').hide();
		}
	},
	
	/*
	 * Template categorization
	 */
	initTemplateCategorization: function( categoryIds )
	{
		categoryPReorder = function( draggableObject, mouseObject )
		{
			var options = {
							method : 'post',
							parameters : Sortable.serialize( 'category-containers-p', { tag: 'div', name: 'category' } )
						};
		 
			new Ajax.Request( ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=blocks&do=reorderCats&md5check=" + ipb.vars['md5_hash'], options );
		
			return false;
		};
		
		categoryDReorder = function( draggableObject, mouseObject )
		{
			var options = {
							method : 'post',
							parameters : Sortable.serialize( 'category-containers-d', { tag: 'div', name: 'category' } )
						};
		 
			new Ajax.Request( ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=blocks&do=reorderCats&md5check=" + ipb.vars['md5_hash'], options );
		
			return false;
		};
			
		for( var i=0; i < categoryIds.length; i++ )
		{
			Sortable.create( categoryIds[ i ], { 
					containment: categoryIds, 
					dropOnEmpty: true, 
					revert: 'failure', 
					format: 'record_([0-9]+)', 
					handle: 'draghandle',
					onUpdate: function( draggableObject, mouseObject )
					{
						if( draggableObject.id.match( "sortable_handle_p_" ) )
						{
							var _thisId	= draggableObject.id.replace( "sortable_handle_p_", "" );
							var _type	= 'page';
						}
						else
						{
							var _thisId	= draggableObject.id.replace( "sortable_handle_d_", "" );
							var _type	= 'db';
						}

						if( _type == 'db' && $('record_000' + parseInt( _thisId ) ) )
						{
							draggableObject.removeChild( $('record_000' + parseInt( _thisId ) ) );
						}
						else if( _type == 'page' && $('record_00' + parseInt( _thisId ) ) )
						{
							draggableObject.removeChild( $('record_00' + parseInt( _thisId ) ) );
						}
						else
						{
							if( parseInt( draggableObject.childElements().length ) == 0 )
							{
								// Create empty row
								var temp = ipb.templates['cat_empty_' + _type ].evaluate( { category: parseInt( _thisId ) } );
																						
								draggableObject.innerHTML = temp;
							}
						}

						new Ajax.Request( ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=templates&do=reorder&category=" + _thisId + "&md5check=" + ipb.vars['md5_hash'], {
											method : 'post',
											parameters : Sortable.serialize( draggableObject.id, { tag: 'li', name: 'template' } )
										} );
					
						return false;
					}  
			} );
			
			if( categoryIds[ i ] == 0 )
			{
				return true;
			}
		}
		
		if( $('category-containers-p') )
		{
			Sortable.create( 'category-containers-p', { tag: 'div', revert: 'failure', format: 'container_p_([0-9]+)', onUpdate: categoryPReorder, handle: 'draghandle' } );
		}
		
		if( $('category-containers-d') )
		{
			Sortable.create( 'category-containers-d', { tag: 'div', revert: 'failure', format: 'container_d_([0-9]+)', onUpdate: categoryDReorder, handle: 'draghandle' } );
		}

		if( $('container_p_0') )
		{
			$('container_p_0').down('.draghandle').hide();
		}
				
		if( $('container_d_0') )
		{
			$('container_d_0').down('.draghandle').hide();
		}
	},
	
	/*
	 * Fetch encoding of remote RSS feed
	 */
	fetchEncoding: function()
	{
		if( !$('rss_feed_url') || !$F('rss_feed_url') )
		{
			alert( ipb.lang['no_rss_feed_url'] );
		}
		else
		{
			var url = ipb.vars['base_url'].replace( /&amp;/g, '&' ) + "app=ccs&module=ajax&section=blocks&do=fetchEncoding";
			
			new Ajax.Request(	url,
								{
									method: 'post',
									evalJSON: 'force',
									parameters: {
										md5check: 	ipb.vars['md5_hash'],
										url:		$F('rss_feed_url')
									},
									onSuccess: function(t)
									{
										if( t.responseJSON['error'] )
										{
											alert(t.responseJSON['error']);
										}
										else
										{
											$('rss_charset').value = t.responseJSON['encoding'];
										}
									}
								}
							);
		}
		
		return false;
	}
}

acp.ccs.init();