<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
  include ("../../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  
  //================ XAJAX ================
  function loadOptions($id,$phone_type){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    if($id!=0){
      $ret=$asterisk->getProvTemplate($id);
      $firmware=$ret[0]["firmware"];
      $oArr=$ret[0]["options"];
      if(is_array($oArr)){
        $optionsArr=array();
        foreach($oArr as $o){
          $optionsArr[$o["key"]]=array(value=>$o["value"],mode=>$o["mode"]);
        }
      }
    }
    $ret=$asterisk->getPhoneOptions($phone_type);
    if(is_array($ret)){
    	$login=""; $sip=""; $nat=""; $rtp=""; $advanced=""; $dkey=""; 
      $fkey=array(); $fkey_pre=array(); $fcontext=array(); $fcontext_pre=array();
      $optionModeArr=array("[none]","!","$");
      foreach($ret as $v){  
        $element="";
        $id=$v["id"];
        $name=$v["name"];
        $description=$v["description"];
        $type=$v["type"];
        $value_list=$v["value_list"];
        $default=$v["default"];
        $visual_list=$v["visual_list"];
        $account=$v["account"];
        //setup option
        if(is_array($optionsArr[$id])){
          $value=$optionsArr[$id]["value"];
          $mode=$optionsArr[$id]["mode"];
          $commented="0";
        }else{
          $value=$default;
          $mode="none";
          $commented="1";
        }
        //create mode element
        if(is_array($optionModeArr)){
          $mode_element="<select name=\"option[$id][mode]\" id=\"mode_$name\" >";
          foreach($optionModeArr as $m) {
            $m=trim($m);
            if($m==$mode) $checked=" selected=\"selected\" "; else $checked=""; 
            $mode_element.="<option value=\"$m\" $checked/> $m </option>";
          }
          $mode_element.="</select>";
        }
        //evaluate the different input type field
        switch ($type) {
          case "radio":
            $arr=explode("|",$value_list);
            $visual_arr=explode("|",$visual_list);
            $count=0;
            foreach($arr as $item) {
              $item=trim($item);
              if($item==$value) $checked=" checked=\"checked\" "; else $checked="";
              if($item==$default){
              	$d=" (default) ";
                if((isset($visual_arr[$count]))&&(trim($visual_arr[$count])!="")) $visual_default=$visual_arr[$count]; 
                else $visual_default=$default; 
              }else{
              	$d="";
              }
              if((isset($visual_arr[$count]))&&(trim($visual_arr[$count])!="")) $item_name=$visual_arr[$count]; else $item_name=$item;
              $element.="<input type=\"radio\" id=\"$item\" name=\"option[$id][value]\" value=\"$item\" $checked> $item_name $d";
              $count++;
            }
          break;
          case "select":
            $arr=explode("|",$value_list);
            $visual_arr=explode("|",$visual_list);
            //errArr($visual_arr);
            $element="<select name=\"option[$id][value]\" id=\"$name\" >";
            $count=0;
            foreach($arr as $item) {
              $item=trim($item);
              if($item==$value) $selected=" selected=\"selected\" "; else $selected="";
              if($item==$default){
              	$d=" (default) ";
                if((isset($visual_arr[$count]))&&(trim($visual_arr[$count])!="")) $visual_default=$visual_arr[$count]; 
                else $visual_default=$default;
              }else{
              	$d="";
              } 
              if((isset($visual_arr[$count]))&&(trim($visual_arr[$count])!="")) $item_name=$visual_arr[$count]; else $item_name=$item;
              $element.="<option value=\"$item\" $selected/> $item_name $d</option>";
              $count++;
            }
            $element.="</select>";
          break;
          case "text":
          default:
            $element.="<input type=\"text\" size=\"25\" id=\"$id\" name=\"option[$id][value]\" value=\"$value\" />";
            $visual_default=$default;
          break;
        }
        //prepare html
        if($commented=="1"){ 
          $on="0"; 
          $status=" class='ON' "; 
          $classOn=" class=\"hide\" "; 
          $classOff=" class=\"show\" "; 
          $buttonLabel="<img src=\"".$relBasePath."/public/img/checkbox.gif\" alt=\"\" />"; 
          $classLabel=" class=\"commented\" ";
        }else{
          $on="1"; 
          $status=" class='OFF' ";  
          $classOn=" class=\"show\" "; 
          $classOff=" class=\"hide\" "; 
          $buttonLabel="<img src=\"".$relBasePath."/public/img/checkbox_ok.gif\" alt=\"\" />"; 
          $classLabel=" class=\"required\" ";
        }
        //set option label
        if(trim($description)=="") $opt_label=$name; else $opt_label=$description;
        //assign html to section   
        if($account==0){
      		$button="<a id=\"a_$name\" $status onclick=\"changeStatus('$name');\">".$buttonLabel."</a>";
          $label="<label id=\"label_$name\" $classLabel>".$opt_label.":</label>";
          $on_element="<div id=\"on_$name\" $classOn >".$mode_element." ".$element."</div>";
          $off_element="<div id=\"off_$name\" $classOff >".$visual_default."</div>";
          $status_element="<input type=\"hidden\" id=\"status_$name\" name=\"option[$id][status]\" value=\"$on\" />";
          //html
          $advanced.="<tr >\n" ;
          $advanced.="  <td class=\"colOption\">$button $label</td>\n" ; 
          $advanced.="  <td width=\"1%\"><nobr> $on_element $off_element $status_element </nobr></td>\n" ;
          $advanced.="</tr>\n" ;
        }else if($account==1){
        	$button="<a id=\"a_$name\" $status onclick=\"changeStatus('$name');\">".$buttonLabel."</a>";
          $label="<label id=\"label_$name\" $classLabel>".$opt_label.":</label>";
          $on_element="<div id=\"on_$name\" $classOn >".$mode_element." ".$element."</div>";
          $off_element="<div id=\"off_$name\" $classOff >".$visual_default."</div>";
          $status_element="<input type=\"hidden\" id=\"status_$name\" name=\"option[$id][status]\" value=\"$on\" />";
          //html
          $login.="<tr >\n" ;
          $login.="  <td class=\"colOption\">$button $label</td>\n" ; 
          $login.="  <td width=\"1%\"><nobr> $on_element $off_element $status_element </nobr></td>\n" ;
          $login.="</tr>\n" ;
        }else if(($account==2)||($account==3)||($account==4)){
        	$button="<a id=\"a_$name\" $status onclick=\"changeStatus('$name');\">".$buttonLabel."</a>";
          $label="<label id=\"label_$name\" $classLabel>".$opt_label.":</label>";
          $on_element="<div id=\"on_$name\" $classOn >".$mode_element." ".$element."</div>";
          $off_element="<div id=\"off_$name\" $classOff >".$visual_default."</div>";
          $status_element="<input type=\"hidden\" id=\"status_$name\" name=\"option[$id][status]\" value=\"$on\" />";
          //html
          $html="";
          $html.="<tr >\n" ;
          $html.="  <td class=\"colOption\">$button $label</td>\n" ; 
          $html.="  <td width=\"1%\"><nobr> $on_element $off_element $status_element </nobr></td>\n" ;
          $html.="</tr>\n" ;	
          if($account==2) $sip.=$html;
          else if($account==3) $nat.=$html;
          else if($account==4) $rtp.=$html;
        }else if(($account==5)||($account==6)||($account==7)||($account==8)){	
        	$button="<a id=\"a_$name\" $status onclick=\"changeStatus('$name');\">".$buttonLabel."</a>";
          $label="<label id=\"label_$name\" $classLabel>".$opt_label.":</label>";
          $on_element="<div id=\"on_$name\" $classOn >".$mode_element." ".$element."</div>";
          $off_element="<div id=\"off_$name\" $classOff >".$visual_default."</div>";
          $status_element="<input type=\"hidden\" id=\"status_$name\" name=\"option[$id][status]\" value=\"$on\" />";
          //html
          $html="";
          $html.="<tr >\n" ;
          $html.="  <td class=\"colOption\">$button $label</td>\n" ; 
          $html.="  <td width=\"1%\"><nobr> $on_element $off_element $status_element </nobr></td>\n" ;
          $html.="</tr>\n" ;
          if($account==5) $fkey[]=$html; 
          else if($account==6) $fkey_pre[]=$html;
          else if($account==7) $fcontext[]=$html;
          else if($account==8) $fcontext_pre[]=$html;
        }else if($account==9){
        	$button="<a id=\"a_$name\" $status onclick=\"changeStatus('$name');\">".$buttonLabel."</a>";
          $label="<label id=\"label_$name\" $classLabel>".$opt_label.":</label>";
          $on_element="<div id=\"on_$name\" $classOn >".$mode_element." ".$element."</div>";
          $off_element="<div id=\"off_$name\" $classOff >".$visual_default."</div>";
          $status_element="<input type=\"hidden\" id=\"status_$name\" name=\"option[$id][status]\" value=\"$on\" />";
          //html
          $dkey.="<tr >\n" ;
          $dkey.="  <td class=\"colOption\">$button $label</td>\n" ;
          $dkey.="  <td width=\"1%\"><nobr> $on_element $off_element $status_element </nobr></td>\n" ;
          $dkey.="</tr>\n" ;
        }
      }
      if(trim($login)!=""){
      	$login="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('login_table');return false;\">".T_("Show Login options...")."</a>".
             "</div>".
             "<table id=\"login_table\" style=\"display:none;\" width=\"100%\">".$login."</table>";
      }
      if(trim($sip)!=""){ 
      	$sip="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('sip_table');return false;\">".T_("Show SIP options...")."</a>".
             "</div>".
             "<table id=\"sip_table\" style=\"display:none;\" width=\"100%\">".$sip."</table>";
      }
      if(trim($nat)!=""){
      	$nat="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('nat_table');return false;\">".T_("Show NAT options...")."</a>".
             "</div>".
             "<table id=\"nat_table\" style=\"display:none;\" width=\"100%\">".$nat."</table>";
      }
      if(trim($rtp)!=""){
      	$rtp="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('rtp_table');return false;\">".T_("Show RTP options...")."</a>".
             "</div>".
             "<table id=\"rtp_table\" style=\"display:none;\" width=\"100%\">".$rtp."</table>";
      }
      if(trim($advanced)!=""){
      	$advanced="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('advanced_table');return false;\">".T_("Show Advanced options...")."</a>".
             "</div>".
        		 "<table id=\"advanced_table\" style=\"display:none;\" width=\"100%\">".$advanced."</table>";
      }
      if((is_array($fkey))||(is_array($fkey_pre))){
      	$html="";
        if(is_array($fkey_pre)){
          for($i=0;$i<count($fkey_pre);$i++){
          	if(isset($fkey_pre[$i])) $html.=$fkey_pre[$i];
            if(isset($fcontext_pre[$i])) $html.=$fcontext_pre[$i];
          }
        }
        if(is_array($fkey)){
          for($i=0;$i<count($fkey);$i++){
          	if(isset($fkey[$i])) $html.=$fkey[$i];
            if(isset($fcontext[$i])) $html.=$fcontext[$i];
          }
        }
      	$fkey="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('fkey_table');return false;\">".T_("Show Function Keys...")."</a>".
             "</div>".
        		 "<table id=\"fkey_table\" style=\"display:none;\" width=\"100%\">".$html."</table>";
      }
      if(trim($dkey)!=""){
      	$dkey="<div style=\"margin-bottom:10px;\">".
        		 "<a href=\"\" class=\"admin\" onclick=\"show_hide('dkey_table');return false;\">".T_("Show Preprogrammed Keys...")."</a>".
             "</div>".
        		 "<table id=\"dkey_table\" style=\"display:none;\" width=\"100%\">".$dkey."</table>";
      }
    }
    //Build Firmware Opt
    $firmwareScript=" fSelect=document.getElementById('firmware'); \n";
    $firmwareScript.=" while(fSelect.length!=0) fSelect.remove((fSelect.length-1)); \n";
    $firmwareScript.="var newOptObj=document.createElement('option'); \n";
    $firmwareScript.="newOptObj.value='0'; \n";
    $firmwareScript.="newOptObj.text='[none]'; \n";
    if($firmware==0) $firmwareScript.="newOptObj.selected=true; \n";
    $firmwareScript.="try {fSelect.add(newOptObj,null);} catch(ex) {fSelect.add(newOptObj);} \n";
    $ret=$asterisk->getProvFirmwareFromPhone($phone_type);
    if(is_array($ret)){
      foreach($ret as $p){        
        $firmwareScript.="var newOptObj=document.createElement('option'); \n";
        $firmwareScript.="newOptObj.value='".$p["id"]."'; \n";
        $firmwareScript.="newOptObj.text='".$p["name"]."'; \n";
        if($p["id"]==$firmware) $firmwareScript.="newOptObj.selected=true; \n";
        $firmwareScript.="try {fSelect.add(newOptObj,null);} catch(ex) {fSelect.add(newOptObj);} \n";
      }
    }  
    // Return the xajaxResponse object
    $objResponse->addAssign("login","innerHTML",$login);
    $objResponse->addAssign("sip","innerHTML",$sip);
    $objResponse->addAssign("nat","innerHTML",$nat);
    $objResponse->addAssign("rtp","innerHTML",$rtp);
    $objResponse->addAssign("options","innerHTML",$advanced);
    $objResponse->addScript($firmwareScript);
    $objResponse->addAssign("firmwareLoading","innerHTML","");
    $objResponse->addAssign("fkey","innerHTML",$fkey);
    $objResponse->addAssign("dkey","innerHTML",$dkey);
    return $objResponse->getXML();  
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form params
    $template=$formData["template"];
    $id=$template["id"];
    $id_phone=$template["id_phone"];
    $name=$template["name"];
    $description=$template["description"];
    $local=$template["local"];
    $registrar=$template["registrar"];
    $dhcp=$template["dhcp"];
    $netmask=$template["netmask"];
    $gateway=$template["gateway"];
    $domain=$template["domain"];
    $dns1=$template["dns1"];
    $dns2=$template["dns2"];
    $http_username=trim($template["http_username"]);
    $http_oldusername=trim($template["http_oldusername"]);
    $http_password=trim($template["http_password"]);
    $http_oldpassword=trim($template["http_oldpassword"]);
    $http_confirm=trim($template["http_comfirm"]);
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
		// Check Name ((not null)&&(unique))
    $nameErr=false;
    $tNameArr=array();
  	$res=$asterisk->getProvTemplate(0);
  	if(is_array($res)){
    	foreach($res as $t){
      	if(($t["id"]==$id)||($t["id_phone"]!=$id_phone)) continue;
        $tNameArr[]=trim($t["name"]);
      }
  	} 
    if(trim($name)=="") { 
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;  
    }else if((is_array($tNameArr))&&(in_array($name,$tNameArr,true))){
      //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 Registrar ((not null)&&(unique))
    $registrarErr=false;
    if(trim($registrar)==""){ 
      //name cannot be null
      $errOut[]= T_("Registrar cannot be null");
      $objResponse->addAssign("registrarErr","innerHTML",$imgErr);
      $registrarErr=true;  
    }
    if($registrarErr===false) $objResponse->addAssign("registrarErr","innerHTML","");
    // Check local Address (not null) [if dhcp off] 
    $netmaskErr=false;
    $gatewayErr=false;
    $dns1Err=false;
    if($dhcp==0){
      if(trim($netmask)==""){
      	$errOut[]= T_("Netmask can not bu null with dhcp off");
        $objResponse->addAssign("netmaskErr","innerHTML",$imgErr);
        $netmaskErr=true;
      }
      if(trim($gateway)==""){
      	$errOut[]= T_("Gateway can not bu null with dhcp off");
        $objResponse->addAssign("gatewayErr","innerHTML",$imgErr);
        $gatewayErr=true;
      }
      if(trim($dns1)==""){
      	$errOut[]= T_("Primary DNS can not bu null with dhcp off");
        $objResponse->addAssign("dns1Err","innerHTML",$imgErr);
        $dns1Err=true;
      }
    }
    if($netmaskErr===false) $objResponse->addAssign("netmaskErr","innerHTML","");
    if($gatewayErr===false) $objResponse->addAssign("gatewayErr","innerHTML","");
    if($dns1Err===false) $objResponse->addAssign("dns1Err","innerHTML","");
    // Check HTTP authentication
    $http_usernameErr=false;
    $http_passwordErr=false;
    $http_confirmErr=false;
    if($http_password!=$http_confirm){
      $errOut[]= T_("HTTP password and HTTP confirmation password do not match");
      $objResponse->addAssign("http_passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("http_confirmErr","innerHTML",$imgErr);
      $http_passwordErr=true;
      $http_confirmErr=true;
    }else if(($http_username=="")&&($http_password!="")){
    	$errOut[]= T_("Username can not be null if HTTP authentication is enabled");
      $objResponse->addAssign("http_usernameErr","innerHTML",$imgErr);
      $http_usernameErr=true;
    }else if(($http_username!="")&&($http_password=="")){
    	$errOut[]= T_("Password can not be null if HTTP authentication is enabled");
      $objResponse->addAssign("http_passwordErr","innerHTML",$imgErr);
      $http_passwordErr=true;
    }
    if($http_usernameErr===false) $objResponse->addAssign("http_usernameErr","innerHTML","");
    if($http_passwordErr===false) $objResponse->addAssign("http_passwordErr","innerHTML","");
    if($http_confirmErr===false) $objResponse->addAssign("http_confirmErr","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","");
      if(($http_username!=$http_oldusername)||($http_password!=$http_oldpassword)){
    		$script="if(confirm('".T_("HTTP authentication settings have been changed and all phones which are linked to template must be reloaded.\\nAre you sure you want continue and reload all linked phones?")."')) document.getElementById('mainform').submit();";
    	}else $script=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("loadOptions");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $template=$_POST["template"];
    $entry=Array(
        "id" => $template["id"],
        "id_phone" => $template["id_phone"],
        "name" => $template["name"],
        "description" => $template["description"],
        "local" => $template["local"],
        "registrar" => $template["registrar"],
        "dhcp" => $template["dhcp"],
        "netmask" => $template["netmask"],
        "gateway" => $template["gateway"],
        "domain" => $template["domain"],
        "dns1" => $template["dns1"],
        "dns2" => $template["dns2"],
        "firmware" => $template["firmware"],
        "directory" => $template["directory"],
        "http_username" => $template["http_username"],
        "http_password" => $template["http_password"],
        "http_scheme" => $template["http_scheme"],
        "ldap" => $template["ldap"]
      );
    //add options to the entry
    $options=array();
    if(is_array($_POST["option"])){
      foreach($_POST["option"] as $k=>$v) {
        if((is_array($v))&&($v["status"]=="1")){
        	$o=array();
          $o["key"]=$k; 
          $o["value"]=$v["value"];
          if($v["mode"]!="[none]") $o["mode"]=$v["mode"];
          else $o["mode"]="";
          $options[]=$o;
        }
      }
    }
    $entry["options"]=$options;
    //put template
    $ret=$asterisk->putProvTemplate($entry);
    if($ret>0){
    	$alert="<div class=\"AlertGood\">".T_("Template has been successfully edited")."</div>";
      //reload template's phones
      if( (trim($template["http_username"])!=trim($template["http_oldusername"])) ||
      	  (trim($template["http_password"])!=trim($template["http_oldpassword"])) ){
      	$asterisk->templatePhoneAction("reboot",$template["id"],array(),$template["http_oldusername"],$template["http_oldpassword"],$template["http_oldscheme"]);
      }
    }else $alert="<div class=\"AlertBad\">".T_("Template has NOT been edited")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
    
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getProvTemplate($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $p=$ret[0];
    $id=$p["id"];
    $id_phone=$p["id_phone"];
    $name=$p["name"];
    $description=$p["description"];
    $ip=$p["ip"];
    $dhcp=$p["dhcp"];
    $local=$p["local"];
    $registrar=$p["registrar"];
    $netmask=$p["netmask"];
    $gateway=$p["gateway"];
    $domain=$p["domain"];
    $dns1=$p["dns1"];
    $dns2=$p["dns2"];
    $firmware=$p["firmware"];
    $directory=$p["directory"];
    $http_username=$p["http_username"];
    $http_password=$p["http_password"];
    $http_scheme=$p["http_scheme"];
    $ldap=$p["ldap"];
    //Title
    $title=sprintf(T_("Edit Template : %s"),$name );
  }else{
    $id=0;
    $domain="";
    $id_phone=1;
    $dhcp=1;
    $local=1;
    $directory=0;
    //Title
    $title=T_("New Template");
  }
	//set dhcp radio
  if($dhcp==1){
  	$dhcp_on="checked=\"checked\"";
    $dhcp_off="";
    $disable_ip="disabled=\"disabled\"";
  }else{
  	$dhcp_on="";
    $dhcp_off="checked=\"checked\"";
    $disable_ip="";
  }
  //set local radio
  if($local==1){
  	$local_on="checked=\"checked\"";
    $local_off="";
    $display_external="display:none;";
  }else{
  	$local_on="";
    $local_off="checked=\"checked\"";
    $display_external="display:block;";
  }
  //set ldap radio
  if($ldap==1){
    $ldap_on="checked=\"checked\"";
    $ldap_off="";
  }else{
    $ldap_on="";
    $ldap_off="checked=\"checked\"";
  }
  //Prepare Phone Opt
  $phoneOpt="";
  $ret=$asterisk->getPhoneType(0);
  if(is_array($ret)){
    foreach($ret as $p) {
      if($p["id"]==$id_phone) $s=" selected=\"selected\" "; else $s="";
      $phoneOpt.="<option value=\"".$p["id"]."\" $s>".$p["vendor"]." ".$p["model"]."</option>\n";
    }
  }
  //Prepare Phone Opt
  $optDir="";
  if($directory==0) $s=" selected=\"selected\" "; else $s="";
  $optDir.="<option value=\"0\" $s>[none]</option>\n";
  $ret=$asterisk->getProvDirectory(0);
  if(is_array($ret)){
    foreach($ret as $d) {
      if($d["id"]==$directory) $s=" selected=\"selected\" "; else $s="";
      $optDir.="<option value=\"".$d["id"]."\" $s>".$d["name"]."</option>\n";
    }
  }
	//Init script
  $initScript="<script> xajax_loadOptions('".$id."','".$id_phone."'); </script>";
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../../admin/lib/xajax/");
  echo $initScript; 
  ?>
    <?$nav="templates";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?>" method="post" autocomplete="off">
        <!-- General Info -->
        <h2><?=T_("General Informations")?></h2>
        <p class="blockintro"><?=T_("Template's general informations")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="template[name]"><?=T_("Name")?>:</label></dt>
            <dd><input type="text" size="25" id="template[name]" name="template[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
            <dt class="required"><label for="template[description]"><?=T_("Description")?>:</label></dt>
            <dd><textarea id="template[description]" name="template[description]" cols="50" ><?=$description?></textarea></dd>
            <dt class="required"><label for="template[id_phone]"><?=T_("Phone Type")?>:</label></dt>
            <dd><select id="phoneSelect" name="template[id_phone]" onchange="putLoading(); xajax_loadOptions('<?=$id?>',this.options[this.selectedIndex].value)"><?=$phoneOpt?></select></dd>
            <dt class="required"><label for="template[firmware]"><?=T_("Firmware")?>:</label></dt>
            <dd><select id="firmware" name="template[firmware]"></select> <span id="firmwareLoading"><img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span></span></dd>
            <dt class="required"><label for="template[directory]"><?=T_("Directory")?>:</label></dt>
            <dd><select name="template[directory]"><?=$optDir?></select></dd>
          </dl>
        </div>
        <!-- Connection -->
        <h2><?=T_("Connection")?></h2>
        <p class="blockintro"><?=T_("Enter client's type of connection")?></p>
        <div class="block">
          <dl style="margin-top:0;padding-top:0">
          <dt class="required"><label for="template[local]"><?=T_("Connection")?>:</label></dt>
            <dd>
              <input type="radio" id="local_on" name="template[local]" value="1" <?=$local_on?> /><span style="vertical-align:bottom;"><?=T_("Local")?></span>&nbsp;
              <input type="radio" id="local_off" name="template[local]" value="0" <?=$local_off?> /><span style="vertical-align:bottom;"><?=T_("Remote")?></span>  
            </dd>
          </dl>
          <dl style="margin-top:0;padding-top:0;">  
            <dt class="required"><label for="template[registrar]"><?=T_("Registrar")?>:</label></dt>
            <dd><input type="text" id="template[registrar]" name="template[registrar]" value="<?=$registrar?>" /><span id="registrarErr"></span></dd>
            <? if(_isModuleLoaded('ldap')){ ?>
              <dt class="required"><label for="template[ldap]"><?=T_("LDAP")?>:</label></dt>
              <dd>
                <input type="radio" id="ldap_on" name="template[ldap]" value="1" <?=$ldap_on?> /><span style="vertical-align:bottom;"><?=T_("On")?></span>&nbsp;
                <input type="radio" id="ldap_off" name="template[ldap]" value="0" <?=$ldap_off?> /><span style="vertical-align:bottom;"><?=T_("Off")?></span>  
              </dd>
            <? }else{ ?>
              <input type="hidden" name="template[ldap]" value="1"/>
            <? } ?>
          </dl>
        </div>
  			<!-- Local Network -->
        <h2><?=T_("Local Network")?></h2>
        <p class="blockintro"><?=T_("Enter client's local network settings")?></p>
        <div class="block">
          <dl style="margin-bottom:0;padding-bottom:0">
            <dt class="required"><label for="template[dhcp]"><?=T_("DHCP")?>:</label></dt>
            <dd>
              <input type="radio" id="dhcp_on" name="template[dhcp]" value="1" onclick="showhideAddress(this.value);" <?=$dhcp_on?> /><span style="vertical-align:bottom;"><?=T_("On")?></span>&nbsp;
              <input type="radio" id="dhcp_off" name="template[dhcp]" value="0" onclick="showhideAddress(this.value);" <?=$dhcp_off?> /><span style="vertical-align:bottom;"><?=T_("Off")?></span>
            </dd>
          </dl>
          <dl style="margin-top:0;padding-top:0;<?=$local_display?>" id="dhcp">
            <dt class="required"><label for="template[netmask]"><?=T_("Netmask")?>:</label></dt>
            <dd><input type="text" maxlength="15" id="template[netmask]" name="template[netmask]" value="<?=$netmask?>" <?=$disable_ip?>/><span id="netmaskErr"></span></dd>
            <dt class="required"><label for="template[gateway]"><?=T_("Gateway")?>:</label></dt>
            <dd><input type="text" id="template[gateway]" name="template[gateway]" value="<?=$gateway?>" <?=$disable_ip?>/><span id="gatewayErr"></span></dd>
          	<dt class="required"><label for="template[domain]"><?=T_("Domain")?>:</label></dt>
            <dd><input type="text" id="template[domain]" name="template[domain]" value="<?=$domain?>" <?=$disable_ip?>/><span id="domainErr"></span></dd>
            <dt class="required"><label for="template[dns1]"><?=T_("DNS 1:")?></label></dt>
            <dd><input type="text" maxlength="15" id="template[dns1]" name="template[dns1]" value="<?=$dns1?>" <?=$disable_ip?>/><span id="dns1Err"></span></dd>
            <dt class="required"><label for="template[dns2]"><?=T_("DNS 2:")?></label></dt>
            <dd><input type="text" maxlength="15" id="template[dns2]" name="template[dns2]" value="<?=$dns2?>" <?=$disable_ip?>/><span id="dns2Err"></span></dd>
          </dl>
        </div>
        <!-- HTTP Authentication -->
        <h2><?=T_("HTTP Authentication")?></h2>
        <p class="blockintro"><?=T_("Insert phone's HTTP authentication params or leave black for no authentication")?></p>
        <div class="block">
       		<dl>
            <dt class="required"><label for="template[http_username]"><?=T_("Username")?>:</label></dt>
            <dd>
            	<input type="text" maxlength="254" id="template[http_username]" name="template[http_username]" value="<?=$http_username?>" /><span id="http_usernameErr"></span>
            	<input type="hidden" name="template[http_oldusername]" value="<?=$http_username?>" />
            </dd>
            <dt class="required"><label for="template[http_password]"><?=T_("Password")?>:</label></dt>
            <dd>
            	<input type="password" id="template[http_password]" name="template[http_password]" value="<?=$http_password?>" /><span id="http_passwordErr"></span>
            	<input type="hidden" name="template[http_oldpassword]" value="<?=$http_password?>" />
            </dd>
            <dt class="required"><label for="template[http_comfirm]"><?=T_("Confirm")?>:</label></dt>
            <dd><input type="password" id="template[http_comfirm]" name="template[http_comfirm]" value="<?=$http_password?>" /><span id="http_confirmErr"></span></dd>
          	<dt class="required"><label for="template[http_scheme]"><?=T_("Scheme")?>:</label></dt>
            <dd>
              <input type="radio" name="template[http_scheme]" value="1" <? if(($http_scheme==1)||($http_scheme=="1")) echo "checked=\"checked\"" ?> /><span style="vertical-align:bottom;"><?=T_("Digest")?></span>&nbsp;
              <input type="radio" name="template[http_scheme]" value="0" <? if(($http_scheme!=1)&&($http_scheme!="1")) echo "checked=\"checked\"" ?> /><span style="vertical-align:bottom;"><?=T_("Basic")?></span>
              <input type="hidden" name="template[http_oldscheme]" value="<?=$http_scheme?>" />
            </dd>
          </dl>
        </div>    
        <!-- Login -->
        <h2><?=T_("Options")?></h2>
        <p class="blockintro"><?=T_("Template Options")?></p>
        <div class="block">
        	<h3 style="margin-top:10px;padding-top:0;"><?=T_("Login")?></h3>
        	<div id="login">
        		<? if($initScript!=""){ ?> 
            	<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
          	<? } ?>
          </div>
          <br/><hr/>
          <!-- SIP -->
          <h3><?=T_("SIP")?></h3>
          <div id="sip">
          	<? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
          <br/><hr/>
          <!-- NAT -->
          <h3><?=T_("NAT")?></h3>
          <div id="nat">
          	<? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
          <br/><hr/>
          <!-- RTP -->
          <h3><?=T_("RTP")?></h3>
          <div id="rtp">
          	<? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
          <br/><hr/>
          <!-- Options -->
          <h3><?=T_("Advanced")?></h3>
          <div id="options">
            <? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
        </div>   
        <!-- Programmable Keys -->
        <h2><?=T_("Programmable Keys")?></h2>
        <p class="blockintro"><?=T_("Settings for programmable keys on snom phone")?></p>
        <div class="block">
        	<!-- Preprogrammed Keys -->
        	<h3 style="margin-top:10px;padding-top:0;"><?=T_("Preprogrammed Keys")?></h3>
        	<div id="dkey">
            <? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
          <br/><hr/>
          <!-- Function Keys -->
          <h3><?=T_("Function Keys")?></h3>
          <div id="fkey">
            <? if($initScript!=""){ ?> 
              <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
            <? } ?>
          </div>
        </div>    
        <!-- Buttons -->
        <div class="action">
          <?if ($_GET["id"]!="") {?> <input type="hidden" id="template[id]" name="template[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=" 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 checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
        -->
        </div>
      </form>
    </div>
    <script>
      function putLoading(){
      	document.getElementById('login').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('sip').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('nat').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('rtp').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('options').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('firmwareLoading').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        document.getElementById('fkey').innerHTML='<img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>';
        return true;
      }
      function changeStatus(name){
        statusObj=document.getElementById('status_'+name);
        //item is on -> turn off
        if(statusObj.value==1){
          statusObj.value=0;
          document.getElementById('a_'+name).innerHTML='<img src="<?=$relBasePath?>public/img/checkbox.gif\" />';
          document.getElementById('a_'+name).className='ON';
          document.getElementById('label_'+name).className='commented';
          document.getElementById('on_'+name).className='hide';
          document.getElementById('off_'+name).className='show';
        }
        //item is off -> turn on
        else{
          statusObj.value=1;
          document.getElementById('a_'+name).innerHTML='<img src="<?=$relBasePath?>public/img/checkbox_ok.gif\" />';
          document.getElementById('a_'+name).className='OFF';
          document.getElementById('label_'+name).className='required';
          document.getElementById('on_'+name).className='show';
          document.getElementById('off_'+name).className='hide';
        }
      }
      function show_hide(id){
      	var obj=document.getElementById(id);
        if(obj.style.display=='none') obj.style.display='block';
        else obj.style.display='none';
      }
      function showhideAddress(value){
        if(value==1){
          document.getElementById('template[netmask]').value='<?=$netmask?>';document.getElementById('template[netmask]').disabled='disabled';
          document.getElementById('template[gateway]').value='<?=$gateway?>';document.getElementById('template[gateway]').disabled='disabled';
          document.getElementById('template[domain]').value='<?=$domain?>';document.getElementById('template[domain]').disabled='disabled';
          document.getElementById('template[dns2]').value='<?=$dns2?>';document.getElementById('template[dns2]').disabled='disabled';
          document.getElementById('template[dns1]').value='<?=$dns1?>';document.getElementById('template[dns1]').disabled='disabled';
        }else{
          document.getElementById('template[netmask]').value='<?=$netmask?>';document.getElementById('template[netmask]').disabled='';
          document.getElementById('template[gateway]').value='<?=$gateway?>';document.getElementById('template[gateway]').disabled='';
          document.getElementById('template[domain]').value='<?=$domain?>';document.getElementById('template[domain]').disabled='';
          document.getElementById('template[dns2]').value='<?=$dns2?>';document.getElementById('template[dns2]').disabled='';
          document.getElementById('template[dns1]').value='<?=$dns1?>';document.getElementById('template[dns1]').disabled='';
        }
      }
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="provisioning";include("../../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new configuration template or to modify an existing one. To create a new template you have to define the name, the phone type, the server ip address and to press save button on the end of the page. It's possibole to link a firmware version and a directory to a template. Moreover it's possible to define other parameters like the network configurations, the phone settings, the function keys, etc...")?></p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

