/**
* IP.Tracker 1.3.3
*  - IPS Community Project Developers
* 
* Prototype Javascript
* Last Updated: $Date: 2010-05-29 00:16:17 +0100 (Sat, 29 May 2010) $
*
* @author		$Author: stoo2000 $
* @copyright	2001 - 2010 Invision Power Services, Inc.
* @license		http://www.invisionpower.com/community/board/license.html
* @package		IP.Tracker
* @subpackage	JavaScript
* @link			http://resources.invisionpower.com
* @version		$Revision: 825 $
*/

var iptracker =
	{
		/* Common Text Variables */
		myStoredSelection: '',
		
		/* Common Array Variables */
		postCache: [],
		ignoreCache: [],
		
		/* Common Integer Variables */
		ajaxLoaded: 1,
		rateValue: 0,
		
		initialize: function()
		{
			/* Check if it has been loaded before we can start */
			document.observe( 'dom:loaded', function()
				{
					iptracker.initEvents();
					//iptracker.resizeImages();
				}
			);
		},
		
		initEvents: function()
		{
			$A( document.getElementsByTagName( 'a' ) ).findAll(
				function( result )
				{
					return ( result.id && result.id.match( /post_([\d]+?)_link/ ) )
				}
			).each(
				function( result )
				{
					var divId = result.id.match( /post_([\d]+?)_link/ );
	
					$( result ).observe( 'click', iptracker.linkToPost.bindAsEventListener( result, divId[1] ) );
				}
			);
			
			/* Set up common delegates */
			ipb.delegate.register( '.bbc_spoiler_show', ipb.global.toggleSpoiler );
			ipb.delegate.register( '.delete_issue', iptracker.deleteConfirm );
			//ipb.delegate.register( '.edit_post', iptracker.ajaxEditShow );
			
			/* Resize Images */
			$$( '.post', '.poll' ).each(
				function( elem )
				{
					ipb.global.findImgs( $( elem ) );
				}
			);
			
			/* Collapse timeline */
			$$( '.timelineCollapse' ).each(
				function( elem )
				{
					elem.setStyle('display:block;');
					elem.observe( 'click', iptracker.collapseTable.bindAsEventListener( 0, elem ) );
				}
			);
		},
		
		deleteConfirm: function(e, elem)
		{
			if( !confirm( ipb.lang['delete_post_confirm'] ) )
			{
				Event.stop(e);
			}
		},
		
		collapseTable: function( event )
		{
			Event.stop(event);
			
			elemId = $A( arguments )[1];
			
			if ( iptracker.inAnimation != 1 )
			{
				iptracker.inAnimation = 1;
				
				new Effect.BlindUp( elemId.up('h3').next('.collapsedTable'),
					{
						duration: 0.4,
						afterFinish: function()
						{
							iptracker.inAnimation = 0;
							
							/* Change to expand */
							elemId.stopObserving();
							elemId.update( 'Expand' );
							elemId.observe( 'click', iptracker.expandTable.bindAsEventListener( 0, elemId ) );		
						}
					}
				);
			}
		},
		
		expandTable: function( event )
		{
			Event.stop(event);
			
			elemId = $A( arguments )[1];
			
			if ( iptracker.inMoreAnimation != 1 )
			{
				iptracker.inMoreAnimation = 1;
				
				new Effect.BlindDown( elemId.up('h3').next('.collapsedTable'),
					{
						duration: 0.4,
						afterFinish: function()
						{
							iptracker.inMoreAnimation = 0;

							/* Change to expand */
							elemId.stopObserving();
							elemId.update( 'Collapse' );
							elemId.observe( 'click', iptracker.collapseTable.bindAsEventListener( 0, elemId ) );		
						}
					}
				);
			}
		},
		
		ajaxEditShow: function( e, elem )
		{
			// If user is holding ctrl or command, just submit since they
			// want to open a new tab (requested by Luke)
			if( e.ctrlKey == true || e.metaKey == true || e.keyCode == 91 )
			{
				return false;
			}
			
			Event.stop(e);
			var edit = [];
			
			edit['button'] = elem;
			if( !edit['button'] ){ return; }
			
			edit['pid'] 		= edit['button'].id.replace('edit_post_', '');
			edit['iid'] 		= iptracker.issue_id;
			edit['project_id'] 	= iptracker.project_id;
			edit['post'] 		= $( 'post_id_' + edit['pid'] ).down('.post');
			
			url = ipb.vars['base_url'] + 'app=tracker&module=ajax&section=xmlout&do=editBoxShow&p=' + edit['pid'] +'&t=' + edit['iid'] +'&f=' + edit['project_id'];
			
			// DO TEH AJAX LOL
			new Ajax.Request( url, 
				{
					method: 'post',
					parameters: {
						md5check: 	ipb.vars['secure_hash']
					},
					onSuccess: function(t)
					{
						if( t.responseText == 'nopermission' || t.responseText == 'NO_POST_FORUM' || t.responseText == 'NO_EDIT_PERMS' )
						{
							alert("You don't have permission to edit this post");
							return;
						}
						if( t.responseText == 'error' )
						{
							alert("Error editing this post");
							return;
						}
						
						// Put it in
						edit['post'].update( t.responseText );
						new Effect.ScrollTo( edit['post'], { offset: -50 } );
						
						// Init the editor SKINNOTE: this needs to respect user preference
						ipb.editors[ edit['pid'] ] = new ipb.editor( edit['pid'], USE_RTE );
						
						// Set up events
						if( $('edit_save_' + edit['pid'] ) ){
							$('edit_save_' + edit['pid'] ).observe('click', ipb.topic.ajaxEditSave );
						}
						if( $('edit_switch_' + edit['pid'] ) ){
							$('edit_switch_' + edit['pid'] ).observe('click', ipb.topic.ajaxEditSwitch );
						}
						if( $('edit_cancel_' + edit['pid'] ) ){
							$('edit_cancel_' + edit['pid'] ).observe('click', ipb.topic.ajaxEditCancel );
						}
					}
				}
			);
		},
		
	 	scrollToPost: function( pid )
		{
			if( !pid || !Object.isNumber( pid ) ){ return; }
			$('entry' + pid).scrollTo();
		},
		
		linkToPost: function( e )
		{
			postID = $A(arguments);
			postID.shift();

			temp = prompt( ipb_lang_tt_prompt, $( this ).readAttribute('href') );
			
			Event.stop(e);
			return false;
		},
		
		resizeImages: function()
		{
			if ( ipsclass.settings['do_linked_resize'] != 1 )
			{
				return true;
			}
		
			var images   = document.getElementsByTagName( 'IMG' );
			var _padding = 2;
			var _count   = 0;
			var _img     = '<img src="' + ipb_var_image_url + '/img-resized.png" style="vertical-align:middle" border="0" alt="" />';
			var _img2    = '<img src="' + ipb_var_image_url + '/folder_attach_images/attach_zoom_in.png" style="vertical-align:middle" border="0" alt="" />';
			var _sw      = screen.width * ( parseInt( ipsclass.settings['resize_percent'] ) / 100 );
		
			for ( var i = 0 ; i < images.length; i++ )
			{
				if ( images[i].className == 'linked-image' )
				{
					_count++;

					if ( images[i].width > _sw )
					{
						var _width   = images[i].width;
						var _height  = images[i].height;
						var _percent = 0;

						images[i].width  = _sw;
		
						if ( images[i].width < _width && _width > 0 && images[i].width > 0 )
						{
							_percent = Math.ceil( parseInt( images[i].width / _width * 100 ) );
						}
		
						images[i].id          = '--ipb-img-resizer-' + _count;
						images[i]._resized    = 1;
						images[i]._width      = _width;

						var div = document.createElement( 'div' );
		
						div.innerHTML            = _img + '&nbsp;' + ipsclass.lang_build_string( ipb_global_lang['image_resized'], _percent, _width, _height );
						div.style.width          = images[i].width - ( _padding * 2 ) + 'px';
						div.className            = 'resized-linked-image';
						div.style.paddingTop     = _padding + "px";
						div.style.paddingBottom  = _padding + "px";
						div.style.paddingLeft    = _padding + "px";
						div.style.paddingRight   = _padding + "px";
						div._is_div              = 1;
						div._resize_id           = _count;
						div.onclick              = fix_linked_images_onclick;
						div.onmouseover          = fix_linked_images_mouseover;
						div.title                = ipb_global_lang['click_to_view' ];
						div._src                 = images[i].src;
		
						images[i].parentNode.insertBefore( div, images[i] );
					}
				}
			}
		},
		
		resizeAttachmentImages: function()
		{
			var _img    = '<img src="' + ipb_var_image_url + '/img-resized.png" style="vertical-align:middle" border="0" alt="" />';
			var img_obj = $( 'ipb-attach-img-'   + attach_id );
			var div_obj = $( 'ipb-attach-div-'   + attach_id );
			var ct_obj  = $( 'ipb-attach-ct-'    + attach_id );
			var cb_obj  = $( 'ipb-attach-cb-'    + attach_id );
			var url_obj = $( 'ipb-attach-url-'   + attach_id );
			var tbl_obj = $( 'ipb-attach-table-' + attach_id );
		
			var _width   = parseInt( img_obj.width )  ? parseInt( img_obj.width )  : parseInt( img_obj.style.width );
			var _height  = parseInt( img_obj.height ) ? parseInt( img_obj.height ) : parseInt( img_obj.style.height );
			var _padding = 5;
			var _percent = 0;
		
			if ( is_ie )
			{
				_width  = parseInt( img_obj.currentStyle['width'] );
				_height = parseInt( img_obj.currentStyle['height'] );
			}
		
			if ( is_safari )
			{
				tbl_obj.style.display = 'inline-block';
			}

			if ( width && height )
			{
				_percent = Math.ceil( 100 - parseInt( _width / width * 100 ) );
			}
			
			// Remove IMG class to stop gray border
			img_obj.className     = 'ipb';
			img_obj.title         = ipb_global_lang['click_to_view'];
			img_obj.onmouseover   = fix_attach_images_mouseover;
			img_obj.onclick       = function(event) { ipsclass.pop_up_window( url_obj.href, width + 20, height + 20 ); ipsclass.cancel_bubble(event); };
		
			// Re-style the main div obj
			div_obj.style.width          = ( _width > 140 ? _width : 140 ) + 'px';
			div_obj.style.height         = _height + ( _padding * 2 ) + 28 + 'px';
			div_obj.className            = 'resized-linked-image';
			div_obj.style.paddingTop     = _padding + "px";
			div_obj.style.paddingBottom  = _padding + "px";
			div_obj.style.paddingLeft    = _padding + 3 + "px";
			div_obj.style.paddingRight   = _padding + 3 + "px";
			div_obj.style.textAlign      = 'center';
			div_obj.title                = ipb_global_lang['click_to_view'];
		
			// Add content to the top div
			ct_obj.style.fontSize  = '9px';
			cb_obj.style.fontSize  = '9px';
			cb_obj.style.textAlign = 'center';
		
			if ( _percent > 0 )
			{
				ct_obj.innerHTML = _img + '&nbsp;' + ipsclass.lang_build_string( ipb_global_lang['image_attach_percent'], _percent );
			}
			else
			{
				ct_obj.innerHTML = _img + '&nbsp;' + ipb_global_lang['image_attach_no_percent'];
			}
		
			cb_obj.innerHTML     = "";
		
			if ( width && height )
			{
				cb_obj.innerHTML = ipsclass.lang_build_string( ipb_global_lang['image_attach_dims'], width, height );
			}
		
			cb_obj.innerHTML += ipsclass.lang_build_string( ipb_global_lang['image_attach_size'], file_size );
		},
		
		setPostHidden: function(id)
		{
			if ( $( 'post_id_' + id ).select( '.post_wrap' )[ 0 ] )
			{
				$( 'post_id_' + id ).select( '.post_wrap' )[ 0 ].hide();

				if ( $( 'unhide_post_' + id ) )
				{
					$( 'unhide_post_' + id ).observe( 'click', iptracker.showHiddenPost );
				}
			}
		},
                
		retrieveAttachments: function( id )
		{
				url = ipb.vars['base_url'] + "&app=tracker&module=ajax&secure_key=" + ipb.vars['secure_hash'] + '&section=attachments&issue_id=' + id;
				popup = new ipb.Popup( 'attachments', { type: 'pane', modal: false, w: '500px', h: '600px', ajaxURL: url, hideAtStart: false, close: 'a[rel="close"]' } );
				return false;
		},
		
		showHiddenPost: function(e)
		{
			link = Event.findElement( e, 'a' );
			id = link.id.replace( 'unhide_post_', '' );
		
			if ( $('post_id_' + id ).select( '.post_wrap' )[ 0 ] )
			{
				elem = $( 'post_id_' + id ).select( '.post_wrap' )[ 0 ];
				new Effect.Parallel( [
					new Effect.BlindDown( elem ),
					new Effect.Appear( elem )
				], { duration: 0.5 } );
			}
		
			if ( $('post_id_' + id ).select( '.post_ignore' )[ 0 ] )
			{
				elem = $( 'post_id_' + id ).select( '.post_ignore' )[ 0 ];
				elem.hide();
			}
		
			Event.stop( e );
		}
	};
	
iptracker.initialize();
