<?
/**
 * VoiceOne Settings/Provider/account
 *
 * Frontend to provide access to the provider's accounts in voiceone.
 * @package voiceone
 * @subpackage  settings_provider
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
 	require_once("$absBasePath/lib/xajax/xajax.inc.php");
 	sajax_init();
  //================ 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=\"res[area_code]\" name=\"res[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($acc_id){
    global $asterisk,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    if($acc_id!=""){
      $ret=$asterisk->getProviderAccount($acc_id,0);
      if ($err=$asterisk->getError()) die("Error: $err");
      $cid_force=$ret[0]["force_cid"];
      $cid_clir=$ret[0]["clir"];
      $cid_number=$ret[0]["cid_number"];
      $cid_name=$ret[0]["cid_name"];
      $cid_appexten=$ret[0]["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
    $account=$formData["res"];
    if($account["provider"]!="") $provider=$account["provider"];
    else $provider=$account["provider_hidden"];
    $id=$account["id"];
    $name=$account["name"];
    $username=$account["username"];
    $password=$account["password"];
    $confirm=$account["confirm"];
    $allow_in=$account["allow_in"];
    $speeddial=$account["speeddial"];
    $oldSpeeddial=$account["oldSpeeddial"];
    $contact_extension=$account["contact_extension"];
    $phonenumberArr=$formData["phonenumber"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all accounts
    $providerArr=$asterisk->getProvider(0);
    if(is_array($providerArr)){
    	$thisaccNumberArr=array();
      foreach($providerArr as $p){
        if(is_array($p["accounts"])){
          foreach($p["accounts"] as $a){
            if($id==$a["id"]){
            	if(is_array($a["numbers"])) $thisaccNumberArr=$a["numbers"];
            	continue;
            }
            $aNameArr[]=$a["name"];
            if(($a["provider"]==$provider)&&(is_array($a["numbers"]))){
              foreach($a["numbers"] as $num) $aNumberArr[]=$num;
            }
          }
        }
      }
    }
    // 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($aNameArr))&&(in_array($name,$aNameArr,true))){
      //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
      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($ch==45){
          $errOut[]=sprintf(T_("Name doesn't allow character %s Please change it"),$name[$i] );
          $objResponse->addAssign("nameErr","innerHTML",$imgErr);
          $nameErr=true;
          break;
        }
      }
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check Username ((not null)and(not spaces))
    $usernameErr=false;
    if($username==""){
      //account username cannot be null
      $errOut[]=T_("Username cannot be null");
      $objResponse->addAssign("usernameErr","innerHTML",$imgErr);
      $usernameErr=true;
    }else{
      //username must have no spaces
      for($i=0; $i<strlen($username); $i++){
        $ch=ord($username[$i]);
        if($ch==32){
          $errOut[]=T_("Username doesn't allow spaces. Please change it");
          $objResponse->addAssign("usernameErr","innerHTML",$imgErr);
          $usernameErr=true;
          break;
        }
      }
    }
    if($usernameErr===false) $objResponse->addAssign("usernameErr","innerHTML","");
    // Check Account Password ((no null if register)&&(==confirm)&&(no spaces))
    $passwordErr=false;
    if(($allow_in==1)&&($password=="")){
      //account password cannot be null
      $errOut[]=T_("Password cannot be null");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else if($password!=$confirm){
      //account password must be equal to confirm
      $errOut[]=T_("Password and confirmation password do not match");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else{
      //account password must have no spaces
      for($i=0; $i<strlen($password); $i++){
        $ch=ord($password[$i]);
        if($ch==32){
          $errOut[]=T_("Password doesn't allow spaces. Please change it");
          $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
          $passwordErr=true;
          break;
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check Contact Extension ((null)or(not spaces))
    $contactErr=false;
    if($contact_extension!=""){
      //contact extension must have no spaces
      for($i=0; $i<strlen($contact_extension); $i++){
        $ch=ord($contact_extension[$i]);
        if($ch==32){
          $errOut[]=T_("Contact extension doesn't allow spaces. Please change it");
          $objResponse->addAssign("contactErr","innerHTML",$imgErr);
          $contactErr=true;
          break;
        }
      }
    }
    if($contactErr===false) $objResponse->addAssign("contactErr","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,true))){
          $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($aNumberArr))&&(in_array($number,$aNumberArr,true))){
          $errOut[]=T_("Some phone numbers have been already defined in another account");
          $objResponse->addAssign("phonenumberErr","innerHTML",$imgErr);
          $phonenumberErr=true;
          break;
        }
      }
    }else if($contact_extension!=""){
      //Phonenumbers must contain cantact extension
      if((!(is_array($phonenumberArr)))||(!(in_array($contact_extension,$phonenumberArr,true)))){
        $errOut[]=T_("Phone numbers list doesn't include Contact Extension");
        $objResponse->addAssign("phonenumberErr","innerHTML",$imgErr);
        $phonenumberErr=true;
      }
    }
    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($thisaccNumberArr))&&(count($thisaccNumberArr)>0)){
      	//create array of deleted numbers
      	if(is_array($phonenumberArr)) $diffArr=array_diff($thisaccNumberArr,$phonenumberArr);
  			else $diffArr=$thisaccNumberArr;
      	//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 (%s) use deleted numbers in Cid\\nIf you continue these settings will be deleted.\\nContinue?"),$extensionList);
      }
    }
    // 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)!="") $objResponse->addScript(" if(confirm('".$pruneScript."')) 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("showCid");
  $xajax->registerFunction("hideCid");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //================= POST  ==================
  if (count($_POST)>0) {
    $data=$_POST["res"];
    $entry=Array(
        "id"            => $data["id"],
        "name"          => $data["name"],
        "speeddial"     => $data["speeddial"],
        "username"      => $data["username"],
        "password"      => $data["password"],
        "did"           => $_POST["did"],
        "allow_in"      => $data["allow_in"],
        "contact_extension" => $data["contact_extension"],
        "location"      => $data["location"],
        "area_code"     => $data["area_code"],
        "prefix_policy" => $data["prefix_policy"],
        "prefix_format" => $data["prefix_format"]
      );
    //provider host and port
    if (isset($data["provider"])&&($data["provider"]!="")) $entry["provider"]=$data["provider"];
    else $entry["provider"]=$data["provider_hidden"];
    $entry["port"]=$data["port"];
		//add the phonenumbers
    if (is_array($_POST["phonenumber"]))
    foreach($_POST["phonenumber"] as $pn) $entry["numbers"][]=trim($pn);
    // add cid setting
    $cid=$_POST["cid"];
    if($cid["passthrough"]==1) $entry["enable_cid"]=0;
    else $entry["enable_cid"]=1;
    $entry["force_cid"]=$cid["force_cid"];
    $entry["clir"]=$cid["clir"];
    $entry["cid_number"]=$cid["cid_number"];
    $entry["cid_name"]=$cid["cid_name"];
    $entry["cid_appexten"]=$cid["cid_appexten"];
    //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["options"]=$options;
    //put account
    $ret=$asterisk->putProviderAccount($entry);
    if ($err=$asterisk->getError()) $alert="<div class=\"AlertBad\">ERROR: $err</div>";
    if ($ret>0) {
      $alert.="<div class=\"AlertGood\">".T_("Provider has been successfully edited")."</div>";
      $_GET["id"]=$ret;
    } else $alert.="<div class=\"AlertBad\">".T_("Provider has NOT been edited")."</div>";
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  // Modify exsisting account
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getProviderAccount($id,0);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $provider=$v["provider"];
    $port=$v["port"];
    $speeddial=$v["speeddial"];
    $rule=$v["rule"];
    $username=$v["username"];
    $password=$v["password"];
    $did=$v["did"];
    $optionsArr=$v["options"];
    $cid["enable_cid"]=$v["enable_cid"];
    if($cid["enable_cid"]==1) $passthrough=0; else $passthrough=1;
    $cid["force_cid"]=$v["force_cid"];
    $cid["clir"]=$v["clir"];
    $cid["cid_number"]=$v["cid_number"];
    $cid["cid_name"]=$v["cid_name"];
    $cid["cid_appexten"]=$v["cid_appexten"];
    $location=$v["location"];
    $area_code=$v["area_code"];
    $prefix_policy=$v["prefix_policy"];
    $prefix_format=$v["prefix_format"];
    $allow_in=$v["allow_in"];
    $contactExt=$v["contact_extension"];
    //create the phone number list
    if (is_array($v["numbers"])) {
      foreach($v["numbers"] as $n) $numbers.="<option value='$n'>$n</option>";
    }
    //set allows
    if($allow_in==1) $checkAllowIn="checked=\"checked\""; else $checkAllowIn="";
    //set title
    $title=sprintf(T_("Edit account: %s "),$name );
  }
  // New provider's account
  else if (isset($_GET["prov"]) and $_GET["prov"]!="") {
    $provider=$_GET["prov"];
    $checkAllowIn="checked=\"checked\"";
    $prefix_policy=0;
    $prefix_format=0;
    //set title
    $title=T_("New account");
  }
  // Error: No account id && No provider id
  else die;
  //get providers
  $ret=$asterisk->getProvider(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)){
    $disableProv="";
    foreach($ret as $p){
      $pid=$p["id"];
      $pname=$p["name"];
      if($pid==$provider){
        $providerList.="<option value=\"$pid\" selected=\"selected\">$pname</option>\n";
        $technology=$p["technology"];
        $type=$p["type"];
        $disableProv="disabled=\"disabled\"";
        if(strpos($p["port"],"-")){
          $portArr=explode("-",$p["port"]);
          $port_current=$portArr[0];
          $port_end=$portArr[1];
          while(($port_current<=$port_end)&&($port_current<65537)){
            if($port_current==$port) $portList.="<option value=\"$port_current\" selected=\"selected\">$port_current</option>\n";
            $portList.="<option value=\"$port_current\" >$port_current</option>\n";
            $port_current++;
          }
          $disablePort="";
        }else{
          $portList.="<option value=\"".$p["port"]."\" selected=\"selected\">".$p["port"]."</option>\n";
        }
      }else{
        $providerList.="<option value=\"$pid\">$pname</option>\n";
      }
    }
  }
  //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."'); ";
  }
  //set default callerid in tech options
  if(!(isset($_GET["id"]) and $_GET["id"]!="")) {
    if($technology==SIP){
      $ret=$asterisk->getConfOption("","SIP",SECTION_DEFAULT);
      if(is_array($ret)){
        foreach($ret as $o){
          if($o["name"]=="callerid") $optionsArr[]=array("key" => $o["id"] , "value" => "null");
        }
      }
    }else if($technology==IAX2){
      $ret=$asterisk->getConfOption("","IAX2",SECTION_DEFAULT);
      if(is_array($ret)){
        foreach($ret as $o){
          if($o["name"]=="callerid") $optionsArr[]=array("key" => $o["id"] , "value" => "null");
        }
      }
    }
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=T_("Back without saving")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>?id=<?=$_GET["id"]?>" method="post"  onSubmit="return selectAll(getElementById('phonenumber'))">
	    <!-- Authentication -->
      <h2><?=T_("Authentication")?></h2>
      <p class="blockintro"><?=T_("Account authentication information to connect to provider")?></p>
      <div class="block">
        <table cellpadding="0" cellspacing="0">
          <tr>
            <td valign="top">
              <dl>
                <dt class="required"><label for="res[name]"><?=T_("Name")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="100" id="res[name]" name="res[name]" value="<?=$name?>" /><span id="nameErr"></span><span class="help"></span></dd>
                <dt class="required"><label for="res[provider]"><?=T_("Provider")?>:</label></dt>
                <dd><select id="res[provider]" name="res[provider]" size="1" style="width: 153px;" length="20" <?=$disableProv?> > <?=$providerList?></select><span class="help"></span>
                    <input type="hidden" id="res[provider_hidden]" name="res[provider_hidden]" value="<?=$provider?>" /></dd>
                <dt class="required"><label for="res[port]"><?=T_("Port")?>:</label></dt>
                <dd><select id="res[port]" name="res[port]" size="1" style="width: 153px;" length="20" <?=$disablePort?> ><?=$portList?></select><span class="help"></span>
              </dl>
            </td>
            <td valign="top">
              <dl>
                <dt class="required"><label for="res[username]"><?=T_("Username")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="100" id="res[username]" name="res[username]" value="<?=$username?>" /><span id="usernameErr"></span><span class="help"></span></dd>
                <dt class="required"><label for="res[password]"><?=T_("Password")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="res[password]" name="res[password]" value="<?=$password?>" /><span id="passwordErr"></span><span class="help"></span></dd>
      					<dt class="required"><label for="res[confirm]"><?=T_("Confirm")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="res[confirm]" name="res[confirm]" value="<?=$password?>" /><span id="confirmErr"></span><span class="help"></span></dd>
                <? if($type!=1){ ?>
                  <dt class="required"><label for="res[register]"><?=T_("Register")?>:</label></dt>
                  <dd><input type="checkbox" id="res[allow_in]" name="res[allow_in]" value="1" <?=$checkAllowIn?> /><span class="help"><?=T_("allow incoming call")?></span></dd>
                <? }else{ ?>
                  <dt class="required"><label for="res[register]"></label></dt>
                  <dd><input type="hidden" id="res[allow_in]" name="res[allow_in]" value="1"/></dd>
                <? } ?>
              </dl>
            </td>
          </tr>
        </table>
      </div>
      <!-- Settings -->
      <h2><?=T_("Settings")?></h2>
      <p class="blockintro"><?=T_("Account general settings")?></p>
      <div class="block">
        <dl>
				  <dt class="required"><label for="res[speeddial]"><?=T_("Speed Dial")?>:</label></dt>
          <dd>
            <input type="text" size="19" maxlength="50" id="res[speeddial]" name="res[speeddial]" value="<?=$speeddial?>" /><big><span style="color: #000000;"> *</span></big><span id="speedErr">&nbsp;</span><span class="help"><?=T_("Direct selection (e.g. <strong>99</strong> or <strong>3</strong>), leave empty for autoassign")?></span>
            <input type="hidden" maxlength="50" id="res[oldSpeeddial]" name="res[oldSpeeddial]" value="<?=$speeddial?>" />
          </dd>
          <? if($technology==SIP){ ?>
				    <dt class="required"><label for="res[contact_extension]"><?=T_("Contact Exten")?>:</label></dt>
            <dd><input type="text" size="22" maxlength="50" id="res[contact_extension]" name="res[contact_extension]" value="<?=$contactExt?>" /><span id="contactErr"></span> <span class="help"><?=T_("used by remote server (leave blank for default: \"<strong>s</strong>\")")?></span></dd>
          <? } ?>
        </dl>
        <? if($technology==IAX2){ ?>
				  <input type="hidden" id="res[contact_extension]" name="res[contact_extension]" value="" />
        <? } ?>
        <table style="margin-left: 24px;">
          <tr>
            <td class="required"><label for="number"><?=T_("Phone number")?>:</label></td>
            <td class="required"><?=T_("Phone 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('phonenumber'),document.getElementById('number').value);document.getElementById('number').value='';" title="<?=T_("Add")?>">
              <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>
              <div style="margin: 0.5em 0"><strong><?=T_("DID")?>:</strong> <?=showDid($did);?></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="<?=T_("Edit")?>" onclick="editOptions(getElementById('phonenumber'))" title="<?=T_("Edit")?>" />
              <input type="button" value="<?=T_("X")?>" onclick="deleteOptions(getElementById('phonenumber'))" title="<?=T_("Delete")?>" />
              <span id="phonenumberErr"></span>
            </td>
          </tr>
        </table>
      </div>
      <!-- Location -->
      <h2><?=T_("Location")?></h2>
      <p class="blockintro"><?=T_("Set where trunk is located and the prifix policy for outgoing call")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="res[location]"><?=T_("Country")?>:</label></dt>
          <dd>
            <select id="res[location]" name="res[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="res[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="res[prefix_policy]"><?=T_("Prefix policy for National Calls")?>:</label></dt>
          <dd>
            <div><input style="vertical-align:center;" type="radio" id="res[prefix_policy]" name="res[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="res[prefix_policy]" name="res[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="res[prefix_policy]" name="res[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="res[prefix_format]"><?=T_("Prefix format")?>:</label></dt>
          <dd>
            <div><input style="vertical-align:center;" type="radio" id="res[prefix_format]" name="res[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="res[prefix_format]" name="res[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="res[prefix_format]" name="res[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('res[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['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['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["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_cid"]==1) echo "checked=\"checked\""; ?> /> <?=T_("overwrite user's caller id setting with default line values")?></dd>
          </dl>
          <? } ?>
        </div>
      </div>
      <!-- Tech Options -->
      <? echo listOption($js, $technology, $optionsArr,false,false,RULE_INCOMING,false,true);?>
	    <!-- Input Buttons -->
      <div class="action">
        <input type="hidden" id="res[id]" name="res[id]" value="<?=$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('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='../'; 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="providers";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new provider account or to modify an existing one. To create a new account you have to define the name, the authentication parameters, the phonenumber of the line, the CID number for the outgoing calls and to press save button on the end of the page. Moreover it's possible to define other parameters like the speed dial, incoming ruleset, advanced options, etc...")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "providers");
  $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');
?>

