<?
/**
 * 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,$cwUserInfo,$cwUserId;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");

  //================ XAJAX ================
  function _contactToString($name,$surname,$company,$order_by){
    if($order_by=="name"){
    	if(trim($company)!="") $ret=$name." ".$surname." (".$company.")";
      else $ret=$name." ".$surname;
    }else if($order_by=="company"){
    	if((trim($surname)!="")||(trim($name)!="")) $ret=$company." (".$surname." ".$name.")";
      else $ret=$company;
    }else{
    	if(trim($company)!="") $ret=$surname." ".$name." (".$company.")";
      else $ret=$surname." ".$name;
    }
    return $ret;
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath,$cwUserInfo,$cwUserId;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $contact=$formData["contact"];
    $id=$contact["id"];
    $name=$contact["name"];
    $surname=$contact["surname"];
    $company=$contact["company"];
    $order_by=$contact["order_by"];
    $cid_name=$contact["cid_name"];
    $phonenumber=$contact["phonenumber"];
    $mobile=$contact["mobile"];
    $fax=$contact["fax"];
    $phonenumber_speed_id=$contact["phonenumber_speed_id"];
    $phonenumber_speed_ext=trim($contact["phonenumber_speed_ext"]);
    $mobile_speed_id=$contact["mobile_speed_id"];
    $mobile_speed_ext=trim($contact["mobile_speed_ext"]);
    $fax_speed_id=$contact["fax_speed_id"];
    $fax_speed_ext=trim($contact["fax_speed_ext"]);
    $phonenumber_on_cid=$contact["phonenumber_on_cid"];
    $mobile_on_cid=$contact["mobile_on_cid"];
    $fax_on_cid=$contact["fax_on_cid"];
    $read=$contact["read"];
    $write=$contact["write"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Check name and order
    $nameErr=false;
    if((trim($name)=="")&&(trim($surname)=="")&&(trim($company)=="")){
      $errOut[]=T_("At least one between name, surname and company must not be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $objResponse->addAssign("surnameErr","innerHTML",$imgErr);
      $objResponse->addAssign("companyErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if(($order_by=="name")&&(trim($name)=="")){
    	$errOut[]=T_("Order filed can not be empty");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if(($order_by=="surname")&&(trim($surname)=="")){
    	$errOut[]=T_("Order filed can not be empty");
      $objResponse->addAssign("surnameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if(($order_by=="company")&&(trim($company)=="")){
    	$errOut[]=T_("Order filed can not be empty");
      $objResponse->addAssign("companyErr","innerHTML",$imgErr);
      $nameErr=true;
    }else{
      $ret=$asterisk->getContactIdFromCidName(_contactToString($name,$surname,$company,$order_by),$cwUserId);
      if(!is_array($ret)) $ret=array();
      if(($id!='')&&(in_array($id,$ret))) unset($ret[array_search($id,$ret)]);
      if(count($ret)>0){
        $errOut[]=T_("A contact width same cid name already exists. Please change contact description.");
        $objResponse->addAssign("nameErr","innerHTML",$imgErr);
        $objResponse->addAssign("surnameErr","innerHTML",$imgErr);
        $objResponse->addAssign("companyErr","innerHTML",$imgErr);
        $nameErr=true;
      }
    }
    if($nameErr===false){
      $objResponse->addAssign("nameErr","innerHTML","");
      $objResponse->addAssign("surnameErr","innerHTML","");
      $objResponse->addAssign("companyErr","innerHTML","");
    }
    //Check speeddial limit
    $new_speed=0;
    $phonenumberspeedErr=false;
    $mobilespeedErr=false;
    $faxspeedErr=false;
    $phonenumber_speed_id=$contact["phonenumber_speed_id"];
    $phonenumber_speed_ext=trim($contact["phonenumber_speed_ext"]);
    $mobile_speed_id=$contact["mobile_speed_id"];
    $mobile_speed_ext=trim($contact["mobile_speed_ext"]);
    $fax_speed_id=$contact["fax_speed_id"];
    $fax_speed_ext=trim($contact["fax_speed_ext"]);
    if((trim($phonenumber_speed_ext)!='')&&($phonenumber_speed_id<=0)) $new_speed++;
    if((trim($mobile_speed_ext)!='')&&($mobile_speed_id<=0)) $new_speed++;
    if((trim($fax_speed_ext)!='')&&($fax_speed_id<=0)) $new_speed++;
    if($new_speed>0){
      $speed_less=$asterisk->speedDialMaxExceed();
      if($speed_less<$new_speed){
        if($speed_less==0) $err_msg=T_("Speed dial limit exceeted. No speed dials left.");
        else if($speed_less==1) $err_msg=T_("Speed dial limit exceeted. Only one speed dial left.");
        else if($speed_less==2) $err_msg=T_("Speed dial limit exceeted. Only two speed dials left.");
        switch ($speed_less-$new_speed){
          case -1:
              $errOut[]=$err_msg;
              if((trim($fax_speed_ext)!='')&&($fax_speed_id<=0)){
                $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
                $faxspeedErr=true;
              }else if((trim($mobile_speed_ext)!='')&&($mobile_speed_id<=0)){
                $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
                $mobilespeedErr=true;
              }else{
                $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
                $phonenumberspeedErr=true;
              }
              break;
          case -2:
              $errOut[]=$err_msg;
              $assigned=0;
              if((trim($fax_speed_ext)!='')&&($fax_speed_id<=0)){
                $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
                $faxspeedErr=true;
                $assigned++;
              }
              if((trim($mobile_speed_ext)!='')&&($mobile_speed_id<=0)){
                $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
                $mobilespeedErr=true;
                $assigned++;
              }
              if($assigned<2){
                $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
                $phonenumberspeedErr=true;
              }
              break;
          case -3:
          default:
              $errOut[]=$err_msg;
              $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
              $faxspeedErr=true;
              $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
              $mobilespeedErr=true;
              $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
              $phonenumberspeedErr=true;
              break;
        }
      }
    }
    // Check phonenumber ((null)||(numeric))
    $phonenumberErr=false;
    if($phonenumber!=""){
      //phonenumber must be numeric
      for($i=0;$i<strlen($phonenumber);$i++){
        $ch=ord($phonenumber[$i]);
        if(!((($ch>47)&&($ch<58)))){
          if(($i==0)&&($ch==43)) continue;
          $errOut[]=T_("Contact phonenumber allow only numeric characters. Please change it");
          $objResponse->addAssign("phonenumberErr","innerHTML",$imgErr);
          $phonenumberErr=true;
          break;
        }
      }
    }
    if($phonenumberErr===false) $objResponse->addAssign("phonenumberErr","innerHTML","");
    // Check Phonenumber Speed (null)||(unique)
    if($phonenumberspeedErr===false){
      if($phonenumber_speed_ext!=""){
      	//speed dial must be null if mobile number is null
      	if($phonenumber==""){
        	$errOut[]=T_("Phonenumber's speed dial must be linked to a phonenumber");
          $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
          $phonenumberspeedErr=true;
      	}
        //speeddial must be unique
        else{
          $ret=$asterisk->getExtension(0);
          if(is_array($ret)){
            foreach($ret as $e) {
            	if($phonenumber_speed_id==$e["entity_id"]) continue;
              if($phonenumber_speed_ext==$e["extension"]){
                $errOut[]=T_("Phonenumber's speed dial already exists. Please change it");
                $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
                $phonenumberspeedErr=true;
              }
            }
          }
        }
      }
    }
    if($phonenumberspeedErr===false) $objResponse->addAssign("phonenumberspeedErr","innerHTML","");
    // Check Phonenumber CID setting
    $phonenumberoncidErr=false;
    if(($phonenumberoncidErr==1)||($phonenumberoncidErr=="1")){
    	//If another contact is linked to this phonenumber and it has cid stting ON, print overwrite alert
    	if($phonenumber==""){
      	$errOut[]=T_("Phonenumber's speed dial must be linked to a phonenumber");
        $objResponse->addAssign("phonenumberoncidErr","innerHTML",$imgErr);
        $phonenumberoncidErr=true;
    	}
    }
    if($phonenumberoncidErr===false) $objResponse->addAssign("phonenumberoncidErr","innerHTML","");
    // Check mobile ((null)||(numeric))
    $mobileErr=false;
    if($mobile!=""){
      //mobile must be numeric
      for($i=0; $i<strlen($mobile); $i++){
        $ch=ord($mobile[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]=T_("Contact mobile number allow only numeric characters. Please change it");
          $objResponse->addAssign("mobileErr","innerHTML",$imgErr);
          $mobileErr=true;
          break;
        }
      }
    }
    if($mobileErr===false) $objResponse->addAssign("mobileErr","innerHTML","");
    // Check Mobile Speed (null)||((unique)&&(-neq Phonenumbers speedDial))
    if($mobilespeedErr===false){
      if($mobile_speed_ext!=""){
      	//speed dial must be null if mobile number is null
      	if($mobile==""){
        	$errOut[]=T_("Mobile's speed dial must be linked to a mobile number");
          $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
          $mobilespeedErr=true;
      	}
        //mobile's speed dial must be not equal to phonenumber's one
        else if($mobile_speed_ext==$phonenumber_speed_ext){
       		$errOut[]=T_("Speed dial must be unique. Please change it");
          $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
          $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
          $mobilespeedErr=true;
        }
        //speeddial must be unique
        else{
          $ret=$asterisk->getExtension(0);
          if(is_array($ret)){
            foreach($ret as $e) {
            	if($mobile_speed_id==$e["entity_id"]) continue;
              if($mobile_speed_ext==$e["extension"]){
                $errOut[]=T_("Mobile's speed dial already exists. Please change it");
                $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
                $mobilespeedErr=true;
              }
            }
          }
        }
      }
    }
    if($mobilespeedErr===false) $objResponse->addAssign("mobilespeedErr","innerHTML","");
    // Check fax ((null)||(numeric))
    $faxErr=false;
    if($fax!=""){
      //mobile must be numeric
      for($i=0; $i<strlen($fax); $i++){
        $ch=ord($fax[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]=T_("Contact fax number allow only numeric characters. Please change it");
          $objResponse->addAssign("faxErr","innerHTML",$imgErr);
          $faxErr=true;
          break;
        }
      }
    }
    if($faxErr===false) $objResponse->addAssign("faxErr","innerHTML","");
    // Check Fax Speed (null)||((unique)&&(-neq Phonenumbers speedDial)&&(-neq Mobile speedDial))
    if($faxspeedErr===false){
      if($fax_speed_ext!=""){
      	//speed dial must be null if fax number is null
      	if($fax==""){
        	$errOut[]=T_("Fax's speed dial must be linked to a fax number");
          $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
          $faxspeedErr=true;
      	}
        //fax's speed dial must be not equal to phonenumber's one
        else if($fax_speed_ext==$phonenumber_speed_ext){
       		$errOut[]=T_("Speed dial must be unique. Please change it");
          $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
          $objResponse->addAssign("phonenumberspeedErr","innerHTML",$imgErr);
          $faxspeedErr=true;
        }
        //fax's speed dial must be not equal to mobile's one
        else if($fax_speed_ext==$mobile_speed_ext){
       		$errOut[]=T_("Speed dial must be unique. Please change it");
          $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
          $objResponse->addAssign("mobilespeedErr","innerHTML",$imgErr);
          $faxspeedErr=true;
        }
        //speeddial must be unique
        else{
          $ret=$asterisk->getExtension(0);
          if(is_array($ret)){
            foreach($ret as $e) {
            	if($mobile_speed_id==$e["entity_id"]) continue;
              if($mobile_speed_ext==$e["extension"]){
                $errOut[]=T_("Fax's speed dial already exists. Please change it");
                $objResponse->addAssign("faxspeedErr","innerHTML",$imgErr);
                $faxspeedErr=true;
              }
            }
          }
        }
      }
    }
    if($faxspeedErr===false) $objResponse->addAssign("faxspeedErr","innerHTML","");
    // Check cid settings
    $pcidErr=false;
    $mcidErr=false;
    $fcidErr=false;
    if($read!=1){
    	if(($phonenumber_on_cid==1)||($mobile_on_cid==1)||($fax_on_cid==1)){
      	$errOut[]=T_("CID settings are possible only for public contacts. Please check read permission");
      	if($phonenumber_on_cid==1){
        	$objResponse->addAssign("pcidErr","innerHTML",$imgErr);
          $pcidErr=true;
        }
      	if($mobile_on_cid==1){
        	$objResponse->addAssign("mcidErr","innerHTML",$imgErr);
          $mcidErr=true;
      	}
        if($fax_on_cid==1){
        	$objResponse->addAssign("fcidErr","innerHTML",$imgErr);
          $fcidErr=true;
      	}
      }
    }
    //check phonenumber
    $pcheck_script="";
    if(($phonenumber_on_cid==1)&&($pcidErr===false)){
      $number=$phonenumber;
      $ret=$asterisk->getContactsFromNumber($number);
      if(is_array($ret)){
    		foreach($ret as $c){
        	if($c["id"]==$id) continue;
        	if((($c["phonenumber"]==$number)&&($c["phonenumber_on_cid"]==1)) ||
             (($c["mobile"]==$number)&&($c["mobile_on_cid"]==1))           ||
             (($c["fax"]==$number)&&($c["fax_on_cid"]==1))                 ){
            $name=_contactToString($c["name"],$c["surname"],$c["company"],$c["order_by"]);
            if(($cwUserInfo["type"]!=USER_STANDARD)||($c["id_user"]==$cwUserId)||($c["write"]==1)){
              $pcheck_script=sprintf(T_("You have selected to show contact's description as CID name for any incoming call which match number %1\$s. This number has been already assigned to %2\$s "),$number, $name).".";
            }else{
            	$errOut[]=T_("Phonenumber has been already linked to another contact. Contact system admin to change the setting");
            	$objResponse->addAssign("pcidErr","innerHTML",$imgErr);
          		$pcidErr=true;
            }
            break;
          }
        }
      }
    }
    //check mobile
    $mcheck_script="";
    if(($mobile_on_cid==1)&&($mcidErr===false)){
      $number=$mobile;
    	$ret=$asterisk->getContactsFromNumber($number);
      if(is_array($ret)){
    		foreach($ret as $c){
        	if($c["id"]==$id) continue;
        	if((($c["phonenumber"]==$number)&&($c["phonenumber_on_cid"]==1)) ||
             (($c["mobile"]==$number)&&($c["mobile_on_cid"]==1))           ||
             (($c["fax"]==$number)&&($c["fax_on_cid"]==1))                 ){
          	$name=_contactToString($c["name"],$c["surname"],$c["company"],$c["order_by"]);
         		if(($cwUserInfo["type"]!=USER_STANDARD)||($c["id_user"]==$cwUserId)||($c["write"]==1)){
              $mcheck_script=sprintf(T_("You have selected to show contact's description as CID name for any incoming call which match mobile number %1\$s. This number has been already assigned to %2\$s"),$number ,$name).".";
            }else{
            	$errOut[]=T_("Mobile number has been already linked to another contact. Contact system admin to change the setting");
            	$objResponse->addAssign("mcidErr","innerHTML",$imgErr);
          		$mcidErr=true;
            }
            break;
          }
        }
      }
    }
    //check fax
    $fcheck_script="";
    if(($fax_on_cid==1)&&($fcidErr===false)){
      $number=$fax;
    	$ret=$asterisk->getContactsFromNumber($number);
      if(is_array($ret)){
    		foreach($ret as $c){
        	if($c["id"]==$id) continue;
        	if((($c["phonenumber"]==$number)&&($c["phonenumber_on_cid"]==1)) ||
             (($c["mobile"]==$number)&&($c["mobile_on_cid"]==1))           ||
             (($c["fax"]==$number)&&($c["fax_on_cid"]==1))                 ){
          	$name=_contactToString($c["name"],$c["surname"],$c["company"],$c["order_by"]);
         		if(($cwUserInfo["type"]!=USER_STANDARD)||($c["id_user"]==$cwUserId)||($c["write"]==1)){
              $fcheck_script=sprintf(T_("You have selected to show contact's description as CID name for any incoming call which match fax number %1\$s. This number has been already assigned to %2\$s"),$number ,$name).".";
            }else{
            	$errOut[]=T_("Fax number has been already linked to another contact. Contact system admin to change the setting");
            	$objResponse->addAssign("fcidErr","innerHTML",$imgErr);
          		$fcidErr=true;
            }
            break;
          }
        }
      }
    }
    if($pcidErr===false) $objResponse->addAssign("pcidErr","innerHTML","");
    if($mcidErr===false) $objResponse->addAssign("mcidErr","innerHTML","");
    if($fcidErr===false) $objResponse->addAssign("fcidErr","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(($pcheck_script!="")||($mcheck_script!="")||($fcheck_script!="")){
      	$script="";
      	if(trim($pcheck_script)!="") $script.=addslashes($pcheck_script)."\\n\\n";
        if(trim($mcheck_script)!="") $script.=addslashes($mcheck_script)."\\n\\n";
        if(trim($fcheck_script)!="") $script.=addslashes($fcheck_script)."\\n\\n";
      	$script=" if(confirm('".$script.T_("If you continue the new settings will overwrite the old ones. Do you want to continue?")."')) 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("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $contact=$_POST["contact"];
    if(is_array($contact["group"])) $groups=implode("|",$contact["group"]); else $groups="";
    if($contact["write"]==1) $contact["read"]=1;
    $entry=Array(
          "id" => $contact["id"],
          "id_user" => $contact["id_user"],
          "name" => $contact["name"],
          "surname" => $contact["surname"],
          "company" => $contact["company"],
          "phonenumber" => $contact["phonenumber"],
          "mobile" => $contact["mobile"],
          "fax" => $contact["fax"],
          "email" => $contact["email"],
          "read" => $contact["read"],
          "write" => $contact["write"],
          "phonenumber_speed_id" => $contact["phonenumber_speed_id"],
          "phonenumber_speed_ext" => $contact["phonenumber_speed_ext"],
          "mobile_speed_id" => $contact["mobile_speed_id"],
          "mobile_speed_ext" => $contact["mobile_speed_ext"],
          "fax_speed_id" => $contact["fax_speed_id"],
          "fax_speed_ext" => $contact["fax_speed_ext"],
          "phonenumber_on_cid" => $contact["phonenumber_on_cid"],
          "mobile_on_cid" => $contact["mobile_on_cid"],
          "fax_on_cid" => $contact["fax_on_cid"],
          "order_by" => $contact["order_by"],
          "cid_name" => $contact["cid_name"],
          "groups" => $groups,
          "key" => $contact["key"],
          "email" => $contact["email"]
        );
    //put Contact
    $ret=$asterisk->putContact($entry,$cwUserId);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Contact has been successfully created")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Contact has NOT been created")."</div>";
	  //go to main page
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  if(isset($_GET["id"]) and $_GET["id"]!=""){
    $ret=$asterisk->getContact($_GET["id"],0,0);
    if(!is_array($ret)) die;
    $c=$ret[0];
    $id=$c["id"];
    $id_user=$c["id_user"];
    $read=$c["read"];
    $write=$c["write"];
    $name=$c["name"];
    $surname=$c["surname"];
    $company=$c["company"];
    $order_by=trim($c["order_by"]);
    $cid_name=$c["cid_name"];
    $phonenumber=$c["phonenumber"];
    $mobile=$c["mobile"];
    $fax=$c["fax"];
    $phonenumber_on_cid=$c["phonenumber_on_cid"];
    $mobile_on_cid=$c["mobile_on_cid"];
    $fax_on_cid=$c["fax_on_cid"];
    $phonenumber_speed_id=$c["phonenumber_speed_id"];
    $phonenumber_speed_ext=$c["phonenumber_speed_ext"];
    $mobile_speed_id=$c["mobile_speed_id"];
    $mobile_speed_ext=$c["mobile_speed_ext"];
    $fax_speed_id=$c["fax_speed_id"];
    $fax_speed_ext=$c["fax_speed_ext"];
    $groups=$c["groups"];
    $key=$c["key"];
    $email=$c["email"];
    //label
    if((trim($surname)!="")||(trim($name)!="")) $namesurname.=trim($surname." ".$name);
    else $namesurname.=trim($company);
    //logic
    if(($read!=1)&&($cwUserId!=$id_user)&&($cwUserInfo["type"]==USER_STANDARD)) die();
    if(($write!=1)&&($cwUserId!=$id_user)&&($cwUserInfo["type"]==USER_STANDARD)) $disabled="disabled=\"disabled\""; else $disabled="";
    if(($cwUserId!=$id_user)&&($cwUserInfo["type"]==USER_STANDARD)) $dis_sharing="disabled=\"disabled\""; else $dis_sharing="";
    //title
    $title=sprintf(T_("Modify Contact &lt;%s&gt;"),$namesurname );
  }else{
    $id_user=$cwUserId;
    $read=1;
    $write=1;
	  //title
    $title=T_("New Contact");
  }
  //Get groups
  $icon_group="<img src=\"$relBasePath/public/img/icon_group.gif\" alt=\"Group of Contacts\" />";
  //$groups=$asterisk->getContactGroup(0,$cwUserId);
  if(is_array($groups)){
    $count=0;
    $html_group="<table cellpadding=\"0\" cellspacing=\"0\"><tr>";
    foreach($groups as $group){
      if((is_array($group["entity"]))&&(in_array($_GET["id"],$group["entity"]))) $checked="checked=\"checked\""; else $checked="";
      $html_group.="<td width=\"33%\"><input type=\"checkbox\" name=\"contact[group][]\" value=\"".$group["id"]."\" $checked/> $icon_group ".$group["name"]."</td>";
      if((++$count)%3==0) $html_group.="</tr><tr>\n";
    }
    if(($count!=0)&&(($count%3)!=0)) $html_group.="<td colspan=\"".($count%3)."\">&nbsp;</td>\n";
    $html_group.="</tr></table>";
  }

  //================ 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_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
    	<!-- General Info -->
      <h2><?=T_("General Informations")?></h2>
      <p class="blockintro"><?=T_("Contact's general informations")?></p>
      <div class="block">
        <input type="hidden" id="contact[cid_name]" name="contact[cid_name]" value="<?=$cid_name?>"/>
        <input type="hidden" id="contact[key]" name="contact[key]" value="<?=$key?>"/>
        <input type="hidden" id="contact[email]" name="contact[email]" value="<?=$email?>"/>
        <dl>
        	<dt class="required"><label for="contact[surname]"><?=T_("Surname")?>:</label></dt>
          <dd>
          	<input type="text" size="25" maxlength="255" id="contact[surname]" name="contact[surname]" value="<?=$surname?>" onkeyup="if((document.getElementById('contact[name]').value=='')&&(document.getElementById('contact[company]').value=='')) document.getElementById('order_surname').checked=true;" <?=$disabled?>/>&nbsp;
            <input type="radio" id="order_surname" name="contact[order_by]" value="surname" <? if($order_by=="surname") echo "checked=\"checked\""; ?> <?=$disabled?> />&nbsp;<?=T_("order by Surname")?>
            <span id="surnameErr"></span>
          </dd>
          <dt class="required"><label for="contact[name]"><?=T_("Name")?>:</label></dt>
          <dd>
          	<input type="text" size="25" maxlength="255" id="contact[name]" name="contact[name]" value="<?=$name?>" onkeyup="if((document.getElementById('contact[company]').value=='')&&(document.getElementById('contact[surname]').value=='')) document.getElementById('order_name').checked=true;" <?=$disabled?>/>&nbsp;
            <input type="radio" id="order_name" name="contact[order_by]" value="name" <? if($order_by=="name") echo "checked=\"checked\""; ?> <?=$disabled?> />&nbsp;<?=T_("order by Name")?>
            <span id="nameErr"></span>
          </dd>
          <dt class="required"><label for="contact[company]"><?=T_("Company")?>:</label></dt>
          <dd>
          	<input type="text" size="25" maxlength="255" id="contact[company]" name="contact[company]" value="<?=$company?>" onkeyup="if((document.getElementById('contact[name]').value=='')&&(document.getElementById('contact[surname]').value=='')) document.getElementById('order_company').checked=true;" <?=$disabled?> />&nbsp;
            <input type="radio" id="order_company" name="contact[order_by]" value="company" <? if($order_by=="company") echo "checked=\"checked\""; ?> <?=$disabled?> />&nbsp;<?=T_("order by Company")?>
            <span id="companyErr"></span>
          </dd>
          <!--
          <dt class="required"><label for="contact[email]"><?=T_("Email")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="255" id="contact[email]" name="contact[email]" value="<?=$email?>" <?=$disabled?>/><span id="emailErr"></span></dd>
          -->
          <? if($dis_sharing==""){ ?>
            <dt class="required"><label for="contact[read]"><?=T_("Sharing")?>:</label></dt>
            <dd><input type="checkbox" id="contact[read]" name="contact[read]" value="1" <?if ($read==1) echo "checked=\"checked\"" ?> <?=$dis_sharing?> />&nbsp;&nbsp;<span><?=T_("Allow users to see this contact")?></span></dd>
            <dt class="required"><label for="contact[write]"></label></dt>
            <dd><input type="checkbox" id="contact[write]" name="contact[write]" value="1" <?if ($write==1) echo "checked=\"checked\"" ?> <?=$dis_sharing?> />&nbsp;&nbsp;<span><?=T_("Allow users to see and modify this contact")?></span></dd>
          <? } ?>
          <? if($dis_sharing!=""){ ?>
            <input type="hidden" id="contact[read]" name="contact[read]" value="1" <?if ($read==1) echo "checked=\"checked\"" ?> />
            <input type="hidden" id="contact[write]" name="contact[write]" value="1" <?if ($write==1) echo "checked=\"checked\"" ?> />
          <? } ?>
        </dl>
      </div>
      <!-- Phonenumebr -->
      <h2><?=T_("Phonenumber")?></h2>
      <p class="blockintro"><?=T_("Contact's phonenumber")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="contact[phonenumber]"><?=T_("Number")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="255" id="contact[phonenumber]" name="contact[phonenumber]" value="<?=$phonenumber?>" onkeyup="checkPhonenumber(this);" <?=$disabled?>/><span id="phonenumberErr"></span></dd>
          <? if($cwUserInfo["type"]!=USER_STANDARD) {?>
						<dt class="required"><label for="contact[phonenumber_speed_ext]"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="contact[phonenumber_speed_ext]" name="contact[phonenumber_speed_ext]" size="5" value="<?=$phonenumber_speed_ext?>" <?if(trim($phonenumber)=="") echo "disabled=\"disabled\"";?> <?=$disabled?>/> <span id="phonenumberspeedErr"></span></dd>
          <? } ?>
          <? if(($cwUserInfo["type"]==USER_STANDARD)&&($_GET["id"]!="")) {?>
          	<dt class="required"><label for="p_speed_dis"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="p_speed_dis" name="p_speed_dis" size="5" value="<?=$phonenumber_speed_ext?>" disabled="disabled" /></dd>
          <? } ?>
          <dt class="required"><label for="contact[phonenumber_cid_name]"><?=T_("CID Setting")?>:</label></dt>
          <dd>
          	<input type="checkbox" id="contact[phonenumber_on_cid]" name="contact[phonenumber_on_cid]" value="1" <?if(trim($phonenumber)=="") echo "disabled=\"disabled\"";?> <? if(($phonenumber_on_cid==1)||($phonenumber_on_cid=="1")) echo "checked=\"cheked\""; echo $disabled ?>/>
            <span id="pcidErr"></span> <span class="help"> <?=T_("Always display contact description when the incoming call matches this phonenumber")?></span>
          </dd>
        </dl>
      </div>
      <!-- Mobile -->
      <h2><?=T_("Mobile")?></h2>
      <p class="blockintro"><?=T_("Contact's mobile number")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="contact[mobile]"><?=T_("Number")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="255" id="contact[mobile]" name="contact[mobile]" value="<?=$mobile?>" onkeyup="checkMobile(this);"<?=$disabled?>/><span id="mobileErr"></span></dd>
          <? if($cwUserInfo["type"]!=USER_STANDARD) {?>
          	<dt class="required"><label for="contact[mobile_speed_ext]"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="contact[mobile_speed_ext]" name="contact[mobile_speed_ext]" size="5" value="<?=$mobile_speed_ext?>" <?if(trim($mobile)=="") echo "disabled=\"disabled\"";?> <?=$disabled?>/> <span id="mobilespeedErr"></span></dd>
          <? } ?>
          <? if(($cwUserInfo["type"]==USER_STANDARD)&&($_GET["id"]!="")) {?>
          	<dt class="required"><label for="m_speed_dis"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="m_speed_dis" name="m_speed_dis" size="5" value="<?=$mobile_speed_ext?>" disabled="disabled" /></dd>
          <? } ?>
          <dt class="required"><label for="contact[mobile_on_cid]"><?=T_("CID Setting")?>:</label></dt>
          <dd>
          	<input type="checkbox" id="contact[mobile_on_cid]" name="contact[mobile_on_cid]" value="1" <?if(trim($mobile)=="") echo "disabled=\"disabled\"";?> <? if(($mobile_on_cid==1)||($mobile_on_cid=="1")) echo "checked=\"cheked\""; echo $disabled ?>/>
            <span id="mcidErr"></span> <span class="help"> <?=T_("Always display contact description when the incoming call matches this mobile number")?></span>
          </dd>
        </dl>
      </div>
      <!-- Fax -->
      <h2><?=T_("Fax")?></h2>
      <p class="blockintro"><?=T_("Contact's fax number")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="contact[fax]"><?=T_("Number")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="255" id="contact[fax]" name="contact[fax]" value="<?=$fax?>" onkeyup="checkFax(this);"<?=$disabled?>/><span id="faxErr"></span></dd>
          <? if($cwUserInfo["type"]!=USER_STANDARD) {?>
          	<dt class="required"><label for="contact[fax_speed_ext]"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="contact[fax_speed_ext]" name="contact[fax_speed_ext]" size="5" value="<?=$fax_speed_ext?>" <?if(trim($fax)=="") echo "disabled=\"disabled\"";?> <?=$disabled?>/> <span id="faxspeedErr"></span></dd>
          <? } ?>
          <? if(($cwUserInfo["type"]==USER_STANDARD)&&($_GET["id"]!="")) {?>
          	<dt class="required"><label for="f_speed_dis"><?=T_("Speed Dial")?>:</label></dt>
          	<dd><input type="text" id="f_speed_dis" name="f_speed_dis" size="5" value="<?=$fax_speed_ext?>" disabled="disabled" /></dd>
          <? } ?>
          <dt class="required"><label for="contact[fax_on_cid]"><?=T_("CID Setting")?>:</label></dt>
          <dd>
          	<input type="checkbox" id="contact[fax_on_cid]" name="contact[fax_on_cid]" value="1" <?if(trim($fax)=="") echo "disabled=\"disabled\"";?> <? if(($fax_on_cid==1)||($fax_on_cid=="1")) echo "checked=\"cheked\""; echo $disabled ?>/>
            <span id="fcidErr"></span> <span class="help"> <?=T_("Always display contact description when the incoming call matches this mobile number")?></span>
          </dd>
        </dl>
      </div>
      <!-- Groups -->
      <h2><?=T_("Groups")?></h2>
      <p class="blockintro"><?=T_("Add to the following groups")?></p>
      <div class="block">
        <?=$html_group?>
      </div>
      <!-- Buttons -->
      <div class="action">
        <?if ($_GET["id"]!="") {?>
        	<input type="hidden" id="contact[id]" name="contact[id]" value="<?=$id?>" />
          <input type="hidden" id="contact[phonenumber_speed_id]" name="contact[phonenumber_speed_id]" value="<?=$phonenumber_speed_id?>" />
          <input type="hidden" id="contact[mobile_speed_id]" name="contact[mobile_speed_id]" value="<?=$mobile_speed_id?>" />
          <input type="hidden" id="contact[fax_speed_id]" name="contact[fax_speed_id]" value="<?=$fax_speed_id?>" />
        <?}?>
        <input type="hidden" id="contact[id_user]" name="contact[id_user]" value="<?=$id_user?>" />
	      <? if($cwUserInfo["type"]==USER_STANDARD) {?>
          <input type="hidden" id="contact[phonenumber_speed_ext]" name="contact[phonenumber_speed_ext]" value="<?=$phonenumber_speed_ext?>"/>
          <input type="hidden" id="contact[mobile_speed_ext]" name="contact[mobile_speed_ext]" value="<?=$mobile_speed_ext?>"/>
          <input type="hidden" id="contact[fax_speed_ext]" name="contact[fax_speed_ext]" value="<?=$fax_speed_ext?>"/>
        <? } ?>
        <a href=""><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="history.back(); return false;"/></a>
        <?if($disabled==""){ ?>
        	<a href=""><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); return false;"/></a>
        <? } ?>
      </div>
    </form>
  </div>

  <script>
  	function checkPhonenumber(obj){
  		if(obj.value.length==0){
      	document.getElementById('contact[phonenumber_speed_ext]').disabled=true;
        document.getElementById('contact[phonenumber_speed_ext]').value='';
        document.getElementById('contact[phonenumber_on_cid]').disabled=true;
        document.getElementById('contact[phonenumber_on_cid]').checked=false;
      }else{
      	document.getElementById('contact[phonenumber_speed_ext]').disabled=false;
        if(document.getElementById('contact[phonenumber_speed_ext]').value==''){
        	document.getElementById('contact[phonenumber_speed_ext]').value='<?=$phonenumber_speed_ext?>';
        }
        document.getElementById('contact[phonenumber_on_cid]').disabled=false;
        if(obj.value=='<?=$phonenumber?>'){
        	document.getElementById('contact[phonenumber_on_cid]').checked=true;
        }
      }
    }
    function checkMobile(obj){
  		if(obj.value.length==0){
      	document.getElementById('contact[mobile_speed_ext]').disabled=true;
        document.getElementById('contact[mobile_speed_ext]').value='';
        document.getElementById('contact[mobile_on_cid]').disabled=true;
        document.getElementById('contact[mobile_on_cid]').checked=false;
      }else{
      	document.getElementById('contact[mobile_speed_ext]').disabled=false;
        if(document.getElementById('contact[mobile_speed_ext]').value==''){
        	document.getElementById('contact[mobile_speed_ext]').value='<?=$mobile_speed_ext?>';
        }
        document.getElementById('contact[mobile_on_cid]').disabled=false;
        if(obj.value=='<?=$mobile?>'){
        	document.getElementById('contact[mobile_on_cid]').checked=true;
        }
      }
    }
    function checkFax(obj){
  		if(obj.value.length==0){
      	document.getElementById('contact[fax_speed_ext]').disabled=true;
        document.getElementById('contact[fax_speed_ext]').value='';
        document.getElementById('contact[fax_on_cid]').disabled=true;
        document.getElementById('contact[fax_on_cid]').checked=false;
      }else{
      	document.getElementById('contact[fax_speed_ext]').disabled=false;
        if(document.getElementById('contact[fax_speed_ext]').value==''){
        	document.getElementById('contact[fax_speed_ext]').value='<?=$fax_speed_ext?>';
        }
        document.getElementById('contact[fax_on_cid]').disabled=false;
        if(obj.value=='<?=$fax?>'){
        	document.getElementById('contact[fax_on_cid]').checked=true;
        }
      }
    }
  </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="list";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new contact or to modify an existing one. To create a new contact you have to define the name, the numbers and to press save button on the end of the page. Moreover it's possible to define other parameters like the order field, the sharing options, etc...")?></p>
      <div style="text-align: center"><img src="<?=$relBasePath?>public/img/book.jpg" align="center"/></div>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "contacts");
  $smarty->assign("subsection", "");
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('main.tpl');
?>

