<?
/**
 * VoiceOne Settings/Tech/zapata/edit
 *
 * Frontend to provide access to the tech system in voiceone.
 * @package voiceone
 * @subpackage  settings_tech
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
 	sajax_init();
  if(!_isModuleLoaded('zap')) goToMainPage('',"../../");
  //================ XAJAX ================
  function changeLocation($id,$area_code){
    global $asterisk,$cwlang;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
		$ret=$asterisk->getLocation($id);
  	if((is_array($ret))&&(is_array($ret[0]))){
      $area_codeArr=$ret[0]["area_codes"];
    }
    $area_codelist="";
    if((is_array($area_codeArr))&&(count($area_codeArr)>0)){
      foreach($area_codeArr as $ac){
        if($area_code==$ac) $s="selected=\"selected\""; else $s="";
        $area_codelist.="<option value=\"".$ac."\" $s>".$ac."</option>\n";
      }
    }else $area_codelist="<option value=\"\">[none]</option>\n";
    $html="<select id=\"area_code\" name=\"area_code\">".$area_codelist."</select>";
    // Return the xajaxResponse object
		$objResponse->addAssign("area_code_div","innerHTML",$html);
    $objResponse->addAssign("area_code_roll","innerHTML","");
    return $objResponse->getXML();
  }
  function showCid($pg_id){
    global $asterisk,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    if($pg_id!=""){
      $ret=$asterisk->getZapataGroup($pg_id);
      errArr($ret);
      if ($err=$asterisk->getError()) die("Error: $err");
      $cid_force=$ret[0]["cid"]["force_cid"];
      $cid_clir=$ret[0]["cid"]["clir"];
      $cid_number=$ret[0]["cid"]["cid_number"];
      $cid_name=$ret[0]["cid"]["cid_name"];
      $cid_appexten=$ret[0]["cid"]["cid_appexten"];
    }
    ob_start();
    ?>
        <dl>
          <dt class="required"><label for="cid[cid_name]"><?=T_("CID Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="20" id="cid[cid_name]" name="cid[cid_name]" value="<?=$cid_name?>" /> <?=T_("default caller id name")?></dd>
          <dt class="required"><label for="cid[cid_number]"><?=T_("CID Number")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="100" id="cid[cid_number]" name="cid[cid_number]" value="<?=$cid_number?>" /> <?=T_("default caller id number")?></dd>
          <dt class="required"><label for="cid[cid_appexten]"><?=T_("Append Exten")?>:</label></dt>
          <dd><input type="checkbox" id="cid[cid_appexten]" name="cid[cid_appexten]" value="1" <?if ($cid_appexten==1) echo "checked=\"checked\""; ?> /> <?=T_("append user's extension to CID Number value")?></dd>
          <dt class="required"><label for="cid[force_cid]"><?=T_("Force Default")?>:</label></dt>
          <dd><input type="checkbox" id="cid[force_cid]" name="cid[force_cid]" value="1" <?if ($cid_force==1) echo "checked=\"checked\""; ?> /> <?=T_("overwrite user's caller id setting with default line values")?></dd>
        </dl>
    <?
    $html=ob_get_contents();
    ob_end_clean();  
    // Return the xajaxResponse object
		$objResponse->addAssign("callerid","innerHTML",$html);
    return $objResponse->getXML(); 
  }
  function hideCid(){
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    $html="";
    // Return the xajaxResponse object
		$objResponse->addAssign("callerid","innerHTML",$html);
    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
    $id=$formData["id"];
    $name=$formData["name"];
    $speeddial=$formData["speeddial"];
    $oldSpeeddial=$formData["oldSpeeddial"];
    $port_type=$formData["port_type"];
    $signalling=$formData["signalling"];
    $phonenumberArr=$formData["phonenumber"];
    $portListArr=$formData["listRight"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all zapata groups
    $zapataGroupsArr=$asterisk->getZapataGroup(0);
    if(is_array($zapataGroupsArr)){
    	$thisgrpNumberArr=array();
      foreach($zapataGroupsArr as $g){
        if($id==$g["id"]){
        	if(is_array($g["msns"])) $thisgrpNumberArr=$g["msns"];
        	continue;
        }
        $gNameArr[]=$g["name"];
        if(is_array($g["msns"]))
          foreach($g["msns"] as $n) $gNumberArr[]=$n;
      }
    }
    // Retrieve Extensions
    $extensionArr=$asterisk->getExtension(0);
    if(is_array($extensionArr)){
      foreach($extensionArr as $ext){
        if(($id==$ext["entity_id"])||($oldSpeeddial."*"==$ext["extension"])) continue;
        $extNumberArr[]=$ext["extension"];
      }
    }
    // Check Name ((not null)&&(unique)&&(no spaces))
    $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($gNameArr))&&(in_array($name,$gNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else{
      //port must have no spaces
      for($i=0; $i<strlen($name); $i++){ 
        $ch=ord($name[$i]);
        if($ch==32){
          $errOut[]=T_("Name doesn't allow spaces. Please change it");
          $objResponse->addAssign("nameErr","innerHTML",$imgErr);
          $nameErr=true;
          break;
        }
      }
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check Speeddial((null)or ((numeric)and(unique)) )
    $speedErr=false;
    if($speeddial!=""){
      //speeddial must be numeric
      for($i=0; $i<strlen($speeddial); $i++){ 
        $ch=ord($speeddial[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]=T_("Speed Dial allows only numeric characters. Please change it");
          $objResponse->addAssign("speedErr","innerHTML",$imgErr);
          $speedErr=true;
          break;
        }
      }
      if($speedErr===false){
        //speeddial must be unique
        if((is_array($extNumberArr))&&(in_array($speeddial."*",$extNumberArr))){
          $errOut[]=T_("Speed Dial already in use. Please change it");
          $objResponse->addAssign("speedErr","innerHTML",$imgErr);
          $speedErr=true;
        }
      }
    }
    if($speedErr===false) $objResponse->addAssign("speedErr","innerHTML","");
    // Check Phonenumbers ((null)or((unique in provider)&&(contain cantact extension))
    $phonenumberErr=false;
    if(is_array($phonenumberArr)){
      //Phonenumbers must be unique in provider
      foreach($phonenumberArr as $number){
        if((is_array($gNumberArr))&&(in_array($number,$gNumberArr,true))){
          $errOut[]=T_("Some phone numbers have been already defined in another Zapata Group");
          $objResponse->addAssign("phonenumberErr","innerHTML",$imgErr);
          $phonenumberErr=true;
          break;
        }
      }
    }
    if($phonenumberErr===false){
    	$objResponse->addAssign("phonenumberErr","innerHTML","");
      // there are extension's cid settings linked to others numbers or not?
      $extensionList=""; 
      if((trim($id)!="")&&($id!=0)&&(is_array($thisgrpNumberArr))&&(count($thisgrpNumberArr)>0)){
      	//create array of deleted numbers
      	if(is_array($phonenumberArr)) $diffArr=array_diff($thisgrpNumberArr,$phonenumberArr);
  			else $diffArr=$thisgrpNumberArr;
      	//get cid settings for this trunk
        $ret=$asterisk->getCidFromTrunk($id);
        if(is_array($ret)){
        	foreach($ret as $c){
          	if(in_array($c["cid_number"],$diffArr,true)===true){
            	$client=$asterisk->getClient($c["extension"],0);
              if((is_array($client))&&(is_array($client[0]))){
              	$extensionList.=$client[0]["extension"].", ";
              }
            }
          }
        }
      }
      $pruneScript="";
      if(trim($extensionList)!=""){
      	$extensionList=substr($extensionList,0,-2);
        $pruneScript=sprintf(T_("Some Extensions (numbers: %s) use deleted numbers in Cid\\nIf you continue these settings will be deleted.\\nContinue?"),$extensionList);
      }
    }
    // Check Port List (not null)
    $portlistErr=false;
    if(!(is_array($portListArr))){
      //Port List must be not null
      $errOut[]=T_("Ports assigned to Zapata Group must be almost one");
      $objResponse->addAssign("portlistErr","innerHTML","&nbsp;&nbsp;".$imgErr);
      $portlistErr=true;
    }
    if($portlistErr===false) $objResponse->addAssign("portlistErr","innerHTML","");
    // Check Signalling
    $otherSigPortList="";
    if(is_array($portListArr)){
      foreach($portListArr as $c_id){
        $ret=$asterisk->getZapataChannel($c_id);
        if((is_array($ret))&&(is_array($ret[0]))){
          if($ret[0]["signalling"]!=$signalling){
            if($ret[0]["zchannel"]<10) $zero="0"; else $zero="";
            $otherSigPortList.=$zero.$ret[0]["zchannel"]." - ";
          } 
        }
      }
    }
    $signallingScript="";
    if(trim($otherSigPortList)!=""){
    	$otherSigPortList=substr($otherSigPortList,0,-3);
      $signallingScript=sprintf(T_("Some Ports (numbers: %s) have different signalling method (you have specify %s for this group).\\nIf you continue ports method will be overwritten with the group signalling value.\\n"),$otherSigPortList,$signalling);
      $signallingScript.=T_('WARNING: this operation will turn off pbx service! Continue?');
    }
    // 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",""); 
      if((trim($pruneScript)!="")&&(trim($signallingScript)!="")){
        $objResponse->addScript(" if(confirm('".$pruneScript."')){ if(confirm('".$signallingScript."')){ document.getElementById('mainform').submit(); } }");
      }else if(trim($pruneScript)!=""){
        $objResponse->addScript(" if(confirm('".$pruneScript."')){ document.getElementById('mainform').submit(); }");
      }else if(trim($signallingScript)!=""){
        $objResponse->addScript(" if(confirm('".$signallingScript."')){ document.getElementById('mainform').submit(); }");
      }else{
        $objResponse->addScript(" document.getElementById('mainform').submit(); ");
      }
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("changeLocation");
  $xajax->registerFunction("processFormData");
  $xajax->registerFunction("showCid");
  $xajax->registerFunction("hideCid");
  $xajax->registerFunction("roll");
  $xajax->processRequests();
  //================ POST & GET ================
  if(count($_POST)>0) {
    $entry=Array(
      "name"        => $_POST["name"],
      "port"        => $_POST["listRight"], 
      "msns"        => $_POST["phonenumber"], 
      "speeddial"   => $_POST["speeddial"],
      "type"        => $_POST["type"],
      "did"         => $_POST["did"],
      "group"       => $_POST["group"],
      "signalling"  => $_POST["signalling"],
      "location"      => $_POST["location"],
      "area_code"     => $_POST["area_code"],
      "prefix_policy" => $_POST["prefix_policy"],
      "prefix_format" => $_POST["prefix_format"]
    ); 
    // add options to the entry
    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if($v=="1") {
          $o["key"]=$k; 
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $entry["option"]=$options;
    // add cid setting
    if($_POST["cid"]["passthrough"]==1) $enable_cid=0; else $enable_cid=1;
    $cid=array(
    		"enable_cid" => $enable_cid,
        "cid_list" => $_POST["phonenumber"],
        "force_cid" => $_POST["cid"]["force_cid"],
        "clir" => $_POST["cid"]["clir"],
        "cid_number" => $_POST["cid"]["cid_number"],
        "cid_name" => $_POST["cid"]["cid_name"],
        "cid_appexten" => $_POST["cid"]["cid_appexten"]
    	);
    $entry["cid"]=$cid;
    //insert new entry or modify only ?
    if(isset($_POST["id"])) $entry["id"]=$_POST["id"];
    // save the group informations
    $ret=$asterisk->putZapataGroup($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("The group has been modified")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("The group hasn't been modified")."</div>";
    //return to groups page
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  //if modify, read the group informations
  if(isset($_GET["id"])){
    $ret=$asterisk->getZapataGroup($_GET["id"]);
    if($err=$asterisk->getError()) die("Error: $err");
    $id          = $ret[0]["id"];
    $name        = $ret[0]["name"];
    $rule        = $ret[0]["rule"];
    $speeddial   = $ret[0]["speeddial"];
    $trunk_order = $ret[0]["trunk_order"];
    $groupPort   = $ret[0]["port"];
    $groupOption = $ret[0]["option"];
    $type        = $ret[0]["type"];
    $did         = $ret[0]["did"];
    $signalling  = $ret[0]["signalling"];
    $group       = $ret[0]["group"];
    $location    = $ret[0]["location"];
    $area_code   = $ret[0]["area_code"];
    $prefix_policy=$ret[0]["prefix_policy"];
    $prefix_format=$ret[0]["prefix_format"];
    if (is_array($ret[0]["msns"]))
    foreach ($ret[0]["msns"] as $n) {
      $numbers.="<option value=\"".$n."\">".$n."</option>";
    }
    $cid=$ret[0]["cid"];
    if($cid["enable_cid"]==1) $passthrough=0; else $passthrough=1;
    $cid_force=$cid["force_cid"];
    $cid_clir=$cid["clir"];
    $cid_number=$cid["cid_number"];
    $cid_appexten=$cid["cid_appexten"];
    $cid_name=$cid["cid_name"];
  }
  //else set port type
  else{
    $cid_enable=1;
    $prefix_policy=0;
    $prefix_format=0;
    $type=$_GET["portType"];
  } 
  //set signalling options
  $option_signalling="";
  $choose_signalling=array();
  switch($type){
    case "PRI":
      $choose_signalling[] = "pri_cpe";
      $choose_signalling[] = "pri_net";
      break;
    case "E&M":
      $choose_signalling[] = "em";
      $choose_signalling[] = "em_w";
      break;
    case "FXO":
      $choose_signalling[] = "fxs_ks";
      $choose_signalling[] = "fxs_ls";
      $choose_signalling[] = "fxs_gs";    
      break;
    case "FXS":
      $choose_signalling[] = "fxo_ks";
      $choose_signalling[] = "fxo_ls";
      $choose_signalling[] = "fxo_gs";    
      break;
    default:
      die("unknown type");
  }
  if(is_array($choose_signalling)){
    foreach($choose_signalling as $s){
      if($s==$signalling) $chk_opt="selected=\"selected\""; else $chk_opt="";
      $option_signalling.="<option value=\"".$s."\" $chk_opt>".$s."</option>";
    }
  }
  // get the ports, channel informations
  $ret=$asterisk->getZapataChannel(0);
  if(is_array($ret)){
    $old_card_id=0;
    $old_port_id=0;
    $countcard=0;
    foreach($ret as $v){
      //skip ports that are not valid or not requested
      if(($v["type"]!=$type)||($v["device"]=="unused")) continue;
      $available = $v["available"];
      $port_id   = $v["port_id"];   // Port Id number
      if($v["zchannel"]<10) $zero="0"; else $zero="";
      // We should only have valid entries to show here !!!
      if ($type == 'FXO' || $type == 'FXS') {
        $pchannel = $v["pchannel"];
        $chaninfo = ",".$pchannel;
      } else {
        $chaninfo = "";
      }
      // Show only one entry for PRI and E&M, anyhow you can only
      // assign the whole port while channelbanks are different 
      if($old_port_id == $port_id && $type == 'PRI'){
        continue; // Show only the whole port here
      }
      if($old_port_id == $port_id && $type == 'E&M'){
        continue; // Show only the whole port here
      }
      //verify current port
      if($old_port_id!=$port_id){
        $p=$asterisk->getZapataPort($port_id);
        $card_id=$p[0]["card_id"];  
        $card=$p[0]["card"];
        $port_num=$p[0]["port"];
        $old_port_id=$port_id;
      }
      //verify current card
      if($old_card_id!=$card_id){ 
        $c=$asterisk->getZapataCard($card);
        if((is_array($c))&&(is_array($c[0]))) $cardname=$c[0]["name"];  else $cardname="unknown";
        $countcard++;
        $old_card_id=$card_id;
      }
      //print option in the correct list
      if((is_array($groupPort))&&(in_array($v["id"],$groupPort,true))){
        $portsRight.="<option value=\"".$v["id"]."\" >[".$zero.$v["zchannel"]."] Card n&deg;".$countcard." (".$cardname.") - Port n&deg;".$port_num."</option>";    
      }else if($available==1){
        $portsLeft.="<option value=\"".$v["id"]."\" >[".$zero.$v["zchannel"]."] Card n&deg;".$countcard." (".$cardname.") - Port n&deg;".$port_num."</option>";
      }          
    }  
  }
  //get the options 
  $html=getOption(OPTION_ZAPATA_GROUPS,$groupOption);
  //get location list
  $countrylist="";
  $location_script="";
  $locationArr=$asterisk->getLocation(0);
  if(is_array($locationArr)){
    $loc_sel_id=0;
    $loc_def_id=0;
    foreach($locationArr as $l){
      if($l["default"]==1) $loc_def_id=$l["id"];
      if($location==$l["id"]){
        $s="selected=\"selected\"";
        $loc_sel_id=$l["id"];
      }else $s="";
      $countrylist.="<option value=\"".$l["id"]."\" $s>".$l["name"]."</option>\n";
    }
    if($loc_sel_id==0) $loc_sel_id=loc_def_id;
    $location_script=" xajax_changeLocation('".$loc_sel_id."','".$area_code."'); ";
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); 
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=sprintf(T_("Group of ports (%s)"),$type )?></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 (isset($_GET['id'])) echo '?id='.$_GET['id'];?>" method="post" onSubmit="selectAll(getElementById('listRight')); return selectAll(getElementById('phonenumber'))">
      <!-- General info -->
      <p class="blockintro"><?=T_("Group of port general information")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="group[name]"><?=T_("Group name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="30" id="group[name]" name="name" value="<?=$name?>" /><span id="nameErr"></span></dd>
          <dt class="required"><label for="speeddial"><?=T_("Speed Dial")?>:</label></dt>
          <dd>           
            <input type="text" name="speeddial" id="speeddial" value="<?=$speeddial?>" size="17" maxlength="3"><big><span style="color: #000000;"> *</span></big><span id="speedErr"></span><span class="help">&nbsp;<?=T_("Direct selection (e.g. <strong>99</strong> or <strong>3</strong>), leave empty for autoassign")?></span>
            <input type="hidden" id="oldSpeeddial" name="oldSpeeddial" value="<?=$speeddial?>" />
          </dd>
          <dt class="required"><label for="signalling"><?=T_("Signalling")?>:</label></dt>
          <dd><select name=signalling><?=$option_signalling?></select> <span class="help"><?=T_("Signalling for this Trunkgroup")?></span></dd>
        </dl>
      </div>
      <!-- Numbers -->
    	<h2><?=T_("Listening phone numbers")?></h2>
      <p class="blockintro"><?=T_("Write the phone numbers that this group can manage")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required"><label for="number"><?=T_("Phone number")?>:</label></td>
            <td class="required"><?=T_("Added phone number")?></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('phonenumber'),document.getElementById('number').value); document.getElementById('number').value='' " title="Add Length">
              <div class="help"><?=T_("Digit the numbers to listen (i.e. <strong>123456</strong>)<br/>or a range of numbers as (<strong>123456-123459</strong>)")?></div>
            </td>
            <td>
              <select name="phonenumber[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="phonenumber">
                <?=$numbers?>
              </select>
              <input type="button" value="edit" onclick="editOptions(getElementById('phonenumber'))" title="Edit Length(s)">
              <input type="button" value="X" onclick="deleteOptions(getElementById('phonenumber'))" title="Delete Length(s)">
              <span id="phonenumberErr"></span>
            </td>
          </tr>
          <tr>
            <td colspan="2"><div style="margin: 0.5em 0"><?=T_("<strong>DID</strong> (Direct Inward Dialing)")?>: <?=showDid($did);?></div></td>
          </tr>
        </table>
      </div>
      <!-- Ports -->
    	<h2><?=T_("Ports")?></h2>
      <p class="blockintro"><?=T_("Choose the ports that belongs to this group")?></p>
      <div class="block">
        <table border="0">
        <tr>
          <td class="required">
            <div ><?=T_("Available ports")?>:</div>
            <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$portsLeft?></select>
          </td>
          <td>   
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), false )" name="Add     >>"  value="<?=T_("&nbsp;Add&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;>")?>" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<?=T_("<&nbsp;&nbsp;&nbsp;&nbsp;Remove&nbsp;&nbsp;&nbsp;&nbsp;")?>" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  )" name="Add All >>"  value="<?=T_("&nbsp;&nbsp;Add All&nbsp;&nbsp;&nbsp;&nbsp;>>")?>" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<?=T_("<<&nbsp;&nbsp;Remove All&nbsp;")?>" style="width:100px"></div>
          </td>
          <td class="required">
            <div><?=T_("Ports added")?>:<span id="portlistErr"></span></div>
            <select multiple size="5" name="listRight[]" id="listRight"><?=$portsRight?></select>
          </td>
        </tr>
        </table>
      </div>
      <!-- Location -->
      <h2><?=T_("Location")?></h2>
      <p class="blockintro"><?=T_("Set where trunk is lacated and the prifix policy for outgoing call")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="location"><?=T_("Country")?>:</label></dt>
          <dd>
            <select id="location" name="location" onchange="document.getElementById('area_code_roll').innerHTML='<img src=\'<?=$relBasePath?>public/img/ico-progress.gif\' alt=\'loading\' /><span><?=T_("loading")?>';xajax_changeLocation(this.options[this.selectedIndex].value,'<?=$area_code?>')">
              <?=$countrylist?>
            </select>
          </dd>
          <dt class="required"><label for="area_code"><?=T_("Area Code")?>:</label></dt>
          <dd>
            <div id="area_code_div" style="display:inline;">&nbsp;</div>
            <div id="area_code_roll" style="display:inline;"><img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span></div>            
          </dd>
        </dl>
        <dl style="margin-top:15px;">
          <dt class="required" style="height:70px;"><label for="prefix_policy"><?=T_("Prefix policy for National Calls")?>:</label></dt>
          <dd>
            <div><input style="vertical-align:center;" type="radio" id="prefix_policy" name="prefix_policy" value="0" <?if ($prefix_policy==0) echo "checked=\"checked\"";?> /> <strong><?=T_("Do nothing")?></strong> (<?=T_("don't modify dialed number")?>)</div>
            <div><input style="vertical-align:center;" type="radio" id="prefix_policy" name="prefix_policy" value="2" <?if ($prefix_policy==2) echo "checked=\"checked\"";?> /> <strong><?=T_("Add prefix")?></strong> (<?=T_("Always prepend international prefix + country code (ie. 0039) to the dialed number")?>)</div>
            <div><input style="vertical-align:center;" type="radio" id="prefix_policy" name="prefix_policy" value="1" <?if ($prefix_policy==1) echo "checked=\"checked\"";?> /> <strong><?=T_("Remove prefix")?></strong> (<?=T_("Always remove international prefix + country code (ie. 0039) to the dialed number")?>)</div>
          </dd>
        </dl>
        <dl style="margin-top:15px;">
          <dt class="required" style="height:70px;"><label for="prefix_format"><?=T_("Prefix format")?>:</label></dt>
          <dd>
            <div><input style="vertical-align:center;" type="radio" id="prefix_format" name="prefix_format" value="0" <?if ($prefix_format==0) echo "checked=\"checked\"";?> /> <strong><?=T_("Do nothing")?></strong> (<?=T_("use 00XX format as default but don't replace +XX format")?>)</div>
            <div><input style="vertical-align:center;" type="radio" id="prefix_format" name="prefix_format" value="2" <?if ($prefix_format==2) echo "checked=\"checked\"";?> /> <strong>00XX</strong> (<?=T_("Use 00XX format as default and always replace +XX format")?>)</div>
            <div><input style="vertical-align:center;" type="radio" id="prefix_format" name="prefix_format" value="1" <?if ($prefix_format==1) echo "checked=\"checked\"";?> /> <strong>+XX</strong> (<?=T_("Use +XX format as default and always replace 00XX format")?>)</div>
          </dd>
        </dl>
      </div>
      <!-- Caller Id -->
      <h2><?=T_("Caller Id")?></h2>
      <p class="blockintro"><?=T_("Set the caller id for this group (it will be shown like: CID Name &lt;CID NUMBER&gt;)")?></p>
      <div class="block">
        <div>
          <dl>
            <dt class="required"><label for="cid[clir]"><?=T_("CLIR")?>:</label></dt>
            <dd><input type="checkbox" id="cid[clir]" name="cid[clir]" value="1" <?if ($cid_clir==1) echo "checked=\"checked\""; ?> /> <?=T_("hide caller id dialing with this line")?></dd>
            <dt class="required"><label for="cid[passthrough]"><?=T_("Pass Through")?>:</label></dt>
            <?if(isset($_GET["id"])) {?><dd><input type="checkbox" id="cid[passthrough]" name="cid[passthrough]" value="1" onclick="if(this.checked){xajax_hideCid();}else{xajax_showCid(document.getElementById('id').value);}" <?if ($passthrough==1) echo "checked=\"checked\""; ?> /> <?=T_("use user's caller id on this line")?></dd>
            <?}else{?><dd><input type="checkbox" id="cid[passthrough]" name="cid[passthrough]" value="1" onclick="if(this.checked){xajax_hideCid();}else{xajax_showCid('');}" <?if ($passthrough==1) echo "checked=\"checked\""; ?> /> <?=T_("use user's caller id on this line")?></dd><? } ?>
          </dl>  
        </div>
        <div id="callerid">
          <?if($passthrough==0) {?>
          <dl>
            <dt class="required"><label for="cid[cid_name]"><?=T_("CID Name")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="20" id="cid[cid_name]" name="cid[cid_name]" value="<?=$cid_name?>" /> <?=T_("default caller id name")?></dd>
            <dt class="required"><label for="cid[cid_number]"><?=T_("CID Number")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="100" id="cid[cid_number]" name="cid[cid_number]" value="<?=$cid_number?>" /> <?=T_("default caller id number")?></dd>
            <dt class="required"><label for="cid[cid_appexten]"><?=T_("Append Exten")?>:</label></dt>
            <dd><input type="checkbox" id="cid[cid_appexten]" name="cid[cid_appexten]" value="1" <?if ($cid_appexten==1) echo "checked=\"checked\""; ?> /> <?=T_("append user's extension to CID Number value")?></dd>
            <dt class="required"><label for="cid[force_cid]"><?=T_("Force Default")?>:</label></dt>
            <dd><input type="checkbox" id="cid[force_cid]" name="cid[force_cid]" value="1" <?if ($cid_force==1) echo "checked=\"checked\""; ?> /> <?=T_("overwrite user's caller id setting with default line values")?></dd>
          </dl>
          <? } ?>
        </div>
      </div>
      <!-- List Options -->
      <? echo listOption($js, ZAP, $groupOption, false, false, RULE_INCOMING);?>   
      <!-- Actions -->
      <?=$numHidden?>      
      <div class="action">
        <? if (isset($_GET["id"])){ ?>
          <input type="hidden" id="id" name="id" value="<?=$_GET['id']?>" />
          <input type="hidden" id="group" name="group" value="<?=$group?>" />
        <? } ?>
        <input type="hidden" name="type" value="<?=$type?>" />
        <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')); selectAll(getElementById('phonenumber')); 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='../groups.php'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
      -->
      </div>
    </form>
  </div>  
  <script>
    <?=$location_script?>
  </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="zapGroup";include("../../sidebar.php");?>
      <h1><?=T_("The group of Zapata ports")?></h1>
      <p></p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "zapGroup");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

