/* Copyright (c) 2004, Noah Sorscher
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	¥ 	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * 	¥ 	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	¥ 	Neither the name of the Noah Sorscher nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
#import "tController.h"
#include "Movies.h"
#include "tPlayback.h"
#import "defaults.h"
#import "MHFormatter.h"
#import "tTextView.h"
#import "iTableView.h"

@interface NSObject (tcAdditions)
+(void)setMovie:(NSMovie *)movie;
-(void)openSprites:(id)sender;
-(void)mhWeb:(id)sender;
-(NSArray *)movieArray;
@end

@interface NSMatrix (tcAdditions)
- (void)selectCellAtRow:(NSNumber *)row;
@end

@implementation NSMatrix (tcAdditions)
- (void)selectCellAtRow:(NSNumber *)row
{   [self selectCellAtRow:[row intValue] column:0];    }
@end

@interface MHOrderCell : NSTextFieldCell {
    int rowForImage;
    BOOL pic;
}
@end

@implementation MHOrderCell : NSTextFieldCell
- (id)init
{
    rowForImage = -1;
    pic = NO;
    return [super init];
}
- (int)imageRow
{
    return rowForImage;
}
- (void)setImageRow:(int)row
{
    rowForImage = row;
}
- (void)setPictureTime:(BOOL)flag
{
    pic = flag;
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    //NSLog(@"drawing");
    if (pic) {
        NSImage *image = [NSImage imageNamed:@"monitors"];
        if (image) {
            NSSize isize = [image size];
            NSRect srcRect;
            srcRect.origin.x = srcRect.origin.y = 0;
            srcRect.size = isize;
            NSRect dstRect = cellFrame;
            dstRect.origin.x += 2;
            dstRect.origin.y += 1;
            dstRect.size = isize;
            [image drawInRect:dstRect fromRect:srcRect operation:NSCompositeSourceOver fraction:1];
            return;
        }
    }
    [super drawInteriorWithFrame:cellFrame inView:controlView];
}
@end

@implementation tController

//////////
//
// constants
//
//////////
/*
// constants used for QTUtils_SaveMovie
#define kSavePrompt				"Save Movie as:"
#define kSaveMovieFileName			"untitled.mov"
#define kSaveResName				"Movie Resource"

// constants used for QTUtils_GetMovieFileLoopingInfo
enum {
	kNormalLooping					= 0, 
	kPalindromeLooping				= 1, 
	kNoLooping					= 2
};

#define kQTVideoEffectsMinVers		0x0300		// version of QT that first supports QT video effects
#define kQTFullScreenMinVers		0x0209		// version of QT that first supports full-screen calls
#define kQTWiredSpritesMinVers		0x0300		// version of QT that first supports wired sprites

#define kInvalidFileRefNum	-1	
*/





//NSArray *expandFolders(NSArray *theArray);

tPlaylist *mainModel, *currentModel;
NSMutableArray *symlinksTraversed;
MHMovie *currentMovie;



- (MHMovie *)currentMovie
{
    return currentMovie;
}

- (MHMovie *)playingMovie
{
    return [player currentMovie];
}

- (void)setPlayingMovie:(MHMovie *)movie
{
	if ([movie isKindOfClass:[NSMenuItem class]]) {
		// this is called from tPlaylist rightClick (sender)
		movie = [movie representedObject];
	}
    [player movieDidChangeTo:movie];
    [player playMovies:self];
}

- (void)addMovieChangeListener:(id)listener
{
    if (nil == movieChangeListeners)
        movieChangeListeners = [[NSMutableArray alloc] init];
    [movieChangeListeners addObject:listener];
    [listener movieDidChangeTo:currentMovie];
}

- (void)setCurrentMovie:(MHMovie *)aMovie
{
    currentMovie = aMovie;
    if (nil != movieChangeListeners) {
        int i, n = [movieChangeListeners count];
        for (i=0;i<n;i++) {
            [[movieChangeListeners objectAtIndex:i] movieDidChangeTo:aMovie];
        }
    }
    [MHSprite setMovie:aMovie];
    [summaryTable setDelegate:currentMovie]; // set the delegate first because when you set the data source the iTableView will ask the delegate a few things, and the old delegate/datasource might have just been released
    [summaryTable setDataSource:currentMovie];
    [summaryTable reloadData];
	NSString *title = @"MetaHoot";
	if (aMovie) title = [NSString stringWithFormat:@"MetaHoot - %@", [aMovie description]];
	[mainWindow setTitle:title];
}

- (void)willDisposeMovie:(MHMovie *)aMovie sender:(id)sender
{
    int i, n = [thePlaylists count];
    if (sender == [thePlaylists objectAtIndex:0]) {
        for (i=1;i<n;i++) {
            [(tPlaylist *)[thePlaylists objectAtIndex:i] removeMovie:[[thePlaylists objectAtIndex:i] indexForMovie:aMovie]];
        }
    }
    if (sender == currentModel && sender != mainModel) {
        [mainModel removeMovie:[mainModel indexForMovie:aMovie]];
    }
    if (aMovie == currentMovie || nil == aMovie) {
        currentMovie = nil;
        if (nil != movieChangeListeners) {
            n = [movieChangeListeners count];
            for (i=0;i<n;i++) {
                [[movieChangeListeners objectAtIndex:i] movieDidChangeTo:nil];
            }
        }
    }
    if (aMovie == [player currentMovie])
        [player movieDidChangeTo:nil];
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)sender defaultFrame:(NSRect)defaultFrame
{
    NSRect r = [sender frame];
    if ([[[mainTabView selectedTabViewItem] identifier] isEqualToString:@"Movie"]) {
        NSRect content = [[mainWindow contentView] frame];
        r.size.height = [[currentMovie objectForKey:@"Original Height"] intValue] + r.size.height - content.size.height + 36;
        r.size.width = [[currentMovie objectForKey:@"Original Width"] intValue] + r.size.width - content.size.width + 22;
        [player performSelector:@selector(inMainWindow:) withObject:self afterDelay:0];
        return r;
    } else {
        [mainWindow performClose:self];
        [player showMini];
        return [mainWindow frame];
        //return [[sender screen] frame];
    }
}

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject
{
    if (anObject == tracksTable) {
        if (!tracksEditTextView)
            tracksEditTextView = [[tTextView alloc] init];
        [tracksEditTextView setDelegate2:tracks];
        return tracksEditTextView;
    }
    if (anObject == theTable) {
        if (!tableEditTextView)
            tableEditTextView = [[tTextView alloc] init];
        [tableEditTextView setDelegate2:currentModel];
        return tableEditTextView;
    }
	if (anObject == summaryTable) {
		if (!summaryEditTextView)
			summaryEditTextView = [[tTextView alloc] init];
		[summaryEditTextView setDelegate2:currentMovie];
		return summaryEditTextView;
	}
    return nil;
}

- (void)windowDidBecomeMain:(NSNotification *)aNotification
{
    //NSLog(@"main");
    NSArray *subs = [movieControls subviews];
    int i, n = [subs count];
    for (i=0;i<n;i++)
	[[subs objectAtIndex:i] performSelector:@selector(setEnabledObject:) withObject:[NSNumber numberWithBool:YES] afterDelay:0];
}

- (void)windowDidResignMain:(NSNotification *)aNotification
{
    //NSLog(@"resign");
    NSArray *subs = [movieControls subviews];
    int i, n = [subs count];
    for (i=0;i<n;i++) {
	NSButton *button = [subs objectAtIndex:i];
	if ([button respondsToSelector:@selector(setEnabled:)])
	    [button setEnabled:NO];
    }
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [thePlaylists count];
}
/*
- (NSMatrix *)saveSize
{
    return saveSize;
}
*/
- (NSTableView *)mainTable
{
    return theTable;
}

- (NSTableView *)summaryTable
{
	return summaryTable;
}

- (NSTableView *)plTable { return playlistTable; }
- (NSTableView *)tracksTable {return tracksTable; }

- (IBAction)copyMetadataFromMenu:(id)sender
{
    if (![sender isKindOfClass:[NSEvent class]]) return;
    NSMenu *menu = [[[NSMenu alloc] init] autorelease];
    int i, n = [theTable numberOfRows];
    for (i=0;i<n;i++) {
        NSMenuItem *item = [[[NSMenuItem alloc] init] autorelease];
        [item setTitle:[[currentModel movieForIndex:i] stringValue]];
        [item setTarget:self];
        if ([currentModel movieForIndex:i] != currentMovie)
            [item setAction:@selector(copyMetadataFrom:)];
        [menu addItem:item];
    }
    [NSMenu popUpContextMenu:menu withEvent:sender forView:nil];
}

- (IBAction)copyMetadataFrom:(id)sender
{
    if (!currentMovie) return;
    int index = [[sender menu] indexOfItem:sender];
    MHMovie *movie = [currentModel movieForIndex:index];
    [movie updateQTMovie];
    OSErr err = CopyMovieUserData([movie QTMovie], [currentMovie QTMovie], kQTCopyUserDataReplace);
    if (err) NSLog(@"error copying user data: %ld", err);
    [currentMovie readMetadata];
	[currentMovie setObject:[movie objectForKey:@"File Name"] forKey:@"File Name"];
    [theTable reloadData];
    [summaryTable reloadData];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if (rowIndex < 0 || rowIndex >= [thePlaylists count]) return nil;
    return [[thePlaylists objectAtIndex:rowIndex] name];
}

- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if (rowIndex < 0 || rowIndex >= [thePlaylists count]) return;
    tPlaylist *aPlaylist = [thePlaylists objectAtIndex:rowIndex];
    if ([(NSString *)anObject length])
        [aPlaylist setName:anObject];
}

- (BOOL) tableView: (NSTableView *) tableView shouldSelectRow: (int) rowIndex
{
    //NSLog(@"selecting playlist table row: %d", rowIndex);
    if (rowIndex < 0 || rowIndex >= [thePlaylists count]) {
        currentModel = mainModel = nil;
        [self setTableModel:nil];
        [totalMB setStringValue:@""];
        return NO;
    }
    tPlaylist *aModel = [thePlaylists objectAtIndex:rowIndex];
    currentModel = mainModel = aModel;
    [self setTableModel:aModel];
    [searchField2 setStringValue:@""];
	if ([aModel sortedString]) {
		int i, n = [[theTable tableColumns] count];
		for (i=0;i<n;i++) {
			NSTableColumn *tc = [[theTable tableColumns] objectAtIndex:i];
			if ([[tc identifier] isEqualToString:[aModel sortedString]]) {
				[theTable selectColumn:i byExtendingSelection:NO];
				break;
			}
		}
	}
    [theTable reloadData];
    [mainModel tableView:theTable shouldSelectRow:0];
    [theTable selectRow:0 byExtendingSelection:NO];
	[aModel tableViewSelectionDidChange:nil];
    [aModel setCurrentPlayingIndex:[aModel currentPlayingIndex]];
    [self updateTotals];
    return YES;
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    [self tableView:nil shouldSelectRow:[playlistTable selectedRow]];
}

- (void)tableView:(NSTableView *)tview willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tc row:(int)rowIndex
{
    if (![cell respondsToSelector:@selector(setTextColor:)]) return;
    if (rowIndex >= 0 && rowIndex < [thePlaylists count]) {
        if ([(tPlaylist *)[thePlaylists objectAtIndex:rowIndex] options])
            [cell setTextColor:[NSColor blueColor]];
        else
            [cell setTextColor:[NSColor blackColor]];
    }
}

- (BOOL)deleteForTableView:(NSTableView *)tableView
{
    if ([playlistTable selectedRow] == 0) return YES;
    int choice = NSRunAlertPanel(@"Are you sure you want to remove the selected playlist?", @"Use Command-Delete to bypass this warning.", @"Remove Playlist", @"Cancel", nil);
    switch (choice) {
        case NSAlertDefaultReturn:
            return [self commandDeleteForTableView:tableView];
        default:
            return YES;
    }
}

- (BOOL)commandDeleteForTableView:(NSTableView *)tableView
{
    [self removePlaylist:nil];
    return YES;
}

- (void)clearTableView:(NSTableView *)tableView
{
    [self removePlaylist:nil];
}

- (NSDragOperation)tableView:(NSTableView*)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)operation
{
    NSArray *types = [[info draggingPasteboard] types];
    if ([types containsObject:@"moviesFromOther"]) {
        if (!row || row == [playlistTable selectedRow] || operation != NSTableViewDropOn) return NSDragOperationNone;
        return NSDragOperationCopy;
    } else if ([types containsObject:NSFilenamesPboardType]) {
        return NSDragOperationCopy;
    }
    return NSDragOperationNone;
}

- (BOOL)tableView:(NSTableView*)tableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation
{
    NSPasteboard *b = [info draggingPasteboard];
    int i, n;
    NSArray *types = [b types];
    n = [types count];
    NSString *type = nil;
    for (i=0;i<n;i++) {
        type = [types objectAtIndex:i];
        type = nil;
    }
    if ([types containsObject:@"moviesFromOther"] && operation == NSTableViewDropOn) {
        if (!row || row == [playlistTable selectedRow]) return NO;
        NSArray *rows = [b propertyListForType:@"moviesFromOther"];
        NSMutableArray *toMove = [NSMutableArray array];
        n = [rows count];
        for (i=0;i<n;i++)
            [toMove addObject:[currentModel movieForIndex:[[rows objectAtIndex:i] intValue]]];
        tPlaylist *newModel = [thePlaylists objectAtIndex:row];
        [newModel addMovies:toMove];
        [theTable reloadData];
    } else if ([types containsObject:NSFilenamesPboardType]) {
        NSArray *files = [b propertyListForType:NSFilenamesPboardType];
        n = [files count];
        for (i=0;i<n;i++) {
            NSString *path = [files objectAtIndex:i];
            BOOL isDir = NO;
            if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir) {
                // make a synced playlist
                tPlaylist *p = [[tPlaylist alloc] initWithController:self];
                [p setName:[path lastPathComponent]];
                [thePlaylists addObject:p];
                [playlistTable reloadData];
                NSArray *options = [NSArray arrayWithObject:[NSString stringWithFormat:@"Sync With Folder|%@", path]];
                [p setOptions:options];
            }
        }
    }
    return YES;
}

- (void)tableView:(NSTableView *) tview rightClickWithEvent:(NSEvent *)event
{
    NSPoint point = [event locationInWindow];
    point = [tview convertPoint:point fromView:nil];
    int row = [tview rowAtPoint:point];
    NSMenu *menu = [[[NSMenu alloc] init] autorelease];
    NSMenuItem *item = nil;
    if (row >= 0 && row < [thePlaylists count]) {
        item = [[[NSMenuItem alloc] initWithTitle:@"Edit Playlist Options..." action:@selector(editSmartPlaylist:) keyEquivalent:@""] autorelease];
        [item setTarget:self];
        [menu addItem:item];
        item = [[[NSMenuItem alloc] initWithTitle:@"Delete Playlist" action:@selector(removePlaylist:) keyEquivalent:@""] autorelease];
        [item setTarget:self];
        [menu addItem:item];
    } else {
        item = [[[NSMenuItem alloc] initWithTitle:@"New Playlist" action:@selector(newPlaylist:) keyEquivalent:@""] autorelease];
        [item setTarget:self];
        [menu addItem:item];
    }
    [self tableView:tview shouldSelectRow:row];
    [tview selectRow:row byExtendingSelection:NO];
    //NSLog(@"point: %g x %g column: %d", point.x, point.y, index);
    [NSMenu popUpContextMenu:menu withEvent:event forView:tview];
}

- (void)setTableModel:(tPlaylist *)aModel
{
    [theTable setDataSource:aModel];
    [theTable setDelegate:aModel];
    [theTable setTarget:aModel];
    [(NSTableView *)theTable setAction:@selector(doSingleClickWithDelay:)];
    [theTable setDoubleAction:@selector(doDoubleClick:)];
    [theSaveTable setDataSource:aModel];
    [theSaveTable setDelegate:aModel];
    [imageView setDelegate:aModel];
    //[editBox setDelegate:aModel];
}

- (void)addPlaylist:(tPlaylist *)newPlaylist
{
    if (newPlaylist == nil) {
        newPlaylist = [(tPlaylist *)[tPlaylist alloc] initWithController:self];
        [newPlaylist setName:[NSString stringWithFormat:@"Playlist %d", [thePlaylists count]]];
        //[thePlaylists addObject:newPlaylist];
    }
    [thePlaylists addObject:newPlaylist];
    [playlistTable reloadData];
    [self tableView:playlistTable shouldSelectRow:[thePlaylists count]-1];
    [playlistTable selectRow:[thePlaylists count]-1 byExtendingSelection:NO];
}

- (IBAction)newPlaylist:(id)sender
{
    tPlaylist *newPlaylist = [(tPlaylist *)[tPlaylist alloc] initWithController:self];
    int newIndex = [thePlaylists count];
    [newPlaylist setName:[NSString stringWithFormat:@"Playlist %d", newIndex]];
    [thePlaylists addObject:newPlaylist];
    [playlistTable reloadData];
    [self tableView:nil shouldSelectRow:newIndex];
    [playlistTable selectRow:newIndex byExtendingSelection:NO];
    [playlistTable editColumn:0 row:newIndex withEvent:nil select:YES];
}

- (IBAction)newSmartPlaylist:(id)sender
{
    [[thePlaylists objectAtIndex:0] showOptions];
}

- (IBAction)editSmartPlaylist:(id)sender
{
    int index = [playlistTable selectedRow];
    if (index >= 1 && index < [thePlaylists count])
        [[thePlaylists objectAtIndex:index] showOptions];
}

- (IBAction)removePlaylist:(id)sender
{
    int index = [playlistTable selectedRow];
    if (index < 1 || index >= [thePlaylists count]) return;
    //if ([thePlaylists count] < 2) return;
    [thePlaylists removeObjectAtIndex:index];
    [playlistTable reloadData];
    [self tableView:nil shouldSelectRow:[playlistTable selectedRow]];
}

- (NSArray *)playlists
{
    return [NSArray arrayWithArray:thePlaylists];
}


- (NSToolbarItem *)toolbar:(NSToolbar *)tb itemForItemIdentifier:(NSString *)tbit willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem *tbi;
    NSArray *idents = [NSArray arrayWithObjects:@"Add", @"Remove", @"Play", @"Add Column", @"Search", @"Chapters", @"Movie", @"Edit", @"Timeline", @"Sprite", @"Web", @"Info", @"Movie Controller", @"Movie Controls", nil];
    void *actions[] = { @selector(openFiles:) , @selector(remove:) , @selector(play:), @selector(addColumn:), @selector(search), @selector(openChapters:), @selector(openMovie), @selector(editingDrawer:), @selector(timeline), @selector(sprite), @selector(www), @selector(summary:), @selector(search), @selector(search) };
    
    int i, n = [idents count];
    for (i=0;i<n;i++) {
        if ([tbit isEqualToString:[idents objectAtIndex:i]]) {
            tbi = [[MHToolbarItem alloc] initWithItemIdentifier:tbit];
            if (i == 3) { // Add Column
                NSRect aRect = [addColumnView frame];
                [tbi setView:addColumnView];
                [tbi setMaxSize:aRect.size];
                [tbi setMinSize:aRect.size];
            } else if (i == 4) { // Search
                NSRect aRect = [searchContentView frame];
                [tbi setView:searchContentView];
                [tbi setMinSize:aRect.size];
                aRect.size.width += 75;
                [tbi setMaxSize:aRect.size];
            } else if (i == 12) { // Movie Controller
                NSRect aRect = [movieController frame];
                [tbi setView:movieController];
                aRect.size.width = 600;
                [tbi setMaxSize:aRect.size];
                aRect.size.width = 200;
                [tbi setMinSize:aRect.size];
	    } else if (i == 13) { // Movie Controls
		NSRect aRect = [movieControls frame];
		[tbi setView:movieControls];
		[tbi setMaxSize:aRect.size];
		[tbi setMinSize:aRect.size];
            } else {
                [tbi setAction:actions[i]];
                [tbi setTarget:self];
                [tbi setImage:[NSImage imageNamed:tbit]];
            }
            [tbi setLabel:tbit];
            [tbi setPaletteLabel:tbit];
            [tbi autorelease];
            return tbi;
        }
    }
    return nil;
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
    if ([[toolbar identifier] isEqualToString:@"miniWindowToolbar"])
        return [NSArray arrayWithObjects:@"Movie Controls", @"Movie Controller", nil];
    return [NSArray arrayWithObjects:@"Movie Controls", @"Movie Controller", @"Add Column", @"Search", @"Sprite", NSToolbarFlexibleSpaceItemIdentifier, nil];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
    return [NSArray arrayWithObjects:@"Add", @"Remove", @"Add Column", @"Search", NSToolbarSeparatorItemIdentifier, NSToolbarSpaceItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, @"Movie", @"Timeline", @"Sprite", @"Web", @"Movie Controller", @"Movie Controls", @"Chapters", nil];
}

- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem
{
    return YES;
}

- (void)toolbarDidRemoveItem:(NSNotification *)notification
{
    [self toolbarChanged];
}

- (void)toolbarWillAddItem:(NSNotification *)notification
{
    //if (opening) return;
    [[MFClickThroughDisabler alloc] initWithControl:[[notification userInfo] objectForKey:@"item"] window:[self mainWindow]];
    [self toolbarChanged];
}

- (void)toolbarChanged
{
    BOOL controllerVisible = NO;
    NSToolbar *toolbar = [mainWindow toolbar];
    if ([toolbar isVisible]) {
        int i, n = [[toolbar items] count];
        for (i=0;i<n;i++) {
            if ([[[[toolbar items] objectAtIndex:i] itemIdentifier] isEqualToString:@"Movie Controller"]) {
                controllerVisible = YES;
                break;
            }
        }
    }
}

- (void)refreshToolbarItems:(NSArray *)list
{
    NSArray *items = [[mainWindow toolbar] items];
    int i, n = [items count];
    for (i=0;i<n;i++) {
        NSToolbarItem *item = [items objectAtIndex:i];
        if ([list containsObject:[item itemIdentifier]]) {
            [[mainWindow toolbar] removeItemAtIndex:i];
            [[mainWindow toolbar] insertItemWithItemIdentifier:[item itemIdentifier] atIndex:i];
        }
    }
}

- (IBAction)customizeToolbar:(id)sender
{
    if (![[mainWindow toolbar] customizationPaletteIsRunning])
        [[mainWindow toolbar] runCustomizationPalette:nil];
}

- (IBAction)versionCheck:(id)sender
{
    NSString *vString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.applesolutions.com/bantha/version"]];
    //NSString *vString = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:@"/Users/nsorscher/Desktop/version"]];
    int v = [vString intValue];
    if (v <= 28) NSRunAlertPanel(@"No New Version", @"There is no new version of this program available at this time", @"OK", nil, nil);
    else {
        int choice = NSRunAlertPanel(@"New Version Found", @"There is a new unstable beta of this program available.  Download it now?", @"Download", @"Cancel", nil);
        if (choice == NSAlertDefaultReturn) [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.applesolutions.com/bantha/MetaHootUnstable.php"]];
    }
}

- (void)openMovie
{
    [player setPMovieView:movieView];
    [viewWindow makeKeyAndOrderFront:nil];
    [player movieDidChangeTo:currentMovie];
}
/*
- (IBAction)editingDrawer:(id)sender
{
    //[currentModel learn];
    //[editDrawer toggle:nil];
    NSRect rect;
    rect.origin.x = rect.origin.y = 0;
    rect.size.width = 200;
    rect.size.height = 50;
    NSArray *views = [editSplitView subviews];
    if (!views || [views count] != 2) return;
    NSView *theView = [views objectAtIndex:1];
    [theView setFrame:rect];
    [editSplitView adjustSubviews];
    if ([theView acceptsFirstResponder])
        [mainWindow makeFirstResponder:theView];
}
*/
- (void)timeline
{
    [timeLine open:nil];
}

- (void)sprite
{	[sprite openSprites:nil];	}

- (void)www
{	[www mhWeb:nil];		}

/*
-(BOOL)windowShouldClose:(id)sender
{
    //[NSApp terminate:nil];
    return YES;
}
*/
- (IBAction)saveWarning:(id)sender
{
    //NSLog(@"savewarning");
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    if (![defs boolForKey:@"noSaveWarn"]) {
        int choice = NSRunAlertPanel(@"Warning", @"This function (\"Save in place\") will modify your source files.  Your original data may be damaged or destroyed.  Keeping back-ups is highly recommended.", @"OK", @"Cancel", @"OK And Disable Warning");
        switch (choice) {
            case NSAlertDefaultReturn:
                break;
            case NSAlertAlternateReturn:
                [saveType performSelector:@selector(selectCellAtRow:) withObject:[defs objectForKey:t_saveType] afterDelay:0];
                return;
                break;
            case NSAlertOtherReturn:
                [defs setBool:YES forKey:@"noSaveWarn"];
                [defs synchronize];
                break;
        }
    }
    [self saveInSource:nil];
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{
    [self search];
}

- (IBAction)okay:(id)sender
{
    [self savePrefs];
    [prefs orderOut:nil];
}
/*
- (IBAction)testMethod:(id)sender
{
    ExitMovies();
    EnterMovies();
}
*/

- (BOOL)isXML:(NSString *)path
{
    NSString *content = [NSString stringWithContentsOfFile:path];
    if (nil == content) return NO;
    if ([content hasPrefix:@"<?xml"]) return YES;
    return NO;
}

- (IBAction)replaceMovieWith:(id)sender
{
    if (!currentMovie) return;
    NSOpenPanel *theOpenPanel = [NSOpenPanel openPanel];
    NSArray *theSelection;
    int result;
    
    [theOpenPanel setCanChooseFiles:YES];
    [theOpenPanel setCanChooseDirectories:NO];
    [theOpenPanel setResolvesAliases:YES];
    [theOpenPanel setAllowsMultipleSelection:NO];
    result = [theOpenPanel runModalForDirectory:nil file:nil types:nil];
    if (result != NSOKButton)
        return;
    theSelection = [theOpenPanel filenames];
    if (![theSelection count])
        return;
    NSMovie *newMovie = [[NSMovie alloc] initWithURL:[NSURL fileURLWithPath:[theSelection objectAtIndex:0]] byReference:NO];
    if (newMovie)
        [currentMovie setMovie:newMovie];
}

- (IBAction)openPlaylist:(id)sender
{
    tPlaylist *aPlaylist;
    NSString *aPath;
    NSArray *URLs = [MHUtil showOpenPanel];
    if ([URLs count] == 0) return;
    NSMutableArray *thePaths = [[NSMutableArray alloc] init];
    NSDictionary *entry;
    [symlinksTraversed removeAllObjects];
    int i, n = [URLs count];
    for (i=0;i<n;i++)
        [thePaths addObjectsFromArray:[self expandStringFolder:[[URLs objectAtIndex:i] path]]];
    n = [thePaths count];
    for (i=0;i<n;i++) {
        aPath = [thePaths objectAtIndex:i];
        aPlaylist = [(tPlaylist *)[tPlaylist alloc] initWithController:self];
        if ([self isXML:aPath]) {
            entry = [NSDictionary dictionaryWithContentsOfFile:aPath];
        } else {
            entry = [self parseTabDoc:aPath];
        }
        NSArray *added = [[thePlaylists objectAtIndex:0] addFromDefsEntry:[entry objectForKey:@"movieData"]];
        [aPlaylist addMovies:added];
        [aPlaylist setName:[entry objectForKey:@"name"]];
        [self addPlaylist:aPlaylist];
    }
}

- (IBAction)openFiles:(id)sender
{
    NSURL *theURL;
    int i, n;
    NSArray *theSelection;
    NSMutableArray *paths = [[NSMutableArray alloc] init];
    //NSMovie *aMovie;
    
    theSelection = [MHUtil showOpenPanel];
    n = [theSelection count];
    if (n == 0) return;
    
    for (i=0; i < n; i++) {
        theURL = [theSelection objectAtIndex:i];
        [paths addObject:[theURL path]];
    }
    makeDupes = YES;
    //[NSThread detachNewThreadSelector:@selector(openFilesFromArray:) toTarget:self withObject:paths];
	[self openFilesFromArray:paths];
}

- (IBAction)openURL:(id)sender
{
    NSString *input = [urlText stringValue];
    [self openFilesFromArray:[NSArray arrayWithObject:input]];
    //[NSThread detachNewThreadSelector:@selector(openFilesFromArray:) toTarget:self withObject:[NSArray arrayWithObject:input]];
    [urlWindow orderOut:nil];
}

- (IBAction)openData:(id)sender
{
    NSOpenPanel *theOpenPanel = [NSOpenPanel openPanel];
    NSString *theSelection;
    int result;
    
    [theOpenPanel setCanChooseFiles:YES];
    [theOpenPanel setCanChooseDirectories:NO];
    [theOpenPanel setResolvesAliases:YES];
    [theOpenPanel setAllowsMultipleSelection:NO];
    result = [theOpenPanel runModalForDirectory:nil file:nil types:nil];
    if (result == NSOKButton) {
        theSelection = [[[theOpenPanel URLs] objectAtIndex:0] path];
    } else {
        return;
    }
    
    // what to do with a database with no movies?
}

- (IBAction)openDivx:(id)sender
{
/*
    NSArray *selection = [MHUtil showOpenPanel];
    int i, n = [selection count];
    if (0 == [selection count]) return;
    NSString *path;
    
    path = [[selection objectAtIndex:0] path];
    NSString *tempPath, *newPath, *name = [path lastPathComponent];
    newPath = tempPath = [[MHUtil supportDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", name]];
    BOOL isDir;
    int count = 1;
    while ([[NSFileManager defaultManager] fileExistsAtPath:tempPath isDirectory:&isDir])
        tempPath = [newPath stringByAppendingFormat:@" %d.mp3", count++];
    newPath = tempPath;
    NSArray *args = [NSArray arrayWithObjects:path, newPath, nil];
    //[NSThread detachNewThreadSelector:@selector(getMp3:) toTarget:self withObject:args];
    [self getMp3:args];
    */
}

- (void)getMp3:(NSArray *)args
{
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"getMp3" ofType:nil];
    //NSTask *task = [NSTask launchedTaskWithLaunchPath:resourcePath arguments:args];
    //[pool release];
}


- (void)openFilesFromArray:(NSArray *)paths
{
    [self openFilesFromArray:paths model:mainModel];
}

- (void)openFilesFromArray:(NSArray *)paths model:(tPlaylist *)theModel
{
    //NSLog(@"tController openFilesFromArray");
    int i, n, maxColumns, oldTotal;
    NSMutableArray *thePaths;
    NSArray *somePaths;
    NSString *aPath;
    MHMovie *theMovie;
    //NSAutoreleasePool *pool;
    
    [openLock lock];
    //pool = [[NSAutoreleasePool alloc] init];
    thePaths = [[NSMutableArray alloc] init];
    if ([thePlaylists count] == 0 || theModel == nil) {
        theModel = [(tPlaylist *)[tPlaylist alloc] initWithController:self];
        [theModel setName:@"Playlist"];
        [self addPlaylist:theModel];
    }
    maxColumns = [autoColumns intValue];
    [symlinksTraversed removeAllObjects];
    n = [paths count];
    for (i=0;i<n;i++) {
        somePaths = [self expandStringFolder:[paths objectAtIndex:i]];
        [thePaths addObjectsFromArray:somePaths];
    }
    oldTotal = [theTable numberOfRows];
    cancelled = NO;
    [openingProgBar performSelectorOnMainThread:@selector(setDoubleValue:) withObject:0 waitUntilDone:NO];
    [openingWindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
    n = [thePaths count];
    tPlaylist *library = [thePlaylists objectAtIndex:0];
    for (i=0;i<n;i++) {
        theMovie = nil;
        aPath = [thePaths objectAtIndex:i];
        [openingFileText performSelectorOnMainThread:@selector(setStringValue:) withObject:aPath waitUntilDone:NO];
        if (!makeDupes)
            theMovie = [library movieWithPath:aPath];
        if (!theMovie) {
            //NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
            theMovie = [[[MHMovie alloc] initWithPath:aPath] autorelease];
            //[pool2 release];
            if (theMovie) {
                if ([[NSUserDefaults standardUserDefaults] boolForKey:@"addSeparateAudio"]) [theMovie addSeparateAudio];
                [library addMovie:theMovie];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"liveUpdateNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:theMovie forKey:@"ALL"]];
            }
        }
        if (theModel != library)
            [theModel addMovie:theMovie];
        [openingProgBar performSelectorOnMainThread:@selector(setDoubleValueObject:) withObject:[NSNumber numberWithDouble:(double)i/(double)n] waitUntilDone:NO];
        if (cancelled) break;
    }
    [theModel updateCategoriesForTable:theTable upTo:maxColumns];
    [theTable reloadData];
    if ([theTable numberOfRows] <= oldTotal)
        oldTotal--;
    [theModel tableView:theTable shouldSelectRow:oldTotal];
    [theTable selectRow:oldTotal byExtendingSelection:NO];
    [self updateTotals];
    [openingFileText performSelectorOnMainThread:@selector(setStringValue:) withObject:@"" waitUntilDone:NO];
    [openingProgBar performSelectorOnMainThread:@selector(setDoubleValue:) withObject:0 waitUntilDone:NO];
    [openingWindow performSelectorOnMainThread:@selector(orderOut:) withObject:nil waitUntilDone:NO];
    [[mainWindow contentView] performSelectorOnMainThread:@selector(setNeedsDisplayObject:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
    [self savePrefs];
    if (![self playingMovie]) [player movieDidChangeTo:currentMovie];
    [openLock unlock];
    //[pool release];
    makeDupes = NO;
	
}

- (IBAction)cancel:(id)sender
{
    cancelled = YES;
    //[saving terminate];
    [theSave cancel];
    [save orderOut:nil];
    //NSLog(@"posting notification of cancel");
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"cancelSave" object:nil];
}

- (void)updateTotals
{
    [totalMB setStringValue:[NSString stringWithFormat:@"%@, %@, %@",  
        [self getDisplayMovie:[currentModel getNumberOfFiles]], 
        [MHUtil displayTime:[currentModel getTotalTime]], 
        [MHUtil displaySize:[currentModel getTotalMB]]]];
    [[mainWindow contentView] setNeedsDisplay:YES];
}

- (NSString *)getDisplayMovie:(int)movies
{
	/* Super Deluxe Movies to Display Convertor -- Hmmmmmmmm */
	if( movies == 1 ) return [NSString stringWithFormat:@"1 movie"];
	else return [NSString stringWithFormat:@"%d movies", movies];
}	

/*
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{	
    OSErr theError;
    theError = EnterMovies();
    [theTable selectRow:0 byExtendingSelection:NO];
}
*/

- (IBAction)shuffle:(id)sender
{
    MHMovie *sMovie = [currentModel movieForIndex:[theTable selectedRow]];
    [currentModel sortByIdentifier:@"Order"];
    [theTable performSelector:@selector(setHighlightedTableColumn:) withObject:[theTable tableColumnWithIdentifier:@"Order"] afterDelay:0]; // k, don't know why this doesn't work straight off but...
    if ([[[sender image] name] isEqualToString:@"shuff2"]) {
        [currentModel unshuffle];
        [sender setImage:[NSImage imageNamed:@"shuff"]];
    } else {
        [currentModel shuffle];
        [sender setImage:[NSImage imageNamed:@"shuff2"]];
    }
    [theTable reloadData];
    if (sMovie) {
        int index = [currentModel indexForMovie:sMovie];
        [theTable selectRow:index byExtendingSelection:NO];
    }
}

- (IBAction)setFloating:(id)sender
{
    if ([floatWindow state])
        [viewWindow setLevel:NSFloatingWindowLevel];
    else
        [viewWindow setLevel:NSNormalWindowLevel];
}

- (IBAction)remove:(id)sender
{
    if ([theTable selectedRow] == -1)
        [self removeColumn:nil];
    else
        [self removeRow:nil];
}

- (void)removeColumn:(id)sender
{
    int index = [theTable selectedColumn];
    if (index == -1) return;
    NSArray *columns = [theTable tableColumns];
    NSTableColumn *aColumn = [columns objectAtIndex:index];
    [theTable removeTableColumn:aColumn];
    [theTable reloadData];
    [currentModel tableView:theTable shouldSelectRow:0];
    [theTable selectRow:0 byExtendingSelection:NO];
}

- (void)removeRow:(id)sender
{
    int i;
    for (i=[theTable numberOfRows]-1;i>=0;i--) {
        if ([theTable isRowSelected:i])
            [currentModel removeMovie:i];
    }
    [self updateTotals];
    [theTable reloadData];
    [[theTable delegate] tableViewSelectionDidChange:nil];
    //[currentModel tableView:theTable shouldSelectRow:[theTable selectedRow]];
}

- (IBAction) removeAll:(id)sender
{
    [mainModel removeAll];
    [theTable reloadData];
    [self updateTotals];
    [self setCurrentMovie:nil];
}

- (IBAction)showAllCols:(id)sender
{
    [currentModel updateCategoriesForTable:theTable upTo:-1];
}

- (IBAction)play:(id)sender
{
    [player playMovies:nil];
}

- (IBAction)openChapters:(id)sender
{
    //[theChapters open:nil];
    [self setMainTabViewName:@"Chapters"];
}

- (void)savePrefs
{
    //NSLog(@"tController");
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSArray *cols = [theTable tableColumns];
    NSMutableArray *colData = [[NSMutableArray alloc] init];
    int i;
    
    for (i=0; i<[cols count]; i++) {
        [colData addObject:[[cols objectAtIndex:i] identifier]];
        [colData addObject:[NSNumber numberWithInt:[[cols objectAtIndex:i] width]]];
    }
    //[defs setObject:colData forKey:t_cols];
    [init savePrefs];
    [theTable autosaveNow];
    
    //tModel *aModel;
    //[defs removeObjectForKey:@"playlists"];
    NSMutableArray *lists = [NSMutableArray array];
    NSMutableArray *names = [NSMutableArray array];
    NSMutableArray *sorts = [NSMutableArray array];
    NSMutableArray *options = [NSMutableArray array];
    NSString *sort = [[thePlaylists objectAtIndex:0] sortedString];
    if (!sort) sort = @"";
    [sorts addObject:sort];
    for (i=1; i<[thePlaylists count]; i++) {
        tPlaylist *p = [thePlaylists objectAtIndex:i];
        NSArray *list = [p movieArray];
        [names addObject:[p name]];
        sort = [p sortedString];
        if (!sort) sort = @"";
        [sorts addObject:sort];
        NSArray *o = [p options];
        if (!o) o = [NSArray array];
        [options addObject:o];
        int j, m = [list count];
        for (j=0;j<m;j++)
            [[list objectAtIndex:j] setListNumber:i];
    }
    [lists addObject:[(tPlaylist *)[thePlaylists objectAtIndex:0] defsEntry]];
    [defs setObject:lists forKey:@"playlists"];
    [defs setObject:names forKey:@"playlistNames"];
    [defs setObject:sorts forKey:@"playlistSorts"];
    [defs setObject:options forKey:@"playlistOptions"];
    [theTable reloadData];
    
    NSArray *views = [playlistSplitView subviews];
    if (views && [views count] == 2)
        [defs setInteger:[[views objectAtIndex:0] frame].size.width forKey:@"playlistListWidth"];
    [defs synchronize];
}

- (IBAction)nextMovie:(id)sender
{
    if (![theTable numberOfRows]) return;
    int index = [theTable selectedRow] + 1;
    if (index >= [theTable numberOfRows])
        index = 0;
    [theTable selectRow:index byExtendingSelection:NO];
}

- (IBAction)prevMovie:(id)sender
{
    if (![theTable numberOfRows]) return;
    int index = [theTable selectedRow] - 1;
    if (index < 0 )
        index = [theTable numberOfRows] - 1;
    [theTable selectRow:index byExtendingSelection:NO];
}

- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
    NSString *ident = [tabViewItem identifier];
    BOOL multi = [currentModel count] > 1;
    if ([ident isEqualToString:@"Main"] || !multi) {
        [navPrevious setTransparent:YES];
        [navNext setTransparent:YES];
        [navPrevious setEnabled:NO];
        [navNext setEnabled:NO];
    } else {
        [navPrevious setTransparent:NO];
        [navNext setTransparent:NO];
        [navPrevious setEnabled:YES];
        [navNext setEnabled:YES];
    }
    if ([ident isEqualToString:@"Main"])
        [navMain setImage:[NSImage imageNamed:@"table2"]];
    else
        [navMain setImage:[NSImage imageNamed:@"table"]];
    if ([ident isEqualToString:@"Info"])
        [navInfo setImage:[NSImage imageNamed:@"inf2"]];
    else
        [navInfo setImage:[NSImage imageNamed:@"inf"]];
    if ([ident isEqualToString:@"Chapters"])
        [navChapters setImage:[NSImage imageNamed:@"chaps2"]];
    else
        [navChapters setImage:[NSImage imageNamed:@"chaps"]];
    if ([ident isEqualToString:@"Tracks"])
        [navTracks setImage:[NSImage imageNamed:@"tracks2"]];
    else
        [navTracks setImage:[NSImage imageNamed:@"tracks"]];
    int i, n = [viewMenu numberOfItems];
    for (i=0;i<n;i++)
        [[viewMenu itemAtIndex:i] setState:[[[viewMenu itemAtIndex:i] title] rangeOfString:ident].length];
}

- (IBAction) changeMainTabViewSetting:(id)sender
{
    NSString *incoming = nil;
    if ([sender isKindOfClass:[NSPopUpButton class]])
        incoming = [sender titleOfSelectedItem];
    else if ([sender isKindOfClass:[NSMenuItem class]] || [sender isKindOfClass:[NSButton class]])
        incoming = [sender title];
    if (!incoming || [incoming isEqualToString:@""]) {
        [self setMainTabViewIndex:0];
        return;
    }
    id cmov = currentMovie;
    if (!cmov) cmov = [NSNull null];
    NSArray *items = [NSArray arrayWithObjects:@"Main View", @"Movie", @"Metadata and Info", @"Tracks", @"Chapters", nil];
    NSArray *objects = [NSArray arrayWithObjects:self, self, cmov, tracks, theChapters, nil];
    int i;
    for (i=0;i<[items count];i++) {
        if ([incoming isEqualToString:[items objectAtIndex:i]] ||
            [[[[mainTabView tabViewItems] objectAtIndex:i] identifier] isEqualToString:incoming]) {
                [self setMainTabViewIndex:i];
                id object = [objects objectAtIndex:i];
                if ([object respondsToSelector:@selector(movieDidChangeTo:)])
                    [object movieDidChangeTo:currentMovie];
                return;
        }
    }
    [self setMainTabViewIndex:0];
}

- (void)    setMainTabViewIndex:(int)index
{
    [mainTabView selectTabViewItemAtIndex:index];
    [mainWindow makeKeyAndOrderFront:self];
}

- (void)    setMainTabViewName:(NSString *)name
{
    [mainTabView selectTabViewItemWithIdentifier:name];
    [mainWindow makeKeyAndOrderFront:self];
}

- (void)awakeFromNib
{
    //NSLog(@"tController");
    
	[movieView setEditable:YES];
    [playlistTable setTarget:self];
    [playlistTable setDoubleAction:@selector(editSmartPlaylist:)];
	int n = [[summaryTable tableColumns] count];
    
    [imageSplitView setAutosaveName:@"cover image split view"];
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    [saveInSourceFolder setState:[defs boolForKey:@"saveInSourceFolder"]];
    [self saveInSource:nil];
    makeDupes = NO;
    opening = YES;
    openLock = [[NSLock alloc] init];
    symlinksTraversed = [[NSMutableArray alloc] init];
    thePlaylists = [[NSMutableArray alloc] init];
    tPlaylist *library = [[tPlaylist alloc] initWithController:self];
    [library setName:@"Library"];
    [thePlaylists addObject:library];
    NSArray *scrollviews = [NSArray arrayWithObjects:[[playlistTable superview] superview], [[theTable superview] superview], nil];
    int i;
    for (i=0;i<[scrollviews count];i++)
        if ([[scrollviews objectAtIndex:i] respondsToSelector:@selector(setAutohidesScrollers:)])
            [[scrollviews objectAtIndex:i] setAutohidesScrollers:YES];
    currentMovie = nil;
    movieChangeListeners = nil;
    toolbarDisabler = nil;
    theSave = nil;
    tableEditTextView = tracksEditTextView = nil;
    //[editBox setDelegate:self];
    [theTable performSelector:@selector(setEditsOnEnterObj:) withObject:[NSNumber numberWithBool:YES] afterDelay:0];
    [theTable restoreFromAutosave];
    if ([theTable columnWithIdentifier:@"Order"] == -1) {
        NSTableColumn *ocol = [theTable addColumnWithName:@"Order"];
        [ocol setWidth:25];
        int oldIndex = [theTable columnWithIdentifier:@"Order"];
        [theTable moveColumn:oldIndex toColumn:0];
    }
    [[theTable tableColumnWithIdentifier:@"Order"] setDataCell:[MHOrderCell new]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replaceCurrentMovieWith:) name:@"replaceCurrentMovieNotification" object:nil];
    
    NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"mainWindowToolbar"];
    [toolbar setDelegate:self];
    [toolbar setAllowsUserCustomization:YES];
    [toolbar setAutosavesConfiguration:YES];
    [mainWindow setToolbar:toolbar];
    opening = NO;
    [self toolbarWillAddItem:nil];
    NSNumber *width = [defs objectForKey:@"playlistListWidth"];
    if (width) {
        NSArray *views = [playlistSplitView subviews];
        if (views && [views count] == 2) {
            NSRect rect = [[views objectAtIndex:0] frame];
            rect.size.width = [width intValue];
            [[views objectAtIndex:0] setFrame:rect];
            [playlistSplitView adjustSubviews];
            [[[playlistTable tableColumns] objectAtIndex:0] setWidth:rect.size.width];
        }
    }
    NSTextField *searchField = nil;
    int w = [searchContentView frame].size.width - 10;
    NSRect frame = NSMakeRect(5, 6, w, 22);
    if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_2)
	searchField = [[NSSearchField alloc] initWithFrame:frame];
    else
        searchField = [[NSTextField alloc] initWithFrame:frame];
    if ([searchField respondsToSelector:@selector(setBezelStyle:)])
        [searchField setBezelStyle:NSTextFieldRoundedBezel];
    [searchField setDelegate:self];
    [searchField setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
    searchField2 = searchField;
    [searchContentView addSubview:searchField];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(coverImageFound:) name:@"CoverImageFoundNotification" object:nil];
}

- (void) coverImageFound:(NSNotification *)note
{
    NSString *path = [note object];
    if (![path isKindOfClass:[NSString class]]) return;
    if (![currentMovie objectForKey:@"Cover Image"]) [currentMovie setImageFile:path];
}

- (void)replaceCurrentMovieWith:(NSNotification *)note
{
    MHMovie *newMovie = [[MHMovie alloc] initWithPath:[note object]];
    [newMovie setEdited:YES];
    [mainModel replaceMovie:currentMovie withMovie:newMovie];
}

- (IBAction)addColumn:(id)sender
{
    NSString *theName, *newName = [addComboBox stringValue];
    theName = newName;
    int index = 1;
    int i = 0;
    while (index != -1) {
        if (i != 0)
            theName = [NSString stringWithFormat:@"%@ %d", newName, i];
        index = [theTable columnWithIdentifier:theName];
        i++;
    }
    
    NSTableColumn *newColumn = [[NSTableColumn alloc] initWithIdentifier:theName];
    [[newColumn headerCell] setStringValue:theName];
    //if ([theName hasPrefix:@"File Path"])
    [[newColumn dataCell] setFormatter:[[MHFormatter alloc] initWithColumn:newColumn]];
    [theTable addTableColumn:newColumn];
    [self resizeColumns];
    [theTable autosaveNow];
    [theTable reloadData];
}

- (IBAction)addColumnFromMenu:(id)sender
{
    //NSLog(@"insert column at: %d", rightClickCol);
    NSString *title = [sender title];
    NSTableColumn *newColumn = [[NSTableColumn alloc] initWithIdentifier:title];
    [[newColumn headerCell] setStringValue:title];
    NSArray *cols = [theTable tableColumns];
    if (rightClickCol == 0) rightClickCol = 1;
    if ([cols isKindOfClass:[NSMutableArray class]] && rightClickCol < [cols count] && rightClickCol >= 0)
        [(NSMutableArray *)cols insertObject:newColumn atIndex:rightClickCol];
    else
        [theTable addTableColumn:newColumn];
    [theTable reloadData];
    [self resizeColumns];
    [theTable autosaveNow];
    [theTable reloadData];
}

- (void)setRightClickColumn:(int)aCol
{
    rightClickCol = aCol;
}

- (IBAction)removeColumnFromMenu:(id)sender
{
    NSString *title = [sender title];
    NSTableColumn *col = [theTable tableColumnWithIdentifier:title];
    if (col) {
        [theTable removeTableColumn:col];
        [theTable autosaveNow];
    }
}

- (void)resizeColumns
{
    int i, n;
    NSRect theBounds;
    NSTableColumn *aColumn;
    NSArray *theColumns = [theTable tableColumns];
    int width;
    
    n = [theColumns count];
    theBounds = [theTable bounds];
    width = theBounds.size.width / n;
    for (i=0; i<n; i++) {
        aColumn = [theColumns objectAtIndex:i];
        if ([aColumn width] > width)
            [aColumn setWidth:width];
    }
}

- (IBAction)saveInSource:(id)sender
{
    //NSLog(@"saveinsource");
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    BOOL state = [saveInSourceFolder state];
    BOOL saveInPlace = [saveType selectedRow] == 2;
    [defs setInteger:[saveType selectedRow] forKey:t_saveType];
    [defs setBool:state forKey:@"saveInSourceFolder"];
    [defs synchronize];
    if (saveInPlace) state = YES;
    [saveBrowseButton setEnabled:!state];
    if (state)
        [saveDirPath setTextColor:[NSColor grayColor]];
    else
        [saveDirPath setTextColor:[NSColor blackColor]];
    [saveInSourceFolder setEnabled:!saveInPlace];
}

- (IBAction)saveBox:(id)sender
{
    int index;
    if ([self playingMovie])
        [[self playingMovie] saveCurrentHeight];
    
    [theSaveTable reloadData];
	[saveButton setEnabled:YES];
    [save makeKeyAndOrderFront:nil];
    index = [theTable selectedRow];
    if (index < 0 && [currentModel count]) index = 0;
    [theSaveTable selectRow:index byExtendingSelection:NO];
    [theSaveTable scrollRowToVisible:index];
}

- (IBAction)selectChanged:(id)sender
{
    int i, n;
    n = [mainModel numberOfRowsInTableView:theTable];
    for (i=0;i<n;i++) {
        if ([[currentModel movieForIndex:i] isEdited])
            [theSaveTable selectRow:i byExtendingSelection:YES];
        else
            [theSaveTable deselectRow:i];
    }
}

- (IBAction)saveFiles:(id)sender
{
    int i, n = [theSaveTable numberOfRows];
	/*
    NSMutableString *unsafes = [NSMutableString stringWithString:@""];
    int row = [saveType selectedRow];
    if (row == 2) {
        int numUnsafe = 0;
        for (i=0;i<n;i++) {
            if ([theSaveTable isRowSelected:i] && [[currentModel movieForIndex:i] saveInPlaceUnSafe]) {
                if ([unsafes length]) [unsafes appendString:@", "];
                [unsafes appendString:[[currentModel movieForIndex:i] stringValue]];
                numUnsafe++;
            }
        }
        if (numUnsafe) {
            if (numUnsafe == 1) unsafes = (NSMutableString *)@"Warning: This Movie Has Changes That Will Not Be Saved By \"Save In Place.\"";
            else [unsafes insertString:@"Warning: The Following Movies Have Changes That Will Not Be Saved By \"Save In Place\": " atIndex:0];
            int result = NSRunAlertPanel(unsafes, @"", @"Save Anyway", @"Cancel", nil);
            if (result == NSAlertAlternateReturn) return;
        }
    }
	 */
    NSString *dirPath = [saveDirPath stringValue];
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    [defs setInteger:[saveType selectedRow] forKey:t_saveType];
    
    //[savingProg startAnimation:nil];
    //[NSThread detachNewThreadSelector:@selector(saveFilesDir:) toTarget:self withObject:dirPath];
    //[self saveFilesDir:dirPath];
    
    if (!theSave) {
        theSave = [[tFileSave alloc] init];
        [theSave setProgressBar:savingProg];
        [theSave setTextField:savingText];
        [theSave setWindow:save];
        [theSave setSaveBeep:saveBeep];
        [theSave setStartButton:saveButton];
    }
    [theSave removeAllMovies];
    [theSave setSameDir:[saveInSourceFolder state]];
    if (![saveInSourceFolder state]) [theSave setDirPath:dirPath];
    else [theSave setDirPath:nil];
    for (i=0;i<n;i++) {
        if ([theSaveTable isRowSelected:i]) {
            MHMovie *aMovie = [currentModel movieForIndex:i];
            //NSLog(@"got movie: %d", [aMovie retainCount]);
            if ([customIcon state] && nil == [aMovie objectForKey:@"Cover Image"])
                [aMovie setObject:[iconText stringValue] forKey:@"Cover Image"];
            [aMovie setSize:[saveSize selectedRow]];
            //NSLog(@"adding to array: %d", [aMovie retainCount]);
            [theSave addMovie:aMovie];
        }
    }
    [MHMovie setLanguages:[lang selectedLanguages]];
    [theSave saveFilesFlattening:[saveType selectedRow]];
}
/*
- (void)saveFilesDir:(NSString *)path
{
    //NSLog(@"tController saveFilesDir");
    int i, n = [theSaveTable numberOfRows];
    NSString *name, *filePath, *tempPath;
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    //filesToSave = [[NSMutableArray alloc] init];
    MHMovie *aMovie;
    BOOL toFlatten = ![saveType selectedRow];
    
    cancelled = NO;
    for (i=0;i<n;i++) {
        //if ([theSaveTable isRowSelected:i])
            //[filesToSave addObject:[mainModel movieForIndex:i]];
    }
    //n = [filesToSave count];
    [MHMovie setLanguages:[lang selectedLanguages]];
    for (i=0;i<n;i++) {
        //aMovie = [filesToSave objectAtIndex:i];
        name = [aMovie stringValue];
        //[savingText setStringValue:[NSString stringWithFormat:@"Saving:  %@",name]];
        [savingText performSelectorOnMainThread:@selector(setStringValue:) withObject:[NSString stringWithFormat:@"Saving:  %@",name] waitUntilDone:NO];
        //[[save contentView] setNeedsDisplay:YES];
        [[save contentView] performSelectorOnMainThread:@selector(setNeedsDisplayObject:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
        filePath = [aMovie objectForKey:@"File Name"];
        if (filePath == nil) filePath = name;
        if ([filePath hasPrefix:@"."])
            filePath = [NSString stringWithFormat:@" %@",filePath];
        tempPath = [MHUtil uniquePath:[[MHUtil supportDir] stringByAppendingPathComponent:filePath]];
        filePath = [MHUtil uniquePath:[path stringByAppendingPathComponent:filePath]];
        //[savingProg setDoubleValue:(double)i/(double)n];
        if ([customIcon state] && nil == [aMovie objectForKey:@"Custom Icon"])
            [aMovie setObject:[iconText stringValue] forKey:@"Custom Icon"];
        [aMovie setSize:[saveSize selectedRow]];
        if (toFlatten) {
            [aMovie saveToPath:tempPath flatten:NO];
            //NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"qtFlatten" ofType:nil];
            //saving = [NSTask launchedTaskWithLaunchPath:resourcePath arguments:[NSArray arrayWithObjects:tempPath, filePath, nil]];
            //[saving waitUntilExit];
            [[NSFileManager defaultManager] removeFileAtPath:tempPath handler:nil];
        } else
            [aMovie saveToPath:filePath flatten:toFlatten];
        if (cancelled) break;
    }
    //[savingProg stopAnimation:nil];
    [savingProg performSelectorOnMainThread:@selector(stopAnimation:) withObject:nil waitUntilDone:NO];
    //[savingText setStringValue:@""];
    [savingText performSelectorOnMainThread:@selector(setStringValue:) withObject:@"" waitUntilDone:NO];
    //[save orderOut:nil];
    [save performSelectorOnMainThread:@selector(orderOut:) withObject:nil waitUntilDone:NO];
    
    if ([saveBeep state])
        [[NSSound soundNamed:@"Glass.aiff"] play];
    //[filesToSave release];
    [pool release];
}
/ *
- (void)flattenOneMovie:(NSNotification *)aNotification
{
    if ([filesToSave count]) {
        MHMovie *aMovie = [filesToSave objectAtIndex:0];
        NSString *name = [aMovie stringValue];
        [savingText performSelectorOnMainThread:@selector(setStringValue:) withObject:[NSString stringWithFormat:@"Saving:  %@",name] waitUntilDone:NO];
        [[save contentView] performSelectorOnMainThread:@selector(setNeedsDisplayObject:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
        NSString *filePath = [aMovie objectForKey:@"File Name"];
        if (!filePath) filePath = name;
        if ([filePath hasPrefix:@"."])
            filePath = [NSString stringWithFormat:@" %@", filePath];
        NSString *tempPath = [MHUtil uniquePath:[[MHUtil supportDir] stringByAppendingPathComponent:filePath]];
        filePath = [MHUtil uniquePath:[dirPath stringByAppendingPathComponent:filePath]];
        if ([customIcon state] && ![aMovie objectForKey:@"Custom Icon"])
            [aMovie setObject:[iconText stringValue] forKey:@"Custom Icon"];
        [aMovie setSize:[saveSize selectedRow]];
        [aMovie saveToPath:tempPath flatten:NO];
        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"qtFlatten" ofType:nil];
        saving = [[[NSTask alloc] init] autorelease];
        [saving setLaunchPath:resourcePath];
        [saving setArguments:[NSArray arrayWithObjects:tempPath, filePath, nil]];
        //saving = [NSTask launchedTaskWithLaunchPath:resourcePath arguments:[NSArray arrayWithObjects:tempPath, filePath, nil]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(flattenOneMovie:) name:NSTaskDidTerminateNotification object:saving];
        [saving launch];
        [filesToSave removeObjectAtIndex:0];
    }
}
/ *
- (void) saveWait:(NSDictionary *)aDict
{
    if ([saving isRunning]) return;
    [[NSFileManager defaultManager] removeFileAtPath:[aDict objectForKey:@"tempPath"] handler:nil];
    
    //[savingProg stopAnimation:nil];
    [savingProg performSelectorOnMainThread:@selector(stopAnimation:) withObject:nil waitUntilDone:NO];
    //[savingText setStringValue:@""];
    [savingText performSelectorOnMainThread:@selector(setStringValue:) withObject:@"" waitUntilDone:NO];
    //[save orderOut:nil];
    [save performSelectorOnMainThread:@selector(orderOut:) withObject:nil waitUntilDone:NO];
}
*/
/*
- (IBAction)saveEdit:(id)sender
{
    if (![currentModel editInfo:[editBox string]]) NSBeep();
    [theTable reloadData];
}
*/
- (IBAction)browseSaveDir:(id)sender
{
    NSOpenPanel *theOpenPanel = [NSOpenPanel openPanel];
    int result;
    NSString *theSelection;
    
    [theOpenPanel setCanChooseFiles:NO];
    [theOpenPanel setCanChooseDirectories:YES];
    [theOpenPanel setResolvesAliases:YES];
    [theOpenPanel setAllowsMultipleSelection:NO];
    result = [theOpenPanel runModalForDirectory:nil file:nil types:nil];
    if (result == NSOKButton) {
        theSelection = [[theOpenPanel filenames] objectAtIndex:0];
        [saveDirPath setStringValue:theSelection];
        [[NSUserDefaults standardUserDefaults] setObject:theSelection forKey:@"saveDir"];
    }
}

- (IBAction)saveAsText:(id)sender
{
    NSSavePanel *sp = [NSSavePanel savePanel];
    int runResult, i, j, n, m;
    //NSString *inputString = [theTextView string];
    NSMutableString *outputString = [[NSMutableString alloc] init];
    NSArray *theColumns = [theTable tableColumns];
    NSString *tableCell;
    
    runResult = [sp runModalForDirectory:nil file:[NSString stringWithFormat:@"%@.tab", mainModel]];

    if (runResult == NSOKButton) {
        n = [mainModel numberOfRowsInTableView:theTable];
        m = [theColumns count];
        
        for (j=0; j<m; j++) {
            tableCell = [[[theColumns objectAtIndex:j] headerCell] stringValue];
            if (tableCell == nil || ![tableCell isKindOfClass:[NSString class]]) tableCell = @"";
            [outputString appendString:tableCell];
            [outputString appendString:@"\t"];
        }
        [outputString appendString:@"\n\n"];
        
        for (i=0; i<n; i++) {
            for (j=0; j<m; j++) {
                tableCell = [mainModel tableView:theTable objectValueForTableColumn:[theColumns objectAtIndex:j] row:i];
                tableCell = [tableCell description];
                if (!tableCell || ![tableCell isKindOfClass:[NSString class]]) tableCell = @"";
                [outputString appendString:tableCell];
                [outputString appendString:@"\t"];
            }
            [outputString appendString:@"\n"];
        }
        if (![outputString writeToFile:[sp filename] atomically:YES])
            NSBeep();
    }
}

- (NSDictionary *)parseTabDoc:(NSString *)path
{
    NSMutableDictionary *oneMovie, *mainDict = [[NSMutableDictionary alloc] init];
    NSMutableArray *newMovies = [[NSMutableArray alloc] init];
    [mainDict setObject:@"Playlist" forKey:@"name"];
    [mainDict setObject:newMovies forKey:@"movieData"];
    NSString *content = [NSString stringWithContentsOfFile:path];
    if (nil == content) return mainDict;
    int i, n;
    NSArray *rows = [content componentsSeparatedByString:@"\n"];
    NSArray *cols = [[rows objectAtIndex:0] componentsSeparatedByString:@"\t"];
    NSMutableArray *entries;
    n = [rows count];
    for (i=1;i<n;i++) {  // for each row
        entries = [NSMutableArray arrayWithArray:[[rows objectAtIndex:i] componentsSeparatedByString:@"\t"]];
        if (0 != [entries count]) {
            while ([entries count] < [cols count])
                [entries addObject:@""];
            while ([entries count] > [cols count])
                [entries removeLastObject];
            oneMovie = [NSMutableDictionary dictionaryWithObjects:entries forKeys:cols];
            [newMovies addObject:oneMovie];
        }
    }
    //[mainDict writeToFile:@"out.xml" atomically:NO];
    return mainDict;
}

- (IBAction)saveAsXML:(id)sender
{
    int index = [playlistTable selectedRow];
    if (-1 == index) return;
    NSDictionary *aDict = [(tPlaylist *)[thePlaylists objectAtIndex:index] defsEntry];
    
    NSSavePanel *sp = [NSSavePanel savePanel];
    
    int runResult = [sp runModalForDirectory:nil file:[NSString stringWithFormat:@"%@.xml", [aDict objectForKey:@"name"]]];

    if (runResult == NSOKButton) {
        [aDict writeToFile:[sp filename] atomically:YES];
    }
}

- (IBAction) search
{
    NSArray *searchResult;
    tPlaylist *newModel = [(tPlaylist *)[tPlaylist alloc] initWithController:self];
    NSString *searchString = [searchField2 stringValue];
    //BOOL searchPrev = [searchPrevious state];
    
    //[trueModel savePrefs];
    
    if ([searchString isEqualToString:@""]) {
        [self unSearch:nil];
        return;
    }
    
    [mainModel retain];
    searchResult = [mainModel search:searchString];
    [newModel addMovies:searchResult];
    [self setTableModel:newModel];
    
    [theTable reloadData];
    //[mainWindow setTitle:[NSString stringWithFormat:@"Search Results For: \"%@\"",searchString]];
    currentModel = newModel;
    [self updateTotals];
}

- (IBAction) unSearch:(id)sender
{
    currentModel = mainModel;
    [self setTableModel:mainModel];
    //[mainWindow setTitle:@"Editing Window"];
    [self updateTotals];
}

- (IBAction)summary:(id)sender
{
    int index = -1;
    index = [theTable selectedRow];
    //NSString *output = [currentModel summaryForIndex:index];
    //[summaryText setStringValue:output];
    [summaryTable setDataSource:currentMovie];
    [summaryTable setDelegate:currentMovie];
    [summaryTable reloadData];
    [self setMainTabViewName:@"Info"];
    //[summaryWindow setTitle:[currentMovie stringValue]];
    //[summaryWindow makeKeyAndOrderFront:nil];
}

- (void)setMainWindow:(NSWindow *)newWindow
{
    if (nil == newWindow || ![newWindow isKindOfClass:[NSWindow class]]) return;
    [mainWindow orderOut:nil];
    [newWindow setDelegate:self];
    [newWindow setToolbar:[mainWindow toolbar]];
    mainWindow = newWindow;
    [self toolbarWillAddItem:nil];
}

- (NSWindow *)mainWindow
{   return mainWindow;      }

- (void)setModel:(tPlaylist *)model
{   mainModel = currentModel = model;       }

- (tPlaylist *)getModel
{   return currentModel;    }

- (tPlaylist *)getTrueModel
{   return mainModel;       }

- (id)getChapters
{   return theChapters;     }

- (tPlayback *)getPlayer
{    return player;     }

- (NSTableView *)getTable
{   return theTable;    }

- (NSComboBox *)getAddColumnBox
{   return addComboBox;     }

- (NSImageView *)getArtworkView
{   return artworkView;     }

- (IBAction)toggleArtworkView:(id)sender
{
    if (artworkView) {
        [artworkView removeFromSuperview];
        artworkView = nil;
    } else {
        artworkView = [[NSImageView alloc] init];
        [[playlistTable superview] addSubview:artworkView positioned:NSWindowBelow relativeTo:playlistTable];
        [artworkView setFrameSize:NSMakeSize(100,100)];
        [artworkView setNeedsDisplay:YES];
    }
}

- (int)getSaveType
{   return [saveType selectedRow];  }

- (NSTextField *)getInfoText
{   return infoText;    }

- (NSTextField *)getSummaryText
{   return nil;         }

- (NSColor *)getHighlightColor
{   return [highlightColor color];  }

- (IBAction)showInFinder:(id)sender
{
    MHMovie *aMovie = nil;
    aMovie = [currentModel movieForIndex:[theTable selectedRow]];
    if (nil == aMovie) return;
    NSString *fullPath = nil;
    fullPath = [aMovie objectForKey:@"File Path"];
    if (nil == fullPath) return;
    [[NSWorkspace sharedWorkspace] selectFile:fullPath inFileViewerRootedAtPath:@""];
}
/*
- (NSTextView *)getEditBox
{   return tableEditTextView;     }

- (NSTextField *)getEditPaneText
{   return editPaneText;    }
*/
- (int)getPathLevels
{   return [pathLevels intValue];   }

- (IBAction)toggleIconDrawer:(id)sender
{
    if (![viewWindow isKeyWindow])
        [viewWindow makeKeyAndOrderFront:nil];
    [iconDrawer toggle:nil];
    NSString *value = [[currentModel movieForIndex:[theTable selectedRow]] objectForKey:@"Cover Image"];
    if (nil == value) {
        [iconCheckbox setState:NO];
        [iconSelect setEnabled:NO];
        return;
    }
    [iconCheckbox setState:YES];
    [iconSelect setEnabled:YES];
    if ([value hasPrefix:@"icns:"])
        [iconSelect selectItemAtIndex:1];
    else if ([value hasPrefix:@"icon:"])
        [iconSelect selectItemAtIndex:2];
    else if ([value hasPrefix:@"http"])
        [iconSelect selectItemAtIndex:3];
    else
        [iconSelect selectItemAtIndex:0];
    [iconIndText setStringValue:value];
}

- (NSString *)iconPath
{   return [iconText stringValue];      }

- (IBAction)setIconFile:(id)sender
{
    if (![customIcon state]) {
        [iconText setStringValue:@""];
        return;
    }
    NSArray *theSelection = [MHUtil showOpenPanel];
    if ([theSelection count] == 0) return;
    [iconText setStringValue:[[theSelection objectAtIndex:0] path]];
}

- (IBAction)iconViewCheckbox:(id)sender
{
    [iconSelect setEnabled:[iconCheckbox state]];
    if (![iconCheckbox state]) {
        [[currentModel movieForIndex:[theTable selectedRow]] setObject:@"" forKey:@"Cover Image"];
        [iconIndText setStringValue:@""];
    }
}

- (IBAction)setIndIcon:(id)sender
{
    int which = [iconSelect indexOfSelectedItem];
    NSString *path = @"";
    NSArray *theSelection;
    long samples;
    switch (which) {
        case 2: //file's icon
            path = @"icon:";
        case 1: //icns file's contents
            if (which == 1)
                path = @"icns:";
        case 0: //file's contents
            theSelection = [MHUtil showOpenPanel];
            if ([theSelection count] == 0) return;
            path = [path stringByAppendingString:[[theSelection objectAtIndex:0] path]];
            break;
        case 3: //IMDB
            //[webWindow makeKeyAndOrderFront:nil];
            //[webTab selectTabViewItemAtIndex:0];
            //[optIcon setState:YES];
            return;
        case 4: //frame
            samples = [player getSampleTimeValue];
            path = [NSString stringWithFormat:@"frame:%d", samples];
            break;
        default:
            break;
    }
    [[currentModel movieForIndex:[theTable selectedRow]] setObject:path forKey:@"Cover Image"];
    [iconIndText setStringValue:path];
}

- (IBAction)setPicViewPic:(NSImage *)image
{
    [picView setImage:image];
}

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
    NSPasteboard *pboard = [sender draggingPasteboard];
    NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] || [[pboard types] containsObject:NSStringPboardType]) {
        if (sourceDragMask & NSDragOperationCopy) {
            return NSDragOperationCopy;
        } else if (sourceDragMask & NSDragOperationLink) {
            return NSDragOperationLink;
        }
    }
    return NSDragOperationNone;
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
    NSPasteboard *pboard = [sender draggingPasteboard];
    //NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
        //n = [files count];
        //for (i=0; i<n; i++) {
            //[self openMpegsFromArray:files];
            makeDupes = YES;
            //[self openFilesFromArray:files];
            //[NSThread detachNewThreadSelector:@selector(openFilesFromArray:) toTarget:self withObject:files];
			[self openFilesFromArray:files];
        //}
    } else if ([[pboard types] containsObject:NSStringPboardType]) {
		NSString *s = [pboard stringForType:NSStringPboardType];
		if ([s hasPrefix:@"http"]) {
			return [[MHWebInput myself] parse:s];
		} else if ([[[mainTabView selectedTabViewItem] identifier] isEqualToString:@"Chapters"]) {
			NSMovie *m = nil;
			if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"chapScale"] boolValue]) m = currentMovie;
			[[currentMovie chapters] parseText:s scaleToMovie:m];
		} else {
			return NO;
		}
	}
    return YES;
}
/*
- (void) openFileAtPath:(NSString *)path
{
    
}
*/

//we will get an array of NSURLs and return an array of NSStrings
- (NSArray *)expandURLFolders:(NSArray *)theArray
{
    NSMutableArray *theNewArray = [[NSMutableArray alloc] init];
    int i, n = [theArray count];
    NSString *pathString;
    
    for (i=0;i<n;i++) {
        pathString = [[theArray objectAtIndex:i] path];
        [theNewArray addObjectsFromArray:[self expandStringFolder:pathString]];
    }
    return theNewArray;
}

- (NSArray *)expandStringFolder:(NSString *)theStringPath
{
    //NSLog(@"tController expandStringFolder");
    int i, n;
    BOOL isDir = NO;
    BOOL isNew = YES;
    NSString *aFile, *aPath;
    NSMutableArray *theNewArray = [[NSMutableArray alloc] init];
    NSArray *theSubPaths;
    
    if (theStringPath == nil || ![theStringPath isKindOfClass:[NSString class]])
        return theNewArray;
    
        if ([[NSFileManager defaultManager] fileExistsAtPath:theStringPath isDirectory:&isDir] && isDir) {
            if (![theStringPath hasSuffix:@"/"])
                theStringPath = [theStringPath stringByAppendingString:@"/"];
            theSubPaths = [[NSFileManager defaultManager] subpathsAtPath:theStringPath];
            for (i=0; i<[theSubPaths count]; i++) {
                aFile = [theSubPaths objectAtIndex:i];
                aPath = [theStringPath stringByAppendingString:aFile];
                aFile = [aPath stringByResolvingSymlinksInPath];
                if ([aPath hasSuffix:@"/"])
                    aPath = [aPath substringToIndex:[aPath length]-1];
                if ([aFile hasSuffix:@"/"])
                    aFile = [aFile substringToIndex:[aFile length]-1];
                if (![aPath isEqualToString:aFile]) {
                    n = [symlinksTraversed count];
                    isNew = YES;
                    for (i=0;i<n;i++) {
                        if ([aFile isEqualToString:[symlinksTraversed objectAtIndex:i]]) {
                            isNew = NO;
                            break;
                        }
                    }
                    if (isNew) {
                        [symlinksTraversed addObject:[aFile copy]];
                        [theNewArray addObjectsFromArray:[self expandStringFolder:aFile]];
                    }
                }
                [theNewArray addObject:aPath];
            }
        } else {
            [theNewArray addObject:theStringPath];
        }
    
    return theNewArray;
}

- (BOOL)isMPEG:(NSString *)path
{
    NSArray *exts = [NSArray arrayWithObjects:@".mpg", @".mpeg", @".MPG", @".MPEG", @".Mpg", @".Mpeg", nil];
    int i, n;
    n = [exts count];
    for (i=0;i<n;i++) {
        if ([path hasSuffix:[exts objectAtIndex:i]]) return YES;
    }
    return NO;
}

- (double)stringToNSeconds: (NSString *)input
{
    //NSLog(@"tController stringToNSeconds");
	char c, cleanedInput[20];
	const char *dirtyInput = [input cString];
	int n = strlen(dirtyInput);
	int  i, m, cleanCounter, mins, hours;
	int secs;
	double seconds, frames;
	seconds = secs = frames = i = m = cleanCounter = mins = hours = 0;
	//NSLog(@"      input: %@", input);
	if ( n >= 20 ) NSBeep();
	else { // input cleaner
            for( i = 0 ; i < n ; i++ ) {
		c = dirtyInput[i];
                if ( c == ':' || c == '.' || (c >= '0' && c <= '9')) {
                    cleanedInput[cleanCounter] = c;
                    cleanCounter++;
                }
            }
            cleanedInput[cleanCounter] = 0;
		// pre-process
		// n = number of :
		// m = number of .
            n = 0;
            for( i = 0 ; i < cleanCounter ; i ++ ) {
                c = cleanedInput[i];
                if ( c == ':' ) {
                    if ( n == 3 ) {
			cleanedInput[i] = '.';
			m++;
                    }
                    n++;
                } else if ( c == '.' ) m++;
            }
            if ( n > 2 || m > 1 ) NSBeep();
            else {
		if ( m == 1 ) {
                    if ( cleanedInput[0] == '.' ) {
			sscanf(cleanedInput , ".%lf" , &frames);
                    } else {
                        switch ( n ) {
                            case 0:
				sscanf(cleanedInput , "%d.%lf" , &secs, &frames);
				break;
                            case 1:
				sscanf(cleanedInput , "%d:%d.%lf" , &mins , &secs, &frames); break;
                            case 2:
				sscanf(cleanedInput , "%d:%d:%d.%lf" , &hours , &mins , &secs, &frames); break;
                            default: break;
                        }
                    }
                } else {
                    switch ( n ) {
                        case 0:
                            sscanf(cleanedInput , "%d" , &secs); break;
                        case 1:
                            sscanf(cleanedInput , "%d:%d" , &mins , &secs); break;
                        case 2:
                            sscanf(cleanedInput , "%d:%d:%d" , &hours , &mins , &secs); break;
                        default: break;
                    }
                }
                seconds = (frames / 30) + secs + (60 * mins) + (3600 * hours);
            }
	}
/*
	NSLog(@"      hours: %d", hours);
	NSLog(@"    minutes: %d", mins);
	NSLog(@"    seconds: %d", secs);
	NSLog(@"     frames: %lf", frames);
	NSLog(@"accumulated: %lf", seconds);
*/	
	return seconds;
}

@end
