
<?php
  print "<form name='PollForm' action='' method=post>";

  if(count($_POST) > 0)
  {
    //инициализируем переменные
    $ToEditMD['quest'] = $_POST['question'];
    $ToEditMD['showstatus'] = $_POST['showstatus'];
    $ToEditMD['protect'] = $_POST['protect'];
    $ToEditMD['time'] = $_POST['time'];
    $FileName = $_POST['file'];

    //выбираем данные из массива $_POST, потом рассортировываем их по переменным
    foreach($_POST as $key => $value)
    {
      //print $key." - ".$value."<br>";
      if(strpos($key, 'var') !== false)
        $ToEditMD[$Variants][] = $value;
      elseif((strpos($key, 'DeleteVar') !== false) and (strpos($key, '_x') !== false))
      {
      	$DeleteVar = str_replace("DeleteVar", '', $key);
	      $DeleteVar = str_replace('_x', '', $DeleteVar);
	      $DeleteVar = (int)$DeleteVar;
	      $DeleteItem = true;
      }
      elseif((strpos($key, 'UpItem') !== false) and (strpos($key, '_x') !== false))
    	{
	      $UpItem = str_replace("UpItem", '', $key);
	      $UpItem = str_replace('_x', '', $UpItem);
	      $UpItem = (int)$UpItem;
	      $UpVar = true;
	    }
	    elseif((strpos($key, 'DownItem') !== false) and (strpos($key, '_x') !== false))
	    {
	      $DownItem = str_replace("DownItem", '', $key);
	      $DownItem = str_replace('_x', '', $DownItem);
	      $DownItem = (int)$DownItem;
        $DownVar = true;
	    }
    }

    //Добавляем вариант
    if(!empty($_POST['AddVar']))
    {
      array_push($ToEditMD[$Variants], "", '0');
    }

    //удаляем элемент
    if($DeleteItem == true)
    {
      for($i = 0; $i < $DeleteVar; $i++)
        $TmpArr[] = $ToEditMD[$Variants][$i];
      for($i = ($DeleteVar+2); $i < count($ToEditMD[$Variants]); $i++)
        $TmpArr[] = $ToEditMD[$Variants][$i];
      $ToEditMD[$Variants] = $TmpArr;
    }

    //опускаем элемент
    if($DownVar == true)
    {
      $ToDownInit = $DownItem;
      $ToDownEnd = $DownItem+1;
      $ToUpInit = $DownItem+2;
      $ToUpEnd = $DownItem+3;
      $Tmp = $ToEditMD[$Variants][$ToDownInit];
      $ToEditMD[$Variants][$ToDownInit] = $ToEditMD[$Variants][$ToUpInit];
      $ToEditMD[$Variants][$ToUpInit] = $Tmp;
      $Tmp = $ToEditMD[$Variants][$ToDownEnd];
      $ToEditMD[$Variants][$ToDownEnd] = $ToEditMD[$Variants][$ToUpEnd];
      $ToEditMD[$Variants][$ToUpEnd] = $Tmp;
    }
    //поднимаем элемент
    if($UpVar == true)
    {
      $ToUpInit = $UpItem;
      $ToUpEnd = $UpItem + 1;
      $ToDownEnd = $UpItem - 1;
      $ToDownInit = $UpItem - 2;
      $Tmp = $ToEditMD[$Variants][$ToDownInit];
      $ToEditMD[$Variants][$ToDownInit] = $ToEditMD[$Variants][$ToUpInit];
      $ToEditMD[$Variants][$ToUpInit] = $Tmp;
      $Tmp = $ToEditMD[$Variants][$ToDownEnd];
      $ToEditMD[$Variants][$ToDownEnd] = $ToEditMD[$Variants][$ToUpEnd];
      $ToEditMD[$Variants][$ToUpEnd] = $Tmp;
    }

    //сохраняем изменения
    if(!empty($_POST['EditPoll']))
    {
      //вопрос
      $ToEditMD['quest'] = CorrectInput($ToEditMD['quest']);
      if($ToEditMD['quest'] == "")
        $Errors[] = $Err_NoQuestion;
      //варианты ответа
      $inx = 1;
      if(count($ToEditMD[$Variants]) > 40)
        $Errors[] = $Err_MaxVarCount;
      else
      {
        for($i = 0; $i < count($ToEditMD[$Variants]); $i = $i + 2)
	      {
	        $ToEditMD[$Variants][$i] = CorrectInput($ToEditMD[$Variants][$i]);
	        if($ToEditMD[$Variants][$i] == "")
	          $Errors[] = $Err_NoVariation."{$inx}</b>";
	        $inx++;
	      }  //for
      } //else
      if(empty($Errors))
      {
        //Приготавливаем голосование для записи в файл
        $Edited = "[quest]".$ToEditMD['quest']."[/quest]\n";
        for($i = 0; $i < count($ToEditMD[$Variants]); $i = $i + 2)
        {
          $inx = $i / 2;
          $Edited .= "[var{$inx}]".$ToEditMD[$Variants][$i]."[/var{$inx}]\n";
          $Edited .= "[var{$inx}voted]".$ToEditMD[$Variants][($i+1)]."[/var{$inx}voted]\n";
        }
        $Edited .= "[show]".$ToEditMD['showstatus']."[/show]\n";
        $Edited .= "[protect]".$ToEditMD['protect']."[/protect]\n";
        $Edited .= "[time]".$ToEditMD['time']."[/time]\n";
        SaveStringInFile($FileName, $Edited, 'w');
        Refresh($PageTmp);
      } //if empty Errors
    } //if($_POST['EditPoll'] == 'Редактировать')
  } //if(count($_POST) > 0)

  if(count($_POST) == 0)
  {
    //выбираем нужное голосование из массива

    $FileName = $_GET['file'];
    $FileName = "../txt/".$FileName;
    $ToEdit = file($FileName);
	  //преобразовываем элементы массива $ToEdit в серию переменных
	  for($i = 0; $i < count($ToEdit); $i++)
	  {
	    if(strpos($ToEdit[$i], '[quest]') !== false)
	    {
	      $ToEditMD['quest'] = trim(StripBBCode($ToEdit[$i]));
	    }
	    elseif(ereg("\[var[0-9a-z]+\]", $ToEdit[$i]) !== false)
	    {
	      $ToEditMD[$Variants][] = trim(StripBBCode($ToEdit[$i]));
	    }
	    elseif(strpos($ToEdit[$i], '[show]') !== false)
	    {
	      $ToEditMD['showstatus'] = trim(StripBBCode($ToEdit[$i]));
	    }
	    elseif(strpos($ToEdit[$i], '[protect]') !== false)
	    {
	      $ToEditMD['protect'] = trim(StripBBCode($ToEdit[$i]));
	    }
	    if(strpos($ToEdit[$i], '[time]') !== false)
	    {
	      $ToEditMD['time'] = trim(StripBBCode($ToEdit[$i]));
	    }
	  }  //for
  } // if(count($_POST) == 0)

  print "<h4>{$Heading_EditPoll}</h4>";
  //выводим ошибки
  ShowErrors($Errors, '100%');
  //Выводим голосование, которое нужно изменить
  //print count($ToEditMD[$Variants]);
  print "<fieldset  class=GeneralField align=center>";
    print "<table class=General cellspacing = 0 cellpadding = 0 width = 100%>";
      print "<tr>";
        print "<td width=90>{$Cpt_Question}</td>";
        print "<td><input type=text name=question value='{$ToEditMD['quest']}' size=90></td>";
      print "</tr>";
    print "</table>";
  print "</fieldset>";
  print "<fieldset  class=GeneralField align=center>";
    print "<table class=General cellspacing = 0 cellpadding = 0 width = 100%>";
      $inx = 0;
      for($i = 0; $i < count($ToEditMD[$Variants]); $i=$i+2)
      {
        print "<tr>";
          print "<td width=90>{$Cpt_Variation}".($inx+1)."</td>";
          //удаление варианта
          $EmptyCase = "<td width=20>&nbsp;</td>";
          if(count($ToEditMD[$Variants])>4)
            print "<td width=20><input type=image src='../img/delete.png' name=DeleteVar{$i} alt='{$Alt_DeleteVar}'></td>";
          else print $EmptyCase;
          //вверх
          if($i != 0)
            print "<td width=20><input type=image src='../img/up.png' name=UpItem{$i} alt='{$Alt_Up}'></td>";
          else print $EmptyCase;
          //вниз
          if($i != (count($ToEditMD[$Variants])-2))
            print "<td width=20><input type=image src='../img/down.png' name=DownItem{$i} alt='{$Alt_Down}'></td>";
          else print $EmptyCase;
          //стереть
          print "<td width=20><img src='../img/eraser.gif' alt='{$Alt_Reset}' width=20, height=20 onClick=\"document.PollForm.var{$i}.value=''\"></td>";
          print $EmptyCase;
          //текстовое поле с вариантом ответа
          print "<td>";
            print "<input type=text name=var{$i} value='{$ToEditMD[$Variants][$i]}' size=75>";
            print "<input type=hidden name=var{$i}voted value='{$ToEditMD[$Variants][($i+1)]}'>";
          print "</td>";
        print "</tr>";
        $inx++;
      }
    print "</table>";
  print "</fieldset>";
  print "<fieldset class=GeneralField align=center>";
  	print "<table class=General cellspacing=0 cellpadding=0 width=100% border=0>";
    	print "<tr>";
	      print "<td><input class=button type=submit name='AddVar' value='{$Cpt_AddVariation}'>&nbsp;&nbsp;";
	      print "<input class=button type=submit name='EditPoll' value={$Cpt_Save}></td>";
        //print "<td><input type=reset value='Очистить'></td>";
        print "<input type=hidden name='showstatus' value='{$ToEditMD['showstatus']}'>";
        print "<input type=hidden name='protect' value='{$ToEditMD['protect']}'>";
        print "<input type=hidden name='time' value='{$ToEditMD['time']}'>";
        print "<input type=hidden name ='file' value={$FileName}>";
	    print "</tr>";
	  print "</table>";
  print "</fieldset>";
  print "</form>";
?>