#!/usr/bin/env perl
# Copyright 2012 Dimitrios - Georgios Kontopoulos
#    <dgkontopoulos[at]member[dot]fsf[dot]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 3 of the License, or
#  (at your option) any later version.
#
#  This program 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 more details at
#  <http://www.gnu.org/licenses>.

use strict;
use warnings;

use Date::Calc qw(Add_Delta_Days Delta_Days);
use DBI;
use Encode;
use Gtk2 -init;
use Gtk2::SimpleList;
use Locale::gettext;
use POSIX;
use utf8;

our $VERSION = 1.4;

my $d = Locale::gettext->domain('OrthCal');
$d->dir('/usr/share/locale/');

my $indicator = 'OrthCal_ind.py';
if ( `ps -e | grep OrthCal` !~ /$indicator/ )
{
    system "/usr/bin/OrthCal_ind.py&";
    exit;
}

if ( $ARGV[0] eq 'about' )
{
    my $window = Gtk2::Window->new('toplevel');
    $window->set_default_icon_from_file(
        '/usr/share/pixmaps/orthcal/OrthCal.png');
    $window->set_title( $d->get('About OrthCal') );
    $window->signal_connect( destroy => sub { Gtk2->main_quit() } );
    $window->set_resizable(0);

    my $logo = Gtk2::Image->new_from_file(
        '/usr/share/pixmaps/orthcal/OrthCal.png');
    my $top_info = $d->get(<<'ABOUT');
<b>OrthCal, the Eastern Orthodox Calendar</b>, v. 1.4
		        <a href="http://launchpad.net/orthcal">Homepage</a> - - <a href="https://www.transifex.com/projects/p/OrthCal">Translations</a>
         (C) 2012 <a href="mailto:dgkontopoulos@member.fsf.org?Subject=OrthCal">Dimitrios - Georgios Kontopoulos</a>
ABOUT
    chomp $top_info;
    my $second_info = $d->get(<<'ABOUT');
<span size="small">This application was written for the <a href="http://developer.ubuntu.com/showdown/">Ubuntu App Showdown contest</a> of
July 2012, mainly as practice.

The indicator's code is written in <a href="http://www.python.org/">Python</a>/<a href="http://www.pygtk.org/">PyGTK</a>, whereas the main part
of the calendar is written in <a href="http://www.perl.org/">Perl</a>/<a href="http://search.cpan.org/~xaoc/Gtk2-1.244/lib/Gtk2.pm">GTK2</a>.</span>
ABOUT
    chomp $second_info;
    my $content_sources = $d->get(<<'ABOUT');
<span size="small"><b><u>Content sources:</u></b>
	➜The daily feasts have been extracted from <a href="http://orthodoxwiki.org/">OrthodoxWiki</a> (CC BY-
SA 2.5), <a href="http://www.saint.gr">saint.gr</a> (<i>"freely ye have received, freely give"</i>) and <a href="http://drevo-info.ru/">Древо</a> (Public
Domain).
	➜The background picture of a cross has been borrowed under the
CC BY 2.0 license from <a href="http://www.flickr.com/photos/brantley/5173197588/">Peter Brantley</a>.
	➜The application's icon has been borrowed under the CC BY-SA
2.0 license from <a href="http://www.flickr.com/photos/59838910@N06/7715907356/">israeltourism</a>.</span>
ABOUT
    chomp $content_sources;
    my $license = $d->get(<<'ABOUT');
<span size="small"><b><u>License:</u></b>
<i>This program is free software; you can redistribute it and/or modify it
under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public License, as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version</a>.

This program 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.</i>

Images and content mentioned at the Content Sources section are
offered under their original respective licenses.</span>
ABOUT
    chomp $license;
    my $thanks = $d->get(<<'ABOUT');
<span size="small"><b><u>Thanks to:</u></b>
	➜<b>Adolfo Jayme Barrientos</b> for translating OrthCal to Spanish.
	➜<b>Ciprian M Cornea</b> and <b>Ovidiu-Constantin Teaca</b> for translating
OrthCal to Romanian.
	➜<b>Rodion Renzhin</b> for editing the Russian feasts content and
translating OrthCal to Russian.
	➜the members of the <b><a href='http://ubuntu.gr'>Ubuntu-gr community</a></b> for bugs detection,
feature suggestions and general support.</span>
ABOUT
    chomp $thanks;
    my $vbox = Gtk2::VBox->new( '0', '10' );
    my $label1 = Gtk2::Label->new();
    $label1->set_markup($top_info);
    my $separator1 = Gtk2::HSeparator->new;
    my $label2     = Gtk2::Label->new();
    $label2->set_markup($second_info);
    my $separator2 = Gtk2::HSeparator->new;

    my $content_button =
      Gtk2::ToggleButton->new_with_label( $d->get('Content sources') );
    my $license_button =
      Gtk2::ToggleButton->new_with_label( $d->get('License') );
    my $thanks_button = Gtk2::ToggleButton->new_with_label( $d->get('Thanks') );

    my $content_counter = 0;
    $content_button->signal_connect(
        toggled => sub {
            if ( $content_counter == 0 )
            {
                $content_counter = 1;
                $license_button->set_active(0);
                $thanks_button->set_active(0);
                $label2->set_markup($content_sources);
                $window->show_all;
            }
            else
            {
                $content_counter = 0;
                $content_button->set_active(0);
                $label2->set_markup($second_info);
                $window->show_all;
            }
        }
    );
    my $license_counter = 0;
    $license_button->signal_connect(
        toggled => sub {
            if ( $license_counter == 0 )
            {
                $license_counter = 1;
                $content_button->set_active(0);
                $thanks_button->set_active(0);
                $label2->set_markup($license);
                $window->show_all;
            }
            else
            {
                $license_counter = 0;
                $license_button->set_active(0);
                $label2->set_markup($second_info);
                $window->show_all;
            }
        }
    );
    my $thanks_counter = 0;
    $thanks_button->signal_connect(
        toggled => sub {
            if ( $thanks_counter == 0 )
            {
                $thanks_counter = 1;
                $content_button->set_active(0);
                $license_button->set_active(0);
                $label2->set_markup($thanks);
                $window->show_all;
            }
            else
            {
                $thanks_counter = 0;
                $thanks_button->set_active(0);
                $label2->set_markup($second_info);
                $window->show_all;
            }
        }
    );

    my $quit_button = Gtk2::Button->new_from_stock('gtk-quit');
    $quit_button->signal_connect( clicked => sub { Gtk2->main_quit() } );

    $vbox->add($logo);
    $vbox->add($label1);
    $vbox->add($separator1);
    $vbox->add($label2);
    $vbox->add($separator2);
    my $hbox = Gtk2::HBox->new( 0, 20 );
    $hbox->add($content_button);
    $hbox->add($license_button);
    $hbox->add($thanks_button);
    $hbox->add($quit_button);
    $vbox->add($hbox);
    $window->set_border_width(15);
    $window->set_position('mouse');
    $window->add($vbox);

    $window->show_all;
    Gtk2->main;
    exit;
}
elsif ( $ARGV[0] eq 'options' )
{
    my $window = Gtk2::Window->new('toplevel');
    $window->set_default_icon_from_file(
        '/usr/share/pixmaps/orthcal/OrthCal.png');
    $window->signal_connect( destroy => sub { Gtk2->main_quit() } );
    $window->set_resizable(0);
    my $vbox = Gtk2::VBox->new( '0', '10' );

    my $column1 = $d->get('Daily Feasts source');
    my $column2 = $d->get('Language');
    my $column3 = $d->get('Completed');

    my $slist = Gtk2::SimpleList->new(
        $column1 => 'text',
        $column2 => 'text',
        $column3 => 'text'
    );

    @{ $slist->{data} } = (
        [ 'orthodoxwiki.org', 'English',          "\t+" ],
        [ 'saint.gr',         'Ελληνικά', "\t+" ],
        [ 'drevo-info.ru',    'русский',   "\t+" ]
    );
    my $username = getpwuid $<;
    my $source;
    if ( -e "/home/$username/.config/orthcal/source" )
    {
        open my $source_fh, '<', "/home/$username/.config/orthcal/source";
        $source = <$source_fh>;
        close $source_fh;
        chomp $source;
        if ( $source =~ /orthodoxwiki[.]org/ )
        {
            $slist->select(0);
        }
        elsif ( $source =~ /saint[.]gr/ )
        {
            $slist->select(1);
        }
        elsif ( $source =~ /drevo[-]info[.]ru/ )
        {
            $slist->select(2);
        }
        else
        {
            $slist->select(0);
            open my $source_fh, '>', "/home/$username/.config/orthcal/source";
            print {$source_fh} 'orthodoxwiki.org';
            close $source_fh;
        }
    }
    else
    {
        unless ( -d "/home/$username/.config/orthcal/" )
        {
            system "mkdir -p /home/$username/.config/orthcal/";
        }
        open my $source_fh, '>', "/home/$username/.config/orthcal/source";
        print {$source_fh} 'orthodoxwiki.org';
        close $source_fh;
    }
    my $changes = 0;
    ##################################################
    #Change feasts source when double clicking a row.#
    ##################################################
    $slist->signal_connect(
        row_activated => sub {
            my $self = shift;
            if ( $self->get_selection )
            {
                my $selection = $self->get_selection;
                $selection->selected_foreach(
                    sub {
                        my ( $model, $path, $iter ) = @_;
                        my $value = $model->get( $iter, 0 );
                        open my $source_fh, '>',
                          "/home/$username/.config/orthcal/source";
                        print {$source_fh} $value;
                        close $source_fh;
                    }
                );
            }
            if ( $changes == 0 )
            {
                $changes = 1;

                my $restart = $d->get(
                    '<i>Please restart OrthCal for changes to take effect.</i>'
                );
                my $restart_label = Gtk2::Label->new();
                $restart_label->set_markup($restart);
                my $red = Gtk2::Gdk::Color->new( 65_535, 0, 0 );
                $restart_label->modify_fg( 'normal', $red );

                $vbox->add($restart_label);
                $window->show_all;
            }
        }
    );
    my $list_message = $d->get(<<'END');
<b>Double click</b> to change from one source to another.
END
    chomp $list_message;

    my $label = Gtk2::Label->new();
    $label->set_markup($list_message);

    my $separator = Gtk2::HSeparator->new;

    my $autostart = $d->get('Start OrthCal on system startup.');
    my $checkbox  = Gtk2::CheckButton->new($autostart);

    if ( -e "/home/$username/.config/autostart/orthcal.desktop" )
    {
        $checkbox->set_active(1);
    }
    else
    {
        $checkbox->set_active(0);
    }

    $checkbox->signal_connect( toggled => \&autostart, $username, );

    $vbox->add($slist);
    $vbox->add($label);
    $vbox->add($separator);
    $vbox->add($checkbox);

    $window->set_title( $d->get('Options for OrthCal') );
    $window->set_border_width(15);
    $window->set_position('mouse');
    $window->add($vbox);

    $window->show_all;
    Gtk2->main;
    exit;
}

my $date = `date +%d/%m/%Y`;
my ( $day, $month, $year );

if ( $date =~ /(\d+)\/(\d+)\/(\d+)/ )
{
    $day   = $1;
    $month = $2;
    $year  = $3;
}

if ( $ARGV[0] eq 'Julian' )
{
    ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, '-13' );
    if ( $month !~ /\d\d/ )
    {
        $month = '0' . $month;
    }
    if ( $day !~ /\d\d/ )
    {
        $day = '0' . $day;
    }
}
my $username = getpwuid $<;
my $source;
if ( -e "/home/$username/.config/orthcal/source" )
{
    open my $source_fh, '<', "/home/$username/.config/orthcal/source";
    $source = <$source_fh>;
    close $source_fh;
    chomp $source;
}
else
{
    $source = 'orthodoxwiki.org';
}
my $dbh =
  DBI->connect( 'dbi:SQLite:/usr/share/applications/orthcal/content/saints.db',
    q{}, q{} );
my $db_sel = $dbh->prepare(
"SELECT * FROM Saints WHERE Month = $month AND Day = $day AND source LIKE '%$source%'"
);
$db_sel->execute();
my $row    = $db_sel->fetch;
my $feasts = $row->[0];
$feasts = decode 'UTF8', $feasts;

my ( $Easterd, $Easterm, $Eastery );
OrthEaster();

( $Eastery, $Easterm, $Easterd ) =
  Add_Delta_Days( $Eastery, $Easterm, $Easterd, '13' );

my $Dd = Delta_Days( $Eastery, $Easterm, $Easterd, $year, $month, $day );

#####################################################################
#Movable Feasts and their distance in days from the Orthodox Easter.#
#####################################################################
my %movable;
$movable{'-77'} = $d->get('<b>Zacchaeus</b> Sunday');
$movable{'-70'} = $d->get('Publican & Pharisee Sunday');
$movable{'-63'} = $d->get('Sunday of the Prodigal Son');
$movable{'-56'} = $d->get('Meat Fare Sunday (Sunday of Last Judgement)');
$movable{'-49'} =
  $d->get('Cheesefare (Forgiveness) Sunday / Expulsion from Paradise');
$movable{'-48'} = $d->get('Great Lent begins');
$movable{'-42'} = $d->get('Sunday of Orthodoxy');
$movable{'-35'} = $d->get('Sunday of St. <b>Gregory</b> Palamas');
$movable{'-28'} = $d->get('Sunday of the Holy Cross');
$movable{'-21'} = $d->get('Sunday of St. <b>John</b> Climacus');
$movable{'-14'} = $d->get('Sunday of St. <b>Mary</b> of Egypt');
$movable{'-8'}  = $d->get('<b>Lazarus</b> Saturday');
$movable{'-7'}  = $d->get('Palm Sunday');
$movable{'-6'}  = $d->get('Holy Monday');
$movable{'-5'}  = $d->get('Holy Tuesday');
$movable{'-4'}  = $d->get('Holy Wednesday');
$movable{'-3'}  = $d->get('Holy Thursday');
$movable{'-2'}  = $d->get('Holy Friday');
$movable{'-1'}  = $d->get('Holy Saturday');
$movable{'0'}   = $d->get('Pascha');
$movable{'7'}   = $d->get('Sunday of St. <b>Thomas</b>');
$movable{'14'}  = $d->get('Sunday of Myrrh-bearing Women');
$movable{'21'}  = $d->get('Sunday of the Paralytic');
$movable{'24'}  = $d->get('Midfeast of Pentecost');
$movable{'28'}  = $d->get('Sunday of the Samaritan Woman');
$movable{'35'}  = $d->get('Sunday of the Blind Man');
$movable{'38'}  = $d->get('Leavetaking of Pascha');
$movable{'39'}  = $d->get('Ascension Thursday');
$movable{'42'}  = $d->get('Fathers of the 1st Ecumenical Council');
$movable{'49'}  = $d->get('Pentecost Sunday');
$movable{'50'}  = $d->get('Day of the Holy Spirit');
$movable{'56'}  = $d->get('Sunday of All Saints');
$movable{'63'}  = $d->get('All Saints of North America');

binmode STDOUT, ':encoding(UTF-8)';

if ( $ARGV[0] eq 'Julian' )
{
    $Dd += 13;
}

if ( defined $movable{$Dd} )
{
    $feasts = '✙✙ <b>' . $movable{$Dd} . '</b> ✙✙✙' . "\n" . $feasts;
}
$feasts = "   ✙ " . $feasts;
$feasts =~ s/\n(\w|[<"])/\n   \✙ $1/g;
my $occurences = ( $feasts =~ tr/\n// );

if ( $source ne 'drevo-info.ru' )
{
    if ( $occurences < 26 )
    {
        if ( $occurences > 20 )
        {
            $feasts =~ s/\n(.+\n.+\n.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        elsif ( $occurences > 15 )
        {
            $feasts =~ s/\n(.+\n.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        elsif ( $occurences > 10 )
        {
            $feasts =~ s/\n(.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        elsif ( $occurences > 5 )
        {
            $feasts =~ s/\n(.+)\n(.+)/\n$1\n\n$2/g;
        }
        else
        {
            $feasts =~ s/\n(.+)/\n\n$1/g;
        }
    }
    elsif ( $occurences < 36 )
    {
        chomp $feasts;
        $feasts = '<span size="x-small">' . $feasts . '</span>';
    }
    else
    {
        chomp $feasts;
        $feasts = '<span size="xx-small">' . $feasts . '</span>';
    }
}
else
{
    if ( $occurences < 20 )
    {
        if ( $occurences > 15 )
        {
            $feasts =~ s/\n(.+\n.+\n.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        elsif ( $occurences > 10 )
        {
            $feasts =~ s/\n(.+\n.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        elsif ( $occurences > 5 )
        {
            $feasts =~ s/\n(.+\n.+)\n(.+)/\n$1\n\n$2/g;
        }
        else
        {
            $feasts =~ s/\n(.+)/\n\n$1/g;
        }
    }
    elsif ( $occurences < 30 )
    {
        chomp $feasts;
        $feasts = '<span size="x-small">' . $feasts . '</span>';
    }
    else
    {
        chomp $feasts;
        $feasts = '<span size="xx-small">' . $feasts . '</span>';
    }
}

my $window = Gtk2::Window->new('toplevel');
$window->set_default_icon_from_file(
    '/usr/share/pixmaps/orthcal/OrthCal.png');
$window->signal_connect( destroy => \&app_quit );
$window->set_resizable(0);

if ( $ARGV[0] eq 'Julian' )
{
    my ( $year2, $month2, $day2 );
    ( $year2, $month2, $day2 ) = Add_Delta_Days( $year, $month, $day, '13' );
    $window->set_title(
        "$day/$month/$year // [$day2/$month2/$year2] -- OrthCal");
}
else
{
    $window->set_title("$day/$month/$year -- OrthCal");
}

#############
#Menu items.#
#############
my $menu_bar = Gtk2::MenuBar->new();

#######
#File.#
#######
my $menu_item_file = Gtk2::MenuItem->new( $d->get('_File') );
my $menu_file      = Gtk2::Menu->new();

my $menu_file_quit = Gtk2::ImageMenuItem->new_from_stock( 'gtk-quit', undef );
$menu_file_quit->signal_connect( 'activate' => sub { app_quit() } );

$menu_file->append($menu_file_quit);
$menu_item_file->set_submenu($menu_file);
$menu_bar->append($menu_item_file);

#######
#Edit.#
#######
my $menu_item_edit = Gtk2::MenuItem->new( $d->get('_Edit') );
my $menu_edit      = Gtk2::Menu->new();

my $menu_edit_preferences =
  Gtk2::ImageMenuItem->new_from_stock( 'gtk-preferences', undef );
$menu_edit_preferences->signal_connect(
    'activate' => sub { system "$0 options&" } );
$menu_edit->append($menu_edit_preferences);

$menu_item_edit->set_submenu($menu_edit);
$menu_bar->append($menu_item_edit);

########
#Tools.#
########
my $menu_item_tools = Gtk2::MenuItem->new( $d->get('_Tools') );
my $menu_tools      = Gtk2::Menu->new();

my $menu_tools_name =
  Gtk2::MenuItem->new( $d->get('Search for feasts by name') );
$menu_tools_name->signal_connect( 'activate' => \&search_by_name );
$menu_tools->append($menu_tools_name);

my $menu_tools_pascha =
  Gtk2::MenuItem->new( $d->get('Pascha date calculator') );
$menu_tools_pascha->signal_connect( 'activate' => \&Pascha_calculator );
$menu_tools->append($menu_tools_pascha);

$menu_item_tools->set_submenu($menu_tools);
$menu_bar->append($menu_item_tools);

#######
#Help.#
#######
my $menu_item_help = Gtk2::MenuItem->new( $d->get('_Help') );
my $menu_help      = Gtk2::Menu->new();

my $menu_help_translations =
  Gtk2::MenuItem->new( $d->get('Translate OrthCal...') );
$menu_help_translations->signal_connect(
    'activate' => sub {
        system 'xdg-open https://www.transifex.com/projects/p/OrthCal/';
    }
);
$menu_help->append($menu_help_translations);

$menu_help->append( Gtk2::SeparatorMenuItem->new() );

my $menu_help_Perl = Gtk2::MenuItem->new( $d->get('About Perl') );
$menu_help_Perl->signal_connect(
    'activate' => sub { system 'xdg-open http://www.perl.org/about.html' } );
$menu_help->append($menu_help_Perl);

my $menu_help_gtk2 = Gtk2::MenuItem->new( $d->get('About gtk2-perl') );
$menu_help_gtk2->signal_connect(
    'activate' => sub { system 'xdg-open http://gtk2-perl.sourceforge.net/' } );
$menu_help->append($menu_help_gtk2);

$menu_help->append( Gtk2::SeparatorMenuItem->new() );

my $menu_help_about = Gtk2::ImageMenuItem->new_from_stock( 'gtk-about', undef );
$menu_help_about->signal_connect( 'activate' => sub { system "$0 about&"; } );
$menu_help->append($menu_help_about);

$menu_item_help->set_submenu($menu_help);
$menu_bar->append($menu_item_help);

###############
#Text options.#
###############
my $label = Gtk2::Label->new();
$label->set_markup($feasts);
$label->set_line_wrap('TRUE');
$window->set_position('mouse');

my $vbox = Gtk2::VBox->new( '0', '10' );
$vbox->add($menu_bar);
$vbox->add($label);

$window->add($vbox);

#############
#Background.#
#############
my $back_pixbuf = Gtk2::Gdk::Pixbuf->new_from_file(
    '/usr/share/pixmaps/orthcal/bg.jpg');
my ( $pixmap, $mask ) = $back_pixbuf->render_pixmap_and_mask(255);
my $style = $window->get_style();
$style = $style->copy();
$style->bg_pixmap( 'normal', $pixmap );
$window->set_style($style);
$window->show_all;
Gtk2->main;

sub app_quit
{
    my $pid = `ps aux | grep -v grep | grep OrthCal.pl`;
    if ( $pid =~ /^\d+\s+(\d+)\s+/ )
    {
        $pid = $1;
        if ( $' =~ /\n\d+\s+(\d+)\s+/ )
        {
            $pid .= q{ } . $1;
        }
    }
    system "kill $pid";
    Gtk2->main_quit();
    return 0;
}

#######################################
#Have OrthCal start on system startup.#
#######################################
sub autostart
{
    my $self     = shift;
    my $username = shift;
    my $changes  = shift;

    if ( $self->get_active )
    {
        unless ( -d "/home/$username/.config/autostart/" )
        {
            system "mkdir -p /home/$username/.config/autostart/";
        }
        open my $desktop_fh, '>',
          "/home/$username/.config/autostart/orthcal.desktop";
        print {$desktop_fh} <<'END';

[Desktop Entry]
Type=Application
Exec=/usr/bin/OrthCal.pl
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=OrthCal
END
        close $desktop_fh;
    }
    else
    {
        if ( -e "/home/$username/.config/autostart/orthcal.desktop" )
        {
            unlink "/home/$username/.config/autostart/orthcal.desktop";
        }
    }
    return 0;
}

sub OrthEaster
{
    if ( defined $_[0] )
    {
        $year = $_[0];
    }
    my ( $a, $b, $c, $d, $e );

    $a       = $year % 4;
    $b       = $year % 7;
    $c       = $year % 19;
    $d       = ( 19 * $c + 15 ) % 30;
    $e       = ( 2 * $a + 4 * $b - $d + 34 ) % 7;
    $Easterm = ( ( $d + $e + 114 ) / 31 );
    $Easterd = ( ( $d + $e + 114 ) % 31 ) + 1;
    $Eastery = $year;

    return $Easterd, $Easterm, $Eastery;
}

sub Pascha_calculator
{
    my $pascha_window = Gtk2::Window->new('toplevel');
    $pascha_window->set_default_icon_from_file(
        '/usr/share/pixmaps/orthcal/OrthCal.png');
    $pascha_window->set_title( $d->get('Pascha calculator -- OrthCal') );
    $pascha_window->signal_connect( destroy => sub { Gtk2->main_quit() } );
    $pascha_window->set_position('mouse');
    $pascha_window->set_resizable(0);
    $pascha_window->set_border_width(15);

    my $vbox = Gtk2::VBox->new( '0', '10' );

    my $adj = Gtk2::Adjustment->new( $year, 33, 9999, 1.0, 5.0, 0.0 );
    my $spinner = Gtk2::SpinButton->new( $adj, 0, 0 );

    my $button  = Gtk2::Button->new_from_stock('gtk-execute');
    my $counter = 0;
    my $date    = Gtk2::Label->new();
    $button->signal_connect(
        clicked => sub {
            my $custom_year = $spinner->get_value_as_int;
            my $old_year    = $year;
            OrthEaster($custom_year);

            ( $Eastery, $Easterm, $Easterd ) =
              Add_Delta_Days( $Eastery, $Easterm, $Easterd, '13' );
            my $result;
            if ( $old_year <= $custom_year )
            {
                $result =
                    $d->get("The date of Pascha in ")
                  . $Eastery
                  . $d->get(" is:")
                  . " <b>$Easterd/$Easterm</b>.";
            }
            else
            {
                $result =
                    $d->get("The date of Pascha in ")
                  . $Eastery
                  . $d->get(" was:")
                  . " <b>$Easterd/$Easterm</b>.";
            }

            $date->set_markup($result);
            if ( $counter == 0 )
            {
                $vbox->add($date);
                $counter = 1;
            }
            else
            {
                $vbox->remove($date);
                $vbox->add($date);
            }
            $pascha_window->show_all;
            Gtk2->main;
            Gtk2->main_quit;
        }
    );

    my $hbox = Gtk2::HBox->new( '0', '5' );
    $hbox->add($spinner);
    $hbox->add($button);
    $vbox->add($hbox);
    my $separator = Gtk2::HSeparator->new;
    $vbox->add($separator);
    $pascha_window->add($vbox);
    $pascha_window->show_all;
    Gtk2->main;
    return 0;
}

sub search_by_name
{
    my $search_window = Gtk2::Window->new('toplevel');
    $search_window->set_default_icon_from_file(
        '/usr/share/pixmaps/orthcal/OrthCal.png');
    $search_window->set_title( $d->get('Feast search -- OrthCal') );
    $search_window->signal_connect( destroy => sub { Gtk2->main_quit() } );
    $search_window->set_position('mouse');
    $search_window->set_resizable(0);
    $search_window->set_border_width(15);

    my $vbox    = Gtk2::VBox->new( '0', '10' );
    my $textbox = Gtk2::Entry->new();
    my $button  = Gtk2::Button->new_from_stock('gtk-find');
    my $query;
    my $result_label = Gtk2::Label->new();
    my $counter      = 0;
    $button->signal_connect(
        clicked => sub {
            $query = $textbox->get_text;
            my @hits;
            my %hits;
            foreach my $key ( keys %movable )
            {
                if ( $movable{$key} =~ /(<b>$query)/i && $query !~ /^\s*$/ )
                {
                    push @hits, $movable{$key};
                    if ( $key > 0 )
                    {
                        $hits{"$movable{$key}"} =
                          $key . $d->get(' days after Pascha');
                    }
                    elsif ( $key < 0 )
                    {
                        my $key2 = $key;
                        $key2 =~ s/[-]//;
                        $hits{"$movable{$key}"} =
                          $key2 . $d->get(' days before Pascha');
                    }
                    else
                    {
                        $hits{"$movable{$key}"} = $d->get('Pascha');
                    }
                }
            }
            my $db_sel = $dbh->prepare(
                "SELECT * FROM Saints WHERE Daily_feasts LIKE '%$query%'");
            $db_sel->execute();
            while ( my @row = $db_sel->fetchrow_array )
            {
                my $row_length = @row;
                for ( my $feasts = 0 ; $feasts < $row_length ; $feasts += 4 )
                {
                    my $feast_name = $row[$feasts];
                    $feast_name = decode 'UTF8', $feast_name;
                    my $month = $row[ $feasts + 1 ];
                    if ( $month !~ /\d\d/ )
                    {
                        $month = '0' . $month;
                    }
                    my $day = $row[ $feasts + 2 ];
                    if ( $day !~ /\d\d/ )
                    {
                        $day = '0' . $day;
                    }
                    if (   $feast_name =~ /\n?(.*<b>$query.*)\n?/i
                        && $query !~ /^\s*$/ )
                    {
                        my $feast_name = $1;
                        push @hits, $feast_name;
                        $hits{$feast_name} = "$month/$day";
                    }
                }
            }
            @hits = sort @hits;
            my @hits2;
            foreach my $result (@hits)
            {
                my $result2 = $result;
                $result2 =~ s/<b>($query)/<b><u>$1<\/u>/i;
                $result2 =~ s/<b>//g;
                $result2 =~ s/<\/b>//g;
                push @hits2, "➜ <b>$hits{$result}:</b> $result2\n";
            }
            @hits2 = sort @hits2;
            my $final_result   = q{};
            my $length_counter = 0;
            foreach my $result (@hits2)
            {
                if ( $result =~ /(➜ <b>.+[:]<\/b>)\s(.+)/ )
                {
                    my $first_part  = $1;
                    my $second_part = $2;
                    if ( $first_part =~ /(\d\d)\/(\d\d)/ )
                    {
                        $first_part = $` . $2 . q{/} . $1 . $';
                    }
                    $final_result .= $first_part . q{ } . $second_part . "\n";
                    $length_counter++;
                }
            }
            chomp $final_result;
            if ( $final_result eq q{} )
            {
                $final_result = $d->get('No feast could be found.');
            }
            else
            {
                if ( $length_counter > 45 )
                {
                    $final_result =
                      '<span size="xx-small">' . $final_result . '</span>';
                }
                elsif ( $length_counter > 30 )
                {
                    $final_result =
                      '<span size="x-small">' . $final_result . '</span>';
                }
                else
                {
                    $final_result =
                      '<span size="small">' . $final_result . '</span>';
                }

            }
            if ( $counter == 0 )
            {
                $result_label->set_markup($final_result);
                $result_label->set_line_wrap('TRUE');
                $vbox->add($result_label);
                $counter = 1;
            }
            else
            {
                $vbox->remove($result_label);
                $result_label->set_markup($final_result);
                $vbox->add($result_label);
            }
            $search_window->show_all;
            Gtk2->main;
            Gtk2->main_quit;
        }
    );
    my $hbox = Gtk2::HBox->new( '0', '5' );
    $hbox->add($textbox);
    $hbox->add($button);
    $vbox->add($hbox);
    my $separator = Gtk2::HSeparator->new;
    $vbox->add($separator);
    $search_window->add($vbox);
    $search_window->show_all;
    Gtk2->main;
    return 0;
}
