/****************************************************************************
 *   Copyright (C) 2004 by Arboretum Systems, Inc.                          *
 *   Technical administrator: Alain Mazy, hav@mazy.be                       *
 *   Lead program designer: Georges Jaroslaw, gjaro@arboretum.com           *
 *                                                                          *
 *   HyperEngine-AV is a video, audio and text editor that can be used to   *
 *   record, import, edit, process and arrange together video, sound and    *
 *   text. These are all achieved in the program's free-form document       *
 *   window, with no limitations to the number of tracks.                   *
 *   The purpose of this program is to provide to users at all levels of    *
 *   expertise a readily accessible tool enabling them to create movies,    *
 *   slide shows or presentations.                                          *
 *                                                                          *
 *   HyperEngine-AV itself is free software. However, plug-ins that can be  *
 *   used as add-ons to HyperEngine-AV may or may not be free software, at  *
 *   the discretion of each plug-in developer and as specified by these     *
 *   plug-ins' respective licenses.                                         *
 *   You can redistribute HyperEngine-AV itself and/or modify it under the  *
 *   terms of the GNU General Public License as published by the Free       *
 *   Software Foundation; either version 2 of the License, or (at your      *
 *   option) any later version.                                             *
 *                                                                          *
 *   HyperEngine-AV is distributed in the hope that it will be useful, but  *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of             *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *   GNU General Public License for all applicable details.                 *
 *                                                                          *
 *   You should have received a copy of the GNU General Public License      *
 *   along with this program; if not, write to:                             *
 *   Free Software Foundation, Inc.,                                        *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.              *
 ****************************************************************************/
#import "MIOverviewController.h"
#import "MIApplicationController.h"
#import "MIMainViewController.h"
#import "MITopLevelContainerRep.h"
#import "MIMainViewController.h"
#import "MIPaletteController.h"
#import "MIMontageDocument.h"
#import "MIDocumentController.h"
#import "MenuTags.h"
#import "MIOverview.h"

@implementation MIOverviewSavedView

- (id)copyWithZone:(NSZone *)zone
{
    MIOverviewSavedView* obj = [[MIOverviewSavedView alloc] init];
    [obj setName:[[[self name]copy] autorelease]];
    [obj setVZoomLevel:[self vZoomLevel]];
    [obj setHZoomLevel:[self hZoomLevel]];
    [obj setHOrigin:[self hOrigin]];
    [obj setVOrigin:[self vOrigin]];
    return obj;
}

- (void)dealloc
{
    [fName release];
    [super dealloc];
}

- (NSString*)name
{
    return fName ;
}

- (void)setName:(NSString*)name
{
    [name retain];
    [fName release];
    fName = name ;
}

- (unsigned int)vZoomLevel
{
    return fVZoomLevel;
}

- (void)setVZoomLevel:(unsigned int)zoom {
    fVZoomLevel = zoom ;
}

- (unsigned int)hZoomLevel
{
    return fHZoomLevel;
}

- (void)setHZoomLevel:(unsigned int)zoom
{
    fHZoomLevel = zoom ;
}


- (ArmeTime)hOrigin
{
    return fHOrigin ;
}

- (void)setHOrigin:(ArmeTime)time
{
    fHOrigin = time ;
}

- (MIVPos)vOrigin
{
    return fVOrigin ;
}

- (void)setVOrigin:(MIVPos)position
{
    fVOrigin = position ;
}

- (BOOL)writeToArchive:(ArmeArchiveHandler*)archiver {
    [super writeToArchive:archiver];
    archiver->WriteObjCObject(fName);
    archiver->WriteUInt32(fVZoomLevel);
    archiver->WriteUInt32(fHZoomLevel);
    archiver->WriteArmeTime(fHOrigin);
    archiver->WriteSInt32(fVOrigin.data);
    return YES;
}

- (id)initFromArchive:(ArmeArchiveHandler*)unarchiver {
    if (( self = [super initFromArchive:unarchiver] ))
    {
        fName = unarchiver->ReadObjCObject();
        [fName retain];
        fVZoomLevel = unarchiver->ReadUInt32();
        fHZoomLevel = unarchiver->ReadUInt32();
        fHOrigin = unarchiver->ReadArmeTime();
        fVOrigin.data = unarchiver->ReadSInt32();
    }
    return self;
}

@end



@implementation MIOverviewController

+ (id)sharedOverviewController
{
    static id sharedOverviewController;
    if ( sharedOverviewController == nil )
    {
        sharedOverviewController = [[self alloc] init]; 
    }
    return sharedOverviewController;
}

+ (NSString*)visibleDefaultName {
    return @"OverviewVisible";
}

- (NSString*)nibName {
    return @"MIOverview";
}

- (int)menuTag {
	return MTGOverviewMenuTag;
}

- (NSString*)menuName {
	return @"Overview";
}

+ (BOOL)factoryVisibleDefault {
    return YES;
}


- (id)init
{
    if (( self = [super init] ))
    {
        fEditedRow = -1;
		fFutureVZoomIndex = -1;
		fFutureHZoomIndex = -1;
        [self refreshCachedImage];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSViewFrameDidChangeNotification object:fView];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MTGCurrentDocumentChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MTGSelectionChangedNotification object:nil];
    [fEditedCbbDataSource release];
    [super dealloc];
}

- (void)awakeFromNib
{
//	NSImage		*image;
//	id 			old;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myBoundsChanged:) name:NSViewFrameDidChangeNotification object:fView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(currentDocumentChanged:) name:MTGCurrentDocumentChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectionChanged:) name:MTGSelectionChangedNotification object:nil];


	[fHZoomButton removeAllItems];
	[fVZoomButton removeAllItems];
	
	double value;
	double defaultVValue = [MIMainViewController getVZoomPNValueFromIndex:[MIMainViewController getDefaultVZoomIndex]];
	double defaultHValue = [MIMainViewController getHZoomPNValueFromIndex:[MIMainViewController getDefaultHZoomIndex]];
	SInt32					nbHZoomIndices = [MIMainViewController getNbHZoomIndices];
	SInt32					nbVZoomIndices = [MIMainViewController getNbVZoomIndices];
	SInt32					convertFactor;
	
	for ( int i =  max(nbHZoomIndices, nbVZoomIndices)-1; i >= 0; i-- )
	{
		if ( i < nbVZoomIndices )
		{
			convertFactor = [MIMainViewController getVZoomPNValueFromIndex:i];
			// convert the horiontal visbible size of the TLC (in pixels) in ArmeTime and compare that to the best delta stored
			if ( convertFactor > 0 )
				value = (double)defaultVValue/convertFactor;
			else
				value = (double)(-convertFactor)/defaultVValue;
			
			[fVZoomButton addItemWithTitle:[NSString stringWithFormat:@"%d%%", (int)(100*value)]];
			[[fVZoomButton lastItem] setTag:i];
			
		}
		if ( i < nbHZoomIndices )
		{
			convertFactor = [MIMainViewController getHZoomPNValueFromIndex:i];
			// convert the horiontal visbible size of the TLC (in pixels) in ArmeTime and compare that to the best delta stored
			if ( convertFactor > 0 )
				value = (double)defaultHValue/convertFactor;
			else
				value = (double)(-convertFactor)/defaultHValue;

			BOOL bPassed = NO;
			for ( int j = -6; j < 8; j++ )
			{
				if ( value == pow(2, j) )
				{
					bPassed = YES;
				}
			}
			
			if ( !bPassed )
				continue;
			
			[fHZoomButton addItemWithTitle:[NSString stringWithFormat:@"%d%%", (int)(100*value)]];
			[[fHZoomButton lastItem] setTag:i];
		}
	}
 
/*
	old = fHZoomButton;
	fHZoomButton = [[NSButton allocWithZone:[self zone]] initWithFrame:[old frame]];
	[fHZoomButton setButtonType:NSMomentaryChangeButton];
	[fHZoomButton setImagePosition:NSImageOnly];
	[fHZoomButton setBordered:NO];
	image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"hZoomButton.png"]];
	[fHZoomButton setImage:image];
	[image release];

	image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"bt+_vert_bleu.png"]];
	[fHZoomButton setAlternateImage:image];
	[image release];
	[fHZoomButton setTarget:self];
	[fHZoomButton setAction:@selector(hZoomButtonPressed:)];
	[[old superview] addSubview:fHZoomButton];
	[old removeFromSuperview];

	old = fVZoomButton;
	fVZoomButton = [[NSButton allocWithZone:[self zone]] initWithFrame:[old frame]];
	[fVZoomButton setButtonType:NSMomentaryChangeButton];
	[fVZoomButton setImagePosition:NSImageOnly];
	[fVZoomButton setBordered:NO];

	image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"vZoomButton.png"]];
	[fVZoomButton setImage:image];
	[image release];
	image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"bt+_vert_bleu.png"]];
	[fVZoomButton setAlternateImage:image];
	[image release];
	[fVZoomButton setTarget:self];
	[fVZoomButton setAction:@selector(vZoomButtonPressed:)];
	[[old superview] addSubview:fVZoomButton];
	[old removeFromSuperview];
*/
	fVZoomSliderView = nil;
	fHZoomSliderView = nil;

	fFutureVZoomIndex = -1;
	fFutureHZoomIndex = -1;
}

extern bool gLazyOverviewUpdateOnSelChanged;

- (void)selectionChanged:(NSNotification*)notification
{
	if(!gLazyOverviewUpdateOnSelChanged)
		[self refreshCachedImage];
}

- (BOOL)canBecomeKeyWindow
{
    return NO;
}

- (BOOL)canBecomeMainWindow
{
    return NO;
}

- (void)myBoundsChanged:(NSNotification*)theNotification
{
    [self refreshCachedImage];
}

- (void)currentDocumentChanged:(NSNotification*)theNotification
{
    [self buildPopupButton];
    [self refreshCachedImage];
}

- (void)updateZoomTexts
{
    UInt32 hZoom = [[NSApp mainViewController] hZoomIndex];
    UInt32 vZoom = [[NSApp mainViewController] vZoomIndex];
    
	[fHZoomButton selectItemAtIndex:[fHZoomButton indexOfItemWithTag:hZoom]];
	[fVZoomButton selectItemAtIndex:[fVZoomButton indexOfItemWithTag:vZoom]];

	return;
	
	
	
	if ( fFutureVZoomIndex == -1 )
		[fVZoomText setStringValue:[NSString stringWithFormat:@"x %d", [[NSApp mainViewController] vZoomIndex] - [MIMainViewController getDefaultVZoomIndex]]];
	else
		[fVZoomText setStringValue:[NSString stringWithFormat:@"x %d", fFutureVZoomIndex - [MIMainViewController getDefaultVZoomIndex]]];

	if ( fFutureHZoomIndex == -1 )
		[fHZoomText setStringValue:[NSString stringWithFormat:@"x %d", [MIMainViewController getDefaultHZoomIndex] - [[NSApp mainViewController] hZoomIndex]]];
	else
		[fHZoomText setStringValue:[NSString stringWithFormat:@"x %d", [MIMainViewController getDefaultHZoomIndex] - fFutureHZoomIndex]];
}

- (void)refreshCachedImage
{
//	NSLog(@"Refreshing CachedImage");

    [self updatePopupButton];
    [fView setCachedImageNeedsRefreshing];
    [fView setNeedsDisplay:YES];
	[self updateZoomTexts];
	
//	NSLog(@"Finished refreshing CachedImage");
}

- (void)setViewNeedsDisplay
{
	[fView setNeedsDisplay:YES];
	[self updateZoomTexts];
}

- (void)setFutureHZoomIndex:(int)newValue
{
	fFutureHZoomIndex = newValue;
	[fView setNeedsDisplay:YES];
	[self updateZoomTexts];
}
- (void)setFutureVZoomIndex:(int)newValue
{
	fFutureVZoomIndex = newValue;
	[fView setNeedsDisplay:YES];
	[self updateZoomTexts];
}
- (int)futureHZoomIndex
{
	return fFutureHZoomIndex;
}

- (int)futureVZoomIndex
{
	return fFutureVZoomIndex;
}



- (void)reflectScrolling:(MITopLevelContainerView*)theView
{
    [self updatePopupButton];
    [fView setNeedsDisplay:YES];
}

// management of the Popup Button
- (void)updatePopupButton
{
    MITopLevelContainerRep	*tlc;
    MIOverviewSavedView		*selItem;
    MIMainViewController	*currentMainViewController;
    int 			index;
    MIMontageDocument		*document;

    currentMainViewController = [NSApp mainViewController] ;
    tlc = [currentMainViewController topLevelContainerView];
    document = [currentMainViewController document];
    index = [fPopupButton indexOfSelectedItem];
    if ( index > 0 )
    {
        selItem = [[document savedViews] objectAtIndex:index -1];
        if ( ( [currentMainViewController vZoomIndex] != [selItem vZoomLevel] ) ||
             ( [currentMainViewController hZoomIndex] != [selItem hZoomLevel] ) ||
             ( [tlc pixelToArmeTime:NSMinX([tlc visibleRect])] != [selItem hOrigin] ) ||
             ( NSMinY([tlc visibleRect]) != [tlc MIVPosToPixel:[selItem vOrigin]] ) )
        {
            [fPopupButton selectItemAtIndex:0];
        }
    }
}

- (void)buildPopupButton
{
    MIMontageDocument *document = (MIMontageDocument*)[[NSDocumentController sharedDocumentController] currentDocument];
    NSArray* savedViews = [document savedViews];
    MIOverviewSavedView *item;

    while ( [fPopupButton numberOfItems] > 4 ) [fPopupButton removeItemAtIndex:1];

    for ( int x = [savedViews count] ; x > 0 ; x-- )
    {
        item = (MIOverviewSavedView*)[savedViews objectAtIndex:x - 1];
        [fPopupButton insertItemWithTitle:[item name] atIndex:1];
        [[fPopupButton itemAtIndex:1] setAction:@selector(savedViewSelected:)];
        [[fPopupButton itemAtIndex:1] setTarget:self];
    }
}

- (IBAction)savedViewSelected:(id)sender
{
    // the user selected another item
    MITopLevelContainerRep	*tlc;
    MIOverviewSavedView *selItem;
    MIMainViewController* currentMainViewController = [NSApp mainViewController] ;
    MIMontageDocument *document = [currentMainViewController document];
    
    tlc = [currentMainViewController topLevelContainerView];

    selItem = [[document savedViews] objectAtIndex:[fPopupButton indexOfItem:sender] -1];

    if ( [currentMainViewController vZoomIndex] != [selItem vZoomLevel] )
    {
        [currentMainViewController setVZoom:[selItem vZoomLevel]];
    }

    if ( [currentMainViewController hZoomIndex] != [selItem hZoomLevel] )
    {
        [currentMainViewController setHZoom:[selItem hZoomLevel]];
    }
    [tlc scrollPoint:NSMakePoint([tlc armeTimeToPixel:[selItem hOrigin]],[tlc MIVPosToPixel:[selItem vOrigin]])];
    [fPopupButton selectItem:sender];
}

// Gestion du panel pour saisir le nom de la vue
- (IBAction)saveView:(id)sender
{
    [fNameField setStringValue:[NSString stringWithFormat:@"New Position %d", [[[[NSDocumentController sharedDocumentController] currentDocument] savedViews] count]+1]];
    [NSApp beginSheet:fNamePanel
       modalForWindow:[self window]
        modalDelegate:self
       didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
          contextInfo:nil];
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    [fNamePanel orderOut:nil];
    if ( returnCode == NSOKButton )
    {
        MIOverviewSavedView *newItem;
        MITopLevelContainerRep	*tlc;
        MIMainViewController* currentMainViewController = [NSApp mainViewController] ;
        MIMontageDocument *document = [currentMainViewController document];
        newItem = [[MIOverviewSavedView alloc] init];

        tlc = [currentMainViewController topLevelContainerView];
        [newItem setName:[fNameField stringValue]];

        [newItem setVZoomLevel:[currentMainViewController vZoomIndex]];
        [newItem setHZoomLevel:[currentMainViewController hZoomIndex]];
        [newItem setHOrigin:[tlc pixelToArmeTime:NSMinX([tlc visibleRect])]];
        [newItem setVOrigin:[tlc pixelToMIVPos:NSMinY([tlc visibleRect])]];

		NSEnumerator *enumerator = [[document savedViews] objectEnumerator];
		MIOverviewSavedView *item;

		while (( item = [enumerator nextObject] )) {
			if ( [[item name] isEqualToString:[newItem name]] ) {
				if ( NSRunAlertPanel(@"Confirmation", @"A saved view \"%@\" already exists. Do you want to replace it ?", @"Replace", @"Cancel", nil, [item name] ) == NSAlertDefaultReturn ) {
					[fPopupButton removeItemWithTitle:[item name]];
					[[document savedViews] removeObject:item];
					break;
				} else return ;
			}
		}
		
        [[document savedViews] insertObject:newItem atIndex:0];
        [fPopupButton insertItemWithTitle:[fNameField stringValue] atIndex:1];
        [[fPopupButton itemAtIndex:1] setAction:@selector(savedViewSelected:)];
        [[fPopupButton itemAtIndex:1] setTarget:self];
        [fPopupButton selectItemAtIndex:1];
        [newItem release];
		[document updateDocumentChangeCount:MIChangeDone];
    }
}

- (IBAction)saveViewName:(id)sender
{
    [NSApp endSheet:fNamePanel returnCode:NSOKButton];
}

- (IBAction)cancelViewName:(id)sender
{
    [NSApp endSheet:fNamePanel returnCode:NSCancelButton];
}

// management of the edit panel
- (IBAction)editView:(id)sender
{
    MIMontageDocument *document = (MIMontageDocument*)[[NSDocumentController sharedDocumentController] currentDocument];
    fEditedCbbDataSource = [[NSMutableArray alloc] initWithCapacity:10];
    unsigned int x ;

    for( x = 0 ; x < [[document savedViews] count] ; x++ )
    {
        [fEditedCbbDataSource addObject:[[[[document savedViews] objectAtIndex:x] copy] autorelease]];
    }

    [fTableView reloadData];
    [fTableView selectRow:0 byExtendingSelection:NO];
    [fTableView setDoubleAction:@selector(renameSelection:)];
    [fTableView setTarget:self];
    [NSApp beginSheet:fEditPanel
       modalForWindow:[self window]
        modalDelegate:self
       didEndSelector:@selector(editSheetDidEnd:returnCode:contextInfo:)
          contextInfo:[document savedViews]];
}

- (void)editSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    NSMutableArray* savedViews = (NSMutableArray*)contextInfo;
    [fEditPanel orderOut:nil];

    if ( returnCode == NSOKButton )
    {
        signed int x;

        [savedViews removeAllObjects];
        [savedViews addObjectsFromArray:fEditedCbbDataSource];
        [fEditedCbbDataSource release];

        while( [fPopupButton numberOfItems] > 4 )
        {
            [fPopupButton removeItemAtIndex:1];
        }

        for ( x = [savedViews count] - 1 ; x >= 0  ; x-- )
        {
            [fPopupButton insertItemWithTitle:[[savedViews objectAtIndex:x] name] atIndex:1];
            [[fPopupButton itemAtIndex:1] setAction:@selector(savedViewSelected:)];
            [[fPopupButton itemAtIndex:1] setTarget:self];
        }
        [fPopupButton selectItemAtIndex:0];
    }
    else
    {
        [fEditedCbbDataSource release];
        fEditedCbbDataSource = nil;
        [fPopupButton selectItemAtIndex:0];
    }
}

- (IBAction)renameSelection:(id)sender
{
    fEditedRow = [fTableView selectedRow];
    [fTableView editColumn:0 row:fEditedRow withEvent:nil select:YES];
}

- (IBAction)deleteSelection:(id)sender
{
    if ( NSRunAlertPanel(@"Confirmation", @"Delete saved view \"%@\" ?", @"Delete", @"Cancel", nil, [[fEditedCbbDataSource objectAtIndex:[fTableView selectedRow]] name] ) == NSAlertDefaultReturn )
    {
        [fEditedCbbDataSource removeObjectAtIndex:[fTableView selectedRow]];
        [fTableView reloadData];
    }
}

- (IBAction)saveEdit:(id)sender
{
    [NSApp endSheet:fEditPanel returnCode:NSOKButton];
}

- (IBAction)cancelEdit:(id)sender
{
    [NSApp endSheet:fEditPanel returnCode:NSCancelButton];
}


// Management of the NSTableView
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [fEditedCbbDataSource count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    return [[fEditedCbbDataSource objectAtIndex:rowIndex] name];
}

- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if ( fEditedRow == rowIndex )
    {
        if ( [((NSString*)anObject) length] > 0 )
            [((MIOverviewSavedView*)[fEditedCbbDataSource objectAtIndex:rowIndex]) setName:anObject];
    }
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    fEditedRow = -1;
    if ( [fTableView selectedRow] == -1 )
    {
        [fRenameButton setEnabled:NO];
        [fDeleteButton setEnabled:NO];
    }
    else
    {
        [fRenameButton setEnabled:YES];
        [fDeleteButton setEnabled:YES];
    }
}

- (BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if ( rowIndex == fEditedRow ) return YES ;
    else return NO ;
}

- (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTableView
{
    return YES;
}

- (void)windowDidExpose:(NSNotification *)aNotification
{
	[self refreshCachedImage];
	[super windowDidExpose:aNotification];
}

- (BOOL)ignoreArrowKeys {
	return YES;
}

- (BOOL)ignoresUndoRedoActions {
	return YES;
}

- (IBAction)vZoomButtonPressed:(id)sender
{

	[[NSApp mainViewController] setVZoom:(UInt32)[[sender selectedItem] tag]];
	return;


	if ( fVZoomSliderView )
	{
		[[self window] removeChildWindow:fVZoomSliderView];
		[fVZoomSliderView close];
		fVZoomSliderView = nil;
		return;
	}
	
	NSRect wFrame;
	NSPoint p;
	
	wFrame = [fVZoomButton frame];
	p.x = NSMidX(wFrame)-9.5;
	p.y = NSMaxY(wFrame);
	
	wFrame.origin = [[self window] convertBaseToScreen:[[fVZoomButton superview] convertPoint:p toView:nil]];
	wFrame.size = NSMakeSize(17, 150);

	NSWindow *win = [[NSWindow alloc] initWithContentRect:wFrame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
	NSSlider *slider = [[MIVSlider allocWithZone:[self zone]] initWithFrame:NSMakeRect(1,1,15,148)];
	[slider setMinValue:0];
	[slider setMaxValue:[MIMainViewController getNbVZoomIndices]-1 ];
	[slider setIntValue:[[NSApp mainViewController] vZoomIndex]];

	[[slider cell] setControlSize:NSSmallControlSize];
	[slider setTarget:self];
	[slider setAction:@selector(vSliderMoved:)];
	[[win contentView] addSubview:slider];
	[slider release]; 
	[win setHasShadow:YES];
	[win setLevel:NSFloatingWindowLevel];
	[[self window] addChildWindow:win ordered:NSWindowAbove];
	[win setLevel:NSFloatingWindowLevel];
	[win makeKeyAndOrderFront:self];
	fVZoomSliderView = win;
}

- (IBAction)hZoomButtonPressed:(id)sender
{
	[[NSApp mainViewController] setHZoom:(UInt32)[[sender selectedItem] tag]];
	return;

	if ( fHZoomSliderView )
	{
		[[self window] removeChildWindow:fHZoomSliderView];
		[fHZoomSliderView close];
		fHZoomSliderView = nil;
		return;
	}
	
	NSRect wFrame;
	NSPoint p;
	wFrame = [fHZoomButton frame];
	p.y = NSMidY(wFrame)-9.5;
	p.x = NSMinX(wFrame) - 150;
	
	wFrame.origin = [[self window] convertBaseToScreen:[[fHZoomButton superview] convertPoint:p toView:nil]];
	wFrame.size = NSMakeSize(150, 17);

	NSRect testFrame = [[NSScreen mainScreen] frame];
	if ( !NSContainsRect(testFrame, wFrame) )
	{
		wFrame.origin.x += 150 + NSWidth([fHZoomButton frame]);
	}

	NSWindow *win = [[NSWindow alloc] initWithContentRect:wFrame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
	NSSlider *slider = [[MIHSlider allocWithZone:[self zone]] initWithFrame:NSMakeRect(1,1,148,17)];
	[slider setMinValue:0];
	[slider setMaxValue:[MIMainViewController getNbHZoomIndices]-1 ];
	[slider setIntValue:(int)[slider maxValue] - [[NSApp mainViewController] hZoomIndex]];

	[[slider cell] setControlSize:NSSmallControlSize];
	[slider setTarget:self];
	[slider setAction:@selector(hSliderMoved:)];
	[[win contentView] addSubview:slider];
	[slider release]; 
	[win setHasShadow:YES];
	[win setLevel:NSFloatingWindowLevel];
	[[self window] addChildWindow:win ordered:NSWindowAbove];
	[win setLevel:NSFloatingWindowLevel];
	[win makeKeyAndOrderFront:self];
	fHZoomSliderView = win;
}

- (IBAction)vSliderMoved:(id)sender
{
	[[MIOverviewController sharedOverviewController] setFutureVZoomIndex:[sender intValue]];
}

- (IBAction)hSliderMoved:(id)sender
{
	[[MIOverviewController sharedOverviewController] setFutureHZoomIndex:(int)[sender maxValue] - [sender intValue]];
}

@end


@implementation MIHSlider : NSSlider
- (void)mouseDown:(NSEvent*)event
{
	[super mouseDown:event];
	[[NSApp mainViewController] setHZoom:(UInt32)[self maxValue] - [self intValue]];
	[[MIOverviewController sharedOverviewController] setFutureHZoomIndex:-1];
	[[MIOverviewController sharedOverviewController] setFutureVZoomIndex:-1];
	[[MIOverviewController sharedOverviewController] hZoomButtonPressed:self]; // toggle the view out
}
@end
@implementation MIVSlider : NSSlider
- (void)mouseDown:(NSEvent*)event
{
	[super mouseDown:event];
	[[NSApp mainViewController] setVZoom:[self intValue]];
	[[MIOverviewController sharedOverviewController] setFutureHZoomIndex:-1];
	[[MIOverviewController sharedOverviewController] setFutureVZoomIndex:-1];
	[[MIOverviewController sharedOverviewController] vZoomButtonPressed:self]; // toggle the view out

}
@end
