<?php
# Tarif_create_form_module ver.1.0
# last modification 24.2.2010
# Formulář pro vytvážení nových tarifů
# POST
# 
# 
#                      
/*
Class bp_bufer {
  var $intervals;
  var $costs;
  var $rows;
  

public  function AddItem ($interval,$cost)  {
    $this->intervals[] = $interval;
    $this->costs[] = $cost;
    $this->rows++;
    echo $this->rows;
  }
public function ReadItem($row){
  return array($this->intervals[$row],$this->costs[$row]);
  }

}
$mybuffer = new bp_bufer();
$mybuffer->AddItem(5,6) ;
$out= $mybuffer->ReadItem(0);
echo "tady: ".$out[0].$out[1] ;
 */
//array_splice($myarray,1,1);//vymazani polozky 2.pozice 
//array_splice($myarray,array_search('banana',$myarray),1);

# prohledani pole s cilem spocitat polozky urcene pro vybranz trunk

 
 
 if (IsSet($_POST['TARIFSAVE'])){
    include "build/db_connect.inc.php"  ;
    $query="START TRANSACTION ";
    $result = mysql_query($query);
    
    if (!$result) {
          die('Transakci nelze spustit:' . mysql_error());
    }
   $query="SELECT idCENAJEDNOTKY
            FROM union_cost
            WHERE cost=".$_POST['TC_UNIONCOST']."";
    $result = mysql_query($query);
    if (!$result) {
          die('Záznam cena jednotky nelze prověřit:' . mysql_error());
    }
     if (mysql_num_rows($result)==0){
        $query="INSERT INTO union_cost (cost)
                VALUES (".$_POST['TC_UNIONCOST'].")";
        $result = mysql_query($query);
        if (!$result) {
            die('Záznam cena jednotky nelze uložit:' . mysql_error());
        }
        $query="SELECT last_insert_id()";  
        $result = mysql_query($query);
        list($idcenajednotky)=mysql_fetch_row($result);
    }
    else{
        list($idcenajednotky)=mysql_fetch_row($result);
    }
#tady by mohla zacit transakce
    $query="INSERT INTO tarif (Name,idCENAJEDNOTKY,description)
            VALUES (\"".$_POST['TC_NAME']."\",".$idcenajednotky.",\"".$_POST['TC_DESCRIPTION']."\")";
    $result = mysql_query($query);
    if (!$result) {
          die("tenZáznam tarifu nelze uložit:". mysql_error());
    }
    $query="SELECT last_insert_id()"; 
    $result = mysql_query($query);
    if (!$result) {
          die("Poslední záznam tarifu nelze načíst:". mysql_error());
    }
    list($tarif)=mysql_fetch_row($result);
    for ($a=0;$a<count($_SESSION['buffer']);$a++){
    
         $query="SELECT idBILLINGPERIOD FROM billing_period 
                 WHERE uptotime=".$_SESSION['buffer'][$a][0]." 
                 AND unionnum=".$_SESSION['buffer'][$a][1]."";
         $result = mysql_query($query);
        if (!$result) {
          die("Problém při načítání účtovacích intervalů:". mysql_error());
        }
        
        list($idbillingperiod)=mysql_fetch_row($result);
        $query="INSERT INTO spec_billing_period (idTARIF,idBILLINGPERIOD)
                VALUES (".$tarif.",".$idbillingperiod.")";
        $result = mysql_query($query);
        if (!$result) {
          die("Problém při vkládání účtovacích intervalů:". mysql_error());
        }
    }
    if (count($_SESSION['buffer'])==0){
        $query="ROLLBACK";
        $result = mysql_query($query);
        die("Musí být zvolen alespoň jeden účtovací interval. <a href=\"admin_page.php?NEXTFORM=13\">Zpět</a>");
    }
    
    
     
    
    
    echo ("Tarif byl uložen.");
    echo "<a href=\"".selfURL()."\"?CLEAR=> Zpět </a>"; 
    $query="COMMIT" ;
    unset ($_SESSION['dest_buffer'])  ;
   
    $result = mysql_query($query);   
}
else{
    if (IsSet($_GET['CLEAR'])){
        if (!IsSet($_SESSION['buffer'])){ unset($_SESSION['buffer']);}
        if (!IsSet($_SESSION['dest_buffer'])){unset($_SESSION['dest_buffer']);}
    
    }

if (!IsSet($_SESSION['buffer'])){
      $_SESSION['buffer']=array();
    }
if (!IsSet($_SESSION['dest_buffer'])){
      $_SESSION['dest_buffer']=array();
    }


//echo ($buffer[1][1]);
if (IsSet($_GET['TC_UNSELECT'])){
#odstraneni zaznamu z bufferu uchov8van0ho v session;bufer zacina od 0 proto get.. -1
array_splice($_SESSION['buffer'],$_GET['TC_UNSELECT']-1,1);//vymazani polozky 2.pozice 
}

if (IsSet($_GET['TC_UNSELECTDEST'])){
#odstraneni zaznamu z bufferu uchov8van0ho v session;bufer zacina od 0 proto get.. -1
array_splice($_SESSION['dest_buffer'],$_GET['TC_UNSELECTDEST']-1,1);//vymazani polozky 2.pozice 
}
//odebrani polozky z pole trunku


#Uložení vybrané hodnoty do bufferu, neni li už v bufferu obsažena                
if (IsSet($_GET['TC_SELECT']) && !in_array(array($_GET['TC_UPTOTIME'],$_GET['TC_UNION']),$_SESSION['buffer'])){
    $_SESSION['buffer'][]=array($_GET['TC_UPTOTIME'],$_GET['TC_UNION'])   ;
}
#Uložení vybrané hodnoty do dest_bufferu, neni li už v bufferu obsažena 
if (IsSet($_GET['TC_SELECTDEST']) && !in_array(array($_GET['TC_DEST'],$_GET['TC_DESTNAME'],$_GET['TC_IDTRUNK']),$_SESSION['dest_buffer'])){
    $_SESSION['dest_buffer'][]=array($_GET['TC_DEST'],$_GET['TC_DESTNAME'],$_GET['TC_IDTRUNK'])   ;
   
}

   

//if (!IsSet($_GET['STEP'])&& !IsSet($_POST['TARIFSAVE'])){ 
?>
<script language="JavaScript">
// soubor funkcí pro kontrolu hodnot formuláře na straně klienta
  function HideIt() {
        document.getElementById('required').style.visibility= "hidden";
        document.getElementById('requiredtext').style.visibility= "hidden";
  }
 
   
  function CheckEmptyField( theField, theMessage ) {
   if( theField.value=="" ) {
      theField.focus();
      if(document.getElementById) {
        document.getElementById('required').style.visibility= "visible";
        document.getElementById('requiredtext').style.visibility= "visible";
        document.getElementById('requiredtext').innerHTML= theMessage;
        setTimeout( "HideIt()",1500);
      } else {
          alert(theMessage);
      }
      return false;
   } else {
      return true;
   }
  }
  function Validate(theForm) {
      if( !CheckEmptyField(theForm.TC_NAME,"Zadejte prosím jméno tarifu!") ) return false;
      if( !CheckEmptyField(theForm.TC_UNIONCOST,"Zadejte prosím cenu jednotky!") ) return false;
      
  // uspech
  return true;
}
     <!-- <![CDATA[
      var MaxLengthLock = false;
      function MaxLengthCount(fieldObj,fieldMaxLength)
      {
        if (!MaxLengthLock)
        {
          MaxLengthLock = true;
          if (fieldObj.value.length > fieldMaxLength)
          {
            alert("Text je delší než " + fieldMaxLength + " znaků!");
            fieldObj.value = fieldObj.value.substring(0,fieldMaxLength);
          }
          var percentage = parseInt(100 - (( fieldMaxLength - fieldObj.value.length) * 100)/fieldMaxLength);
          document.getElementById(fieldObj.id + "_PBar").style.width = parseInt((parseInt(fieldObj.offsetWidth)*percentage)/100)+"px";
          MaxLengthLock = false;
        }
      }
      //]]> -->

  function FloatCheck(theObj){ 
        if (isNaN(theObj.value)){
        theObj.value="";
        document.getElementById('required').style.visibility= "visible";
        document.getElementById('requiredtext').style.visibility= "visible";
        document.getElementById('requiredtext').innerHTML= "V ceně může být pouze číslo";
        setTimeout( "HideIt()",1500);
        
      
     }
  
  
  }

</script>


 <div class="forms">
<h3>Vytvoření nové položky tarifu</h3><span class="backtoform"><a href="admin_page.php?NEXTFORM=10">Zpět</a> </span>
 



<script language="JavaScript"><!-------------
// Tuto funkci je mozno vlozit na konec hlavního dokumentu a ušetři její opakování
if(document.getElementById) {
  document.write('<img ID="required" STYLE="visibility:hidden;z-index:5; position:absolute; left:150; top:300" src="required.gif">');
  document.write('<p ID="requiredtext" STYLE="visibility:hidden; z-index:5;position:absolute; left:215; top:335" >abc</p>');
}

//-----------></script>
<?php
//}
###############################################################################
//if ($_GET['STEP']==2){

//echo $_SESSION['TC_NAME'];
// echo $_SESSION['TC_UNIONCOST'];
// echo $_SESSION['TC_DESCRIPTION'];
    include "build/db_connect.inc.php"  ;
    $query="SELECT uptotime,unionnum 
              FROM billing_period
              WHERE validity=1
              ";
#serayeni hodnot v poli buffer
    foreach ($_SESSION['buffer'] as $key => $row){
        $interval[$key] = $row[0];
        $cost[$key] = $row[1];
    }
    array_multisort($interval,SORT_ASC,$cost,SORT_DESC,$_SESSION['buffer']) ;
    unset($interval);
    unset($cost);
#------------------------------

 
    if (count($_SESSION['buffer'])>0){
        $query=$query."AND uptotime NOT IN(";          
        for ($i=0;$i<count($_SESSION['buffer']);$i++){
             if ($i+1!=count($_SESSION['buffer'])){
                 $query=$query.$_SESSION['buffer'][$i][0].",";
             }else{
                 $query=$query.$_SESSION['buffer'][$i][0].")";
             }
        }
    }
    $query=$query." ORDER BY uptotime ASC";
    $result = mysql_query($query);
    if (!$result) {
          die('Předvýběr nelze načíst:' . mysql_error());
    }
  
?>

 <!-- <h3>Nastavení účtovacích intervalů</h3> -->
  <fieldset>
    <legend>Účtovací intervaly</legend>
  <div class="userlist">
      <table align="center" width="500px">
          <tr>
              <td colspan=3 class="tablehead">Předvýběr</td><td colspan=3 class="tablehead">V plánovaném tarifu</td>
          </tr><tr>
              <td class="tableculombhead">Interval</td>     
              <td class="tableculombhead">Počet jednotek</td>
              
              <td class="tableculombhead" style="width:20px"> </td><td class="tableculombhead" style="width:20px"> </td>
              
              <td class="tableculombhead">Interval</td>
              <td class="tableculombhead">Počet jednotek</td>
            
          </tr>
      <?php
        $poradizaznamu = 0;
        
        if (mysql_num_rows($result) >count($_SESSION['buffer'])){
            $i=0;
            $a=0;
            while (list($uptotime,$unionnum) = mysql_fetch_row($result)) {
                #Stridani barev řádků tabulky
                if($a==1){$a=0; $barva="white";}else{$a=1;$barva="lightgrey"; }
                #####################################################################
                echo "<tr bgcolor=$barva>";
                echo "<td>".$uptotime."</td><td>".$unionnum."</td><td style=\"text-align:right;width:20px\"><a href=\"".selfURL()."?STEP=2&TC_SELECT=TRUE&TC_UPTOTIME=".$uptotime."&TC_UNION=".$unionnum."\"><img src=\"files/pictures/vyber.gif\" alt=\"Vyber\"></a></td>";
                if ($i<count($_SESSION['buffer'])){
                    $poradizaznamu++;
                    echo ("<td style=\"width:20px\"><a href=\"".selfURL()."?STEP=2&TC_UNSELECT=".$poradizaznamu."&TC_UPTOTIME=".$_SESSION['buffer'][$i][0]."&TC_UNION=".$_SESSION['buffer'][$i][1]."\"><img src=\"files/pictures/odstran.gif\"></a></td><td>".$_SESSION['buffer'][$i][0]."</td><td>".$_SESSION['buffer'][$i][1]."</td>");
                }
            echo "</tr>";
            $i++; 
            }
       }
       else{
            $i=0;
            for ($a=0;$a<count($_SESSION['buffer']);$a++){
                #Stridani barev řádků tabulky
                if($i==1){$i=0; $barva="white";}else{$i=1;$barva="lightgrey"; }
                #####################################################################
                if ($a<mysql_num_rows($result)){
                echo "<tr bgcolor=$barva>";
                list($uptotime,$unionnum) = mysql_fetch_row($result);
                echo "<td>".$uptotime."</td><td>".$unionnum."</td><td style=\"text-align:right;width:20px\"><a href=\"".selfURL()."?STEP=2&TC_SELECT=TRUE&TC_UPTOTIME=".$uptotime."&TC_UNION=".$unionnum."\"><img src=\"files/pictures/vyber.gif\" alt=\"Vyber\"></a></td>";
                }
            else{
                echo "<tr bgcolor=$barva>";
                echo "<td></td><td></td><td></td>";}
                $poradizaznamu++;
                echo ("<td style=\"width:20px\"><a href=\"".selfURL()."?STEP=2&TC_UNSELECT=".$poradizaznamu."&TC_UPTOTIME=".$_SESSION['buffer'][$a][0]."&TC_UNION=".$_SESSION['buffer'][$a][1]."\"><img src=\"files/pictures/odstran.gif\"></a></td><td>".$_SESSION['buffer'][$a][0]."</td><td>".$_SESSION['buffer'][$a][1]."</td>");
                echo "</tr>";
            }
      }
      unset($pozadimenu);
      //echo "zaznamu: ".mysql_num_rows($result);
      ?>
  </table>
  </div>
 </fieldset>





<?php
//} 


//}
###############################################################################
//if ($_GET['STEP']==4){



    
?>  



<script language="JavaScript">
    function RefreshForm(theForm){
      //document.form1.TC_SUBMIT.value="FALSE";
      document.forms.form1.submit();
  
  }
  </script>   
  


  <!--<h3>Výběr předvoleb pro tarif</h3>-->



  <fieldset>
  <legend>Obecné informace</legend>
  
<form name="form1" action="admin_page.php" onSubmit="return Validate(this);" method="post">

      <table style="width:200px" >
        <tr>
          <td class="tablehead">Jméno </td>
          <td class="tableculombhead"><input type="text"  name="TC_NAME" ></td>
        </tr><tr>
          <td class="tablehead">Cena jednotky</td>
          <td class="tableculombhead"><input type="text" id="TC_UNIONCOST" OnChange="FloatCheck(this)" name="TC_UNIONCOST"> </td>
            
        
        </tr><tr>
          <td class="tablehead" colspan=2>Popis </td>
        </tr><tr>
          <td colspan=2><textarea name="TC_DESCRIPTION" id="TC_DESCRIPTION" style="max-width:300px" accesskey="T"  cols="60" wrap="virtual"
            onpropertychange="MaxLengthCount(this,160);"
            onclick="MaxLengthCount(this,160);"
            onmousemove="MaxLengthCount(this,160);"
            onblur="MaxLengthCount(this,160);"
            onkeyup="MaxLengthCount(this,160);"
            onfocus="MaxLengthCount(this,160);"
            onchange="MaxLengthCount(this,160);"
            onafterupdate="MaxLengthCount(this,160);"></textarea>
          <div id="TC_DESCRIPTION_PBar" style="width:0px;height:10px;border:0;font-size:8px;overflow:hidden;background-color: #3399FF;"></div></td>
        </tr><tr>
           <input name="STEP" type="hidden" value="2">
          <input name="TARIFSAVE" type="hidden" value="">
        <td colspan=2><input type="reset" value="Storno"><input type="submit" value="Ulož">
        </form>
        
        </tr>
      </table>
</fieldset> 
</div>
</center>
<?php
//}
 } 
 
      
?>

