#!/usr/bin/perl

use strict;
use Template;
use CGI::Lite;
use FCGI;
use MIME::Lite;
use String::Similarity;
use Digest::MD5 qw(md5_hex);
use Digest::SHA qw(sha256_hex sha1_hex);
use Compress::Zlib;
use Time::HiRes qw(gettimeofday tv_interval);
use GD::Graph::lines3d;
use Net::DNS;
use XML::Simple;
use URI::Find::Schemeless;
use Date::Simple ('today');
use JSON;
                                
require LWP;
require "/www/mine.sk/wow/chat/modules/globals.pm";
require "/www/mine.sk/wow/chat/modules/sqldb.pm";
require "/www/mine.sk/wow/chat/modules/sessions.pm";
require "/www/mine.sk/wow/chat/modules/tt.pm";
require "/www/mine.sk/wow/chat/modules/system.pm";
require "/www/mine.sk/wow/chat/modules/pokec.pm";
require "/www/mine.sk/wow/chat/modules/captcha.pm";

use Geo::IP;

my $gi = Geo::IP->new(GEOIP_STANDARD);
my $ret_template = tt::init($globals::fs_dir.'/chat/templates');
my $tt = $ret_template->{template};
my $dbh = sqldb::init($globals'mysql->{database},$globals'mysql->{interface},$globals'mysql->{user}, $globals'mysql->{password});
my $cgi = CGI::Lite->new();
my $md5 = Digest::MD5->new();
$cgi->set_directory ($globals::datadir.'/tmp');
captcha::init($dbh);

my $request = FCGI::Request();

my $finder = URI::Find::Schemeless->new( sub {
	my $uri    = shift;
	my $string = shift;
	if (length($string) > 80) {$string =~ s/^(.{77}).*$/$1.../;}
        my $str = $uri->abs;
        $str =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
        return '<a target="_blank" href="redir.php?url='.$str.'">'.$string.'</a>';
});
                                

my $refreshs = { '1' => '10', '2' => '15', '3' => '20', };
my $lines = { '1' => '10', '2' => '15', '3' => '20', '4' => '25', '5' => '30', };
my $map_qualities = { '1' => '11', '2' => '12', '3' => '13', '4' => '14', '5' => '10', '6' => '9', '7' => '15', };
my $map_backgrounds = { '0' => { 'basic' => '000000', 'extra' => '000000', }, '2' => { 'basic' => '111111', 'extra' => '222222', }, };

my $chat_server_id;


$main::get_servers->execute();
my $servers = $main::get_servers->fetchall_arrayref({});
foreach my $server (@{$servers}) {
   $chat_server_id->{$server->{armory_server_id}} = $server->{server_id};
}
$main::get_servers->finish();

my $guilds;
#$main::get_servers->execute();
#foreach my $server (@{$main::get_servers->fetchall_arrayref({})}) {
#   $main::get_guilds->execute();
#   foreach (@{$main::get_guilds->fetchall_arrayref({})}) {
#      $guilds->{$chat_server_id->{$_->{server_id}}}->{$_->{id}} = $_;
#   }
#   $main::get_guilds->finish();
#}

my $cities;
$main::get_cities->execute();
my $cities_array = $main::get_cities->fetchall_arrayref({});
foreach (@{$cities_array}) {
   $cities->{$_->{city_id}} = $_;
}

my $jobs;
$main::get_jobs->execute();
my $jobs_array = $main::get_jobs->fetchall_arrayref({});
foreach (@{$jobs_array}) {
   $jobs->{$_->{job_id}} = $_;
}


$main::get_maps->execute();
my $maps = $main::get_maps->fetchall_hashref('map_id');

$main::get_zones->execute();
my $zones = $main::get_zones->fetchall_hashref('zone_id');

#$main::get_maps_zones->execute();
#my $maps_zones = $main::get_maps_zones->fetchall_hashref('col_0');
my $maps_zones = {};


$main::get_skills->execute();
my $skills_array = $main::get_skills->fetchall_arrayref({});

$main::get_ranks->execute();
my $ranks = $main::get_ranks->fetchall_hashref('rank_id');


my $itemclass;
$main::get_itemclasses->execute();
my $itemclasses = $main::get_itemclasses->fetchall_arrayref({});
foreach (@{$itemclasses}) {
   $itemclass->{$_->{itemclass_id}} = $_->{itemclass_name};
}

my $itemsubclass;
$main::get_itemsubclasses->execute();
my $itemsubclasses = $main::get_itemsubclasses->fetchall_arrayref({});
foreach (@{$itemsubclasses}) {
   $itemsubclass->{$_->{itemclass_id}}->{$_->{itemsubclass_id}} = $_->{itemsubclass_name};
}


$main::get_substitutions->execute();
my $substitutions = $main::get_substitutions->fetchall_hashref('id');
$main::get_substitutions->finish();

$main::get_substitutions->execute();
my $substitutions_id = $main::get_substitutions->fetchall_hashref('id');
$main::get_substitutions->finish();

$main::get_channels->execute();
my $channels = $main::get_channels->fetchall_arrayref({});
my $channels_hashref;
foreach (@{$channels}) {
   $channels_hashref->{$_->{channel_id}} = { channel_name => $_->{channel_name}, };
}
$main::get_channels->finish();

my $ret_blizzard_servers = system::get_blizzard_servers();


my $map_prefixes = {
	'1_1' => '+421901', 
	'1_2' => '+421902',
	'1_3' => '+421903',
	'1_4' => '+421904',
	'1_5' => '+421905',
	'1_6' => '+421907',
	'1_7' => '+421908',
	'1_8' => '+421910',
	'1_9' => '+421911',
	'1_17' => '+421914',
	'1_10' => '+421915',
	'1_18' => '+421917', # last
	'1_11' => '+421918',
	'1_12' => '+421919',
	'1_13' => '+421940',
	'1_14' => '+421944',
	'1_15' => '+421948',
	'1_16' => '+421949',

	'2_1' => '+420601',
	'2_2' => '+420602',
	'2_3' => '+420603',
	'2_4' => '+420604',
	'2_5' => '+420605',
	'2_6' => '+420606',
	'2_7' => '+420607',
	'2_8' => '+420608',
	'2_9' => '+420720',
	'2_10' => '+420721',
	'2_11' => '+420722',
	'2_12' => '+420723',
	'2_13' => '+420724',
	'2_14' => '+420725',
	'2_15' => '+420726',
	'2_16' => '+420727',
	'2_17' => '+420728',
	'2_18' => '+420729',
	'2_19' => '+420730',
	'2_20' => '+420731',
	'2_21' => '+420732',
	'2_22' => '+420733',
	'2_23' => '+420734',
	'2_24' => '+420735',
	'2_25' => '+420736',
	'2_26' => '+420737',
	'2_27' => '+420738',
	'2_28' => '+420739',
	'2_33' => '+420773', # last cechy
	'2_29' => '+420774',
	'2_30' => '+420775',
	'2_31' => '+420776',
	'2_32' => '+420777',

	'3_1' => '+4176',
	'3_2' => '+4177',
	'3_3' => '+4178',
	'3_4' => '+4179',	# last svajciarsko

	'4_1' => '+35386',	# last irsko

	'5_1' => '+4475',
	'5_2' => '+4476',
	'5_3' => '+4477',
	'5_4' => '+4478',
	'5_5' => '+4479',	# last britania

	'6_1' => '+316',	# last holandsko
	
};



my $loop_instance = 1000;
while($request->Accept() >= 0) {


#   my $utime = time();
   my $t0 = [gettimeofday];

   $dbh = &sqldb::check($dbh);
   if ($dbh eq 0) {
      warn "sql connection problem";
      print "Location: /chat/static.html\n\n";
      next;

   } else {

      my ($html,$page,$template,$mime);
      my $q = $cgi->parse_new_form_data();
      my $c = $cgi->parse_cookies();

      if (!defined($q->{lang_id}) || $q->{lang_id} !~ /^\d+$/) {$q->{lang_id} = 1;}
      if (defined($q->{'s'})) {
         $q->{'s'} =~ s/\D//gs;
      }

      my $template = $tt->{$q->{lang_id}};
      my $ccode = $gi->country_code_by_addr($ENV{REMOTE_ADDR});


      my $usegzip;
      foreach my $enc ( split( /\s*,\s*/, $ENV{HTTP_ACCEPT_ENCODING} )) {
         $enc =~ s/;.*$//s;
         $usegzip = $enc if ( $enc =~ /^(x-)?gzip$/ );
      }

      my $is_ssl = 0;
      if ($ENV{SERVER_PORT} == 443) {
         $is_ssl = 1;
      }

      my $hua = 0;
      if ($ENV{HTTP_USER_AGENT} =~ /MSIE/i) {
         $hua = 1;
      } elsif ($ENV{HTTP_USER_AGENT} =~ /Mozilla/i && $ENV{HTTP_USER_AGENT} !~ /MSIE/i) {
         $hua = 2;
      } elsif ($ENV{HTTP_USER_AGENT} =~ /Opera/i) {
         $hua = 3;
      }

      my $contenttype = 'text/html';

      my $vars = {
		query => $q, 
		logged => 0,
		guilds => $guilds,
		cities => $cities,
		cities_array => $cities_array,
		jobs => $jobs,
		jobs_array => $jobs_array,
		encoding => 'utf-8',
		gzip => $usegzip,
		is_ssl => $is_ssl,
		servers => $servers,
		doctype => 2,
		hua => $hua,
      };



      if (!defined($q->{sid})) {
#         $q->{sid} = sessions::create_session($dbh, { ip => $ENV{REMOTE_ADDR}, }, );
      } else {
         if (sessions::check_duplicate_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, ) ) {
         } else {
            sessions::prolong_session($dbh, {sid => $q->{sid}, }, );
            my $ret_session = sessions::get_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
            if ($ret_session->{ec} == 1) {
               if ($ret_session->{nick_id} != 0) {
                  $vars->{session_id} = $ret_session->{session_id};
                  $vars->{logged} = 1;
                  $vars->{nick_id} = $ret_session->{nick_id};
                  $vars->{nick} = $ret_session->{nick};
                  $vars->{level} = $ret_session->{level};
                  $vars->{global_level} = $ret_session->{global_level};
                  $vars->{chat_rank} = $ret_session->{chat_rank};
                  $vars->{chat_rank_points} = $ret_session->{chat_rank_points};
                  $vars->{punish_id} = $ret_session->{punish_id};
                  $vars->{channel_id} = $ret_session->{channel_id};
                  $vars->{incline} = $ret_session->{incline};
                  $vars->{incline_colors} = $ret_session->{incline_colors};
                  $vars->{incline_chat} = $ret_session->{incline_chat};
                  $vars->{show_graph} = $ret_session->{show_graph};
                  $vars->{show_chat} = $ret_session->{show_chat};
                  $vars->{show_info} = $ret_session->{show_info};
                  $vars->{show_guild} = $ret_session->{show_guild};
                  $vars->{guilds_type} = $ret_session->{guilds_type};
                  $vars->{privates_type} = $ret_session->{privates_type};
                  $vars->{privates_size} = $ret_session->{privates_size};
                  $vars->{refresh_id} = $ret_session->{refresh_id};
                  $vars->{graph_id} = $ret_session->{graph_id};
                  $vars->{lines_id} = $ret_session->{lines_id};
                  $vars->{chat_font} = $ret_session->{chat_font};
                  $vars->{ding_change} = $ret_session->{ding_change};
                  $vars->{segregate} = $ret_session->{segregate};
                  $vars->{active_nicks} = $ret_session->{active_nicks};
                  $vars->{theme_id} = $ret_session->{theme_id};
                  $vars->{import_messages} => $ret_session->{import_messages};
                  $vars->{frame_size} => $ret_session->{frame_size};
                  $vars->{auction_type} => $ret_session->{auction_type};
                  $vars->{show_joins} => $ret_session->{show_joins};
                  $vars->{import_ingame_chat} = $ret_session->{import_ingame_chat};

                  $vars->{won_quizzes} = $ret_session->{won_quizzes};
                  $vars->{quizz_points} = $ret_session->{quizz_points};
                  $vars->{doafk} = $ret_session->{doafk};
                  $vars->{wowchat_email} = $ret_session->{wowchat_email};
                  $vars->{last_guild_message_id} = $ret_session->{last_guild_message_id};
                  $vars->{pokec_i9} = $ret_session->{pokec_i9};
               } else {
                  $vars->{logged} = 0;
                  $vars->{chat_font} = 1;
                  $vars->{incline_colors} = 0;
                  $vars->{incline_chat} = 0;
                  $vars->{theme_id} = 0;
                  $vars->{global_level} = 0;
                  $vars->{level} = 0;
               }
            }
         }
      }




      my $hf = 0;
      my $location = '';
      my $set_cookie = '';

      if ($vars->{logged} == 0) {
         if (defined($q->{'s'})) {
            $vars->{channel_id} = $q->{'s'};
         } else {
            $vars->{channel_id} = 1;
         }
      } else {
         if (!defined($q->{'s'}) || $q->{'s'} !~ /^\d+$/) {
            $q->{'s'} = $vars->{channel_id};
         }
      }


      if (!defined($vars->{theme_id}) || $vars->{theme_id} eq '') {$vars->{theme_id} = 0;}


      my $browser_hash_id;

      $main::get_browser_hash_id->execute(md5_hex($ENV{HTTP_USER_AGENT}));
      if ($main::get_browser_hash_id->rows() == 0) {
         $main::add_browser_hash->execute(md5_hex($ENV{HTTP_USER_AGENT}),$ENV{HTTP_USER_AGENT});
         $browser_hash_id = $main::add_browser_hash->{mysql_insertid};
      } else {
         $browser_hash_id = $main::get_browser_hash_id->fetchrow();
      }


      $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{extra};


      if ($q->{page} eq 'redirect') {
         $hf = 0;
         $vars->{title} = 20;

         if ($q->{what} eq 'save_settings') {
            if (!defined($q->{show_graph}) || $q->{show_graph} ne '1') {$q->{show_graph} = 0;}
            if (!defined($q->{show_chat}) || $q->{show_chat} ne '1') {$q->{show_chat} = 0;}
            if (!defined($q->{show_info}) || $q->{show_info} ne '1') {$q->{show_info} = 0;}
            if (!defined($q->{ding_change}) || $q->{ding_change} ne '1') {$q->{ding_change} = 0;}
            if (!defined($q->{segregate}) || $q->{segregate} ne '1') {$q->{segregate} = 0;}
            if (!defined($q->{incline_colors}) || $q->{incline_colors} ne '1') {$q->{incline_colors} = 0;}
            if (!defined($q->{incline_chat}) || $q->{incline_chat} ne '1') {$q->{incline_chat} = 0;}
            if (!defined($q->{mark_messages}) || $q->{mark_messages} ne '1') {$q->{mark_messages} = 0;}
            if (!defined($q->{show_guild}) || $q->{show_guild} ne '1') {$q->{mark_messages} = 0;}

            if (!defined($q->{hold_me_frak}) || $q->{hold_me_frak} ne '1') {$q->{hold_me_frak} = 0;}
            if (!defined($q->{hide_blabla}) || $q->{hide_blabla} ne '1') {$q->{hide_blabla} = 0;}
            if (!defined($q->{hold_to_nick}) || $q->{hold_to_nick} ne '1') {$q->{hold_to_nick} = 0;}
            if (!defined($q->{reverse_chat}) || $q->{reverse_chat} ne '1') {$q->{reverse_chat} = 0;}
            if (!defined($q->{fade_in}) || $q->{fade_in} ne '1') {$q->{fade_in} = 0;}

            if (!defined($q->{autocomplete_nicks}) || $q->{autocomplete_nicks} ne '1') {$q->{autocomplete_nicks} = 0;}
            if (!defined($q->{show_macros}) || $q->{show_macros} ne '1') {$q->{show_macros} = 0;}
            if (!defined($q->{import_messages}) || $q->{import_messages} ne '1') {$q->{import_messages} = 0;}
            if (!defined($q->{show_joins}) || $q->{show_joins} ne '1') {$q->{show_joins} = 0;}
            

            $main::get_settings->execute($vars->{nick_id});
            my $sett = $main::get_settings->fetchrow_hashref();

            if ($sett->{incline} != $q->{incline}) {
               $main::shedule_refraction->execute($vars->{nick_id},$sett->{incline},$q->{incline});
            }

            $main::set_settings->execute($q->{refresh_time},$q->{show_graph},$q->{show_chat},$q->{show_info},$q->{show_guild},$q->{guilds_type},$q->{privates_type},$q->{privates_size},$q->{nicks_panel},$q->{hold_me_frak},$q->{hide_blabla},$q->{hold_to_nick},$q->{reverse_chat},$q->{fade_in},$q->{graph_type1}.$q->{graph_type2},$q->{lines},$q->{chat_font},$q->{ding_change},$q->{segregate},$q->{incline_colors},$q->{incline_chat},$q->{channel_id},$q->{server_id},$q->{theme_id},$q->{active_nicks},$q->{mark_messages},$q->{mark_how},$q->{autocomplete_nicks},$q->{show_macros},$q->{background},$q->{import_messages},$q->{frame_size},$q->{auction_type},$q->{show_joins},$q->{import_ingame_chat},$vars->{nick_id});
#            $set_cookie = 'Set-Cookie: s_'.$vars->{nick_id}.'='.$q->{lrefresh_time}.'|'.$q->{lshow_graph}.'|'.$q->{lshow_chat}.'|'.$q->{lshow_info}.'|'.$q->{llines}.'|'.$q->{lgraph_type1}.$q->{lgraph_type2}.'|'.$q->{ltheme_id}.'|'.$q->{lchat_font}.'|'.$q->{lactive_nicks}.'|'.$q->{lding_change}.'|'.$q->{lsegregate}.'|'.$q->{lincline_colors}.'|'.$q->{lmark_messages}.'|'.$q->{lmark_how}.'|'.$q->{lshow_guild}.'|'.$q->{lprivates_type}.'|'.$q->{lincline_colors}.'|'.$q->{privates_size}.'; domain=wow.mine.sk; path=/chat; expires=Fri, 01-Jan-2015 00:00:00 GMT'."\n";

            system::add_action( { action => 37, nick_id => $vars->{nick_id}, }, );


            $location = $globals::misc_script.'?page=settings_settings&sid='.$q->{sid};

         } elsif ($q->{what} eq 'del_refraction') {
            $main::del_user_sheduled_refraction->execute($q->{id},$vars->{nick_id});
            $location = $globals::misc_script.'?page=settings_settings&sid='.$q->{sid};

         } elsif ($q->{what} eq 'save_ticket') {
            system::add_ticket( { requestor => $vars->{nick_id}, request_text => $q->{request_text}, section => $q->{section}, }, );
            $location = $globals::misc_script.'?page=tickets&sid='.$q->{sid};

         } elsif ($q->{what} eq 'add_comment') {
            system::add_photoalbum_image_comment( { nick_id=> $vars->{nick_id}, image_id => $q->{image_id}, message => $q->{comment}, ip => $ENV{REMOTE_ADDR}, }, );
#            $location = $globals::misc_script.'?page=show_image&album_id='.$q->{album_id}.'&from='.$q->{from}.'&image_index='.$q->{image_index}.'&nick_id='.$q->{nick_id}.'&sid='.$q->{sid};
            $location = $globals::misc_script.'?album_id='.$q->{album_id}.'&from='.$q->{from}.'&image_id='.$q->{image_id}.'&image_index='.$q->{image_index}.'&nick_id='.$q->{nick_id}.'&page=show_image&sid='.$q->{sid};

         } elsif ($q->{what} eq 'save_gsm') {

            if (defined($q->{prefix}) && $q->{prefix} ne '' && defined($q->{number}) && $q->{number} ne '') {
               $md5->add($map_prefixes->{$q->{prefix}}.$q->{number});
               my $hash = $md5->hexdigest;

               $main::get_confirmed_gsm_number->execute($hash);
               if ($main::get_confirmed_gsm_number->rows() == 0) {
                  $main::unset_requested_gsm_number->execute($map_prefixes->{$q->{prefix}}.$q->{number});
                  $main::set_requested_gsm_number->execute($map_prefixes->{$q->{prefix}}.$q->{number},$vars->{nick_id});
                  $location = $globals::misc_script.'?page=gsm_activate&save=1&sid='.$q->{sid};
               } else {
                  $location = $globals::misc_script.'?page=gsm_activate&error=1&sid='.$q->{sid};
               }
            } else {
               if (!$q->{prefix} || $q->{prefix} eq '') {
                  $location = $globals::misc_script.'?page=gsm_activate&error=2&sid='.$q->{sid};
               } elsif (!$q->{number} || $q->{number} eq '') {
                  $location = $globals::misc_script.'?page=gsm_activate&error=3&sid='.$q->{sid};
               }
            }
         }

      } elsif ($q->{page} eq 'search_frame') {
         $page = 'search_frame';
         $hf = 0;
         $location = '';
         $vars->{title} = 21;


      } elsif ($q->{page} eq 'game_account_invitation') {
#         $page = 'game_account';
         $hf = 1;
         $location = '';
         $vars->{title} = 22;

         $page = 'game_account_invitation';

         $main::admin_get_server->execute($q->{'s'});
         my $server_info = $main::admin_get_server->fetchrow_hashref();
         $main::admin_get_server->finish();
         $vars->{server_info} = $server_info;



         if ($q->{v} == 2) {
            $vars->{background} = 'http://www.anthoria.net/themes/default/bgbg.jpg';
         } else {
            $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';
         }

         if (!defined($q->{'s'}) || $q->{'s'} !~ /^\d+$/) {
            $q->{'s'} = 18;
         }

         if (defined($q->{action}) && $q->{action} eq 'check') {

            my @errors;

            my $enc_password;
            if (defined($q->{response}) && $q->{response} =~ /^.{64}$/) {
               my $ret_check_challenge = system::check_challenge( { login => lc($q->{login_invitation}), session_hex => $q->{sid}, response => $q->{response}, } );
               if ($ret_check_challenge->{rv} == 1) {
                  $enc_password = $ret_check_challenge->{enc_password};
               }
            }


            $main::get_nick_by_enc->execute($q->{login_invitation},$enc_password);
            if ($main::get_nick_by_enc->rows() != 1) {push @errors,'0';}
            my $nick_data = $main::get_nick_by_enc->fetchrow_hashref();
            if ($nick_data->{state} == 0 && scalar(@errors) == 0) {push @errors,'1';}
            $main::get_nick_by_enc->finish();
            my $nick_id = $nick_data->{id};

            if (scalar(@errors) == 0) {

                        $main::create_invitation->execute();
                        my $invitation_id = $main::create_invitation->{mysql_insertid};


                        my $md5 = Digest::MD5->new;
                        $md5->add(lc($q->{'login_invitation'}));
                        $md5->add($invitation_id);
                        $md5->add($nick_id);
                        $md5->add('invite');
                        $md5->add('mega coder SoCo');
                        my $hash = $md5->hexdigest;

                        $main::update_invitation->execute($hash,undef,$q->{'s'},undef,$nick_id,lc($q->{'login_invitation'}),$q->{'email_invitation'},$invitation_id);


                        my $msg = MIME::Lite->new(
				From			=> 'WebAccountInvitation',
				To			=> $q->{email_invitation},
				Subject			=> 'Pozvanka na '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade pozvania uzivatela serveru.'."\n\n".'ID Vasej pozvanky je: '.uc($hash)."\n\n".'Zaregistrovat sa mozete kliknutim na: '.$globals::misc_path.'?page=game_account&invitation='.uc($hash).'&s='.$q->{'s'}.' alebo neskor '.$globals::misc_path.'?page=game_account&s='.$q->{'s'}.' a vpisanim ID pozvanky do prislusneho policka.'."\n".'Ak neplanujete hrat na serveri '.$server_info->{server_name}.', povazujte tento E-mail za bezpredmetny'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                        );
                        $msg->send;

                   $vars->{ok} = 1;

            } else {
               $vars->{errors} = \@errors;
            }
         }


         my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
         $vars->{challenge} = $ret_create_challenge->{challenge};

      } elsif ($q->{page} eq 'game_account') {
         $hf = 1;
         $location = '';
         $page='game_account';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';


=cut

      } elsif ($q->{page} eq 'game_account') {
#         $page = 'game_account';
         $hf = 1;
         $location = '';
         $vars->{title} = 22;

         if ($q->{v} == 2) {
            $vars->{background} = 'http://www.anthoria.net/themes/default/bgbg.jpg';
            $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';
            $page = 'game_account';
         } else {
            $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';
            $page = 'game_account';
         }
         
         if (!defined($q->{'s'}) || $q->{'s'} !~ /^\d+$/) {
            $q->{'s'} = 18;
         }


         $main::get_today_created_game_accounts->execute($q->{'s'});
         my $status = $main::get_today_created_game_accounts->fetchrow_hashref();
         $vars->{status} = $status;

         $main::admin_get_server->execute($q->{'s'});
         my $server_info = $main::admin_get_server->fetchrow_hashref();
         $main::admin_get_server->finish();
         $vars->{server_info} = $server_info;

         $vars->{post_title} = $server_info->{server_name};

         if (defined($q->{action}) && $q->{action} eq 'check') {
            my @errors;
            if ($q->{login} !~ /^[a-zA-Z0-9_\*]+$/) {push @errors,'0';}
            if (length($q->{login}) < 2) {push @errors,'1';}
            if (length($q->{login}) > 16) {push @errors,'2';}
            if ($q->{login} !~ /^[a-zA-Z]/) {push @errors,'3';}
            if ($q->{login} !~ /[a-zA-Z0-9]$/) {push @errors,'4';}
            if ($q->{email} !~ m/^['_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name))$/i) {push @errors,'5';}
            if (length($q->{password}) < 4) {push @errors,'6';}
            if (similarity (lc $q->{login}, lc $q->{password}) > 0.75) {push @errors,'7';}
            if (lc $ccode ne 'sk' && lc $ccode ne 'cz') {
               my $md5 = Digest::MD5->new;
               $md5->add($q->{salt});
               $md5->add('mega coder SoCo');
               my $ok_hash = $md5->hexdigest;
               if ($ok_hash ne $q->{ok_hash}) {
                  push @errors,'8';
               }
            }
            $main::is_game_account->execute($q->{'s'},$q->{login});
            if ($main::is_game_account->rows() != 0) {push @errors,'9';}
            $main::is_game_account->finish();
            if ($q->{agree} ne '1') {push @errors,'10';}
            if ($status->{rph} > 20) {push @errors,'11';}
            if ($server_info->{registrations} != 1) {push @errors,'12';}
            $main::is_game_email_used->execute($q->{email},$q->{'s'});
            if ($main::is_game_email_used->rows() != 0) {push @errors,'13';}
            if ($q->{question} eq '') {push @errors,'14';}
            if ($q->{answer} eq '') {push @errors,'15';}
            if ($q->{question} eq $q->{answer}) {push @errors,'19';}


            $main::get_invitation_by_hex->execute($q->{invitation});
            my $invitation_ok = $main::get_invitation_by_hex->rows();
            my $invitation = $main::get_invitation_by_hex->fetchrow_hashref();

#            my $md5 = Digest::MD5->new;
#            $md5->add(lc($invitation->{account_name}));
#            $md5->add($invitation->{id});
#            $md5->add($invitation->{account_id});
#            $md5->add('invite');
#            $md5->add('mega coder SoCo');
#            my $hash_test = $md5->hexdigest;

            


            if ($invitation->{used} != 0) {push @errors,'16';}
            if ($invitation_ok == 0) {push @errors,'17';}

            if (defined($invitation->{account_id}) && $invitation->{account_id} ne '') {
               $main::get_game_account_state_by_id->execute($invitation->{account_id},$invitation->{server_id});
               my $account_data = $main::get_game_account_state_by_id->fetchrow_hashref();
               if ($account_data->{invited} != 0) {push @errors,'18';}
            } elsif (defined($invitation->{nick_id}) && $invitation->{nick_id} ne '') {
               $main::check_chat_invitation_used->execute($invitation->{nick_id});
               if ($main::check_chat_invitation_used->rows() > 0) {push @errors,'18';}
            }


            if (scalar(@errors) == 0) {
               my $hash = md5_hex($q->{password});
               $main::create_game_account->execute($q->{'s'},$browser_hash_id,$ENV{REMOTE_ADDR},$q->{login},$hash,$q->{password},$q->{email},$q->{chat_nick},$q->{forum_nick},$q->{name},$q->{surname},$q->{address},$q->{phone},$q->{question},$q->{answer},$invitation->{id});
               my $record_id = $main::create_game_account->{mysql_insertid};
               $page = 'game_account_ok';

               my $md5 = Digest::MD5->new;
               $md5->add($q->{login});
               $md5->add($q->{email});
               $md5->add($record_id);
               $md5->add('mega coder SoCo');
               my $hash = $md5->hexdigest;


               $main::set_invitation_used->execute($invitation->{id});
               $main::set_account_invited->execute($invitation->{account_id});


               my $msg = MIME::Lite->new(
			From			=> 'WebAccountActivation',
			To			=> $q->{email},
			Subject			=> 'Overenie E-mailovej adresy (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> 'Tento mail Vam bol odoslany na zaklade odoslania registracneho formularu so ziadostou o vytvorenie herneho konta na serveri WoW '.$server_info->{server_name}.' (z IP adresy '.$ENV{REMOTE_ADDR}.'). Ak ste ho odosielali Vy, kliknite na nasledovnu URL adresu a tym potvrdite ze ste majitelom tejto E-mailovej adresy '.$globals::misc_path.'?page=confirm_email&hex='.$hash.'&id='.$record_id.'&s='.$q->{'s'}."\n".'V pripade, ze ste o ziadne konto neziadali, povazujte tento E-mail za bezpredmetny.'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
               );

               $msg->send;
            } else {
               $vars->{errors} = \@errors;
            }
         }


         my $matrix;

         if (lc $ccode ne 'sk' && lc $ccode ne 'cz') {
            my $arr = [qw(q w e r t y u i o p a s d f g h j k l z x c v b n m 0 1 2 3 4 5 6 7 8 9)];
            my $ok_x = 1+int(rand(10));
            my $ok_y = 1+int(rand(10));
            my $ok_hash;
            for (my $y=1;$y<=10;++$y) {
               for (my $x=1;$x<=10;++$x) {
                  my $salt;
                  for (my $i=0; $i<5; ++$i) {$salt .= $arr->[int(rand(scalar(@{$arr})))]}
                  $matrix->{$x}->{$y} = $salt;
                  if ($x == $ok_x && $y == $ok_y) {
                     my $md5 = Digest::MD5->new;
                     $md5->add($salt);
                     $md5->add('mega coder SoCo');
                     $ok_hash = $md5->hexdigest;
                  }

               }
            }
            $vars->{matrix} = $matrix;
            $vars->{ok_hash} = $ok_hash;
            $vars->{ok_x} = $ok_x;
            $vars->{ok_y} = $ok_y;
         }




#      } elsif ($q->{page} eq 'register_game') {
#         $page = 'register_game';
#         $hf = 1;
#         $vars->{title} = 23;
#         $location = '';
#
#         if (defined($q->{action}) && $q->{action} eq 'check') {
#            my @errors;
#            if (length($q->{login}) < 2) {push @errors,'0';}
#            if (length($q->{login}) > 12) {push @errors,'1';}
#            if (length($q->{password}) < 4) {push @errors,'2';}
#            if ($q->{login} !~ /^[a-zA-Z0-9_\*]+$/) {push @errors,'3';}
#            if ($q->{agree} ne '1') {push @errors,'4';}
#            if ($q->{login} !~ /^[a-zA-Z]/) {push @errors,'5';}
#            if ($q->{login} !~ /[a-zA-Z0-9]$/) {push @errors,'6';}
#            if (similarity (lc $q->{login}, lc $q->{password}) > 0.75) {push @errors,'7';}
#            if (lc $ccode ne 'sk' && lc $ccode ne 'cz') {push @errors,'8';}
#
#            if (scalar(@errors) == 0) {
#               my $ret_wget = system::wget('http://wowserver.antik.sk:3333/vytvormikonto.html?action=create&user='.$q->{login}.'&pass='.$q->{password}.'&image.x=38&image.y=11');
#               if ($ret_wget->{state} == 0) {
#                  push @errors,'9';
#               } else {
#                  if ($ret_wget->{content} =~ /<p align="center" class="small Style6 Style8">Herny ucet \[.+?\] uspesne vytvoreny.<\/p>/) {
#                  if ($ret_wget->{content} =~ /<tr><td>Account created for user: \[/) {
#                  } else {
#                     push @errors,'10';
#                  }
#               }
#            }
#
#            if (scalar(@errors) == 0) {
#               $page = 'register_game_ok';
#            } else {
#               $vars->{errors} = \@errors;
#            }
#         }

=cut


      } elsif ($q->{page} eq 'terms') {
         $page = 'terms';
         $hf = 1;
         $vars->{title} = 89;

         $location = '';


      } elsif ($q->{page} eq 'captcha') {

         my $ret_generate_image = captcha::generate_image($dbh, { id => $q->{id}, }, );

         $location = '';
         $mime = $ret_generate_image->{mime_type};
         $html = $ret_generate_image->{image_data};

      } elsif ($q->{page} eq 'register') {
         $page = 'register';
         $hf = 1;
         $vars->{title} = 24;

         $location = '';

         my $ret_create_random = captcha::create_random($dbh);
         $vars->{captcha_id} = $ret_create_random->{id};

         if (defined($q->{action}) && $q->{action} eq 'check') {
            my @errors;
            if (length($q->{nick}) < 2) {push @errors,'0';}
            if (length($q->{nick}) > 12) {push @errors,'1';}
            if (length($q->{password}) < 4) {push @errors,'2';}
            if ($q->{nick} !~ /^[a-zA-Z0-9\.\-_\*]+$/) {push @errors,'3';}
            $main::get_nick_id->execute($q->{nick});
            if ($main::get_nick_id->rows() != 0) {push @errors,'4';}
            $main::get_nick_id->finish();
            if ($q->{agree} ne '1') {push @errors,'5';}
            if ($q->{nick} !~ /^[a-zA-Z]/) {push @errors,'6';}
            if ($q->{nick} !~ /[a-zA-Z0-9]$/) {push @errors,'7';}
            if ($q->{nick} =~ /[0-9\.\-_\*]{2}/) {push @errors,'11';}

            if (similarity (lc $q->{nick}, lc $q->{password}) > 0.75) {push @errors,'8';}

            my $ret_check_code = captcha::check_code($dbh, { id => $q->{captcha_id}, string => $q->{captcha}, }, );
            if ($ret_check_code->{rv} == 0) {push @errors,'9';}

#            $main::get_passwords_count->execute($q->{password});
#            my $cnt = $main::get_passwords_count->fetchrow();
#            if ($cnt > 9) {push @errors,'10';}
#            $main::get_passwords_count->finish();

            if (defined($q->{email}) && $q->{email} ne '') {
               if ($q->{email} =~ /^.+\@(.+)$/) {
                  my $res = Net::DNS::Resolver->new;
                  my @mx = mx($res, $1);
                  if (!@mx) {push @errors,'12';}
               } else {
                  push @errors,'13';
               }

            }

            






            if (scalar(@errors) == 0) {
               $page = 'register_ok';

               if (!defined($q->{'s'}) || $q->{'s'} eq '' || $q->{'s'} == 0) {
                  $q->{'s'} = 1;
               }

               my $dig = sha256_hex(uc($q->{nick}).':'.uc($q->{password}));

               my $num = 0;
               foreach my $x (split('',$q->{nick})) {
                  $num += ord(lc($x));
               }

               $num = 1+($num % 60);

               my $pre;
               my $post;
               my $tmp = 0;
               foreach my $char (split('',$dig)) {
                  if ($tmp < $num) {
                     $pre .= $char;
                  } else {
                     $post .= $char;
                  }
                  ++$tmp;
               }

               $pre = reverse($pre);
               $post = reverse($post);
               chop($post);

               my $out = $post.'0'.$pre;


               $main::add_nick->execute(ucfirst(lc($q->{nick})),'',$out,100,$ENV{REMOTE_ADDR},lc($q->{email}),$q->{incline},100,$browser_hash_id);
               my $nick_id = $main::add_nick->{mysql_insertid};

               system::add_action( { action => 34, nick_id => $nick_id, value => 1, }, );
                           
            } else {
               $vars->{errors} = \@errors;
            }

         }



      } elsif ($q->{page} eq 'new_captcha') {
         $page = 'new_captcha';
         $hf = 0;

         my $ret_create_random = captcha::create_random($dbh);
         $vars->{captcha_id} = $ret_create_random->{id};


      } elsif ($q->{page} eq 'unregister') {
         $page = 'unregister';
         $hf = 1;
         $vars->{title} = 25;
         $location = '';

         $main::get_nick_by_nick_id->execute($q->{id});
         my $data = $main::get_nick_by_nick_id->fetchrow_hashref();
         $main::get_nick_by_nick_id->finish();

         $vars->{status} = 0;
         $vars->{data} = $data;




         if (defined($q->{action}) && $q->{action} eq 'delete') {

            my $is_punished = 0;
            foreach (keys(%{$channels_hashref})) {
               my $ret_punish = system::get_punished( { nick_id => $q->{id}, channel_id => $_, }, );
#warn "system::get_punished( { nick_id => $q->{id}, channel_id => $_, }, );";
#warn "  ret_punish->{is_punished} = $ret_punish->{is_punished}";
#warn "  ret_punish->{ban} = $ret_punish->{ban}";
               if ($ret_punish->{is_punished} == 1) {
                  $is_punished = 1;
                  last;
               }
            }

            if ($is_punished == 0) {
               my $ctx = Digest::MD5->new;
               $ctx->add($q->{id});
               $ctx->add($data->{nick});
               $ctx->add($data->{password});
               $ctx->add($data->{email});
               $ctx->add('super');
               $ctx->add($q->{'s'});
               my $hash = $ctx->hexdigest;

               if ($q->{h} eq $hash) {
                  my $ret_delete_user = system::delete_user( { nick_id => $q->{id}, on_behalf => 1, } );
                  if ($ret_delete_user->{rv} == 1) {

                     my $msg = MIME::Lite->new(
				From			=> 'WebChat',
				To			=> $_->{email},
				Subject			=> 'Oznam o zmazani uctu na wow.mine.sk (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
				'Auto-Submitted:'	=> 'auto-generated',
				Data			=> 'Na Vasu ziadost bolo Vase chat konto zmazane a tento krok je nevratny. Ak budete mat v buducnosti zaujem o opatovne posobenie na chate wow.mine.sk, radi Vas privitame.'."\n".'Opatovne sa mozete zaregistrovat tu: http://wow.mine.sk/chat/misc.fcgi?page=register'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'mine.sk Crew',
                     );
                     $msg->send;

                     $vars->{status} = 1;
                  } else {
                     $vars->{status} = 3;
                  }
               } else {
                  $vars->{status} = 2;
               }
            } else {
               $vars->{status} = 4;
            }
         }

      } elsif ($q->{page} eq 'pokec_private') {
         $page = 'pokec_private';
         $hf = 1;
         $vars->{title} = 26;

         $location = '';



         if (!defined($q->{order}) || ($q->{order} ne 'num' && $q->{order} ne 'lst' && $q->{order} ne 'azet_nick')) {$q->{order} = 'lst';}
         if (!defined($q->{asc}) || $q->{asc} ne '1') {$q->{asc} = 0;}
         if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
         if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 50;} else {$q->{count} = int($q->{count});}

         if ($q->{asc} == 0) {
            $main::get_pokec_privates_desc->execute($vars->{nick_id},$q->{order},$q->{from},$q->{count});
            my $users = $main::get_pokec_privates_desc->fetchall_arrayref({});
            $vars->{users} = $users;
            $main::get_pokec_privates_desc->finish();
         } else {
            $main::get_pokec_privates_asc->execute($vars->{nick_id},$q->{order},$q->{from},$q->{count});
            my $users = $main::get_pokec_privates_asc->fetchall_arrayref({});
            $vars->{users} = $users;
            $main::get_pokec_privates_asc->finish();
         }

         $main::get_pokec_privates_total->execute($vars->{nick_id});
         my $total = $main::get_pokec_privates_total->rows();

         $vars->{total} = $total;
         $vars->{pages} = $total/$q->{count};


         my $set_reverse;
         foreach my $column ('num','lst','azet_nick') {
            if ($q->{order} eq $column) {
               if ($q->{asc} == 1) {
                  $set_reverse->{$column} = 0;
               } else {
                  $set_reverse->{$column} = 1;
               }
            } else {
               $set_reverse->{$column} = $q->{asc};
            }
         }

         $vars->{setrev} = $set_reverse;




      } elsif ($q->{page} eq 'private') {
         $page = 'private';
         $hf = 1;
         $vars->{title} = 27;
         $location = '';

         my $deleted_nicks_hash;
         my $ret_deleted_nicks = system::get_deleted_nicks();
         foreach (@{$ret_deleted_nicks->{deleted_nicks}}) {
             $deleted_nicks_hash->{$_->{nick_id}} = $_;
         }
         $vars->{deleted_nicks_hash} = $deleted_nicks_hash;


         if (defined($q->{action}) && $q->{action} eq 'add_ignore') {
            $main::get_ignored->execute($vars->{nick_id},$q->{id});
            if ($main::get_ignored->rows() == 0) {
               $main::add_ignore->execute($vars->{nick_id},$q->{id});
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'del_ignore') {
            $main::del_ignore->execute($q->{id},$vars->{nick_id});

         } elsif (defined($q->{action}) && $q->{action} eq 'delete') {
            $main::get_privates_user_delete->execute($vars->{nick_id},$q->{id},$q->{id},$vars->{nick_id});
            my $for_delete = $main::get_privates_user_delete->fetchall_arrayref({});
            $main::get_privates_user_delete->finish();

            foreach my $msg (@{$for_delete}) {
               if ($msg->{from_id} == $vars->{nick_id} && $msg->{deleted_from} == 0 && $msg->{deleted_to} == 0) {
                  $main::set_deleted_from_private->execute($msg->{id});
               } elsif ($msg->{nick_id} == $vars->{nick_id} && $msg->{deleted_from} == 0 && $msg->{deleted_to} == 0) {
                  $main::set_deleted_to_private->execute($msg->{id});
               } elsif (($msg->{from_id} == $vars->{nick_id} && $msg->{deleted_to} == 1) || ($msg->{nick_id} == $vars->{nick_id} && $msg->{deleted_from} == 1)) {
                  $main::delete_history_privates->execute($msg->{id});
               }
            }

         }


#         my $order;
#         if (defined($q->{order}) && $q->{order} eq 'num') {
#            $order = 'num';
#         } elsif (defined($q->{order}) && $q->{order} eq 'lst') {
#            $order = 'lst';
#         } elsif (defined($q->{order}) && $q->{order} eq 'nick') {
#            $order = 'nick';
#         } else {
#            $order = 'lst';
#         }
#
#         if (!defined($q->{asc}) || $q->{asc} ne '1') {$q->{asc} = 0;}
#         if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
         if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 50;} else {$q->{count} = int($q->{count});}
#
#         if ($q->{asc} == 0) {
#            $main::get_privates_desc->execute($vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$order,$q->{from},$q->{count});
#            my $users = $main::get_privates_desc->fetchall_arrayref({});
#            $vars->{users} = $users;
#            $main::get_privates_desc->finish();
#         } else {
#            $main::get_privates_asc->execute($vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$order,$q->{from},$q->{count});
#            my $users = $main::get_privates_asc->fetchall_arrayref({});
#            $vars->{users} = $users;
#            $main::get_privates_asc->finish();
#         }
#
#         foreach (@{$vars->{users}}) {
#            warn "$_->{dt} : $_->{nick}";
#         }

#         $main::get_privates_total->execute($vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id});
#         my $total = $main::get_privates_total->rows();

         my $ret_privates = system::get_privates( $dbh, { nick_id => $vars->{nick_id}, order => $q->{order}, from => $q->{from}, count => $q->{count}, asc => $q->{asc}, filter => $q->{filter}, } );

         $vars->{users} = $ret_privates->{users};
         $vars->{total} = $ret_privates->{count};
         $vars->{pages} = $ret_privates->{count}/$q->{count};


         my $set_reverse;
         foreach my $column ('num','lst','nick') {
            if ($q->{order} eq $column) {
               if ($q->{asc} == 1) {
                  $set_reverse->{$column} = 0;
               } else {
                  $set_reverse->{$column} = 1;
               }
            } else {
               $set_reverse->{$column} = $q->{asc};
            }
         }

         $vars->{setrev} = $set_reverse;






      } elsif ($q->{page} eq 'pokec_private_read') {
         $page = 'pokec_private_read';
         $hf = 1;
         $vars->{title} = 29;
         $location = '';

         $main::get_pokec_privates_user->execute($vars->{nick_id},$q->{azet_id},$q->{azet_id});
         my $lines = $main::get_pokec_privates_user->fetchall_arrayref({});
         $vars->{lines} = $lines;
         $main::get_pokec_privates_user->finish();

         $main::get_azet_name->execute($q->{azet_id});
         $vars->{with} = $main::get_azet_name->fetchrow();
         $main::get_azet_name->finish();


      } elsif ($q->{page} eq 'private_read') {
         $page = 'private_read';
         $hf = 1;
         $vars->{title} = 30;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'delete' && $q->{delete} ne '') {
            my $ids;

            if (ref($q->{delete}) ne 'ARRAY') {
               push @{$ids}, $q->{delete};
            } else {
               $ids = $q->{delete};
            }

            my $get_for_delete = $dbh->prepare('SELECT id,from_id,nick_id,deleted_from,deleted_to FROM history_privates WHERE id IN ('.join(',',@{$ids}).')');
            $get_for_delete->execute();
            my $for_delete = $get_for_delete->fetchall_arrayref({});

            foreach my $msg (@{$for_delete}) {
               if ($msg->{from_id} == $vars->{nick_id} && $msg->{deleted_from} == 0 && $msg->{deleted_to} == 0) {
                  $main::set_deleted_from_private->execute($msg->{id});
                  $main::set_deleted_from_chat->execute($msg->{id});
               } elsif ($msg->{nick_id} == $vars->{nick_id} && $msg->{deleted_from} == 0 && $msg->{deleted_to} == 0) {
                  $main::set_deleted_to_private->execute($msg->{id});
                  $main::set_deleted_to_chat->execute($msg->{id});
               } elsif (($msg->{from_id} == $vars->{nick_id} && $msg->{deleted_to} == 1) || ($msg->{nick_id} == $vars->{nick_id} && $msg->{deleted_from} == 1)) {
                  $main::delete_history_privates->execute($msg->{id});
                  $main::delete_chat->execute($msg->{id});
               }
            }
         }

         $main::get_privates_user->execute($q->{nick_id},$vars->{nick_id},$vars->{nick_id},$q->{nick_id},$q->{nick_id});
         my $lines = $main::get_privates_user->fetchall_arrayref({});
         foreach my $x (@{$lines}) {
            $x->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
         }
         $vars->{lines} = $lines;
         $main::get_privates_user->finish();

         $main::get_nick_name->execute($q->{nick_id});
         my $with_nick = $main::get_nick_name->fetchrow();

         if ($with_nick eq '') {
            my $deleted_nick;
            my $ret_deleted_nick = system::get_deleted_nick( { nick_id => $q->{nick_id}, }, );
            $with_nick = $ret_deleted_nick->{deleted_nick}->{nick};
         }

         $vars->{with} = $with_nick;
         $main::get_nick_name->finish();

         $vars->{post_title} = $with_nick;


      } elsif ($q->{page} eq 'privates_search') {

         if ($q->{where} eq '1') {

            $page = 'privates_search';
            $hf = 1;
            $vars->{title} = 31;
            $location = '';

            $main::search_privates_user->execute($q->{query},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$q->{query});
            my $lines = $main::search_privates_user->fetchall_arrayref({});
            $vars->{lines} = $lines;
            $main::search_privates_user->finish();
         } elsif ($q->{where} eq '2') {
            $hf = 0;
            $location = $globals::misc_script.'?page=private&filter='.$q->{query}.'&sid='.$q->{sid};
         }



      } elsif ($q->{page} eq 'new_privates') {
         $page = 'new_privates';
         $hf = 1;
         $vars->{title} = 32;
         $location = '';
         $vars->{doctype} = 1;

         if (defined($q->{action}) && $q->{action} eq 'mark_showed') {
            $main::set_showed_chat->execute($q->{message_id});
            $main::set_showed_history->execute($q->{message_id});
            system::add_action( { action => 15, nick_id => $vars->{nick_id}, }, );

            my $ret_channel_message_by_message_id = system::get_channel_message_by_message_id( { message_id => $q->{message_id}, }, );
            my $message = $ret_channel_message_by_message_id->{message};
                        
            system::add_action( { action => 24, nick_id => $message->{channel_id}, message_id => $q->{message_id}, }, );
               
         }

         $main::get_chat_pms->execute($vars->{nick_id},$vars->{nick_id});
         my ($privates,$privates_senders,$tmp_privates_senders);
         foreach my $x (@{$main::get_chat_pms->fetchall_arrayref({})}) {
            $finder->find(\$x->{message});

            $x->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;

#            $x->{message} =~ s/\[item=(\d+)\]/&system::ajax_rewrite_item($params->{channel_id},$1)/egs;
#            $x->{message} =~ s/\[npc=(\d+)\]/&system::ajax_rewrite_npc($params->{channel_id},$1)/egs;
#            $x->{message} =~ s/\[quest=(\d+)\]/&system::jax_rewrite_quest($params->{channel_id},$1)/egs;
            $x->{message} =~ s/\[spell=(\d+)\]/&system::ajax_rewrite_spell($1)/egs;
            $x->{message} =~ s/\[achievement=(\d+)\]/&system::ajax_rewrite_achievement($1)/egs;
            $x->{message} =~ s/\[youtube=(\d+)\]/&system::ajax_rewrite_youtube($1)/egs;

            $x->{message} =~ s/%S/$q->{sid}/gs;

            push @{$privates->{$x->{nick_id}}}, $x;
            if (!defined($tmp_privates_senders->{$x->{nick_id}})) {
               push @{$privates_senders}, { nick => $x->{nick}, nick_id => $x->{nick_id}, };
               $tmp_privates_senders->{$x->{nick_id}} = 1;
            }

         }
         $vars->{privates} = $privates;
         $vars->{privates_senders} = $privates_senders;
         $main::get_chat_pms->finish();

         if (defined($q->{action}) && $q->{action} eq 'reply') {
            if ($q->{type} eq 'a') {
               $main::get_azet_name->execute($q->{azet_id});
               $vars->{name} = $main::get_azet_name->fetchrow();
               $main::get_azet_name->finish();

               $main::get_pokec_privates_user_last->execute($vars->{nick_id},$q->{azet_id},$q->{azet_id});
               my $lines = $main::get_pokec_privates_user_last->fetchall_arrayref({});
               $vars->{lines} = $lines;
               $main::get_pokec_privates_user_last->finish();

            } elsif ($q->{type} eq 'p') {

               if (defined($q->{what}) && $q->{what} eq 'friendlist_remove') {
                  $main::del_friend->execute($q->{friendlist_id},$vars->{nick_id});
               } elsif (defined($q->{what}) && $q->{what} eq 'ignorelist_remove') {
                  $main::del_ignore->execute($q->{ignorelist_id},$vars->{nick_id});
               } elsif (defined($q->{what}) && $q->{what} eq 'ignorelist_add') {
                  $main::add_ignore->execute($vars->{nick_id},$q->{nick_id});
               } elsif (defined($q->{what}) && $q->{what} eq 'friendlist_add') {
                  $main::add_friend->execute($vars->{nick_id},$q->{nick_id});
               }

               $main::get_nick_name->execute($q->{nick_id});
               $vars->{name} = $main::get_nick_name->fetchrow();
               $main::get_nick_name->finish();

               $main::get_is_logged->execute($q->{nick_id});
               $vars->{nick_logged} = $main::get_is_logged->fetchrow();
               $main::get_is_logged->finish();

               $main::get_nick_joined_channels->execute($q->{nick_id});
               my $chans;
               if ($main::get_nick_joined_channels->rows() > 0) {
                  $chans = $main::get_nick_joined_channels->fetchall_arrayref({});
               }
               $main::get_nick_joined_channels->finish();
               $vars->{nick_channels} = $chans;

               $main::get_privates_user_last->execute($q->{nick_id},$vars->{nick_id},$vars->{nick_id},$q->{nick_id},$q->{nick_id});
               my $lines = $main::get_privates_user_last->fetchall_arrayref({});
               foreach my $x (@{$lines}) {
                  $x->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
               }
               $vars->{lines} = $lines;
               $main::get_privates_user_last->finish();

               $main::get_in_reply_to_history_private->execute($q->{message_id},$vars->{nick_id},$vars->{nick_id});
               my $in_reply_to = $main::get_in_reply_to_history_private->fetchrow_hashref();
               $in_reply_to->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
               $vars->{in_reply_to} = $in_reply_to;
               $main::get_in_reply_to_history_private->finish();

               $main::get_history_private->execute($q->{message_id},$vars->{nick_id},$vars->{nick_id});
               my $reply_to = $main::get_history_private->fetchrow_hashref();
               $reply_to->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
               $vars->{reply_to} = $reply_to;
               $main::get_history_private->finish();
            }

            $main::get_line->execute($q->{message_id});
            my $line = $main::get_line->fetchrow_hashref();
            $vars->{line} = $line;

            $main::set_showed_chat->execute($q->{message_id});
            $main::set_showed_history->execute($q->{message_id});
            system::add_action( { action => 15, nick_id => $vars->{nick_id}, }, );

            my $ret_channel_message_by_message_id = system::get_channel_message_by_message_id( { message_id => $q->{message_id}, }, );
            my $message = $ret_channel_message_by_message_id->{message};
                        
            system::add_action( { action => 24, nick_id => $message->{channel_id}, message_id => $q->{message_id}, }, );
                                    
                                    
            $main::get_nick_friend->execute($vars->{nick_id},$q->{nick_id});
            my $friendlist_id = $main::get_nick_friend->fetchrow();

            $main::get_ignored->execute($vars->{nick_id},$q->{nick_id});
            my $ignorelist_id = $main::get_ignored->fetchrow();


            $vars->{friendlist_id} = $friendlist_id;
            $vars->{ignorelist_id} = $ignorelist_id;


         } elsif (defined($q->{action}) && $q->{action} eq 'new' && defined($q->{to_nick}) && $q->{to_nick} ne '' ) {
            if ($q->{type} eq 'a') {
               $main::get_pokec_privates_user_last->execute($vars->{nick_id},$q->{azet_id},$q->{azet_id});
               my $lines = $main::get_pokec_privates_user_last->fetchall_arrayref({});
               $vars->{lines} = $lines;
               $main::get_pokec_privates_user_last->finish();
            } elsif ($q->{type} eq 'p') {
               $main::get_nick_id->execute($q->{to_nick});
               if ($main::get_nick_id->rows == 1) {
                  $main::get_nick_joined_channels->execute($q->{nick_id});
                  my $chans = $main::get_nick_joined_channels->fetchall_arrayref({});
                  $main::get_nick_joined_channels->finish();
                  $vars->{channels} = $chans;
                  my $to_nick_id = $main::get_nick_id->fetchrow();
                  $main::get_privates_user_last->execute($to_nick_id,$vars->{nick_id},$vars->{nick_id},$to_nick_id,$to_nick_id);
                  my $lines = $main::get_privates_user_last->fetchall_arrayref({});
                  $vars->{lines} = $lines;
                  $main::get_privates_user_last->finish();
                  $vars->{to_nick_id} = $to_nick_id;
               }
            }

            $main::get_nick_friend->execute($vars->{nick_id},$q->{nick_id});
            my $friendlist_id = $main::get_nick_friend->fetchrow();

         } elsif (defined($q->{action}) && $q->{action} eq 'read_all') {
            foreach my$x (keys(%{$privates})) {
               foreach (@{$privates->{$x}}) {
                  $main::set_showed_chat->execute($_->{id});
                  $main::set_showed_history->execute($_->{id});
                  system::add_action( { action => 24, nick_id => $_->{nick_id}, message_id => $_->{id}, }, );
               }
            }
            system::add_action( { action => 15, nick_id => $vars->{nick_id}, }, );

            $main::get_chat_pms->execute($vars->{nick_id},$vars->{nick_id});
            my $privates = $main::get_chat_pms->fetchall_arrayref({});
            $vars->{privates} = $privates;
            $main::get_chat_pms->finish();

         }

         $vars->{channels_hashref} = $channels_hashref;



      } elsif ($q->{page} eq 'ajax_item_search') {
         $page = 'ajax_item_search';
         $hf = 0;
         $location = '';

         my $ret_items_by_like_name = system::get_items_by_like_name( { server_id => $q->{server_id}, name => $q->{query}, }, );
        
         my $suggestions;
         my $data;

         foreach (@{$ret_items_by_like_name->{items}}) {
            push @{$suggestions}, '\''.$_->{name}.'\'';
            push @{$data}, '\''.$_->{entry}.'\'';
         }

         $vars->{suggestions} = $suggestions;
         $vars->{data} = $data


      } elsif ($q->{page} eq 'settings_auctionhouse') {
         $page = 'settings_auctionhouse';
         $hf = 1;
         $vars->{title} = 91;
         $location = '';

         if (defined($q->{what}) && $q->{what} eq 'add') {
            if ($q->{item_id} != 0) {
               system::add_auction_hook( { server_id => $q->{server_id}, nick_id => $vars->{nick_id}, item_id => $q->{item_id}, price => $q->{gold}.sprintf("%02d",$q->{silver}).sprintf("%02d",$q->{copper}), }, );
            } else {
               system::del_all_server_auction_hooks( { server_id => $q->{server_id}, nick_id => $vars->{nick_id}, } );
               system::add_auction_hook( { server_id => $q->{server_id}, nick_id => $vars->{nick_id}, item_id => 0, price => 0, }, );
            }
         } elsif (defined($q->{what}) && $q->{what} eq 'delete') {
            system::del_auction_hook( { id => $q->{id}, nick_id => $vars->{nick_id}, } );
         }

         my $ret_user_auctions_by_nick_id = system::get_user_auctions_by_nick_id( $dbh, { server_id => $q->{server_id}, nick_id => $vars->{nick_id}, stats=> $q->{stats}, }, );
         $vars->{auctions} = $ret_user_auctions_by_nick_id->{auctions};
         $vars->{all_auctions} = $ret_user_auctions_by_nick_id->{all};






      } elsif ($q->{page} eq 'settings_guilds') {
         $page = 'settings_guilds';
         $hf = 1;
         $vars->{title} = 33;
         $location = '';

#warn "oh yeah";

         if (!defined($q->{server_id}) || $q->{server_id} =~ /\D/) {
            $q->{server_id} = $vars->{channel_id};
         }

#warn "q->{action} = $q->{action}";

         if (defined($q->{action}) && $q->{action} eq 'invite') {
#            system::add_bind_nick_channel_guild( { nick_id => $vars->{nick_id}, member => $q->{nick}, channel_id => $q->{server_id}, guild_id => $q->{guild_id}, }, );

            $main::get_armory_server_id->execute($q->{server_id});
            my $armory_server_id = $main::get_armory_server_id->fetchrow();
            $main::get_armory_server_id->finish();


#            warn " system::add_channel_guild_invitation( { nick_id => $vars->{nick_id}, nick => $q->{nick}, channel_id => $q->{server_id}, server_id => $armory_server_id, guild_id => $q->{guild_id}, }, );";

            my $ret_channel_guild_invitation = system::add_channel_guild_invitation( { nick_id => $vars->{nick_id}, nick => $q->{nick}, channel_id => $q->{server_id}, server_id => $armory_server_id, guild_id => $q->{guild_id}, }, );
            if ($ret_channel_guild_invitation->{rv} == -1) {
               $vars->{invitation_error} = 1;
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'decline') {
            system::del_guild_invite( { nick_id => $vars->{nick_id}, invite_id => $q->{id}, }, );

         } elsif (defined($q->{action}) && $q->{action} eq 'accept') {
            system::set_guild_invite( { nick_id => $vars->{nick_id}, invite_id => $q->{id}, }, );

         } elsif (defined($q->{action}) && $q->{action} eq 'del') {
            system::del_bind_nick_channels_guilds( { nick_id => $vars->{nick_id}, member_id => $q->{nick_id}, channel_id => $q->{server_id}, guild_id => $q->{guild_id}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'rank') {
            system::set_guild_rank_by_nick_id_channel_id_guild_id( { nick_id => $vars->{nick_id}, member_id => $q->{nick_id}, channel_id => $q->{server_id}, guild_id => $q->{guild_id}, level => $q->{level}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'set') {

            $main::get_armory_server_id->execute($q->{server_id});
            my $armory_server_id = $main::get_armory_server_id->fetchrow();
            $main::get_armory_server_id->finish();

            system::set_guild_definition( { server_id => $q->{server_id}, armory_server_id => $armory_server_id, guild_id => $q->{guild_id}, nick_id => $vars->{nick_id}, guild_short => $q->{guild_short}, guild_web => $q->{guild_web}, incline => $q->{incline}, }, );
#warn "            system::set_guild_definition( { server_id => $q->{server_id}, armory_server_id => $armory_server_id, guild_id => $q->{guild_id}, nick_id => $vars->{nick_id}, guild_short => $q->{guild_short}, guild_web => $q->{guild_web}, incline => $q->{incline}, }, );";



         } elsif (defined($q->{action}) && $q->{action} eq 'guild_master') {

#warn "get_guild_id_by_channel_and_nick_id->execute($q->{server_id},$vars->{nick_id})";

            $main::get_guild_id_by_channel_and_nick_id->execute($q->{server_id},$vars->{nick_id});
            if ($main::get_guild_id_by_channel_and_nick_id->rows() == 0) {

               $main::admin_get_server->execute($q->{server_id});
               my $server_info = $main::admin_get_server->fetchrow_hashref();
               $main::admin_get_server->finish();

               $main::get_armory_server_id->execute($q->{server_id});
               my $armory_server_id = $main::get_armory_server_id->fetchrow();
               $main::get_armory_server_id->finish();

               my $ret_server_type_and_url = system::get_server_type_and_url( { armory_server_id => $armory_server_id, }, );
               my $server_type_and_url = $ret_server_type_and_url->{server_type_and_url};
                  

               my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$q->{login}.'&password='.$q->{password}.'&action=get_owned_guilds_by_login_and_password');


               if ($ret_wget->{content} !~ /^0$/) {
                  my $guilds_ranks;

#warn "input ".$ret_wget->{content};

                  foreach my $data (split(/\n/, $ret_wget->{content})) {
                     my ($guid,$rank) = split(/\|/,$data);
#warn "($guid,$rank)";
#warn "main::get_guild_id_by_guild_guid->execute($q->{server_id},$guid);";

                     $main::get_guild_id_by_guild_guid->execute($q->{server_id},$guid);
                     my $guild_id = $main::get_guild_id_by_guild_guid->fetchrow();
#warn "!!! guild_id = $guild_id";
                     $main::get_guild_id_by_guild_guid->finish();
                     if (!defined($guilds_ranks->{$guild_id}) || $rank < $guilds_ranks->{$guild_id}) {
#warn "guilds_ranks->{$guild_id} = $rank;";
                        $guilds_ranks->{$guild_id} = $rank;
                     }
                  }


                  foreach (keys(%{$guilds_ranks})) {
                     if (defined($_) && $_ > 0) {
#warn "main::bind_nick_channel_guild->execute($vars->{nick_id},$q->{server_id},$_,$guilds_ranks->{$_});";
                        $main::bind_nick_channel_guild->execute($vars->{nick_id},$q->{server_id},$_,$guilds_ranks->{$_});
                     }
                  }
               }

            }
            $main::get_guild_id_by_channel_and_nick_id->finish();







         }

         $main::get_guilds->execute();
         foreach (@{$main::get_guilds->fetchall_arrayref({})}) {
            $guilds->{$_->{server_id}}->{$_->{id}} = $_;
         }
         $main::get_guilds->finish();

         my $ret_channels = system::get_channels_on_in_guild_by_nick_id( { nick_id => $vars->{nick_id}, }, );
         $vars->{available_channels} = $ret_channels->{channels};

         my $ret_guilds = system::get_is_in_guilds_by_nick_id_channel_id( { channel_id => $q->{server_id}, nick_id => $vars->{nick_id}, }, );

         my $tmp_chars = system::get_all_bind_nick_players_of_server_id( { server_id => $q->{server_id}, }, );
         $vars->{chars} = $tmp_chars->{chars};

         my $ret_nicks;
         foreach (@{$ret_guilds->{guilds}}) {
            my $tmp_nicks = system::get_guild_nicks_by_channel_id_guild_id( { channel_id => $q->{server_id}, guild_id => $_->{guild_id}, }, );
            $_->{nicks} = $tmp_nicks->{nicks};
            my $tmp_level = system::get_guild_member_level_by_nick_id_channel_id_guild_id( { nick_id => $vars->{nick_id}, channel_id => $q->{server_id}, guild_id => $_->{guild_id}, }, );
            $_->{level} = $tmp_level->{level};
         }
         $vars->{owned_guild} = $ret_guilds->{guilds};

         my $ret_guild_invites_by_nick_id = system::get_guild_invites_by_nick_id( { nick_id => $vars->{nick_id}, }, );
         my $guild_invites = $ret_guild_invites_by_nick_id->{invites};
         $vars->{guild_invites} = $guild_invites;


      } elsif ($q->{page} eq 'settings_friends') {
         $page = 'settings_friends';
         $hf = 1;
         $vars->{title} = 34;
         $location = '';


         if (defined($q->{action}) && $q->{action} eq 'add_friend') {
            $main::get_nick_id->execute($q->{to_nick});
            if ($main::get_nick_id->rows == 1) {
               my $to_nick_id = $main::get_nick_id->fetchrow();
               $main::get_nick_friend->execute($vars->{nick_id},$to_nick_id);
               $main::get_ignored->execute($vars->{nick_id},$to_nick_id);

               if ($main::get_nick_friend->rows() == 0 && $to_nick_id != $vars->{nick_id} && $main::get_ignored->rows() == 0) {
                  $main::add_friend->execute($vars->{nick_id},$to_nick_id);
               }
               $main::get_nick_friend->finish();
            }
         } elsif (defined($q->{action}) && $q->{action} eq 'del_friend') {
            $main::del_friend->execute($q->{id},$vars->{nick_id});
         } elsif (defined($q->{action}) && $q->{action} eq 'set_notify') {
            $main::set_friend_notify->execute($q->{notify},$q->{id},$vars->{nick_id});
         } elsif (defined($q->{action}) && $q->{action} eq 'set_highlight') {
            $main::set_friend_highlight->execute($q->{highlight},$q->{id},$vars->{nick_id});
         }

         $main::get_nick_friends->execute($vars->{nick_id});
         $vars->{friends} = $main::get_nick_friends->fetchall_arrayref({});
         $main::get_nick_friends->finish();

         my $ret_users_for_im_friend = system::get_users_for_im_friend( { nick_id => $vars->{nick_id}, }, );
         $vars->{im_friend} = $ret_users_for_im_friend->{im_friend};

      } elsif ($q->{page} eq 'settings_ignores') {
         $page = 'settings_ignores';
         $hf = 1;
         $vars->{title} = 35;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'add_ignore') {
            $main::get_nick_id->execute($q->{to_nick});
            if ($main::get_nick_id->rows == 1) {
               my $to_nick_id = $main::get_nick_id->fetchrow();
               $main::get_ignored->execute($vars->{nick_id},$to_nick_id);

               $main::get_nick_friend->execute($vars->{nick_id},$to_nick_id);
               if ($main::get_nick_friend->rows() == 0 && $to_nick_id != $vars->{nick_id} && $main::get_ignored->rows() == 0) {
                  $main::add_ignore->execute($vars->{nick_id},$to_nick_id);
               }
            }            
         } elsif (defined($q->{action}) && $q->{action} eq 'del_ignore') {
            $main::del_ignore->execute($q->{id},$vars->{nick_id});
         } elsif (defined($q->{action}) && $q->{action} eq 'set_channel_ignore') {
            $main::set_channel_ignore->execute($q->{notify},$q->{id},$vars->{nick_id});
         }

         $main::get_ignored_nicks->execute($vars->{nick_id});
         $vars->{ignores} = $main::get_ignored_nicks->fetchall_arrayref({});
         $main::get_ignored_nicks->finish();


      } elsif ($q->{page} eq 'settings_frame') {
         $page = 'settings_frame';
         $hf = 0;
         $location = '';


      } elsif ($q->{page} eq 'logins_history') {
         $page = 'logins_history';
         $hf = 1;
         $vars->{title} = 37;
         $location = '';

         $main::get_logins_history->execute($vars->{nick_id});
         $vars->{history} = $main::get_logins_history->fetchall_arrayref({});
         $main::get_logins_history->finish();

         if (defined($q->{id}) && $q->{id} =~ /^\d+$/) {
            $main::get_rank_points_history->execute($q->{id},$vars->{nick_id});
            $vars->{points_history} = $main::get_rank_points_history->fetchall_arrayref({});
            $main::get_rank_points_history->finish();
         }



      } elsif ($q->{page} eq 'settings_navigation') {
         $page = 'settings_navigation';
         $hf = 1;
         $vars->{title} = 39;
         $location = '';

         my $ret_comments_count_of_my_images = system::get_comments_count_of_my_images( { nick_id => $vars->{nick_id}, } );
         $vars->{old} = $ret_comments_count_of_my_images->{old};
         $vars->{new} = $ret_comments_count_of_my_images->{new};
                                    

      } elsif ($q->{page} eq 'settings_email') {
         $page = 'settings_email';
         $hf = 1;
         $vars->{title} = 40;
         $location = '';



      } elsif ($q->{page} eq 'settings_ui') {
         $page = 'settings_ui';
         $hf = 1;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'save') {
            for (my $i=0; $i<=28; ++$i) {
               system::set_user_event( { action_id => $i, pre_code => $q->{'pre_code_'.$i}, post_code => $q->{'post_code_'.$i}, nick_id => $vars->{nick_id}, } );
#warn "system::set_user_event( { action_id => $i, pre_code => $q->{'pre_code_'.$i}, post_code => $q->{'post_code_'.$i}, nick_id => $vars->{nick_id}, } );";
            }
         }

         my $ret_user_events = system::get_user_events( { nick_id => $vars->{nick_id}, } );
         my $user_events = $ret_user_events->{user_events};
         foreach (keys(%{$user_events})) {
            my ($pre,$post);
            @{$pre} = split(/\n/,$user_events->{$_}->{pre_code});
            @{$post} = split(/\n/,$user_events->{$_}->{post_code});

            if (ref($pre) eq 'ARRAY') {
               $user_events->{$_}->{pre_num} = scalar(@{$pre});
            } else {
               $user_events->{$_}->{pre_num} = 10;
            }

            if (ref($post) eq 'ARRAY') {
               $user_events->{$_}->{post_num} = scalar(@{$post});
            } else {
               $user_events->{$_}->{post_num} = 10;
            }

         }
         $vars->{user_events} = $user_events;


      } elsif ($q->{page} eq 'settings_settings') {
         $page = 'settings_settings';
         $hf = 1;
         $vars->{title} = 41;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'save') {
         } elsif (defined($q->{action}) && $q->{action} eq 'guild_quit') {
#            $main::del_nick_guild->execute($vars->{guild_id_member},$vars->{nick_id});
#            $vars->{guild_id_member} = 0;
         }


         $main::get_settings->execute($vars->{nick_id});
         my $sett = $main::get_settings->fetchrow_hashref();

         $vars->{refresh_id} = $sett->{refresh_id};
         $vars->{show_graph} = $sett->{show_graph};
         $vars->{show_chat} = $sett->{show_chat};
         $vars->{show_info} = $sett->{show_info};
         $vars->{lines_id} = $sett->{lines_id};
         $vars->{graph_id} = $sett->{graph_id};
         $vars->{theme_id} = $sett->{theme_id};
         $vars->{chat_font} = $sett->{chat_font};
         $vars->{active_nicks} = $sett->{active_nicks};
         $vars->{ding_change} = $sett->{ding_change};
         $vars->{segregate} = $sett->{segregate};
         $vars->{incline_colors} = $sett->{incline_colors};
         $vars->{incline_chat} = $sett->{incline_chat};
         $vars->{mark_messages} = $sett->{mark_messages};
         $vars->{mark_how} = $sett->{mark_how};
         $vars->{autocomplete_nicks} = $sett->{autocomplete_nicks};
         $vars->{show_macros} = $sett->{show_macros};
         $vars->{show_guild} = $sett->{show_guild};
         $vars->{guilds_type} = $sett->{guilds_type};
         $vars->{privates_type} = $sett->{privates_type};
         $vars->{privates_size} = $sett->{privates_size};
         $vars->{nicks_panel} = $sett->{nicks_panel};
         $vars->{hold_me_frak} = $sett->{hold_me_frak};
         $vars->{hide_blabla} = $sett->{hide_blabla};
         $vars->{hold_to_nick} = $sett->{hold_to_nick};
         $vars->{reverse_chat} = $sett->{reverse_chat};
         $vars->{fade_in} = $sett->{fade_in};
         $vars->{channel_id} = $sett->{channel_id};
         $vars->{server_id} = $sett->{server_id};
         $vars->{channels} = $channels;
         $vars->{incline} = $sett->{incline};
         $vars->{background} = $sett->{background};
         $vars->{import_messages} = $sett->{import_messages};
         $vars->{frame_size} = $sett->{frame_size};
         $vars->{auction_type} = $sett->{auction_type};
         $vars->{show_joins} = $sett->{show_joins};
         $vars->{import_ingame_chat} = $sett->{import_ingame_chat};


         $main::get_settings->finish();

         $main::get_user_sheduled_refraction->execute($vars->{nick_id});
         my $refraction = $main::get_user_sheduled_refraction->fetchrow_hashref();
         $main::get_user_sheduled_refraction->finish();
         $vars->{refraction} = $refraction;

         $main::get_profiled_settings->execute($vars->{nick_id});
         my $profiled_settings = $main::get_profiled_settings->fetchall_arrayref({});
         $vars->{profiled_settings} = $profiled_settings;
         $main::get_profiled_settings->finish();




      } elsif ($q->{page} eq 'settings_login') {
         $page = 'settings_login';
         $hf = 1;
         $vars->{title} = 42;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'change_login') {

            $main::get_free_nicks_changes->execute($vars->{nick_id});
            my $free_renames = $main::get_free_nicks_changes->fetchrow();
            $main::get_free_nicks_changes->finish();



            my @errors;
            if (length($q->{nick}) < 2) {push @errors,'0';}
            if (length($q->{nick}) > 12) {push @errors,'1';}
            if ($q->{nick} !~ /^[a-zA-Z0-9\.\-_\*]+$/) {push @errors,'2';}
            $main::get_nick_id->execute($q->{nick});
            if ($main::get_nick_id->rows() != 0) {push @errors,'3';}
            $main::get_nick_id->finish();
            if ($q->{nick} !~ /^[a-zA-Z]/) {push @errors,'4';}
            if ($q->{nick} !~ /[a-zA-Z0-9]$/) {push @errors,'5';}
            if ($q->{nick} =~ /[0-9\.\-_\*]{2}/) {push @errors,'10';}
            if ($free_renames == 0) {
               if ($vars->{chat_rank} < 1) {push @errors,'6';}
               if ($vars->{chat_rank_points} < 1000) {push @errors,'7';}
               if ($q->{agree} != 1) {push @errors,'9';}
            }
#            if ($vars->{wowchat_email} ne '') {push @errors,'8';}


            my $enc_password;
#warn "q->{response} = $q->{response}";
            if (defined($q->{response}) && $q->{response} =~ /^.{64}$/) {
               my $ret_check_challenge = system::check_challenge( { login => lc($vars->{nick}), session_hex => $q->{sid}, response => $q->{response}, } );
#warn "ret_check_challenge = system::check_challenge( { login => lc($vars->{nick}), session_hex => $q->{sid}, response => $q->{response}, } )";
               if ($ret_check_challenge->{rv} == 1) {
                  $enc_password = $ret_check_challenge->{enc_password};
#warn "enc_password = $ret_check_challenge->{enc_password};";

               }
            }

            $main::get_nick_by_enc->execute($vars->{nick},$enc_password);
            if ($main::get_nick_by_enc->rows() != 1) {push @errors,'11';}


            if (scalar(@errors) == 0) {

               $q->{nick} = ucfirst(lc($q->{nick}));

               if ($free_renames == 0) {
                  $main::rename_nick->execute($q->{nick},$vars->{nick_id});
               } else {
                  $main::rename_nick_free->execute($q->{nick},$vars->{nick_id});
                  $main::sub_free_nicks_changes->execute($vars->{nick_id});
               }
               $main::log_rename_nick->execute($vars->{nick_id},$vars->{nick},$q->{nick});

               $main::get_nick_by_nick_id->execute($vars->{nick_id});
               my $nick_data = $main::get_nick_by_nick_id->fetchrow_hashref();
               my $msg = MIME::Lite->new(
			From			=> 'NickChange',
			To			=> $nick_data->{email},
			Subject			=> 'Zaslanie noveho prihlasovacieho mena (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> 'Tento mail Vam bol odoslany na zaklade zmeny prihlasovacieho mena (z IP adresy '.$ENV{REMOTE_ADDR}.'). Pokial ste si prihlasovacie meno nemenili Vy, tak bolo Vase konto kompromitovane a urychlene kontaktujte spravcu stranky.'."\n\n".'Nove prihlasovacie meno: '.$q->{nick}."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'mine.sk Crew',
               );
               $main::get_nick_by_nick_id->finish();
               $msg->send;


               my $dig = sha256_hex(uc($q->{nick}).':'.uc($q->{password}));

               my $num = 0;
               foreach my $x (split('',$q->{nick})) {
                  $num += ord(lc($x));
               }

               $num = 1+($num % 60);

               my $pre;
               my $post;
               my $tmp = 0;
               foreach my $char (split('',$dig)) {
                  if ($tmp < $num) {
                     $pre .= $char;
                  } else {
                     $post .= $char;
                  }
                  ++$tmp;
               }

               $pre = reverse($pre);
               $post = reverse($post);
               chop($post);

               my $out = $post.'0'.$pre;

               $main::change_enc_password->execute($out,$vars->{nick_id});



               $vars->{success} = 1;
            } else {
               $vars->{errors} = \@errors;
               $vars->{success} = 0;
            }


         }

         $main::get_free_nicks_changes->execute($vars->{nick_id});
         my $free_renames = $main::get_free_nicks_changes->fetchrow();
         $vars->{free_renames} = $free_renames;
         $main::get_free_nicks_changes->finish();

         my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
         $vars->{challenge} = $ret_create_challenge->{challenge};



      } elsif ($q->{page} eq 'settings_password') {
         $page = 'settings_password';
         $hf = 1;
         $vars->{title} = 43;
         $location = '';

         $vars->{rv} = 0;

         if (defined($q->{action}) && $q->{action} eq 'change_password') {
            my @errors;

            my $enc_password;
            if (defined($q->{response}) && $q->{response} =~ /^.{64}$/) {
               my $ret_check_challenge = system::check_challenge( { login => lc($vars->{nick}), session_hex => $q->{sid}, response => $q->{response}, } );
               if ($ret_check_challenge->{rv} == 1) {
                  $enc_password = $ret_check_challenge->{enc_password};
               }
            }


            $main::get_nick_by_enc->execute($vars->{nick},$enc_password);
            if ($main::get_nick_by_enc->rows() != 1) {push @errors,'0';}
            if (length($q->{new1}) < 4) {push @errors,'1';}
            if ($q->{new1} ne $q->{new2}) {push @errors,'2';}
            if (similarity (lc $vars->{nick}, lc $q->{new1}) > 0.75) {push @errors,'3';}

            if (scalar(@errors) == 0) {


               my $nick_data = $main::get_nick_by_enc->fetchrow_hashref();

               my $msg = MIME::Lite->new(
			From			=> 'PasswordChange',
			To			=> $nick_data->{email},
			Subject			=> 'Zaslanie noveho hesla (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> 'Tento mail Vam bol odoslany na zaklade zmeny hesla (z IP adresy '.$ENV{REMOTE_ADDR}.'). Pokial ste si heslo nemenili Vy, tak bolo Vase konto kompromitovane a urychlene kontaktujte spravcu stranky.'."\n\n".'Nove prihlasovacie heslo: '.$q->{new1}."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'mine.sk Crew',
               );

               $msg->attr(
			'content-type.charset'	=> 'UTF-8',
               );

               $msg->send;

               my $dig = sha256_hex(uc($nick_data->{nick}).':'.uc($q->{new1}));

               my $num = 0;
               foreach my $x (split('',$nick_data->{nick})) {
                  $num += ord(lc($x));
               }

               $num = 1+($num % 60);

               my $pre;
               my $post;
               my $tmp = 0;
               foreach my $char (split('',$dig)) {
                  if ($tmp < $num) {
                     $pre .= $char;
                  } else {
                     $post .= $char;
                  }
                  ++$tmp;
               }

               $pre = reverse($pre);
               $post = reverse($post);
               chop($post);

               my $out = $post.'0'.$pre;

               $main::change_enc_password->execute($out,$vars->{nick_id});
#               $main::change_password->execute($q->{new1},$vars->{nick_id});

               $vars->{rv} = 1;

            } else {
               $vars->{errors} = \@errors;
               $vars->{rv} = -1
            }
            $main::get_nick_by_enc->finish();

         }

         my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
         $vars->{challenge} = $ret_create_challenge->{challenge};


      } elsif ($q->{page} eq 'settings_pokec') {
         $page = 'settings_pokec';
         $hf = 1;
         $vars->{title} = 44;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'save') {

            my @errors;
            if ($q->{pokec_login} eq '') {push @errors,'0';}
            if ($q->{pokec_password} eq '') {push @errors,'1';}
            my $ret_connect = pokec::connect($q->{pokec_login},$q->{pokec_password},$q->{pokec_channel});
            my $azet_id;
            if ($ret_connect->{rv} == 0) {
               push @errors,'2';
            } else {
               $azet_id = $ret_connect->{azet_id};
            }

            if (scalar(@errors) == 0) {
               $main::set_pokec->execute($q->{pokec_login},$q->{pokec_password},$azet_id,$q->{pokec_channel},$vars->{nick_id});
            } else {
               $vars->{errors} = \@errors;
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'logoff') {

            my $ret_disconnect = pokec::disconnect($vars->{pokec_i9});
            $main::set_pokec_i9->execute('',$vars->{nick_id});
            $vars->{pokec_i9} = '';

         } elsif (defined($q->{action}) && $q->{action} eq 'logon') {

            $main::get_pokec->execute($vars->{nick_id});
            my $ret_pokec = $main::get_pokec->fetchrow_hashref();
            $main::get_pokec->finish();

            my $ret_connect = pokec::connect($ret_pokec->{pokec_login},$ret_pokec->{pokec_password},$ret_pokec->{pokec_channel});
            if ($ret_connect->{rv} == 1) {
               $vars->{pokec_i9} = $ret_connect->{i9};
               $main::set_pokec_i9->execute($vars->{pokec_i9},$vars->{nick_id});
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'cancel') {
               my $ret_disconnect = pokec::disconnect($vars->{pokec_i9});
               $main::set_pokec_i9->execute('',$vars->{nick_id});
               $vars->{pokec_i9} = '';
               $main::set_pokec->execute('','','','',$vars->{nick_id});

         }

         $main::get_pokec->execute($vars->{nick_id});
         my $ret_pokec = $main::get_pokec->fetchrow_hashref();
         $main::get_pokec->finish();

         $vars->{pokec} = $ret_pokec;


      } elsif ($q->{page} eq 'settings_profile') {
         $page = 'settings_profile';
         $hf = 1;
         $vars->{title} = 45;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'save_profile') {

            if (!defined($q->{day}) || $q->{day} =~ /\D/) {$q->{day} = 0;}
            if (!defined($q->{month}) || $q->{month} =~ /\D/) {$q->{month} = 0;}
            if (!defined($q->{year}) || $q->{year} =~ /\D/) {$q->{year} = 0;}
            if (!defined($q->{high}) || $q->{high} =~ /\D/) {$q->{high} = 0;}
            if (!defined($q->{weigth}) || $q->{weigth} =~ /\D/) {$q->{weigth} = 0;}
            if (!defined($q->{icq}) || $q->{icq} =~ /\D/) {$q->{icq} = 0;}
            if (!defined($q->{hide_icq}) || $q->{hide_icq} =~ /\D/) {$q->{hide_icq} = 0;}

            if ($q->{high} < 150 || $q->{high} > 250) {$q->{high} = 0;}
            if ($q->{weigth} < 35 || $q->{weigth} > 250) {$q->{weigth} = 0;}

            $q->{file} =~ m/^\d+__(.*)$/;
            my $file = $1;

            if (defined($file) && $file ne '') {
               my $ret_make_thumb = system::make_thumb( { source => $globals::datadir.'/tmp/'.$q->{file}, destination => $globals::datadir.'/photos/'.$vars->{nick_id}.'.jpg', width => 133, height => 200, } );
               $main::set_profile->execute($q->{sex},$q->{year}.'-'.$q->{month}.'-'.$q->{day},$q->{city},$q->{job},$q->{education},1,$q->{status},$q->{high},$q->{weight},$q->{icq},$q->{hide_icq},$vars->{nick_id});
            } else {
               $main::get_profile->execute($vars->{nick_id});
               my $ret_profile = $main::get_profile->fetchrow_hashref();
               $main::get_profile->finish();
               $main::set_profile->execute($q->{sex},$q->{year}.'-'.$q->{month}.'-'.$q->{day},$q->{city},$q->{job},$q->{education},$ret_profile->{profile_photo},$q->{status},$q->{high},$q->{weight},$q->{icq},$q->{hide_icq},$vars->{nick_id});
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'remove_photo') {
            $main::set_profile_photo->execute(0,$vars->{nick_id});
            unlink $globals::datadir.'/photos/'.$vars->{nick_id}.'.jpg';
         }

         $main::get_profile->execute($vars->{nick_id});
         my $ret_profile = $main::get_profile->fetchrow_hashref();
         $main::get_profile->finish();

         $vars->{profile} = $ret_profile;


      } elsif ($q->{page} eq 'settings_characters') {
         $page = 'settings_characters';
         $hf = 1;
         $vars->{title} = 46;
         $location = '';


         my @errors;
         my @errors2;

         if (defined($q->{action}) && $q->{action} eq 'save_characters') {

            foreach my $srv (@{$servers}) {
               my $tmp_chars = system::get_all_bind_nick_players_of_nick_id_on_server_id( { server_id => $srv->{server_id}, nick_id => $vars->{nick_id}, }, );
               foreach my $char (@{$tmp_chars->{chars}}) {
                  if ($q->{'guild_id_'.$srv->{server_id}.'_'.$char->{player_id}} != $char->{guild_id}) {
                     system::set_guild_of_character( { server_id => $srv->{server_id}, guild_id => $q->{'guild_id_'.$srv->{server_id}.'_'.$char->{player_id}}, character_id => $char->{player_id}, }, );
                  }
               }
            }


            if (defined($q->{character}) && $q->{character} ne '') {


               $main::admin_get_server->execute($q->{'server_id'});
               my $server_info = $main::admin_get_server->fetchrow_hashref();
               $main::admin_get_server->finish();
               $vars->{server_info} = $server_info;



warn $server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login';
               my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');

warn $ret_wget->{content};
#               if ($ret_wget->{content} =~ /^[^0]\d*\|([\d_]+)$/) {
               if ($ret_wget->{content} =~ /^(\-?\d*)\|(.+)$/) {

                  if ($1 != -1) {

                     my $accid = $1;
                     my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$q->{login}.'&password='.$q->{password}.'&action=get_account_by_character_guid');
warn $server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$q->{login}.'&password='.$q->{password}.'&action=get_account_by_character_guid';

                     my $characters_found;

                     my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&account_id='.$accid.'&action=get_account_characters');
warn $server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&account_id='.$accid.'&action=get_account_characters';
                     if ($ret_wget->{content} =~ /^0$/) {

                     } else {
                        my $tmp;

                        @{$tmp} = split(/\n/,$ret_wget->{content});
                        my $characters;

                        foreach (@{$tmp}) {
                           my ($guid,$name,$race,$class,$level,$online,$backuped,$backup_version) = split(/\|/,$_);
warn "$guid,$name,...";
                           if (lc $name eq lc $q->{character}) {
                              $characters_found = 1;
                           }
                        }
                     }


                     if ($characters_found == 1) {


                        $main::get_player_by_name->execute($q->{server_id},$q->{character});
                        if ($main::get_player_by_name->rows() == 1)  {
                           my $id = $main::get_player_by_name->fetchrow();
                           $main::check_bind_player->execute($id,$q->{server_id});
                           if ($main::check_bind_player->rows() == 0) {
                              $main::set_bind_nick_players->execute($q->{server_id},$vars->{nick_id},$id);
                           } else {
                              push @errors,'2';
                           }
                        } else {
                           push @errors,'1';
                        }
                     } else {
                        push @errors,'3';
                     }



                  } else {
                     push @errors,'0';
                  }

               } else {
                  push @errors,'0';
               }

            }
         } elsif (defined($q->{action}) && $q->{action} eq 'del_character') {
            $main::del_bind_nick_players->execute($vars->{nick_id},$q->{id});
         } elsif (defined($q->{action}) && $q->{action} eq 'add_blizzard_character') {
#warn "system::get_blizzard_character_from_armory( { server_id => $q->{blizzard_server_id}, character_name => ucfirst($q->{blizzard_character}), } );";
            my $ret_blizzard_character_from_armory = system::get_blizzard_character_from_armory( { server_id => $q->{blizzard_server_id}, character_name => ucfirst($q->{blizzard_character}), } );
            if ($ret_blizzard_character_from_armory->{rv} == 1) {
               my $blizzard_character_id = $ret_blizzard_character_from_armory->{blizzard_character_id};

#warn "system::add_blizzard_character_to_nick( { nick_id => $vars->{nick_id}, server_id => $q->{blizzard_server_id}, blizzard_character_id => $blizzard_character_id, }, );";

               my $ret_add_blizzard_character_to_nick = system::add_blizzard_character_to_nick( { nick_id => $vars->{nick_id}, server_id => $q->{blizzard_server_id}, blizzard_character_id => $blizzard_character_id, }, );
               if ($ret_add_blizzard_character_to_nick->{rv} == 1) {

               } else {
                  $vars->{old_nick} = $ret_add_blizzard_character_to_nick->{nick};
                  push @errors2,'0';
               }
            } elsif ($ret_blizzard_character_from_armory->{rv} == -1) {
               push @errors2,'1';

            } elsif ($ret_blizzard_character_from_armory->{rv} == -2) {
               push @errors2,'2';

            } elsif ($ret_blizzard_character_from_armory->{rv} == -3) {
               push @errors2,'3';
                           
                           
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'del_blizzard_character') {
            system::del_blizzard_character_from_nick( { nick_id => $vars->{nick_id}, bind_id => $q->{id}, }, );
         }

         my $ret_nick_players;
         foreach my $srv (@{$servers}) {

            my $tmp_chars = system::get_all_bind_nick_players_of_nick_id_on_server_id( { server_id => $srv->{server_id}, nick_id => $vars->{nick_id}, }, );
            if (scalar(@{$tmp_chars->{chars}}) > 0) {
               $ret_nick_players->{$srv->{server_id}}->{server} = $srv;
               $ret_nick_players->{$srv->{server_id}}->{chars} = $tmp_chars->{chars};

               my $ret_guilds = system::get_is_in_guilds_by_nick_id_channel_id( { channel_id => $srv->{server_id}, nick_id => $vars->{nick_id}, }, );
               if (scalar(@{$ret_guilds->{guilds}}) > 0) {
                  $ret_nick_players->{$srv->{server_id}}->{guilds} = $ret_guilds->{guilds};
               }
            }

         }

         $vars->{characters} = $ret_nick_players;

         $vars->{errors} = \@errors;
         $vars->{errors2} = \@errors2;


         $vars->{blizzard_servers_hash} = $ret_blizzard_servers->{blizzard_servers_hash};
         $vars->{blizzard_servers_array} = $ret_blizzard_servers->{blizzard_servers_array};

         my $ret_all_nick_blizzard_characters = system::get_all_nick_blizzard_characters( { nick_id => $vars->{nick_id}, }, );
         $vars->{blizzard_characters_servers} = $ret_all_nick_blizzard_characters->{blizzard_characters_servers};


      } elsif ($q->{page} eq 'popular_nicks') {
         $page = 'popular_nicks';
         $hf = 1;
         $vars->{title} = 47;
         $location = '';

         my $ret_nicks_popularity = system::get_nicks_popularity( $dbh );

         $vars->{popular_nicks} = $ret_nicks_popularity->{popular_nicks};
         $vars->{popular_nicks_array} = $ret_nicks_popularity->{popular_nicks_array};




      } elsif ($q->{page} eq 'get_last_activations_status') {
         $page = 'get_last_activations_status';
         $hf = 0;
         $location = '';
         $mime = 'image/png';

         my ($stamp,$total,$dminus);

         $main::get_last_activations_status->execute();
         foreach (@{$main::get_last_activations_status->fetchall_arrayref({})}) {
            $dminus->{$_->{dminus}} = $_->{num};
         }



         my $today = today();


         for (my $i=200; $i>=0; --$i) {
            if ($i % 20 == 0) {
               if ($i == 0) {
                  push @{$stamp}, 'Dnes';
               } else {
                  push @{$stamp}, $today - $i;
               }
            } else {
               push @{$stamp}, '';
            }
            push @{$total}, 0+$dminus->{$i};
         }

#         push @{$stamp}, 'Dnes';


         my $data;
         @{$data} = (	$stamp,
			$total,
         );

         my $graph = new GD::Graph::lines3d( 1000, 400 );
         $graph->set(
		bgclr			=> 'black',
		fgclr			=> 'gray',
		textclr			=> 'dgray',
		axislabelclr		=> 'dgray',
		labelclr		=> 'dgray',

                x_label                 => 'Datum',
                y_label                 => 'Hodnota',
                title                   => 'Vyvoj aktivacii',
                box_axis                => 0,
                y_tick_number           => 10,
                legend_placement        => 'BL',
#                lg_cols                 => 1,
                line_depth              => 1,
         );

         $graph->set( dclrs => [ qw(yellow) ] );

         $graph->set_legend('Pocet aktivacii');
         my $gd = $graph->plot( $data );
         $html = $gd->png;





      } elsif ($q->{page} eq 'get_nicks_last_month_popularity') {
         $page = 'get_nicks_last_month_popularity';
         $hf = 0;
         $location = '';
         $mime = 'image/png';


         my $ret_nicks_last_month_popularity = system::get_nicks_last_month_popularity( { nick_id => $q->{nick_id}, }, );
         my $month_popularity = $ret_nicks_last_month_popularity->{month_popularity};

         my ($stamp,$total,$popularity,$hate);

         foreach (@{$month_popularity}) {
            push @{$stamp}, $_->{stamp};
            push @{$total}, $_->{total};
            push @{$popularity}, $_->{popularity};
            push @{$hate}, abs($_->{hate});
         }

         my $data;
         @{$data} = (	$stamp,
			$total,
			$popularity,
			$hate,
         );

         my $graph = new GD::Graph::lines3d( 1000, 400 );
         $graph->set(
                x_label                 => 'Datum',
                y_label                 => 'Hodnota',
                title                   => 'Vyvoj popularity',
                box_axis                => 0,
                y_tick_number           => 10,
                legend_placement        => 'BL',
#                lg_cols                 => 1,
#                line_depth              => 4,
         );

         $graph->set( dclrs => [ qw(blue green red) ] );

         $graph->set_legend('Celkovo','Popularita','Nepopularita');
         my $gd = $graph->plot( $data );
         $html = $gd->png;



      } elsif ($q->{page} eq 'ranks_list') {
         $page = 'ranks_list';
         $hf = 1;
         $vars->{title} = 49;
         $location = '';

         if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
         if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 150;} else {$q->{count} = int($q->{count});}
         $main::get_chat_ranks_list->execute($q->{from},$q->{count});
         $main::get_chat_ranks_count->execute();

         my $list = $main::get_chat_ranks_list->fetchall_arrayref({});
         $main::get_chat_ranks_list->finish();
         foreach (@{$list}) {
            1 while $_->{chat_rank_points} =~ s/(\d)(\d\d\d)(?!\d)/$1 $2/g;
         }      
         my $total = $main::get_chat_ranks_count->fetchrow();
         $main::get_chat_ranks_count->finish();

         my $bind_guilds;
         $main::get_bind_nicks_channels_guilds->execute();
         foreach (@{$main::get_bind_nicks_channels_guilds->fetchall_arrayref({})}) {
            push @{$bind_guilds->{$_->{nick_id}}}, { channel_id => $_->{channel_id}, guild_id => $_->{guild_id}, };
         }
         $main::get_bind_nicks_channels_guilds->finish();

         my $bind_channels;
         $main::get_all_nicks_joined_channels->execute();
         foreach (@{$main::get_all_nicks_joined_channels->fetchall_arrayref({})}) {
            push @{$bind_channels->{$_->{nick_id}}}, { channel_id => $_->{channel_id}, };
         }
         $main::get_all_nicks_joined_channels->finish();


         $vars->{list} = $list;
         $vars->{total} = $total;
         $vars->{pages} = $total/$q->{count};
         $vars->{ranks} = $ranks;
         $vars->{bind_guilds} = $bind_guilds;
         $vars->{bind_channels} = $bind_channels;
         $vars->{channels_hashref} = $channels_hashref;




      } elsif ($q->{page} eq 'points_ladder') {
         $page = 'points_ladder';
         $hf = 1;
         $vars->{title} = 0;
         $location = '';


         my $ret_ranks_points_ladder = system::get_ranks_points_ladder( { } );
         $vars->{ladders} = $ret_ranks_points_ladder->{ladders};



      } elsif ($q->{page} eq 'quizz_list') {
         $page = 'quizz_list';
         $hf = 1;
         $vars->{title} = 50;
         $location = '';

         if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
         if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 100;} else {$q->{count} = int($q->{count});}

         my $tmp_results = system::quizz_list( { from => $q->{from}, count => $q->{count}, }, );
         my $list = $tmp_results->{list};
         my $total = $tmp_results->{count};

         $vars->{list} = $list;
         $vars->{total} = $total;
         $vars->{pages} = $total/$q->{count};



      } elsif ($q->{page} eq 'search_user') {
         $page = 'search_user';
         $hf = 1;
         $vars->{title} = 90;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'search') {

            if (!defined($q->{order}) || ($q->{order} ne 'id' && $q->{order} ne 'nick' && $q->{order} ne 'chat_rank' && $q->{order} ne 'chat_rank_points' && $q->{order} ne 'profile_sex' && $q->{order} ne 'profile_city' && $q->{order} ne 'profile_job' && $q->{order} ne 'profile_education' && $q->{order} ne 'profile_status' && $q->{order} ne 'profile_high' && $q->{order} ne 'profile_weight' && $q->{order} ne 'profile_photo')) {$q->{order} = 'id';}
            if (!defined($q->{asc}) || $q->{asc} ne '1') {$q->{asc} = 0;}
            if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
            if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 50;} else {$q->{count} = int($q->{count});}


            my $tmp_results = system::search_user( $dbh, { nick => $q->{nick}, asc => $q->{asc}, from => $q->{from}, count => $q->{count}, order => $q->{order}, sex => $q->{sex}, city => $q->{city}, status => $q->{status}, education => $q->{education}, }, );
            my $results = $tmp_results->{nicks};
            my $total = $tmp_results->{count};

            $vars->{results} = $results;
            $vars->{total} = $total;
            $vars->{pages} = $total/$q->{count};

#warn "vars->{results} = $results;";
#warn "vars->{total} = $total;";
#warn "vars->{pages} = ".($total/$q->{count}).";";

            my $set_reverse;
            foreach my $column ('id','nick','chat_rank','chat_rank_points','profile_sex','profile_city','profile_job','profile_education','profile_status','profile_high','profile_weight','profile_photo') {
               if ($q->{order} eq $column) {
                  if ($q->{asc} == 1) {
                     $set_reverse->{$column} = 0;
                  } else {
                     $set_reverse->{$column} = 1;
                  }
               } else {
                  $set_reverse->{$column} = $q->{asc};
               }
            }

            $vars->{setrev} = $set_reverse;
         }




      } elsif ($q->{page} eq 'search_message') {
         $page = 'search_message';
         $hf = 1;
         $vars->{title} = 51;
         $location = '';


         if (defined($q->{action}) && $q->{action} eq 'search') {

            if (!defined($q->{f}) || $q->{f} !~ /^\d+$/) {$q->{f} = 0;} else {$q->{f} = int($q->{f});}
            if (!defined($q->{c}) || $q->{c} !~ /^\d+$/) {$q->{c} = 100;} else {$q->{c} = int($q->{c});}

            if (!defined($q->{fd}) || $q->{fd} =~ /\D/ || $q->{fd} < 0 || $q->{fd} > 31) {$q->{fd} = 0;}
            if (!defined($q->{fm}) || $q->{fm} =~ /\D/ || $q->{fm} < 0 || $q->{fm} > 12) {$q->{fm} = 0;}
            if (!defined($q->{fy}) || $q->{fy} =~ /\D/ || $q->{fy} < 1900 || $q->{fy} > 2020) {$q->{fy} = 0;}
            if (!defined($q->{fh}) || $q->{fh} =~ /\D/ || $q->{fh} < 0 || $q->{fh} > 24) {$q->{fh} = 0;}
            if (!defined($q->{fi}) || $q->{fi} =~ /\D/ || $q->{fi} < 0 || $q->{fi} > 60) {$q->{fi} = 0;}
            if (!defined($q->{fs}) || $q->{fs} =~ /\D/ || $q->{fs} < 0 || $q->{fs} > 60) {$q->{fs} = 0;}

            if (!defined($q->{td}) || $q->{td} =~ /\D/ || $q->{td} < 0 || $q->{td} > 31) {$q->{td} = 0;}
            if (!defined($q->{tm}) || $q->{tm} =~ /\D/ || $q->{tm} < 0 || $q->{tm} > 12) {$q->{tm} = 0;}
            if (!defined($q->{ty}) || $q->{ty} =~ /\D/ || $q->{ty} < 1900 || $q->{ty} > 2100) {$q->{ty} = 0;}
            if (!defined($q->{th}) || $q->{th} =~ /\D/ || $q->{th} < 0 || $q->{th} > 24) {$q->{th} = 0;}
            if (!defined($q->{ti}) || $q->{ti} =~ /\D/ || $q->{ti} < 0 || $q->{ti} > 60) {$q->{ti} = 0;}
            if (!defined($q->{ts}) || $q->{ts} =~ /\D/ || $q->{ts} < 0 || $q->{ts} > 60) {$q->{ts} = 0;}

            my ($stamp_from,$stamp_to);

            if ($q->{fd} != 0 && $q->{fm} != 0 && $q->{fy} != 0) {
               $stamp_from = $q->{fy}.'-'.$q->{fm}.'-'.$q->{fd}.' '.$q->{fh}.':'.$q->{fi}.':'.$q->{fs};
            }

            if ($q->{td} != 0 && $q->{tm} != 0 && $q->{ty} != 0) {
               $stamp_to = $q->{ty}.'-'.$q->{tm}.'-'.$q->{td}.' '.$q->{th}.':'.$q->{ti}.':'.$q->{ts};
            }


            my $tmp_results = system::search_messages( $dbh, { text => $q->{t}, from => $q->{f}, count => $q->{c}, stamp_from => $stamp_from, stamp_to => $stamp_to, channel_id => $q->{ch}, nick => $q->{n}, } );
            my $results = $tmp_results->{messages};
            my $total = $tmp_results->{count};


            my $level = 0;
            $main::get_level_for_server->execute($q->{ch},$vars->{nick_id});
            if ($main::get_level_for_server->rows() != 0) {
                $level = $main::get_level_for_server->fetchrow();
            }
            $main::get_level_for_server->finish();

            $main::admin_get_server_permissions->execute($q->{ch},$vars->{nick_id});
            my $permissions = $main::admin_get_server_permissions->fetchrow_hashref();

            foreach my $x (@{$results}) {
               if ($x->{message} =~ m/\[item=(\d+)\]/) {
                  $x->{message} =~ s/\[item=(\d+)\]/&rewrite_item($1)/egs;
                  $x->{item} = 1;
               }

               $x->{message} =~ s/\[youtube=(\d+)\]/&system::rewrite_youtube($1)/egs;

               if ($x->{message} =~ m/S&(\d+)&/) {


                  if ($x->{msg_type} ne 'f') {
                     $x->{message} = &substitutions($x->{message});
                  } else {
                     $x->{message} = &substitutions_lite($x->{message});
                  }


#                  $x->{message} =~ s/S&(\d+)&/<font title="$substitutions->{$1}->{value}" style="cursor:help">$substitutions->{$1}->{shortcut}<\/font>/gs;
               }
               

#if ($x->{nick_id} == 1) {
#warn "[$x->{tstamp}] $x->{message}";
#warn "    if ($x->{msg_type} eq 'f' && (($x->{incline} != $vars->{incline} && ($x->{level} eq '' && $vars->{level} == 0)) || ($x->{level} > 0 && $level == 0))) {";
#}

#               if ($x->{global_level} > 0 && $x->{level} == 0) {
#                  $x->{level} = $x->{global_level};
#               }

#if (f eq 'f' && (        (3 != 2 && ('' eq '' && 6 == 0))         || ('' > 0 && 0 == 0))) { 
#if (f eq 'f' && (        (3 != 3 && ('' eq '' && 1 == 0))         || ('' > 0 && 0 == 0))) {

               my $translate = 0;

               if ($vars->{global_level} > 0) {
                  if ($x->{msg_type} eq 'f') {
                     if ($permissions->{history} == 1) {
                        $translate = 0;
                     } else {
                        $translate = 1;
                     }
                  }

               } else {
                  if ($level != 0) {
# permissions here
                     if ($x->{msg_type} eq 'f') {
                        if ($permissions->{history} == 1) {
                           $translate = 0;
                        } else {
                           $translate = 1;
                        }
                     }
                  } else {
                     if ($x->{msg_type} eq 'f') {
#                        if ($x->{incline} != $vars->{incline}) {
                           $translate = 1;
#                        } else {
#                           $translate = 0;
#                        }
                     } else {
                        $translate = 0;
                     }
                  }
               }

#               if ($x->{msg_type} eq 'f' && (($x->{incline} != $vars->{incline} && $level eq '') || ($level == '' && $x->{global_level} == 0))) {
               if ($translate == 1) {
                  $x->{message} = system::htmlrefilter($x->{message});
                  if ($vars->{incline} == 1) {
                     $x->{message} = system::translate_h($x->{message});
                  } elsif ($vars->{incline} == 2) {
                     $x->{message} = system::translate_a($x->{message});
                  } else {
                     $x->{message} = system::translate_g($x->{message});
                  }
                  $x->{message} = system::htmlfilter($x->{message});

               }


            }








            $vars->{results} = $results;
            $vars->{total} = $total;
            $vars->{pages} = $total/$q->{c};

         }
 
         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
         ++$mon;
         $year += 1900;

         if (!defined($q->{fd}) || $q->{fd} == 0) {$q->{fd} = $mday;}
         if (!defined($q->{fm}) || $q->{fm} == 0) {$q->{fm} = $mon;}
         if (!defined($q->{fy}) || $q->{fy} == 0) {$q->{fy} = $year;}
         if (!defined($q->{fh}) || $q->{fh} == 0) {
            if ($hour - 1 < 0) {
               $q->{fh} = '00';
               $q->{fi} = '00';
            } else {
               $q->{fh} = $hour-1;
            }
         }
         if ((!defined($q->{fi})) && $hour - 1  > 0) {$q->{fi} = $min;}
         if (!defined($q->{fs})) {$q->{fs} = $sec;}

         if (!defined($q->{td}) || $q->{td} == 0) {$q->{td} = $mday;}
         if (!defined($q->{tm}) || $q->{tm} == 0) {$q->{tm} = $mon;}
         if (!defined($q->{ty}) || $q->{ty} == 0) {$q->{ty} = $year;}
         if (!defined($q->{th}) || $q->{th} == 0) {$q->{th} = $hour;}
         if (!defined($q->{ti}) || $q->{ti} == 0) {$q->{ti} = $min;}
         if (!defined($q->{ts}) || $q->{ts} == 0) {$q->{ts} = $sec;}

         $vars->{channels} = $channels;


      } elsif ($q->{page} eq 'guilds') {
         $page = 'guilds';
         $hf = 1;
         $vars->{title} = 52;
         $location = '';


         my $tmp_chars = system::get_all_bind_nick_players_of_server_id( { server_id => $q->{'s'}, }, );
         $vars->{chars} = $tmp_chars->{chars};
         $vars->{num_chars} = $tmp_chars->{count};

         my $no_guild_master;
         my $num_nicks = 0;
         foreach (keys(%{$guilds->{$q->{'s'}}})) {
            my $tmp_nicks = system::get_guild_nicks_by_channel_id_guild_id( { channel_id => $q->{'s'}, guild_id => $_, }, );
            $num_nicks += $tmp_nicks->{count};

            $guilds->{$q->{'s'}}->{$_}->{nicks} = $tmp_nicks->{nicks};
            if (scalar(@{$tmp_nicks->{nicks}}) == 0) {
               push @{$no_guild_master}, $_;
            }
         }

         $vars->{no_guild_master} = $no_guild_master;
         $vars->{num_nicks} = $num_nicks;

         $main::admin_get_server->execute($q->{'s'});
         my $server_info = $main::admin_get_server->fetchrow_hashref();
         $main::admin_get_server->finish();
         $vars->{server_info} = $server_info;

         $vars->{post_title} = $server_info->{server_name};


      } elsif ($q->{page} eq 'show_guild_top') {
         $page = 'show_guild_top';
         $hf = 1;
         $vars->{title} = 53;
         $location = '';

         $vars->{channels_hashref} = $channels_hashref;

         $vars->{post_title} = $guilds->{$q->{channel_id}}->{$q->{guild_id}}->{guild_name}.' @ '.$channels_hashref->{$q->{channel_id}}->{channel_name};



      } elsif ($q->{page} eq 'show_guild') {
         $page = 'show_guild';
         $hf = 0;
         $location = '';

         $vars->{channels_hashref} = $channels_hashref;


      } elsif ($q->{page} eq 'show_guild_nicks') {
         $page = 'show_guild_nicks';
         $hf = 1;
         $vars->{title} = 55;
         $location = '';
         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{extra};

         my $tmp_chars = system::get_all_bind_nick_players_of_server_id( { server_id => $q->{channel_id}, }, );
         $vars->{chars} = $tmp_chars->{chars};

         my $ret_nicks = system::get_guild_nicks_by_channel_id_guild_id( { channel_id => $q->{channel_id}, guild_id => $q->{guild_id}, }, );
         $vars->{nicks} = $ret_nicks->{nicks};

         $vars->{post_title} = $guilds->{$q->{channel_id}}->{$q->{guild_id}}->{guild_name}.' @ '.$channels_hashref->{$q->{channel_id}}->{channel_name};


      } elsif ($q->{page} eq 'ajax_show_profile') {
      
         $hf = 0;
         $contenttype = 'text/xml';
         $page = 'ajax_show_profile';
         
         $main::get_profile->execute($q->{nick_id});
         my $ret_profile = $main::get_profile->fetchrow_hashref();
         $main::get_profile->finish();
         $vars->{profile} = $ret_profile;
#         $vars->{profile}->{icq_status} = system::icq_status($ret_profile->{profile_icq});
                                                                     

      } elsif ($q->{page} eq 'show_profile') {
         $page = 'show_profile';
         $hf = 1;
         $vars->{title} = 56;
         $location = '';
         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{basic};

         $main::get_armory_server_id->execute($q->{'s'});
         my $armory_server_id = $main::get_armory_server_id->fetchrow();
         $main::get_armory_server_id->finish();
         $vars->{armory_server_id} = $armory_server_id;
                                    

         system::add_profile_showed( { nick_id => $q->{nick_id}, to_nick_id => $vars->{nick_id}, }, );

         if (defined($q->{action}) && $q->{action} eq 'save') {
            system::change_nick_user_comment( { message => $q->{comment}, nick_id => $vars->{nick_id}, about_id => $q->{nick_id}, }, );
         }

         $main::get_profile->execute($q->{nick_id});
         my $ret_profile = $main::get_profile->fetchrow_hashref();
         $main::get_profile->finish();
         $vars->{profile} = $ret_profile;
         $vars->{profile}->{icq_status} = system::icq_status($ret_profile->{profile_icq});

         my $ret_nick_user_comment = system::get_nick_user_comment( { nick_id => $vars->{nick_id}, about_id => $q->{nick_id}, }, );
         $vars->{profile}->{comment} = $ret_nick_user_comment->{comment};

         $main::get_chat_rank_position->execute($q->{nick_id},$q->{nick_id},$q->{nick_id});
         my $ret_chat_rank_position = $main::get_chat_rank_position->fetchrow();
         $main::get_chat_rank_position->finish();
         $vars->{chat_rank_position} = $ret_chat_rank_position;

         $main::get_nick_joined_channels->execute($q->{nick_id});
         my $chans = $main::get_nick_joined_channels->fetchall_arrayref({});
         $main::get_nick_joined_channels->finish();
         $vars->{profile}->{channels} = $chans;

         my $ret_nick_renames = system::get_nick_renames( { nick_id => $q->{nick_id}, }, );
         $vars->{profile}->{renames} = $ret_nick_renames->{nicks};

         $vars->{post_title} = $ret_profile->{nick};


#         $main::get_bind_nick_players->{$ret_profile->{guild_server_id}}->execute($q->{nick_id},$ret_profile->{guild_server_id});
#         my $ret_nick_players = $main::get_bind_nick_players->{$ret_profile->{guild_server_id}}->fetchall_arrayref({});
#         $vars->{characters} = $ret_nick_players;
#         $main::get_bind_nick_players->{$ret_profile->{guild_server_id}}->finish();

         my $ret_nick_players;
 #        foreach my $srv (@{$servers}) {
 #           $main::get_bind_nick_players->execute($q->{nick_id},$srv->{server_id});
 #           $ret_nick_players->{$srv->{server_id}} = $main::get_bind_nick_players->fetchall_arrayref({});
 #           $main::get_bind_nick_players->finish();
 #        }

         $vars->{characters} = $ret_nick_players;


         $vars->{blizzard_servers_hash} = $ret_blizzard_servers->{blizzard_servers_hash};
         my $ret_all_nick_blizzard_characters = system::get_all_nick_blizzard_characters( { nick_id => $q->{nick_id}, }, );
         $vars->{blizzard_characters_servers} = $ret_all_nick_blizzard_characters->{blizzard_characters_servers};




         $main::nick_chat_stats->execute($q->{nick_id});
         $main::nick_private_from_stats->execute($q->{nick_id});
         $main::nick_private_to_stats->execute($q->{nick_id});

         $vars->{chat_stats} = $main::nick_chat_stats->fetchrow();
         $vars->{private_from} = $main::nick_private_from_stats->fetchrow();
         $vars->{private_to} = $main::nick_private_to_stats->fetchrow();
         $vars->{channels_hashref} = $channels_hashref;
         $vars->{ranks} = $ranks;

         my $ret_number_of_photoalbums_by_nick_id = system::get_number_of_photoalbums_by_nick_id( { nick_id => $q->{nick_id}, }, );
         $vars->{profile}->{photoalbums} = $ret_number_of_photoalbums_by_nick_id->{number};


         $vars->{profile}->{tickets_stats} = system::get_tickets_stats_by_requestor( { nick_id => $q->{nick_id}, }, );

                                    

      } elsif ($q->{page} eq 'search_item') {
         $page = 'search_item';
         $hf = 1;
         $vars->{title} = 57;
         $location = '';
         $vars->{doctype} = 1;

         if (defined($q->{action}) && $q->{action} eq 'search') {

            if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
            if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 20;} else {$q->{count} = int($q->{count});}

            my $tmp_results = system::search_item( $dbh, { item => $q->{item}, from => $q->{from}, count => $q->{count}, itemclass => $q->{icjs}, itemsubclass => $q->{iscjs}, binds => $q->{binds}, quality => $q->{quality}, level_from => $q->{level_from}, level_to => $q->{level_to}, class => $q->{class}, server_id => $q->{server_id}, } );

#            $main::search_item->execute($q->{item},$q->{item},$q->{from},$q->{count});
#            my $results = $main::search_item->fetchall_arrayref({});
            my $results = $tmp_results->{items};
# ac & 1,2,4,8, 
# perl -e 'print 9 & 1';


            foreach (@{$results}) {
               if ($_->{buyprice} <= 99) {
                  $_->{buy_c} = $_->{buyprice};
               } elsif ($_->{buyprice} > 99 && $_->{buyprice} <= 9999) {
                  $_->{buyprice} =~ m/(\d{1,2})(\d{2})/;
                  $_->{buy_s} = $1;
                  $_->{buy_c} = $2;
               } elsif ($_->{buyprice} > 9999) {
                  $_->{buyprice} =~ m/(\d+)(\d{2})(\d{2})/;
                  $_->{buy_g} = $1;
                  $_->{buy_s} = $2;
                  $_->{buy_c} = $3;
               }

               if ($_->{sellprice} <= 99) {
                  $_->{sell_c} = $_->{sellprice};
               } elsif ($_->{sellprice} > 99 && $_->{sellprice} <= 9999) {
                  $_->{sellprice} =~ m/(\d{1,2})(\d{2})/;
                  $_->{sell_s} = $1;
                  $_->{sell_c} = $2;
               } elsif ($_->{sellprice} > 9999) {
                  $_->{sellprice} =~ m/(\d+)(\d{2})(\d{2})/;
                  $_->{sell_g} = $1;
                  $_->{sell_s} = $2;
                  $_->{sell_c} = $3;
               }
            }

            $vars->{results} = $results;
#            $main::search_item->finish();

#            $main::search_found->execute($q->{item});
#            my $total = $main::search_found->fetchrow();
            $vars->{total} = $tmp_results->{count};
#            $main::search_found->finish();

            $vars->{pages} = $tmp_results->{count}/$q->{count};

            $vars->{itemclass} = $itemclass;
            $vars->{itemclasses} = $itemclasses;
            $vars->{itemsubclass} = $itemsubclass;
            $vars->{itemsubclasses} = $itemsubclasses;
         }

         $vars->{itemclasses} = $itemclasses;
         $vars->{itemsubclass} = $itemsubclass;

         

      } elsif ($q->{page} eq 'show_item') {
         $page = 'show_item';
         $hf = 1;
         $vars->{title} = 58;
         $location = '';
         $vars->{doctype} = 1;

         $main::get_item->execute($q->{itemid});
         my $item = $main::get_item->fetchrow_hashref();

         $vars->{post_title} = $item->{name1};

         if ($item->{buyprice} <= 99) {
            $item->{buy_c} = $item->{buyprice};
         } elsif ($item->{buyprice} > 99 && $item->{buyprice} <= 9999) {
            $item->{buyprice} =~ m/(\d{1,2})(\d{2})/;
            $item->{buy_s} = $1;
            $item->{buy_c} = $2;
         } elsif ($item->{buyprice} > 9999) {
            $item->{buyprice} =~ m/(\d+)(\d{2})(\d{2})/;
            $item->{buy_g} = $1;
            $item->{buy_s} = $2;
            $item->{buy_c} = $3;
         }

         if ($item->{sellprice} <= 99) {
            $item->{sell_c} = $item->{sellprice};
         } elsif ($item->{sellprice} > 99 && $item->{sellprice} <= 9999) {
            $item->{sellprice} =~ m/(\d{1,2})(\d{2})/;
            $item->{sell_s} = $1;
            $item->{sell_c} = $2;
         } elsif ($item->{sellprice} > 9999) {
            $item->{sellprice} =~ m/(\d+)(\d{2})(\d{2})/;
            $item->{sell_g} = $1;
            $item->{sell_s} = $2;
            $item->{sell_c} = $3;
         }


         $vars->{item} = $item;
         $main::get_item->finish(); 

         if ($item->{setid} != 0) {
            $main::get_setitems->execute($item->{setid});
            my $setitems = $main::get_setitems->fetchall_arrayref({});
            $vars->{setitems} = $setitems;
            $main::get_setitems->finish();
         }

#         $main::get_subitems->execute($q->{id});
#         my $subitems = $main::get_subitems->fetchall_arrayref({});
#         $vars->{subitems} = $subitems;
#         $main::get_subitems->finish();


#      } elsif ($q->{page} eq 'map_zone') {
#         $page = 'map_zone';
#         $hf = 1;
#         $vars->{title} = 59;
#         $location = '';
#         $vars->{encoding} = 'windows-1250';


      } elsif ($q->{page} eq 'details_frame') {
         $page = 'details_frame';
         $hf = 0;
         $location = '';


      } elsif ($q->{page} eq 'details_navigation') {
         $page = 'details_navigation';
         $hf = 1;
         $vars->{title} = 61;
         $location = '';

         $vars->{channels} = $channels;

         $main::get_armory_server_id->execute($q->{'s'});
         my $armory_server_id = $main::get_armory_server_id->fetchrow();
         $main::get_armory_server_id->finish();
         $vars->{armory_server_id} = $armory_server_id;
                                    

      } elsif ($q->{page} eq 'details_map_zone') {
         $page = 'details_map_zone';
         $hf = 1;
         $vars->{title} = 62;
         $location = '';

         $main::get_armory_server_id->execute($q->{'s'});
         my $armory_server_id = $main::get_armory_server_id->fetchrow();
         $main::get_armory_server_id->finish();
         $vars->{armory_server_id} = $armory_server_id;

         if (defined($armory_server_id) && $armory_server_id ne '' && $armory_server_id != 0) {

            my $data;
            $main::get_online_players->execute($q->{'s'});
            $data = $main::get_online_players->fetchall_arrayref({});

            my ($num_map_zone_continent,$num_map_zone_instance,$players_map_zone,$players_neutrals,$players_raids,$players_dungeons,$players_others,$players_battlegrounds,$tmp_map_zone,$tmp_map,$continent_zones,$continents,$dungeons,$raids,$neutrals,$others,$battlegrounds,$vs_players);

            foreach my $rec (@{$data}) {
               if ($rec->{bg_type} != 0) {
                  if ($rec->{bg_type} == 2) {$rec->{map} = 489;} #wsg
                  if ($rec->{bg_type} == 3) {$rec->{map} = 529;} #ab
                  if ($rec->{bg_type} == 1) {$rec->{map} = 30;} #av
                  if ($rec->{bg_type} == 7) {$rec->{map} = 566;} #eots
               }
               if (!defined($rec->{nick_id})) {$rec->{nick_id} = 0;}
               if ($rec->{map} == 609) {$rec->{map} = 0;}

               if ($rec->{map} == 0 || $rec->{map} == 1 || $rec->{map} == 530 || $rec->{map} == 571) { # old continent, bc, wotlk
                  if (!defined($tmp_map_zone->{$rec->{map}}->{$rec->{zone}})) {
                     $tmp_map_zone->{$rec->{map}}->{$rec->{zone}} = 1;
                     push @{$continent_zones->{$rec->{map}}},$rec->{zone};
                  }
                  if (!defined($tmp_map->{$rec->{map}})) {
                     $tmp_map->{$rec->{map}} = 1;
                     push @{$continents},$rec->{map};
                  }

                  ++$num_map_zone_continent->{$rec->{map}}->{$rec->{zone}};
                  push @{$players_map_zone->{$rec->{map}}->{$rec->{zone}}}, $rec;

               } else {

                  ++$num_map_zone_instance->{$rec->{map}};

                  if ($maps->{$rec->{map}}->{dungeon} == 1) {
                     if (!defined($tmp_map->{$rec->{map}})) {
                        $tmp_map->{$rec->{map}} = 1;
                        push @{$dungeons},$rec->{map};
                     }
                     push @{$players_dungeons->{$rec->{map}}->{$rec->{instance}}}, $rec;

                  } elsif ($maps->{$rec->{map}}->{dungeon} == 2) {
                     if (!defined($tmp_map->{$rec->{map}})) {
                        $tmp_map->{$rec->{map}} = 1;
                        push @{$raids},$rec->{map};
                     }
                     push @{$players_raids->{$rec->{map}}->{$rec->{instance}}}, $rec;

                  } elsif ($maps->{$rec->{map}}->{dungeon} == 3) {
                     if (!defined($tmp_map->{$rec->{map}})) {
                        $tmp_map->{$rec->{map}} = 1;
                        push @{$neutrals},$rec->{map};
                     }
                     push @{$players_neutrals->{$rec->{map}}->{$rec->{instance}}}, $rec;

                  } elsif ($maps->{$rec->{map}}->{dungeon} == 4) {

                     if (!defined($tmp_map->{$rec->{map}})) {
                        $tmp_map->{$rec->{map}} = 1;
                        push @{$battlegrounds},$rec->{map};
                     }


                    my $range = 0;
if ( $rec->{map} == 489 && ($rec->{level} >= 10 && $rec->{level} <= 19)) {$range = '10-19';	# wsg
} elsif ($rec->{map} == 489 && ($rec->{level} >= 20 && $rec->{level} <= 29)) {$range = '20-29';
} elsif ($rec->{map} == 489 && ($rec->{level} >= 30 && $rec->{level} <= 39)) {$range = '30-39';
} elsif ($rec->{map} == 489 && ($rec->{level} >= 40 && $rec->{level} <= 49)) {$range = '40-49';
} elsif ($rec->{map} == 489 && ($rec->{level} >= 50 && $rec->{level} <= 59)) {$range = '50-59';
} elsif ($rec->{map} == 489 && ($rec->{level} >= 60 && $rec->{level} <= 69)) {$range = '60-69';
} elsif ($rec->{map} == 489 && ($rec->{level} >= 70 && $rec->{level} <= 79)) {$range = '70-79';
} elsif ($rec->{map} == 489 && $rec->{level} == 80) {$range = '80';

} elsif ($rec->{map} == 529 && ($rec->{level} >= 20 && $rec->{level} <= 29)) {$range = '20-29';	# ab
} elsif ($rec->{map} == 529 && ($rec->{level} >= 30 && $rec->{level} <= 39)) {$range = '30-39';
} elsif ($rec->{map} == 529 && ($rec->{level} >= 40 && $rec->{level} <= 49)) {$range = '40-49';
} elsif ($rec->{map} == 529 && ($rec->{level} >= 50 && $rec->{level} <= 59)) {$range = '50-59';
} elsif ($rec->{map} == 529 && ($rec->{level} >= 60 && $rec->{level} <= 69)) {$range = '60-69';
} elsif ($rec->{map} == 529 && ($rec->{level} >= 70 && $rec->{level} <= 79)) {$range = '70-79';
} elsif ($rec->{map} == 529 && $rec->{level} == 80) {$range = '80';

} elsif ($rec->{map} == 30 && ($rec->{level} >= 51 && $rec->{level} <= 60)) {$range = '51-60';	# av
} elsif ($rec->{map} == 30 && ($rec->{level} >= 61 && $rec->{level} <= 70)) {$range = '61-70';
} elsif ($rec->{map} == 30 && ($rec->{level} >= 71 && $rec->{level} <= 80)) {$range = '71-80';

} elsif ($rec->{map} == 566 && ($rec->{level} >= 61 && $rec->{level} <= 69)) {$range = '61-69';	# eots
} elsif ($rec->{map} == 566 && ($rec->{level} >= 70 && $rec->{level} <= 79)) {$range = '70-79';
} elsif ($rec->{map} == 566 && ($rec->{level} == 80)) {$range = '80';

}

                     push @{$players_battlegrounds->{$rec->{map}}->{$range}->{$rec->{instance}}}, $rec;
                     if ($rec->{race} == 1 || $rec->{race} == 3 || $rec->{race} == 4 || $rec->{race} == 7 || $rec->{race} == 11) {
                        ++$vs_players->{$rec->{map}}->{$range}->{$rec->{instance}}->{a};
                     } else {
                        ++$vs_players->{$rec->{map}}->{$range}->{$rec->{instance}}->{h};
                     }






                  } else {
                     if (!defined($tmp_map->{$rec->{map}})) {
                        $tmp_map->{$rec->{map}} = 1;
                        push @{$others},$rec->{map};
                     }
                     push @{$players_others->{$rec->{map}}->{$rec->{instance}}}, $rec;
                  }

               }

            }

            $vars->{num_map_zone_continent} = $num_map_zone_continent;
            $vars->{num_map_zone_instance} = $num_map_zone_instance;
            $vars->{players_map_zone} = $players_map_zone;
            $vars->{players_dungeons} = $players_dungeons;
            $vars->{players_raids} = $players_raids;
            $vars->{players_neutrals} = $players_neutrals;
            $vars->{players_others} = $players_others;
            $vars->{players_battlegrounds} = $players_battlegrounds;
            $vars->{continent_zones} = $continent_zones;
            $vars->{continents} = $continents;
            $vars->{dungeons} = $dungeons;
            $vars->{others} = $others;
            $vars->{raids} = $raids;
            $vars->{neutrals} = $neutrals;
            $vars->{battlegrounds} = $battlegrounds;
            $vars->{maps} = $maps;
            $vars->{zones} = $zones;
            $vars->{data} = $data;
            $vars->{maps_zones} = $maps_zones;
            $vars->{vs_players} = $vs_players;
         }

      } elsif ($q->{page} eq 'details_races') {
         $page = 'details_races';
         $hf = 1;
         $vars->{title} = 63;
         $location = '';

         my $data;
         $main::get_online_players->execute($q->{'s'});
         $data = $main::get_online_players->fetchall_arrayref({});

         my $the_race;

         foreach my $rec (@{$data}) {
            push @{$the_race->{$rec->{race}}}, $rec;
         }

         $vars->{the_race} = $the_race;
         $vars->{data} = $data;


      } elsif ($q->{page} eq 'details_classes') {
         $page = 'details_classes';
         $hf = 1;
         $vars->{title} = 64;
         $location = '';

         my $data;
         $main::get_online_players->execute($q->{'s'});
         $data = $main::get_online_players->fetchall_arrayref({});

         my $the_class;

         foreach my $rec (@{$data}) {
            if ($rec->{race} == 1 || $rec->{race} == 3 || $rec->{race} == 4 || $rec->{race} == 7 || $rec->{race} == 11 ) {
               push @{$the_class->{$rec->{class}}->{a}}, $rec;
            } else {
               push @{$the_class->{$rec->{class}}->{h}}, $rec;
            }
         }

         $vars->{the_class} = $the_class;
         $vars->{data} = $data;


      } elsif ($q->{page} eq 'details_levels') {
         $page = 'details_levels';
         $hf = 1;
         $vars->{title} = 65;
         $location = '';

         my $data;
         $main::get_online_players->execute($q->{'s'});
         $data = $main::get_online_players->fetchall_arrayref({});

         my $the_level;

         foreach my $rec (@{$data}) {
#            push @{$the_level->{$rec->{level}}}, $rec;

            if ($rec->{race} == 1 || $rec->{race} == 3 || $rec->{race} == 4 || $rec->{race} == 7 || $rec->{race} == 11 ) {
              push @{$the_level->{$rec->{level}}->{a}}, $rec;
            } else {
              push @{$the_level->{$rec->{level}}->{h}}, $rec;
            }
                                                                  
         }

         $vars->{the_level} = $the_level;
         $vars->{data} = $data;

      } elsif ($q->{page} eq 'details_guilds') {
         $page = 'details_guilds';
         $hf = 1;
         $vars->{title} = 66;
         $location = '';

         my $data;
         $main::get_online_players->execute($q->{'s'});
         $data = $main::get_online_players->fetchall_arrayref({});

         my $the_guild;

         foreach my $rec (@{$data}) {
            push @{$the_guild->{$rec->{guild_id}}}, $rec;
         }

         $vars->{the_guild} = $the_guild;
         $vars->{data} = $data;

      } elsif ($q->{page} eq 'details_skills') {
         $page = 'details_skills';
         $hf = 1;
         $vars->{title} = 67;
         $location = '';

         my $data;
#         $main::get_online_players_skills->execute($q->{'s'});
#         $data = $main::get_online_players_skills->fetchall_arrayref({});

         my $the_skill;

         foreach my $rec (@{$data}) {
            push @{$the_skill->{$rec->{skill_id}}}, $rec;
         }

         $vars->{the_skill} = $the_skill;
         $vars->{data} = $data;
         $vars->{skills} = $skills_array;


      } elsif ($q->{page} eq 'account_state') {
         $page = 'account_state';
         $hf = 1;
         $vars->{title} = 68;
         $location = '';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';


=cut
      } elsif ($q->{page} eq 'account_state') {
         $page = 'account_state';
         $hf = 1;
         $vars->{title} = 68;
         $location = '';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';

         if (!defined($q->{'s'}) || $q->{'s'} !~ /^\d+$/) {
            $q->{'s'} = 1;
         }

         $main::admin_get_server->execute($q->{'s'});
         my $server_info = $main::admin_get_server->fetchrow_hashref();
         $main::admin_get_server->finish();
         $vars->{server_info} = $server_info;

         $vars->{post_title} = $server_info->{server_name};

         if (defined($q->{action}) && $q->{action} eq 'email') {

            $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
            my $account_data = $main::get_game_account_state_by_id->fetchrow_hashref();

            my $md5 = Digest::MD5->new;
            $md5->add($account_data->{login});
            $md5->add($account_data->{email});
            $md5->add($account_data->{id});
            $md5->add('mega coder SoCo');
            my $hash = $md5->hexdigest;


            my $msg = MIME::Lite->new(
			From			=> 'WebAccountActivation',
			To			=> $account_data->{email},
			Subject			=> 'Overenie E-mailovej adresy [2] (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
                        'Auto-Submitted:'	=> 'auto-generated',
                        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> 'Tento mail Vam bol odoslany na zaklade ziadosti (z IP adresy '.$ENV{REMOTE_ADDR}.') o opatovane zaslanie kontrolnej URL adresy '.$globals::misc_path.'?page=confirm_email&hex='.$hash.'&id='.$account_data->{id}.'&s='.$q->{'s'}.' na ktoru musite kliknut a tym potvrdit, ze tato E-mailova adresa patri Vam.'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
            );

            $msg->send;
            $vars->{account_state} = $account_data;
            $vars->{message} = 1;

         } elsif (defined($q->{action}) && $q->{action} eq 'delete') {
            $main::del_game_account_by_everything->execute($q->{id},$q->{login},$q->{email},$q->{'s'});
            $vars->{message} = 2;

            $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
            $vars->{account_state} = $main::get_game_account_state_by_id->fetchrow_hashref();


         } elsif (defined($q->{action}) && $q->{action} eq 'search') {


            my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');

#warn $server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login';
#warn $ret_wget->{content};

warn " $ret_wget->{content}";

            if ($ret_wget->{content} =~ /^([^0]\d*)\|([\d_]+)$/) {
               my $account_id = $1;
               my $version = $2;



               my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&action=get_gmlevel_by_username');
               $ret_wget->{content} =~ m/^(\d)\|(\d)\|(\d)\|(.*)\|(\d)\|(\d)$/;
               my $gmlevel = $1;
               my $vip = $2;
               my $locked = $3;
               my $last_ip = $4;
               my $expansion = $5;
               my $banned = $6;

               $vars->{version} = $version;
               $vars->{vip} = $vip;
               $vars->{locked} = $locked;
               $vars->{last_ip} = $last_ip;
               $vars->{expansion} = $expansion;
               $vars->{banned} = $banned;


               if (defined($q->{what}) && $q->{what} eq 'change_password') {

                  my $errors = [];

                  if (length($q->{new_password1}) < 4) {push @${errors},'1';}
                  if (similarity (lc $q->{login}, lc $q->{new_password1}) > 0.75) {push @${errors},'2';}
                  if ($q->{new_password1} ne $q->{new_password2}) {push @${errors},'3';}


                  if (scalar(@${errors}) == 0) {

                     $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
                     my $account_state = $main::get_game_account_state_by_id->fetchrow_hashref();


                     my $ret_wget = system::wget($server_info->{activations_url}.'?action=set_password_by_user_and_email&login='.$q->{login}.'&email='.$account_state->{email}.'&password='.$q->{new_password1});

                     if ($ret_wget->{state} == 0) {
                        push @${errors},'4';
                     } else {
                        if ($ret_wget->{content} =~ /^1$/) {



                           my $hash = md5_hex($q->{new_password1});
                           $main::set_game_account_password->execute($hash,$q->{new_password1},$q->{id},$q->{'s'});

                           my $msg = MIME::Lite->new(
					From			=> 'WebAccountRecovery',
					To			=> $account_state->{email},
					Subject			=> 'Vygenerovanie noveho hesla (Automaticky generovany E-mail)',
					Type			=> 'text/plain',
					'Auto-Submitted:'	=> 'auto-generated',
					'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
					Data			=> 'Tento mail Vam bol odoslany na zaklade odoslania formularu so ziadostou o zmenu hesla pre pristup na '.$server_info->{server_name}.' WoW (z IP adresy '.$ENV{REMOTE_ADDR}.')'."\n\n".'Nove heslo je: '.$q->{new_password1}."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                           );

                           $main::log_game_account_data_change->execute($q->{id},$q->{'s'},$ENV{REMOTE_ADDR},'password',$q->{new_password1});
                           
                           $msg->send;

                           $vars->{ec2} = 1;

                        } else {
                           push @${errors},'5';
                        }
                     }
                  }

                  $vars->{errors2} = $errors;


               } elsif (defined($q->{what}) && $q->{what} eq 'send_invitation') {

                  my $level_enough = 0;

                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&action=get_account_characters');
                  if ($ret_wget->{content} =~ /^0$/) {

                  } else {
                     my $tmp;

                     @{$tmp} = split(/\n/,$ret_wget->{content});
                     my $characters;
                     foreach (@{$tmp}) {
                        my ($guid,$name,$race,$class,$level,$online,$backuped,$backup_version) = split(/\|/,$_);
                        push @{$characters}, { guid => $guid, name => $name, race => $race, class => $class, level => $level, online => $online, backuped => $backuped, backup_version => $backup_version };
                        if ($level >= 55) {$level_enough = 1;}
                     }
                  }

                  if ($level_enough == 1 && $banned != 1) {

                     my $errors;

                     $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
                     my $account_data = $main::get_game_account_state_by_id->fetchrow_hashref();
                        
                     my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=set_email_by_user_and_password&email='.$account_data->{email});

                     if ($ret_wget->{content} =~ /^1$/) {
                        $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                        my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();

                        $main::create_invitation->execute();
                        my $invitation_id = $main::create_invitation->{mysql_insertid};


                        my $md5 = Digest::MD5->new;
                        $md5->add(lc($q->{'login'}));
                        $md5->add($invitation_id);
                        $md5->add($game_account_state->{id});
                        $md5->add('invite');
                        $md5->add('mega coder SoCo');
                        my $hash = $md5->hexdigest;

                        $main::update_invitation->execute($hash,$game_account_state->{'id'},$q->{'s'},lc($q->{'login'}),undef,undef,$q->{'invite_email'},$invitation_id);


                        my $msg = MIME::Lite->new(
				From			=> 'WebAccountInvitation',
				To			=> $q->{invite_email},
				Subject			=> 'Pozvanka na '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade pozvania uzivatela serveru.'."\n\n".'ID Vasej pozvanky je: '.uc($hash)."\n\n".'Zaregistrovat sa mozete kliknutim na: '.$globals::misc_path.'?page=game_account&invitation='.uc($hash).'&s='.$q->{'s'}.' alebo neskor '.$globals::misc_path.'?page=game_account&s='.$q->{'s'}.' a vpisanim ID pozvanky do prislusneho policka.'."\n".'Ak neplanujete hrat na serveri '.$server_info->{server_name}.', povazujte tento E-mail za bezpredmetny'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                        );
                        $msg->send;

                        $vars->{ec7} = 1;
                     } else {
                        push @${errors},'1';
                     }
                                       
                     $vars->{errors7} = $errors;


                  }

               } elsif (defined($q->{what}) && $q->{what} eq 'unlock') {

                  my $errors;

                  $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
                  my $account_data = $main::get_game_account_state_by_id->fetchrow_hashref();
                        
                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=set_email_by_user_and_password&email='.$account_data->{email});

                  if ($ret_wget->{content} =~ /^1$/) {
                     $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                     my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();

                     my $md5 = Digest::MD5->new;
                     $md5->add(lc($q->{login}));
                     $md5->add(lc($game_account_state->{email}));
                     $md5->add($game_account_state->{id});
                     $md5->add('unlock');
                     $md5->add('mega coder SoCo');
                     my $hash = $md5->hexdigest;

                     if (!defined($game_account_state->{email}) || $game_account_state->{email} eq '') {

                        $vars->{hash} = $hash;
                        $vars->{ec5} = 3;

#c_path.'?page=confirm_new_email&hex='.$hash.'&new_email='.$q->{new_email}.'&id='.$game_account_state->{id}.'&s='.$q->{'s'}.

                     } else {

                        my $msg = MIME::Lite->new(
				From			=> 'WebAccountUnlock',
				To			=> $game_account_state->{email},
				Subject			=> 'Odomknutie herneho uctu na '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade ziadosti (z IP adresy '.$ENV{REMOTE_ADDR}.') o odomknutie pristupu k hernemu uctu.'."\n\n".'Login: '.$q->{login}."\n\n".'Aby bol ucet odomknuty, musite kliknut na nasledovnu URL adresu: '.$globals::misc_path.'?page=confirm_unlock&hex='.$hash.'&id='.$game_account_state->{id}.'&s='.$q->{'s'}."\n".'Ak ste o odomknutie herneho uctu neziadali Vy, kontaktujte urychlene GM alebo spravcu servera'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                        );
                        $msg->send;

                        $vars->{ec5} = 1;
                     }
                  } else {
                     push @${errors},'1';
                  }
                                       
                  $vars->{errors5} = $errors;
                                                         
                                                         

               } elsif (defined($q->{what}) && $q->{what} eq 'change_data') {

                  my $errors;

                  $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
                  my $account_data = $main::get_game_account_state_by_id->fetchrow_hashref();
                        
                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=set_email_by_user_and_password&email='.$account_data->{email});

                  if ($ret_wget->{content} =~ /^1$/) {
                     $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                     my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();


                     $main::get_game_account_additional_data->execute($q->{'s'},$q->{id});
                     my $game_account_data = $main::get_game_account_additional_data->fetchrow_hashref();
                     foreach ('email','chat_nick','forum_nick','name','surname','address','phone') {
                        if ($game_account_data->{$_} ne $q->{$_}) {
                           $main::log_game_account_data_change->execute($q->{id},$q->{'s'},$ENV{REMOTE_ADDR},$_,$q->{$_});
                        }
                     }

#                     $main::set_game_account_data->execute($q->{email},$q->{chat_nick},$q->{forum_nick},$q->{name},$q->{surname},$q->{address},$q->{phone},$q->{id},$q->{'s'});
                     $main::set_game_account_data->execute($game_account_state->{email},$q->{chat_nick},$q->{forum_nick},$q->{name},$q->{surname},$q->{address},$q->{phone},$q->{id},$q->{'s'});


                     my $msg = MIME::Lite->new(
				From			=> 'WebAccountActivation',
				To			=> $game_account_state->{email},
				Subject			=> 'Zmena udajov k hernemu uctu '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade ziadosti (z IP adresy '.$ENV{REMOTE_ADDR}.') o zmenu udajov o vlastnikovi herneho uctu.'."\n\n".'Email: '.$q->{email}."\n".'Chat nick: '.$q->{chat_nick}."\n".'Forum nick '.$q->{forum_nick}."\n".'Meno: '.$q->{name}."\n".'Priezvisko: '.$q->{surname}."\n".'Adresa: '.$q->{address}."\n".'Telefon: '.$q->{phone}."\n\n".'Ak ste tieto udaje nemenili Vy, kontaktujte urychlene GM alebo spravcu servera'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                     );
                     $msg->send;

                     


                     $vars->{ec1} = 1;

                  } else {
                     
                     push @${errors},'1';

                  }

                  $vars->{errors1} = $errors;


               } elsif (defined($q->{what}) && $q->{what} eq 'delete_account_data') {

                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=delete_account_data_by_login_and_password');







               } elsif (defined($q->{what}) && $q->{what} eq 'chartrader_setup') {

#                  my $characters_hash;

#                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&action=get_account_characters');
#                  if ($ret_wget->{content} =~ /^0$/) {

#                  } else {
#                     my $tmp;

#                     @{$tmp} = split(/\n/,$ret_wget->{content});
#                     my $characters;

#                     foreach (@{$tmp}) {
#                        my ($guid,$name,$race,$class,$level,$online,$backuped,$backup_version) = split(/\|/,$_);
#                        push @{$characters}, { guid => $guid, name => $name, race => $race, class => $class, level => $level, online => $online, backuped => $backuped, backup_version => $backup_version };
#                        $characters_hash->{$guid} = {name => $name, race => $race, class => $class, level => $level,};
#warn "guid => $guid, name => $name, race => $race, class => $class, level => $level, online => $online, backuped => $backuped, backup_version => $backup_version";

#                        if ($level >= 55) {$level_enough = 1;}
#                     }
#                      $vars->{characters} = $characters;
#                     $vars->{characters_hash} = $characters_hash;
#                  }
#                  $vars->{level_enough} = $level_enough;



                  $main::get_game_account_trade_offers->execute($q->{'s'},$account_id);
                  my $chartrader_offers = $main::get_game_account_trade_offers->fetchall_arrayref({});
                  foreach (@{$chartrader_offers}) {

                     if ($_->{state} == 0) {	# nenastavene
                        if ($q->{'action_'.$_->{char_guid}} == 1) {
                           # zaradit do db
                           $main::set_game_account_trade_state->execute(1,$q->{'s'},$account_id,$_->{char_guid});

                        } elsif ($q->{'action_'.$_->{char_guid}} == 2) {
                           $main::del_game_account_trade->execute($q->{'s'},$account_id,$_->{char_guid});
                           # zrusit z traderu
                        }
                        # save zmien

                        my $new_class = $q->{'new_class_'.$_->{char_guid}};

                        if (ref($new_class) ne 'ARRAY') {$new_class = [$new_class];}
                        
                        
                        my $map_class_id_to_mask = {
				'1' => 1,
			        '2' => 2,
			        '3' => 4,
			        '4' => 8,
			        '5' => 16,
			        '6' => 32,
			        '7' => 64,
			        '8' => 128,
			        '9' => 256,
			        '11' => 1024,
                        };

                        my $new_class_mask = 0;
                        foreach (@{$new_class}) {
                           if ($_ == 0) {$new_class_mask = 0; last;}
                           $new_class_mask += $map_class_id_to_mask->{$_};
                        }

                        $main::set_game_account_trade->execute($q->{'new_faction_'.$_->{char_guid}},$new_class_mask,$q->{'s'},$account_id,$_->{char_guid});

                     } elsif ($_->{state} == 1) {

                        if ($q->{'action_'.$_->{char_guid}} == 3) {
                           # zmazat z db
                           $main::del_game_account_trade->execute($q->{'s'},$account_id,$_->{char_guid});
                        } elsif ($q->{'action_'.$_->{char_guid}} == 4) {
                           # zmenit parametre
                           $main::set_game_account_trade_state->execute(0,$q->{'s'},$account_id,$_->{char_guid});
                        }

                     } elsif ($_->{state} == 2) {
                        if ($q->{'action_'.$_->{char_guid}} == 5) {
                           # zamietnut
                        } elsif ($q->{'action_'.$_->{char_guid}} == 6) {
                           # prijat
                        }

                     }

                  }
                  $main::get_game_account_trade_offers->finish();








               } elsif (defined($q->{what}) && $q->{what} eq 'reset_position') {

                  my $errors;

                  if ($q->{reset_id} =~ /^\d+$/) {

                     if ($q->{'butt'} eq 'Resetnut poziciu') {
                    
                        my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&action=reset_starting_position&guid='.$q->{reset_id});
                        if ($ret_wget->{content} =~ /^1$/) {
                           $vars->{ec3} = 1;
                        } else {
                           push @{$errors},'1';
                        }
                     } elsif ($q->{'butt'} eq 'Zalohovat') {

                        my $ret_wget = system::wget($server_info->{activations_url}.'?action=backup_character&login='.$q->{login}.'&password='.$q->{password}.'&guid='.$q->{reset_id});
                        if ($ret_wget->{content} =~ /^1$/) {
                           $vars->{ec3} = 2;
                        } else {
                           push @{$errors},'3';
                        }

                     } elsif ($q->{'butt'} eq 'Chartrader') {



                        $main::is_game_account_in_trade_offers->execute($q->{'s'},$account_id,$q->{reset_id});
                        if ($main::is_game_account_in_trade_offers->rows() == 0 ) {
                           $main::add_game_account_trade->execute($q->{'s'},$account_id,$q->{reset_id});
                        }
                        $main::is_game_account_in_trade_offers->finish();



                     }

                  } else {
                     push @{$errors},'2';
                  }
                  $vars->{errors3} = $errors;

               } elsif (defined($q->{what}) && $q->{what} eq 'change_email') {

                  my $errors = [];



                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');


                  if ($ret_wget->{content} =~ /^[^0]\d*\|.+$/) {


                     if ($q->{new_email} =~ /^.+\@(.+)$/) {
                        my $res = Net::DNS::Resolver->new;
                        my @mx = mx($res, $1);
                        if (!@mx) {push @${errors},'4';}
                     } else {
                        push @${errors},'3';
                     }
                                   
                     $main::is_game_email_used->execute($q->{new_email},$q->{'s'});
                     if ($main::is_game_email_used->rows() != 0) {push @{$errors},'5';}
                     $main::is_game_email_used->finish();
                                                                                                                     
                     if (scalar(@{$errors}) == 0) {

                        $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                        my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();

                        my $md5 = Digest::MD5->new;
                        $md5->add(lc($q->{login}));
                        $md5->add(lc($game_account_state->{email}));
                        $md5->add($game_account_state->{id});
                        $md5->add(lc($q->{new_email}));
                        $md5->add('mega coder SoCo');
                        my $hash = $md5->hexdigest;

                        if (!defined($game_account_state->{email}) || $game_account_state->{email} eq '') {

                        $vars->{hash} = $hash;
                        $vars->{ec4} = 3;

#c_path.'?page=confirm_new_email&hex='.$hash.'&new_email='.$q->{new_email}.'&id='.$game_account_state->{id}.'&s='.$q->{'s'}.

                        } else {

                           my $msg = MIME::Lite->new(
				From			=> 'WebAccountActivation',
				To			=> $game_account_state->{email},
				Subject			=> 'Zmena E-mailu k hernemu uctu '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade ziadosti (z IP adresy '.$ENV{REMOTE_ADDR}.') o zmenu E-mailovej adresy k herneho uctu.'."\n\n".'Login: '.$q->{login}."\n".'Povodny E-mail: '.$game_account_state->{email}."\n\n".'Novy E-mail: '.$q->{new_email}."\n\n".'Aby bola E-mailova adresa zmenena, musite kliknut na nasledovnu URL adresu: '.$globals::misc_path.'?page=confirm_new_email&hex='.$hash.'&new_email='.$q->{new_email}.'&id='.$game_account_state->{id}.'&s='.$q->{'s'}."\n".'Ak ste o zmenu E-mailovej adresy neziadali Vy, kontaktujte urychlene GM alebo spravcu servera'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                           );
                           $msg->send;

                           $vars->{ec4} = 1;
                        }            

                     }

                  } else {
                     
                     push @${errors},'1';

                  }

                  $vars->{errors4} = $errors;




               } elsif (defined($q->{what}) && $q->{what} eq 'change_expansion') {

                  my $errors;

                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');
                  if ($ret_wget->{content} =~ /^[^0]\d*\|.+$/) {

#                     if ($vip == 1 && $q->{expansion} == 2) {
                        my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&expansion='.$q->{expansion}.'&action=set_expansion_by_username');
                        $vars->{ec6} = 1;
#                     } else {
#                        push @${errors},'2';
#                     }
                     
                     $vars->{expansion} = $q->{expansion};

                  } else {
                     push @${errors},'1';
                  }

                  $vars->{errors6} = $errors;          



               } elsif (defined($q->{what}) && $q->{what} eq 'change_email_finish') {

                  my $errors;

                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');


                  if ($ret_wget->{content} =~ /^[^0]\d*\|.+$/) {
                     $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                     my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();


                     my $md5 = Digest::MD5->new;
                     $md5->add(lc($q->{login}));
                     $md5->add(lc($game_account_state->{email}));
                     $md5->add($game_account_state->{id});
                     $md5->add(lc($q->{new_email}));
                     $md5->add('mega coder SoCo');
                     my $hash = $md5->hexdigest;

                     if ($q->{hex} eq $hash) {

                        my $msg = MIME::Lite->new(
				From			=> 'WebAccountActivation',
				To			=> $game_account_state->{email},
				Subject			=> 'Zmena E-mailu k hernemu uctu '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Emailova adresa k uctu: "'.$q->{login}.'" bola uspesne zmenena'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                        );
                        $msg->send;

                     
                        my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=set_email_by_user_and_password&email='.$q->{new_email});
                        $main::set_game_account_email->execute($q->{new_email},$game_account_state->{id},$q->{'s'});
                        $main::log_game_account_data_change->execute($game_account_state->{id},$q->{'s'},$ENV{REMOTE_ADDR},'email',$q->{new_email});


                        $vars->{ec4} = 2;
                     } else {
                        push @${errors},'2';
                     }

                  } else {
                     
                     push @${errors},'1';

                  }

                  $vars->{errors4} = $errors;


               } elsif (defined($q->{what}) && $q->{what} eq 'unlock_finish') {

                  my $errors;

                  my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=check_by_password_and_login');


                  if ($ret_wget->{content} =~ /^[^0]\d*\|.+$/) {
                     $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
                     my $game_account_state = $main::get_game_account_state_by_login->fetchrow_hashref();


                     my $md5 = Digest::MD5->new;
                     $md5->add(lc($q->{login}));
                     $md5->add(lc($game_account_state->{email}));
                     $md5->add($game_account_state->{id});
                     $md5->add('unlock');
                     $md5->add('mega coder SoCo');
                     my $hash = $md5->hexdigest;

                     if ($q->{hex} eq $hash) {

                        my $msg = MIME::Lite->new(
				From			=> 'WebAccountUnlock',
				To			=> $game_account_state->{email},
				Subject			=> 'Odomknutie herneho uctu na '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
        	                'Auto-Submitted:'	=> 'auto-generated',
                	        'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Herny ucet "'.$q->{login}.'" bol uspesne odomknuty'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                        );
                        $msg->send;

                     
                        my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&password='.$q->{password}.'&action=unlock_account_by_login_and_password');


                        $vars->{ec5} = 2;
                     } else {
                        push @${errors},'2';
                     }

                  } else {
                     
                     push @${errors},'1';

                  }

                  $vars->{errors5} = $errors;



               }



               $main::get_invitation_state_by_login->execute($vip,$vip,$q->{login},$q->{'s'});
               my $invite_state = $main::get_invitation_state_by_login->fetchrow_hashref();
               $vars->{invite_state} = $invite_state;

               if ($invite_state->{do_reset} == 1) {
                  $main::reset_invitation_state_by_login->execute($q->{login},$q->{'s'});
               }



               $main::get_game_account_state_by_login->execute($q->{login},$q->{'s'});
               my $account_state = $main::get_game_account_state_by_login->fetchrow_hashref();
               $account_state->{email} =~ m/^(.).*?(\@.+)$/;
               $account_state->{masked_email} = $1.'...'.$2;
                                          
               $vars->{account_state} = $account_state;

               $main::get_game_account_accesses->execute($account_id);
               my $accesses = $main::get_game_account_accesses->fetchall_arrayref({});
               $vars->{accesses} = $accesses;
               $main::get_game_account_accesses->finish();               




               my $md5 = Digest::MD5->new;
               $md5->add($q->{login});
               $md5->add($q->{password});
               $md5->add($vars->{account_state}->{id});
               $md5->add('mega coder SoCo');
               my $hash = $md5->hexdigest;

               $vars->{passwd_hash} = $hash;

               my $level_enough = 0;
               my $characters_hash;

               my $ret_wget = system::wget($server_info->{activations_url}.'?login='.$q->{login}.'&action=get_account_characters');
               if ($ret_wget->{content} =~ /^0$/) {

               } else {
                  my $tmp;

                  @{$tmp} = split(/\n/,$ret_wget->{content});
                  my $characters;

                  foreach (@{$tmp}) {
                     my ($guid,$name,$race,$class,$level,$online,$backuped,$backup_version) = split(/\|/,$_);
                     push @{$characters}, { guid => $guid, name => $name, race => $race, class => $class, level => $level, online => $online, backuped => $backuped, backup_version => $backup_version };
                     $characters_hash->{$guid} = {name => $name, race => $race, class => $class, level => $level,};
warn "guid => $guid, name => $name, race => $race, class => $class, level => $level, online => $online, backuped => $backuped, backup_version => $backup_version";

                     if ($level >= 55) {$level_enough = 1;}
                  }
                  $vars->{characters} = $characters;
                  $vars->{characters_hash} = $characters_hash;
               }
               $vars->{level_enough} = $level_enough;




               my $map_class_mask_to_id = {
			'1' => 1,
			'2' => 2,
			'4' => 3,
			'8' => 4,
			'16' => 5,
			'32' => 6,
			'64' => 7,
			'128' => 8,
			'256' => 9,
			'1024' => 11,
               };


               my $traded_char;
               $main::get_game_account_trade_offers->execute($q->{'s'},$account_id);
               my $chartrader_offers = $main::get_game_account_trade_offers->fetchall_arrayref({});
               foreach (@{$chartrader_offers}) {
                  $_->{char} = $characters_hash->{$_->{char_guid}};
                  $traded_char->{$_->{char_guid}} = 1;

                  if ($_->{new_class} != 0) {
                     my $tmp_classes;
                     foreach my $class_mask (keys(%{$map_class_mask_to_id})) {
                        if ($_->{new_class} & $class_mask) {
                           $tmp_classes->{$map_class_mask_to_id->{$class_mask}} = 1;
                        }
                     }
                     $_->{new_class} = $tmp_classes;
                  } else {
                     my $tmp_classes;
                     $tmp_classes->{'0'} = 1;
                     $_->{new_class} = $tmp_classes;
                  }

               }
               $main::get_game_account_trade_offers->finish();
               $vars->{chartrader_offers} = $chartrader_offers;
               $vars->{traded_char} = $traded_char;

            }

         }

      } elsif ($q->{page} eq 'confirm_unlock') {
         $hf = 1;
         $vars->{title} = 69;
         $location = '';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';

         $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
         my $game_account = $main::get_game_account_state_by_id->fetchrow_hashref();
         $main::get_game_account_state_by_id->finish();


         my $md5 = Digest::MD5->new;

         $md5->add(lc($game_account->{login}));
         $md5->add(lc($game_account->{email}));
         $md5->add($game_account->{id});
         $md5->add('unlock');
         $md5->add('mega coder SoCo');
         my $hash = $md5->hexdigest;

         if ($hash eq $q->{hex}) {

            $vars->{game_account} = $game_account;

            $page = 'confirm_unlock_ok';
         } else {
            $page = 'confirm_unlock_bad';
         }

=cut

      } elsif ($q->{page} eq 'confirm_new_email') {
         $hf = 1;
         $vars->{title} = 69;
         $location = '';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';

         $main::get_game_account_state_by_id->execute($q->{id},$q->{'s'});
         my $game_account = $main::get_game_account_state_by_id->fetchrow_hashref();
         $main::get_game_account_state_by_id->finish();


         my $md5 = Digest::MD5->new;

         $md5->add(lc($game_account->{login}));
         $md5->add(lc($game_account->{email}));
         $md5->add($game_account->{id});
         $md5->add(lc($q->{new_email}));
         $md5->add('mega coder SoCo');
         my $hash = $md5->hexdigest;

         if ($hash eq $q->{hex}) {

            $vars->{game_account} = $game_account;

            $page = 'confirm_new_email_ok';
         } else {
            $page = 'confirm_new_email_bad';
         }




      } elsif ($q->{page} eq 'confirm_email') {
         $hf = 1;
         $vars->{title} = 69;
         $location = '';

         $main::get_game_account_no_email->execute($q->{id});
         my $ret_data = $main::get_game_account_no_email->fetchrow_hashref();
         $main::get_game_account_no_email->finish();

         my $md5 = Digest::MD5->new;
         $md5->add($ret_data->{login});
         $md5->add($ret_data->{email});
         $md5->add($q->{id});
         $md5->add('mega coder SoCo');
         my $hash = $md5->hexdigest;

         if ($hash eq $q->{hex}) {
            $page = 'confirm_email_ok';


            $main::admin_get_inactive_game_account->execute($q->{id},$q->{'s'});
            my $ret_account = $main::admin_get_inactive_game_account->fetchrow_hashref();


            $main::admin_get_server->execute($q->{'s'});
            my $server_info = $main::admin_get_server->fetchrow_hashref();
            $main::admin_get_server->finish();

            my $error = 0;

            $main::admin_get_inactive_game_account->execute($q->{id},$q->{'s'});
            my $ret_game_account = $main::admin_get_inactive_game_account->fetchrow_hashref();
            $main::admin_get_inactive_game_account->finish();


#warn $server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$ret_account->{login}.'&password='.$ret_account->{plain_passwd}.'&ip='.$ret_game_account->{ip}.'&email='.$ret_game_account->{email};
            my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&login='.$ret_account->{login}.'&password='.$ret_account->{plain_passwd}.'&ip='.$ret_game_account->{ip}.'&email='.$ret_game_account->{email});
#            my $ret_wget = { state => 1 , content => '1', };

            if ($ret_wget->{state} == 0) {

               $page = 'confirm_email_noconnect';

            } else {
               if ($ret_wget->{content} =~ /^\d+$/ && $ret_wget->{content} ne '0') {
#                  $main::admin_set_active_game_account->execute($vars->{nick_id},$q->{id},$q->{server_id});

                  $main::set_game_account_account_id->execute($ret_wget->{content},$q->{id});

                  my $msg = MIME::Lite->new(
				From			=> 'AccountActivation',
				To			=> $ret_game_account->{email},
				Subject			=> 'Aktivacia herneho uctu na WoW '.$server_info->{server_name}.' (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
				'Auto-Submitted:'	=> 'auto-generated',
				'X-Originating-IP:'	=> $ret_game_account->{ip},
				Data			=> 'Bola spracovana ziadost o vytvorenie WoW konta (z IP adresy '.$ret_game_account->{ip}.'). Konto s prihlasovacime menom "'.$ret_game_account->{login}.'" bolo aktivovane a mozete sa prihlasit. Prajeme prijemne chvile stravene pri WoW.'."\n".'Realmlist je: '.$server_info->{ip}."\n".'Ak ste si ziadne WoW konto neregistrovali, povazujte tento mail za bezpredmetny.'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                     );

                     $msg->send;
                    $main::set_game_account_email_ok->execute($q->{id});
               }
            }

         } else {
            $page = 'confirm_email_bad';
         }


      } elsif ($q->{page} eq 'login_recovery') {
         $page = 'login_recovery';
         $hf = 1;
         $vars->{title} = 70;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'check') {
            $main::get_nick_by_email->execute($q->{email});
            if ($main::get_nick_by_email->rows() > 0) {
               my $nick = $main::get_nick_by_email->fetchall_arrayref({});

               my $data = 'Tento mail Vam bol odoslany na zaklade odoslania formularu so ziadostou o pripomenutie prihlasovacieho mena (z IP adresy '.$ENV{REMOTE_ADDR}.'). Pokial ste o heslo neziadali Vy, tak tento E-mail jednoducho ignorujte a kludne ho vymazte.'."\n\n";
               foreach (@{$nick}) {
                  $data .= 'Prihlasovacie meno: '.$_->{nick}."\n\n"
               }
               $data .= 'Na tento E-mail neodpovedajte!'."\n\n".'mine.sk Crew';

               my $msg = MIME::Lite->new(
			From			=> 'WebLoginRecovery',
			To			=> $q->{email},
			Subject			=> 'Zaslanie prihlasovacieho mena (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> $data,
               );

               $msg->send;
               $vars->{return} = 1;
            } else {
               $vars->{return} = 1;
            }
            $main::get_nick_by_email->finish();

         }


      } elsif ($q->{page} eq 'account_password_recovery') {
         $page = 'account_password_recovery';
         $hf = 1;
         $vars->{title} = 71;
         $location = '';
         $vars->{background} = 'http://wow.mine.sk/temp/testbg.jpg';

         $main::admin_get_server->execute($q->{'s'});
         my $server_info = $main::admin_get_server->fetchrow_hashref();
         $main::admin_get_server->finish();
         $vars->{server_info} = $server_info;

         $vars->{post_title} = $server_info->{server_name};

         if (defined($q->{action}) && $q->{action} eq 'check') {

            my $error = 0;
            if (defined($server_info->{activations_url}) && $server_info->{activations_url} ne '') {
               my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&action=check_by_password_and_email&login='.$q->{login}.'&email='.$q->{email});
               if ($ret_wget->{state} == 0) {
                  $vars->{return} = 2;
               } else {
                  if ($ret_wget->{content} =~ /^1$/) {

                     srand;
                     my $id = int(rand(4294967290));

                     $main::add_random_to_game_account->execute($id,$q->{'s'},$q->{login},$q->{email});

                     my $msg = MIME::Lite->new(
				From			=> 'WebAccountRecovery',
				To			=> $q->{email},
				Subject			=> 'Instrukcie ku vygenerovaniu noveho hesla na '.$server_info->{server_name}.' WoW (Automaticky generovany E-mail)',
				Type			=> 'text/plain',
				'Auto-Submitted:'	=> 'auto-generated',
				'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
				Data			=> 'Tento mail Vam bol odoslany na zaklade odoslania formularu so ziadostou o vygenerovanie noveho hesla pre pristup na '.$server_info->{server_name}.' WoW (z IP adresy '.$ENV{REMOTE_ADDR}.'). Ak si zelate vygenerovat nove heslo, kliknite na nasledujucu URL adresu: '.$globals::misc_path.'?page=account_password_recovery&action=new&login='.$q->{login}.'&email='.$q->{email}.'&id='.$id.'&s='.$q->{'s'}.' a nove heslo Vam bude zaslane v E-maile o par sekund. Pokial ste o heslo neziadali Vy, tak tento E-mail jednoducho ignorujte.'."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                     );

                     $msg->send;

                     $vars->{return} = 1;
                  } else {
                     $vars->{return} = 0;
                  }
               }
            }
         } elsif (defined($q->{action}) && $q->{action} eq 'new') {
            my $error = 0;
            if (defined($server_info->{activations_url}) && $server_info->{activations_url} ne '') {
               my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&action=check_by_password_and_email&login='.$q->{login}.'&email='.$q->{email});
               if ($ret_wget->{state} == 0) {
                  $vars->{return} = 2;
               } else {
                  if ($ret_wget->{content} =~ /^1$/) {
                     $main::check_game_account_by_random->execute($q->{id},$q->{'s'},$q->{login},$q->{email});
                     if ($main::check_game_account_by_random->rows() == 1) {
                        my $user_id = $main::check_game_account_by_random->fetchrow();

                        my $arr = [qw(q w e r t y u i p a s d f g h k z x c v b n 2 3 4 5 6 7 9 A C E F H K L M P R T U X Y Z)];
                        my $salt;
                        for (my $i=0; $i<8; ++$i) {$salt .= $arr->[int(rand(scalar(@{$arr})))]}

                        my $ret_wget = system::wget($server_info->{activations_url}.'?http_password='.$server_info->{http_password}.'&action=set_password_by_user_and_email&login='.$q->{login}.'&email='.$q->{email}.'&password='.$salt);

                        if ($ret_wget->{state} == 0) {
                           $vars->{return} = 2;
                        } else {
                           if ($ret_wget->{content} =~ /^1$/) {


                              my $hash = md5_hex($salt);
                              $main::set_game_account_password->execute($hash,$salt,$user_id,$q->{'s'}); #}}
#warn "main::set_game_account_password->execute($hash,$salt,$user_id,$q->{'s'})";
                           
                              my $msg = MIME::Lite->new(
					From			=> 'WebAccountRecovery',
					To			=> $q->{email},
					Subject			=> 'Vygenerovanie noveho hesla (Automaticky generovany E-mail)',
					Type			=> 'text/plain',
					'Auto-Submitted:'	=> 'auto-generated',
					'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
					Data			=> 'Tento mail Vam bol odoslany na zaklade odoslania formularu so ziadostou o vygenerovanie noveho hesla pre pristup na '.$server_info->{server_name}.' WoW (z IP adresy '.$ENV{REMOTE_ADDR}.')'."\n\n".'Nove heslo je: '.$salt."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'S pozdravom Team '.$server_info->{server_name},
                              );

                              $main::log_game_account_data_change->execute($user_id,$q->{'s'},$ENV{REMOTE_ADDR},'password',$salt);
                           
                              $msg->send;

                              $vars->{return} = 3;
                           } else {
                              $vars->{return} = 0;
                           }
                        }
                     } else {
                        $vars->{return} = 4;
                     }
                  } else {
                     $vars->{return} = 0;
                  }
               }
            }


         }


      } elsif ($q->{page} eq 'password_recovery') {
         $page = 'password_recovery';
         $hf = 1;
         $vars->{title} = 72;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'check') {

#warn "main::get_nick_id_by_login_password->execute($q->{login},$q->{email});";

            $main::get_nick_id_by_login_password->execute($q->{login},$q->{email});
            if ($main::get_nick_id_by_login_password->rows() == 1) {

#warn "OKOKK";

               my $tmp_nick_id = $main::get_nick_id_by_login_password->fetchrow();
               $vars->{return} = 1;

               my $arr = [qw(q w e r t y u i p a s d f g h k z x c v b n 2 3 4 5 6 7 9 A C E F H K L M P R T U X Y Z)];
               my $salt;
               for (my $i=0; $i<8; ++$i) {$salt .= $arr->[int(rand(scalar(@{$arr})))]}

               $main::del_temporary_passwords_by_nick_id->execute($tmp_nick_id);


               my $dig = sha256_hex(uc($q->{login}).':'.uc($salt));
               my $num = 0;
               foreach my $x (split('',$q->{login})) {
                   $num += ord(lc($x));
               }

               $num = 1+($num % 60);

               my $pre;
               my $post;
               my $tmp = 0;
               foreach my $char (split('',$dig)) {
                  if ($tmp < $num) {
                     $pre .= $char;
                  } else {
                     $post .= $char;
                  }
                  ++$tmp;
               }

               $pre = reverse($pre);
               $post = reverse($post);
               chop($post);

               my $out = $post.'0'.$pre;


               $main::add_temporary_password->execute($tmp_nick_id,$out);
#warn ":add_temporary_password->execute($tmp_nick_id,$out);";

               my $msg = MIME::Lite->new(
			From			=> 'WebAccountRecovery',
			To			=> $q->{email},
			Subject			=> 'Zaslanie noveho docasneho hesla (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data			=> 'Tento mail Vam bol odoslany na zaklade odoslania formularu so ziadostou o vygenerovanie noveho docasneho hesla (z IP adresy '.$ENV{REMOTE_ADDR}.'). Toto heslo je platne az po prvom pouziti. Pokial ste o heslo neziadali Vy, tak tento E-mail jednoducho ignorujte a mozete sa prihlasit prostrednictom povodneho hesla.'."\n\n".'Prihlasovacie meno: '.$q->{login}."\n".'Nove docasne heslo: '.$salt."\n\n".'Na tento E-mail neodpovedajte!'."\n\n".'mine.sk Crew',
               );

               $msg->send;

               

            } else {
               $vars->{return} = 0;
            }
         }


      } elsif ($q->{page} eq 'punishlist') {
         $page = 'punishlist';
         $hf = 1;
         $vars->{title} = 73;
         $location = '';

         my $ret_punishes = system::get_all_active_punishes_by( $dbh, { }, );
         $vars->{normal} = $ret_punishes->{punishes}->{normal};
         $vars->{ultimate} = $ret_punishes->{punishes}->{ultimate};

         if (defined($q->{nick_id}) && $q->{nick_id} ne '') {
            my $ret_punishments = system::get_nick_all_punishments( { nick_id => $q->{nick_id}, }, );
            $vars->{punishments} = $ret_punishments->{punishments};
         }

         $vars->{channels_hashref} = $channels_hashref;


      } elsif ($q->{page} eq 'private_edit') {
         $page = 'private_edit';
         $hf = 1;
         $vars->{title} = 74;
         $location = '';


         if (defined($q->{action}) && $q->{action} eq 'edit_line' && defined($q->{id}) && $q->{id} =~ /^\d+$/) {
            $q->{message} =~ s/&/&amp;/gs;
            $q->{message} =~ s/</&lt;/gs;
            $q->{message} =~ s/>/&gt;/gs;
            $main::update_private_message->execute($q->{message},$q->{id},'p');

            $main::get_private_message_shown->execute($q->{id});
            my $shown = $main::get_private_message_shown->fetchrow();

            if ($shown != 1) {
               $main::update_private_message_history->execute($q->{message},$q->{id});
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'delete' && defined($q->{id}) && $q->{id} =~ /^\d+$/) {
            $main::get_private_message_shown->execute($q->{id});
            my $shown = $main::get_private_message_shown->fetchrow();

            if ($shown != 1) {
               $main::delete_private_message->execute($q->{id},'p');
               $main::delete_private_message_history->execute($q->{id});
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'move_to_channel' && defined($q->{id}) && $q->{id} =~ /^\d+$/) {

            my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $vars->{channel_id}, }, );
            if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{stop} == 1)) {

               $main::get_line->execute($q->{id});
               my $line = $main::get_line->fetchrow_hashref();
               $main::transfer_message->execute('c',$vars->{channel_id},$line->{channel_id},$q->{id},'p');
            }
         }

         $main::get_private_message_shown->execute($q->{id});
         my $shown = $main::get_private_message_shown->fetchrow();
         $vars->{shown} = $shown;

         $main::get_line->execute($q->{id});
         my $line = $main::get_line->fetchrow_hashref();
         $vars->{line} = $line;



#      } elsif ($q->{page} eq 'ajax_nicks') {
#         $page = 'ajax_nicks';
#         $hf = 0;
#         $location = '';
#
#         my $ret_nicks = system::get_nick_like_nick( { input => $q->{input}, }, );
#         if ($ret_nicks->{count} > 0) {
#            foreach (@{$ret_nicks->{nicks}}) {
#               $vars->{ajax_nicks} .= '`'.$_->{id}.'|'.$_->{nick};
#               $vars->{ajax_nicks} .= $_->{nick}.'|';
#            }
#            $vars->{ajax_nicks} =~ s/\|$//;
#         }
#
#         $vars->{ajax_nicks} = $ret_nicks->{nicks};


      } elsif ($q->{page} eq 'tickets') {
         $page = 'tickets';
         $hf = 1;
         $vars->{title} = 75;
         $location = '';


         my $ret_all_tickets_by = system::get_all_tickets_by($dbh, { section => $q->{section}, requestor => $q->{requestor}, state => $q->{state}, order => [ { 'order' => 'state', 'asc' => 1, }, { 'order' => 'request_datestamp', 'asc' => 0, } ], }, );
         my $tickets;
         foreach (@{$ret_all_tickets_by->{tickets}}) {
            push @{$tickets->{$_->{state}}}, $_;
         }
         $vars->{tickets} = $tickets;
         $vars->{count} = $ret_all_tickets_by->{count};


#      } elsif ($q->{page} eq 'new_ticket') {
#         $page = 'new_ticket';
#         $hf = 1;
#         $vars->{title} = 76;
#         $location = '';


      } elsif ($q->{page} eq 'settings_away') {
         $page = 'settings_away';
         $hf = 1;
         $vars->{title} = 77;
         $location = '';

         if (defined($q->{action}) && $q->{action} eq 'add_message') {
            if (defined($q->{shortcut}) && $q->{shortcut} ne '' && defined($q->{message}) && $q->{message} ne '') {
               my $message;
               if ($vars->{level} > 0) {
                  $message = system::htmlfilter($q->{message});
               } else {
                  my $message1 = system::bwfilter($q->{message});
                  $message = system::htmlfilter($message1);
               }
               $main::add_away_message->execute($vars->{nick_id},$q->{shortcut},$message);
            }

         } elsif (defined($q->{action}) && $q->{action} eq 'del_message') {
            $main::del_away_message->execute($q->{id},$vars->{nick_id});

         } elsif (defined($q->{action}) && $q->{action} eq 'activate') {
            $main::get_away_message_by_message_id_nick_id->execute($q->{id},$vars->{nick_id});
            my $away_message = $main::get_away_message_by_message_id_nick_id->fetchrow_hashref();
            $main::get_away_message_by_message_id_nick_id->finish();
            $main::set_away_message_by_nick_id->execute($away_message->{message},$vars->{nick_id});

         } elsif (defined($q->{action}) && $q->{action} eq 'unset') {
            $main::set_away_message_by_nick_id->execute('',$vars->{nick_id});

         }

         $main::get_away_message_by_nick_id->execute($vars->{nick_id});
         my $current_message = $main::get_away_message_by_nick_id->fetchrow_hashref();
         $main::get_away_message_by_nick_id->finish();


         $main::get_all_away_messages_by_nick_id->execute($vars->{nick_id});
         my $away_messages = $main::get_all_away_messages_by_nick_id->fetchall_arrayref({});
         foreach (@{$away_messages}) {
            if ($_->{message} eq $current_message->{away_message}) {
               $_->{active} = 1;
            }
         }
         $vars->{away_messages} = $away_messages;
         $main::get_all_away_messages_by_nick_id->finish();


      } elsif ($q->{page} eq 'new_guild') {
         $page = 'new_guild';
         $hf = 1;
         $vars->{title} = 78;
         $location = '';
         $vars->{doctype} = 1;


         if (defined($q->{action}) && $q->{action} eq 'read_msg' && defined($q->{msg_id}) && $q->{msg_id} =~ /^\d+$/) {
            system::del_guild_chat_shown_by_nick_id_and_msg_id( { nick_id => $vars->{nick_id}, msg_id => $q->{msg_id}, } );
            system::add_action( { action => 21, nick_id => $vars->{nick_id}, message_id => $q->{msg_id}, }, );
            
         } elsif (defined($q->{action}) && $q->{action} eq 'read_all') {
            system::del_guild_chat_shown_by_nick_id( { nick_id => $vars->{nick_id}, } );
            system::add_action( { action => 21, nick_id => $vars->{nick_id}, message_id => $q->{msg_id}, }, );

         }

         my $ret_guild_chat_messages = system::get_guild_chat_messages( { nick_id => $vars->{nick_id}, } );
         if ($ret_guild_chat_messages->{rv} == 1) {

            foreach my $ch (keys(%{$ret_guild_chat_messages->{messages}})) {
               foreach my $g (keys(%{$ret_guild_chat_messages->{messages}->{$ch}})) {
                  foreach my $msg (@{$ret_guild_chat_messages->{messages}->{$ch}->{$g}}) {
                     $msg->{message} = &substitutions($msg->{message});
                  }
               }
            }

            $vars->{messages} = $ret_guild_chat_messages->{messages};
            $vars->{count} = $ret_guild_chat_messages->{count};
            $vars->{channels_hashref} = $channels_hashref;
            my $min = $ret_guild_chat_messages->{min};

            foreach my $ch (keys(%{$min})) {
               foreach my $g (keys(%{$min->{$ch}})) {
                  my $ret_guild_chat_history_messages = system::get_guild_chat_history_messages( { msg_id => $min->{$ch}->{$g}, channel_id => $ch, guild_id => $g, }, );
                  foreach my $msg (@{$ret_guild_chat_history_messages->{messages}}) {
                     $msg->{message} = &substitutions($msg->{message});
                  }
                  $vars->{messages_history}->{$ch}->{$g} = $ret_guild_chat_history_messages->{messages};
               }
            }
         } else {
            $location = $globals::misc_script.'?page=history_guild&sid='.$q->{sid};
         }



      } elsif ($q->{page} eq 'history_guild') {
         $page = 'history_guild';
         $hf = 1;
         $vars->{title} = 79;
         $location = '';
         $vars->{doctype} = 1;

         my $ret_channels = system::get_channels_on_in_guild_by_nick_id( { nick_id => $vars->{nick_id}, }, );
         my $channels = $ret_channels->{channels};
         foreach (@{$channels}) {
            my $ret_guilds = system::get_is_in_guilds_by_nick_id_channel_id( { channel_id => $_->{channel_id}, nick_id => $vars->{nick_id}, }, );
            $_->{guilds} = $ret_guilds->{guilds};
         }

         $vars->{guilds_channels} = $channels;

         if (defined($q->{action}) && $q->{action} eq 'search') {

            if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}#-
            if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 50;} else {$q->{count} = int($q->{count});}#-

            my $history = system::get_guild_chat_history( { channel_id => $q->{channel_id}, guild_id => $q->{guild_id}, from => $q->{from}, count => $q->{count}, }, );
            foreach my $msg (@{$history->{messages}}) {
               $msg->{message} = &substitutions($msg->{message});
            }

            $vars->{messages} = $history->{messages};
            $vars->{total} = $history->{count};
            $vars->{pages} = $history->{count}/$q->{count};


         }

      } elsif ($q->{page} eq 'profile_shows') {
         $page = 'profile_shows';
         $hf = 1;
         $vars->{title} = 80;
         $location = '';
         $vars->{doctype} = 1;

         if (!defined($q->{order}) || ($q->{order} ne 'total' && $q->{order} ne 'ps.id' && $q->{order} ne 'n.nick' && $q->{order} ne 'n.chat_rank' && $q->{order} ne 'n.profile_sex' && $q->{order} ne 'n.profile_city' && $q->{order} ne 'n.profile_high' && $q->{order} ne 'n.profile_weight' && $q->{order} ne 'ps.showed_stamp' && $q->{order} ne 'n.profile_birthdate')) {$q->{order} = 'ps.id';}
         if (!defined($q->{asc}) || $q->{asc} ne '1') {$q->{asc} = 0;}
         if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
         if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 200;} else {$q->{count} = int($q->{count});}

         my $ret_profile_showed = system::get_profile_showed( $dbh, { order => $q->{order}, asc => $q->{asc}, nick_id => $vars->{nick_id}, from => $q->{from}, count => $q->{count}, }, );
         if ($ret_profile_showed->{rv} == 1) {
            $vars->{shows} = $ret_profile_showed->{shows};
            $vars->{total} = $ret_profile_showed->{count};
            $vars->{pages} = $ret_profile_showed->{count}/$q->{count};
         }

         my $set_reverse;
         foreach my $column ('total','ps.id','n.nick','n.chat_rank','n.profile_sex','n.profile_city','n.profile_high','n.profile_weight','ps.showed_stamp','n.profile_birthdate') {
            if ($q->{order} eq $column) {
               if ($q->{asc} == 1) {
                  $set_reverse->{$column} = 0;
               } else {
                  $set_reverse->{$column} = 1;
               }
            } else {
               $set_reverse->{$column} = $q->{asc};
            }
         }

         $vars->{setrev} = $set_reverse;
                                                                                                                                                                        
                                                                                                                                                                        



      } elsif ($q->{page} eq 'settings_image_change') {
         $page = 'settings_image_change';
         $hf = 1;
         $vars->{title} = 81;
         $location = '';
         $vars->{doctype} = 1;

         my $ret_album_images_by_album_id = system::get_album_images_by_album_id( $dbh, { album_id => $q->{album_id}, order => $q->{order}, asc => $q->{asc}, from => $q->{image_index}, count => 1, }, );
         $vars->{image} = $ret_album_images_by_album_id->{images}->[0];
         $vars->{total} = $ret_album_images_by_album_id->{count};

         my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, }, );
         if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
            $vars->{data} = $ret_photoalbum_by_id_and_owner->{album};
         }



      } elsif ($q->{page} eq 'settings_albums') {
         $page = 'settings_albums';
         $hf = 1;
         $vars->{title} = 82;
         $location = '';
         $vars->{doctype} = 1;

         if (defined($q->{action}) && $q->{action} eq 'add_album') {
            my $ret_add_new_photoalbum = system::add_new_photoalbum( { nick_id => $vars->{nick_id}, album_name => $q->{album_name}, album_text => $q->{album_text}, album_category => $q->{album_category}, album_access => $q->{album_access}, album_password => $q->{album_password}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'change') {
            my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, }, );
            if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
               $vars->{data} = $ret_photoalbum_by_id_and_owner->{album};
            }
         } elsif (defined($q->{action}) && $q->{action} eq 'set_album') {
            my $ret_save_photoalbum = system::save_photoalbum( { nick_id => $vars->{nick_id}, album_name => $q->{album_name}, album_text => $q->{album_text}, album_category => $q->{album_category}, album_access => $q->{album_access}, album_password => $q->{album_password}, album_id => $q->{album_id}, }, );

         } elsif (defined($q->{action}) && $q->{action} eq 'delete_icon') {
            system::set_icon_to_album( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, delete => '1', }, );

         } elsif (defined($q->{action}) && $q->{action} eq 'delete_album') {
            system::delete_album_by_id_and_owner( { nick_id => $vars->{nick_id}, album_id => $q->{album_id}, }, );

         }

         my $ret_all_user_photoalbums = system::get_all_user_photoalbums( { nick_id => $vars->{nick_id}, }, );
         if ($ret_all_user_photoalbums->{rv} == 1) {
            $vars->{photoalbums} = $ret_all_user_photoalbums->{photoalbums};
            $vars->{total_images} = $ret_all_user_photoalbums->{total_images};
            $vars->{total_size} = $ret_all_user_photoalbums->{total_size};
            $vars->{total_quotes} = $ret_all_user_photoalbums->{total_quotes};
            $vars->{total_quotes_values} = $ret_all_user_photoalbums->{total_quotes_values};
         }


      } elsif ($q->{page} eq 'albums_list') {
         $page = 'albums_list';
         $hf = 1;
         $location = '';
         $vars->{title} = 83;
         $vars->{doctype} = 1;

         my $ret_all_user_photoalbums = system::get_all_user_photoalbums( { nick_id => $q->{nick_id}, }, );
         if ($ret_all_user_photoalbums->{rv} == 1) {
            $vars->{photoalbums} = $ret_all_user_photoalbums->{photoalbums};
            $vars->{total_images} = $ret_all_user_photoalbums->{total_images};
         }

         $main::get_nick_by_nick_id->execute($q->{nick_id});
         my $nick = $main::get_nick_by_nick_id->fetchrow_hashref();
         $main::get_nick_by_nick_id->finish();
         $vars->{nick} = $nick;


      } elsif ($q->{page} eq 'settings_photos') {
         $page = 'settings_photos';
         $hf = 1;
         $location = '';
         $vars->{title} = 84;
         $vars->{doctype} = 1;

         my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, }, );
         if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
            $vars->{data} = $ret_photoalbum_by_id_and_owner->{album};
         }

         sessions::delete_session_data_by_name($dbh, { session_id => $vars->{session_id}, name => 'is_uploading', }, );
         sessions::delete_session_data_by_name($dbh, { session_id => $vars->{session_id}, name => 'upload_start', }, );
         sessions::delete_session_data_by_name($dbh, { session_id => $vars->{session_id}, name => 'content_length', }, );


      } elsif ($q->{page} eq 'settings_comments') {
         $page = 'settings_comments';
         $hf = 1;
         $location = '';
         $vars->{title} = 84;
         $vars->{doctype} = 1;
                                                   
         my $ret_all_comments_of_my_images = system::get_all_comments_of_my_images( { nick_id => $vars->{nick_id}, } );
         $vars->{images_comments} = $ret_all_comments_of_my_images->{images_comments};
         

      } elsif ($q->{page} eq 'show_album') {
         $page = 'show_album';
         $hf = 1;
         $location = '';
         $vars->{title} = 85;
         $vars->{doctype} = 1;

         $q->{sort} = '';

         my $ret_half_session = sessions::get_half_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
         if ($ret_half_session->{ec} == 1) {
            $vars->{session_id} = $ret_half_session->{session_id};
         }


         if (defined($q->{action}) && $q->{action} eq 'check_password') {
            sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name=> 'album_'.$q->{album_id}, value => $q->{'album_'.$q->{album_id}}, } );
#            system::add_bind_session_photoalbum_password( { album_id => $q->{album_id}, session_id => $vars->{session_id}, password => $q->{'album_'.$q->{album_id}}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'delete_image') {
            system::del_image_from_photoalbum( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, image_name => $q->{image_name}, image_extension => $q->{image_extension}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'set_icon') {
            my $ret_album_images_by_album_id = system::get_album_images_by_album_id( $dbh, { album_id => $q->{album_id}, order => $q->{order}, asc => $q->{asc}, from => $q->{image_index}, count => 1, }, );
            my $image = $ret_album_images_by_album_id->{images}->[0];
            system::set_icon_to_album( { album_id => $q->{album_id}, nick_id => $vars->{nick_id}, image_id => $image->{image_id}, image_name => $image->{image_name}, image_extension => $image->{image_extension}, }, );
         }

         if (!defined($q->{nick_id}) || $q->{nick_id} eq '') {$q->{nick_id} = $vars->{nick_id};}
         my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $q->{album_id}, nick_id => $q->{nick_id}, }, );
         if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
            $vars->{data} = $ret_photoalbum_by_id_and_owner->{album};
         }

         $vars->{post_title} = $vars->{data}->{album_name};

         my $allowed = -1;

         if (defined($vars->{data}->{access}) && ($vars->{data}->{access} == 0 || $vars->{data}->{album_owner} == $vars->{nick_id} || $vars->{nick_id} == 1 || $vars->{nick_id} == 4228)) {
            $allowed = 1;
         } elsif ($vars->{data}->{access} == 1) {
            my $get_user_in_ignorelist = system::is_user_in_ignorelist( { owner_id => $vars->{data}->{album_owner}, nick_id => $vars->{nick_id}, }, );
            if ($get_user_in_ignorelist->{rv} == 1) {
               $allowed = -1;
            } else {
               $allowed = 1;
            }
         } elsif ($vars->{data}->{access} == 2) {
            my $get_user_in_friendlist = system::is_user_in_friendlist( { owner_id => $vars->{data}->{album_owner}, nick_id => $vars->{nick_id}, }, );
            if ($get_user_in_friendlist->{rv} == 1) {
               $allowed = 1;
            } else {
               $allowed = -1;
            }
         } elsif ($vars->{data}->{access} == 3) {
#            my $ret_bind_session_photoalbum_password = system::get_bind_session_photoalbum_password( { session_id => $vars->{session_id}, album_id => $q->{album_id}, }, );#-
#            if ($ret_bind_session_photoalbum_password->{session_photoalbum_password}->{album_password} eq $ret_photoalbum_by_id_and_owner->{album}->{passwd}) {

            my $ret_session_data =  sessions::get_session_data($dbh, {session_id => $vars->{session_id} , } );
            my $session_data = $ret_session_data->{session_data};
                  
            if ($session_data->{'album_'.$q->{album_id}} eq $ret_photoalbum_by_id_and_owner->{album}->{passwd}) {
               $allowed = 1;
            } else {
               $allowed = 0;
            }
         } else {
            $allowed = -1;
         }

         if ($allowed == 1) {
            if (!defined($q->{from}) || $q->{from} !~ /^\d+$/) {$q->{from} = 0;} else {$q->{from} = int($q->{from});}
            if (!defined($q->{count}) ||$q->{count} !~ /^\d+$/) {$q->{count} = 12;} else {$q->{count} = int($q->{count});}
            if (!defined($q->{order}) || ($q->{order} ne 'image_id' && $q->{order} ne 'added_stamp' && $q->{order} ne 'image_bytes') && $q->{order} ne 'quote_final') {$q->{order} = 'image_id';}

            my $ret_album_images_by_album_id = system::get_album_images_by_album_id( $dbh, { album_id => $q->{album_id}, order => $q->{order}, asc => $q->{asc}, from => $q->{from}, count => $q->{count}, }, );
            $vars->{images} = $ret_album_images_by_album_id->{images};
            $vars->{total} = $ret_album_images_by_album_id->{count};
            if ($ret_album_images_by_album_id->{count} % $q->{count} == 0) {
               $vars->{pages} = $ret_album_images_by_album_id->{count}/$q->{count} - 1;
            } else {
               $vars->{pages} = $ret_album_images_by_album_id->{count}/$q->{count};
            }

            system::set_album_showed( { album_id => $q->{album_id}, }, );

         }

         $vars->{allowed} = $allowed;




      } elsif ($q->{page} eq 'show_image') {
         $page = 'show_image';
         $hf = 1;
         $location = '';
         $vars->{title} = 86;
         $vars->{doctype} = 1;

         my $ret_half_session = sessions::get_half_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
         if ($ret_half_session->{ec} == 1) {
            $vars->{session_id} = $ret_half_session->{session_id};
         }

         if (defined($q->{action}) && $q->{action} eq 'check_password') {
            system::add_bind_session_photoalbum_password( { album_id => $q->{album_id}, session_id => $vars->{session_id}, password => $q->{'album_'.$q->{album_id}}, }, );
         }

         if (!defined($q->{nick_id}) || $q->{nick_id} eq '') {$q->{nick_id} = $vars->{nick_id};}
         my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $q->{album_id}, nick_id => $q->{nick_id}, }, );
         if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
            $vars->{data} = $ret_photoalbum_by_id_and_owner->{album};
         }

         my $allowed = -1;

         if (defined($vars->{data}->{access}) && ($vars->{data}->{access} == 0 || $vars->{data}->{album_owner} == $vars->{nick_id} || $vars->{nick_id} == 1 || $vars->{nick_id} == 4228)) {
            $allowed = 1;
         } elsif ($vars->{data}->{access} == 1) {
            my $get_user_in_ignorelist = system::is_user_in_ignorelist( { owner_id => $vars->{data}->{album_owner}, nick_id => $vars->{nick_id}, }, );
            if ($get_user_in_ignorelist->{rv} == 1) {
               $allowed = -1;
            } else {
               $allowed = 1;
            }
         } elsif ($vars->{data}->{access} == 2) {
            my $get_user_in_friendlist = system::is_user_in_friendlist( { owner_id => $vars->{data}->{album_owner}, nick_id => $vars->{nick_id}, }, );
            if ($get_user_in_friendlist->{rv} == 1) {
               $allowed = 1;
            } else {
               $allowed = -1;
            }
         } elsif ($vars->{data}->{access} == 3) {
            my $ret_bind_session_photoalbum_password = system::get_bind_session_photoalbum_password( { session_id => $vars->{session_id}, album_id => $q->{album_id}, }, );#-
            if ($ret_bind_session_photoalbum_password->{session_photoalbum_password}->{album_password} eq $ret_photoalbum_by_id_and_owner->{album}->{passwd}) {
               $allowed = 1;
            } else {
               $allowed = 0;
            }
         } else {
            $allowed = -1;
         }

         if ($allowed == 1) {

#            my $ret_album_images_by_album_id = system::get_album_images_by_album_id( $dbh, { album_id => $q->{album_id}, order => $q->{order}, asc => $q->{asc}, from => $q->{image_index}, count => 1, }, );
#            $vars->{image} = $ret_album_images_by_album_id->{images}->[0];
#            $vars->{total} = $ret_album_images_by_album_id->{count};

            if (!defined($q->{order}) || ($q->{order} ne 'image_id' && $q->{order} ne 'added_stamp' && $q->{order} ne 'image_bytes') && $q->{order} ne 'quote_final') {$q->{order} = 'image_id';}

            my $ret_album_image_by_image_id = system::get_album_image_by_image_id( $dbh, { album_id => $q->{album_id}, order => $q->{order}, asc => $q->{asc}, image_id => $q->{image_id}, }, );
            $vars->{image} = $ret_album_image_by_image_id->{image};
            $vars->{total} = $ret_album_image_by_image_id->{count};
            $vars->{next_image} = $ret_album_image_by_image_id->{next_image};
            $vars->{prev_image} = $ret_album_image_by_image_id->{prev_image};
            $vars->{first_image} = $ret_album_image_by_image_id->{first_image};
            $vars->{last_image} = $ret_album_image_by_image_id->{last_image};
                                    

#            $vars->{image}->{average} = sprintf "%.2f",($vars->{image}->{quotes_value}/$vars->{image}->{quotes});

            if (defined($q->{action}) && $q->{action} eq 'add_mark') {
               system::add_nick_voted_photoalbum_image( { album_id => $q->{album_id}, image_id => $vars->{image}->{image_id}, nick_id => $vars->{nick_id}, mark => $q->{mark}, }, );
            }


            system::set_album_image_showed( { album_id => $q->{album_id}, image_id => $vars->{image}->{image_id}, }, );

            my $ret_nick_voted_photoalbum_image = system::get_nick_voted_photoalbum_image( { album_id => $q->{album_id}, image_id => $vars->{image}->{image_id}, nick_id => $vars->{nick_id}, }, );
            $vars->{voted} = $ret_nick_voted_photoalbum_image->{voted};

#            $vars->{post_title} = $vars->{data}->{album_name}.', No.'.$q->{image_index};

            my $ret_photoalbum_image_comments = system::get_photoalbum_image_comments( { image_id => $vars->{image}->{image_id}, }, );
            $vars->{image_comments} = $ret_photoalbum_image_comments->{image_comments};

         }
         $vars->{allowed} = $allowed;



      } elsif ($q->{page} eq 'progress_bar') {
         $page = 'progress_bar';
         $hf = 0;
         $location = '';
         $vars->{doctype} = 0;

         my $ret_session_data =  sessions::get_session_data($dbh, {session_id => $vars->{session_id} , } );
         my $session_data = $ret_session_data->{session_data};

         my $uploaded_files = 0;
         my $uploaded_bytes = 0;

         if (-d $globals::datadir.'/tmp/'.$q->{sid}) {
            if (opendir(DIRHANDLE, $globals::datadir.'/tmp/'.$q->{sid})) {
               my @file_list = readdir(DIRHANDLE);
               closedir(DIRHANDLE);

               foreach my $file (@file_list){
                  unless (($file eq ".") || ($file eq "..")) {
                     my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat( $globals::datadir.'/tmp/'.$q->{sid}.'/'.$file );
                     $uploaded_bytes += $size;
                     ++$uploaded_files;
                  }
               }
            }
         }


         my $elapsed_time = $t0->[0] - $session_data->{upload_start};
         my $upload_speed;
         if ($elapsed_time != 0) {
            $upload_speed = $uploaded_bytes/$elapsed_time;
         }
         my $estimated_time;
         if ($upload_speed != 0) {
            $estimated_time = ($session_data->{content_length}/$upload_speed) - $elapsed_time;
         }
         my $percent;
         if ($session_data->{content_length} != 0) {
            $percent = int(($uploaded_bytes/$session_data->{content_length})*100);
         }

         $vars->{data} = $session_data->{is_uploading}.'|'.system::upload_time($elapsed_time).'|'.system::make_size($session_data->{content_length}).'|'.system::make_size($uploaded_bytes).'|'.$uploaded_files.'|'.system::make_size($upload_speed).'/s|'.$percent.'|'.system::upload_time(int($estimated_time));


      } elsif ($q->{page} eq 'latest_photoalbums') {
         $page = 'latest_photoalbums';
         $hf = 1;
         $location = '';
         $vars->{title} = 87;
         $vars->{doctype} = 1;

         my $ret_latest_photoalbums_by_categories = system::get_latest_photoalbums_by_categories();
         $vars->{albums} = $ret_latest_photoalbums_by_categories->{albums};


#      } elsif ($q->{page} eq 'download_graph') {
#         $hf = 0;
#
#         my $x = [ 'antik', 'small', 'hday', 'day', 'week', ];
#         my $y = [ 'hvsa','pvsgm','races','classes', ];
#
#         foreach my $gr (@{$x}) {
#            foreach my $fe (@{$y}) {
#               `/usr/bin/wget -O "/www/mine.sk/wow/chat/images/s$q->{server_id}_$fe-$gr.png" http://img.mine.sk/s$q->{server_id}_$fe-$gr.png`;
##warn "/usr/bin/wget -O \"/www/mine.sk/wow/chat/images/s$q->{server_id}_$fe-$gr.png\" http://img.mine.sk/s$q->{server_id}_$fe-$gr.png"
#            }
#         }

      } elsif ($q->{page} eq 'settings_macros') {
         $page = 'settings_macros';
         $hf = 1;
         $location = '';
         $vars->{title} = 88;
         $vars->{doctype} = 1;

         if (defined($q->{action}) && $q->{action} eq 'add_macro') {
           system::add_user_macro( { nick_id => $vars->{nick_id}, macro_name => $q->{macro_name}, macro_text => $q->{macro_text}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'del_macro') {
           system::del_macro_by_id_and_nick_id( { nick_id => $vars->{nick_id}, id => $q->{id}, }, );
         } elsif (defined($q->{action}) && $q->{action} eq 'set_macro') {
           system::set_user_macro_by_id_and_nick_id( { nick_id => $vars->{nick_id}, id => $q->{id}, macro_name => $q->{macro_name}, macro_text => $q->{macro_text}, }, );
         }


         my $ret_macros_by_nick_id = system::get_macros_by_nick_id( { nick_id => $vars->{nick_id}, }, );
         my $macros = $ret_macros_by_nick_id->{macros};
         $vars->{macros} = $macros;


      } elsif ($q->{page} eq 'winamp') {
         $page = 'winamp';
         $hf = 1;
         $location = '';
                                 
#      warn "!!! winamp ".$q->{'Song[0][Title]'}.' - '.$q->{'Song[0][Artist]'};


      } elsif ($q->{page} eq 'item_info') {

         $mime = 'text/xml';
         
#         my $ret_wget = system::wget('http://www.wowarmory.sk/player-status.fcgi?page=item_info&s='.$q->{'s'}.'&item_id='.$q->{item_id});
         my $ret_wget = system::wget('http://wow.anthoria.net/anthoria/items/ajax.php?action=get_item&item_id='.$q->{item_id});
         $ret_wget->{content} =~ s/^get_item\((.+)\)/$1/;

         my $perl_scalar = from_json($ret_wget->{content});

         my $content = '<div class="wowitem wowitemlive">'.$perl_scalar->{'data'}->{'data'}.'</div>';
         $content =~ s/&/&amp;/gs;
         $content =~ s/</&lt;/gs;
         $content =~ s/>/&gt;/gs;

         $html = '<?xml version="1.0" encoding="UTF-8"?><r><data><a>2</a><i>'.$q->{item_id}.'</i><h>'.$content.'</h></data></r>';


      } elsif ($q->{page} eq 'spell_info') {

         $mime = 'text/xml';

         my $ret_wget = system::wget('http://www.wowarmory.sk/player-status.fcgi?page=spell_info&s='.$q->{'s'}.'&spell_id='.$q->{spell_id});
         $html = $ret_wget->{content};


      } elsif ($q->{page} eq 'quest_info') {
      
         $mime = 'text/xml';
         my $ret_get_quest_by_entry_id = system::get_quest_by_entry_id( { server_id => $q->{'s'}, entry_id => $q->{quest_id}, }, );
         my $quest = $ret_get_quest_by_entry_id->{quest};
         $html = '<?xml version="1.0" encoding="UTF-8"?><r><data><a>4</a><i>'.$q->{quest_id}.'</i><h>&lt;div class=&quot;wowitem wowitemlive&quot;&gt;&lt;span class=&quot;goldtext&quot; style=&quot;font-size:16px&quot;&gt;'.$quest->{Title}.'&lt;/span&gt;&lt;br /&gt;';
         if ($quest->{Objectives} ne '') {
            $html .= '&lt;span class=&quot;wowitemt&quot;&gt;'.$quest->{Objectives}.'&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;';
            if ($quest->{ObjectiveText1} ne '' || $quest->{ObjectiveText2} ne '' || $quest->{ObjectiveText3} ne '' || $quest->{ObjectiveText4} ne '') {
               $html .= '&lt;span class=&quot;goldtext&quot;&gt;Requirements:&lt;br /&gt;&lt;/span&gt;';
               for (my $i=1;$i<=4;++$i) {
                  if ($quest->{'ObjectiveText'.$i} ne '') {
                     $html .= '&lt;span class=&quot;wowitemt&quot;&gt;- '.$quest->{'ObjectiveText'.$i}.'&lt;br /&gt;&lt;/span&gt;';
                  }               
               }
            }
         } elsif ($quest->{'RequestItemsText'} ne '') {
            $quest->{'RequestItemsText'} =~ s/\$b/&lt;br&gt;/gsm;
            $html .= '&lt;span class=&quot;wowitemt&quot;&gt;'.$quest->{RequestItemsText}.'&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;';
         }
         
         $html .= '&lt;/div&gt;</h></data></r>';
        
        
       } elsif ($q->{page} eq 'achievement_info') {
       
         $mime = 'text/xml';
                
         my $ret_wget = system::wget('http://www.wowarmory.sk/player-status.fcgi?page=achievement_info&s='.$q->{'s'}.'&achievement_id='.$q->{achievement_id});
         $html = $ret_wget->{content};

      } elsif ($q->{page} eq 'player_info') {
       
         $mime = 'text/xml';
                
         my $player = system::get_player_lite( { player_id => $q->{player_id}, }, );
         $html = '<?xml version="1.0" encoding="UTF-8"?><r><data><a>7</a><i>'.$q->{player_id}.'</i><n>'.$player->{name}.'</n><r>'.$player->{race}.'</r><c>'.$player->{class}.'</c><l>'.$player->{level}.'</l><hk>'.$player->{honor_kills}.'</hk><hp>'.$player->{honor_points}.'</hp><ap>'.$player->{arena_points}.'</ap>';
         $html .= '</data></r>';
                  

      } elsif ($q->{page} eq 'last_server_announces') {
         $page = 'last_server_announces';
         $hf = 1;
         $location = '';
         $vars->{title} = 188;
         $vars->{doctype} = 1;
                  

         my $ret_last_server_announces = system::get_last_server_announces( { server_id => $q->{'s'}, } );
         $vars->{server_announces} = $ret_last_server_announces->{server_announces};

         
                                  
      } elsif ($q->{page} eq 'gsm_activate') {
         $page = 'gsm_activate';
         $hf = 1;
         $location = '';
         $vars->{title} = 188;
         $vars->{doctype} = 1;

         $main::check_gsm_subsystem->execute();
         my $working = $main::check_gsm_subsystem->fetchrow();
         $vars->{working} = $working;
         $main::check_gsm_subsystem->finish();

         if ($working == 0) {
            my $msg = MIME::Lite->new(
		From	=> 'SMSAccountActivation',
		To	=> 'soco@gsm.eurotel.sk',
		Subject	=> 'Nefunguju SMS aktivacie!!!',
		Type	=> 'text/plain',
		Data	=> 'Nefunguju SMS aktivacie!!!',
            );
#            $msg->send;
         }                                                                                                                                                                                          


         $main::get_gsm_number_by_nick_id->execute($vars->{nick_id});
         $vars->{gsm} = $main::get_gsm_number_by_nick_id->fetchrow_hashref();
         $main::get_gsm_number_by_nick_id->finish();

         foreach (keys(%{$map_prefixes})) {
            my $tmp = '\\'.$map_prefixes->{$_};
            if ($vars->{gsm}->{requested_gsm_number} =~ /^$tmp(\d+)$/) {
               $vars->{selected_prefix} = $_;
               $vars->{selected_number} = $1;
            }
         }

         $main::get_already_activated_count->execute();
         $vars->{activated} = $main::get_already_activated_count->fetchrow();
         my $last_activated;
         $main::get_last_activated_count->execute();
         foreach (@{$main::get_last_activated_count->fetchall_arrayref({})}) {
            $last_activated->{$_->{what}} = $_->{activated};
         }

         $vars->{last_activated} = $last_activated;

         $main::get_already_activated_count->finish();
                                    

#&page=import_in_game_chat&channel_id=18&type=1&msg='.$message.'&name='.$player);

      } elsif ($q->{page} eq 'import_in_game_chat') {
         $page = '';
         $hf = 0;
         $location = '';

         my $passwords = { '18' => 'kokotina', '100' => 'sSnFLXeQPbG' };

         if (defined($q->{channel_id}) && $q->{channel_id} =~ /^\d+$/ && defined($q->{msg}) && $q->{msg} ne '' && $q->{passwd} eq $passwords->{$q->{channel_id}}) {
            my $ret_message = system::add_chat_message( { msg_type => 'w', channel_id => $q->{channel_id}, nick_id => 0, faction => $q->{type}, message => system::htmlfilter($q->{msg}), pokec_nick => $q->{name}, ip => '127.0.0.1', }, );
            system::add_action( { action => 38, channel_id => $q->{channel_id}, message_id => $ret_message->{message_id}, value => 1, }, );
#warn "system::add_action( { action => 38, channel_id => $q->{channel_id}, message_id => $ret_message->{message_id}, value => 1, }, );";

         }



      } elsif ($q->{page} eq 'import_in_game_message') {
         $page = '';
         $hf = 0;
         $location = '';

         my $passwords = { '18' => 'kokotina', '100' => 'sSnFLXeQPbG' };

         if (defined($q->{channel_id}) && $q->{channel_id} =~ /^\d+$/ && defined($q->{message}) && $q->{message} ne '' && $q->{passwd} eq $passwords->{$q->{channel_id}}) {
            my $ret_message = system::add_chat_message( { msg_type => 'c', channel_id => $q->{channel_id}, nick_id => 0, message => $q->{message}.' ('.$q->{name}.')', ip => '127.0.0.1', }, );
            system::add_action( { action => 19, channel_id => $q->{channel_id}, message_id => $ret_message->{message_id}, value => 1, }, );
            $main::add_servers_announce->execute($q->{channel_id},$q->{message},$q->{name});
         }

      } elsif ($q->{page} eq 'import_gm_action') {
         $page = '';
         $hf = 0;
         $location = '';

         my $passwords = { '18' => 'kokotina', '100' => 'sSnFLXeQPbG' };


         if (defined($q->{channel_id}) && $q->{channel_id} =~ /^\d+$/ && defined($q->{message}) && $q->{message} ne '' && $q->{passwd} eq $passwords->{$q->{channel_id}}) {

            my $ret_gamemaster = system::get_gamemaster( { server_id => $q->{channel_id}, name => $q->{name}, }, );
            if ($ret_gamemaster->{gamemaster}->{chat_invisible} == 1) {
               $q->{what} = 2;
            }
            my $ret_message = system::add_chat_message( { msg_type => 'l', channel_id => $q->{channel_id}, nick_id => 0, message => $q->{message}, ip => '127.0.0.1', }, );
            system::add_action( { action => 32, channel_id => $q->{channel_id}, message_id => $ret_message->{message_id}, value => $q->{what}, }, );
         }

      } elsif ($q->{page} eq 'import_auction') {
         $page = '';
         $hf = 0;
         $location = '';

         my $passwords = { '18' => 'kokotina', '100' => 'sSnFLXeQPbG' };


         if (defined($q->{channel_id}) && $q->{channel_id} =~ /^\d+$/ && $q->{passwd} eq $passwords->{$q->{channel_id}}) {

            my $ret_item_by_entry_id = system::get_item_by_entry_id( { server_id => $q->{channel_id}, entry_id => $q->{item_template}, }, );
            my $item = $ret_item_by_entry_id->{item};

            if ($q->{change} == 1) {
               $main::add_auction->execute($q->{channel_id},1,$q->{auction_id},$q->{item_template},$q->{count},$q->{itemowner},$q->{buyoutprice},$q->{buyguid},$q->{lastbid},$q->{startbid},$item->{name},$item->{class},$item->{subclass},$item->{itemlevel},$item->{quality});
               system::add_action( { action => 36, channel_id => $q->{channel_id}, value => $q->{auction_id}, }, );

            } elsif ($q->{change} == 2) { # expired - no bid / buy out
               $main::set_expire_auction->execute(2,0,0,$q->{channel_id},$q->{auction_id});

            } elsif ($q->{change} == 3) { # sold - bid / buy out
               $main::set_expire_auction->execute(3,$q->{buyguid},$q->{lastbid},$q->{channel_id},$q->{auction_id});
            }

         }



      } elsif ($q->{page} eq 'server_info') {

         $main::set_server_id_to_nick_id->execute($q->{'server_id'},$vars->{nick_id});

         my $ret_ingame_gamemasters = system::get_ingame_gamemasters( { server_id => $q->{'server_id'}, }, );
         my $gamemasters = $ret_ingame_gamemasters->{gm_list};
                  
         my $get_last_server_state = system::get_last_server_state( { server_id => $q->{'server_id'}, }, );
         my $state = $get_last_server_state->{state};


         my $map_graphs = {
		'11' => '_pvsgm-hday',
		'12' => '_pvsgm-week',
		'13' => '_pvsgm-antik',
		'14' => '_pvsgm-small',
		'21' => '_hvsa-hday',
		'22' => '_hvsa-week',
		'23' => '_hvsa-antik',
		'24' => '_hvsa-small',
		'31' => '_races-hday',
		'32' => '_races-week',
		'33' => '_races-antik',
		'34' => '_races-small',
		'41' => '_classes-hday',
		'42' => '_classes-week',
		'43' => '_classes-antik',
		'44' => '_classes-small',
         };
         my $graph = 's'.$q->{server_id}.$map_graphs->{$vars->{graph_id}};
                                    
         
      
         $mime = 'text/xml';
         $html = '<?xml version="1.0" encoding="UTF-8"?><r><data><a>5</a><i>'.$q->{server_id}.'</i><sn>'.$state->{server_name}.'</sn>';
         $html .= '<ld>'.$state->{stamp_last_down}.'</ld>';
         $html .= '<lu>'.$state->{stamp_last_up}.'</lu>';
         $html .= '<hs>'.$state->{web_status}.'</hs>';
         $html .= '<as>'.$state->{auth_status}.'</as>';
         $html .= '<ws>'.$state->{world_status}.'</ws>';
         $html .= '<pt>'.($state->{players}+$state->{vips}+$state->{gamemasters}).'</pt>';
         $html .= '<pv>'.$state->{vips}.'</pv>';
         $html .= '<ph>'.$state->{horde}.'</ph>';
         $html .= '<pa>'.$state->{alliance}.'</pa>';
         $html .= '<cv>'.$state->{client_version}.'</cv>';
         $html .= '<sl>'.$state->{server_limit}.'</sl>';
         $html .= '<sr>'.$state->{ip}.'</sr>';
         $html .= '<gm>'.$gamemasters.'</gm>';
         $html .= '<sd>'.$state->{state_days}.'</sd>';
         $html .= '<sh>'.$state->{state_hours}.'</sh>';
         $html .= '<sm>'.$state->{state_minutes}.'</sm>';
         $html .= '<ss>'.$state->{state_seconds}.'</ss>';
         $html .= '<g>'.$graph.'</g>';

                           
         $html .= '</data></r>';
         
         
#         warn $html;      

      }





      if ($location eq '' && -f $globals::datadir."/templates/".$page.".tt2" && $mime eq '') {
         $vars->{elapsed} = &tv_interval($t0);;
         $vars->{utime} = $t0->[0];
         if ($usegzip) {print 'Content-Encoding: '.$usegzip."\n";}
         print 'Content-type: '.$contenttype."\n\n";
         if ($hf == 1) {$template->process('header.tt2', $vars, \$html) || warn $template->error();}
         $template->process($page.'.tt2', $vars, \$html) || warn $template->error();
         if ($hf == 1) {$template->process('footer.tt2', $vars, \$html) || warn $template->error();}
         if ($usegzip) {$html = Compress::Zlib::memGzip( $html );}
         print $html;
         $html = '';
      } elsif ($location ne '' && $mime eq '') {
         if ($set_cookie ne '') {print $set_cookie;}
         print 'Location: '.$location."\n\n";
         $request->Finish();
         next;
      } elsif ($location eq '' && $mime ne '') {
         print 'Content-type: '.$mime."\n\n";
         print $html;
         $request->Finish();
         next;
      } else {
         print 'Content-type: text/html'."\n\n".'bububu';
      }
   }

   $loop_instance--;

   if ($loop_instance <= 1) {
      last;
   }
}

$request->Finish();




sub plain_time_format($) {
   my ($utime) = @_;

   my $h = int($utime / 3600);
   my $stack = $utime % 3600;
   my $m = int($stack / 60);
   my $s= $stack  % 60;

   my $out;
   if ($h != 0) {$out = $h.'h ';}
   $out .= $m.'m ';

   return $out;
}




sub rewrite_item($) {

   my ($item_id) = @_;

   $main::get_item_lite->execute($item_id);
   my $item = $main::get_item_lite->fetchrow_hashref();
   $main::get_item_lite->finish();

   return '<span class="t1xt'.$map_qualities->{$item->{quality}}.'"><a href="javascript:void(0)" onclick="ai(\''.$item_id.'\')">+</a><a target="_blank" href="?id='.$item_id.'&page=show_item">['.$item->{item_name}.']</a></span>';
}


sub substitutions($) {
   my ($to_substitute) = @_;
   $to_substitute =~ s/S&(\d+)&/<font title="$substitutions_id->{$1}->{value}" style="cursor:help">$substitutions_id->{$1}->{shortcut}<\/font>/g;
   return $to_substitute;
}


sub substitutions_lite($) {
   my ($to_substitute) = @_;
   $to_substitute =~ s/S&(\d+)&/$substitutions_id->{$1}->{shortcut}/g;
   return $to_substitute;
}

