<?php

function generator($size){
	$size = intval($size);
	if ($size>32) $size =32;
	if ($size<1) $size =1;
	$chars="qazxswedcvfrtgbnhyujmkiolp1234567890";
	$leng=StrLen($chars)-1;
	$password='';
	while($size--) $password.=$chars[rand(0,$leng)];
	return($password);
}

function filter($t){
	$t = mysql_real_escape_string(htmlspecialchars(trim($t)));
	return $t;
}


function data($time = NULL) {
	if(!$time) $time = time();
	$data = date('j.n.y', $time);
	if($data == date('j.n.y')) $res = date('H:i:s', $time);
	else $res = '<span title="'.date('H:i:s', $time).'">'.date('d.m.y', $time).'</span>';
	return $res;
}

function navigation($all,$napage,$page,$url,$total){
	global $gets;
	if(!($all<=$napage)){
		echo '<div class="str">';
		if($page < 5){
			if($page != 1) for($i=1;$i < $page;$i++) echo '<a href="'.$url.'page='.$i.'&'.$gets.'"><span class="page">'.$i.'</span></a>';
		}
		else{
        	echo '<a href="'.$url.'page=1&'.$gets.'"><span class="page">1</span></a>';
        	echo '..';
            for($i=$page-3;$i < $page;$i++) echo '<a href="'.$url.'page='.$i.'&'.$gets.'"><span class="page">'.$i.'</span></a>';
		}
		echo '<span class="thispage">'.$page.'</span>';
		if($total - $page < 4){
			if($page != $total) for($i=$page+1;$i <= $total;$i++) echo '<a href="'.$url.'page='.$i.'&'.$gets.'"><span class="page">'.$i.'</span></a>';
		}
		else{
		    for($i=$page+1;$i < $page+4;$i++) echo '<a href="'.$url.'page='.$i.'&'.$gets.'"><span class="page">'.$i.'</span></a>';
		    echo '..';
        	echo '<a href="'.$url.'page='.$total.'&'.$gets.'"><span class="page">'.$total.'</span></a>';
		}
		echo '</div>';
	}
}

function chislo($num, $str1, $str2, $str3) {
	$num = intval($num);
	$val = $num % 100;
	if ($val > 10 && $val < 20) return $num .' '. $str3;
	else {
		$val = $num % 10;
		if ($val == 1) return $num .' '. $str1;
		elseif ($val > 1 && $val < 5) return $num .' '. $str2;
		else return $num .' '. $str3;
	}
}

function chislo_word($edinstv,$mnozh, $num, $str1, $str2, $str3) {
	$num = intval($num);
	if($num == 1) $word = $edinstv;
	else $word = $mnozh;
	$val = $num % 100;
	if ($val > 10 && $val < 20) return $word.' '.$num .' '. $str3;
	else {
		$val = $num % 10;
		if ($val == 1) return $word.' '.$num .' '. $str1;
		elseif ($val > 1 && $val < 5) return $word.' '.$num .' '. $str2;
		else return $word.' '.$num .' '. $str3;
	}
}

function pol($pol,$man,$woman){
	if($pol == 'woman') return $woman;
	else return $man;
}

function declination($num, $one, $ed, $mn, $notnumber = false) {
	if($num === "") print "";
	if(($num == "0") or (($num >= "5") and ($num <= "20")) or preg_match("|[056789]$|",$num))
	if(!$notnumber) return $num.' '.$mn;
	else return $mn;
	if(preg_match("|[1]$|",$num)) if(!$notnumber) return $num.' '.$one;
	else return $one;
	if(preg_match("|[234]$|",$num)) if(!$notnumber) return $num.' '.$ed;
	else return $ed;
}

function birthday($dday,$dmonth,$dyear){
	$sec_birthday = mktime(0, 0, 0, $dmonth, $dday, $dyear);
	$sec_now = time();
	for($time = $sec_birthday, $month = 0; $time < $sec_now; $time = $time + date('t', $time) * 86400, $month++) $rtime = $time;
	$month = $month - 1;
	$year = intval($month / 12);
	$month = $month % 12;
	$result = declination($year, "год", "года", "лет")." ";
	return $result;
}


function smiles($msg){
	global $set;
	if($set['images'] == 'on'){
		$msg=str_replace(array(':D',':-D',':Д',':-Д',':д',':-Д',':d',':-d'), '<img src="/images/smiles/biggrin.gif" alt="" />', $msg);
		$msg=str_replace(array('))',':)',':-)'), '<img src="/images/smiles/smile.gif" alt="" />', $msg);
		$msg=str_replace(array('((',':(',':-('), '<img src="/images/smiles/sad.gif" alt="" />', $msg);
		$msg=str_replace(array(':OK',':ok',':ОК',':ок',':Ok',':Ок'), '<img src="/images/smiles/ok.gif" alt="" />', $msg);
		$msg=str_replace(array(':lol',':LOL',':ЛОЛ',':лол'), '<img src="/images/smiles/lol.gif" alt="" />', $msg);
	}
	return $msg;
}

function strlen2($str){
	return iconv_strlen($str,'utf-8');
}

function vozrast($vozr){
    $res = '';
	$months = floor($vozr / (2592000));
	$vozr = $vozr - $months*2592000;
	$days = floor($vozr / (86400));
	if($months != 0) $res .= chislo($months,'месяц','месяца','месяцев').' и ';
	$res .= chislo($days,'день','дня','дней');
	return $res;
}

function icon($iconka){
	global $set;
	if($set['images'] == 'on') return '<img src="/images/icons/'.$iconka.'.png" alt=""> ';
	else return '';
}

function icon2($iconka){
	global $set;
	return '<img src="/images/icons/'.$iconka.'.png" class="icon_small" alt=""> ';
}

function zna4ok($iconka,$podpis){
	global $set;
	if($set['images'] == 'on') return ' <img src="/images/icons/'.$iconka.'.png" width="12px" height="12px" alt="" title="'.$podpis.'">';
	else return ' ['.$podpis.']';
}

function res_nado($deistvie,$money,$wood,$stone,$iron,$grain,$oil,$territory){

	global $country;

	if($country['money'] - $money <0) $nehvat_money = ' <font color="red">(не хватает '.($money - $country['money']).')</font>'; else $nehvat_money = '';
    if($country['wood'] - $wood <0) $nehvat_wood = ' <font color="red">(не хватает '.($wood - $country['wood']).')</font>'; else $nehvat_wood = '';
    if($country['stone'] - $stone <0) $nehvat_stone = ' <font color="red">(не хватает '.($stone - $country['stone']).')</font>'; else $nehvat_stone = '';
    if($country['iron'] - $iron <0) $nehvat_iron = ' <font color="red">(не хватает '.($iron - $country['iron']).')</font>'; else $nehvat_iron = '';
    if($country['grain'] - $grain <0) $nehvat_grain = ' <font color="red">(не хватает '.($grain - $country['grain']).')</font>'; else $nehvat_grain = '';
    if($country['oil'] - $oil <0) $nehvat_oil = ' <font color="red">(не хватает '.($oil - $country['oil']).')</font>'; else $nehvat_oil = '';
    if($country['territory_free'] - $territory <0) $nehvat_territory = ' <font color="red">(не хватает '.($territory - $country['territory_free']).')</font>'; else $nehvat_territory = '';

    t1();
	echo 'Для '.$deistvie.' требуется:<br/>';
	if($money != 0) echo 'Монет: '.$money.'/'.$country['money'].$nehvat_money.'<br/>';
	if($wood != 0) echo 'Дерева: '.$wood.'/'.$country['wood'].$nehvat_wood.'<br/>';
	if($stone != 0) echo 'Камня: '.$stone.'/'.$country['stone'].$nehvat_stone.'<br/>';
	if($iron != 0) echo 'Железа: '.$iron.'/'.$country['iron'].$nehvat_iron.'<br/>';
	if($grain != 0) echo 'Зерна: '.$grain.'/'.$country['grain'].$nehvat_grain.'<br/>';
	if($oil != 0) echo 'Нефти: '.$oil.'/'.$country['oil'].$nehvat_oil.'<br/>';
	if($territory != 0) echo 'Территории: '.$territory.'/'.$country['territory_free'].$nehvat_territory.'<br/>';
	t2();
}

function res_proverka($money,$wood,$stone,$iron,$grain,$oil,$territory){
	global $country;
    if ($country['money'] - $money < 0) return false;
    else  if ($country['wood'] - $wood < 0) return false;
    else if ($country['stone'] - $stone < 0) return false;
    else if ($country['iron'] - $iron < 0) return false;
    else if ($country['grain'] - $grain < 0) return false;
    else if ($country['oil'] - $oil < 0) return false;
    else if ($country['territory_free'] - $territory < 0) return false;
    else return true;

}

function res_okrugl($res,$name_rp){
	if ($res>=1000000000) return '<span title="'.$res.' '.$name_rp.'">'.round($res/1000000000,0).'G</span>';
	else if ($res>=1000000) return '<span title="'.$res.' '.$name_rp.'">'.round($res/1000000,0).'M</span>';
	else if ($res>=1000) return '<span title="'.$res.' '.$name_rp.'">'.round($res/1000,0).'K</span>';
	else return '<span title="'.$res.' '.$name_rp.'">'.$res.'</span>';
}

function user($user_id){
	global $set;
	$usr =  mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = ".$user_id.""));
	$vihod = '';
    if($set['images'] == 'on'){
    	if($usr['time_last'] > time() - $set['timeon']) $status= 'on';
		else $status = 'off';
		if($usr['level'] == 1) $icon = $usr['gender'];
		else $icon = 'mod';
		$vihod .= '<img src="/images/icons/users/'.$icon.'_'.$status.'.png" alt="'.$status.'"> ';
    }
    else{
    	$zaglav = mb_substr($usr['nick'], 0, 1, 'utf-8');
    	if($usr['time_last'] > time() - $set['timeon']) $usr['nick'] =  '<font color="green">'.$zaglav.'</font>'.mb_substr($usr['nick'], 1, 20, 'utf-8');
		else $usr['nick'] =  '<font color="red">'.$zaglav.'</font>'.mb_substr($usr['nick'], 1, 20, 'utf-8');

    }
    $vihod .= $usr['nick'];

	if($set['images'] == 'off'){
		if($usr['level'] == 4) $vihod .= ' <font color="#C4C4C4" title="Создатель">[соз]</font>';
		else if($usr['level'] == 3) $vihod .= ' <font color="#C4C4C4" title="Администратор">[адм]</font>';
		else if($usr['level'] == 2) $vihod .= ' <font color="#C4C4C4" title="Модератор">[мд]</font>';
    }
	return $vihod;
}

function num($chislo){
	return abs(intval($chislo));
}

function period($otrezok){
    $res = '';
    if($otrezok >= 3600){
    	 $chasi = floor($otrezok / 3600);
         $otrezok = $otrezok - $chasi * 3600;
    }

    if($otrezok >= 60){
    	 $minuti = floor($otrezok / 60);
         $otrezok = $otrezok - $minuti * 60;
    }

	if($chasi != 0) $res .= chislo($chasi,'час','часа','часов');
	if($minuti != 0 AND $chasi != 0) $res .= ', ';
	if($minuti != 0) $res .= chislo($minuti,'минута','минуты','минут');
	if(($minuti != 0 OR $chasi != 0) AND $otrezok != 0) $res .= ' и ';
	if($otrezok != 0) $res .= chislo($otrezok,'секунда','секунды','секунд');
	return $res;
}

function provel($otrezok){
    $res = '';
    if($otrezok < 60) $res.= chislo($otrezok,'секунда','секунды','секунд');

    if($otrezok >= 3600){
    	 $chasi = floor($otrezok / 3600);
         $otrezok = $otrezok - $chasi * 3600;
    }

    if($otrezok >= 60){
    	 $minuti = floor($otrezok / 60);
         $otrezok = $otrezok - $minuti * 60;
    }

	if($chasi != 0) $res .= chislo($chasi,'час','часа','часов');
	if($minuti != 0 AND $chasi != 0) $res .= ' и ';
	if($minuti != 0) $res .= chislo($minuti,'минута','минуты','минут');

	return $res;
}

function time_right($vremja){
	return '<span class="time">'.data($vremja).'</span>';
}

function deleted($udalil){
	global $user;
	if($udalil != 0 AND $user['level'] >= 2 AND $user) return ' <font color="red">[Удалил '.user($udalil).']</font>';
	else return '';
}


function BBcode($msg){
	global $set;
 	$bbcode=array();
	$bbcode['/\[i\](.+)\[\/i\]/isU'] = '<em>$1</em>';
	$bbcode['/\[b\](.+)\[\/b\]/isU'] = '<strong>$1</strong>';
	$bbcode['/\[u\](.+)\[\/u\]/isU'] = '<span style="text-decoration:underline;">$1</span>';
	$bbcode['/\[small\](.+)\[\/small\]/isU'] = '<small>$1</small>';
	$bbcode['/\[red\](.+)\[\/red\]/isU'] = '<span style="color:#ff0000;">$1</span>';
	$bbcode['/\[yellow\](.+)\[\/yellow\]/isU'] = '<span style="color:#ffff22;">$1</span>';
	$bbcode['/\[green\](.+)\[\/green\]/isU'] = '<span style="color:#00bb00;">$1</span>';
	$bbcode['/\[blue\](.+)\[\/blue\]/isU'] = '<span style="color:#0000bb;">$1</span>';
	if (count($bbcode)) $msg = preg_replace(array_keys($bbcode), array_values($bbcode), $msg);
 	return $msg;
}

function voisko($pehota,$kavaleria,$strelki){
	$res = '';
	if($pehota != 0 OR $kavaleria != 0 OR $strelki != 0){
	    if($strelki != 0) $res .= chislo($strelki, 'стрелок', 'стрелка', 'стрелков');
        if($strelki != 0 AND $pehota != 0 AND $kavaleria != 0) $res .= ', ';
	    if($kavaleria != 0) $res .= chislo($kavaleria, 'кавалерист', 'кавалериста', 'кавалеристов');
	    if($pehota != 0 AND ($strelki != 0 OR $kavaleria != 0)) $res .= ' и ';
	    if($pehota != 0) $res .= chislo($pehota, 'пехотинец', 'пехотинца', 'пехотинцев');
	}
	else $res .= 'отсутствует';
	return $res;
}

function a_user($user_id,$time=null){
	global $set;
	$usr =  mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = ".$user_id.""));

	if($set['images'] == 'on'){
		$icon = 'users/';
		if($usr['level'] == 1) $icon .= $usr['gender'];
		else $icon .= 'mod';
    	if($usr['time_last'] > time() - $set['timeon']) $icon .= '_on';
		else $icon .= '_off';

    }
    else{
    	$zaglav = mb_substr($usr['nick'], 0, 1, 'utf-8');
    	if($usr['time_last'] > time() - $set['timeon']) $usr['nick'] =  '<font color="green">'.$zaglav.'</font>'.mb_substr($usr['nick'], 1, 20, 'utf-8');
		else $usr['nick'] =  '<font color="red">'.$zaglav.'</font>'.mb_substr($usr['nick'], 1, 20, 'utf-8');
    }

	if($set['images'] == 'off'){
		if($usr['level'] == 4) $dolzh = ' <font color="#C4C4C4" title="Создатель">[соз]</font>';
		else if($usr['level'] == 3) $dolzh = ' <font color="#C4C4C4" title="Администратор">[адм]</font>';
		else if($usr['level'] == 2) $dolzh = ' <font color="#C4C4C4" title="Модератор">[мд]</font>';
		else $dolzh = '';
    }
    if($time != '') a('/user.php?id='.$user_id.'&','<span class="time"><small>'.$time.'</small></span>'.$usr['nick'].$dolzh,$icon);
    else a('/user.php?id='.$user_id.'&',$usr['nick'].$dolzh,$icon);
}

?>