<?
/**
 * VoiceOne Settings/Queues/edit
 *
 * Frontend to provide access to the queue system in voiceone.
 * @package voiceone
 * @subpackage  settings_queues
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $location=$formData["location"];
    $id=$location["id"];
    $name=trim($location["name"]);
    $int_prefix=$location["int_prefix"];
    $country_code=$location["country_code"];
    $nat_prefix=$location["nat_prefix"];
    $nat_prefix_intl=$location["nat_prefix_intl"];
    $default=$location["default"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Retrieve all accounts
    $locationArr=$asterisk->getLocation(0);
    if(is_array($locationArr)){
      foreach($locationArr as $l){
        if($id==$l["id"]) continue;
        $lNameArr[]=$l["name"];
        $lCCArr[]=$l["country_code"];
      }
    }
    // Check Name ((not null)&&(unique))
    $nameErr=false;
    if($name==""){
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($lNameArr))&&(in_array($name,$lNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
		// Check int_prefix (not null)&&(numeric)
    $int_prefixErr=false;
    if($int_prefix==""){
      //int_prefix cannot be null
      $errOut[]= T_("International prefix cannot be null");
      $objResponse->addAssign("int_prefixErr","innerHTML",$imgErr);
      $int_prefixErr=true;
    }else if(!is_numeric($int_prefix)){
 			//int_prefix must be numeric
      $errOut[]= T_("International prefix must be numeric");
      $objResponse->addAssign("int_prefixErr","innerHTML",$imgErr);
      $int_prefixErr=true;   
    }
   	if($int_prefixErr===false) $objResponse->addAssign("int_prefixErr","innerHTML","");
    // Check country_code (not null)&&(numeric)&&(unique)
    $country_codeErr=false;
    if($country_code==""){
      //int_prefix cannot be null
      $errOut[]= T_("Country code cannot be null");
      $objResponse->addAssign("country_codeErr","innerHTML",$imgErr);
      $country_codeErr=true;
    }else if(!is_numeric($country_code)){
 			//int_prefix must be numeric
      $errOut[]= T_("Country code must be numeric");
      $objResponse->addAssign("country_codeErr","innerHTML",$imgErr);
      $country_codeErr=true;   
    }else if((is_array($lCCArr))&&(in_array($country_code,$lCCArr))){
      //country_code must be unique
      $errOut[]= T_("Country code already exists");
      $objResponse->addAssign("country_codeErr","innerHTML",$imgErr);
      $country_codeErr=true;
    }
   	if($country_codeErr===false) $objResponse->addAssign("country_codeErr","innerHTML","");
    // Check nat_prefix (not null)&&(numeric)
    $nat_prefixErr=false;
    if($nat_prefix==""){
      //nat_prefix cannot be null
      $errOut[]= T_("National prefix cannot be null");
      $objResponse->addAssign("nat_prefixErr","innerHTML",$imgErr);
      $nat_prefixErr=true;
    }else if(!is_numeric($nat_prefix)){
 			//int_prefix must be numeric
      $errOut[]= T_("National prefix must be numeric");
      $objResponse->addAssign("nat_prefixErr","innerHTML",$imgErr);
      $nat_prefixErr=true;   
    }
   	if($nat_prefixErr===false) $objResponse->addAssign("nat_prefixErr","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("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $location=$_POST["location"];
    $entry=array(
      "id" => $location["id"],
      "name" => $location["name"],
      "int_prefix" => $location["int_prefix"],
      "country_code" => $location["country_code"],
      "nat_prefix" => $location["nat_prefix"],
      "nat_prefix_intl" => $location["nat_prefix_intl"],
      "default" => $location["default"]
    );
    $entry["area_codes"]=array();
    if(is_array($_POST["area_codes"])) $entry["area_codes"]=$_POST["area_codes"];
    if(is_array($_POST["area_codesHidden"])) $entry["area_codes"]=array_merge($entry["area_codes"],$_POST["area_codesHidden"]);
    $entry["special_patterns"]=array();
    if(is_array($_POST["special_patterns"])) $entry["special_patterns"]=$_POST["special_patterns"];
    //put location
    $ret=$asterisk->putLocation($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("The location has been modified")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("The location hasn't been modified")."</div>";
    //go to main page
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  //retrieve location informations
  if ($_GET["id"]!="") {
    $location=$asterisk->getLocation($_GET["id"]);
    if((is_array($location))&&(is_array($location[0]))){
      $location=$location[0];
    }
    $title=sprintf(T_("Modify location: %s"),$location["name"]);
    //create the area code list
    $area_codeList="";
    $area_codeHidden="";
    if(is_array($location["area_codes"])){
      foreach($location["area_codes"] as $ac){
        if(trim($ac)=="") continue;
        $d="";
        if(!$asterisk->isAreaCodeErasable($location["id"],$ac)){
          $area_codeHidden.="<input type=\"hidden\" name=\"area_codesHidden[]\" value=\"".$ac."\" />";
          $d="disabled=\"disabled\"";
        }
        $area_codeList.="<option value='$ac' $d>$ac</option>";
      }
    }
    //create the area code list
    $special_patternsList="";
    if(is_array($location["special_patterns"])){
      foreach($location["special_patterns"] as $sp) $special_patternsList.="<option value='$sp'>$sp</option>";
    }
  }else{
    $title=T_("New location");
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <?$sel="location";include("../../navigation.php");?>
  <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?><? if ($_GET['id']!="") echo "?id=".$_GET['id']; ?>" method="post">
      <!-- Country -->
      <h2><?=T_("Country Informations")?></h2>
      <p class="blockintro"><?=T_("Define the contry options. See ITU-T E.164 Directive (International Public Telecomunication Numbering Plan)")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="location[name]"><?=T_("Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="30" id="location[name]" name="location[name]" value="<?=$location['name']?>" /><span id="nameErr"></span> <?=T_("label for the country")?></dd>
          <dt class="required"><label for="location[int_prefix]"><?=T_("International Prefix")?>:</label></dt>
          <dd><input type="text" size="4" maxlength="30" id="location[int_prefix]" name="location[int_prefix]" value="<?=$location['int_prefix']?>" /><span id="int_prefixErr"></span> <?=T_("Do not use '+'. In italy: 00")?></dd>
          <dt class="required"><label for="location[country_code]"><?=T_("Country Code")?>:</label></dt>
          <dd><input type="text" size="4" maxlength="30" id="location[country_code]" name="location[country_code]" value="<?=$location['country_code']?>" /><span id="country_codeErr"></span> <?=T_("Without prefix. In italy: 39")?></dd>
          <dt class="required"><label for="location[nat_prefix]"><?=T_("National Prefix")?>:</label></dt>
          <dd><input type="text" size="4" maxlength="30" id="location[nat_prefix]" name="location[nat_prefix]" value="<?=$location['nat_prefix']?>" /><span id="nat_prefixErr"></span> <?=T_("In italy: 0")?></dd>
          <dt class="required"><label style="line-height:20px;" for="location[nat_prefix_intl]">&nbsp;</label></dt>
          <dd><input type="checkbox" id="location[nat_prefix_intl]" name="location[nat_prefix_intl]" value="1" <? if($location['nat_prefix_intl']==1) echo "checked=\"checked\"";?>/></span> <?=T_("Check the box if, when dialing in international format, the area code (or the entire number if area codes are not in use) needs the nationa prefix. Checked for italy")?></dd>
          <dt class="required"><label for="location[default]"><?=T_("Default")?>:</label></dt>
          <dd><input type="checkbox" id="location[default]" name="location[default]" value="1" <? if($location['default']==1) echo "checked=\"checked\"";?>/></span> <?=T_("Check the box to set this location as default")?></dd>            
        </dl>    
     	</div>
      <!-- Area Codes -->
      <h2><?=T_("Area Codes")?></h2>
      <p class="blockintro"><?=T_("Define area codes or leave empty this section if they are not in use in this location")?></p>
      <div class="block">
      	<table style="margin-left: 24px;">
          <tr>
            <td class="required"><label for="codes"><?=T_("Area code")?>:</label></td>
            <td class="required"><?=T_("Area codes added")?></td>
          </tr>
          <tr>
            <td valign="top">
              <input type="text" size="25" maxlength="100" id="code" name="code" value="" />
              <input type="button" value="+" onclick="addOption(getElementById('area_codes'),document.getElementById('code').value);document.getElementById('code').value='';" title="<?=T_("Add")?>">
              <div class="help"><?=T_("Digit the area code to add without national prefix")?></div>
            </td>
            <td>
              <select name="area_codes[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="area_codes">
                <?=$area_codeList?>
              </select>
              <?=$area_codeHidden?>
              <input type="button" value="<?=T_("Edit")?>" onclick="editOptions(getElementById('area_codes'))" title="<?=T_("Edit")?>" />
              <input type="button" value="<?=T_("X")?>" onclick="deleteOptions(getElementById('area_codes'))" title="<?=T_("Delete")?>" />
              <span id="area_codesErr"></span>
            </td>
          </tr>
          <tr>
            <td class="required"><label for="number"><?=T_("Special number")?>:</label></td>
            <td class="required"><?=T_("Special numbers added")?></td>
          </tr>
          <tr>
            <td valign="top">
              <input type="text" size="25" maxlength="100" id="number" name="number" value="" />
              <input type="button" value="+" onclick="addOption(getElementById('special_patterns'),document.getElementById('number').value);document.getElementById('number').value='';" title="<?=T_("Add")?>">
              <div class="help"><?=T_("Digit the numbers that don't need area code to be called from each area")?></div>
              <div class="help"><?=T_("(ie. Emergency Numbers, ecc...)")?></div>
            </td>
            <td>
              <select name="special_patterns[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="special_patterns">
                <?=$special_patternsList?>
              </select>
              <input type="button" value="<?=T_("Edit")?>" onclick="editOptions(getElementById('special_patterns'))" title="<?=T_("Edit")?>" />
              <input type="button" value="<?=T_("X")?>" onclick="deleteOptions(getElementById('special_patterns'))" title="<?=T_("Delete")?>" />
              <span id="special_patternsErr"></span>
            </td>
          </tr>
        </table>
      </div>
      <div class="action">
        <?if ($_GET["id"]!="") {?><input type="hidden" name="location[id]" value="<?=$_GET['id']?>" /><?}?>
        <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('area_codes'));selectAll(getElementById('special_patterns'));document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      </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 location or to modify an existing one. To create a new location you have to define the numbering option as specify on ITU-T E.164 directive and to press save button on the end of the page.")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "system");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');

?>

