/***************************************************************************
                          kstarsinit.cpp  -  Trinity Desktop Planetarium
                             -------------------
    begin                : Mon Feb 25 2002
    copyright            : (C) 2002 by Jason Harris
    email                : jharris@30doradus.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it 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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tqlayout.h>
#include <tqfile.h>
#include <tqdir.h>
#include <dcopclient.h>
#include <tdeshortcut.h>
#include <kiconloader.h>
#include <tdepopupmenu.h>
#include <kstatusbar.h>
#include <ktip.h>
#include <tdemessagebox.h>
#include <kstandarddirs.h>

#include "Options.h"
#include "kstars.h"
#include "kstarsdata.h"
#include "kstarssplash.h"
#include "skymap.h"
#include "skyobject.h"
#include "ksplanetbase.h"
#include "ksutils.h"
#include "ksnumbers.h"
#include "infoboxes.h"
#include "toggleaction.h"
#include "indimenu.h"
#include "simclock.h"
#include "timestepbox.h"

//This file contains functions that kstars calls at startup (except constructors).
//These functions are declared in kstars.h

void KStars::initActions() {
//File Menu:
	new TDEAction(i18n("&New Window"), "window-new", TDEShortcut( "Ctrl+N"  ),
			this, TQ_SLOT( newWindow() ), actionCollection(), "new_window");
	new TDEAction(i18n("&Close Window"), "window-close", TDEShortcut( "Ctrl+W"  ),
			this, TQ_SLOT( closeWindow() ), actionCollection(), "close_window");
	new TDEAction( i18n( "&Download Data..." ), "knewstuff", TDEShortcut( "Ctrl+D" ),
			this, TQ_SLOT( slotDownload() ), actionCollection(), "get_data" );
	new TDEAction( i18n( "Open FITS..."), "document-open", TDEShortcut( "Ctrl+O"), this, TQ_SLOT( slotOpenFITS()), actionCollection(), "open_file");
	new TDEAction( i18n( "&Save Sky Image..." ), "fileexport", TDEShortcut( "Ctrl+I" ),
			this, TQ_SLOT( slotExportImage() ), actionCollection(), "export_image" );
	new TDEAction( i18n( "&Run Script..." ), "launch", TDEShortcut( "Ctrl+R" ),
			this, TQ_SLOT( slotRunScript() ), actionCollection(), "run_script" );
	KStdAction::print(this, TQ_SLOT( slotPrint() ), actionCollection(), "print" );
	KStdAction::quit(this, TQ_SLOT( close() ), actionCollection(), "quit" );

//Time Menu:
	new TDEAction( i18n( "Set Time to &Now" ), TDEShortcut( "Ctrl+E"  ),
		this, TQ_SLOT( slotSetTimeToNow() ), actionCollection(), "time_to_now" );
	new TDEAction( i18n( "set Clock to New Time", "&Set Time..." ), "clock", TDEShortcut( "Ctrl+S"  ),
		this, TQ_SLOT( slotSetTime() ), actionCollection(), "time_dialog" );
	ToggleAction *actTimeRun = new ToggleAction( i18n( "Stop &Clock" ), BarIcon("media-playback-pause"),
				i18n("Start &Clock"), BarIcon("1rightarrow"),
				0, this, TQ_SLOT( slotToggleTimer() ), actionCollection(), "timer_control" );
	actTimeRun->setOffToolTip( i18n( "Start Clock" ) );
	actTimeRun->setOnToolTip( i18n( "Stop Clock" ) );
	TQObject::connect(data()->clock(), TQ_SIGNAL(clockStarted()), actTimeRun, TQ_SLOT(turnOn()) );
	TQObject::connect(data()->clock(), TQ_SIGNAL(clockStopped()), actTimeRun, TQ_SLOT(turnOff()) );
//UpdateTime() if clock is stopped (so hidden objects get drawn)
	TQObject::connect(data()->clock(), TQ_SIGNAL(clockStopped()), this, TQ_SLOT(updateTime()) );

//Focus Menu:
	new TDEAction(i18n( "&Zenith" ), TDEShortcut( "Z" ),
			this, TQ_SLOT( slotPointFocus() ),  actionCollection(), "zenith");
	new TDEAction(i18n( "&North" ), TDEShortcut( "N" ),
			this, TQ_SLOT( slotPointFocus() ),  actionCollection(), "north");
	new TDEAction(i18n( "&East" ), TDEShortcut( "E" ),
			this, TQ_SLOT( slotPointFocus() ),  actionCollection(), "east");
	new TDEAction(i18n( "&South" ), TDEShortcut( "S" ),
			this, TQ_SLOT( slotPointFocus() ),  actionCollection(), "south");
	new TDEAction(i18n( "&West" ), TDEShortcut( "W" ),
			this, TQ_SLOT( slotPointFocus() ),  actionCollection(), "west");
	TDEAction *tmpAction = KStdAction::find( this, TQ_SLOT( slotFind() ),
												actionCollection(), "find_object" );
	tmpAction->setText( i18n( "&Find Object..." ) );
	tmpAction->setToolTip( i18n( "Find object" ) );

	new TDEAction( i18n( "Engage &Tracking" ), "decrypted", TDEShortcut( "Ctrl+T"  ),
		this, TQ_SLOT( slotTrack() ), actionCollection(), "track_object" );

	new TDEAction( i18n( "Set Focus &Manually..." ), TDEShortcut( "Ctrl+M" ),
			this, TQ_SLOT( slotManualFocus() ),  actionCollection(), "manual_focus" );

//View Menu:
	KStdAction::zoomIn(this, TQ_SLOT( slotZoomIn() ), actionCollection(), "zoom_in" );
	KStdAction::zoomOut(this, TQ_SLOT( slotZoomOut() ), actionCollection(), "zoom_out" );
	new TDEAction( i18n( "&Default Zoom" ), "viewmagfit.png", TDEShortcut( "Ctrl+Z" ),
		this, TQ_SLOT( slotDefaultZoom() ), actionCollection(), "zoom_default" );
	new TDEAction( i18n( "&Zoom to Angular Size..." ), "viewmag.png", TDEShortcut( "Ctrl+Shift+Z" ),
		this, TQ_SLOT( slotSetZoom() ), actionCollection(), "zoom_set" );
	actCoordSys = new ToggleAction( i18n("Horizontal &Coordinates"), i18n( "Equatorial &Coordinates" ),
			Key_Space, this, TQ_SLOT( slotCoordSys() ), actionCollection(), "coordsys" );
	KStdAction::fullScreen( this, TQ_SLOT( slotFullScreen() ), actionCollection(), 0 );


//Settings Menu:
	//
	// MHH - 2002-01-13
	// Setting the slot in the TDEToggleAction constructor, connects the slot to
	// the activated signal instead of the toggled signal. This seems like a bug
	// to me, but ...
	//
	//Info Boxes option actions
	TDEToggleAction *a = new TDEToggleAction(i18n( "Show the information boxes", "Show &Info Boxes"),
			0, 0, 0, actionCollection(), "show_boxes");
	a->setChecked( Options::showInfoBoxes() );
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), infoBoxes(), TQ_SLOT(setVisible(bool)));
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show time-related info box", "Show &Time Box"),
			0, 0, 0, actionCollection(), "show_time_box");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), infoBoxes(), TQ_SLOT(showTimeBox(bool)));
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show focus-related info box", "Show &Focus Box"),
			0, 0, 0, actionCollection(), "show_focus_box");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), infoBoxes(), TQ_SLOT(showFocusBox(bool)));
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show location-related info box", "Show &Location Box"),
			0, 0, 0, actionCollection(), "show_location_box");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), infoBoxes(), TQ_SLOT(showGeoBox(bool)));
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

//Toolbar view options
	a = new TDEToggleAction(i18n( "Show Main Toolbar" ),
			0, 0, 0, actionCollection(), "show_mainToolBar");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show View Toolbar" ),
			0, 0, 0, actionCollection(), "show_viewToolBar");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

//Statusbar view options
	a = new TDEToggleAction(i18n( "Show Statusbar" ),
			0, 0, 0, actionCollection(), "show_statusBar");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show Az/Alt Field" ),
			0, 0, 0, actionCollection(), "show_sbAzAlt");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

	a = new TDEToggleAction(i18n( "Show RA/Dec Field" ),
			0, 0, 0, actionCollection(), "show_sbRADec");
	TQObject::connect(a, TQ_SIGNAL( toggled(bool) ), this, TQ_SLOT(slotShowGUIItem(bool)));

//Color scheme actions.  These are added to the "colorschemes" TDEActionMenu.
	colorActionMenu = new TDEActionMenu( i18n( "C&olor Schemes" ), actionCollection(), "colorschemes" );
	addColorMenuItem( i18n( "&Default" ), "cs_default" );
	addColorMenuItem( i18n( "&Star Chart" ), "cs_chart" );
	addColorMenuItem( i18n( "&Night Vision" ), "cs_night" );
	addColorMenuItem( i18n( "&Moonless Night" ), "cs_moonless-night" );

//Add any user-defined color schemes:
	TQFile file;
	TQString line, schemeName, filename;
	file.setName( locate( "appdata", "colors.dat" ) ); //determine filename in local user KDE directory tree.
	if ( file.exists() && file.open( IO_ReadOnly ) ) {
		TQTextStream stream( &file );

		while ( !stream.eof() ) {
			line = stream.readLine();
			schemeName = line.left( line.find( ':' ) );
			//I call it filename here, but it's used as the name of the action!
			filename = "cs_" + line.mid( line.find( ':' ) +1, line.find( '.' ) - line.find( ':' ) - 1 );
			addColorMenuItem( i18n( schemeName.local8Bit() ), filename.local8Bit() );
		}
		file.close();
	}

	//Add FOV Symbol actions
	fovActionMenu = new TDEActionMenu( i18n( "&FOV Symbols" ), actionCollection(), "fovsymbols" );
	initFOV();

	new TDEAction( i18n( "Location on Earth", "&Geographic..." ), 
			"kstars_geo", TDEShortcut( "Ctrl+G"  ), this, 
			TQ_SLOT( slotGeoLocator() ), actionCollection(), "geolocation" );

	KStdAction::preferences( this, TQ_SLOT( slotViewOps() ), actionCollection(), "configure" );

	new TDEAction(i18n( "Startup Wizard..." ), "wizard", TDEShortcut(), 
			this, TQ_SLOT( slotWizard() ), actionCollection(), "startwizard" );

//Tools Menu:
	new TDEAction(i18n( "Calculator..."), TDEShortcut( "Ctrl+C"),
			this, TQ_SLOT( slotCalculator() ), actionCollection(), "astrocalculator");

	new TDEAction(i18n( "Observing List..."), TDEShortcut( "Ctrl+L"),
			this, TQ_SLOT( slotObsList() ), actionCollection(), "obslist");

	// enable action only if file was loaded and processed successfully.
	if (!data()->VariableStarsList.isEmpty())
		new TDEAction(i18n( "AAVSO Light Curves..."), TDEShortcut( "Ctrl+V"),
						this, TQ_SLOT( slotLCGenerator() ), actionCollection(), "lightcurvegenerator");

	new TDEAction(i18n( "Altitude vs. Time..."), TDEShortcut( "Ctrl+A"),
						this, TQ_SLOT( slotAVT() ), actionCollection(), "altitude_vs_time");
	new TDEAction(i18n( "What's up Tonight..."), TDEShortcut("Ctrl+U"),
						this, TQ_SLOT(slotWUT()), actionCollection(), "whats_up_tonight");
//FIXME GLOSSARY
//	new TDEAction(i18n( "Glossary..."), TDEShortcut("Ctrl+K"),
//						this, TQ_SLOT(slotGlossary()), actionCollection(), "glossary");
	new TDEAction(i18n( "Script Builder..."), TDEShortcut("Ctrl+B"),
						this, TQ_SLOT(slotScriptBuilder()), actionCollection(), "scriptbuilder");
	new TDEAction(i18n( "Solar System..."), TDEShortcut("Ctrl+Y"),
						this, TQ_SLOT(slotSolarSystem()), actionCollection(), "solarsystem");
	new TDEAction(i18n( "Jupiter's Moons..."), TDEShortcut("Ctrl+J"),
						this, TQ_SLOT(slotJMoonTool()), actionCollection(), "jmoontool");

// devices Menu
	new TDEAction(i18n("Telescope Wizard..."), 0, this, TQ_SLOT(slotTelescopeWizard()), actionCollection(), "telescope_wizard");
	new TDEAction(i18n("Telescope Properties..."), 0, this, TQ_SLOT(slotTelescopeProperties()), actionCollection(), "telescope_properties");
	new TDEAction(i18n("Device Manager..."), 0, this, TQ_SLOT(slotINDIDriver()), actionCollection(), "device_manager");
	
	tmpAction = new TDEAction(i18n("Capture Image Sequence..."), 0, this, TQ_SLOT(slotImageSequence()), actionCollection(), "capture_sequence");
	tmpAction->setEnabled(false);
	
	tmpAction = new TDEAction(i18n("INDI Control Panel..."), 0, this, TQ_SLOT(slotINDIPanel()), actionCollection(), "indi_control_panel");
	tmpAction->setEnabled(false);
	
	new TDEAction(i18n("Configure INDI..."), 0, this, TQ_SLOT(slotINDIConf()), actionCollection(), "configure_indi");



//Help Menu:
	new TDEAction( i18n( "Tip of the Day" ), "idea", 0,
			this, TQ_SLOT( slotTipOfDay() ), actionCollection(), "help_tipofday" );

//Handbook toolBar item:
	new TDEAction( i18n( "&Handbook" ), "contents", TDEShortcut( "F1"  ),
			this, TQ_SLOT( appHelpActivated() ), actionCollection(), "handbook" );

//
//viewToolBar actions:
//

//show_stars:
	a = new TDEToggleAction( i18n( "Toggle Stars" ), "kstars_stars", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_stars" );

//show_deepsky:
	a = new TDEToggleAction( i18n( "Toggle Deep Sky Objects" ), "kstars_deepsky", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_deepsky" );

//show_planets:
	a = new TDEToggleAction( i18n( "Toggle Solar System" ), "kstars_planets", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_planets" );

//show_clines:
	a = new TDEToggleAction( i18n( "Toggle Constellation Lines" ), "kstars_clines", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_clines" );

//show_cnames:
	a = new TDEToggleAction( i18n( "Toggle Constellation Names" ), "kstars_cnames", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_cnames" );

//show_cbound:
	a = new TDEToggleAction( i18n( "Toggle Constellation Boundaries" ), "kstars_cbound", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_cbounds" );

//show_mw:
	a = new TDEToggleAction( i18n( "Toggle Milky Way" ), "kstars_mw", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_mw" );

//show_grid:
	a = new TDEToggleAction( i18n( "Toggle Coordinate Grid" ), "kstars_grid", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_grid" );

//show_horizon:
	a = new TDEToggleAction( i18n( "Toggle Ground" ), "kstars_horizon", 
		0, this, TQ_SLOT( slotViewToolBar() ), actionCollection(), "show_horizon" );
	
	if (Options::fitsSaveDirectory().isEmpty())
			Options::setFitsSaveDirectory(TQDir:: homeDirPath());
}

void KStars::initFOV() {
	//Read in the user's fov.dat and populate the FOV menu with its symbols.  If no fov.dat exists, populate
	//create a default version.
	TQFile f;
	TQStringList fields;
	TQString nm;

	f.setName( locateLocal( "appdata", "fov.dat" ) );

	//if file s empty, let's start over
	if ( (uint)f.size() == 0 ) f.remove();

	if ( ! f.exists() ) {
		if ( ! f.open( IO_WriteOnly ) ) {
			kdDebug() << i18n( "Could not open fov.dat." ) << endl;
		} else {
			TQTextStream ostream(&f);
			ostream << i18n( "Do not use a field-of-view indicator", "No FOV" ) <<  ":0.0:0:#AAAAAA" << endl;
			ostream << i18n( "use field-of-view for binoculars", "7x35 Binoculars" ) << ":558:1:#AAAAAA" << endl;
			ostream << i18n( "use 1-degree field-of-view indicator", "One Degree" ) << ":60:2:#AAAAAA" << endl;
			ostream << i18n( "use HST field-of-view indicator", "HST WFPC2" ) << ":2.4:0:#AAAAAA" << endl;
			ostream << i18n( "use Radiotelescope HPBW", "30m at 1.3cm" ) << ":1.79:1:#AAAAAA" << endl;
			f.close();
		}
	}

	//just populate the FOV menu with items, don't need to fully parse the lines
	if ( f.open( IO_ReadOnly ) ) {
		TQTextStream stream( &f );
		while ( !stream.eof() ) {
			TQString line = stream.readLine();
			fields = TQStringList::split( ":", line );

			if ( fields.count() == 4 ) {
				nm = fields[0].stripWhiteSpace();
				TDEToggleAction *kta = new TDEToggleAction( nm, 0, this, TQ_SLOT( slotTargetSymbol() ), 
						actionCollection(), nm.utf8() );
				kta->setExclusiveGroup( "fovsymbol" );
				if ( nm == Options::fOVName() ) kta->setChecked( true );
				fovActionMenu->insert( kta );
			}
		}
	} else {
		kdDebug() << i18n( "Could not open file: %1" ).arg( f.name() ) << endl;
	}

	fovActionMenu->popupMenu()->insertSeparator();
	fovActionMenu->insert( new TDEAction( i18n( "Edit FOV Symbols..." ), 0, this, TQ_SLOT( slotFOVEdit() ), actionCollection(), "edit_fov" ) );
}

void KStars::initStatusBar() {
	statusBar()->insertItem( i18n( " Welcome to KStars " ), 0, 1, true );
	statusBar()->setItemAlignment( 0, AlignLeft | AlignVCenter );

	TQString s = "000d 00m 00s,   +00d 00\' 00\""; //only need this to set the width

	if ( Options::showAltAzField() ) {
		statusBar()->insertFixedItem( s, 1, true );
		statusBar()->setItemAlignment( 1, AlignRight | AlignVCenter );
		statusBar()->changeItem( "", 1 );
	}

	if ( Options::showRADecField() ) {
		statusBar()->insertFixedItem( s, 2, true );
		statusBar()->setItemAlignment( 2, AlignRight | AlignVCenter );
		statusBar()->changeItem( "", 2 );
	}

	if ( ! Options::showStatusBar() ) statusBar()->hide();
}

void KStars::datainitFinished(bool worked) {
	if (!worked) {
		kapp->quit();
		return;
	}

	if (pd->splash) {
		delete pd->splash;
		pd->splash = 0;
	}

	pd->buildGUI();
	data()->setFullTimeUpdate();
	updateTime();

	//Do not start the clock if the user specified "--paused" on the cmd line
	if ( StartClockRunning )
		data()->clock()->start();

//Initialize FOV symbol from options
	data()->fovSymbol.setName( Options::fOVName() );
	data()->fovSymbol.setSize( Options::fOVSize() );
	data()->fovSymbol.setShape( Options::fOVShape() );
	data()->fovSymbol.setColor( Options::fOVColor().name() );

	show();

	//If this is the first startup, show the wizard
	if ( Options::runStartupWizard() ) {
		slotWizard();
		//reset the clock to the system CPU
		slotSetTimeToNow();
	}

	//Check whether initial position is below the horizon.
	//We used to just call slotCenter() in buildGUI() which performs this check.
	//However, on some systems, if the messagebox is shown before show() is called,
	//the program exits.  It does not crash (at least there are no error messages),
	//it simply exits.  Very strange.
	if ( Options::useAltAz() && Options::showGround() &&
			map()->focus()->alt()->Degrees() < -1.0 ) {
		TQString caption = i18n( "Initial Position is Below Horizon" );
		TQString message = i18n( "The initial position is below the horizon.\nWould you like to reset to the default position?" );
		if ( KMessageBox::warningYesNo( this, message, caption,
				i18n("Reset Position"), i18n("Do Not Reset"), "dag_start_below_horiz" ) == KMessageBox::Yes ) {
			map()->setClickedObject( NULL );
			map()->setFocusObject( NULL );
			Options::setIsTracking( false );

			data()->setSnapNextFocus(true);

			SkyPoint DefaultFocus;
			DefaultFocus.setAz( 180.0 );
			DefaultFocus.setAlt( 45.0 );
			DefaultFocus.HorizontalToEquatorial( LST(), geo()->lat() );
			map()->setDestination( &DefaultFocus );
		}
	}

	//Store focus coords in Options object before calling applyConfig()
	Options::setFocusRA( map()->focus()->ra()->Hours() );
	Options::setFocusDec( map()->focus()->dec()->Degrees() );

	//Propagate Options values through the program
	applyConfig();

	//If there is a focusObject() and it is a SS body, add a temporary Trail to it.
	if ( map()->focusObject() && map()->focusObject()->isSolarSystem()
			&& Options::useAutoTrail() ) {
		((KSPlanetBase*)map()->focusObject())->addToTrail();
		data()->temporaryTrail = true;
	}

// just show dialog if option is set (don't force it)
	KTipDialog::showTip( "kstars/tips" );
}

void KStars::privatedata::buildGUI() {
	//create the widgets
	ks->centralWidget = new TQWidget( ks );
	ks->setCentralWidget( ks->centralWidget );

	//set AAVSO modaless dialog pointer to 0
	ks->AAVSODialog = 0;

	//INDI menu started without GUI
	ks->indimenu = new INDIMenu(ks);

	//INDI driver set to null
	ks->indidriver = 0;
	
	//INDI img sequence, set to null
	ks->indiseq = 0;

	ks->skymap = new SkyMap( ks->data(), ks->centralWidget );
	// update skymap if KStarsData send update signal
	TQObject::connect(kstarsData, TQ_SIGNAL( update() ), ks->skymap, TQ_SLOT( forceUpdateNow() ) );

	// get focus of keyboard and mouse actions (for example zoom in with +)
	ks->map()->TQWidget::setFocus();

	ks->initStatusBar();
	ks->initActions();

	// create the layout of the central widget
	ks->topLayout = new TQVBoxLayout( ks->centralWidget );
	ks->topLayout->addWidget( ks->skymap );

	// 2nd parameter must be false, or plugActionList won't work!
	ks->createGUI("kstarsui.rc", false);

	//Do not show text on the view toolbar buttons
	//FIXME: after strings freeze, remove this and make the
	//text of each button shorter
	ks->toolBar( "viewToolBar" )->setIconText( TDEToolBar::IconOnly );

	ks->TimeStep = new TimeStepBox( ks->toolBar() );
	ks->toolBar()->insertWidget( 0, 6, ks->TimeStep, 15 );

//Changing the timestep needs to propagate to the clock, check if slew mode should be
//(dis)engaged, and return input focus to the skymap.
	connect( ks->TimeStep, TQ_SIGNAL( scaleChanged( float ) ), ks->data(), TQ_SLOT( setTimeDirection( float ) ) );
	connect( ks->TimeStep, TQ_SIGNAL( scaleChanged( float ) ), ks->data()->clock(), TQ_SLOT( setScale( float )) );
//	connect( ks->TimeStep, TQ_SIGNAL( scaleChanged( float ) ), ks->skymap, TQ_SLOT( slotClockSlewing() ) );
	connect( ks->data()->clock(), TQ_SIGNAL( scaleChanged( float ) ), ks->map(), TQ_SLOT( slotClockSlewing() ) );
	connect( ks->TimeStep, TQ_SIGNAL( scaleChanged( float ) ), ks, TQ_SLOT( mapGetsFocus() ) );

	ks->resize( Options::windowWidth(), Options::windowHeight() );

	//Geographic location
	ks->setGeoLocation( Options::cityName(), Options::provinceName(), Options::countryName() );

	// initialize clock with current time/date or the date/time specified on the command line
	KStarsDateTime startDate = KStarsDateTime::fromString( ks->StartDateString );
	if ( startDate.isValid() )
		ks->data()->changeDateTime( ks->geo()->LTtoUT( startDate ) );
	else 
		ks->slotSetTimeToNow();
	
	//Define the celestial equator, horizon and ecliptic
	KSNumbers tempnum(ks->data()->ut().djd());
	ks->data()->initGuides(&tempnum);

	//Connect the clock.
	TQObject::connect( ks->data()->clock(), TQ_SIGNAL( timeAdvanced() ), ks, TQ_SLOT( updateTime() ) );
	TQObject::connect( ks->data()->clock(), TQ_SIGNAL( timeChanged() ), ks, TQ_SLOT( updateTime() ) );

	// Connect cache function
	TQObject::connect( kstarsData, TQ_SIGNAL( clearCache() ), ks, TQ_SLOT( clearCachedFindDialog() ) );

	SkyPoint newPoint;
	if ( ks->data()->useDefaultOptions ) {
		newPoint.setAz( Options::focusRA() );
		newPoint.setAlt( Options::focusDec() + 0.0001 );
		newPoint.HorizontalToEquatorial( ks->LST(), ks->geo()->lat() );
	} else {
		newPoint.set( Options::focusRA(), Options::focusDec() );
	}

//need to set focusObject before updateTime, otherwise tracking is set to false
	if ( (Options::focusObject() != i18n( "star" ) ) &&
		     (Options::focusObject() != i18n( "nothing" ) ) )
			ks->map()->setFocusObject( ks->data()->objectNamed( Options::focusObject() ) );

	ks->updateTime();

	//Set focus of Skymap to value stored in config.
	//Set default position in case stored focus is below horizon
//	SkyPoint DefaultFocus;
//	DefaultFocus.setAz( 180.0 );
//	DefaultFocus.setAlt( 45.0 );
//	DefaultFocus.HorizontalToEquatorial( ks->LST(), ks->geo()->lat() );
//	ks->map()->setDestination( &DefaultFocus );

	//if user was tracking last time, track on same object now.
	if ( Options::isTracking() ) {
		if ( (Options::focusObject() == i18n( "star" ) ) ||
		     (Options::focusObject() == i18n( "nothing" ) ) ) {
			ks->map()->setFocusPoint( &newPoint );
		} else {
			ks->map()->setClickedObject( ks->data()->objectNamed( Options::focusObject() ) );
			if ( ks->map()->clickedObject() ) {
				ks->map()->setFocusPoint( ks->map()->clickedObject() );
				ks->map()->setFocusObject( ks->map()->clickedObject() );
			} else {
				ks->map()->setFocusPoint( &newPoint );
			}
		}
//		ks->map()->slotCenter();
	} else {
		ks->map()->setFocusPoint( &newPoint );
//		ks->map()->slotCenter();
	}

//	if ( Options::focusObject() == i18n( "star" ) ) Options::setFocusObject( i18n( "nothing" ) );

	ks->map()->setDestination( ks->map()->focusPoint() );
	ks->map()->destination()->EquatorialToHorizontal( ks->LST(), ks->geo()->lat() );
	ks->map()->setFocus( ks->map()->destination() );
	ks->map()->focus()->EquatorialToHorizontal( ks->LST(), ks->geo()->lat() );

//	ks->infoBoxes()->focusObjChanged( Options::focusObject() );
//	ks->infoBoxes()->focusCoordChanged( ks->map()->focus() );
	ks->map()->showFocusCoords();
	
	ks->data()->setHourAngle( ks->LST()->Hours() - ks->map()->focus()->ra()->Hours() );

	ks->map()->setOldFocus( ks->map()->focus() );
	ks->map()->oldfocus()->setAz( ks->map()->focus()->az()->Degrees() );
	ks->map()->oldfocus()->setAlt( ks->map()->focus()->alt()->Degrees() );

	// check zoom in/out buttons
	if ( Options::zoomFactor() >= MAXZOOM ) ks->actionCollection()->action("zoom_in")->setEnabled( false );
	if ( Options::zoomFactor() <= MINZOOM ) ks->actionCollection()->action("zoom_out")->setEnabled( false );

	kapp->dcopClient()->resume();
}
