<?php
session_start();
// Corporate Adreess book v 1.8.0.1 admin
// (c) Shamarinov V.V. 2007-2012

if (isset($_POST['config']))
 {
 $file= @fopen("config.php","wb");

 fwrite ($file, stripslashes($_POST['config']));
 fclose($file);
 }
include("config.php");

function GetIP()
    {
     global $HTTP_SERVER_VARS;

     $IP = $HTTP_SERVER_VARS["REMOTE_ADDR"];
     if(isset($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])) {
         $IP .= " ".$HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
     }

     $IPS = @split("[ ;,]",$IP);
     $IP = "";
     while(list($i,$VAL) = each($IPS)) $IP .= $VAL.",";
     $IP = substr($IP,0,strlen($IP)-1);

     return Trim($IP);
    }
$myip = GetIP();
$myip = Trim($HTTP_SERVER_VARS["REMOTE_ADDR"]);
if ($myip=="192.168.0.1")
 $myip = Trim($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]);


$admip = 0;
/*                 // надо снять комментарий чтобы сделать автологин по ip
@$fp = fopen("ip","rt");
if ($fp)
 {
 while (!feof($fp))
  {
  $ip = Trim(fgets($fp));
  if ($myip == $ip) $admip = 1;
  }
 fclose($fp);
 }
*/
if (!$admip)
 {
 if (isset($_POST['pass']))
  {
  if ($_POST['pass']==$adminpass)
   $_SESSION['admin']=1;
  else
   {
   echo "
   <html>
   <head>
    <title>Администрирование $maintitle</title>
   </head>
   <body>
   <center>
   Вы ввели неправильный пароль!<br>
    <form method=post>
     Введите пароль администратора:<br><br>
    <input type='password' name='pass'>
    <input type='submit' name='submit' value='Вход'>
   </form>
   </center>
   </body>
   </html>
   ";
   return;
   }
  }
 if (!isset($_SESSION['admin']))
  {
  echo "
   <html>
   <head>
    <title>Администрирование $maintitle</title>
   </head>
   <body>
   <center>
   <form method=post>
    Введите пароль администратора для редактирования телефонной книги:<br><br>
    <input type='password' name='pass'>
    <input type='submit' name='submit' value='Вход'>
    </form>
    </center>
   </body>
   </html>
   ";
  return;
  }
 }
?>
<!doctype html public "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
  <title>Администрирование <?php echo $maintitle?></title>
</head>
<link rel="stylesheet" href="images-silver/style.css" type="text/css">

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />

<body>
<script type="text/javascript" language="javascript">
var intid = 0;
function makeRequest(url,object) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
// Читайте ниже об этой строке
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Не вышло  Невозможно создать экземпляр класса XMLHTTP ');
return false;
}
http_request.onreadystatechange = function() { alertContents(http_request,object); };
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents(http_request,object) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById(object).innerHTML = http_request.responseText;
} else {
alert('С запросом возникла проблема.');
}
}
}
/*
function fadeline(ind)
 {
 h = document.getElementById("tr"+ind).style.height;
 alert(h);
 if (h<=1)
  {
  document.getElementById("tr"+ind).style.display = "none";
  clearInterval(intid);
  }
 else h-=1;
 document.getElementById("tr"+ind).style.height = h;
 }
*/
function normcolor(ind)
 {
 document.getElementById("tr"+ind).style.background = "#F0F0F0";
 }

function del(ind)
 {
 oldcol = document.getElementById("tr"+ind).style.background;
 if (oldcol=="") oldcol="#F0F0F0";
 document.getElementById("tr"+ind).style.background = "#FFA0A0";
 ok=confirm("Вы действительно хотите удалить запись?");
 if (ok==true)
  {
  //intid = setInterval("fadeline("+ind+")",100);
  document.getElementById("tr"+ind).style.display = "none";
  makeRequest("delete.php?id="+ind,"request");
  }
 document.getElementById("tr"+ind).style.background = oldcol;
 /*
 if (ok==true) location.href="admin.php?delete="+ind;
 else
  {
  location.href="admin.php";
  location.reload();
  }
 */
 }
function delfoto(ind)
 {
 ok=confirm("Вы действительно хотите удалить фотографию?");
 if (ok==true) location.href="admin.php?edit="+ind+"&delfoto=1";
 else
  {
  location.href="admin.php?edit="+ind;
  location.reload();
  }
 }
function ok(type,ind)
 {
 val = document.getElementById(type+"input"+ind).value;
 document.getElementById(type+"d"+ind).innerHTML = val;
 document.getElementById(type+ind).style.display = "inline";
 document.getElementById(type+"ed"+ind).style.display = "none";
 /*
 if (type=="perm")
  {
  permcaption = "";
  switch (val)
   {
   case 't':  permcaption="Междугор. вызов"; break;
   case 'a':  permcaption="Отв. лицо"; break;
   case 'sa': permcaption="Админ"; break;
   case 'hidden': permcaption="Скрыт"; break;
   case 'hiddent': permcaption="Скрыт/Междугор.выз"; break;
   default:   permcaption="&nbsp;"; break;
   }
  document.getElementById("permcaption"+ind).innerHTML = permcaption;
  if (val=="hidden" || val=="hiddent")
   document.getElementById("tr"+ind).style.background = "#E0E0E0";
  else
   document.getElementById("tr"+ind).style.background = "#F0F0F0";
  }
 */
 makeRequest("change.php?id="+ind+"&field="+type+"&value="+encodeURIComponent(val),"request");
 //снимаем выделение с редактируемой строчки
 document.getElementById("tr"+ind).style.background = "#F0F0F0";
 }
function cancel(type,ind)
 {
 document.getElementById(type+ind).style.display = "inline";
 document.getElementById(type+"ed"+ind).style.display = "none";
 //снимаем выделение с редактируемой строчки
 document.getElementById("tr"+ind).style.background = "#F0F0F0";
 }
function edit(type,ind,vid)
 {
 /*
    <div id="<?php echo $type?>ed<?php echo $ind?>"  style="display: none">
     <input id='<?php echo $type?>input<?php echo $ind?>' type=text value='<?php echo $value?>'>
     <img src="ok.png" width="16" height="16" alt="Ok" onclick="ok('<?php echo $type?>',<?php echo $ind?>)" />
     <img src="cancel.gif" width="16" height="16" alt="Cancel" onclick="cancel('<?php echo $type?>',<?php echo $ind?>)"/>
    </div>
 */
 val = document.getElementById(type+"d"+ind).innerHTML;
 size = "";
 if (type=="tel" || type=="room") size="style='width: 80px'";
 //divhtml="<div id='"+type+"ed"+ind+"'>";
 switch (vid)
  {
  case "text": divhtml="<textarea id='"+type+"input"+ind+"' type=text rows='3'>"+val+"</textarea>";break;
  default: divhtml="<input id='"+type+"input"+ind+"' type=text value='"+val+"' "+size+" >";break;
  }
 divhtml+='<img src="images/ok.png" width="16" height="16" alt="Ok" onclick="ok(\''+type+'\','+ind+')" style="cursor: pointer" />';
 divhtml+='<img src="images/cancel.gif" width="16" height="16" alt="Ok" onclick="cancel(\''+type+'\','+ind+')" style="cursor: pointer" />';

 document.getElementById(type+"ed"+ind).innerHTML = divhtml;

 document.getElementById(type+"input"+ind).value = val;
 document.getElementById(type+ind).style.display = "none";
 document.getElementById(type+"ed"+ind).style.display = "inline";
 //выделяем редактируемую строчку
 document.getElementById("tr"+ind).style.background = "#FAFAFA";
 }
function perm(ind,value)
 {
 if (value=="hidden" || value=="hiddent")
  document.getElementById("tr"+ind).style.background = "#E0E0E0";
 else
  document.getElementById("tr"+ind).style.background = "#F0F0F0";
 makeRequest("change.php?id="+ind+"&field=perm&value="+encodeURIComponent(value),"request");
 }
function up(ind)
 {
 prev = document.getElementById("prev"+ind).value;
 if (prev==0) return;
 if (document.getElementById("tr"+prev).style.display == "none") return;
 h = new Array(7);
 h[0]="name";
 h[1]="rank";
 h[2]="tel";
 h[3]="mail";
 h[4]="room";
 h[5]="dep";
 h[6]="perm";
 for (i=0;i<6;i++)
  {
  temp = document.getElementById(h[i]+"d"+prev).innerHTML;
  document.getElementById(h[i]+"d"+prev).innerHTML = document.getElementById(h[i]+"d"+ind).innerHTML;
  document.getElementById(h[i]+"d"+ind).innerHTML = temp;
  }
 temp = document.getElementById("perm"+prev).value;
 document.getElementById("perm"+prev).value = document.getElementById("perm"+ind).value;
 document.getElementById("perm"+ind).value = temp;
 document.getElementById("tr"+prev).style.background = "#FCFCFC";
 intid = setTimeout("normcolor("+prev+")",500);
 makeRequest("exchange.php?from="+ind+"&to="+prev,"request");
 }
function down(ind)
 {
 next = document.getElementById("next"+ind).value;
 if (next==0) return;
 if (document.getElementById("tr"+next).style.display == "none") return;
 h = new Array(7);
 h[0]="name";
 h[1]="rank";
 h[2]="tel";
 h[3]="mail";
 h[4]="room";
 h[5]="dep";
 h[6]="perm";
 for (i=0;i<6;i++)
  {
  temp = document.getElementById(h[i]+"d"+next).innerHTML;
  document.getElementById(h[i]+"d"+next).innerHTML = document.getElementById(h[i]+"d"+ind).innerHTML;
  document.getElementById(h[i]+"d"+ind).innerHTML = temp;
  }
 temp = document.getElementById("perm"+next).value;
 document.getElementById("perm"+next).value = document.getElementById("perm"+ind).value;
 document.getElementById("perm"+ind).value = temp;
 document.getElementById("tr"+next).style.background = "#FCFCFC";
 setTimeout("normcolor("+next+")",500);
 makeRequest("exchange.php?from="+ind+"&to="+next,"request");
 }
function turboup(ind)
 {
 c=10; //на сколько перемещаем вверх
 prev = document.getElementById("prev"+ind).value;
 setTimeout("tu("+ind+","+prev+","+c+")",200);
 }
function tu(ind,prev,c)
 {
 if (prev==0) return;
 if (document.getElementById("tr"+prev).style.display == "none") return;
 h = new Array(7);
 h[0]="name";
 h[1]="rank";
 h[2]="tel";
 h[3]="mail";
 h[4]="room";
 h[5]="dep";
 h[6]="perm";
 for (i=0;i<6;i++)
  {
  temp = document.getElementById(h[i]+"d"+prev).innerHTML;
  document.getElementById(h[i]+"d"+prev).innerHTML = document.getElementById(h[i]+"d"+ind).innerHTML;
  document.getElementById(h[i]+"d"+ind).innerHTML = temp;
  }
 document.getElementById("perm"+prev).value = document.getElementById("perm"+ind).value;
 document.getElementById("perm"+ind).value = temp;
 document.getElementById("tr"+prev).style.background = "#FCFCFC";
 setTimeout("normcolor("+prev+")",250);
 makeRequest("exchange.php?from="+ind+"&to="+prev,"request");
 ind = prev;
 prev = document.getElementById("prev"+ind).value;
 c--;
 if (c>0) setTimeout("tu("+ind+","+prev+","+c+")",200);
 }

function turbodown(ind)
 {
 c=10; //на сколько перемещаем вверх
 next = document.getElementById("next"+ind).value;
 setTimeout("td("+ind+","+next+","+c+")",200);
 }
function td(ind,next,c)
 {
 if (next==0) return;
 if (document.getElementById("tr"+next).style.display == "none") return;
 h = new Array(7);
 h[0]="name";
 h[1]="rank";
 h[2]="tel";
 h[3]="mail";
 h[4]="room";
 h[5]="dep";
 h[6]="perm";
 for (i=0;i<6;i++)
  {
  temp = document.getElementById(h[i]+"d"+next).innerHTML;
  document.getElementById(h[i]+"d"+next).innerHTML = document.getElementById(h[i]+"d"+ind).innerHTML;
  document.getElementById(h[i]+"d"+ind).innerHTML = temp;
  }
 temp = document.getElementById("perm"+next).value;
 document.getElementById("perm"+next).value = document.getElementById("perm"+ind).value;
 document.getElementById("perm"+ind).value = temp;
 document.getElementById("tr"+next).style.background = "#FCFCFC";
 setTimeout("normcolor("+next+")",250);
 makeRequest("exchange.php?from="+ind+"&to="+next,"request");
 ind = next;
 next = document.getElementById("next"+ind).value;
 c--;
 if (c>0) setTimeout("td("+ind+","+next+","+c+")",200);
 }
</script>
<center>
<table cellpadding=2 cellspacing=1 class=forumline>
<tr><th colspan=2 class=thCornerL1 height=25 nowrap=nowrap><b><i><a name="begin"></a> Администрирование <?php echo $maintitle?> </i></b></th></tr>
<tr><td>

<?php 
/*
if ($_SESSION['find']==1)
 {
 $find=1;
 if (!isset($findval)) $findval=$_SESSION['findv'];
 }
*/


mysql_connect ($dbhost, $username, $password);
mysql_select_db ($maindb);

if (isset($_GET['edit'])) $edit = $_GET['edit'];
if (isset($_GET['add'])) $add = $_GET['add'];
if (isset($_GET['addfoto'])) $addfoto = $_GET['addfoto'];
if (isset($_GET['delfoto'])) $delfoto = $_GET['delfoto'];
if (isset($_GET['editcomp'])) $editcomp = $_GET['editcomp'];
if (isset($_GET['replace'])) $replace = $_GET['replace'];

if (isset($_GET['find'])) $find = $_GET['find'];
if (isset($_GET['findval'])) $findval = $_GET['findval'];
if (isset($_GET['fselect'])) $fselect = $_GET['fselect'];
if (isset($_POST['findval'])) $findval = $_POST['findval'];
if (isset($_POST['fselect'])) $fselect = $_POST['fselect'];
if (isset($_POST['sort'])) $sort = $_POST['sort'];

//настройки уменьшенных изображений по умолчанию
if (!isset($th_show))     $th_show = 1;
if (!isset($th_img_w))    $th_img_w = 16;
if (!isset($th_img_h))    $th_img_h = 20;
if (!isset($th_img_zoom)) $th_img_zoom = 2;
//настройки подписей столбцов по умолчанию
if (!isset($header_num))  $header_num="№";
if (!isset($header_name)) $header_name="Фамилия Имя Отчество";
if (!isset($header_rank)) $header_rank="Должность";
if (!isset($header_tel))  $header_tel="№ тел.";
if (!isset($header_mail)) $header_mail="E-mail";
if (!isset($header_room)) $header_room="№ ком.";
if (!isset($header_dep))  $header_dep="Отдел";
//для поиска по умолчанию
if (!isset($fheader_all))  $fheader_all="везде";
if (!isset($fheader_name)) $fheader_name="по Ф.И.О.";
if (!isset($fheader_rank)) $fheader_rank="по должности";
if (!isset($fheader_tel))  $fheader_tel= "по телефону";
if (!isset($fheader_mail)) $fheader_mail="по комнате";
if (!isset($fheader_room)) $fheader_room="по отделу";
if (!isset($fheader_dep))  $fheader_dep= "по e-mail";

if (!isset($_POST['showphoto'])) $_POST['showphoto']=$th_show;

$dval  = $_POST['dval'];
$rval  = $_POST['rval'];

$tname = $_POST['tname'];
$trank = $_POST['trank'];
$ttel  = $_POST['ttel'];
$tmail = $_POST['tmail'];
$troom = $_POST['troom'];
$tdep  = $_POST['tdep'];
$tperm  = $_POST['tperm'];

if (!isset($edit))  // новая запись
 {
 ?>
 <script>
 function newstrclick()
  {
  if (document.getElementById("newstr").style.display=="none")
   {
   document.getElementById("newstr").style.display="table";
   document.getElementById("newstrimg").src="images/hide.png";
   }
  else
   {
   document.getElementById("newstr").style.display="none";
   document.getElementById("newstrimg").src="images/show.png";
   }
  }
 function configclick()
  {
  if (document.getElementById("config").style.display=="none")
   {
   document.getElementById("config").style.display="table";
   document.getElementById("configimg").src="images/hide.png";
   }
  else
   {
   document.getElementById("config").style.display="none";
   document.getElementById("configimg").src="images/show.png";
   }
  }
 function importclick()
  {
  if (document.getElementById("import").style.display=="none")
   {
   document.getElementById("import").style.display="table";
   document.getElementById("importimg").src="images/hide.png";
   }
  else
   {
   document.getElementById("import").style.display="none";
   document.getElementById("importimg").src="images/show.png";
   }
  }
 </script>
 <?php 
 echo "<center>";
 /*
 ?>
 <a id="newstrlink" href="JavaScript:" onclick="document.getElementById('newstr').style.display='table';this.style.display='none';">Новая запись<br /></a>
 <a id="configlink" href="JavaScript:" onclick="document.getElementById('config').style.display='table';this.style.display='none';">Конфигурация<br /></a>
 <?php 
 */
 echo "<table cellpadding=2 cellspacing=1 class=forumline width='100%' >
       <tr><th class=thCornerL3 height=25 nowrap=nowrap style='cursor:pointer'  onclick='newstrclick()'> Новая запись <img id='newstrimg' src='images/show.png'/> </th></tr>
       <tr ><td align=center>";
 //echo "<h4>Новая запись:</h4>";
 echo "<form action='admin.php?add=1' method=post>";
 echo "<table id='newstr' style='display:none' cellspacing='1' cellpadding='3' bgcolor='#000000' style='font-family:tahoma;font-size:14px;' width=100%> ";
 echo " <tr style='background-color:#CCF;'>";
 echo "  <th>$header_name</th>";
 echo "  <th>$header_rank</th>";
 echo "  <th>$header_tel</th>";
 echo "  <th>$header_mail</th>";
 echo "  <th>$header_room</th>";
 echo "  <th>$header_dep</th>";
 echo " </tr>";
 echo " <tr style='background-color:#F0F0F0;' valign=middle>";
 ?>

 <td><input type=text name=tname value='' style='width:99%'></td>
 <td><input type=text name=trank value='' style='width:99%'></td>
 <td><input type=text name=ttel  value='' style='width:99%'></td>
 <td><input type=text name=tmail value='' style='width:99%'></td>
 <td><input type=text name=troom value='' style='width:99%'></td>
 <td>
  <table cellpadding="0" cellspacing="0"><tr><td>
  <!--<input type=hidden name=tdep  value='<?php echo $tdep?>' size=30>-->
  <select name=tdep id=seldep style="width: 100%; ">
   <option value='' >...</option>
   <?php 
   $result = mysql_query ("SELECT DISTINCT dep FROM t1 ORDER BY dep;");
   unset($dd);
   while ($value = mysql_fetch_array($result))
    $dd[]=$value[0];
   sort($dd);
   for ($i=0;$i<count($dd);$i++)
    {
    $val=$dd[$i];
    echo "<option value='$val'>$val</option>";
    }
   ?>
  </select>
  <input type=text name=tdep2 id=txtdep style="width:100%;display: none" value="<?php echo $tdep?>"    />
  </td><td>
  <button id=selbtn onclick="getElementById('txtdep').value=getElementById('seldep').value;getElementById('txtdep').name='tdep';getElementById('seldep').name='tdep2';getElementById('txtdep').style.display='inline';getElementById('seldep').style.display='none';getElementById('txtbtn').style.display='inline';getElementById('selbtn').style.display='none'" type="button" style="position: relative">...</button>
  <button id=txtbtn onclick="getElementById('txtdep').name='tdep2';getElementById('seldep').name='tdep';getElementById('txtdep').style.display='none';getElementById('seldep').style.display='inline';getElementById('txtbtn').style.display='none';getElementById('selbtn').style.display='inline'" style="display: none;position: relative" type="button"> &gt; </button>
  </td></tr></table>
 </td>


 <?php 
 /*
 echo "  <td><input type=text name=tname size=30></td>";
 echo "  <td><input type=text name=trank></td>";
 echo "  <td><input type=text name=ttel size=10></td>";
 echo "  <td><input type=text name=tmail size=30></td>";
 echo "  <td><input type=text name=troom size=10></td>";
 echo "  <td><input type=text name=tdep size=30></td>";
 */
 echo " </tr>";
 ?>
 <tr style="background: #F8F8F8" onmousemove="style.background='#D0F8D0'"  onmouseout="style.background='#F8F8F8'">
  <td colspan=6 align="center" style="cursor: pointer; " onclick="getElementById('addbutton').click();" >
   <b>Добавить</b>
   <input id="addbutton" type=submit value='Добавить' style="width: 100%; display:none; " align="center">
  </td>
 </tr>
 <?php 
 echo "</table>";
 echo "</form>";
 //echo "<br>";
 echo "</td></tr>"

 ?>
 <tr><th class=thCornerL3 height=25 nowrap=nowrap style='cursor:pointer'  onclick='configclick()'> Настройки <img id="configimg" src='images/show.png'/> </th></tr>
 <tr><td id=config style="display: none">
  <form method="post">
  <textarea name="config" style="width: 600px" rows="20"><?php 
   $file= @fopen("config.php","rb");
   fpassthru($file);
   fclose($file);
   ?></textarea>
  <table cellspacing="1" cellpadding="3" bgcolor="#000000" width="100%">
  <tr style="background: #F8F8F8; cursor: pointer" align="center">
   <td colspan=4 onmousemove="style.background='#D0F8D0'"  onmouseout="style.background='#F8F8F8'" onclick='getElementById("sendconfig").click()'><b>Сохранить</b></td>
   <td colspan=3 onmousemove="style.background='#F8F8D0'"  onmouseout="style.background='#F8F8F8'" onclick='document.location.href="admin.php"'><b>Отмена</b></td>
  </tr>
  </table>

   <input type="submit" id="sendconfig" style="display:none" />
  </form>
 </td></tr>
 <tr><th class=thCornerL3 height=25 nowrap=nowrap style='cursor:pointer'  onclick='importclick()'> Импорт из файла Excel (xls)<img id="importimg" src='images/show.png'/> </th></tr>
 <tr><td id=import style="display: none">

    <form method="post" enctype="multipart/form-data">
      <font color="#000000">
        <!-- accept="application/vnd.ms-excel" -->
        Выберите xls-файл для импорта 
        <input type="file" name="filename" onchange="getElementById('upldbtn').click()" accept="application/vnd.ms-excel" >
        <input type="hidden" name="uploadcsv" value="1">
        <input type="submit" id="upldbtn" value="Импорт" class="btn" style="display: none" />
        <input type="button" class="btn" value="Отмена" onclick="document.location.href='?action=cancel'"/> 
        
             <input type="checkbox" name="cleartable" value="1"/> удалить имеющиеся данные
             <!--
             &nbsp;<a href="sample.xls">[Скачать образец файла для загрузки]</a>
             -->
      </font>
    </form>
         
 </td></tr>

 <?php 
 
if (isset($_POST['uploadcsv']) && $_POST['uploadcsv']==1)
{
    echo "<tr><td>";
        if ($_POST['cleartable']==1)
    mysql_query("TRUNCATE t1;");

        

     $newfn = "xls/".htmlspecialchars(translit2en($_FILES["filename"]["name"]));
     if(!copy($_FILES["filename"]["tmp_name"], $newfn))
      {
      ?>
      <div class="erorrmsg">
      Ошибка загрузки файла!
      </div>
      <?
      }
     else
      {
      echo("<b>Файл успешно загружен!</b> <br>");
      require_once ('Excel/reader.php');

      $data = new Spreadsheet_Excel_Reader();
      $data->setOutputEncoding('cp-1251');
      $data->setUTFEncoder('mb'); $data->read($newfn);

      $table="t1";
      //print_r($data->sheets[0]['cells']);
      $y0=0;
      for ($i=1;$i<count($data->sheets[0]['cells']);$i++)
       if (substr($data->sheets[0]['cells'][$i][1],0,1)=="N" || substr($data->sheets[0]['cells'][$i][1],0,1)=="№")
       {
        $y0=$i+1;
       }
      $newitems=0;
      for ($y=$y0;$y<=count($data->sheets[0]['cells']);$y++)
       if ($data->sheets[0]['cells'][$y][2]!="")
        {
        unset($row);
        $row = $data->sheets[0]['cells'][$y];
        $sql = "INSERT INTO $table VALUES('0','{$row[2]}','{$row[3]}','{$row[4]}','{$row[5]}','{$row[6]}','{$row[7]}','')";
        mysql_query($sql);
        $newitems++;
        }
      //echo "$newgroups-$newitems-$repitems<br />";
       echo "Файл успешно импортирован!<br>Добавлено новых записей: $newitems";
        
    echo "</td></tr>";
    } 
 }
 echo "</table>";
 echo "</center>";
 }
else
 {
 $result = mysql_query ("SELECT * FROM t1 WHERE id='$edit';");
 $value = mysql_fetch_array($result);
// $tid   = $value[0];
 $tname = $value[1];
 $trank = $value[2];
 $ttel  = $value[3];
 $tmail = $value[4];
 $troom = $value[5];
 $tdep  = $value[6];
 $tperm = $value[7];
 ?>

 <center>


 <!--<h4>Редактирование записи:</h4>-->
 <table cellpadding=2 cellspacing=1 class=forumline><form action='admin.php?editcomp=<?php echo $edit?>' method=post>
 <tr><th colspan=2 class=thCornerL3 height=25 nowrap=nowrap><b> Редактирование записи </b></th></tr>
 <tr><td>
 <table cellspacing="1" cellpadding="3" bgcolor="#000000" style="font-family:tahoma;font-size:14px;" >
  <tr style='background-color:#CCF;' valign=middle>
   <!--<th>id</th>-->
   <th><?php echo $header_name?></th>
   <th><?php echo $header_rank?></th>
   <th><?php echo $header_tel?></th>
   <th><?php echo $header_mail?></th>
   <th><?php echo $header_room?></th>
   <th><?php echo $header_dep?></th>
   <th>Права</th>
  </tr>
  <tr style='background-color:#F0F0F0;' valign=middle>


 <td><input type=text name=tname value='<?php echo $tname?>' size=32></td>
 <td><input type=text name=trank value='<?php echo $trank?>'></td>
 <td><input type=text name=ttel  value='<?php echo $ttel?>' size=10></td>
 <td><input type=text name=tmail value='<?php echo $tmail?>' size=30></td>
 <td><input type=text name=troom value='<?php echo $troom?>' size=10></td>
 <td>
  <table cellpadding="0" cellspacing="0"><tr><td>
  <!--<input type=hidden name=tdep  value='<?php echo $tdep?>' size=30>-->
  <select name=tdep id=seldep style="width: 194px">
   <option value='' >...</option>
   <?php 
   $result = mysql_query ("SELECT DISTINCT dep FROM t1 ORDER BY dep;");
   while ($value = mysql_fetch_array($result))
    $dd[]=$value[0];
   sort($dd);
   for ($i=0;$i<count($dd);$i++)
    {
    $val=$dd[$i];
    if ($val!=$tdep)
     echo "<option value='$val'>$val</option>";
    else
     echo "<option selected value='$val'>$val</option>";
    }
   ?>
  </select>
  <input type=text name=tdep2 id=txtdep style="display: none" value="<?php echo $tdep?>" size=30  />
  </td><td>
  <button id=selbtn onclick="getElementById('txtdep').name='tdep';getElementById('seldep').name='tdep2';getElementById('txtdep').style.display='inline';getElementById('seldep').style.display='none';getElementById('txtbtn').style.display='inline';getElementById('selbtn').style.display='none'" type="button">...</button>
  <button id=txtbtn onclick="getElementById('txtdep').name='tdep2';getElementById('seldep').name='tdep';getElementById('txtdep').style.display='none';getElementById('seldep').style.display='inline';getElementById('txtbtn').style.display='none';getElementById('selbtn').style.display='inline'" style="display: none" type="button"> &gt; </button>
  </td></tr></table>
 </td>
 <td>
 <select name=tperm>
  <option value='' <?php  if ($tperm=="") echo "selected"; ?>>&nbsp;</option>
  <option value='sa' <?php  if ($tperm=="sa") echo "selected"; ?>>Админ</option>
  <option value='hidden' <?php  if ($tperm=="hidden") echo "selected"; ?>>Скрыт</option>
 </select>
 </td>
 </tr>
 <tr style="background: #F8F8F8; cursor: pointer" align="center">
  <td colspan=4 onmousemove="style.background='#D0F8D0'"  onmouseout="style.background='#F8F8F8'" onclick='getElementById("savebutton").click()'><b>Сохранить</b></td>
  <td colspan=3 onmousemove="style.background='#F8F8D0'"  onmouseout="style.background='#F8F8F8'" onclick='document.location.href="admin.php"'><b>Отмена</b></td>
 </tr>
 </table>
 </td></tr>
  <input type=submit id=savebutton value='Сохранить' style='display:none'>
 </form>
 <form method=post action="admin.php?edit=<?php echo $edit?>&addfoto=1" enctype="multipart/form-data">
   <tr align="center"><td colspan="7">
   Фото:
 <?php 
 $translitname = strtolower(translit(Trim($tname)));
 //echo $translitname.".jpg";
 $pfn = "photos/".$translitname.".jpg";

 if ($delfoto==1) unlink($pfn); // если нажато удаление фото
 if ($addfoto==1)
  {
  if(!copy($_FILES["filename"]["tmp_name"], $pfn)) echo "Загрузка не удалась!<br />";
  }

 $photo=0;
 if (file_exists($site_dir.$pfn))
  {
  echo "<a href='photos/$translitname.jpg' rel='lightbox[edit]' title='$tname'>$translitname.jpg</a> ";
  echo "[<a href='JavaScript:delfoto($edit)'>Удалить</a>]";
  }
 else
  echo "нет";
 ?>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 Загрузить фото:
 <input type="file" name="filename">&nbsp;
 <input type="submit" value="Загрузить" />
  </td></tr>
 </form>
</table>
<br />
 </center>
 <?php 
 mysql_free_result($result);
 mysql_close();
 }
?>

<!--
<form action='admin.php?sql=1' method=post>
SQL-запрос: <input type=text name=sqlquery1 size=47> &nbsp; <input type=submit value='Выполнить'>
</form>
!-->
<div align="center" style="margin-bottom: 2px; margin-top: 3px">
<form action='admin.php?replace=1' method=post>
<!--
<?php 
 if ($find==1)
  echo "<input type='hidden' id='frep' name='findval' value='$findval' />";

?>
-->
Переименовать отдел:
  <select name=dval id=dval style="width: 190px">
   <option value='' >...</option>
   <?php 
   unset($dd);
   $result = mysql_query ("SELECT DISTINCT dep FROM t1 ORDER BY dep;");
   while ($value = mysql_fetch_array($result))
    $dd[]=$value[0];
   sort($dd);
   for ($i=0;$i<count($dd);$i++)
    {
    $val=$dd[$i];
    if ($val!=$dval)
     echo "<option value='$val'>$val</option>";
    else
     echo "<option selected value='$val'>$val</option>";
    }
   ?>
  </select>

<!--<input type=text name=dval value='<?php  echo $dval; ?>'>-->
на <input type=text name=rval value='<?php  echo $rval; ?>' style="width: 190px"> &nbsp;
<input type=submit value='Переименовать'><br />
</form>
</div>
<hr />
<div align="center" style="margin-bottom: 3px; margin-top: 2px">
<form action='admin.php?find=1' method=post>
Поиск: <input type=text id=fval name=findval value='<?php  if (!isset($findval)) echo $_SESSION['findv']; else echo $findval; ?>' size=30> &nbsp;
Искать в полях: <select name=fselect>
<?php 
 if (!isset($fselect))
  {
  echo "<option selected value='all'>   $fheader_all";
  echo "<option value='name'>           $fheader_name";
  echo "<option value='rank'>           $fheader_rank";
  echo "<option value='tel'>            $fheader_tel";
  echo "<option value='room'>           $fheader_room";
  echo "<option value='dep'>            $fheader_dep";
  echo "<option value='mail'>           $fheader_mail";
  }
 else
  {
  if ($fselect=="all")
   echo "<option selected value='all'>$fheader_all";
  else
   echo "<option value='all'>$fheader_all";

  if ($fselect=="name")
   echo "<option selected value='name'>$fheader_name";
  else
   echo "<option value='name'>$fheader_name";

  if ($fselect=="rank")
   echo "<option selected value='rank'>$fheader_rank";
  else
   echo "<option value='rank'>$fheader_rank";

  if ($fselect=="tel")
   echo "<option selected value='tel'>$fheader_tel";
  else
   echo "<option value='tel'>$fheader_tel";

  if ($fselect=="room")
   echo "<option selected value='room'>$fheader_room";
  else
   echo "<option value='room'>$fheader_room";

  if ($fselect=="dep")
   echo "<option selected value='dep'>$fheader_dep";
  else
   echo "<option value='dep'>$fheader_dep";

  if ($fselect=="mail")
   echo "<option selected value='mail'>$fheader_mail";
  else
   echo "<option value='mail'>$fheader_mail";
  }
?></select>
&nbsp;
<!-- onclick='fadd.value=fval.value; frep.value=fval.value;' -->
<input type=submit id='sendbtn' value='Найти'>
<button type="button" title="Очистить форму поиска" onclick="document.location.href='admin.php'" style="cursor: pointer"><img src="images/delete.png" width="10" height="11" /></button>&nbsp;
<button type="button" title="Экспорт в Excel" onclick="document.location.href='xls.php'" style="cursor: pointer"><img src="images/excel.png" width="11" height="11" /></button>
<button type="button" title="Скрыть или показать фото" id="showphotobtn" style="cursor: pointer" onclick="showphoto1();"><img src="images/photo<?php  if ($_POST['showphoto']==1) echo "x"; ?>.png" height="11px" width="10px" /></button>
<input type="hidden" id="showphoto" name="showphoto" value="<?php echo $_POST['showphoto']?>" />
<script>
function showphoto1()
{
if (document.getElementById('showphoto').value=='0')
 document.getElementById('showphoto').value='1';
else document.getElementById('showphoto').value='0';
document.getElementById('sendbtn').click();
}
</script>
&nbsp;
<!-- <form action='admin.php' method=post> !-->
Упорядочить по:
<select name=sort onchange='getElementById("sendbtn").click()'>
<?php 
 if (!isset($sort))
  {
  echo "<option selected value='6'>$fheader_dep";
  echo "<option value='1'>$fheader_name";
  echo "<option value='2'>$fheader_rank";
  echo "<option value='3'>$fheader_tel";
  echo "<option value='4'>$fheader_room";
  echo "<option value='5'>$fheader_mail";
  }
 else
  {
  if ($sort=="6")
   echo "<option selected value='6'>$fheader_dep";
  else
   echo "<option value='6'>$fheader_dep";

  if ($sort=="1")
   echo "<option selected value='1'>$fheader_name";
  else
   echo "<option value='1'>$fheader_name";

  if ($sort=="2")
   echo "<option selected value='2'>$fheader_rank";
  else
   echo "<option value='2'>$fheader_rank";

  if ($sort=="3")
   echo "<option selected value='3'>$fheader_tel";
  else
   echo "<option value='3'>$fheader_tel";

  if ($sort=="4")
   echo "<option selected value='4'>$fheader_mail";
  else
   echo "<option value='4'>$fheader_mail";

  if ($sort=="5")
   echo "<option selected value='5'>$fheader_room";
  else
   echo "<option value='5'>$fheader_room";
  }
?>
</select>
 </form>
 </div>

<center>
<table cellspacing="1" cellpadding="3" bgcolor="#000000" style="font-family:tahoma;font-size:14px;">
 <tr style="background-color:#CCF;">
  <th>№</th>
  <th><?php echo $header_name;?></th>
  <th><?php echo $header_rank;?></th>
  <th><?php echo $header_tel;?></th>
  <th><?php echo $header_mail;?></th>
  <th><?php echo $header_room;?></th>
  <th><?php echo $header_dep;?></th>
  <th>Права</th>
  <th>&nbsp;</th>
  <th>&nbsp;</th>
  <th>&nbsp;</th>
  <th>&nbsp;</th>
  <th>&nbsp;</th>
  <th>&nbsp;</th>
 </tr>

<?php 
if ($find==1)
 {
 $_SESSION['finds']=1;
 $_SESSION['findv']=$findval;
 if ($findval=="")
  $_SESSION['finds']=0;
 }
if ($_SESSION['finds']==1)
 {
 $find=1;
 $findval=$_SESSION['findv'];
 }
if ($findval=="")
 {
 $_SESSION['finds']=0;
 $find=0;
 unset($find);
 }

function QueryOR($query)
 {
 $vall = mysql_fetch_array(mysql_query($query));
 return $vall[0];
 }
function alert($str) //debug function
{
  echo "<script>alert(\"$str\");</script>" ;
}

include("config.php");
mysql_connect ($dbhost, $username, $password);
mysql_select_db ($maindb);

/*
if (isset($sql))
 {
 //mysql_query ("$sqlquery1");
 }
*/
$operation = 0;
if (isset($replace))
 {
 $rval=Trim($rval);
 mysql_query("UPDATE t1 SET dep='$rval' WHERE dep='$dval';");
 }
if (isset($turboup))
 {
 for ($i=0; $i<10; $i++)
  {
  $prevkode = QueryOR("SELECT id FROM t1 WHERE id<$turboup ORDER BY id DESC;");
  if ($prevkode)
   {
   //$Kode = $prevkode;
   $result = mysql_query ("SELECT * FROM t1 WHERE id='$turboup';");
   $value = mysql_fetch_array($result);
   $tname = $value[1];
   $trank = $value[2];
   $ttel  = $value[3];
   $tmail = $value[4];
   $troom = $value[5];
   $tdep  = $value[6];
   $tperm = $value[7];

   $result2 = mysql_query ("SELECT * FROM t1 WHERE id='$prevkode';");
   $value2 = mysql_fetch_array($result2);
   $tname2 = $value2[1];
   $trank2 = $value2[2];
   $ttel2  = $value2[3];
   $tmail2 = $value2[4];
   $troom2 = $value2[5];
   $tdep2  = $value2[6];
   $tperm2 = $value2[7];

   mysql_query ("UPDATE t1 SET name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep', perm='$tperm' WHERE id='$prevkode';");
   mysql_query ("UPDATE t1 SET name='$tname2', rank='$trank2', tel='$ttel2', mail='$tmail2', room='$troom2', dep='$tdep2', perm='$tperm2' WHERE id='$turboup';");
   $operation = $prevkode;
   $turboup = $prevkode;
   }
  }
 }

if (isset($up))
 {
 $prevkode = QueryOR("SELECT id FROM t1 WHERE id<$up ORDER BY id DESC;");

 if ($prevkode!=NULL)
  {
  //$Kode = $prevkode;
  $result = mysql_query ("SELECT * FROM t1 WHERE id='$up';");
  $value = mysql_fetch_array($result);
  $tname = $value[1];
  $trank = $value[2];
  $ttel  = $value[3];
  $tmail = $value[4];
  $troom = $value[5];
  $tdep  = $value[6];
  $tperm = $value[7];

  $result2 = mysql_query ("SELECT * FROM t1 WHERE id='$prevkode';");
  $value2 = mysql_fetch_array($result2);
  $tname2 = $value2[1];
  $trank2 = $value2[2];
  $ttel2  = $value2[3];
  $tmail2 = $value2[4];
  $troom2 = $value2[5];
  $tdep2  = $value2[6];
  $tperm2 = $value2[7];

  mysql_query ("UPDATE t1 SET name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep', perm='$tperm' WHERE id='$prevkode';");
  mysql_query ("UPDATE t1 SET name='$tname2', rank='$trank2', tel='$ttel2', mail='$tmail2', room='$troom2', dep='$tdep2', perm='$tperm2' WHERE id='$up';");
  $operation = $prevkode;
  }
 }

if (isset($down))
 {
 $nextkode = QueryOR("SELECT id FROM t1 WHERE id>$down ORDER BY id;");

 if ($nextkode)
  {
  //$Kode = $nextkode;
  $result = mysql_query ("SELECT * FROM t1 WHERE id='$down';");
  $value = mysql_fetch_array($result);
  $tname = $value[1];
  $trank = $value[2];
  $ttel  = $value[3];
  $tmail = $value[4];
  $troom = $value[5];
  $tdep  = $value[6];
  $tperm = $value[7];

  $result2 = mysql_query ("SELECT * FROM t1 WHERE id='$nextkode';");
  $value2 = mysql_fetch_array($result2);
  $tname2 = $value2[1];
  $trank2 = $value2[2];
  $ttel2  = $value2[3];
  $tmail2 = $value2[4];
  $troom2 = $value2[5];
  $tdep2  = $value2[6];
  $tperm2 = $value2[7];

  mysql_query ("UPDATE t1 SET name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep', perm='$tperm' WHERE id='$nextkode';");
  mysql_query ("UPDATE t1 SET name='$tname2', rank='$trank2', tel='$ttel2', mail='$tmail2', room='$troom2', dep='$tdep2', perm='$tperm2' WHERE id='$down';");
  $operation = $nextkode;
  }
 }

if (isset($turbodown))
 {
 for ($i=0; $i<10; $i++)
  {
  $nextkode = QueryOR("SELECT id FROM t1 WHERE id>$turbodown ORDER BY id;");
  if ($nextkode)
   {
   //$Kode = $nextkode;
   $result = mysql_query ("SELECT * FROM t1 WHERE id='$turbodown';");
   $value = mysql_fetch_array($result);
   $tname = $value[1];
   $trank = $value[2];
   $ttel  = $value[3];
   $tmail = $value[4];
   $troom = $value[5];
   $tdep  = $value[6];
   $tperm = $value[7];

   $result2 = mysql_query ("SELECT * FROM t1 WHERE id='$nextkode';");
   $value2 = mysql_fetch_array($result2);
   $tname2 = $value2[1];
   $trank2 = $value2[2];
   $ttel2  = $value2[3];
   $tmail2 = $value2[4];
   $troom2 = $value2[5];
   $tdep2  = $value2[6];
   $tperm2 = $value2[7];

   mysql_query ("UPDATE t1 SET name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep', perm='$tperm' WHERE id='$nextkode';");
   mysql_query ("UPDATE t1 SET name='$tname2', rank='$trank2', tel='$ttel2', mail='$tmail2', room='$troom2', dep='$tdep2', perm='$tperm2' WHERE id='$turbodown';");
   $operation = $nextkode;
   $turbodown = $nextkode;
   }
  }
 }
if (isset($add))
 {
 //alert($tdep);
 $lid = QueryOR("SELECT id FROM t1 WHERE dep='$tdep' ORDER BY id DESC;");
 if ($lid!=NULL)
  {
  mysql_query ("UPDATE t1 SET id=id+1 WHERE id>$lid;");
  $lid++;
  mysql_query ("INSERT INTO t1 VALUES ('$lid','$tname','$trank','$ttel','$tmail','$troom','$tdep','');");
  $operation = $lid;
  //alert($lid);
  }
 else
  {
  mysql_query ("INSERT INTO t1 VALUES ('0','$tname','$trank','$ttel','$tmail','$troom','$tdep','');");
  $operation = QueryOR("SELECT id FROM t1 WHERE dep='$tdep' ORDER BY id DESC;");
  }
 ?>
 <script>document.location.href="admin.php#n<?php echo $operation-2?>";</script>
 <?php 
 }
if (isset($editcomp))
 {
 // mysql_query ("UPDATE t1 SET id='$tid', name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep' WHERE id='$editcomp';");
 $olddep = QueryOR("SELECT dep FROM t1 WHERE id='$tid';");
 if (Trim($olddep)==Trim($tdep))
  {
  mysql_query ("UPDATE t1 SET name='$tname', rank='$trank', tel='$ttel', mail='$tmail', room='$troom', dep='$tdep', perm='$tperm' WHERE id='$editcomp';");
  $operation = $editcomp;
  }
 else
  {
  mysql_query("DELETE FROM t1 WHERE id='$editcomp'");
  $lid = QueryOR("SELECT id FROM t1 WHERE dep='$tdep' ORDER BY id DESC;");
  if ($lid!=NULL)
   {
   mysql_query ("UPDATE t1 SET id=id+1 WHERE id>$lid;");
   $lid++;
   mysql_query ("INSERT INTO t1 VALUES ('$lid','$tname','$trank','$ttel','$tmail','$troom','$tdep','$tperm');");
   $operation = $lid;
   //alert($lid);
   }
  else
   {
   mysql_query ("INSERT INTO t1 VALUES ('0','$tname','$trank','$ttel','$tmail','$troom','$tdep','$tperm');");
   $operation = QueryOR("SELECT id FROM t1 WHERE dep='$tdep' ORDER BY id DESC;");
   }
  }
 ?>
 <script>document.location.href="admin.php#n<?php echo $operation-2?>";</script>
 <?php 
 }
$opercomp=1;
if (isset($edit))
 {
 $operation = $edit;
 $opercomp=0;
 }
if (isset($delete))
 {
 mysql_query ("DELETE FROM t1 WHERE id='$delete';");
 $opercomp=0;
 }

//alert($find);

$hname=array("id","name","rank","tel", "mail","room","dep");
if (!isset($sort)) $sort=6;

//вывод записей
$cols = "id,name,rank,tel,mail,room,dep,perm";
$hname=array("id","name","rank","tel", "mail","room","dep");
if ($findval=="") $find=0;
if (!isset($sort)) $sort=6;

$findval2 = $findval; // сохраняем первоначальное значение findval

$findval=strtolower(translit($findval));
$findval2 = strtolower(translit(encodestring($findval2)));

$sortname=$hname[$sort];
unset($srt);
$i=0;
$result = mysql_query("SELECT $cols FROM t1 ORDER BY id;");
while($value = mysql_fetch_array($result))
 {
 $ok=0;
 if ($find==1)
  {
  if ($fselect=="all" || $fselect=="")
   {
   if (
      InStr(strtolower(translit($value['name'])),$findval)==-1 && InStr(strtolower(translit($value['name'])),$findval2)==-1 &&
      InStr(strtolower(translit($value['rank'])),$findval)==-1 && InStr(strtolower(translit($value['name'])),$findval2)==-1 &&
      InStr(strtolower(translit($value['tel'])),$findval)==-1 &&
      InStr(strtolower(translit($value['mail'])),$findval)==-1 &&
      InStr(strtolower(translit($value['room'])),$findval)==-1 &&
      InStr(strtolower(translit($value['dep'])),$findval)==-1 && InStr(strtolower(translit($value['name'])),$findval2)==-1
      ) $ok=0; else $ok=1;
   }
  else
   {
   if (InStr(strtolower(translit($value[$fselect])),$findval)==-1 && InStr(strtolower(translit($value[$fselect])),$findval2)==-1)
   $ok=0; else $ok=1;
   }
  }
 else $ok=1;
 //if (substr($value['perm'],0,6)=="hidden") $ok=0; // только для пользователей
 if ($ok)
  {
  $srt[$i][0]=$value['id'];
  $srt[$i][1]=$value[$sortname];
  //echo $srt[$i][0]." ".$srt[$i][1]."<br />";
  $i++;
  }
 }
@mysql_free_result($result);

$srtc=$i;
//sort($srt);
//array_multisort_key($srt, 1, $type = SORT_ASC, $cmp_func = 'strcmp');
if ($sort!=6)
 $srt=array_order($srt,1,SORT_ASC);

for ($i=0; $i<$srtc; $i++)
 {
 $id=$srt[$i][0];
 $ind=$id;
 $result=mysql_query("SELECT * FROM t1 WHERE id='$id';");
 $name = mysql_result ($result, 0, 1);
 $rank = mysql_result ($result, 0, 2);
 $tel =  mysql_result ($result, 0, 3);
 $mail = mysql_result ($result, 0, 4);
 $room = mysql_result ($result, 0, 5);
 $dep =  mysql_result ($result, 0, 6);
 $perm = mysql_result ($result, 0, 7);

 $cdate=mysql_result ($result, 0, $sort*1);
 $c=$i+1;
 if (strtolower(translit(Trim($cdate))) != strtolower(translit(Trim($olddate))) && $sort!=1 && $sort!=4)
  {
  print "<tr style='background-color:#E0E0E0;'><td colspan=14><center><i> $cdate </i></center></td></tr>";
  $olddate = $cdate;
  }
 $bgcolor="#F0F0F0";
 if ($ind==$operation) $bgcolor="#FAFAFA";
 if (substr($perm,0,6)=="hidden") $bgcolor="#E0E0E0";
 $permcaption="&nbsp;";
 switch ($perm)
  {
  case 't':  $permcaption="Междугор. вызов"; break;
  case 'a':  $permcaption="Отв. лицо"; break;
  case 'sa': $permcaption="Админ"; break;
  case 'hidden': $permcaption="Скрыт"; break;
  case 'hiddent': $permcaption="Скрыт/Междугор.выз"; break;
  default:   $permcaption="&nbsp;"; break;
  }

 $translitname = strtolower(translit(Trim($name)));
 //echo $translitname.".jpg";
 $pfn = "photos/".$translitname.".jpg";
 $photo=0;
 if (file_exists($site_dir.$pfn)) $photo=1;
 else $pfn="photos/nophoto.gif";
 $a1="";
 $a2="";
 if ($photo==1 && $print!=1)
  {
  $a1="<a href='$pfn' class='lightbox' title='$name,<br />$rank<br />($dep)' style='text-decoration: none; color: #000000'>";
  $a2="</a>";
  }
 ?>
 <tr id="tr<?php echo $ind?>" style='background-color:<?php echo $bgcolor?>;'>
  <td><center><a name='n<?php echo $ind?>'><?php echo $c?></a></center></td>
  <td><center><?php  if ($_POST['showphoto']==1 && $photo==1) {   ?>
              <table cellpadding="0" cellspacing="0" width="100%"><tr>
              <td align="left">
               <img src="<?php echo $pfn?>" width="<?php echo $th_img_w?>" height="<?php echo $th_img_h?>"
                     onclick="document.getElementById('idd<?php echo $c?>').click()"
                     onmousemove="this.width=<?php echo $th_img_w*$th_img_zoom?>;this.height=<?php echo $th_img_h*$th_img_zoom?>;"
                     onmouseout="this.width=<?php echo $th_img_w?>;this.height=<?php echo $th_img_h?>;"
                    style="cursor:pointer"
                    />&nbsp;</td>
              <td align="center">
              <?php   }

              if ($photo==0) editfield2("name",$ind,$name);
              else editlink2("name",$ind,$name,"id='idd$c' href='$pfn' rel='lightbox[main]' title='$name,<br />$rank<br />($dep)' style='text-decoration: none; color: #000000'");
              //echo "<a href='$pfn' rel='lightbox[main]' title='$name,<br />$rank<br />($dep)' style='text-decoration: none; color: #000000'>$name</a>";
              if ($_POST['showphoto']==1 && $photo==1) {
              ?>
              </td>
              </tr>
              </table>  <?php  } ?>
              </center></td>
  <td><center><?php  editfield2("rank",$ind,$rank); ?></center></td>
  <td><center><img src="images/phone.png" height="9"  width="12"><?php  editfield("tel",$ind,$tel); ?></center></td>
  <td><center><?php  editlink("mail",$ind,$mail,"href='mailto:$mail' target='_parent'"); ?></center></td>
  <td><center><?php  editlink("room",$ind,$room,"href='index.php?find=1&fselect=room&findval=$room' style='text-decoration: none; color: #000000'"); ?></center></td>
  <td><center><?php  editfield2("dep",$ind,$dep); ?></center></td>
  <td><center>
    <select id="perm<?php echo $ind?>" onchange="perm(<?php echo $ind?>,value)" style="width: 90px">
     <option <?php  if ($perm=="") echo "selected"; ?> value="">&nbsp;</option>
     <option <?php  if ($perm=="sa") echo "selected"; ?> value="sa">Админ</option>
     <option <?php  if ($perm=="hidden") echo "selected"; ?> value="hidden">Скрыт</option>
    </select>
  <?php 
  $previ=0;
  $nexti=0;
  if ($i>0) $previ=$srt[$i-1][0];
  if (($i+1)<$srtc) $nexti=$srt[$i+1][0];
  ?>
  <input type="hidden" id="prev<?php echo $ind?>" value="<?php echo $previ?>" /><input type="hidden" id="next<?php echo $ind?>" value="<?php echo $nexti?>" />
  </center></td>

  <td><center><img src='images/edit.png' onclick='location.href="admin.php?edit=<?php echo $ind?>"' style="cursor: pointer"></center></td>
  <td><center><img src='images/del.png' onclick='del(<?php echo $ind?>)' style="cursor: pointer" ></center></td>
  <td><center><img src='images/turboup.png' onclick='turboup(<?php echo $ind?>)' style="cursor: pointer"></center></td>
  <td><center><img src='images/up.png' onclick='up(<?php echo $ind?>)' style="cursor: pointer"></center></td>
  <td><center><img src='images/down.png' onclick='down(<?php echo $ind?>)' style="cursor: pointer"></center></td>
  <td><center><img src='images/turbodown.png' onclick='turbodown(<?php echo $ind?>)' style="cursor: pointer"></center></td>

 </tr>
 <?php 
 @mysql_free_result($result);
 }
mysql_close();


if ($srtc==0) // ничего не найдено
 {
 echo "<tr style='background-color:#F0F0F0;'><td colspan=14><center> По вашему запросу ничего не найдено! </center></td></tr>";
 }

// шаблон для редактируемого поля
function editfield($type,$ind,$value)
    {
    ?>
    <span id="<?php echo $type.$ind?>" ><span id="<?php echo $type?>d<?php echo $ind?>"><?php echo $value?></span>
     <img src="images/edit2.png" height="14"  width="14" onclick="edit('<?php echo $type?>',<?php echo $ind?>,'input')" style="cursor: pointer"></span>
    <div id="<?php echo $type?>ed<?php echo $ind?>" style="display: none"></div>
    <?php 
    }
// многосторочное
function editfield2($type,$ind,$value)
    {
    ?>
    <span id="<?php echo $type.$ind?>" ><span id="<?php echo $type?>d<?php echo $ind?>"><?php echo $value?></span>
     <img src="images/edit2.png" height="14"  width="14" onclick="edit('<?php echo $type?>',<?php echo $ind?>,'text')" style="cursor: pointer"></span>
    <div id="<?php echo $type?>ed<?php echo $ind?>"  style="display: none"></div>
    <?php 
    }

// шаблон для редактируемой ссылки
function editlink($type,$ind,$value,$linkhtml)
    {
    ?>
    <span id="<?php echo $type.$ind?>" >
     <a <?php echo $linkhtml?> ><span id="<?php echo $type?>d<?php echo $ind?>"><?php echo $value?></span></a>
     <img src="images/edit2.png" height="14"  width="14" onclick="edit('<?php echo $type?>',<?php echo $ind?>,'input')" style="cursor: pointer">
    </span>
    <div id="<?php echo $type?>ed<?php echo $ind?>"  style="display: none"></div>
    <?php 
    }
// многострочный
function editlink2($type,$ind,$value,$linkhtml)
    {
    ?>
    <span id="<?php echo $type.$ind?>" >
     <a <?php echo $linkhtml?> ><span id="<?php echo $type?>d<?php echo $ind?>"><?php echo $value?></span></a>
     <img src="images/edit2.png" height="14"  width="14" onclick="edit('<?php echo $type?>',<?php echo $ind?>,'text')" style="cursor: pointer">
    </span>
    <div id="<?php echo $type?>ed<?php echo $ind?>"  style="display: none"></div>
    <?php 
    }

// функция превода текста с английской раскладки в русскую
function encodestring($st)
    {
    // Сначала заменяем "односимвольные" фонемы.
    $st=strtr($st,"f,dult`;pbqrkvyjghcnea[wxio]sm'.z",
                  "абвгдеёжзийклмнопрстуфхцчшщъыьэюя");
    $st=strtr($st,"F,DULT`;PBQRKVYJGHCNEA[WXIO]SM'.Z",
                  "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ");
    // Возвращаем результат.
    return $st;
    }

function translit($st)
    {
    // Сначала заменяем "односимвольные" фонемы.
    $st=strtr($st,"абвгдеёзийклмнопрстуфхъыэ. ",
    "abvgdeeziyklmnoprstufh'ie__");
    $st=strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ ",
    "ABVGDEEZIYKLMNOPRSTUFH'IE_");
    // Затем - "многосимвольные".
    $st=strtr($st,
                    array(
                        "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
                        "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
                        "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
                        "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
                        "ї"=>"i", "Ї"=>"Yi", "є"=>"ie", "Є"=>"Ye",
                        "№"=>"N"
                        )
             );
    // Возвращаем результат.
    return $st;
    }

function translit2en($st)
    {
    // Сначала заменяем "односимвольные" фонемы.
    $st=strtr($st,"абвгдеёзийклмнопрстуфхъыэ. ",
    "abvgdeeziyklmnoprstufh'ie._");
    $st=strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ ",
    "ABVGDEEZIYKLMNOPRSTUFH'IE_");
    // Затем - "многосимвольные".
    $st=strtr($st,
                    array(
                        "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
                        "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
                        "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
                        "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
                        "ї"=>"i", "Ї"=>"Yi", "є"=>"ie", "Є"=>"Ye",
                        "№"=>"N"
                        )
             );
    // Возвращаем результат.
    return $st;
    }

function array_order($array,$key,$type=SORT_ASC)
{
    if(!is_array($array)) return;
    $ASC = ( $type === SORT_ASC );
    $elements = count($array)-1;
    for($i = 0; $i < $elements; $i++) {
        for($k = $elements; $k > $i ; $k--) {
            if($ASC ? $array[$k][$key] < $array[$k-1][$key] : $array[$k][$key] > $array[$k-1][$key]) {
                $buf = $array[$k-1]; $array[$k-1] = $array[$k]; $array[$k] = $buf;
            }
        }
    }
    return $array;
}

function InStr($haystack, $needle)
{
    $pos=strpos($haystack, $needle);
    if ($pos !== false)
    {
        return $pos;
    }
    else
    {
        return -1;
    }
}

function fileex($url)
 {
 $Headers = @get_headers($url);
 // проверяем ли ответ от сервера с кодом 200 - ОК
 //if(preg_match("|200|", $Headers[0])) { // - немного дольше :)
 //echo $Headers[0];
 if(strpos( $Headers[0],'200'))
  return 1;//echo "Файл существует";
 else
  return 0;//echo "Файл не найден";
 }


?>
</table>
</center>
<center><a href="#begin">Наверх</a></center>
</td></tr></table>

<br>
<!--
<a href=index.php>&gt;&gt; Выйти из режима администрирования &lt;&lt;</a>
!-->


<!--
<br />
<a href="#n62">test</a>
<br />
<button onclick='document.location.href="#n62"'>test</button>
<br />
-->
</center>
<input type="hidden" name="to" />
<input type="hidden" name="from" />
<div id=request></div>
</body>
<?php 
if ($operation>0 && $opercomp )
 echo
  "
  <script>
  document.location.href=\"#n".($operation-2)."\";
  </script>
  ";
?>
</html>
