//Simon Champion, 2008. Routeplans management functions (v2.0).
var G_ListActive=true;
var G_AddMode=false;
var G_CurrRec='';
var G_MaxRec='';
var G_Table=new Array();
var G_loadingsel=false;

var G_Mailboxes=new Array();
var G_MBselect="";

var bg_def='';
var bg_over='#BBBBFF';
var bg_sel='#FFC000';
var bg_selover='#E3D599';

var selbox_fieldlist=new Array('name','inuse_yn','num1d','num2d');
selbox_align['inuse_yn']='center';
var main_fieldlist=new Array('name','rtype','mblast');

//used for alt text and title attribute, each in two places, so defined globally rather than repeating them all the time.
var G_AltText=new Array;
G_AltText['suspended']="Number is suspended: Please contact us to re-enable it.";
G_AltText['nowhere']="Number inactive. Callers will hear an engaged tone.";
G_AltText['number']="Configure with a single destination number (eg route to my home phone)";
G_AltText['dayparting']="Configure with a time-based system (eg route to my mobile after office hours)";
G_AltText['routeplan']="Configure with a single route plan (eg divert call after 15 seconds)";
G_AltText['fax2email']="Configured as a fax to email service.";
G_AltText['externally-routed']="Special customised configuration.";
G_AltText['2stageIDA']="Configured with 2-Stage Indirect Access.";
G_AltText['customer']="Allocate to one of your customers.";
G_AltText['sip']="Configure with a SIP (VOIP) address.";
G_AltText['originbased']="Origin-based routing. (caller location)";
G_AltText['voicemail']="Divert number directly to a voicemail box";

if(!window.G_imgdir) {var G_imgdir='';}

function PreloadSequence(pldseq) {
	pldseq++;
	switch(pldseq) {
		case 1: //mailboxes
			BuildMailboxArray(G_Mailboxes,'PreloadSequence('+pldseq+')','PreloadSequence('+pldseq+')');
			break;
		case 2: //routeplans
			BuildRoutePlanArray(G_Table,1,'PreloadSequence('+pldseq+')','PreloadSequence('+pldseq+')');
			break;
		default://insert new features in sequence above here.
			for(var gt in G_Table) {for(var ctr=1; ctr<=G_Table[gt].qtynums; ctr++) {
				//display mailbox names instead of IDs in selectbox.
				if(G_Table[gt]['type'+ctr+'d']=='voicemail') {G_Table[gt]['num'+ctr+'d']=G_Mailboxes[G_Table[gt]['num'+ctr+'d']].name;}
			}}
			BuildSelectBoxes();	//generate some select box code for the routeplans, etc.
			BuildTable();		//all done with the setup, so display the loaded routeplans in the selection list on the page.
			break;
	}
}

function BuildSelectBoxes() {
	//Load the mailbox select list....
	if(document.getElementById('temp_info_msg')) {document.getElementById('temp_info_msg').innerHTML+="...";}
	G_MBselect="";
	if(G_Mailboxes.length==0) {
		G_MBselect+="<option value='0'>-- no mailboxes --</option>";
	} else {
		G_MBselect+="<option value='0'>-- please select --</option>";
	}
	for(var mnum in G_Mailboxes) {
		G_MBselect+="<option value='"+G_Mailboxes[mnum].id+"'>"+G_Mailboxes[mnum].name+"</option>";
	}
	if(document.getElementById('temp_info_msg')) {document.getElementById('temp_info_msg').innerHTML+="...";}
}

function LoginCallback(userstring,errmessage) {
	if(errmessage) { userstring='';}
	HdrLoginFlip(userstring.length>0,userstring);
	if(userstring) {
		document.getElementById("loggedininfo").innerHTML="<p>You are now logged in to the Skycom management area.</p>";
		PreloadSequence(0);
		document.getElementById("loginblock").className="hideblock";
		document.getElementById("mainblock").className="showblock";
	} else {
		document.getElementById("loginblock").className="showblock";
		document.getElementById("mainblock").className="hideblock";
		EmptyList();
	}
}
function LoggedIn(username) {G_LoginDisplayed=0; LoginLogout(username?0:1);}	//may be called this way too if user clicked on login/logout button at top of page.

function PressAddButton() {
	//Clear the form, ready for the user to start typing a new entry.
	SelectRow(0);
	G_AddMode=true;
	ClearForm();
	AddSelRow();
	document.getElementById("f_name").value="New Routeplan";
	document.getElementById("f_rtype").value=0; //"seqfirst";	//default to standard routeplan model.
	document.getElementById("f_mblast").checked=false;
	document.getElementById("f_name").select();
}

function PressSaveButton() {
	//Save the current record. (this may be either an existing record or a new one, depending on previous actions)
	if(!G_CurrRec && !G_AddMode) {return;}

	//do some data validation here...
	if(!document.getElementById('f_name').value) {
		alert("Please specify the Routeplan Name.");
		return;
	}

	var TempTable=PopTempTable();
	var apicall={"func":(G_AddMode?"create":"edit")};

	if(!G_AddMode) {apicall["rpid"]=TempTable.id;}
	apicall['desc']=TempTable.name;
	apicall['rtype']=TempTable.rtype;
	apicall['mblast']=TempTable.mblast;

	var tb=document.getElementById('seloptstable').tBodies[0].rows
	tbln=tb.length-1;
	for(var trx=0; trx<=tbln; trx++) {
		var tr=tb[trx];
		if(tr && tr.id && tr.id.match(/_row/)) {
			var sx=tr.id.replace(/_row/,''); var isx="items["+sx+"]";
			apicall[isx+"[type]"]=document.getElementById(sx+"_termtype").value; //'number';
			apicall[isx+"[arg]"]=document.getElementById(sx+"_"+apicall[isx+"[type]"]).value;
			if(document.getElementById(sx+"_duration").value>0) {apicall[isx+"[dur]"]=document.getElementById(sx+"_duration").value;}
			if(document.getElementById(sx+"_weight")) {apicall[isx+"[weight]"]=document.getElementById(sx+"_weight").value;}
		}
	}

	apilite_post('updaterouteplans.php', apicall, (G_AddMode?'RPAddRec_okay':'RPEditRec_okay'), TempTable, (G_AddMode?'RPAddRec_fail':'RPEditRec_fail'), TempTable);

	G_AddMode=false;
}

function PressDelButton() {
	//User has asked to delete the current record, so confirm it's okay, and delete it.
	if(!G_CurrRec) {if(!G_AddMode){ClearForm();} return;}

	var okay=confirm(MSIE_MsgBox("Are you sure you want to delete routeplan \""+G_Table[G_CurrRec]['name']+"\"?"));
	if(okay) {
		var TempTable=PopTempTable();
		var apicall={"func":"delete","rpid":TempTable.id};
		apilite_post('updaterouteplans.php', apicall, 'RPDelRec_okay', TempTable, 'RPDelRec_fail', TempTable);
	}
	G_AddMode=false;
}

function PopTempTable() {
	var TempTable={id:G_CurrRec,
			name:document.getElementById('f_name').value,
			rtype:document.getElementById('f_rtype').value,
			mblast:(document.getElementById('f_mblast').checked?1:0),
			qtynums:(G_AddMode?0:G_Table[G_CurrRec]['qtynums']),
			inuse:(G_AddMode?0:G_Table[G_CurrRec]['inuse']),
			inuse_yn:(G_AddMode?0:G_Table[G_CurrRec]['inuse_yn'])
	};
	var rows=(document.getElementById('seloptstable').tBodies[0].rows.length)-1;
	TempTable.qtynums=rows;
	for(var rctr=1; rctr<=rows; rctr++) {
	    //- DCK: Quick Patch. The Hidden input boxes seems to skip a number every now and then. The part that causes errors have been encapsulated 
	    //       to continue functioning even if one of the boxes are missing.
	    try{
		    switch(document.getElementById('s'+rctr+'_termtype').value) {
			    case 'number'   : TempTable['num'+rctr+'d']=document.getElementById('s'+rctr+'_number').value; break;
			    case 'voicemail': TempTable['num'+rctr+'d']=G_Mailboxes[document.getElementById('s'+rctr+'_voicemail').value].name; break;
			    default : TempTable['num'+rctr+'d']='';
		    }
	    }
	    catch(err){
	        //DCK: Do Nothing
	    }
	    //+	    
	}
	return TempTable;
}

function RPDelRec_okay(responsestring,args) {
	var rownum=document.getElementById('dtr_'+args.id).rowIndex;
	document.getElementById('datatable').tBodies[0].deleteRow(rownum);	//delete the table row.
	delete G_Table[args.id];						//delete the array element.
	G_CurrRec='';								//clear the current record pointer.
	ClearForm();
	EnableButton('del',false);						//disable the buttons until another record is selected.
	EnableButton('sav',false);
	alert("Thank you. Your routeplan has been deleted.");
}

function RPDelRec_fail(responsestring,args) {
	if(responsestring.match("expired")) {AutoLogout(); return;}
	alert("Error deleting routeplan.\n"+responsestring);
}

function RPAddRec_okay(responsestring,args) {
	G_CurrRec=responsestring;
	args.id=G_CurrRec;
	G_Table[G_CurrRec]=args;
	AddLineToList(G_Table[G_CurrRec]);
	SelectRow(G_CurrRec);
	RowMouseout(G_CurrRec);
	var mybox=document.getElementById('datatable').parentNode;
	if(mybox.scrollHeight>mybox.clientHeight) {
		//scroll the list down to the bottom so the user can see their new entry.
		mybox.scrollTop=mybox.scrollHeight-mybox.clientHeight;
	}
	alert("Routeplan created.");
}

function RPAddRec_fail(responsestring,args) {
	if(responsestring.match("expired")) {AutoLogout(); return;}
	alert("Error creating record.\n"+responsestring);
	G_AddMode=true; //if it's a fixable error, they'd probably quite like to fix it and try again.
}

function RPEditRec_okay(responsestring,args) {
	G_CurrRec=args.id;
	G_Table[G_CurrRec]=args;
ShowDebug("HELP! "+args['num1d']+"<br />");
for(var qwqw in args) {ShowDebug("::: ["+qwqw+"] == ["+args[qwqw]+"]<br />");}
	RefreshRow(G_Table[G_CurrRec]);
	alert("Routeplan updated.");
}

function RPEditRec_fail(responsestring,args) {
	if(responsestring.match("expired")) {AutoLogout(); return;}
	alert("Cannot save routeplan.\n"+responsestring);
}

function ClearForm() {
	//Blank out all the form fields. We do this even when we're about to populate them all again, so we can avoid any display errors with data being left behind from a previous record.
	var editable=(G_CurrRec||G_AddMode);
	for(fld in main_fieldlist) {
		document.getElementById("f_"+main_fieldlist[fld]).disabled=!editable;

		if(document.getElementById("f_"+main_fieldlist[fld]).type=='checkbox') {
			document.getElementById("f_"+main_fieldlist[fld]).checked=false;
		} else {
			document.getElementById("f_"+main_fieldlist[fld]).value="";
		}
		document.getElementById("f_"+main_fieldlist[fld]).valid=false;
	}
	DelAllSelRows();
}

function PopulateForm() {
	//Display the record currently selected in the list onto the form fields.
	ClearForm();
	if(!G_CurrRec) { return; }

	document.body.style.cursor = "wait";
	G_loadingsel=true;
	var apicall={"rpid":G_CurrRec,'getalso':1};
	apilite_post('listmyrouteplans.php', apicall, 'RPGetRec_okay', '', 'RPGetRec_fail', '');
}

function RPGetRec_okay(responsestring,args) {
	var rpitems=responsestring.split("%%");
	var maindata=rpitems[0].split("|");

	var dispflds={name:maindata[1],rtype:maindata[3],mblast:maindata[6]};
	for(field in dispflds) {
		if(document.getElementById("f_"+field)) {
			if(document.getElementById("f_"+field).type=='checkbox') {
				document.getElementById("f_"+field).checked=(dispflds[field]>0);
			} else {
				document.getElementById("f_"+field).value=dispflds[field];
			}
			document.getElementById("f_"+field).valid=true;	//already saved this value, so assume must be valid.
		}
	}


	rpitems.shift();	//drop first element as not valid (this is the maindata content)
	for(var rpln in rpitems) {
		var tsl=rpitems[rpln].split("|");
		AddSelRow({type:tsl[0], duration:tsl[1], number:tsl[2], weight:tsl[3]});
	}

	ToggleRouteTypeOpts(dispflds.rtype);
	document.body.style.cursor = "";
	G_loadingsel=false;
}

function RPGetRec_fail(responsestring,args) {
	if(responsestring.match("expired")) {AutoLogout(); return;}
	document.body.style.cursor = "";
	G_loadingsel=false;
	alert("There was an error loading the routeplan list");
}

function ToggleRouteTypeOpts(key) {
	document.getElementById('routplan_type_info').innerHTML=rpttext[key];
	document.getElementById('routplan_type_info').className='showblock';
}

//-----------------------------------------------------------------------------

function RoutingField(ftype,brow,activebtn,flddesc,itype,opts) {
	var trigger=""; //"ValidateNum(\""+ftype+"\",\""+brow+"\",this.value);";
	var fldcode='';
	switch(itype) {
		case 'select' :
			fldcode="<select id='"+brow+"_"+ftype+"' name='"+brow+"_"+ftype+"' style='width:15em; vertical-align: middle;' onchange='"+trigger+"' >"+opts+"</select>";
			break;
		case 'input' :
			if(activebtn!=ftype) {opts='';}
			fldcode="<input type='text' style='vertical-align:middle; width:15em;' name='"+brow+"_"+ftype+"' id='"+brow+"_"+ftype+"' value='"+opts+"' onchange='"+trigger+"' />";
			break;
		case 'saveonly' :
			fldcode=opts;
			break;
		default:
			break;
	}
	var outstr="<span id='popvalue-"+ftype+"-"+brow+"' class='"+(activebtn==ftype?'showblock':'hideblock')+"'>";
	if(fldcode)  {outstr+="<span class='termopt_field'>"+fldcode+"</span>";}
		else {outstr+="<span class='termopt_info'>"+flddesc+"</span>";}
	outstr+="</span>";
	return outstr;
}

function DrawBtn(inname,brow,activebtn) {
	//inname = the name of this button (eg 'routeplan').
	//brow = the row identifier (on number management page, this would be 0845 number, etc; here it is the row ID.
	//activebtn = the name of the active button in this set, so we know whether to show the highlighted one or not.
	var gfxname=G_imgdir+"images/mgt/mgt-"+inname;
	var stext="alt='"+G_AltText[inname]+"' title='"+G_AltText[inname]+"'";
	var script="onmouseover='this.src=\""+gfxname+"-b.gif\";' onmouseout='this.src=\""+gfxname+"-c.gif\";' onclick='NumTermSwitch(\""+inname+"\",\""+brow+"\");'";

	var outstr='';

	outstr+= "<img src='"+gfxname+"-a.gif' "+stext+" id='term-"+inname+"-a_"+brow+"' class='termbtn_active "+(activebtn==inname?"showblock":"hideblock")+"' />"
		+"<img src='"+gfxname+"-c.gif' "+stext+" id='term-"+inname+"-b_"+brow+"' class='termbtn_ready " +(activebtn!=inname?"showblock":"hideblock")+"' "+script+" />";
	return outstr;
}

function NumTermSwitch(termtype,number) {
	for(var key in G_AltText) {
		NumTermSwitch2(key,termtype,number);
	}
	document.getElementById(number+'_termtype').value=termtype;
}
function NumTermSwitch2(key,termtype,number) {
	var ta=document.getElementById("term-"+key+"-a_"+number);	//this is the highlighted toggle image for this termination type.
	var tb=document.getElementById("term-"+key+"-b_"+number);	//this is the greyed toggle button for this termination type.
	var pv=document.getElementById("popvalue-"+key+"-"+number);	//this is the input block for this termination type.
	//need to check that they all exist, as some termination types may be disabled.
	if(ta) { ta.className="termbtn_active "+(termtype==key?"showblock":"hideblock"); }
	if(tb) {
		tb.className="termbtn_ready "+(termtype==key?"hideblock":"showblock");
		tb.src=G_imgdir+"images/mgt/mgt-"+key+"-c.gif";	//simulate a mouseout event, so we don't leave highlighted images behind.
	}
	if(pv) { pv.className=((termtype==key)?"showblock":"hideblock"); }
}

//-----------------------------------------------------------------------------
var g_topsx=0;

function AddSelRow(rec) {
	if(!G_CurrRec && !G_AddMode) {return;}
	if(!rec) {rec={type:'number', number:'', voicemail:0, duration:'', weight:''};}
	var durasel={0:'',5:'',10:'',15:'',20:'',30:'',45:'',60:'',90:''};
	if(rec.duration) {durasel[rec.duration]="selected='1'";}

	btnstr='';
	for(var btnkey in thisbtns) {btnstr+=DrawBtn(btnkey,'sx',rec.type);}
	btnstr+="<input type='hidden' name='sx_termtype' id='sx_termtype' value='"+rec.type+"' />";

	var fldstr='';
	if(thisbtns['number']) {fldstr+=RoutingField('number','sx',rec.type,'','input',(rec.type=='number'?rec.number:''));}
	if(thisbtns['voicemail']) {fldstr+=RoutingField('voicemail','sx',rec.type,'','select',G_MBselect);}
    //!- DCK: Adding VOIP
	if(thisbtns['sip']) {fldstr+=RoutingField('sip','sx',rec.type,'','input',(rec.type=='sip'?rec.number:''));}
    //!+ 


	var fields=new Array();
	fields.type=btnstr;
	fields.number=fldstr; //"<input type='text' size='15' name='sx_number' id='sx_number' value='"+rec.number+"' />"
	fields.duration="<select style='width:9em;' name='sx_duration' id='sx_duration'>";
	for(var ctr in durasel) {
		if(ctr>0) {ctrshow=''+ctr+' secs';} else {ctrshow='no timeout';}
		fields.duration+="<option value='"+ctr+"' "+durasel[ctr]+">"+ctrshow+"</option>";
	}
	fields.duration+="</select>";
// 	fields.weight="<input style='text-align:right;' type='text' size='3' name='sx_weight' id='sx_weight' value='"+rec.weight+"' />";

	fields.remove="<img src='"+G_imgdir+"images/minus.gif' alt='Delete' title='Delete' id='sx_delete' onclick='DelSelRow(\"sx\")' class='clickable' />";

	var rows=document.getElementById('seloptstable').tBodies[0].rows;
	if(rows.length>5) {alert("Routeplans are currently restricted to a maximum of five entries."); return;}	//SDC, req by WB: Hard stop at 5 entries until we've confirmed system for advanced routeplans.

	if(rows[rows.length-1].id.match(/_row/)) { //don't show the 'move up' button on the first row.
		fields.moveup="<img src='"+G_imgdir+"images/sort_up1.gif' alt='Move up' title='Move up' id='sx_moveup' onclick='MoveRowUp(\"sx\")' class='clickable' />";
	} else {
		fields.moveup="";
	}

	if(!rec) {rec=new Array();}
	var newTR = document.createElement('tr');
	if(rec.id>g_topsx) {g_topsx=rec.id;} else {rec.id=++g_topsx;}
	newTR.setAttribute('id', "s"+rec.id+"_row");
	newTR.setAttribute('className', 't2bb rpfield_row');

	for(var fnum in fields) {
		var newTD = document.createElement((fnum=='remove' || fnum=='moveup')?'th':'td');
		newTD.setAttribute('id', "s"+rec.id+"_"+fnum+"_td");
		newTD.innerHTML=fields[fnum].replace(/sx/g,"s"+g_topsx+"");
		newTR.appendChild(newTD);
	}
	document.getElementById('seloptstable').tBodies[0].appendChild(newTR);
	if(rec.type=='voicemail') {document.getElementById('s'+g_topsx+'_'+'voicemail').value=rec.number;}
}

function DelSelRow(rowID) {
	if(!G_CurrRec && !G_AddMode) {return;}
	var tr=document.getElementById(rowID+'_row');
	tr.parentNode.deleteRow(tr.rowIndex);
}

function DelAllSelRows() {
	var tb=document.getElementById('seloptstable').tBodies[0].rows
	for(var trx=tb.length-1; trx>=0; trx--) {
		var tr=tb[trx];
		if(tr && tr.id && tr.id.match(/_row/)) {tr.parentNode.deleteRow(tr.rowIndex);}
	}
	g_topsx=0;
}

function MoveRowUp(rowID) {
	if(!G_CurrRec && !G_AddMode) {return;}
	var tr=document.getElementById(rowID+'_row');
	if(!tr) {return;}
	var pr=tr.previousSibling;
	if(!pr) {return;}
	if(!pr.id.match(/_row$/) || !tr.id.match(/_row$/)) {return;}
	var prowID=pr.id.replace(/_row$/,'');

	//Swap all the field values it the two rows.
// 	var fieldlist=new Array('number','duration','weight','termtype','voicemail');
	var fieldlist=new Array('number','duration','termtype','voicemail');
	var fields=new Array();
	for(var fld in fieldlist) {
ShowDebug("FLD: "+fld+" / "+fieldlist[fld]+" / "+rowID+" / "+prowID);
		fields[fieldlist[fld]]=document.getElementById(rowID+'_'+fieldlist[fld]).value;
		document.getElementById(rowID+'_'+fieldlist[fld]).value=document.getElementById(prowID+'_'+fieldlist[fld]).value;
		document.getElementById(prowID+'_'+fieldlist[fld]).value=fields[fieldlist[fld]];
	}
	NumTermSwitch(document.getElementById(rowID+'_termtype').value,rowID)
	NumTermSwitch(document.getElementById(prowID+'_termtype').value,prowID)
}
