/**
 * @project talenthouse
 * @package th.myprofile.medialist
 * @since   07.05.2009
 *
 * This file contains functions supporting the MyProfile->CREATE processes. 
 * 
 * That means for example the sorting, top pic and edit functions in the 
 * artwork/making of tabs for 
 * 
 */
th.myprofile.medialist = {
	
	/**
	 * @method itemHtml
	 * 
	 * HTML generator for appended items
	 * This is the content-div for the newly created item
	 * 
	 * @param boolean $processing true if item should be processed (waitet and checked every few seconds if ready).
	 * 
	 */
	itemHtml: function( itemId, thumbUrl, mediatype , title , processing ) {
		var editTitle = th.params.tr_Edit; 
		if  (title != '') { editTitle = title; };
		switch (mediatype)
		{
			case 'Video':
				media_class = 'media_movie';
				break;
			case 'Image':
				media_class = 'media_pic';
				break;
			case 'Audio':
				media_class = 'media_sound';
				thumbUrl = th.params.img_DefaultAudio;
				break;
			default:
				media_class = 'media_pic';
				break;
		} 
		
		var pClass = '';
		if ( processing == true ) {
			pClass = ' processing';
		}
		var html = '<li id="' + itemId + '" class="rounded_all handle' + pClass + '" style="margin:0 0 22px 31px;">';
		html += '<p onclick="th.myprofile.medialist.mark(\'#' + itemId + '\')" style="background: #252525 url(' + thumbUrl + ') no-repeat center top;">';
		html += '<a id="itemPic' + itemId + '" href="javascript:;" title="' + title + '" class="kind_of_media ' + media_class + ' handle" style="height:63px; margin: 0;"></a>';
		html += '<a class="edit crop" title="' + title + '"  onclick="th.myprofile.medialist.edit(\'' + itemId + '\', \'' + th.params.url_ItemEdit + '/' + itemId + '\'); return false;">'+ editTitle + '</a></p>';
		if ( processing == true ) {
			html += '<div id="' + itemId + '_processing" style="background: #000 none repeat scroll 0% 0%; opacity: 0.8; position: relative; top: -63px; left: 0px; width: 103px; height: 63px;" ';
			html += ' class="handle" onclick="th.myprofile.medialist.mark(\'#' + itemId + '\')" ><div class="handle" style="width: 50px; height: 50px; margin: 0px auto;"><div id="' + itemId + '_processingswf"></div></div></div>';

			// Add callback to insert processing animation
			th.ajax.addOnLoadCallback(function() {
				swfobject.embedSWF(th.params.swfLoadingAnim, itemId + '_processingswf', "50", "50", "9.0.0", th.params.bucketPath + '/flash/expressInstall.swf', {}, { bgcolor: "#000000", wmode: "transparent" });
			});
		}
		html += '</li>';

		return html;
	},


	/**
	 * @method append
	 * 
	 * Wrapper function for appendItemHtml
	 * This function gets called by th_upload_onComplete AFTER one upload is complete !!!
	 * This basically is the FIRST function that gets called after the upload of a file !!
	 */
	append: function( itemId, thumbUrl, mediatype , title , _appendToTab, _itemProjectId ) 
	{

		if ( mediatype == 'video' )
		{
			th.myprofile.medialist.appendItemHtml(
					itemId
					, th.myprofile.medialist.itemHtml( itemId, thumbUrl, mediatype , title, false ) // since checkStatus (which gets called on the way) only processes youtube-videos for now there just isn't any point in loading this here
					, _appendToTab
					, _itemProjectId
				);
		}
		else
		{
			th.myprofile.medialist.appendItemHtml ( 
					itemId
					// , th.myprofile.medialist.itemHtml( itemId, th.params.img_DefaultVideo, mediatype , title, false )
					, th.myprofile.medialist.itemHtml( itemId, thumbUrl, mediatype , title, false )
					, _appendToTab
					, _itemProjectId
				);
		}
		// note: this call almost certainly need to be here, but another few checks are required:
		//th.myprofile .processing.add( 'import', _itemProjectId, itemId , _appendToTab );
	},


	/**
	 * @method append
	 * 
	 */
	appendImportItem: function( itemId, thumbUrl, mediatype , title , _appendToTab, _itemProjectId ) 
	{
		th.myprofile.medialist.appendItemHtml ( 
				itemId
				, th.myprofile.medialist.itemHtml( itemId, thumbUrl, mediatype , title, true )
				, _appendToTab
				, _itemProjectId
			);
		
		th.myprofile.processing.add( 'import', _itemProjectId, itemId , _appendToTab ); // this adds the current file to the processing-list !
	
	},
	
	
	
	/**
	 * Stack to hold 'Append' functions to add items to tab
	 * Used in APPEND function when the panel is not loaded, but
	 * we wish to update 
	 */
	queuedUpdatesArtwork: [],
	queuedUpdatesMakingOf: [],
	

	/**
	 * @method append
	 * 
	 * Appends HTML to the ARTWORK or MAKINGOF tabs. If the tab is not loaded 
	 * (as is the case if we create a project, then immediately upload) - then 
	 * the APPEND request is pushed onto a queue to be processed later.
	 * 
	 */
	appendItemHtml: function( itemId, itemHtml, _appendToTab, _itemProjectId ) 
	{
		if (typeof _appendToTab == 'undefined')
		{
			_appendToTab = '#' + $('div[rel*=medialist]:visible:first').attr('id');
		}
		
		oppositeTab = '#pnl_artwork';
		if ( _appendToTab == '#pnl_artwork' ) {
			oppositeTab = '#pnl_makingof';
		}
		
		// Queue updates
		if (_appendToTab == '#pnl_artwork') {
			
			// Check if panel is loaded: 
			if ( $('ul.media_list', $('#pnl_artwork')).size() > 0 )
			{
				// th.log('append: ItemHtml: PANEL LOADED - LOAD IMMEDIATELY' );
				
				// PANEL LOADED: Update immediately:
				th.myprofile.medialist.appendItemHtmlNow(  itemId, itemHtml , '#pnl_artwork' , _itemProjectId );
			}
			else
			{
				// th.log('append: ItemHtml: PANEL NOT LOADED' );
				// PANEL NOT LOADED: Queue update for ARTWORK
				th.myprofile.medialist.queuedUpdatesArtwork.push( function() {
						th.myprofile.medialist.appendItemHtmlNow(  itemId, itemHtml , '#pnl_artwork' , _itemProjectId );
				});

				// Process Q
				th.myprofile.medialist.appendClearQ();
			}
			
		} else { 

			// MAKING OF: 
			
			// Check if panel is loaded: 
			if ( $('ul.media_list', $('div#pnl_makingof')).size() > 0 ) 
			{
				// PANEL LOADED: Update immediately:
				th.myprofile.medialist.appendItemHtmlNow(  itemId, itemHtml , '#pnl_makingof' , _itemProjectId );
			} else {

				// PANEL NOT LOADED: Queue update for MAKINGOF
				th.myprofile.medialist.queuedUpdatesMakingOf.push( function() {
						th.myprofile.medialist.appendItemHtmlNow(  itemId, itemHtml , '#pnl_makingof' , _itemProjectId );
				});

				// Process Q
				th.myprofile.medialist.appendClearQ();

			}
			
		}
		
		
	},
	

	/**
	 * @method appendItemHtmlNow
	 * 
	 */
	appendItemHtmlNow: function( itemId, itemHtml, _appendToTab, _itemProjectId ) 
	{
		th.log('append: appendItemHtmlNow: [' + itemId + '][' + _appendToTab + '][' + _itemProjectId + ']', 'FunctionCall');
		
		try {
			// th.log('append: appendItemHtmlNow: SIZE [' + $('#'+itemId , $(_appendToTab + ' ul.media_list')).size()+ ']');
		} catch (e) {
			// th.log('append: appendItemHtmlNow: ERROR');
		}
		
		// On Update, check if item already there (if DB has loaded it)
		if ( $('#'+itemId , $(_appendToTab + ' ul.media_list')).size() < 1 )
		{			
			// Check the projectId has not changed (the user has not clicked another panel)
			var activeProjectId = $('ul.project_select_list a.active:first').parents('li:first').attr('id');
			if ( typeof _itemProjectId != 'undefined' && _itemProjectId != '' ) { 
				if ( _itemProjectId != activeProjectId ) {
					// user switched projects; do not append!
					return;					
				}
			}
			

			
			// Append!
			
			
			// If Artwork, check for top pic:
			if (_appendToTab == '#pnl_artwork')
			{
				// if item exists, append after it
				if ( $('li', $('#pnl_artwork ul.media_list')).size() > 0 )
				{
					$('li:first', $('#pnl_artwork ul.media_list')).after( itemHtml );
				}
				else
				{
					$('#pnl_artwork ul.media_list').prepend( itemHtml );
				}
				
				// th.myprofile.medialist.updateMediaOrder( 'artwork' , _itemProjectId ) ;
			}
			else
			{
				// th.log('append: appendItemHtmlNow: Renoving top pic thing');
						
				$('#pnl_makingof ul.media_list').prepend( itemHtml );
				
				$('.toppic', $('#pnl_makingof ul.media_list') ).each(function(){ $(this).remove('span'); });
				$('.nodrag', $('#pnl_makingof ul.media_list') ).each(function(){ $(this).removeClass('nodrag'); });
				
				// th.myprofile.medialist.updateMediaOrder( 'makingof' , _itemProjectId ) ;
			}
		
		}
		
		// Execute onLoad Callbacks (Adds Loading Animations, etc.)
		th.ajax.executeOnLoadCallbacks();

	},
	
	
	/**
	 * @method append
	 * 
	 */
	appendClearQ: function() 
	{
		if ( $('#pnl_artwork ul.media_list').size() > 0 ) 
		{
			while (th.myprofile.medialist.queuedUpdatesArtwork.length > 0)
			{
				var f = th.myprofile.medialist.queuedUpdatesArtwork.pop();
				if (typeof f == 'function'){
					f();
				}
			}
		}
		
		if ( $('#pnl_makingof ul.media_list').size() > 0 ) 
		{			
			while (th.myprofile.medialist.queuedUpdatesMakingOf.length > 0)
			{
				var m = th.myprofile.medialist.queuedUpdatesMakingOf.pop();
				if (typeof m == 'function'){
					m();
				}
			}
		} 

		th.myprofile.medialist.updateMediaCounts();
		th.myprofile.medialist.checkTopPic();
	},


	appendCheckQ: function() {
		if  (th.myprofile.medialist.queuedUpdatesArtwork.length > 0) {
			return 'You have unsaved changes, please wait while we update (KB: will change this to standard overlay with animating and cancel/continue link)';
		}
		
		return;
	},
	
	/**
	 * @method updateMediaOrder
	 * 
	 */
	updateMediaOrder: function( _activetab , projectId ) 
	{
		th.log('** updateMediaOrder [' + _activetab + '][' + projectId + ']', 'FunctionCall');

    	if (typeof projectId == 'undefined' || projectId == '') {
    		th.log('ERROR: th.myprofile.medialist: Project Id is Undefined!')
    		return;
    	}
    	
		var activetab = _activetab;
		var updateUrl = th.params.url_SortItems;
		
    	// Get artwork/makingof order array
    	var strMedia = '';
    	var comma = ',';
    	var mediaIdArray =new Array();
    	$('li', $('div#pnl_' + activetab + ' ul.media_list')).each(function(i){
    		strMedia += comma + $(this).attr('id');
    		comma = ',';
    		if ( $(this).hasClass="processing" != true ) {
    			mediaIdArray[i] = $(this).attr('id');
    		}
    	});
    	
    	// add a comma to the end
    	strMedia += ',';
    	
    	
    	// Post to server
        if (activetab == 'makingof')
        {
        	// th.log('** updateMediaOrder UPDATING: [' + _activetab + ']');
        	th.ajax.asyncQueue('orderMakingOf'+projectId, updateUrl, { 'projectId': projectId, 'makingof': strMedia });
        }
        if (activetab == 'artwork')
        {
        	// th.log('** updateMediaOrder UPDATING: [' + _activetab + ']');
        	th.ajax.asyncQueue('orderArtwork'+projectId, updateUrl, { 'projectId': projectId, 'artwork': strMedia });
		} 

        //update flash
        
    	th.flash.updateMediaOrder( projectId, activetab, mediaIdArray );
   },
	
	
	/**
	 * @method markItem
	 * 
	 * 
	 * 
	 */
	mark: function( objItem )
	{
		if ( $(objItem).hasClass('markedItem') === false )
		{
			// th.log('ADDING CLASS MARKED ITEM TO ' + $(objItem).attr('id') );
			$(objItem).addClass(
				'markedItem'
			);
		}
		else
		{
			// th.log('REMOVING CLASS MARKED ITEM FROM ' + $(objItem).attr('id') );
			$(objItem).removeClass(
				'markedItem'
			);
		}
	},
	
	
	
	

	/**
	 * @method moveItems
	 * 
	 * Moves an item to the Artwork/MakingOf list
	 * 
	 */
	moveItems: function( _moveTo ) 
	{
		var moveFrom = 'artwork';
		var moveTo = _moveTo;
		if (moveTo=='artwork')
		{
			moveFrom = 'makingof'
		} 

		var sourcePanelId = 'div#pnl_' + moveFrom;
		var targetTab = '#' + moveTo + 'Tab';

		// Get active project
		var projectId = $('ul.project_select_list a.active:first').parents('li:first').attr('id');

		// Construct Items Container
		var itemsObj = '';
		var comma = '';
		var items = [];

		$('li.markedItem', $(sourcePanelId)).each(function(i, item) {
			items.push( item.id );
			itemsObj += comma + item.id; 
	    	comma=',';
		});


		// th.log('Moving Items: [' + sourcePanelId + '][' + itemsObj + ']');

		if (itemsObj == '')
		{
			return;
		}
		
    	var count = items.length-1;

    	// Append HTML
    	for ( var i = count; i >= 0; i-- )
    	{
    		var appendItem = items[i];
    		
    		var outerHtml = $('#' + appendItem, $('div#pnl_' + moveFrom)).outerHtml();
    		var itemUid = items[i];
    		th.myprofile.medialist.appendItemHtml( itemUid, outerHtml , '#pnl_'+moveTo, projectId);
    	}
    	
    	
    	// ANIMATE: 'Move' Animation
    	var targetPos = $(targetTab, $(sourcePanelId)).position();
    	for ( var k = count; k >= 0; k-- )
    	{
    		var item = items[k];
    		var itemId = '#' + item;
    		
    		// Animate Move:
    		sourcePos = $( itemId, $('div#pnl_' + moveFrom) ).position();
    		
    		$clone = $(itemId, $('div#pnl_' + moveFrom))
    					.clone()
    					.attr('id','clone_'+itemId).css({ position : 'absolute', 'z-index': '1000', 'opacity': '.7', 'top': sourcePos.top, 'left': sourcePos.left })
						.insertAfter($(itemId, $('div#pnl_' + moveFrom)));
    		
			$(itemId, $('div#pnl_' + moveFrom)).remove();

			$clone.animate({ 
    					'top': targetPos.top+'px', 
    					'left': targetPos.left+'px' }
    					, 500, 
    					function() { 
    						$(this).remove();
    						
        		    		// Update Media Count
        		    		th.myprofile.medialist.updateMediaCounts();

        		    		// Check Top Pic
    						th.myprofile.medialist.checkTopPic();
    					}
    				);
    		
    	};
		
    	$(targetTab, $('div#pnl_' + moveFrom)).effect('pulsate',{},500)
    	
    	
		var postData = { 
			moveto: moveTo, 
			items: itemsObj
		};
    	
    	// Check Top Poc when animations are through
    	setTimeout(function() {
    		th.myprofile.medialist.checkTopPic();
    	}, 800);
    	
    	// Now make server update!
		th.ajax.asyncQueue( 'movemedia', th.params.url_MoveItems , postData );
		
		// Flash Update:
    	for ( var j = count; j >= 0; j-- )
    	{
    		// th.log('FLASH: th.flash.moveMediaToCategory [' + projectId + '][' + items[j] + '][' + moveFrom + '][' + moveTo + ']')
    		th.flash.moveMediaToCategory( projectId, items[j], moveFrom, moveTo );
    	}
    	
	},


	/**
	 * @method deleteItems
	 * 
	 * Deletes an item to the Artwork/MakingOf list
	 * 
	 */
	deleteItems: function( _activeTab , _projectId ) 
	{
		var activeTab = _activeTab;
		var projectId = _projectId;
		
		var parentPanelId = '#pnl_' + activeTab;
		
		
		// Construct Items Container
		//var itemsObj = '';
		var sChar = '';
		
		// create POST data 
		var postData = ""; 
		$(parentPanelId + ' .media_list li.markedItem').each(function(i, item) {
			postData += sChar + 'delItemId[]=' + item.id; 
			sChar='&';
		});

		// Animate out of the list
		$(parentPanelId + ' .media_list li.markedItem').each(function(){
			$(this).hide('scale', {percent: 0}, 300, function() { 
    			$(this).remove();
    		});
    	});
		
		/**
		 *  @todo start flash call NOW
		 */
		setTimeout(function(){
					// Queue delete update + execute the js-script on success
			        th.ajax.asyncQueue( 'deletemedia', th.params.url_DeleteItems, '#pnl_asyncResponse' , { data: postData, success:function(html){$( document.createElement('div') ).html(html);} });

					// update counts
					th.myprofile.medialist.updateMediaCounts();
					
			        // check top pic  
			        th.myprofile.medialist.checkTopPic();

			        // update order
					th.myprofile.medialist.updateMediaOrder( activeTab , projectId);
				}
			, 600);
		


	},
	
	/**
	 * @method checkTopPic
	 * 
	 * @param _forceUpdate Updates server even if panel looks ok!
	 */
    checkTopPic: function( _forceUpdate )
	{
		// th.log('TOPPIC: Checking for Top Pic');

		if ( $('ul.media_list', $('div#pnl_artwork')).size() < 1 )
		{
			// artwork not loaded; ignore
			// th.log('TOPPIC: Artwork Panel Not Loaded');
			return;
		}
		else
		{
			if ( $('ul.media_list li', $('div#pnl_artwork')).size() < 1 )
			{
				// th.log('TOPPIC: Reset Top Pic to Default');
				th.myprofile.medialist.unsetTopPic();
			}
			else
			{
				// th.log('TOPPIC: Artwork Panel Loaded HAS ITEMS');
				
				if ($('.toppic', $('div#pnl_artwork ul.media_list li:first')).size() > 0 ) {
					// Top pic exists in first place; all is good!
					// th.log('TOPPIC: Top Pic Already Exists');
					
					// Force update
					if ( _forceUpdate === true )
					{
						th.myprofile.medialist.setTopPic( $('div#pnl_artwork ul.media_list li:first').attr( 'id' ) );
					}

				} else {
					if ($('.toppic', $('div#pnl_artwork ul.media_list')).size() < 1) {
						// th.log('TOPPIC: Choose First Item');
						
						// no top pic exists - choose first item as top pic
						$tpId = $('li:first', $('div#pnl_artwork ul.media_list'));
						var itemId = $tpId.attr('id');
							
						if ($('#' + itemId + '_processing', $tpId).size > 0 ) {
							while ($tpId != null) {
								if ($('#' + itemId + '_processing', $tpId).size() < 1 ) {
									break;
								} else {
									$tpId = $tpId.next();
								}
							}
						}
						
						if ($tpId == null) {
							return;
						}
						
						th.myprofile.medialist.setTopPic( $tpId.attr("id") );
					}
					else
					{
						// th.log('TOPPIC: MOVE TO HEAD: ' + $('.toppic', $('div#pnl_artwork ul.media_list')).parents('li:first').attr( 'id' ));
						// top pic exists - but not in first place! reset (will move item to queue head)
						th.myprofile.medialist.setTopPic( $('.toppic', $('div#pnl_artwork ul.media_list')).parents('li:first').attr( 'id' ) );
					}
				}
			}
		}
		

	},

	
	/**
	 * @method setTopPic
	 * 
	 */
    setTopPic: function( itemId , backgroundCss  )
	{
		if ( typeof itemId == 'undefined' || itemId == '')
		{
			itemId = $('li.markedItem:first', $('div#pnl_artwork ul.media_list') ).attr( 'id' );
		}
		
		// th.log('TOPPIC: SET TOP PIC; ID:  ' + itemId);
		if ( typeof itemId != 'undefined' )
		{
			// If item processing, do not set as top pic:
			if ( $('#' + itemId + '_processing').size > 0 ) {
				return;
			}
			
    		// Remove any existing marker 
    		$('.toppic').each(function() { $(this).remove('span'); });
    		
    		// Allow dragging of elements
    		$('li.nodrag').addClass('handle');
    		$('li.nodrag').removeClass('nodrag');
    		$('a.nodrag').addClass('handle');
    		$('a.nodrag').removeClass('nodrag');
    		
    		// Add Marker to selected image
    		$('#itemPic' + itemId + '').html('<span class="toppic">&nbsp;</span>');
    		// Prevent dragging
    		$('#' + itemId + '').addClass('nodrag');
    		$('#' + itemId + ' a:first').addClass('nodrag');
    		$('#' + itemId + '').removeClass('handle');
    		$('#' + itemId + ' a:first').addClass('handle');
    		
    		

			// ACTIVE PROJECT ID CAN BE USED HERE, BECAUSE YOU ARE _ALWAYS_ LOOKING AT THE ARTWORK 
			// THAT IS BEING SET - SOMETIMES IT IS CALLED AFTER THE USER HAS CHANGED PROJECTS BUT 
			// IT LOADS THE ITEM LIST FOR THE ORDER HERE ANYWAY 
			// 
			// - OTHER ASYNC ACTIONS SHOULD BE WARY OF USING THIS PARAMETER AS IT CHANGES WHEN 
			// USERS SWITCH PROJECTS
			// 
			var projectId = ACTIVE_PROJECT_ID;
			if ( typeof projectId == 'undefined' || projectId == '' ) {
				th.log('ERROR: th.myprofile.medialist.setTopPic: PROJECT ID UNDEFINED!: ItemId = ' + itemId);
				return;
			}
			
			
    		if (typeof backgroundCss != 'undefined' && backgroundCss != '' ) {

    			// th.log('TOPPIC: Update Project CSS to Unknown:  ' + projectId);
        		
    			$('#' + projectId + ' a').css('background', backgroundCss);
    		} else {
        		// Attempt to replicate style 
    			var newStyle = $('li#' + itemId + ' p').attr('style');
    			$('#' + projectId + ' a').attr( 'style', newStyle );
    			// th.log('TOPPIC: Update Project CSS to Style :  ' + projectId + ' [' + newStyle + ']');
    		}
    		
    		
    		// Move item to head of media list
    		var html = $( 'li#' + itemId ).outerHtml();
    		$( 'li#' + itemId ).remove();
    		$('ul.media_list', $('div#pnl_artwork')).prepend(html);

    		// Unselect all images
    		th.myprofile.medialist.unmarkAll();
    		
            // Update Flash
			th.flash.setTopMedia( projectId, itemId );

            // Queue server update
			// KB: REMOVED: Server side ORDER will make first pic in artwork the top pic
            // th.ajax.asyncQueue( 'toppic', th.params.url_updatePic + '/' + projectId + '/' + itemId , {} );

			

			// Send changed order to server
			th.myprofile.medialist.updateMediaOrder( 'artwork' , projectId);
		}
	
	},
	
	

	/**
	 * @method unsetTopPic
	 * 
	 * Reset top pic to dummy image
	 * 
	 */
	unsetTopPic: function()
	{
		// KB: Disabled - if they don't want a top pic, they can delete the project
		
		/*
		// Get active project
		var projectId = $('ul.project_select_list a.active:first').parents('li:first').attr('id');
		
		if (typeof projectId == 'undefined' || projectId == '') {
			return;
		}
		
		// reset project pic to default: 
		$('ul.project_select_list .active').attr('style', th.params.img_defaultProject);
		
		// Update server:
        // Queue server update
        th.ajax.asyncQueue( 'toppic', th.params.url_updatePic + '/' + projectId + '/0', {} );
		*/
	},
	
	

	/**
	 * @method updateMediaCounts
	 *
	 * will run both updates if _appendToTab not specified 
	 * x returns count from artwork tab if neither specified
	 */
	updateMediaCounts: function(  )
	{
		var makingOfCount = 0;
		makingOfCount = $('#pnl_makingof .media_list p').size();

		if (makingOfCount > 0) {
			var nMheight = parseInt( makingOfCount/5 ) * 113 + 113;
			if (nMheight < 350) {
				nMheight = 350;
			}
			$('#pnl_makingof ul.media_list').css('height', nMheight + 'px');
			$('#itemCount_makingof').html(makingOfCount + ' ');
		} else {
			$('#itemCount_makingof').html('');
		}
		
		var artworkCount = 0;
		artworkCount = $('#pnl_artwork .media_list p').size();

		if (artworkCount == 0) {
			$('#itemCount_artwork').html('');
		} else {
			var nAheight = parseInt( artworkCount/5 ) * 113 + 113;
			if (nAheight < 350) {
				nAheight = 350;
			}
			$('#pnl_artwork ul.media_list').css('height', nAheight + 'px');
			$('#itemCount_artwork').html(artworkCount + ' ');
		}
		
	},
	
	

	
	/**
	 * @method edit
	 * 
	 * 
	 * 
	 */
	edit: function( itemId, url )
	{
		this.markOnlyCurrent( itemId );
		url = url + '?width=335&height=250';
		th.ui.thickbox.show( itemId, url );
	},
	
	/**
	 * @method submitEditForm
	 * 
	 * 
	 * @version dp-06.06.2009
	 */
	
	editSubmitFormActive: false,
	editSubmitForm : function()
	{
		if ( th.myprofile.medialist.editSubmitFormActive )  {
			return;
		}
		th.myprofile.medialist.editSubmitFormActive = true;
		
		$('#TB_ajaxContent #editItemForm').ajaxSubmit(
			    {
			    	beforeSubmit: function(){
			    		th.ui.loadingAnimation.start('#TB_ajaxContent #editItemForm');
			    	},
			    	success: function( response ){
			    		th.myprofile.medialist.editSubmitFormSuccess(response); // too much code so another helper-function gets called
			    		
			    	},
			    	complete: function() {
			    		th.myprofile.medialist.editSubmitFormActive = false;
			    		th.ui.loadingAnimation.stop();
			    	}
			    }
			); 
	}, 
	// this function gets called when sucess was returned from the ajax-request:
	editSubmitFormSuccess: function(response)
	{
		try{
			var mediaJsonObject = JSON.parse(response);
		}catch(e) {}
		
		if (typeof mediaJsonObject == 'object') // if json.parse() was correct this should be an object/array
		{
			th.flash.updateMedia(mediaJsonObject, mediaJsonObject.projectId, mediaJsonObject.mediaCategory);
			th.myprofile.medialist.setTitle( mediaJsonObject.media, mediaJsonObject.title );
			th.ui.thickbox.hide();
		}
		else// if parse wasn't correct the server returned html with the new form
		{
			if(response == '')
			{
				th.ui.thickbox.hide(); // if response was neigther good nor error just close box
			}
			else
			{
				$('#TB_ajaxContent').html(response); // new form sent by ajax request replaces the old form in the overlay-thing
			}
		}		
	},
	/**
	 * @method setTitle
	 * 
	 * 
	 * 
	 */
	setTitle : function( itemId, itemTitle )
	{
		$( '#' + itemId + ' a.edit').html( itemTitle );
		// th.log('UPDATE: [itemId: ' + itemId + '][itemTitle: ' + itemTitle + ']');
		$( '#itemPic' + itemId ).attr( 'title', itemTitle );
		$( '#itemPic' + itemId).next().attr( 'title', itemTitle );
	},
	
	/**
	 * @method markOnlyCurrent
	 * 
	 * 
	 * 
	 */
	markOnlyCurrent : function( itemId )
	{
		// th.log('MARK ONLY CURRENT');
		this.unmarkAll();
		$('#' + itemId).addClass('markedItem');
	},
	
	/**
	 * @method unmarkAll
	 * 
	 * 
	 * 
	 */
	unmarkAll : function()
	{
		// th.log('UNMARK ALL');
		$('.markedItem').removeClass('markedItem');
	},
	
	addcollaborater : function(first, last, nick, img)
	{
		if($('#role_new').val() != '' && first !='NEW' )
		{
			if( $("*").index( $('#' + nick) ) < 0)
			{
				var out 	 = '<div style="display:block; margin: 15px 0 15px 0; width:600px" id="'+ nick +'">';
				out 	 	+= '<img src="/media/user/dummie.gif" width="50" height="50" />';
				//out 	 	+= '<img src="/media/user/' + img + '" width="50" height="50" />';
				out 	 	+= '<input type="text" name="role[]" value="'+ $('#role_new').val() +'" />';
				out 		+= '<input type="text" name="firstname_add[]" value="'+ first +'" />';
				out 		+= '<input type="text" name="lastname_add[]" value="'+ last +'" />';
				out 		+= '<input type="hidden" name="nick_add[]" value="'+ nick +'" />';
				out			+= '<a onclick="$(\'#' + nick +'\').remove()" class="submit_link">delete</a>';
				$('#col_old').append(out);
				$('#search_firstname').val('');
				$('#role_new').val('');
				$('#search_lastname').val('');
				$('#role_new').btOff();
				$('#role_new').css({border:'none'});
				return;
			}
		}
		else
		{
			$('#role_new').css({border:'solid 2px red'});
			$('#role_new').btOn();
			th.addErrorToFormField('role_new', 'notempty');
		}
	},
	
	addnewcollaborater : function(email)
	{
		if($('#role_new_user').val() != '')
		{
			var id_mail = email.replace('@','_');
			id_mail = id_mail.replace('.','_');
			
			if( $("*").index( $('#' + id_mail) ) < 0)
			{
				if(th.checkEmail(email))
				{
					
					var out 	 = '<div style="display:block; margin: 15px 0 15px 0; width:600px" id="'+ id_mail +'">';
					out 	 	+= '<img src="/media/user/dummie.gif" width="50" height="50" />';
					out 	 	+= '<input type="text" name="role_new_user[]" value="'+ $('#role_new_user').val() +'" />';
					out 		+= '<input type="text" name="email[]" value="'+ email +'" />';
					out			+= '<a onclick="$(\'#' + id_mail +'\').remove()" class="submit_link">delete</a>';
					$('#col_old').append(out);
					
					$('#role_new_user').val('');
					$('#new_user_email').val('');
					
					$('#role_new_user').btOff();
					$('#new_user_email').btOff();
					
					$('#role_new_user').css({border:'none'});
					$('#new_user_email').css({border:'none'});
					return;
				}
				else
				{
					$('#new_user_email').css({border:'solid 2px red'});
					$('#new_user_email').btOn();
					th.addErrorToFormField('new_user_email', 'notanemail');
					return;
				}
			}
		}
		else
		{
			$('#role_new_user').css({border:'solid 2px red'});
			$('#role_new_user').btOn();
			th.addErrorToFormField('role_new_user', 'notempty');
		}
	}
	
};

