Page.routing.php for IP08

Hello, (i think you are my jesus ! p_lindheimer)

i’m using an IP08 soho, and in its interface it’s not possible to have more than one fallback trunk (ZAP).

So i’d like to add this possibility to the interface. The problem is that all IP08 use htlm / javascript for the interfaces and are asterisk 1.4 based.

Any help ? thank you in advance !

i’ll put you here under the code used in the file numberplan.html (responsible to generate the context):

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
<!--
 * IP PBX-GUI	-	for IPPBX configuration interface which is secondarily developed
 * by ZYCOO IT.,Co based on Asterisk-GUI which copyright 2006-2007,Digium,Inc.
 * Asterisk-GUI is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 * www.zycoo.com
 * [email protected]

-->
<script src="scripts/prototype.js"></script>
<script src="scripts/astman.js"></script>
<script src="scripts/tooltip.js"></script>
<link href="stylesheets/schwing.css" media="all" rel="Stylesheet" type="text/css" />
<script>
var widgets = { } ;
var trunkcallbacks = { };
var trunks_desc = { };
var numplan_callbacks = { };
var numberplansdata = { };
var fieldnames = ['cancel', 'deleted', 'include', 'name', 'new', 'plancomment', 'save'];

//var default_numberplan = 0;
var isnewrule ;
var iscustom ;
var pattern_beingedited ;
var pattern_beingedited_priority ;
var np_oldselect;

function basicpattern(){
	iscustom = false;
	_$('define_advanced').style.display="none";
	_$('define_usual').style.display="";
}


function ownpattern(){
	iscustom = true;
	_$('define_advanced').style.display="";
	_$('define_usual').style.display="none";
}

function enablesave(){
	_$('save_a').disabled = 0;
	return true;
}

function add_callingrule(){
	isnewrule = true;
	iscustom = false;
	_$('authck').checked = false;
	_$('dialpasswd').value = "";
	_$('dialpasswordtab').style.display = "none";
	_$('rulename').value = "";
	_$('trunks').selectedIndex = -1 ;
	_$('fallback').selectedIndex = 0 ;
	_$('pattern').value = "";
	_$('prepend').value = "";
	_$('strip').value = "0" ;
	_$('save_a').disabled = 1;
	_$('define_advanced').style.display="none";
	_$('define_usual').style.display="";
	_$('userscontent').style.display="";
	_$('bg_transparent').style.display ='';
	_$('addrule').disabled =1;
	_$('beginswith').value = "";
	_$('followedby').value ="";
	_$('ormore').checked = false;
}

function checkfields(){
	if( _$('rulename').value.length == 0 ){
		gui_alert("Please enter a Rule Name");
		_$('rulename').focus();
		return false;
	}

	if( _$('trunks').selectedIndex == -1){
		gui_alert("Please select a service provider to place this call through");
		return false;
	}
	if( _$('authck').checked)
		if( _$('dialpasswd').value.length==0){
		gui_alert("Please Enter the PIN Code!");
		return false;
	}
	
	if( _$('define_advanced').style.display=="none" && _$('beginswith').value.length==0 ){
		gui_alert("Please Enter the beginning pattern of the number");
		_$('beginswith').focus();
		return false;
	}

	if( _$('define_usual').style.display=="none" && _$('pattern').value.length == 0 ){
		gui_alert("Please Enter a custom pattern");
		_$('pattern').focus();
		return false;
	}
return true;
}

function check_if_analog(){
	if( _$('trunks').options[_$('trunks').selectedIndex].text.substr(0,4) == "Port" ){
		_$('fallback').disabled = 1;
		_$('fallback').selectedIndex = 0 ;
	}else{
		_$('fallback').disabled = 0;
	}
}

function buildpatternstring(){
	var pattern = $('beginswith').value;
	// Add an underscore
	pattern = "_" + pattern;
	// append 'followedby' number of X's
 	var s = _$('followedby').value ;
       for (var r=0; r < s ; r++){
               pattern = pattern + "X" ;
       }
	// append a '.' if 'ormore' is checked
	if( _$('ormore').checked ){
		pattern = pattern + "." ;
	}
	// assign this to the field 'pattern'
	_$('pattern').value = pattern;
}

function add_rule_fromeditform( pri, oncomplete ){
	var commentstring = (iscustom )? "custom" :"standard" ;
	var _ptv = _$('pattern').value ;
	var _extv = _$('extensions').value ;
	var _rnv = _$('rulename').value ;
	var _tv = _$('trunks').value ;
	var _fv = _$('fallback').value ;
	var _sv = _$('strip').value ;
	var _pv = _$('prepend').value ;
	var _ac = _$("authck").checked;
	var _dpv = _$("dialpasswd").value;
	var this_priority = (pri * 1) + 1;
	var p = 0;

	var checkgw_string = _ptv + ',' + pri + ",NoOp()" ;
	var uri = build_action('append', p , _extv ,"exten", checkgw_string ); p=p+1;
	if(_ac){
	var dialauth_string = _ptv + ',' + this_priority + ',authenticate(' + _dpv + ')' ;
	uri += build_action('append', p , _extv ,"exten", dialauth_string ); p=p+1;
	this_priority = this_priority + 1;
	}else
		_dpv = "";
	if( _fv != "none")
		var rule_string = _ptv + ',' + this_priority + ',Macro(trunkdial-failover,${' + _tv + '}/'+ _pv +'${EXTEN:' + _sv + '},${' + _fv + '}/'+ _pv +'${EXTEN:' + _sv + '})' ;
	else
		var rule_string = _ptv + ',' + this_priority + ',Macro(trunkdial-failover,${' + _tv + '}/'+ _pv +'${EXTEN:' + _sv + '},)' ;
	uri += build_action('append', p , _extv ,"exten", rule_string ); p=p+1;
	commentstring = _ptv + ',' + this_priority + ',' + _rnv + "," + commentstring ;
	uri += build_action('append', p , _extv ,"comment", commentstring ); p=p+1;

	_$('userscontent').style.display = "none";
	_$('bg_transparent').style.display = "none";
	_$('status_message').style.display = "";

	makerequest('u', 'extensions.conf', uri,
		function(t){
			_$('status_message').style.display="none";
			var m = numberplansdata[_extv]['npdata'];
			if ( typeof m[_ptv] == 'undefined' ) { m[_ptv] = { }; }
			m[_ptv][pri] = ( _fv != "none" ) ? new ruleinanpdata(_tv, _sv, _pv, _dpv, _fv) : new ruleinanpdata(_tv, _sv , _pv, _dpv );
			m[_ptv][pri].rulename =  _rnv ; 
			m[_ptv][pri].ruledesc = (iscustom) ? "custom" : parsepattern(_ptv,0) ;
			oncomplete(); 
		}
	);
}

function saverule(){
	if ( !checkfields() ) return false;
	if( !iscustom){	buildpatternstring();}
	var _extv = _$('extensions').value ;
	var _pv = _$('pattern').value ;

	if(isnewrule){ 
		var newpriority=1;
		var m = numberplansdata[_extv]['npdata'];
		if( m.hasOwnProperty(_pv) && m[_pv].hasOwnProperty(''+newpriority)  ) { 
			gui_alert("A rule for this pattern is already defined !") ; 
			return ;
		}

		var msg = "Dial Rule Added." ;
		add_rule_fromeditform( newpriority, oncomplete = function(){ show_npdata_table(_extv);gui_feedback(msg,'blue'); } );
	 }else{	// update exiting rule
		// delete existing rule
		// add rule with new values
		delete_callingrule(pattern_beingedited,pattern_beingedited_priority, oncomplete = function(){
				var msg = "Dial Rule Updated." ;
				add_rule_fromeditform( pattern_beingedited_priority, oncomplete = function(){show_npdata_table(_extv); gui_feedback(msg,'blue');});
			} 
		);
	 }
}

function parse_nprulesAndnpcomments(){
	// for each element in numberplansdata[t.name]	{
	//			create an object numberplansdata[t.name]['npdata']
	//			parse "numberplansdata[t.name]['nprules']" and add to "numberplansdata[t.name]['npdata']"
	//			parse "numberplansdata[t.name]['npcomments']" and add to "numberplansdata[t.name]['npdata']"
	//	}
	for(x in numberplansdata){ if (numberplansdata.hasOwnProperty(x)) {
		var z = numberplansdata[x];
		var y = z['npdata'];
		var rulepattern = "";
		var trunkname;
		var dialpasswd = "";
		var stripdigits;
		var prepend;
		var fallbacktrunk = "none";
		for ( k =0 ; k < z['nprules'].length ; k++ ){
			var temp = z['nprules'][k].split(","); // temp[0] is the pattern, temp[1] is the priority,temp[2] is 'Macro(trunkdial', temp[3] is ${trunkname}/${EXTEN:1})
			var lastline = ( (k + 1) == z['nprules'].length )? true : false;
		 try {
			if( temp[2].match("authenticate") ){
		// authenticate('') - whatever in the brackets
				var l = temp[2].replace(/authenticate\(/, "");
				dialpasswd = l.replace(/\)/, "");
				rulepattern = temp[0];				
			}else{
				rulepattern = temp[0];
			}
			
			if ( temp[2].substr(0,6) != 'System' && temp[2].substr(0,4) != 'NoOp' && temp[2].substr(0,12) != 'authenticate' ){
				var temp1 = temp[3].split("{");
				var temp1b = temp1[1].split("/");
				var temp1c = temp1b[1].split("$") ;
				var temp2 = temp1[1].split("}");
				var temp3 = temp1[2].split("}");
				var temp4 = temp3[0].split(":");
				if(temp.length > 4){
					if(temp[4] != ")"){
						var temp11 = temp[4].split("{");
						var temp11b = temp11[1].split("/");
						var temp11c = temp11b[1].split("$") ;
						var temp12 = temp11[1].split("}");
						fallbacktrunk = temp12[0];
					}else
						fallbacktrunk = "none";
				}
				trunkname = temp2[0] ; // temp[4] is trunkname
				stripdigits = temp4[1] ; // temp[5] is the #digits to strip in the front
				
				if ( typeof y[temp[0]] == 'undefined' ) {
					y[temp[0]] = { };
				}
				prepend = temp1c[0];
			}
		  }
		  catch(err){}
			var nextline;
			if ( !lastline ){
				nextline = z['nprules'][k+1].split(",");
				if ( rulepattern != "" && nextline[0] != rulepattern ){
					y[rulepattern][1] = ( fallbacktrunk == "none" )? new ruleinanpdata(trunkname, stripdigits, prepend, dialpasswd) : new ruleinanpdata(trunkname, stripdigits, prepend, dialpasswd, fallbacktrunk);
					dialpasswd = "";
				}
				}else{
					y[rulepattern][1] = ( fallbacktrunk == "none" )? new ruleinanpdata(trunkname, stripdigits, prepend, dialpasswd) : new ruleinanpdata(trunkname, stripdigits, prepend, dialpasswd, fallbacktrunk);
			}
		}
		for ( k =0 ; k < z['npcomments'].length ; k++ ){
			var temp = z['npcomments'][k].split(","); 
			if( typeof y[temp[0]] == "undefined"){ continue ; }
			if ( typeof y[temp[0]][1]  == "undefined" ){  continue ; }
			y[temp[0]][1].rulename = temp[2] ;
			y[temp[0]][1].ruledesc = ( temp[3] !="custom" ) ? parsepattern(temp[0],0) : "custom" ;
		}
	}}
}

function show_npdata_table(a){
	// now show m in a table - where m is the npdata of the selected numberplan
	clear_table();
	_$('table_one').style.display="";
	var rules_nosp = new Array ;
	var m = numberplansdata[a]['npdata'];
	var _trunks = _$('trunks') ;

	for( var x in  m ){ if (m.hasOwnProperty(x)) {
		var sorted_priorities = [ ];
		for ( var y in m[x] ){
			if (m[x].hasOwnProperty(y)) { sorted_priorities.push(y); }
		}
		sorted_priorities.sort();
		for( var z=0; z < sorted_priorities.length ; z++ ){
			var trunk_exists = 0;
			for(var i=0; i < _trunks.length ; i++ ){
				if( _trunks.options[i].value == m[x][sorted_priorities[z]].trunk ){
					trunk_exists = 1;
					break;
				}
			}				
			if ( m[x][sorted_priorities[z]].trunk  == "" ){
				rules_nosp.push(m[x][sorted_priorities[z]].rulename) ;
				addrowtotable( x , sorted_priorities[z] , "undefined" , m[x][sorted_priorities[z]].digits2strip );
			}else if(trunk_exists == 0){
				rules_nosp.push(m[x][sorted_priorities[z]].rulename) ;
				addrowtotable( x , sorted_priorities[z] , "invalid" , m[x][sorted_priorities[z]].digits2strip );
			}else{
				addrowtotable( x , sorted_priorities[z] , m[x][sorted_priorities[z]].trunk , m[x][sorted_priorities[z]].digits2strip );
			}
		}
	}}

	if(rules_nosp.length > 0 ){
		gui_feedback("A Trunk is not defined for the Rule(s)<BR>" + rules_nosp,'default');
		_trunks.selectedIndex = -1;
	}

	if( _$('callingRulesTable').rows.length == 0 ){
		_$('table_one').style.display="none";
		var newRow = _$('callingRulesTable').insertRow(-1);
		var newCell0 = newRow.insertCell(0);
		newCell0 .align = "center";
		newCell0 .innerHTML = "<BR>A <I>Dial Rule</I> is not defined<BR><BR> Please click on the 'Add a Dial Rule' button<BR> to add a Dial Rule<BR><BR>" ;
		return true;
	}

	_$('addrule').disabled = false;
} 

function clear_table(){
	var _crt = _$('callingRulesTable') ;
	for( var i=0; i <  _crt.rows.length; ){ _crt.deleteRow(i); }
}

function parsepattern(a,e){
	returnstring="";
	// Parsing into fields
	// if first character is underscore (always) - remove it 
	var temp = a.substr(1);
	// if there is a dot at the end 
	//		check ormore and remove the trailing dot
	//modify 2009-5-25 ,in IE  and Firefox
	var start_i=temp.length-1;
	if (temp.substr(start_i)=="."){
         	temp = temp.substr(0,start_i);
		returnstring = "or more";
		if(e == 1){ _$('ormore').checked = true; }
	}
	var posofx = temp.indexOf('X');
	// if X does not occur anywhere followedby is = 0
	// if X happens somewhere then beginswith = string till somewhere
	//		and followedby = length of string from somewhere till end
	if(posofx == -1){ 	
		if(returnstring == "or more"){
			returnstring = "Begins with " + temp + " and followed by more than 0 digits" ;
		}else{
			returnstring = "Exactly matches " + temp  ;
		}
		if(e == 1){
			_$('beginswith').value = temp;
			_$('followedby').value = 0;
		}
	}else{
		if(returnstring == "or more"){
			returnstring = "Begins with " + temp.substr(0,posofx) + " and followed by more than "+(temp.length - posofx)+" digits" ;
		}else{
			returnstring = "Begins with " + temp.substr(0,posofx) + " and followed by "+(temp.length - posofx) + " digits";
		}
		if(e == 1){
			_$('beginswith').value = temp.substr(0,posofx);
			_$('followedby').value = (temp.length - posofx);
		}
	}

return returnstring;
}


function addrowtotable(a,b,c,d){	// a is pattern, b is priority, c is trunk, d is digits2strip
	var m = numberplansdata[_$('extensions').value]['npdata'];
	var _crt = _$('callingRulesTable') ;
	var sno = _crt.rows.length + 1;
	var newRow = _crt.insertRow(-1);
	newRow.id = "row" + sno; 

	var newCell0 = newRow.insertCell(0);
	newCell0.innerHTML = sno ;
	newCell0.width=35;
	newCell0.align="center";

	var newCell1 = newRow.insertCell(1);
	newCell1.innerHTML =  (m[a][b].rulename) ? m[a][b].rulename : "Not Defined" ; 
	newCell1.width=90;

	var newCell2 = newRow.insertCell(2);
	newCell2.innerHTML =  (m[a][b].ruledesc) ? m[a][b].ruledesc : a ; 
	if(newCell2.innerHTML == "custom"){ newCell2.innerHTML = "custom ("+ a + ")"; }

	var newCell3 = newRow.insertCell(3);
	newCell3.align="center";
	newCell3.width=85;
	if(c == "invalid" || c== "undefined"  ){
		newCell3.innerHTML = "<span style='cursor:pointer; color : #0000ff;'  onclick=\"editcallingrule('"+ a +"', '"+ b +"')\">Select a Trunk</span>";
	}else{
		newCell3.innerHTML = trunks_desc[c].comment  ;
	}

	var newCell4 = newRow.insertCell(4);
	newCell4.innerHTML = "<A href=\"#\" onclick=\"editcallingrule('"+ a +"', '"+ b +"')\" tip=\"en,callingrules,2\">Edit</A>&nbsp;&nbsp;<A href=\"#\" onclick=\"deletecallingrule('"+ a +"', '"+ b +"')\"><font color=\"#FF6666\" tip=\"en,callingrules,3\">Delete</font></A>";
	newCell4.width=75;
	newCell4.align="center";
	return true;
}

function deletecallingrule(a,b){ // a is pattern, b is priority
	if(!confirm("Are you sure ?")) { return true; }
	delete_callingrule(a,b, oncomplete = function(){ show_npdata_table( _$('extensions').value ); gui_feedback("Calling Rule Deleted",'default'); } ) ;
}

function delete_callingrule(a,b,oncomplete){ // a is pattern, b is priority
	var _extv = $('extensions').value ;
	var priority = 1;
	var p = 0;
	var m = numberplansdata[_extv]['npdata'];
	var commentstring = (m[a][b].ruledesc == 'custom') ? "custom" : "standard" ;

	var noop_string = a + ',' + priority + ",NoOp()" ;
	uri = build_action('delete', p, _extv ,"exten","", noop_string ); p=p+1;
	if(m[a][b].dialpasswd.length){
	var dialauth_string = a + "," + (priority+1) + ",authenticate(" + m[a][b].dialpasswd + ")" ;
	uri += build_action('delete', p , _extv ,"exten","", dialauth_string ); p=p+1;
	priority = priority +1;
	}

	if ( m[a][b].fallback )
		var rule_string = a + ',' + (priority+1) + ',Macro(trunkdial-failover,${' + m[a][b].trunk + '}/'+ m[a][b].prepend + '${EXTEN:' + m[a][b].digits2strip + '},${' + m[a][b].fallback + '}/'+ m[a][b].prepend +'${EXTEN:' + m[a][b].digits2strip + '})' ;
	else
		var rule_string = a + ',' + (priority+1) + ',Macro(trunkdial-failover,${' + m[a][b].trunk + '}/'+ m[a][b].prepend + '${EXTEN:' + m[a][b].digits2strip + '},)' ;
	uri += build_action('delete', p, _extv ,"exten","", rule_string ); p=p+1;
	
	commentstring = a + ',' + (priority+1) + ',' + m[a][b].rulename + ',' + commentstring ;
	uri += build_action('delete', p , _extv ,"comment","", commentstring ); p=p+1;

	_$('userscontent').style.display = "none";
	_$('bg_transparent').style.display = "none";
	_$('status_message').style.display = "";

	makerequest('u','extensions.conf', uri,
		function(t){
			_$('status_message').style.display="none";
			delete numberplansdata[ _extv ]['npdata'][a][b] ;
			oncomplete(); 
		}
	);
}


function editcallingrule(a,b){	// a is pattern, b is priority
	pattern_beingedited = a ;
	pattern_beingedited_priority = 1;
	isnewrule = false ;
	_$('authck').checked = false;
	_$('dialpasswd').value = "";
	var _trunks = _$('trunks') ;
	var _fallback = _$('fallback') ;

	var m = numberplansdata[_$('extensions').value]['npdata'];
	_$('rulename').value = m[a][b].rulename;
	_trunks.selectedIndex = -1 ;
	for(var i=0; i < _trunks.length ; i++ ){
		if( _trunks.options[i].value == m[a][b].trunk ){
			_trunks.selectedIndex = i ;
			break;
		}
	}
	_fallback.selectedIndex = 0 ;
	if(_trunks.selectedIndex != -1)
	{
	_fallback.disabled = 0;
	for(var i=0; i < _fallback.length ; i++ ){
		if( _fallback.options[i].value == m[a][b].fallback ){
			_fallback.selectedIndex = i ;
			break;
		}
	}
	}

	_$('pattern').value = a;
	if(m[a][b].dialpasswd.length){
		_$('authck').checked = true;
		_$('dialpasswd').value = m[a][b].dialpasswd
		}
	displayauth();
	_$('strip').value = m[a][b].digits2strip;
	_$('prepend').value = m[a][b].prepend;
	_$('save_a').disabled = 1;
	if( m[a][b].ruledesc == 'custom' || !m[a][b].ruledesc ){
		// if this is a custom pattern then donot try to parse the pattern
		iscustom = true;
		_$('rulename').value = (m[a][b].rulename) ? m[a][b].rulename : "";
		m[a][b].ruledesc = 'custom' ;
		_$('define_advanced').style.display="";
		_$('define_usual').style.display="none";
	}else{
		// if this is standard pattern then parse the pattern into 'beginswith', 'followedby'
		var temp = parsepattern(a,1);
		iscustom = false;
		_$('define_advanced').style.display="none";
		_$('define_usual').style.display="";
	}
	_$('userscontent').style.display="";
	_$('bg_transparent').style.display ='';
	_$('addrule').disabled =1;
}

function displayauth(){
	if(_$("authck").checked)
		_$("dialpasswordtab").style.display = "";
	else
		_$("dialpasswordtab").style.display = "none";
}

function ruleinanpdata(a,b,c,d,e){
	this.trunk = a ;
	this.digits2strip = b;
	this.prepend = c;
	this.dialpasswd = d
	if (e){
		this.fallback = e;
	}
	
}

function numberplan_context(){
	this.plancomment = "";
	this.nprules = [ ];
	this.npcomments = [ ];
	this.npdata = { }; 
}

numplan_callbacks.format = function(t, x) {
	if ((t.name.substr(0,11) != 'numberplan-'))
		return null;
	if( x == undefined ){  // is a new number plan 
		numberplansdata[t.name] = new numberplan_context ;
		try{
			return t.fieldbyname['plancomment'] ;
		}catch(err){
			return t.name;
		}
	}else if( t.names[x]=='plancomment' ){ 
		numberplansdata[t.name]['plancomment'] =  t.fields[x] ; 
	}else if( t.names[x]=='exten' ){ 
		numberplansdata[t.name]['nprules'].push( t.fields[x] ) ; 
	}else if( t.names[x]=='comment' ){ 
		var tmp = t.fields[x].split(",");
		if( tmp.length > 1 ){
			numberplansdata[t.name]['npcomments'].push( t.fields[x] ) ; 
		}
	}
	
	return null;
}

numplan_callbacks.loaded = function() {
	var _extns = _$('extensions') ;
	ASTGUI.events.add( _extns , 'change', select_differentplan );
	if( _extns.options.length ==0 ){

	    parent.eventeater.pingstatus = true;
	    _$('msg_bg_transparent').style.display="none";
	    _$('bg_transparent').style.display="none";
	    _$('iframe_bg_transparent').style.display="none";
	    _$('status_message').style.display="none";
		addthe_default_callingplan();
	}else{
	  	_extns.selectedIndex = 0;
		  _extns.selectitem(0);
		  parse_nprulesAndnpcomments();
		  show_npdata_table(_extns.options[0].value);
		  parent.eventeater.pingstatus = true;
     	_$('msg_bg_transparent').style.display="none";
      _$('bg_transparent').style.display="none";
      _$('iframe_bg_transparent').style.display="none";
      _$('status_message').style.display="none";
//		parent.loadscreen(this);
	}
}

numplan_callbacks.newcategory = function() {
	var _extns = _$('extensions') ;
	np_oldselect = _extns.selectedIndex ;
	_$('include').value = "default";
	var c = 1 ;
	for(var u =0 ; u < _extns.length ; u++ ){
		var tmp =  _extns.options[u].value.split("-") ;
		if( c < tmp[2] ){ break; }
		c++ ;
	}
	gen = _extns.stored_config.catbyname[_extns.value];
	temp = objcopy(gen);
	temp.name = "numberplan-custom-" + c ;
	temp.fieldbyname['plancomment'] = "DialPlan" + c;
	_$('plancomment').value = "DialPlan" + c;
	return temp;
}

numplan_callbacks.cancelnewcategory = function(){
	var _extns = _$('extensions') ; 
	_extns.selectedIndex = np_oldselect;
	_extns.selectitem(np_oldselect);
	_$('npcontent').style.display="none";
	_$('bg_transparent').style.display ='none';
}

numplan_callbacks.savechanges = function(){
	_$('npcontent').style.display="none";
	_$('bg_transparent').style.display ='none';
	show_npdata_table( _$('extensions').value );
}

numplan_callbacks.delchanges = function(box, value) {
	var _extns = _$('extensions') ;
	if( _extns.options.length ==0 ){
		addthe_default_callingplan();
	}else{
		_extns.selectedIndex = 0;
		_extns.selectitem(0);
		show_npdata_table( _extns.options[0].value );
	}
}

numplan_callbacks.eachline = true;
numplan_callbacks.includecats = true;

function localajaxinit(){
	ASTGUI.events.add(document, 'mouseover', show_tooltip);
	showdiv_statusmessage();
	setWindowTitle("Dial Rules");
//	ASTGUI.events.add( _$('trunks') , 'change' , check_if_analog ) ;
	for (var x =0; x < fieldnames.length; x++ ) {
		widgets[fieldnames[x]] = _$(fieldnames[x]);
		widgets[fieldnames[x]].disabled = true;
	}

	   //_$('message_text').innerHTML ="Saving Changes...";

     parent.eventeater.pingstatus=false;
	   _$('msg_bg_transparent').style.display="";
	   _$('bg_transparent').style.display="";
 	   _$('iframe_bg_transparent').style.display="";
     showdiv_statusmessage();
   	_$('status_message').style.display="block";
   	_$('message_text').innerHTML = "Loading  Outbound Routes Information ...";
     parent.loadscreen(this);

	config2json('users.conf', 1, trunks_loaded ) ;
	//parent.astmanEngine.config2list("users.conf", $('trunks'), new Array(), trunkcallbacks);
}

function trunks_loaded(b){
	var c = b ;
	for( var d in c ){
		if ( c.hasOwnProperty(d) && c[d]['context'] && (c[d]['context'] == asterisk_guiTDPrefix + d ) ) {
			trunks_desc[d] = new Object();
			trunks_desc[d].comment = (c[d]['trunkname']) ? unescape(c[d]['trunkname']) : d ;
			trunks_desc[d].style = unescape(c[d]['trunkstyle']);
			var New_OPTION = document.createElement('option');
			New_OPTION.text =  unescape(trunks_desc[d].comment) ;
			New_OPTION.value =d ;
			var New_OPTION_fallback = document.createElement('option');
			New_OPTION_fallback.text = unescape(trunks_desc[d].comment) ;
			New_OPTION_fallback.value = d ;
			try {
				_$('trunks').add(New_OPTION, null); // W3C way
				_$('fallback').add(New_OPTION_fallback, null); // W3C way
			}catch(ex) {
				_$('trunks').add(New_OPTION); // IE way
				_$('fallback').add(New_OPTION_fallback); // IE way
			}
		}
	}
	parent.astmanEngine.config2list("extensions.conf", _$('extensions'), widgets , numplan_callbacks);
}

function select_differentplan(){
	var _extns = _$('extensions').value ;
	if(typeof numberplansdata[_extns] == "undefined"){
		numberplansdata[_extns] = new numberplan_context ;
		numberplansdata[_extns].plancomment = $("plancomment").value;
	}
	show_npdata_table(_extns);
}

function newnumberplan(){
	_$('npcontent').style.display="";
	_$('bg_transparent').style.display ='';
	_$('new').click();
}

function delete_numberplan(){	_$('deleted').click();	}

function addthe_default_callingplan(a){
	if(!a){
		_$('message_text').innerHTML = "A default DialPlan is not found !! "
		+ "<BR><BR> <A href=\"#\" class=\"splbutton\" onclick=\"addthe_default_callingplan(1)\">click here</A> to create a default DialPlan";
		var _bg_s = _$('bg_transparent').style ;
		var _sm_s = _$('status_message').style ;
		_sm_s.left = 120 ;
		_sm_s.zIndex = _bg_s.zIndex + 1;
		_bg_s.display = '' ;
		_sm_s.display = "" ;
		return true;
	}
	var default_planname = 'numberplan-custom-1' ;
	var uri = build_action('newcat', 0, default_planname ,"", "");
	uri += build_action('append', 1, default_planname,"plancomment", "DialPlan1"); 
	uri += build_action('append', 2, default_planname,"include", "default"); 
	makerequest('u','extensions.conf', uri, function(t){gui_feedback("Created Default DialPlan",'green'); location.reload(); }   );
}

function free_mem( ){
	if( navigator.userAgent.indexOf("MSIE") == -1 ){ return true; }
	try{
		widgets['save'].hostselectbox = null ;
		widgets['cancel'].hostselectbox = null ;
		widgets['new'].hostselectbox = null ;
		widgets['deleted'].hostselectbox = null ;
		purge( document.body );
	}catch(e){ }
}
</script>
<style type="text/css">
<!--
body {
	background-color: #ebebeb;
}
.STYLE1 {font-size: 16px}
-->
</style><body id="foo" onLoad="localajaxinit()" onUnload="free_mem()">
<div class="mainscreenTitleBar">
	<table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td align="center"><span class="STYLE1" style="margin-left: 4px;font-weight:bold;">Dial Rules</span> <span style="cursor: pointer; cursor: hand;" onClick="window.location.href=window.location.href;" >&nbsp;<img src="images/refresh.png" title=" Refresh " border=0 >&nbsp;</span></td>
      </tr>
    </table>
</div>
<div class="mainscreenContentBox" id="mailboxcontent">
<center>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="15" bgcolor="#cecece"><img src="images/line.jpg" width="15" height="20"></td>
    <td width="485" bgcolor="#cecece"><strong>List of DialPlans:</strong></td>
  </tr>
  <tr>
    <td height="30" colspan="2" valign="middle" class="h_line"><CENTER>
      <select id="extensions" class="input9" style="z-index:2"></select>&nbsp;&nbsp;
			<input type="button" class="buttonbold" tip="en,callingrules,0"  onClick="newnumberplan()" value="New">&nbsp;&nbsp;
			<input type="button" class="deletetabb" tip="en,callingrules,1" onClick="delete_numberplan()" value="Delete">
			<input id='new' value='New' type="button"  style="display:none">
			<input id='deleted' value='Delete' type="button"  style="display:none">
			
		</CENTER></td>
  </tr>
</table>
  <br>
</center>
	<BR>
	<div id="npcontent" STYLE="display:none; position: absolute; left: 110; top: 40; width:320; height:110;  background-color:#f5f5f5;   border-width: 1px; border-color: #888888; border-style: solid; z-index:6">
	<table width="100%" cellpadding=0 cellspacing=0  onmousedown="ASTGUI.startDrag(event , 'npcontent');">
		<TR bgcolor="#888888"  style="background-image:url('images/title_gradient.gif');">
			<TD Height="20" align="center" style="cursor: move">
				<font style="color:#FFFFFF; font-size: 12px; font-weight:bold;">Create new Dial Plan? </font>
			</TD>
			<TD Height="20" align="right" style="cursor: move">
				<A href="#" onClick="$('cancel').click();"><font style="color:#FFFFFF; font-size: 12px; font-weight:bold;">X</font></A>
			</TD>
			<TD width=4></TD>
		</TR>
	</table>
	<TABLE cellpadding=0 cellspacing=3 border=0 width="100%">
		<TR>	<TD colspan=2 height=10></TD>	</TR>
		<TR>
			<TD align="center"><input id="name" style="display:none">Create a new Dial Plan? <input id="plancomment" size=15 class="input9" style="display:none"><input id="include" style="display:none"></TD>
		</TR>
		<TR>	<TD colspan=2 height=10></TD>	</TR>
		<TR>	<TD align="center" colspan=2>
				<input id='save' class="buttonbold"  value='Yes' type="button">&nbsp;&nbsp;
				<input id='cancel' class="buttonbold"  value='No' type="button">
			</TD>
		</TR>
	</TABLE>
	</div>
	<center>
	<table width="100%" style="height: 390px; " border="0" cellspacing="0" cellpadding="0" id="fieldset2">
  <tr>
    <td width="15" height="20" bgcolor="#cecece"><img src="images/line.jpg" width="15" height="21"></td>
    <td width="200" height="20" valign="middle" bgcolor="#cecece"><strong>List of Dial Rules:</strong></td>
    <td width="525" height="20" valign="middle" bgcolor="#cecece"><input style="font-weight:bold" type="button" id="addrule" class="buttonbold"  value="Add a Dial Rule" onClick="add_callingrule();"  tip="en,callingrules,4"></td>
  </tr>
  <tr>
    <td colspan="3" valign="top">
	<table width=100% border=0 align=center cellpadding=2 cellspacing=2 class="table_black" id="table_one">
		<tr>	<td width=35>S.No</td>
			<td width=90>RuleName</td>
			<td>Dial Pattern</td>
			<td width=85 align=center>Call Using</td>
			<td width=75 align=center>Options</td>
		</tr>
		</table>
		<div id="callingRulesTable_div" style="height:260px;width=100%; overflow :auto; padding : 0px 0px 0px 0px;">
			<table id="callingRulesTable" cellpadding=2 cellspacing=1 border=0 align=center width=100%></table>
		</div>
		<BR>
		</td>
  </tr>
</table>
	</center>

	<div id="userscontent" STYLE="display:none; position: absolute; left: 20; top: 144; width:500; height:320;  background-color:#f5f5f5;   border-width: 1px; border-color: #888888; border-style: solid; z-index:5">
	<table width="100%" cellpadding=0 cellspacing=0  onmousedown="ASTGUI.startDrag(event , 'userscontent');">
	<TR bgcolor="#888888"  style="background-image:url('images/title_gradient.gif');">
		<TD Height="20" align="right" style="cursor: move">
			<A href="#" onClick="$('cancel_a').click();"><font style="color:#FFFFFF; font-size: 12px; font-weight:bold;">X</font></A>
		</TD>
		<TD width=4></TD>
	</TR>
	</table>
	<TABLE	align=center cellpadding=2 cellspacing=2 border=0 width="480">
	<TR>	<TD align="right" width=189 tip="en,callingrules,5">Rule Name:</TD>
		<TD colspan="2"><input type="text" id="rulename" size="" onChange="enablesave();" onKeyUp="enablesave();" class="input9"></TD>
	</TR>
	<TR>	<TD  align="right" tip="en,callingrules,6"> Place this call through :</TD>
		<TD colspan="2"><select id="trunks"  class="input9" onChange="enablesave();"></select></TD>
	</TR>
	<TR>	<TD  align="right" tip="en,callingrules,10"> Failover :</TD>
		<TD colspan="2"><select id="fallback"  class="input9" onChange="enablesave();"><option value="none">None</option></select></TD>
	</TR>
		<TR>	<TD  align="right" tip="en,callingrules,11"> PIN Set:</TD>
	<TD width="26" valign="top"><input type="checkbox" id="authck" onClick="displayauth();enablesave();" onChange="enablesave();"> </TD>
	    <TD width="245" valign="top"><table id="dialpasswordtab" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td> Entry PIN Code:   
              <input name="text" type="text" id="dialpasswd" onChange="enablesave();" onKeyUp="enablesave();" size="16" maxlength="20"></td>
          </tr>
        </table>
        </TD>
	</TR>
	<TR id="define_usual" height=100>
		<TD valign="top" align=right tip="en,callingrules,7">Dialing Rules :</TD>
		<TD colspan="2" valign="top"> If the number begins with <input id="beginswith"  class="input8" pattern="^[0-9*]*$" size=6 onChange="enablesave();" onKeyUp="enablesave();"> and 
				followed by (<input type="checkbox" id="ormore" onChange="enablesave();" onClick="enablesave();")>more than) <input id="followedby" type='text'  class="input9" pattern='^[0-9*]*$' size=1 onChange="enablesave();" onKeyUp="enablesave();"> digits  <BR>
			<A href="#" onClick="ownpattern();">(define a custom pattern)</A>
		</TD>
	</TR>
	
	<TR id="define_advanced"  height=100>
		<TD valign="top" align=right tip="en,callingrules,8"> Custom Pattern: </TD>
		<TD colspan="2" valign=top>
			<input type="text" id="pattern" size="" pattern='^[a-zA-Z_0-9. ]*$' onChange="enablesave();" onKeyUp="enablesave();"  class="input9"><BR>
			<A href="#" onClick="basicpattern();">(define a Basic Pattern)</A><BR>
			<table align='left' cellpadding=0 cellspacing=0>
			<tr>	<td class="field_text"><b>Z&nbsp;&nbsp;</b></td>
				<td class="field_text">Any digit from 1 to 9</td>
			</tr>
			<tr>	<td class="field_text"><b>N&nbsp;&nbsp;</b></td>
				<td class="field_text">Any digit from 2 to 9</td>
			</tr>
			<tr>	<td class="field_text"><b>X&nbsp;&nbsp;</b></td>
				<td class="field_text">Any digit from 0 to 9</td>
			</tr>
			<tr>	<td class="field_text"><b>.&nbsp;&nbsp;</b></td>
				<td class="field_text">Any number of additional digits</td>
			</tr>
			</table>
		</TD>
	</TR>
	<TR>	<TD colspan=3 align=center tip="en,callingrules,9">
			Delete <input type="text" id="strip"  class="input9" size="1" pattern='^[0-9*]*$' onChange="enablesave();" onKeyUp="enablesave();"> 
			digits from the front and auto-add digit <input type="text" id="prepend"  class="input9" size="3" pattern='^[0-9*]*$'  onChange="enablesave();" onKeyUp="enablesave();"> before dialing
		</TD>
	</TR>
	<TR>	<TD colspan=3 align=center height=50 valign=middle>  
			<input type="button" class="buttonbold" id="save_a" value="Save" onClick="saverule();">&nbsp;&nbsp;
			<input type="button" class="buttonbold" id="cancel_a" value="Cancel" onClick="$('userscontent').style.display='none'; $('bg_transparent').style.display ='none'; $('addrule').disabled =0;">
		</TD>
	</TR>
	</TABLE>
	</div>
</div>
<div id="bg_transparent" STYLE="display:none; position: absolute; left: 0; top: 24; width:100%; height:100%;  background-color:#EFEFEF; -moz-opacity:.50;opacity:.50;filter:alpha(opacity=40); border-width: 1px; border-color: #EFEFEF; border-style: solid; z-index:4">
</div>
<iframe id = "iframe_bg_transparent" frameborder="0" style="display:none;position:absolute;z-index:4;left:0;top:0;width:100%;filter:alpha(opacity=0);height:100%;"></iframe>
<iframe id="msg_bg_transparent" frameborder="0" STYLE="display:none; position: absolute; left: 170; top: 190; width:350; height:115;  background-color:#EFEFEF;border-width: 1px; border-color: #EFEFEF; border-style: solid; z-index:6">
</iframe>
</body>

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////