<?
/**
 * VoiceOne Settings/MOH/edit
 *
 * Frontend to manage a music on hold class in voiceone.
 * @package voiceone
 * @subpackage  settings_moh
 */
include ("../../../admin/config/cfg.php");
global $cwlang; 
require_once("$absBasePath/lib/xajax/xajax.inc.php");
  
  //=================== XAJAX ==================
  function showProperty($mode){
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Make response
    if($mode=="files"){
      $objResponse->addAssign("application_dt","style.display", "none");
      $objResponse->addAssign("application_dd","style.display", "none");
      }
    else{
      $objResponse->addAssign("application_dt","style.display", "block");
      $objResponse->addAssign("application_dd","style.display", "block");
    }
    //return the xajaxResponse object
    return $objResponse->getXML();  
  } 
  function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $name=$formData["class"]["name"];
    $mode=$formData["class"]["mode"];
    $application=$formData["class"]["application"];
    $oldname=$formData["oldname"];
    $songsArr=$formData["listRight"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all moh classes
    $mohclassesArr=$asterisk->getMohClass("");
    if(is_array($mohclassesArr)){
      foreach($mohclassesArr as $c) {
        if($c["name"]==$oldname) continue;
        $cNameArr[]=$c["name"];
      }
    }
    // Check Name ((not null)&&(unique))
    $nameErr=false;
    if($oldname==""){
      if($name=="") { 
        //name cannot be null
        $errOut[]= T_("Name cannot be null");
        $objResponse->addAssign("nameErr","innerHTML",$imgErr);
        $nameErr=true;  
      }else if((is_array($cNameArr))&&(in_array($name,$cNameArr))){
        //name must be unique
        $errOut[]= T_("Name already exists. Please change it");
        $objResponse->addAssign("nameErr","innerHTML",$imgErr);
        $nameErr=true;
      }else{
        //name must have no spaces or strange charcaters
        for($i=0; $i<strlen($name); $i++){ 
          $ch=ord($name[$i]);
          if($ch==32){ //spaces
            $errOut[]=T_("Name doesn't allow spaces. Please change it");
            $objResponse->addAssign("nameErr","innerHTML",$imgErr);
            $nameErr=true;
            break;
          }else if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==95))) {
            $errOut[]=sprintf(T_("Character \" %1\$s \" is not permitted. Please change class name"),$name[$i] );
            $objResponse->addAssign("nameErr","innerHTML",$imgErr);
            $nameErr=true;
            break;
          }
        }
      } 
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check Application (not null)
    $appErr=false;
    if($application=="") { 
      //application cannot be empty
      $errOut[]= T_("Application cannot be null");
      $objResponse->addAssign("appErr","innerHTML",$imgErr);
      $appErr=true;  
    }
    if($appErr===false) $objResponse->addAssign("appErr","innerHTML","");
    // Check Songs List (not empty)
    $listErr=false;
    if(!(is_array($songsArr))) { 
      //list cannot be empty
      $errOut[]= T_("There are no songs assigned to this class. Please assign songs to the class");
      $objResponse->addAssign("listErr","innerHTML",$imgErr);
      $listErr=true;  
    }
    if($listErr===false) $objResponse->addAssign("listErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->registerFunction("showProperty");
  $xajax->processRequests();
  
  //=============== POST and GET ===============
  $alert=getAlert();
  // Populate setting value
  $default=$asterisk->getMohClass("default");
  $application=$default[0]["application"]; 
  //$application="/usr/bin/madplay -Q --attenuate=-12 --mono -R 8000 --output=RAW:-";
  if(count($_GET)>0){
    if(isset($_GET["name"])&&($_GET["name"]!="")){
      //Extract class information
      $ret=$asterisk->getMohClass($_GET["name"]); 
      $name=$ret[0]["name"];
      $mode=$ret[0]["mode"];
      $application=$ret[0]["application"];
      //Extract songs information
      $songsSelected=$asterisk->getMohSongs($name);
			if (is_array($songsSelected)){ 
        foreach($songsSelected as $song){
				  $song=trim($song);
					if(strlen($song)>20) $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,17)."...";
	        else $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,-4);
          $listRight.="<option value=\"$song\">$song_visual</option>";  
        }
			}
      // display or not application text field
      if($mode=="files") $dis_app="display: none";
      else $dis_app="display: block";
    }
  }
  // Save class
  else if(count($_POST)>0){
    // Crate a new class
    if((!(isset($_POST["oldname"])))&&($_POST["class"]["name"]!="")){
      $def["name"]=$_POST["class"]["name"];
      $def["mode"]=$_POST["class"]["mode"];
      if($def["mode"]=="files") $def["application"]=$application;
      else $def["application"]=$_POST["class"]["application"];
      foreach($_POST["listRight"] as $song){
        $def["songs"][]=$song; 
      }
      $ret=$asterisk->createMohClass($def);
      if ($ret>0) {$alert="<div class=\"AlertGood\">".T_("The class has been created")."</div>";
      } else $alert="<div class=\"AlertBad\">".T_("The class hasn't been created")."</div>";  
      goToMainPage($alert);
    }
    // Modify a class
    else if((isset($_POST["oldname"]))&&($_POST["oldname"]!="")){
      //Make new class definition
      $def["name"]=$_POST["oldname"];
      $def["mode"]=$_POST["class"]["mode"];
      $def["application"]=$_POST["class"]["application"];   
      if(is_array($_POST["listRight"])) 
      foreach($_POST["listRight"] as $song){
        $def["songs"][]=$song; 
      }
      $ret=$asterisk->modifyMohClass($def);
      if($ret>0) {$alert="<div class=\"AlertGood\">".T_("The class has been modified")."</div>";
      } else $alert="<div class=\"AlertBad\">".T_("The class hasn't been modified")."</div>";
      goToMainPage($alert);
    }
  }
  
  //================ PAGE LOGIC ================
  //Define page title
  if(isset($_GET["name"])&&($_GET["name"]!="")) $title=sprintf(T_("Modify class \"%s\""),$name );
  else $title=T_("New class");
  // Create modes list
  if($mode=="custom") $modeList.="<option value=\"custom\" selected=\"selected\">custom</option>\n";
  else $modeList.="<option value=\"custom\">custom</option>\n";
  if($mode=="mp3") $modeList.="<option value=\"mp3\" selected=\"selected\">mp3</option>\n";
  else $modeList.="<option value=\"mp3\">mp3</option>\n";
  if($mode=="mp3nb") $modeList.="<option value=\"mp3nb\" selected=\"selected\">mp3nb</option>\n";
  else $modeList.="<option value=\"mp3nb\">mp3nb</option>\n";
  if($mode=="quietmp3") $modeList.="<option value=\"quietmp3\" selected=\"selected\">quietmp3</option>\n";
  else $modeList.="<option value=\"quietmp3\">quietmp3</option>\n";
  if($mode=="quietmp3nb") $modeList.="<option value=\"quietmp3nb\" selected=\"selected\">quietmp3nb</option>\n";
  else $modeList.="<option value=\"quietmp3nb\">quietmp3nb</option>\n";
  if($mode=="files") $modeList.="<option value=\"files\" selected=\"selected\">files</option>\n";
  else $modeList.="<option value=\"files\">files</option>\n";
  // Create songs list
  $songsList=$asterisk->getMohSongs("");
  if(is_array($songsList)){
    foreach($songsList as $song){
  	  $song=trim($song);
  		if(strlen($song)>20) $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,17)."...";
  	  else $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,-4);
      $listLeft.="<option value=\"$song\">$song_visual</option>";   
    }
  }
  //create a visual list of classes
  $ret=$asterisk->getMohClass("");
  $count=0;
  if (is_array($ret)){
    foreach($ret as $otherClass){
      $otherName=$otherClass["name"];
      $script.="\"$otherName\",";
    }
    if ($script!="") $script="<script> var alreadyDefinedClass=new Array(".substr($script, 0, -1).");</script>"; 
  }
  // create pannel var
  $add=T_("  Add        ");
  $addAll=T_("  Add all    ");
  $remove=T_("     Remove  ");
  $removeAll=T_("  Remove all ");
 
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/"); 
  ?>
  <?=$script?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin"><?=T_("Return without save")?></a> 
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post" onSubmit=" return selectAll(getElementById('listRight'));">
      <!-- Class setting -->
      <h2><?=T_("Class")?></h2>
      <p class="blockintro"><?=T_("General class parameters")?></p>
      <table>
        <tr>
          <td>
            <div class="block" id="property">
              <dl>
                <? if(!(isset($_GET["name"]))) { ?>
                  <dt class="required"><label for="class[name]"><?=T_("Class Name")?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="30" id="class[name]" name="class[name]" value=""><span id="nameErr"></span></dd>
                <? } ?>                   
                <dt class="required"><label for="class[mode]"><?=T_("Class Mode")?>:</label></dt>
                <dd><select id="class[mode]" name="class[mode]" onChange="xajax_showProperty(this.value);"><?=$modeList?></select></dd>
                <dt class="required" id="application_dt" style="<?=$dis_app?>"><label for="client[language]"><?=T_("Application")?>:</label></dt>
                <dd id="application_dd" style="<?=$dis_app?>"><input type="text" size="100" maxlength="100" id="class[application]" name="class[application]" value="<?=$application?>"/><span id="appErr"></dd> 
              </dl>  
            </div>
          </td>
        </tr>
      </table>  
      <!-- Songs selection -->
      <div id="songList">
      	<h2><?=T_("Songs List")?></h2>
        <p class="blockintro"><?=T_("Choose which of the available songs to be added to this class")?></p>
        <div class="block">
          <table>
            <tr>
              <td class="required">
                <div ><?=T_("Available Songs")?>:</div>
                <select multiple size="10"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
              </td>
              <td>   
                <div><input type="button" onclick="addDualList(document.getElementById('listLeft'), document.getElementById('listRight'), false)" name="Add     >>"  value="<?=$add?>>>" style="width:100px"></div>
                <div><input type="button" onclick="removeDualList(document.getElementById('listRight'), false )" name="Add     <<"  value="<<<?=$remove?>" style="width:100px"></div>
                <div><input type="button" onclick="addDualList(document.getElementById('listLeft'), document.getElementById('listRight'), true)" name="Add All >>"  value="<?=$addAll?>>>" style="width:100px"></div>
                <div><input type="button" onclick="removeDualList(document.getElementById('listRight'), true)" name="Add All <<"  value="<<<?=$removeAll?>" style="width:100px"></div>
              </td>
              <td class="required"><div ><?=T_("Selected Songs")?>:</div>
                <div style="float: left;">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_up.gif"  onclick="moveOptions ( document.getElementById('listRight'), -1); return false" name="Up"  value="Down" style="display: block">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_down.gif"  onclick="moveOptions ( document.getElementById('listRight'), 1); return false;" name="Down"  value="Down" style="display: block">
                </div>
                <span style="float: right;" id="listErr"></span>
                <select multiple size="10" name="listRight[]" id="listRight"><?=$listRight?></select>
              </td>
            </tr>
          </table>
        </div>
      </div>
      <!-- Input Buttons -->
      <div class="action">
        <?if ($_GET["name"]!="") {?> <input type="hidden" id="oldname" name="oldname" value="<?=$_GET[name]?>" /><?}?>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" selectAll(getElementById('listRight')); document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
     <!--   
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkData();"/>
      -->
      </div>
   </form>
  </div>     
    
  <? 
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new music on hold class or to modify an existing one. To create a new class you have to define the class name, the playlist selecting the songs that will be played and to press save button on the end of the page. Moreover it's possible to define other parameters like the software which play music file, etc...")?></p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "moh");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

