/**********************************
* Majority of this code belongs to IPS
* The remainder belongs to AH Modding
* http://socialiser.ahmodding.co.uk
***********************************/

var socialiser = new socialiser();

function socialiser()
{
	/**
	* Menus
	*/
	this.divs = new Array();
	this.items = new Array();
	this.openMenus = {};
	this.divcount = 0;
	this.menu_registered  = new Array();
	this.menu_openfuncs   = new Array();
	this.menu_over_css    = new Array();
	this.menu_out_css     = new Array();
	this.menu_open_event  = new Array();
	this.dynamic_register = new Array();
	this.menu_cur_open    = null;
	this.dynamic_html     = null;
	
	this.imageset;
	
	this.rightclickmenus = { };
		
	/**
	* Language
	*/
	this.languages = {
					 'gender_male'      : 'Male',
					 'gender_female'    : 'Female',
					 'gender_mystery'   : 'Gender Not Set',
					 'saving_comment'   : 'Saving Comment...',
					 'loading_tab'      : ajax_load_msg,
					 'deleting_comment' : 'Deleting Comment...'
				 	 };

	/**
	* iframe tabs
	*/
	this.iframe_tabs = {
						 'comments' : ipb_var_base_url + 'act=profile&CODE=personal_iframe_comments',
						 'settings' : ipb_var_base_url + 'act=profile&CODE=personal_iframe_settings',
						 'friends'  : ipb_var_base_url + 'act=profile&CODE=personal_iframe_friends'
					   };
					   
	/**
	* Settings
	*/
	this.settings = {
					'edit_allowed'		: 0,
					'member_id'         : 0,
					'viewer_id'         : 0,
					'img_base_url'      : '',
					'img_menu_icon'     : '',
					'default_tab'       : '',
					'img_friend_remove' : ipb_var_image_url + '/folder_profile_portal/friend_remove_small.png',
					'img_friend_add'    : ipb_var_image_url + '/folder_profile_portal/friend_add_small.png'
	 				};
	 				
	/**
	* Stored tabs
	*/
	this.stored_tabs  = { };
	
	/**
	* Stored div classes
	*/
	this.stored_div_classes = { };
	
	/**
	* Stored tabs
	*/
	this.stored_tabs_css  = { };	 				
	 				
	/**
	* Loaded tab
	*/
	var loaded_tab = null;
	
	this.register = function( cid, callback, menu_over_css, menu_out_css, event_type )
	{
		if ( event_type )
		{
			this.menu_open_event[ cid ] = ( event_type == 'onmouseover' ) ? 'onmouseover' : 'onclick';
		}
		
		this.menu_registered[ cid ] = new ips_menu_class( cid );
			
		if ( callback )
		{
			this.menu_openfuncs[ cid ] = callback;
		}
		
		if ( menu_over_css && menu_out_css )
		{
			this.menu_over_css[ cid ] = menu_over_css;
			this.menu_out_css[ cid ]  = menu_out_css;
		}
		
		return this.menu_registered[ cid ];		
	}	
	
	/**
	* Delete comment
	*/
	this.delete_comment = function( comment_id )
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		var url          = ipb_var_base_url+'act=profile&CODE=personal_ajax_delete_comment&member_id=' + this.settings['member_id'];
		var final_fields = new Array();
		
		//-----------------------------------------
		// Populate the form fields
		//-----------------------------------------
		
		final_fields['md5check']   = ipb_md5_check;
		final_fields['comment_id'] = comment_id;
		
		//-----------------------------------------
		// Ajaxify mah bad self!
		//-----------------------------------------

		do_request_function = function()
		{
			//----------------------------------
			// Ignore unless we're ready to go
			//----------------------------------

			if ( ! xmlobj.readystate_ready_and_ok() )
			{
				xmlobj.show_loading( socialiser.languages['deleting_comment'] );
				return;
			}

			xmlobj.hide_loading();

			//----------------------------------
			// INIT
			//----------------------------------

			var html = xmlobj.xmlhandler.responseText;

			if ( html == 'nopermission' )
			{
				alert( message_pop_up_lang['no_permission'] );

			}
			else if ( html != 'error' )
			{
				document.getElementById( 'pp-comments-wrap' ).innerHTML = html;
				
				//-----------------------------------------
				// Reload comments tab
				//-----------------------------------------
				
				if ( socialiser.loaded_tab == 'comments' )
				{
					socialiser.load_content_tab( 'comments' );
				}
			}
		};

		//----------------------------------
		// LOAD XML
		//----------------------------------

		xmlobj = new ajax_request();
		xmlobj.onreadystatechange( do_request_function );
		var xmlreturn = xmlobj.process( url, 'POST', xmlobj.format_for_post( final_fields ) );

		return false;
	};
	
	/**
	* Show friend add/remove
	*/
	this.show_friend_add_or_remove = function( add_friend )
	{
		try
		{
			var _div  = document.getElementById( 'pp-friend-wrap' );
			var _html = '';
			
			if ( _div.id )
			{
				if ( add_friend )
				{
					_html  = "<img src='" + this.settings['img_friend_add'] + "' id='pp-friend-img' alt='' border='0' /> ";
					_html += "<a href='#' onclick='friends_pop(\"&amp;do=add&amp;member_id=" +  this.settings['member_id'] + "&amp;md5check=" + ipb_md5_check + "\"); socialiser.show_friend_add_or_remove( 0 ); return false;' id='pp-friend-text'>" + this.languages['friend_add'] + "</a>";
				}
				else
				{
					_html  = "<img src='" + this.settings['img_friend_remove'] + "' id='pp-friend-img' alt='' border='0' /> ";
					_html += "<a href='#' onclick='friends_pop(\"&amp;do=remove&amp;member_id=" +  this.settings['member_id'] + "&amp;md5check=" + ipb_md5_check + "\"); socialiser.show_friend_add_or_remove( 1 ); return false;' id='pp-friend-text'>" + this.languages['friend_remove'] + "</a>";
			
				}
		
				_div.innerHTML = _html;
			}
		}
		
		catch( error )
		{
			
		}
	};	
	
	
	/**
	* Save comment
	*/
	this.save_comment = function()
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		var url          = ipb_var_base_url+'act=profile&CODE=personal_ajax_add_comment&member_id=' + this.settings['member_id'];
		var final_fields = new Array();
		
		//-----------------------------------------
		// Close menu
		//-----------------------------------------
		
		menu_action_close();
		
		//-----------------------------------------
		// Populate the form fields
		//-----------------------------------------
		
		final_fields['md5check'] = ipb_md5_check;
		final_fields['comment']  = document.getElementById( 'pp-acomment-textarea' ).value;
	
		//-----------------------------------------
		// Ajaxify mah bad self!
		//-----------------------------------------
		
		do_request_function = function()
		{
			//----------------------------------
			// Ignore unless we're ready to go
			//----------------------------------

			if ( ! xmlobj.readystate_ready_and_ok() )
			{
				xmlobj.show_loading( socialiser.languages['saving_comment'] );
				return;
			}

			xmlobj.hide_loading();

			//----------------------------------
			// INIT
			//----------------------------------

			var html = xmlobj.xmlhandler.responseText;

			if ( html == 'nopermission' )
			{
				alert( message_pop_up_lang['no_permission'] );
				return;
			}
			
			else if ( html == 'error-no-comment' )
			{
				show_inline_messages_instant( 'pp_comment_error' );
				return;
			}
			
			else if ( html != 'error' )
			{
				document.getElementById( 'pp-comments-wrap' ).innerHTML = html;
				xmlobj.execute_javascript( html );
				
				//-----------------------------------------
				// Reload comments tab
				//-----------------------------------------
				
				if ( socialiser.loaded_tab == 'comments' )
				{
					socialiser.load_content_tab( 'comments' );
				}
				
				document.getElementById( 'pp-acomment-textarea' ).value = '';
			}
		};

		//----------------------------------
		// LOAD XML
		//----------------------------------

		xmlobj = new ajax_request();
		xmlobj.onreadystatechange( do_request_function );
		var xmlreturn = xmlobj.process( url, 'POST', xmlobj.format_for_post( final_fields ) );
		
		return false;
		
	};	
	
	this.init = function()
	{
		//-----------------------------------------
		// INIT tabs
		//-----------------------------------------
		
		this.divs     = document.getElementsByTagName( 'DIV' );
		this.divcount = 0;

		//----------------------------------
		// Sort through and grab divs
		//----------------------------------

		for ( var i = 0 ; i <= this.divs.length ; i++ )
		{
			try
			{
				if ( ! this.divs[i].id )
				{
					continue;
				}
			}
			catch(error)
			{
				continue;
			}

			var divid   = this.divs[i].id;
			var divname = ipsclass.get_name_from_text( this.divs[i].id );
			var divnum  = ipsclass.get_id_from_text( this.divs[i].id );

			//----------------------------------
			// Work with it?
			//----------------------------------

			if ( divname == 'pp-content-tab' )
			{
				var _highlight = 0;
				
				this.stored_tabs[ divnum ]     = this.divs[i];
				this.stored_tabs_css[ divnum ] = this.divs[i].className;
				
				this.divs[i].style.cursor = 'pointer';
				this.divs[i].onclick      = this.tab_onclick;
				//divs[i].onRightClick = this.make_menu.bindAsEventListener( divs[i].id, divs[i].items );	
				
				/* create new menu */
				this.divs[i].items = new Array();
				
				var tabname = divid.replace( /pp-content-tab-/, '' );
				//alert( tabname );			
									
				this.divs[i].items.push( { 'type': 'separator' } );
				//items		 = push( { 'type': 'seperator' } );
				this.divs[i].items.push( { 'title': 'Go to my Gallery', 'url': ipb_var_base_url + '&autocom=socialiser&module=gallery&mid=' + this.settings['member_id'] } );	
				
				this.i = i;	
				
				// BOOKMARKED FOR 1.1
				
					
				//this.divs[i].menu = new Menu( 
				//	{ 
				//		'id'         : this.divs[i].id,
				//		'items'      : this.divs[i].items,
				//		'currentTab' : this.divs[i]
				//	}	
				//);
				
				//Object.extend( this.divs[i].menu, {
				//	Base: this
				//});
				
				//this.divs[i].menu.build();
				
				//this.divs[i].boundContext = this.divs[i].menu.show.bindAsEventListener( this.divs[i].menu )										
				
				//Event.observe( $( divid ), 'contextmenu', this.divs[i].boundContext );
				
				//this._stop.bindAsEventListener( this.divs[1] );
				
				//-----------------------------------------
				// Show this tab?
				//-----------------------------------------
				
				if ( this.settings['default_tab'] != "" )
				{
					if ( this.settings['default_tab'] == divnum )
					{
						_highlight = 1;
					}
				}
				else if ( divcount == 0 )
				{
					_highlight = 1;
				}
				
				//----------------------------------
				// Set correct classes / display
				//----------------------------------
				
				if ( _highlight == 1)
				{
					// First tab...
					this.divs[i].className     = this.settings['tab_on_css'];
					this.divs[i].style.display = 'block';
				}
				else
				{
					// Second tab
					
					if ( this.divs[i].className != this.settings['tab_shaded_css'] )
					{
						this.divs[i].className = this.settings['tab_off_css'];
					}
					
					this.divs[i].style.display = 'block';
				}

				this.divcount++;
			}
		}
	};
	
	this._stop = function( e )
	{
		Event.stop( e );		
	};
	
	/**
	* On mouseover event
	*/
	this.tab_onclick = function( event )
	{
		//-------------------------------
		// No? Get one then
		//-------------------------------

		var tabid = ipsclass.get_id_from_text( this.id );
		
		// Stop scrolling to top of the page...
		ipsclass.cancel_bubble( event );
		
		//----------------------------------
		// Load tab
		//----------------------------------

		socialiser.tab_load( tabid );
		
		return false;
	};
	
	this._openURL = function( e )
	{	
		Event.stop( e );
	};	
	
	/**
	* On mouseover event
	*/
	this.tab_load = function( tabid )
	{
		//-------------------------------
		// Got it?
		//-------------------------------

		for ( var i in socialiser.stored_tabs )
		{
			if ( i == tabid )
			{
				socialiser.stored_tabs[ i ].style.display   = 'block';
				socialiser.stored_tabs[ i ].className       = this.settings['tab_on_css'];
			}
			else
			{
				socialiser.stored_tabs[ i ].style.display   = 'block';
				
				if ( socialiser.stored_tabs_css[ i ] == this.settings['tab_shaded_css'] )
				{
					socialiser.stored_tabs[ i ].className = this.settings['tab_shaded_css'];
				}
				else
				{
					socialiser.stored_tabs[ i ].className = this.settings['tab_off_css'];
				}
			}
		}
		
		//----------------------------------
		// Load tab
		//----------------------------------

		socialiser.load_content_tab( tabid );
		
		return false;
	};								
	 									   	
	this.load_content_tab = function( tab )
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		var html = '';
		
		//-----------------------------------------
		// IE is a pain...
		//-----------------------------------------
		
		if ( is_ie && !is_ie7 )
		{
			var _div   = document.getElementById( 'pp-main-tab-content' );
			var _width = parseInt( _div.offsetWidth - 12 );
	
			// IE adds the 12 px from the padding set below back into the width..
		}
		
		//-----------------------------------------
		// Got a rating?
		//-----------------------------------------
		
		if ( tab )
		{
			//-----------------------------------------
			// Make sure messages are hidden
			//-----------------------------------------
			
			hide_inline_messages_instant();
			
			//-----------------------------------------
			// Loaded tab...
			//-----------------------------------------
			
			this.loaded_tab = tab;
			
			//-----------------------------------------
			// iFrame tab
			//-----------------------------------------
			
			if ( this.iframe_tabs[ tab ] )
			{
				var url = this.iframe_tabs[ tab ] + '&member_id=' + this.settings['member_id'] + '&md5check=' + ipb_md5_check;
				
				document.getElementById( 'pp-main-tab-content' ).innerHTML = '';
				
				var iframeinclude                 = new iframe_include();
				iframeinclude.iframe_id		      = 'pp-main-tab-content-iframe';
				iframeinclude.iframe_add_to_div   = 'pp-main-tab-content';
				iframeinclude.iframe_main_wrapper = 'pp-iframe-wrap';
				iframeinclude.init();
				iframeinclude.include( url );
				
				document.getElementById( 'pp-main-tab-content' ).className     = socialiser.settings['content_bg'];				
			}
			//-----------------------------------------
			// Normal tab
			//-----------------------------------------
			
			else
			{
				//----------------------------------
				// INIT
				//----------------------------------
	
				var url = ipb_var_base_url+'autocom=socialiser&CODE=load_tab&member_id=' + this.settings['member_id'] + '&tab=' + tab + '&md5check=' + ipb_md5_check;
	
				/*--------------------------------------------*/
				// Main function to do on request
				// Must be defined first!!
				/*--------------------------------------------*/
	
				do_request_function = function()
				{
					//----------------------------------
					// Ignore unless we're ready to go
					//----------------------------------
	
					if ( ! xmlobj.readystate_ready_and_ok() )
					{
						xmlobj.show_loading( socialiser.languages['loading_tab'] );
						return;
					}
	
					xmlobj.hide_loading();
	
					//----------------------------------
					// INIT
					//----------------------------------
	
					var html = xmlobj.xmlhandler.responseText;
					
					if ( html != 'error' )
					{ 
						document.getElementById( 'pp-main-tab-content' ).innerHTML = html;
					
						//-----------------------------------------
						// Topic attachment sizes...
						//-----------------------------------------
					
						try
						{
							fix_linked_image_sizes();
							xmlobj.execute_javascript( html );
							
							//-----------------------------------------
							// Resize box nicely...
							//-----------------------------------------
							
							document.getElementById( 'pp-main-tab-content' ).style.height  = 'auto';
							document.getElementById( 'pp-main-tab-content' ).style.padding = '6px';
							document.getElementById( 'pp-main-tab-content' ).className     = socialiser.settings['content_bg'];
							
							//-----------------------------------------
							// IE is still a pain
							//-----------------------------------------
	
							if ( is_ie )
							{
								_div.style.width     = ( _width ) ? _width + "px" : 'auto';
								_div.style.overflowX = 'auto';
							}
						}
						catch(error)
						{
							//alert(error);
						}
					}
					else
					{
						alert( js_error_no_permission );
					}
				};
	
				//----------------------------------
				// LOAD XML
				//----------------------------------
	
				xmlobj = new ajax_request();
				xmlobj.onreadystatechange( do_request_function );
	
				xmlobj.process( url );
				
				return false;
			}
		}
	};
}

var Menu = Class.create();

Menu.prototype = {
	
	//------------------------------
	// Constructor
	// @access private
	//------------------------------
	initialize: function( menuData ){
		if ( typeof( menuData ) != 'undefined' )
		{
			this.id          = menuData.id;
			this.items       = menuData.items;
			this.masterClass = menuData.masterClass;
			this.currentTab  = menuData.currentTab;
			this.boundHide   = this.hide.bindAsEventListener( this );
			this.trackEvents = new Object; // Track events for event observing purposes
		}
	},
	
	build: function(){
		this._createMenu( this.items );
	},
	
	_removeAllOpenMenus: function( event ){
		
		for( var i in this.Base.openMenus )
		{
			//alert( this.Base.openMenus );
			var _id    = i;
			var _bound = this.Base.openMenus[i];
			
			if ( typeof( _id ) != 'undefined' )
			{				
				Effect.Fade( $(_id), {duration: 0.7} );
			}
		}	
		
		this.Base.openMenus = {};	
		this.Base.last		= {};
	},
	
	//------------------------------
	// Show the menu
	// @access public
	//------------------------------
	show: function( e )
	{		
		this._removeAllOpenMenus();
		
		/* Get various coords we need */
		pX = parseInt( e.clientX );
		pY = parseInt( e.clientY );
		pW = parseInt( document.body.clientWidth );
		mW = $( this.theMenu ).getWidth();
		
		/* Now position */
		if( ( pX + mW ) > pW )
		{
			var padding = 0;
			
			// FF not play nice :(
			if( Browser.is_moz )
			{
				x = document.defaultView.getComputedStyle(this.theMenu,null).getPropertyValue('padding-right');
				padding = ( typeof(x) == 'undefined' ) ? 0 : parseInt( x );
			}
			
			pX = pX - mW - padding;
		}
			
		//----------------------------------
		// Get ID of menu DIV to show
		//----------------------------------
		
		var left_px = ipsclass.get_obj_leftpos( this.currentTab );
		//alert( left_px );
		var top_px  = ipsclass.get_obj_toppos( this.currentTab ) + this.currentTab.offsetHeight;
		var ifid    = this.currentTab.id;
		
		try
		{
			if ( is_safari && ! ipb_is_acp )
			{
				top_px += 20;
			}
		}
		catch(error)
		{
			if ( is_safari )
			{
				top_px += 20;
			}
		}
		
		//----------------------------------
		// Show menu DIV.. but keep it underneath
		//----------------------------------
		
		this.theMenu.style.zIndex  = -1;
		
		//----------------------------------
		// Try and keep it on screen
		//----------------------------------
		
		var width = parseInt( this.theMenu.style.width ) ? parseInt( this.theMenu.style.width ) : this.theMenu.offsetWidth;
		
		if ( (left_px + width) >= document.body.clientWidth )
		{
			left_px = left_px + this.currentTab.offsetWidth - width;
		}
		
		//-----------------------------------------
		// Firefox bump
		//-----------------------------------------
		
		if ( is_moz )
		{
			top_px -= 1;
		}
		
		this.theMenu.style.position = "absolute";	
		
		//----------------------------------
		// Finalize menu position
		//----------------------------------
		
		this.theMenu.style.left   = left_px + "px";
		this.theMenu.style.top    = top_px  + "px";
		this.theMenu.style.zIndex = 100;	
		
		
		$( this.theMenu ).setStyle( {
			left: this.theMenu.style.left,
			top: this.theMenu.style.top
		});							
		
		Effect.Appear( $( this.theMenu ), { duration: 0.7 } );
		Event.observe( document, 'click', this.boundHide );		
		this.Base.openMenus[ this.theMenu.id ] = this.theMenu.id;		
		//this.theMenu.show();
		Event.stop( e );		
	},
	
	//------------------------------
	// Hide the menu
	// @access public
	//------------------------------
	hide: function(){
		Effect.Fade( $( this.theMenu ), { duration: 0.7 } );
		Event.stopObserving( window, 'click', this.boundHide );
	},
	//------------------------------
	// Create the menu in the page
	// @access private
	//------------------------------
	_createMenu: function( items ){
		
		if ( items.length == 0 )
		{
			return;
		}
		
		var css = 'Menu';
		
		/* Create the shell for the menu */
		menuShell = document.createElement( 'DIV' );
		Element.extend( menuShell ); //Important
		
//		this.Base.divs[ this.Base.i ]  = "tab_menuid_" + this.id;
//		this.Base.i++;
		
		menuShell.id = "tab_menuid_" + this.id;
		menuShell.hide();
		menuShell.className = css;
		
		/* now loop through each item and populate */
		items.each( function( i, index ){
			
			// What type?
			switch( i.type )
			{
				case 'separator':
					menuitem = document.createElement( 'DIV' );
					menuitem.className = 'separator';
					menuShell.appendChild( menuitem );
					menuitem = null;
				break;
				default:
					
					menuitem           = document.createElement( 'A' );
					menuitem.innerHTML = i.title;
					menuitem.id        = "tab_menuid_" + this.id + "_" + index;
					menuitem.href      = i.url;				
					menuitem.innerHTML = "<img src='" + this.Base.imageset + "/user-online.png' /> " + menuitem.innerHTML;							
					
					menuShell.appendChild( menuitem );
					menuitem = null;
				break;
			}
		}.bind( this )); // Important - so that 'this' can be used in the iterator
		
		document.getElementById( 'pp-tabwrap' ).appendChild( menuShell );
		
		/* For ease of use */
		this.theMenu = menuShell;		
	},
	
	//------------------------------
	// Delete the menu
	// @access private
	//------------------------------
	deleteSelf: function(){
		
		/* remove menu from page */
		this.theMenu.hide();
		
		/* remove event handlers */
		/*items = this.theMenu.getElementsByTagName('A');
		
		items.each( function( i, index ){
			Event.stopObserving( i, 'click', this.trackEvents[ index ] );
		}.bind(this));*/
		
		this.theMenu.remove(); // Deletes it from the document
		
	}
	
}
