
Ext.Frs.SwfController=function()
{var UNDEF="undefined",OBJECT="object",SHOCKWAVE_FLASH="Shockwave Flash",SHOCKWAVE_FLASH_AX="ShockwaveFlash.ShockwaveFlash",FLASH_MIME_TYPE="application/x-shockwave-flash",win=window,doc=document,nav=navigator,domLoadFnArr=[],regObjArr=[],timer=null,storedAltContent=null,storedAltContentId=null,isDomLoaded=false,isExpressInstallActive=false;var ua=function(){var playerVersion=[0,0,0],d=null;if(typeof nav.plugins!=UNDEF&&typeof nav.plugins[SHOCKWAVE_FLASH]==OBJECT){d=nav.plugins[SHOCKWAVE_FLASH].description;if(d){d=d.replace(/^.*\s+(\S+\s+\S+$)/,"$1");playerVersion[0]=parseInt(d.replace(/^(.*)\..*$/,"$1"),10);playerVersion[1]=parseInt(d.replace(/^.*\.(.*)\s.*$/,"$1"),10);playerVersion[2]=/r/.test(d)?parseInt(d.replace(/^.*r(.*)$/,"$1"),10):0;}}
else if(typeof win.ActiveXObject!=UNDEF){var a=null,fp6Crash=false;try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX+".7");}
catch(e){try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX+".6");playerVersion=[6,0,21];a.AllowScriptAccess="always";}
catch(e){if(playerVersion[0]==6){fp6Crash=true;}}
if(!fp6Crash){try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX);}
catch(e){}}}
if(!fp6Crash&&a){try{d=a.GetVariable("$version");if(d){d=d.split(" ")[1].split(",");playerVersion=[parseInt(d[0],10),parseInt(d[1],10),parseInt(d[2],10)];}}
catch(e){}}
var u=nav.userAgent.toLowerCase(),p=nav.platform.toLowerCase(),webkit=/webkit/.test(u)?parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false;}
return{w3cdom:true,pv:playerVersion,webkit:webkit,ie:Ext.isIE,win:Ext.isWindows,mac:Ext.isMac};}();function fixParams(obj){var nestedObj=obj.getElementsByTagName(OBJECT)[0];if(nestedObj){var e=createElement("embed"),a=nestedObj.attributes;if(a){var al=a.length;for(var i=0;i<al;i++){if(a[i].nodeName.toLowerCase()=="data"){e.setAttribute("src",a[i].nodeValue);}
else{e.setAttribute(a[i].nodeName,a[i].nodeValue);}}}
var c=nestedObj.childNodes;if(c){var cl=c.length;for(var j=0;j<cl;j++){if(c[j].nodeType==1&&c[j].nodeName.toLowerCase()=="param"){e.setAttribute(c[j].getAttribute("name"),c[j].getAttribute("value"));}}}
obj.parentNode.replaceChild(e,obj);}}
function fixObjectLeaks(id)
{if(ua.ie&&ua.win&&hasPlayerVersion("8.0.0"))
{win.attachEvent("onunload",function()
{});}}
function showInstallWindow()
{fv="MMredirectURL="+win.location;var ew=new Ext.Window({title:"Install Flash Player",width:"300",height:"300"});ew.on("render",function(ct,pos)
{Ext.Frs.SwfController.createSWF({data:"expressInstall.swf",width:"300px",height:"300px"},{flashvars:fv},this.body);},ew);ew.show();}
function createSWF(attObj,parObj,el){var r=null;if(ua.ie&&ua.win){var att="";for(var i in attObj){if(attObj[i]!=Object.prototype[i]){if(i=="data"){parObj.movie=attObj[i];}
else if(i.toLowerCase()=="styleclass"){att+=' class="'+attObj[i]+'"';}
else if(i!="classid"){att+=' '+i+'="'+attObj[i]+'"';}}}
if(!attObj["id"])att+=" id = "+Ext.id();var par="";for(var j in parObj){if(parObj[j]!=Object.prototype[j]){par+='<param name="'+j+'" value="'+parObj[j]+'" />';}}
var ohtml='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+att+'>'+par+'</object>'
r=el.insertHtml('afterBegin',ohtml,true);r=r.dom;fixObjectLeaks(r.id);}
else
{var o=createElement(OBJECT);o.setAttribute("type",FLASH_MIME_TYPE);for(var m in attObj){if(attObj[m]!=Object.prototype[m]){if(m.toLowerCase()=="styleclass"){o.setAttribute("class",attObj[m]);}
else if(m!="classid"){o.setAttribute(m,attObj[m]);}}}
for(var n in parObj){if(parObj[n]!=Object.prototype[n]&&n!="movie"){createObjParam(o,n,parObj[n]);}}
el.dom.appendChild(o);r=o;}
return r;}
function createObjParam(el,pName,pValue){var p=createElement("param");p.setAttribute("name",pName);p.setAttribute("value",pValue);el.appendChild(p);}
function getElementById(id){return doc.getElementById(id);}
function createElement(el){return doc.createElement(el);}
function hasPlayerVersion(rv){var pv=ua.pv,v=rv.split(".");v[0]=parseInt(v[0],10);v[1]=parseInt(v[1],10);v[2]=parseInt(v[2],10);return(pv[0]>v[0]||(pv[0]==v[0]&&pv[1]>v[1])||(pv[0]==v[0]&&pv[1]==v[1]&&pv[2]>=v[2]))?true:false;}
return{embedSWF:function(src,el,width,height,version,loader,oVars,parObj,attObj){if(!src||!el||width==null||height==null||!version)return;width+="";height+="";if(hasPlayerVersion(version)){var att=attObj;Ext.apply(att,{data:src,width:width,height:height});var par=parObj?parObj:{};if(oVars){for(var i in oVars){if(oVars[i]!=Object.prototype[i]){if(typeof par.flashvars!=UNDEF){par.flashvars+="&"+i+"="+oVars[i];}
else{par.flashvars=i+"="+oVars[i];}}}}
return createSWF(att,par,el);}},showInstallWindow:function(){return showInstallWindow();},getFlashPlayerVersion:function(){return{major:ua.pv[0],minor:ua.pv[1],release:ua.pv[2]};},hasFlashPlayerVersion:hasPlayerVersion,createSWF:function(attObj,parObj,el){return createSWF(attObj,parObj,el);},createCSS:function(sel,decl){createCSS(sel,decl);},getQueryParamValue:function(param){var q=doc.location.search||doc.location.hash;if(param==null){return q;}
if(q){var pairs=q.substring(1).split("&");for(var i=0;i<pairs.length;i++){if(pairs[i].substring(0,pairs[i].indexOf("="))==param){return pairs[i].substring((pairs[i].indexOf("=")+1));}}}
return"";},destroySWF:function(o){if(Ext.isIE){for(var i in o){if(typeof o[i]=="function"){o[i]=null;}}}
if(o&&o.parentNode)o.parentNode.removeChild(o);}};}(); 

if("object"!=typeof IPCM)IPCM={};if(!IPCM.JSON){IPCM.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.json2toJSON!=='function'){Date.prototype.json2toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.json2toJSON=Number.prototype.json2toJSON=Boolean.prototype.json2toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.json2toJSON==='function'){value=value.json2toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof IPCM.JSON.stringify!=='function'){IPCM.JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('IPCM.JSON.stringify');}
return str('',{'':value});};}
if(typeof IPCM.JSON.parse!=='function'){IPCM.JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('IPCM.JSON.parse');};}})(); 

var MD5=function(string){function RotateLeft(lValue,iShiftBits){return(lValue<<iShiftBits)|(lValue>>>(32-iShiftBits));}
function AddUnsigned(lX,lY){var lX4,lY4,lX8,lY8,lResult;lX8=(lX&0x80000000);lY8=(lY&0x80000000);lX4=(lX&0x40000000);lY4=(lY&0x40000000);lResult=(lX&0x3FFFFFFF)+(lY&0x3FFFFFFF);if(lX4&lY4){return(lResult^0x80000000^lX8^lY8);}
if(lX4|lY4){if(lResult&0x40000000){return(lResult^0xC0000000^lX8^lY8);}else{return(lResult^0x40000000^lX8^lY8);}}else{return(lResult^lX8^lY8);}}
function F(x,y,z){return(x&y)|((~x)&z);}
function G(x,y,z){return(x&z)|(y&(~z));}
function H(x,y,z){return(x^y^z);}
function I(x,y,z){return(y^(x|(~z)));}
function FF(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(F(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function GG(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(G(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function HH(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(H(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function II(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(I(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function ConvertToWordArray(string){var lWordCount;var lMessageLength=string.length;var lNumberOfWords_temp1=lMessageLength+8;var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1%64))/64;var lNumberOfWords=(lNumberOfWords_temp2+1)*16;var lWordArray=Array(lNumberOfWords-1);var lBytePosition=0;var lByteCount=0;while(lByteCount<lMessageLength){lWordCount=(lByteCount-(lByteCount%4))/4;lBytePosition=(lByteCount%4)*8;lWordArray[lWordCount]=(lWordArray[lWordCount]|(string.charCodeAt(lByteCount)<<lBytePosition));lByteCount++;}
lWordCount=(lByteCount-(lByteCount%4))/4;lBytePosition=(lByteCount%4)*8;lWordArray[lWordCount]=lWordArray[lWordCount]|(0x80<<lBytePosition);lWordArray[lNumberOfWords-2]=lMessageLength<<3;lWordArray[lNumberOfWords-1]=lMessageLength>>>29;return lWordArray;};function WordToHex(lValue){var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;for(lCount=0;lCount<=3;lCount++){lByte=(lValue>>>(lCount*8))&255;WordToHexValue_temp="0"+lByte.toString(16);WordToHexValue=WordToHexValue+WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);}
return WordToHexValue;};function Utf8Encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;};var x=Array();var k,AA,BB,CC,DD,a,b,c,d;var S11=7,S12=12,S13=17,S14=22;var S21=5,S22=9,S23=14,S24=20;var S31=4,S32=11,S33=16,S34=23;var S41=6,S42=10,S43=15,S44=21;string=Utf8Encode(string);x=ConvertToWordArray(string);a=0x67452301;b=0xEFCDAB89;c=0x98BADCFE;d=0x10325476;for(k=0;k<x.length;k+=16){AA=a;BB=b;CC=c;DD=d;a=FF(a,b,c,d,x[k+0],S11,0xD76AA478);d=FF(d,a,b,c,x[k+1],S12,0xE8C7B756);c=FF(c,d,a,b,x[k+2],S13,0x242070DB);b=FF(b,c,d,a,x[k+3],S14,0xC1BDCEEE);a=FF(a,b,c,d,x[k+4],S11,0xF57C0FAF);d=FF(d,a,b,c,x[k+5],S12,0x4787C62A);c=FF(c,d,a,b,x[k+6],S13,0xA8304613);b=FF(b,c,d,a,x[k+7],S14,0xFD469501);a=FF(a,b,c,d,x[k+8],S11,0x698098D8);d=FF(d,a,b,c,x[k+9],S12,0x8B44F7AF);c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);a=FF(a,b,c,d,x[k+12],S11,0x6B901122);d=FF(d,a,b,c,x[k+13],S12,0xFD987193);c=FF(c,d,a,b,x[k+14],S13,0xA679438E);b=FF(b,c,d,a,x[k+15],S14,0x49B40821);a=GG(a,b,c,d,x[k+1],S21,0xF61E2562);d=GG(d,a,b,c,x[k+6],S22,0xC040B340);c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);b=GG(b,c,d,a,x[k+0],S24,0xE9B6C7AA);a=GG(a,b,c,d,x[k+5],S21,0xD62F105D);d=GG(d,a,b,c,x[k+10],S22,0x2441453);c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);b=GG(b,c,d,a,x[k+4],S24,0xE7D3FBC8);a=GG(a,b,c,d,x[k+9],S21,0x21E1CDE6);d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);c=GG(c,d,a,b,x[k+3],S23,0xF4D50D87);b=GG(b,c,d,a,x[k+8],S24,0x455A14ED);a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);d=GG(d,a,b,c,x[k+2],S22,0xFCEFA3F8);c=GG(c,d,a,b,x[k+7],S23,0x676F02D9);b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);a=HH(a,b,c,d,x[k+5],S31,0xFFFA3942);d=HH(d,a,b,c,x[k+8],S32,0x8771F681);c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);a=HH(a,b,c,d,x[k+1],S31,0xA4BEEA44);d=HH(d,a,b,c,x[k+4],S32,0x4BDECFA9);c=HH(c,d,a,b,x[k+7],S33,0xF6BB4B60);b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);d=HH(d,a,b,c,x[k+0],S32,0xEAA127FA);c=HH(c,d,a,b,x[k+3],S33,0xD4EF3085);b=HH(b,c,d,a,x[k+6],S34,0x4881D05);a=HH(a,b,c,d,x[k+9],S31,0xD9D4D039);d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);b=HH(b,c,d,a,x[k+2],S34,0xC4AC5665);a=II(a,b,c,d,x[k+0],S41,0xF4292244);d=II(d,a,b,c,x[k+7],S42,0x432AFF97);c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);b=II(b,c,d,a,x[k+5],S44,0xFC93A039);a=II(a,b,c,d,x[k+12],S41,0x655B59C3);d=II(d,a,b,c,x[k+3],S42,0x8F0CCC92);c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);b=II(b,c,d,a,x[k+1],S44,0x85845DD1);a=II(a,b,c,d,x[k+8],S41,0x6FA87E4F);d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);c=II(c,d,a,b,x[k+6],S43,0xA3014314);b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);a=II(a,b,c,d,x[k+4],S41,0xF7537E82);d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);c=II(c,d,a,b,x[k+2],S43,0x2AD7D2BB);b=II(b,c,d,a,x[k+9],S44,0xEB86D391);a=AddUnsigned(a,AA);b=AddUnsigned(b,BB);c=AddUnsigned(c,CC);d=AddUnsigned(d,DD);}
var temp=WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);return temp.toLowerCase();} 

var cstaRequestId=0;CstaLib_ForwardingType_Enum={forwardImmediate:"forwardImmediate",forwardBusy:"forwardBusy",forwardNoAns:"forwardNoAns",forwardUnreacheable:"forwardUnreacheable"};CstaLib_ConsultOptions_Enum={unrestricted:"unrestricted",consultOnly:"consultOnly",transferOnly:"transferOnly",conferenceOnly:"conferenceOnly"};CstaLib_CallControlEvents_Enum={none:"none",reserved:"reserved",bridged:"BridgedEvent",callCleared:"CallClearedEvent",conferenced:"ConferencedEvent",connectionCleared:"ConnectionClearedEvent",delivered:"DeliveredEvent",digitsDialed:"DigitsDialedEvent",diverted:"DivertedEvent",established:"EstablishedEvent",failed:"FailedEvent",held:"HeldEvent",networkCapabilitiesChanged:"NetworkCapabilitiesChangedEvent",networkReached:"NetworkReachedEvent",offered:"OfferedEvent",originated:"OriginatedEvent",queued:"QueuedEvent",retrieved:"RetrievedEvent",serviceInitiated:"ServiceInitiatedEvent",transferred:"TransferedEvent",conferenced:"ConferencedEvent",deviceCapsChanged:"DeviceCapsChangedEvent"};CstaLib_RequestType_Enum={failure:"CSTAErrorCode",cstaFeatures:"GetCSTAFeatures",monitorStart:"MonitorStart",snapshotDevice:"SnapshotDevice",clearConnection:"ClearConnection",makeCall:"MakeCall",consultationCall:"ConsultationCall",transferCall:"TransferCall",sstepTransferCall:"SingleStepTransferCall",snapshotCall:"SnapshotCall",getForwarding:"GetForwarding",getDND:"GetDND",getMWI:"GetMWI",parkCall:"ParkCall",groupPickupCall:"GroupPickupCall",directedPickupCall:"DirectedPickupCall",monitorStop:"MonitorStop",deflectCall:"DeflectCall",holdCall:"HoldCall",retrieveCall:"RetrieveCall",alternateCall:"AlternateCall",answerCall:"AnswerCall",generateDigits:"GenerateDigits",associateData:"AssociateData",sendUserInformation:"SendUserInformation",setForwarding:"SetForwarding",setDND:"SetDND",getSystemStatus:"RequestSystemStatus",recordMessage:"RecordMessage",stop:"Stop",conferenceCall:"ConferenceCall",sstepConferenceCall:"SingleStepConferenceCall",max:35};function normalizeDN(deviceNumber){if(deviceNumber.indexOf(":")==-1)
deviceNumber="tel:"+deviceNumber;return deviceNumber;}
function CstaConnectionId(callId,deviceId){this.callID=callId;this.deviceID=normalizeDN(deviceId);}
function CstaLibAppAssociation(){this.username=null;this.authUsername=null;this.authPassword=null;this.realm=null;this.nonce=null;this.loginAttempts=0;this.onCstaResponse=function(origRequest,response){};this.onCstaRequest=function(request){};this.onCstaEvent=function(event){};this.onCstaServerDisconnected=function(){};this.onCstaServerConnected=function(){};this.onCstaLoginFailed=function(message){};this.onCstaLoginSuccess=function(message){};}
function CstaLib(logFunction){this.me='csta'+Math.floor(Math.random()*9999);this.party="sipcsta";this.log=logFunction;this.connected=false;this.loggedIn=true;this.clientCallback=null;this.requests=new Array();this.Login=function(oCstaLoginRequest)
{if(this.clientCallback!=null){this.Logout(this.clientCallback);}
this.clientCallback=oCstaLoginRequest.oCstaAppAssociation;this.clientCallback.username=oCstaLoginRequest.sUsername;this.clientCallback.authUsername=oCstaLoginRequest.sAuthUsername;this.clientCallback.authPassword=oCstaLoginRequest.sAuthPassword;this.clientCallback.loginAttempts=0;if(this.connected)
this.sendClientLogin();};this.sendRequest=function(cstaRequest){if(!this.loggedIn)
return false;this.requests.push(cstaRequest);this.send(IPCM.JSON.stringify(new CstaRequest(cstaRequest)));return true;}
this.sendClientLogin=function(){var loginRequest=null;var now=(new Date()).toString();if(this.clientCallback.realm==null){loginRequest={"login":{"user":this.clientCallback.username,"digest":"","date":now,"nonce":now,"realm":"a"}};}
else{var a1=this.clientCallback.authUsername+":"+this.clientCallback.realm+":"+this.clientCallback.authPassword;var digest=MD5(MD5(a1)+":"+this.clientCallback.nonce);loginRequest={"login":{"user":this.clientCallback.username,"digest":digest,"date":now,"nonce":this.clientCallback.nonce,"realm":this.clientCallback.realm}};}
this.send(IPCM.JSON.stringify(loginRequest));};this.Logout=function(oCstaAppAssociation){this.clientCallback=null;};this.onConnected=function()
{this.log("CstaLib::onConnected");this.connected=true;this.loggedIn=true;if(this.clientCallback!=null){this.clientCallback.onCstaServerConnected();}};this.onDisconnected=function()
{this.log("CstaLib::onDisconnected");this.connected=false;this.loggedIn=false;this.requests=new Array();if(this.clientCallback!=null){this.clientCallback.onCstaServerDisconnected();}};this.onData=function(data){this.log("CstaLib::onData"+data);if(!this.loggedIn){var loginResponse=eval('('+data+')');if("result"in loginResponse){if(loginResponse.result){this.loggedIn=true;if(this.clientCallback!=null){this.clientCallback.loginAttempts=0;this.clientCallback.onCstaLoginSuccess(loginResponse.srv);}}
else{if(++this.clientCallback.loginAttempts==3||!("realm"in loginResponse)){if(this.clientCallback!=null){var theClientCallback=this.clientCallback;this.clientCallback=null;theClientCallback.onCstaLoginFailed(loginResponse.error);}}
else if(this.clientCallback!=null&&"realm"in loginResponse){this.clientCallback.realm=loginResponse.realm;this.clientCallback.nonce=loginResponse.nonce;this.sendClientLogin();}}}}
else{var re=eval('('+data+')');if("rs"in re){var rsp=re.rs;var rid=rsp.id;for(var i=0;i<this.requests.length;++i){if(this.requests[i].id==rid){var request=this.requests[i];this.requests.splice(i,1);if(this.clientCallback!=null){this.clientCallback.onCstaResponse(request,rsp);}
break;}}}
else if("ev"in re){if(this.clientCallback!=null){this.clientCallback.onCstaEvent(re.ev);}}
else if("rq"in re){if(this.clientCallback!=null){this.clientCallback.onCstaRequest(re.rq);}}}};this.send=function(data){var fproxy=window.fproxy?window.fproxy:document.getElementById('fproxy');fproxy.endpointSend(this.me,this.party,data);};}
function CstaLoginRequest(sUsername,sAuthUsername,sAuthPassword,oCstaAppAssociation){this.sUsername=sUsername;this.sAuthUsername=sAuthUsername;this.sAuthPassword=sAuthPassword;this.oCstaAppAssociation=oCstaAppAssociation;}
function CstaRequest(request){this.rq=request;}
function CstaRequestSystemStatus(){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.systemStatus;}
function CstaRequestGetCSTAFeatures(){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.cstaFeatures;}
function CstaRequestMonitorStart(deviceId,generateDeviceCapsEvent){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.monitorStart;this.extensions={"privateData":{"private":{"deviceCapsEvent":generateDeviceCapsEvent}}};this.monitorObject={"deviceObject":normalizeDN(deviceId)};}
function CstaRequestMakeCall(callingDevice,calledDirectoryNumber,callSubject){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.makeCall;this.callingDevice={"mediaClass":"voice","typeOfNumber":"dialingNumber","deviceObject":normalizeDN(callingDevice)};this.calledDirectoryNumber={"mediaClass":"voice","typeOfNumber":"dialingNumber","deviceObject":normalizeDN(calledDirectoryNumber)};this.autoOriginate="doNotPrompt";this.subjectOfCall=callSubject;}
function CstaRequestClearConnection(connectionId){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.clearConnection;this.connectionToBeCleared=connectionId;}
function CstaRequestAnswerCall(callToBeAnswered){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.answerCall;this.callToBeAnswered=callToBeAnswered;}
function CstaRequestDeflectCall(callToBeDiverted,newDestination,subjectOfCall){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.deflectCall;this.callToBeDiverted=callToBeDiverted;this.newDestination=normalizeDN(newDestination);this.subjectOfCall=subjectOfCall;}
function CstaRequestSetForwarding(deviceId,forwardDN,forwardingTypeEnumValue,ringCount,activate){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.setForwarding;this.device=deviceId;this.forwardingType=forwardingTypeEnumValue;this.activateForward=new Boolean(activate);this.forwardDN=forwardDN;this.ringCount=ringCount;}
function CstaRequestHoldCall(callToBeHeld){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.holdCall;this.callToBeHeld=callToBeHeld;}
function CstaRequestRetrieveCall(callToBeRetrieved){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.retrieveCall;this.callToBeRetrieved=callToBeRetrieved;}
function CstaRequestAlternateCall(heldCall,activeCall){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.alternateCall;this.heldCall=heldCall;this.activeCall=activeCall;}
function CstaRequestTransferCall(heldCall,activeCall){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.transferCall;this.heldCall=heldCall;this.activeCall=activeCall;}
function CstaRequestSingleStepTransferCall(activeCall,transferredToDeviceId,subjectOfCall){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.sstepTransferCall;this.activeCall=activeCall;this.transferredToDevice=transferredToDeviceId;this.subjectOfCall=subjectOfCall;}
function CstaRequestConsultationCall(existingCall,consultedDeviceId,consultOptionsEnumValue,subjectOfCall){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.consultationCall;this.existingCall=existingCall;this.consultedDevice=consultedDeviceId;this.consultOptions=consultOptionsEnumValue;this.subjectOfCall=subjectOfCall;}
function CstaRequestMonitorStop(monitorCrossRefID){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.monitorStop;this.monitorCrossRefID=monitorCrossRefID;}
function CstaRequestSnapshotDevice(deviceId){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.snapshotDevice;this.snapshotObject=deviceId;}
function CstaRequestGetForwarding(deviceId){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.getForwarding;this.device=deviceId;}
function CstaRequestConferenceCall(heldCall,activeCall,subjectOfCall,terminationType,conferenceType){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.conferenceCall;this.heldCall=heldCall;this.activeCall=activeCall;this.subjectOfCall=subjectOfCall;this.extensions={"privateData":{"private":{"termPolicy":terminationType,"confTypePolicy":conferenceType}}};}
function CstaRequestSingleStepConferenceCall(activeCall,deviceToJoin,subjectOfCall,terminationType,conferenceType){this.id=++cstaRequestId;this.type=CstaLib_RequestType_Enum.sstepConferenceCall;this.activeCall=activeCall;this.deviceToJoin={"mediaClass":"voice","typeOfNumber":"dialingNumber","deviceObject":normalizeDN(deviceToJoin)};this.subjectOfCall=subjectOfCall;this.extensions={"privateData":{"private":{"termPolicy":terminationType,"confTypePolicy":conferenceType}}};} 

if("object"!=typeof IPCM)IPCM={};IPCM.AgentCallbackPrototype=function(){};IPCM.AgentCallbackPrototype.prototype.connected=function(_agentControl){};IPCM.AgentCallbackPrototype.prototype.disconnected=function(_agentControl){};IPCM.AgentCallbackPrototype.prototype.agentLoginFailed=function(_agentControl,_message){};IPCM.AgentCallbackPrototype.prototype.stateChanged=function(_agentControl,_state,_reason,_acwtimeout){};IPCM.AgentCallbackPrototype.prototype.newInteraction=function(_agentControl,_iid){};IPCM.AgentCallbackPrototype.prototype.interactionData=function(_agentControl,_iid,_values){};IPCM.AgentCallbackPrototype.prototype.userExists=function(_agentControl,_exists){};IPCM.AgentCallbackPrototype.prototype.canLogin=function(_agentControl,_can,_dn){};IPCM.AgentCallbackPrototype.prototype.canGoReady=function(_agentControl,_can){};IPCM.AgentCallbackPrototype.prototype.canGoNotReady=function(_agentControl,_can,_reasons,_mandatoryReason){};IPCM.AgentCallbackPrototype.connected=function(_agentControl){};IPCM.AgentCallbackPrototype.disconnected=function(_agentControl){};IPCM.AgentCallbackPrototype.agentLoginFailed=function(_agentControl,_message){};IPCM.AgentCallbackPrototype.stateChanged=function(_agentControl,_state,_reason,_acwtimeout){};IPCM.AgentCallbackPrototype.newInteraction=function(_agentControl,_iid){};IPCM.AgentCallbackPrototype.interactionData=function(_agentControl,_iid,_values){};IPCM.AgentCallbackPrototype.userExists=function(_agentControl,_exists){};IPCM.AgentCallbackPrototype.canLogin=function(_agentControl,_can,_dn){};IPCM.AgentCallbackPrototype.canGoReady=function(_agentControl,_can){};IPCM.AgentCallbackPrototype.canGoNotReady=function(_agentControl,_can,_reasons,_mandatoryReason){};IPCM.DecodeBoolean=function(_value)
{var b=false;if("boolean"!=typeof _value)
{try
{b=Boolean(_value);}
catch(e)
{}}
else
b=_value;return b;};IPCM.NotReadyReason=function(_label,_available)
{if("string"!=typeof _label)
{this.label="";this.available=false;}
else
{this.label=_label;if("boolean"==typeof _available)
this.available=_available;else
this.available=false;}};IPCM.AGENT_STATE={UNKNOWN:0,LOGGED_OUT:1,NOT_READY:2,READY:3,RESERVED:4,BUSY:5,AFTER_CALL_WORK:6,WRAP_UP:6,FINAL:7};IPCM.AgentControl=function(_callback){this.Register=function(_user,_token){if(!this.endpointRegistered){var fproxy=window.fproxy?window.fproxy:document.getElementById('fproxy');this.user=_user;if("string"!=typeof(_token)||0==_token.length){_token=fproxy.getOpaqueToken();}
if("string"==typeof(_token)&&0!=_token.length)
this.me="agent:"+_token+":"+_user;else
this.me="agent:"+_user;fproxy.endpointRegister(this.me);fproxy.endpointConnect(this.me,this.party);this.endpointRegistered=true;}};this.Login=function(_dn){if(null!=this.user){if(this.endpointConnected)
if(this.UserOverrideDN){this.sendLoginRequest(this.UserOverrideDN);}else{this.sendLoginRequest(_dn);}
else{this.loginPending=true;}
this.loginDN=_dn;}};this.Logout=function(){var cmd={cmd:"agent_logout"};this.send(cmd);};this.SetReady=function(){var cmd={cmd:"agent_set_ready"};this.send(cmd);};this.SetNotReady=function(_reason){var cmd={cmd:"agent_set_not_ready",reason:_reason};this.send(cmd);};this.GetInteractionData=function(_iid,_names){var cmd={cmd:"get_interaction_data",interaction_id:_iid,names:_names};this.send(cmd);};this.send=function(_data){var fproxy=window.fproxy?window.fproxy:document.getElementById('fproxy');fproxy.endpointSend(this.me,this.party,IPCM.JSON.stringify(_data));}
this.sendLoginRequest=function(_dn){var cmd={cmd:"agent_login",userid:this.user,req_id:"ipcmLogin"};if("string"==typeof _dn)
cmd.phone=_dn;this.send(cmd);};this.onConnected=function(){this.endpointConnected=true;if("function"==typeof this.callback.connected)
this.callback.connected(this);if(this.loginPending){this.sendLoginRequest(this.loginDN);this.loginPending=false;this.loginDN=null;}};this.onDisconnected=function(){this.endpointConnected=false;this.loginPending=false;this.loginDN=null;if("function"==typeof this.callback.stateChanged)
this.callback.stateChanged(this,0,null,null);if("function"==typeof this.callback.canGoReady)
this.callback.canGoReady(this,false);if("function"==typeof this.callback.canGoNotReady)
this.callback.canGoNotReady(this,false,null,false);if("function"==typeof this.callback.canLogin)
this.callback.canLogin(this,false,null);if("function"==typeof this.callback.disconnected)
this.callback.disconnected(this);};this.onData=function(_data){var evt=IPCM.JSON.parse(_data),status,reason,acwtimeout,iid=null,rc=null,vals=null;switch(evt.event){case"agent_state_changed":if("number"!=typeof(status=evt["state"]))
status=Number(status);try{reason=evt["reason"];if(undefined==reason||("string"==typeof reason&&0==reason.length))
reason=null;}catch(e){reason=null;}
try{acwtimeout=evt["acw_timeout"];if(undefined==acwtimeout||("string"==typeof acwtimeout&&0==acwtimeout.length))
acwtimeout=null;}catch(e){acwtimeout=null;}
this.onAgentStateChanged(status,reason,acwtimeout);break;case"new_interaction":try{if(undefined==(iid=evt["int_id"]))
iid=null;}catch(e){}
if(null!=iid&&"function"==typeof this.callback.newInteraction)
this.callback.newInteraction(this,iid);break;case"interaction_data":try{if(undefined==(rc=evt["rc"]))
rc=null;else
rc=Number(rc);if(undefined==(vals=evt["values"]))
vald=null;}
catch(e){rc=null;vals=null;}
if(null!=rc&&"function"==typeof this.callback.interactionData)
this.callback.interactionData(this,rc,vals);break;case"not_ready_reasons":try{var reasons=evt.reasons,required=evt.required;switch(typeof required){case"string":required=required=="true";break;case"boolean":break;default:required=false;break;}
if("object"!=typeof reasons||0==reasons.length){reasons=null;required=false;}
this.onNotReadyReasonsReceived(reasons,required);}
catch(e){this.onNotReadyReasonsReceived(null,false);}
break;case"user_info":this.onUserInformationReceived(evt);break;case"error":this.onErrorReceived(evt);break;}};this.onNotReadyReasonsReceived=function(_reasons,_mandatory){this.reasons=_reasons;this.reasonIsMandatory=_mandatory;};this.onAgentStateChanged=function(_state,_reason,_acwtimeout){if("function"==typeof this.callback.stateChanged)
this.callback.stateChanged(this,_state,_reason,_acwtimeout);switch(_state){case IPCM.AGENT_STATE.READY:if("function"==typeof this.callback.canGoNotReady)
this.callback.canGoNotReady(this,true,this.buildReasons(_reason),this.reasonIsMandatory);if("function"==typeof this.callback.canGoReady)
this.callback.canGoReady(this,false);break;case IPCM.AGENT_STATE.NOT_READY:if("function"==typeof this.callback.canGoNotReady)
this.callback.canGoNotReady(this,this.isNotReadyAvailable(_reason),this.buildReasons(_reason),this.reasonIsMandatory);if("function"==typeof this.callback.canGoReady)
this.callback.canGoReady(this,true);break;case IPCM.AGENT_STATE.AFTER_CALL_WORK:if("function"==typeof this.callback.canGoNotReady)
this.callback.canGoNotReady(this,true,this.buildReasons(_reason),this.reasonIsMandatory);if("function"==typeof this.callback.canGoReady)
this.callback.canGoReady(this,true);break;default:if("function"==typeof this.callback.canGoNotReady)
this.callback.canGoNotReady(this,false,this.buildReasons(_reason),this.reasonIsMandatory);if("function"==typeof this.callback.canGoReady)
this.callback.canGoReady(this,false);break;}};this.onErrorReceived=function imOnErrorReceived(_event){if("string"==typeof _event.req_id)switch(_event.req_id){case"ipcmLogin":if("function"==typeof this.callback.agentLoginFailed)
this.callback.agentLoginFailed(undefined==_event.msg?null:_event.msg);break;}};this.onUserInformationReceived=function(_event){var dn=null,isAgent=IPCM.DecodeBoolean(_event.is_agent),isUser=IPCM.DecodeBoolean(_event.is_user);if("string"==typeof _event.phone)
dn=_event.phone;if("function"==typeof this.callback.userExists)
this.callback.userExists(this,isUser);if(isUser&&"function"==typeof this.callback.canLogin)
this.callback.canLogin(this,isAgent,dn);};this.buildReasons=function(_currentReason){var reasons=null,i;if(null!=this.reasons&&0!=this.reasons.length){reasons=new Array();for(i=0;i<this.reasons.length;++i){var reasonAvailable=true;if("string"==typeof _currentReason&&_currentReason==this.reasons[i])
reasonAvailable=false;reasons[i]=new IPCM.NotReadyReason(this.reasons[i],reasonAvailable);}}
return reasons;};this.isNotReadyAvailable=function(_currentReason){var available=true;if(null==this.reasons||(1==this.reasons.length&&this.reasons[0]==_currentReason&&this.reasonIsMandatory))
available=false;return available;};this.callback=_callback;this.reasons=null;this.reasonIsMandatory=false;this.user=null;this.party="Server:IPCM_Server";this.me=null;this.endpointRegistered=false;this.endpointConnected=false;this.loginPending=false;this.loginDN=null;fproxyRegisterEndpoint(this);}; 

var fproxyRegistry=new Array();var fproxyReconnectTimer=null;function _fproxyOnReconnectTimer()
{fproxyReconnectTimer=null;if(typeof fproxyOnReconnectTimer=='function')fproxyOnReconnectTimer();}
function fproxyStartReconnectTimer()
{if(fproxyReconnectTimer!=null)clearTimeout(fproxyReconnectTimer);fproxyReconnectTimer=setTimeout("_fproxyOnReconnectTimer()",1000);}
function fproxyRegisterEndpoint(ep)
{fproxyRegistry.push(ep);}
function fproxyFindEndpoint(me,party)
{for(i=0;i<fproxyRegistry.length;i++)
if(fproxyRegistry[i].me==me&&fproxyRegistry[i].party==party)
return fproxyRegistry[i];return null;}
function _fproxyLog(str)
{if(typeof fproxyLog=='function')fproxyLog(str);}
function _fproxyOnLoad()
{_fproxyLog(String.format('fproxy: loaded'));if(typeof fproxyOnLoad=='function')fproxyOnLoad();}
function _fproxyOnTransportServerConnected(username,privileges)
{_fproxyLog('fproxy: server connected and auth accepted');if(typeof fproxyOnTransportServerConnected=='function')
fproxyOnTransportServerConnected(username,privileges);for(i=0;i<fproxyRegistry.length;i++)
{fproxy.endpointRegister(fproxyRegistry[i].me);fproxy.endpointConnect(fproxyRegistry[i].me,fproxyRegistry[i].party);}}
function _fproxyOnTransportServerAuthRejected()
{_fproxyLog('fproxy: auth rejected');fproxy.disconnectFromServer();fproxyStartReconnectTimer();if(typeof fproxyOnTransportServerAuthRejected=='function')fproxyOnTransportServerAuthRejected();}
function _fproxyOnTransportServerDisconnected()
{fproxy.disconnectFromServer();fproxyStartReconnectTimer();_fproxyLog('fproxy: server disconnected');for(i=0;i<fproxyRegistry.length;i++)
fproxyRegistry[i].onDisconnected();if(typeof fproxyOnTransportServerDisconnected=='function')fproxyOnTransportServerDisconnected();}
function _fproxyOnTransportIOError()
{fproxy.disconnectFromServer();fproxyStartReconnectTimer();_fproxyLog('fproxy: io error');if(typeof fproxyOnTransportIOError=='function')fproxyOnTransportIOError();}
function _fproxyOnTransportSecurityError()
{fproxy.disconnectFromServer();fproxyStartReconnectTimer();_fproxyLog('fproxy: security error');if(typeof fproxyOnTransportSecurityError=='function')fproxyOnTransportSecurityError();}
function _fproxyOnEndpointConnected(me,party)
{if(me=='')
{_fproxyLog(String.format('fproxy: server available: {0}',party));if(typeof fproxyOnServerAvailable=='function')fproxyOnServerAvailable(party);}
else
{_fproxyLog(String.format('fproxy: endpoint connected: {0} {1}',me,party));var ep=fproxyFindEndpoint(me,party);if(ep)ep.onConnected();}}
function _fproxyOnEndpointDisconnected(me,party)
{if(me=='')
{_fproxyLog(String.format('fproxy: server unavailable: {0}',party));if(typeof fproxyOnServerUnavailable=='function')fproxyOnServerUnavailable(party);}
else
{_fproxyLog(String.format('fproxy: endpoint disconnected: {0} {1}',me,party));var ep=fproxyFindEndpoint(me,party);if(ep)ep.onDisconnected();}}
function _fproxyOnEndpointData(me,party,data)
{_fproxyLog(String.format('fproxy: endpoint data received: {0} {1} {2}',me,party,data));var ep=fproxyFindEndpoint(me,party);if(ep)ep.onData(data);} 

if("object"!=typeof IPCM)IPCM={};IPCM.CALL_STATE={IDLE:0,DIALING:1,ALERTED:2,RINGING:3,ESTABLISHED:4,HELD:5,HELD_LOCALLY:6};IPCM.CallStateIndex=function(){this.states=new Array();this.states.push(IPCM.CALL_STATE.RINGING);this.states.push(IPCM.CALL_STATE.DIALING);this.states.push(IPCM.CALL_STATE.ALERTED);this.states.push(IPCM.CALL_STATE.ESTABLISHED);this.states.push(IPCM.CALL_STATE.HELD_LOCALLY);this.states.push(IPCM.CALL_STATE.HELD);this.getStateIndex=function(_state){var index=null,i;for(i=0;null==index&&i<this.states.length;++i){if(_state==this.states[i])
index=i;}
return index;}};IPCM.CALL_DIRECTION={UNKNOWN:"unknown",IN:"in",OUT:"out"};IPCM.CALL_CONTROL={HANG_UP:0x001,ANSWER:0x002,HOLD:0x004,RETRIEVE:0x008,TRANSFER:0x010,COMPLETE:0x020,DIAL_CONSULT:0x040,DIAL:0x080,ALTERNATE:0x100,SWAP:0x200,CONFERENCE:0x400,SSTEPCONFERENCE:0x800};IPCM.RetrieveDeviceNumber=function(_devId){var colonIndex=_devId.indexOf("tel:");if(0==colonIndex){_devId=_devId.substr(4);}
return _devId;}
IPCM.SubjectString=function(_subject)
{return"string"!=typeof _subject?"":_subject;};IPCM.ExtractDisplayName=function(_event,_item)
{var name=null;try
{if("string"!=typeof(name=_event.correlatorData["private"].ipcm[_item])||""==name)
name=null;}
catch(e)
{}
return name;};IPCM.CallControlCallbackPrototype=function(){};IPCM.CallControlCallbackPrototype.prototype.onLoginFailed=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.onMonitorStarted=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canHangUp=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canAnswer=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canHold=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canRetrieve=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canTransfer=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canComplete=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canDialConsult=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canDial=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canAlternate=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.displayCall=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canConferSingleStep=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.canSetUpConference=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.prototype.onCallInserted=function(_call){};IPCM.CallControlCallbackPrototype.prototype.onCallRemoved=function(_call){};IPCM.CallControlCallbackPrototype.prototype.onCallEstablished=function(_call){};IPCM.CallControlCallbackPrototype.onLoginFailed=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.onMonitorStarted=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canHangUp=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canAnswer=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canHold=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canRetrieve=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canTransfer=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canComplete=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canDialConsult=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canDial=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canAlternate=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.displayCall=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.canSetUpConference=function(_callControl,_arg){};IPCM.CallControlCallbackPrototype.onCallInserted=function(_call){};IPCM.CallControlCallbackPrototype.onCallRemoved=function(_call){};IPCM.CallControlCallbackPrototype.onCallEstablished=function(_call){};IPCM.CstaCall=function(_connection,_direction){this.myConnection=_connection;this.remoteDeviceID=null;this.remoteName=null;this.displayName="";this.direction=_direction;this.state=IPCM.CALL_STATE.IDLE;this.stateVersion=new Date();this.capabilities=IPCM.CALL_CONTROL.HANG_UP;this.holdingDevices=new Array();this.isActive=function(){return IPCM.CALL_STATE.IDLE!=this.state;};this.HangUp=function imHangUp(_frCallControl){_frCallControl.cstaLib.sendRequest(new CstaRequestClearConnection(this.myConnection));};this.Answer=function imAnswer(_frCallControl){_frCallControl.cstaLib.sendRequest(new CstaRequestAnswerCall(this.myConnection));};this.Hold=function imHold(_frCallControl){_frCallControl.cstaLib.sendRequest(new CstaRequestHoldCall(this.myConnection));};this.Retrieve=function imRetrieve(_frCallControl){_frCallControl.cstaLib.sendRequest(new CstaRequestRetrieveCall(this.myConnection));};this.Alternate=function imAlternate(_frCallControl,_frAlternateCall){var sendRequest=true;if(null!=_frCallControl.monitor&&_frCallControl.monitor.alternateCallsOnClient()){sendRequest=false;_frCallControl.updateUI();}
if(sendRequest)
_frCallControl.cstaLib.sendRequest(new CstaRequestAlternateCall(this.myConnection,_frAlternateCall.myConnection));};this.setState=function(_newState){if(_newState!=this.state){this.state=_newState;this.stateVersion=new Date();}};this.updateCapabilities=function(_event){if(undefined!=_event.servicesPermitted){var capable;this.capabilities=IPCM.CALL_STATE.IDLE!=this.state?IPCM.CALL_CONTROL.HANG_UP:0;try{capable=String(_event.servicesPermitted.callControlServices.answerCall);if(capable=="true")
this.capabilities|=IPCM.CALL_CONTROL.ANSWER;}
catch(e){}
try{capable=String(_event.servicesPermitted.callControlServices.holdCall);if(capable=="true")
this.capabilities|=IPCM.CALL_CONTROL.HOLD;}
catch(e){}
try{capable=String(_event.servicesPermitted.callControlServices.retrieveCall);if(capable=="true")
this.capabilities|=IPCM.CALL_CONTROL.RETRIEVE;}
catch(e){}
try{capable=String(_event.servicesPermitted.callControlServices.alternateCall);if(capable=="true")
this.capabilities|=IPCM.CALL_CONTROL.ALTERNATE;}
catch(e){}}};this.addHoldingDevice=function(_deviceID){var found=false;for(dev in this.holdingDevices){if(dev==_deviceID){found=true;break;}}
if(!found)
this.holdingDevices.push(_deviceID);};this.removeHoldingDevice=function(_deviceID){for(i=0;i<this.holdingDevices.length;++i){if(this.holdingDevices[i]==_deviceID){this.holdingDevices.splice(i,1);break;}}
return 0==this.holdingDevices.length;};this.applySnapshot=function(_snapshot){if(_snapshot.localCallState.compoundCallState.localConnectionState[1]=="alerting"){this.remoteDeviceID=_snapshot.endpointDevice.deviceIdentifier;this.setState(IPCM.CALL_STATE.DIALING);this.updateDisplayName();}
else{this.remoteDeviceID=_snapshot.endpointDevice.deviceIdentifier;this.updateDisplayName();if(_snapshot.localCallState.compoundCallState.localConnectionState[0]=="alerting")
this.setState(IPCM.CALL_STATE.RINGING);else if(_snapshot.localCallState.compoundCallState.localConnectionState[1]=="hold")
this.setState(IPCM.CALL_STATE.HELD);else if(_snapshot.localCallState.compoundCallState.localConnectionState[0]=="hold")
this.setState(IPCM.CALL_STATE.HELD_LOCALLY);else
this.setState(IPCM.CALL_STATE.ESTABLISHED);}
if(_snapshot.localCallState.compoundCallState.localConnectionState[1]=="hold")
this.addHoldingDevice(_snapshot.endpointDevice.deviceIdentifier);if(_snapshot.localCallState.compoundCallState.localConnectionState[0]=="hold")
this.addHoldingDevice(this.myConnection.deviceID);try{switch(_snapshot.extensions.privateData.private.ipcm.flow){case"outgoing":this.direction=IPCM.CALL_DIRECTION.OUT;this.remoteName=_snapshot.extensions.privateData.private.ipcm.to;this.updateDisplayName();break;case"incoming":this.direction=IPCM.CALL_DIRECTION.IN;this.remoteName=_snapshot.extensions.privateData.private.ipcm.from;this.updateDisplayName();break;}}
catch(e){}
this.updateCapabilities(_snapshot);};this.onOriginated=function(_event,_monitor){this.remoteDeviceID=_event.calledDevice.deviceIdentifier;try{this.remoteName=IPCM.ExtractDisplayName(_event,"to");this.updateDisplayName();}
catch(e){}
this.updateCapabilities(_event);this.setState(IPCM.CALL_STATE.DIALING);};this.onDelivered=function(_event,_monitor){if(this.isActive()){this.remoteDeviceID=_event.calledDevice.deviceIdentifier;this.setState(IPCM.CALL_STATE.ALERTED);}
else{this.remoteDeviceID=_event.callingDevice.deviceIdentifier;this.setState(IPCM.CALL_STATE.RINGING);try{this.remoteName=IPCM.ExtractDisplayName(_event,"from");this.updateDisplayName();}
catch(e){}}
this.updateCapabilities(_event);};this.onConnectionCleared=function(_event,_monitor){if(("string"==typeof _event.localConnectionInfo&&"null"==_event.localConnectionInfo)||_monitor.isMyDevice(_event.droppedConnection.deviceID))
this.setState(IPCM.CALL_STATE.IDLE);else
this.updateCapabilities(_event);};this.onTransfered=function(_event,_monitor){if("string"!=typeof _event.localConnectionInfo||"null"==_event.localConnectionInfo){this.setState(IPCM.CALL_STATE.IDLE);}
else{if(_event.transferredToDevice.deviceIdentifier!=this.remoteDeviceID){this.remoteDeviceID=_event.transferredToDevice.deviceIdentifier;this.remoteName=null;this.updateDisplayName();}
for(i=0;i<_event.transferredConnections.connectionListItem.length;++i){var item=_event.transferredConnections.connectionListItem[i];if(_monitor.isMyDevice(item.newConnection.deviceID)){this.myConnection=item.newConnection;}
else{this.remoteDeviceID=item.newConnection.deviceID;this.remoteName=null;this.updateDisplayName();}}
this.updateCapabilities(_event);}};this.onDiverted=function(_event,_monitor){if(("string"==typeof _event.localConnectionInfo&&"null"==_event.localConnectionInfo)||_monitor.isMyDevice(_event.connection.deviceID))
this.setState(IPCM.CALL_STATE.IDLE);else
this.updateCapabilities(_event);};this.onEstablished=function(_event,_monitor){this.setState(IPCM.CALL_STATE.ESTABLISHED);this.updateCapabilities(_event);};this.onHeld=function(_event,_monitor){this.addHoldingDevice(_event.holdingDevice.deviceIdentifier);if(_monitor.isMyDevice(_event.holdingDevice.deviceIdentifier))
this.setState(IPCM.CALL_STATE.HELD_LOCALLY);else if(IPCM.CALL_STATE.HELD_LOCALLY!=this.state)
this.setState(IPCM.CALL_STATE.HELD);this.updateCapabilities(_event);};this.onRetrieved=function(_event,_monitor){var remoteHold=!_monitor.isMyDevice(_event.retrievingDevice.deviceIdentifier),oldCaps=0;if(this.removeHoldingDevice(_event.retrievingDevice.deviceIdentifier))
this.setState(IPCM.CALL_STATE.ESTABLISHED);else{if(_event.localConnectionInfo!="hold")
this.setState(IPCM.CALL_STATE.HELD);}
this.updateCapabilities(_event);};this.onConferenced=function(_event,_monitor){this.setState(IPCM.CALL_STATE.ESTABLISHED);this.displayName="Conference";this.updateCapabilities(_event);};this.initFromConference=function(_event){this.remoteDeviceID=_event.conferencingDevice.deviceIdentifier;this.direction=IPCM.CALL_DIRECTION.OUT;};this.updateDisplayName=function(){var name=null,dev=null;if(null!=this.remoteName&&0!=this.remoteName.length)
name=this.remoteName;if(null!=this.remoteDeviceID&&0!=this.remoteDeviceID.length)
dev=IPCM.RetrieveDeviceNumber(this.remoteDeviceID);if(null!=name&&null!=dev)
this.displayName=name+" ("+dev+")";else if(null!=name)
this.displayName=name;else if(null!=dev)
this.displayName=dev;else
this.displayName="";};};IPCM.CstaMonitor=function(_monitorID,_deviceID,_callback){this.monitorID=_monitorID;this.deviceID=_deviceID;this.calls=new Array();this.capabilities=0;this.deviceCapabilities=0;this.activeCallIndex=null;this.heldCallsAlternated=false;this.callback=_callback;this.csi=null;this.isMyEvent=function(_event){return _event.monitorCrossRefID==this.monitorID;}
this.isMyDevice=function(_deviceID){return _deviceID==this.deviceID;}
this.handleCstaEvent=function(_event){var changed=true;switch(_event.type){case CstaLib_CallControlEvents_Enum.connectionCleared:changed=this.onConnectionCleared(_event);break;case CstaLib_CallControlEvents_Enum.delivered:this.onDelivered(_event);break;case CstaLib_CallControlEvents_Enum.diverted:this.onDiverted(_event);break;case CstaLib_CallControlEvents_Enum.originated:this.onOriginated(_event);break;case CstaLib_CallControlEvents_Enum.held:this.onHeld(_event);break;case CstaLib_CallControlEvents_Enum.retrieved:this.onRetrieved(_event);break;case CstaLib_CallControlEvents_Enum.failed:this.onFailed(_event);break;case CstaLib_CallControlEvents_Enum.established:this.onEstablished(_event);break;case CstaLib_CallControlEvents_Enum.transferred:this.onTransfered(_event);break;case CstaLib_CallControlEvents_Enum.conferenced:this.onConferenced(_event);break;case CstaLib_CallControlEvents_Enum.deviceCapsChanged:this.onDeviceCapsChanged(_event);break;default:changed=false;}
if(changed)
this.updateState();return changed;};this.onOriginated=function(_event){if(null==this.findCall(_event.originatedConnection.callID)){var newCall=new IPCM.CstaCall(_event.originatedConnection,IPCM.CALL_DIRECTION.OUT);newCall.onOriginated(_event,this);this.insertCall(newCall,true);}};this.onDelivered=function(_event){var call=this.findCall(_event.connection.callID);if(null==call){if(this.isMyDevice(_event.connection.deviceID)){call=new IPCM.CstaCall(_event.connection,IPCM.CALL_DIRECTION.IN);call.onDelivered(_event,this);if(call.isActive())
this.insertCall(call,true);}}
else{if(!this.isMyDevice(_event.connection.deviceID))
call.onDelivered(_event,this);}};this.onEstablished=function(_event){var call=this.findCall(_event.establishedConnection.callID);if(null!=call){call.onEstablished(_event,this);if(this.callback&&this.callback.onCallEstablished&&"function"==typeof(this.callback.onCallEstablished)){this.callback.onCallEstablished(call);}}};this.onTransfered=function(_event){var primary=(!_event.primaryOldCall)?null:this.findCall(_event.primaryOldCall.callID),secondary=(!_event.secondaryOldCall)?null:this.findCall(_event.secondaryOldCall.callID),call=null!=primary?primary:secondary,localConn=null,remoteConn=null,callID=null,savedState=null;if(null!=call)
savedState=call.state;if(null!=primary){primary.onTransfered(_event,this);if(!primary.isActive())
this.removeCall(_event.primaryOldCall.callID);}
if(null!=secondary){secondary.onTransfered(_event,this);if(!secondary.isActive())
this.removeCall(_event.secondaryOldCall.callID);}
for(i=0;i<_event.transferredConnections.connectionListItem.length;++i){var item=_event.transferredConnections.connectionListItem[i];if(this.isMyDevice(item.newConnection.deviceID)){localConn=item.newConnection;callID=item.newConnection.callID}
else{remoteConn=item.newConnection;}}
if("string"==typeof _event.localConnectionInfo&&"null"!=_event.localConnectionInfo&&null!=localConn&&null!=remoteConn&&null!=callID){var newCall=new IPCM.CstaCall(localConn,call.direction);newCall.capabilities=call.capabilities;newCall.setState(savedState);newCall.updateDisplayName();this.insertCall(newCall,true);}};this.onConferenced=function(_event){var addedConnection=null,item;for(i=0;i<_event.conferenceConnections.connectionListItem.length;++i){var item=_event.conferenceConnections.connectionListItem[i];if(item.newConnection.deviceID==_event.addedParty.deviceIdentifier){addedConnection=item.newConnection;break;}}
if(null!=addedConnection){var call=this.findCall(addedConnection.callID);if(null!=call){call.onConferenced(_event,this);}
else{var newCall=new IPCM.CstaCall(addedConnection,IPCM.CALL_DIRECTION.OUT);newCall.initFromConference(_event);newCall.onConferenced(_event,this);this.insertCall(newCall,true);}}};this.onDeviceCapsChanged=function(_event){switch(_event.cause){case"deviceOutOfService":this.deviceCapabilities=0;break;default:try{this.deviceCapabilities=this.parseDeviceCapabilities(_event.extensions.privateData.private.supportedServices.callControlServList);}
catch(e){this.deviceCapabilities=0;}
break;}}
this.onConnectionCleared=function(_event){var changed=false;var callID=_event.droppedConnection.callID;var call=this.findCall(callID);if(null!=call){call.onConnectionCleared(_event,this);if(!call.isActive()){this.removeCall(callID);changed=true;}}
return changed;};this.onDiverted=function(_event){var callID=_event.connection.callID;var call=this.findCall(callID);if(null!=call){call.onDiverted(_event,this);if(!call.isActive())
this.removeCall(callID);}};this.onHeld=function(_event){var callID=_event.heldConnection.callID;var call=this.findCall(callID);if(null!=call)
call.onHeld(_event,this);};this.onRetrieved=function(_event){var callID=_event.retrievedConnection.callID;var call=this.findCall(callID);if(null!=call)
call.onRetrieved(_event,this);};this.onFailed=function(_event){};this.insertCall=function(_call,_callBack){if(null==this.findCall(_call.myConnection.callID)){this.calls.push(_call);if(_callBack&&this.callback&&this.callback.onCallInserted&&"function"==typeof(this.callback.onCallInserted)){this.callback.onCallInserted(_call);}}};this.findCall=function(_callID){var call=null;for(i=0;null==call&&i<this.calls.length;++i){if(this.calls[i].myConnection.callID==_callID)
call=this.calls[i];}
return call;};this.removeCall=function(_callID){var removed=false;for(i=0;!removed&&i<this.calls.length;++i){if(this.calls[i].myConnection.callID==_callID){var removedCall=this.calls[i];this.calls.splice(i,1);removed=true;if(this.callback&&this.callback.onCallRemoved&&"function"==typeof(this.callback.onCallRemoved)){this.callback.onCallRemoved(removedCall);}}}
return removed;};this.updateState=function(){var callIndex,stateIndex,states;this.activeCallIndex=null;switch(this.calls.length){case 0:break;case 1:this.activeCallIndex=0;break;default:if(null==(this.activeCallIndex=this.selectActiveLocallyHeldCall())){var callIndex,stateIndex=null;if(null==this.csi)
this.csi=new IPCM.CallStateIndex();for(callIndex=0;callIndex<this.calls.length;++callIndex){var newStateIndex=this.csi.getStateIndex(this.calls[callIndex].state);if(null==this.activeCallIndex){this.activeCallIndex=callIndex;stateIndex=newStateIndex;}
else if(newStateIndex==stateIndex){if(this.calls[callIndex].stateVersion>=this.calls[this.activeCallIndex].stateVersion){this.activeCallIndex=callIndex;stateIndex=newStateIndex;}}
else if(newStateIndex<stateIndex){this.activeCallIndex=callIndex;stateIndex=newStateIndex;}}}
break;}
switch(this.calls.length){case 0:this.capabilities=this.deviceCapabilities;this.capabilities&=~(IPCM.CALL_CONTROL.TRANSFER|IPCM.CALL_CONTROL.COMPLETE|IPCM.CALL_CONTROL.CONFERENCE|IPCM.CALL_CONTROL.SSTEPCONFERENCE);break;case 1:this.capabilities=this.deviceCapabilities|this.calls[0].capabilities;this.capabilities&=~(IPCM.CALL_CONTROL.TRANSFER|IPCM.CALL_CONTROL.CONFERENCE);if(0!=(this.capabilities&(IPCM.CALL_STATE.ESTABLISHED|IPCM.CALL_STATE.HELD|IPCM.CALL_STATE.HELD_LOCALLY))&0!=(this.deviceCapabilities&IPCM.CALL_CONTROL.DIAL))
this.capabilities|=IPCM.CALL_CONTROL.DIAL_CONSULT;break;case 2:if(null!=this.activeCallIndex){this.capabilities=this.calls[this.activeCallIndex].capabilities;if(this.canAlternateCalls()){this.capabilities|=IPCM.CALL_CONTROL.SWAP;}
if(this.canCompleteTransfer()){this.capabilities|=IPCM.CALL_CONTROL.COMPLETE;}
if(this.canSetUpConference()){this.capabilities|=IPCM.CALL_CONTROL.CONFERENCE;}}
break;default:if(null!=this.activeCallIndex)
this.capabilities=this.calls[this.activeCallIndex].capabilities;break;}
if(null!=this.activeCallIndex){var callState=this.calls[this.activeCallIndex].state;switch(callState){case IPCM.CALL_STATE.ALERTED:case IPCM.CALL_STATE.RINGING:case IPCM.CALL_STATE.DIALING:break;default:this.capabilities|=IPCM.CALL_CONTROL.TRANSFER&this.deviceCapabilities;this.capabilities|=IPCM.CALL_CONTROL.SSTEPCONFERENCE&this.deviceCapabilities;break;}}
if(!this.hasTwoLocallyHeldCalls())
this.heldCallsAlternated=false;};this.hasTwoLocallyHeldCalls=function(){return 2==this.calls.length&&IPCM.CALL_STATE.HELD_LOCALLY==this.calls[0].state&&IPCM.CALL_STATE.HELD_LOCALLY==this.calls[1].state;}
this.canCompleteTransfer=function(){var can=false;if(2==this.calls.length){if((IPCM.CALL_CONTROL.ALTERNATE&this.calls[0].capabilities)||(IPCM.CALL_CONTROL.ALTERNATE&this.calls[1].capabilities)){switch(this.calls[0].state){case IPCM.CALL_STATE.ESTABLISHED:case IPCM.CALL_STATE.HELD:if(IPCM.CALL_STATE.HELD_LOCALLY==this.calls[1].state)
can=true;break;case IPCM.CALL_STATE.HELD_LOCALLY:switch(this.calls[1].state){case IPCM.CALL_STATE.HELD:case IPCM.CALL_STATE.ESTABLISHED:can=true;break;}
break;}}}
return can;};this.canSetUpConference=function(){var can=false;if(2==this.calls.length){if((IPCM.CALL_CONTROL.ALTERNATE&this.calls[0].capabilities)||(IPCM.CALL_CONTROL.ALTERNATE&this.calls[1].capabilities)){switch(this.calls[0].state){case IPCM.CALL_STATE.ESTABLISHED:case IPCM.CALL_STATE.HELD:if(IPCM.CALL_STATE.HELD_LOCALLY==this.calls[1].state)
can=true;break;case IPCM.CALL_STATE.HELD_LOCALLY:switch(this.calls[1].state){case IPCM.CALL_STATE.HELD:case IPCM.CALL_STATE.ESTABLISHED:can=true;break;}
break;}}}
return can;};this.canAlternateCalls=function(){var can=false;if(2==this.calls.length){if(this.canCompleteTransfer())
can=true;else if(this.hasTwoLocallyHeldCalls())
can=true;}
return can;}
this.alternateCallsOnClient=function(){var alternated=false;if(this.hasTwoLocallyHeldCalls()){this.heldCallsAlternated=!this.heldCallsAlternated;this.updateState();alternated=true;}
return alternated;}
this.selectActiveLocallyHeldCall=function(){var callIndex=null;if(this.hasTwoLocallyHeldCalls()){callIndex=(this.calls[0].stateVersion>this.calls[1].stateVersion)?0:1;if(this.heldCallsAlternated)
callIndex=0==callIndex?1:0;}
else{this.heldCallsAlternated=false;}
return callIndex;}
this.parseDeviceCapabilities=function(_capabilities){var caps=0;if("makeCall"in _capabilities){caps|=IPCM.CALL_CONTROL.DIAL;}
if("transferCall"in _capabilities){caps|=IPCM.CALL_CONTROL.COMPLETE;}
if("singleStepTransfer"in _capabilities){caps|=IPCM.CALL_CONTROL.TRANSFER;}
if("conferenceCall"in _capabilities){caps|=IPCM.CALL_CONTROL.CONFERENCE;}
if("singleStepConference"in _capabilities){caps|=IPCM.CALL_CONTROL.SSTEPCONFERENCE;}
return caps;}};IPCM.CallControl=function(_logProc,_callback){this.logProc=_logProc;this.callback=_callback;this.credentials=null;this.loginRequest=null;this.monitor=null;this.cstaLib=new CstaLib(_logProc);this.cleanup=function imCleanup(){this.monitor=null;this.logProc=null;this.callback=null;if(null!=this.loginRequest){this.loginRequest.oCstaAppAssociation=null;this.loginRequest=null;this.credentials=null;}};this.log=function imLog(_message){if(null!=this.logProc)
this.logProc(_message);};this.updateUI=function imUpdateUI(){var activeCall=null,activeCallCaps=0;if(null!=this.monitor.activeCallIndex){activeCall=this.monitor.calls[this.monitor.activeCallIndex];activeCallCaps=activeCall.capabilities;}
this.callback.displayCall(this,this.monitor.calls[this.monitor.activeCallIndex]);this.callback.canHangUp(this,0!=(IPCM.CALL_CONTROL.HANG_UP&this.monitor.capabilities));this.callback.canAnswer(this,0!=(IPCM.CALL_CONTROL.ANSWER&this.monitor.capabilities));this.callback.canHold(this,0!=(IPCM.CALL_CONTROL.HOLD&this.monitor.capabilities));this.callback.canRetrieve(this,0!=(IPCM.CALL_CONTROL.RETRIEVE&this.monitor.capabilities));this.callback.canTransfer(this,0!=(IPCM.CALL_CONTROL.TRANSFER&this.monitor.capabilities));this.callback.canComplete(this,0!=(IPCM.CALL_CONTROL.COMPLETE&this.monitor.capabilities)&&this.monitor.canCompleteTransfer());this.callback.canDialConsult(this,0!=(IPCM.CALL_CONTROL.DIAL_CONSULT&this.monitor.capabilities));this.callback.canDial(this,0!=(IPCM.CALL_CONTROL.DIAL&this.monitor.capabilities));this.callback.canAlternate(this,0!=(IPCM.CALL_CONTROL.SWAP&this.monitor.capabilities));this.callback.canSetUpConference(this,0!=(IPCM.CALL_CONTROL.CONFERENCE&this.monitor.capabilities)&&this.monitor.canSetUpConference());this.callback.canConferSingleStep(this,0!=(IPCM.CALL_CONTROL.SSTEPCONFERENCE&this.monitor.capabilities));};this.addSnapshotCall=function imAddSnapshotCall(_call){var newCall=new IPCM.CstaCall(_call.connectionIdentifier,IPCM.CALL_DIRECTION.UNKNOWN);newCall.applySnapshot(_call);this.monitor.insertCall(newCall,false);};this.onMonitorStartResponse=function imOnMonitorStartResponse(_origRequest,_response){this.monitor=new IPCM.CstaMonitor(_response.monitorCrossRefID,_origRequest.monitorObject.deviceObject,this.callback);this.callback.onMonitorStarted(this,_origRequest.monitorObject);this.callback.canDial(this,0!=(IPCM.CALL_CONTROL.DIAL&this.monitor.capabilities));this.cstaLib.sendRequest(new CstaRequestSnapshotDevice(_origRequest.monitorObject.deviceObject));};this.onSnapshotDeviceResponse=function imOnSnapshotDeviceResponse(_origRequest,_response){for(i=0;i<_response.crossRefIDorSnapshotData.snapshotData.snapshotDeviceResponseInfo.length;++i)
this.addSnapshotCall(_response.crossRefIDorSnapshotData.snapshotData.snapshotDeviceResponseInfo[i]);this.monitor.updateState();this.updateUI();};this.Login=function imLogin(_credentials){if(null!=this.loginRequest){this.log("CSTA is already logged-in");}
else{this.loginRequest=new CstaLoginRequest(_credentials.user,_credentials.user,_credentials.password,this);this.credentials=_credentials;this.cstaLib.Login(this.loginRequest);}};this.StartMonitor=function imStartMonitor(_dn){if(null==this.credentials)
this.credentials={dn:_dn};else if(null!=_dn)
this.credentials.dn=_dn;this.cstaLib.loggedIn=true;this.cstaLib.clientCallback=this;this.cstaLib.clientCallback.loginAttempts=0;this.cstaLib.sendRequest(new CstaRequestMonitorStart(this.credentials.dn,true));};this.StopMonitor=function inStopMonitor(){if(null!=this.monitor){this.cstaLib.sendRequest(new CstaRequestMonitorStop(this.monitor.monitorID));this.monitor=null;}};this.Dial=function imDial(_destination,_subject){if(null!=this.monitor){this.cstaLib.sendRequest(new CstaRequestMakeCall(this.credentials.dn,_destination,IPCM.SubjectString(_subject)));}};this.HangUp=function imHangUp(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex)
this.monitor.calls[this.monitor.activeCallIndex].HangUp(this);};this.Answer=function imAnswer(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex)
this.monitor.calls[this.monitor.activeCallIndex].Answer(this);};this.Hold=function imHold(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex)
this.monitor.calls[this.monitor.activeCallIndex].Hold(this);};this.Retrieve=function imRetrieve(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex)
this.monitor.calls[this.monitor.activeCallIndex].Retrieve(this);};this.Alternate=function imAlternate(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex&&2==this.monitor.calls.length){var alternatingCall=null,alternateCall=null;if(IPCM.CALL_CONTROL.ALTERNATE&this.monitor.calls[0].capabilities){alternatingCall=this.monitor.calls[0];alternateCall=this.monitor.calls[1];}
else if(IPCM.CALL_CONTROL.ALTERNATE&this.monitor.calls[1].capabilities){alternatingCall=this.monitor.calls[1];alternateCall=this.monitor.calls[0];}
if(null!=alternatingCall)
alternatingCall.Alternate(this,alternateCall);}};this.DialConsult=function imDialConsult(_destination,_subject){if(null!=this.monitor&&(IPCM.CALL_CONTROL.DIAL_CONSULT&this.monitor.capabilities)&&1==this.monitor.calls.length){this.cstaLib.sendRequest(new CstaRequestConsultationCall(this.monitor.calls[0].myConnection,_destination,CstaLib_ConsultOptions_Enum.unrestricted,IPCM.SubjectString(_subject)));}};this.Transfer=function imTransfer(_destination,_subject){if(null!=this.monitor&&null!=this.monitor.activeCallIndex){var activeCall=this.monitor.calls[this.monitor.activeCallIndex];if(null!=activeCall){if(IPCM.CALL_STATE.RINGING==activeCall.state){this.cstaLib.sendRequest(new CstaRequestDeflectCall(activeCall.myConnection,_destination,IPCM.SubjectString(_subject)));}
else{this.cstaLib.sendRequest(new CstaRequestSingleStepTransferCall(activeCall.myConnection,_destination,IPCM.SubjectString(_subject)));}}}};this.Complete=function imComplete(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex&&2==this.monitor.calls.length){var heldCall=null,activeCall=null;if(this.monitor.calls[0].capabilities&IPCM.CALL_CONTROL.ALTERNATE){heldCall=this.monitor.calls[0].myConnection;activeCall=this.monitor.calls[1].myConnection;}
else if(this.monitor.calls[1].capabilities&IPCM.CALL_CONTROL.ALTERNATE){heldCall=this.monitor.calls[1].myConnection;activeCall=this.monitor.calls[0].myConnection;}
if(null!=heldCall&&null!=activeCall)
this.cstaLib.sendRequest(new CstaRequestTransferCall(heldCall,activeCall));}};this.SingleStepConference=function imSingleStepConference(_destination,_subject){if(null!=this.monitor&&null!=this.monitor.activeCallIndex){var activeCall=this.monitor.calls[this.monitor.activeCallIndex];if(null!=activeCall&&(IPCM.CALL_STATE.ESTABLISHED==activeCall.state||IPCM.CALL_STATE.HELD_LOCALLY==activeCall.state)){this.cstaLib.sendRequest(new CstaRequestSingleStepConferenceCall(activeCall.myConnection,_destination,IPCM.SubjectString(_subject),"hostLeaves","multiparty"));}}};this.Conference=function imConference(){if(null!=this.monitor&&null!=this.monitor.activeCallIndex&&2==this.monitor.calls.length){var heldCall=null,activeCall=null;if(this.monitor.calls[0].capabilities&IPCM.CALL_CONTROL.ALTERNATE){heldCall=this.monitor.calls[0].myConnection;activeCall=this.monitor.calls[1].myConnection;}
else if(this.monitor.calls[1].capabilities&IPCM.CALL_CONTROL.ALTERNATE){heldCall=this.monitor.calls[1].myConnection;activeCall=this.monitor.calls[0].myConnection;}
if(null!=heldCall&&null!=activeCall)
this.cstaLib.sendRequest(new CstaRequestConferenceCall(heldCall,activeCall,"","hostLeaves","multiparty"));}};fproxyRegisterEndpoint(this.cstaLib);var fproxy=window.fproxy?window.fproxy:document.getElementById('fproxy');fproxy.endpointRegister(this.cstaLib.me);fproxy.endpointConnect(this.cstaLib.me,this.cstaLib.party);};IPCM.CallControl.prototype=new CstaLibAppAssociation();IPCM.CallControl.prototype.onCstaServerConnected=function()
{};IPCM.CallControl.prototype.onCstaResponse=function(origRequest,response)
{if(response.type=="MonitorStartResponse")
this.onMonitorStartResponse(origRequest,response);else if(response.type=="SnapshotDeviceResponse")
this.onSnapshotDeviceResponse(origRequest,response);};IPCM.CallControl.prototype.onCstaServerDisconnected=function()
{if(null!=this.monitor)
{this.monitor=null;if(null!=this.loginRequest)
{this.loginRequest.oCstaAppAssociation=null;this.loginRequest=null;}}
this.callback.canDial(this,false);};IPCM.CallControl.prototype.onCstaLoginFailed=function(_message)
{this.callback.onLoginFailed(this,_message);};IPCM.CallControl.prototype.onCstaLoginSuccess=function(message)
{this.cstaLib.sendRequest(new CstaRequestMonitorStart(this.credentials.dn,true));};IPCM.CallControl.prototype.onCstaEvent=function(_event)
{if(null!=this.monitor&&this.monitor.isMyEvent(_event))
{this.monitor.handleCstaEvent(_event);this.updateUI();}}; 

function _fproxyOnEndpointData(me,party,data){try{_fproxyLog(String.format('fproxy: endpoint data received: {0} {1} {2}',me,party,data));var ep=fproxyFindEndpoint(me,party);if(ep)ep.onData(data);}catch(e){Ext.Frs.alert("IPCM: "+e);}}
function fproxyOnLoad(){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(100,MessageChannel,["ready"]);}
function fproxyOnTransportServerConnected(username,privileges){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["connect"]);}
function fproxyOnTransportServerAuthRejected(){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["authreject"]);}
function fproxyOnTransportServerDisconnected(){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["disconnect"]);}
function fproxyOnTransportIOError(){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["ioerror"]);}
function fproxyOnTransportSecurityError(){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["securityerror"]);}
function fproxyOnServerAvailable(_party){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["serveravailable",_party]);}
function fproxyOnServerUnavailable(_party){if(!window.MessageChannel)return;MessageChannel.fireEvent.defer(10,MessageChannel,["serverunavailable",_party]);} 

if("object"!=typeof IPCM)IPCM={};IPCM.ExtCallControlAdapter=function(){if(this.addEvents)this.addEvents("loginfailed","monitorstarted","canhangup","cananswer","canhold","canretrieve","cantransfer","cancomplete","candialconsult","candial","canalternate","displaycall","canConferSingleStep","canSetUpConference","onCallInserted","onCallEstablished");}
IPCM.ExtCallControlAdapter=Ext.extend(IPCM.ExtCallControlAdapter,Ext.util.Observable,IPCM.CallControlCallbackPrototype.prototype);IPCM.ExtCallControlAdapter.override({onLoginFailed:function(_callControl,_arg){this.fireEvent("loginfailed",_callControl,_arg);},onMonitorStarted:function(_callControl,_arg){this.fireEvent("monitorstarted",_callControl,_arg);},canHangUp:function(_callControl,_arg){this.fireEvent("canhangup",_callControl,_arg);},canAnswer:function(_callControl,_arg){this.fireEvent("cananswer",_callControl,_arg);},canHold:function(_callControl,_arg){this.fireEvent("canhold",_callControl,_arg);},canRetrieve:function(_callControl,_arg){this.fireEvent("canretrieve",_callControl,_arg);},canTransfer:function(_callControl,_arg){this.fireEvent("cantransfer",_callControl,_arg);},canComplete:function(_callControl,_arg){this.fireEvent("cancomplete",_callControl,_arg);},canDialConsult:function(_callControl,_arg){this.fireEvent("candialconsult",_callControl,_arg);},canDial:function(_callControl,_arg){this.fireEvent("candial",_callControl,_arg);},canAlternate:function(_callControl,_arg){this.fireEvent("canalternate",_callControl,_arg);},displayCall:function(_callControl,_arg){this.fireEvent("displaycall",_callControl,_arg);},canSetUpConference:function(_callControl,_arg){this.fireEvent("canSetUpConference",_callControl,_arg);},canConferSingleStep:function(_callControl,_arg){this.fireEvent("canConferSingleStep",_callControl,_arg);},onCallInserted:function(_callControl){this.fireEvent("onCallInserted",_callControl);},onCallEstablished:function(_callControl){this.fireEvent("onCallEstablished",_callControl);}});IPCM.ExtAgentControlAdapter=function(){if(this.addEvents)this.addEvents("connected","disconnected","agentloginfailed","statechanged","newinteraction","interactiondata","cangoready","cangonotready","userexists","canlogin");}
IPCM.ExtAgentControlAdapter=Ext.extend(IPCM.ExtAgentControlAdapter,Ext.util.Observable,IPCM.AgentCallbackPrototype.prototype);IPCM.ExtAgentControlAdapter.override({connected:function(_agentControl){this.fireEvent("connected",_agentControl);},disconnected:function(_agentControl){this.fireEvent("disconnected",_agentControl);},agentLoginFailed:function(_agentControl,_message){this.fireEvent("agentloginfailed",_agentControl,_message);},stateChanged:function(_agentControl,_state,_reason,_acwtimeout){this.fireEvent("statechanged",_agentControl,_state,_reason,_acwtimeout);},newInteraction:function(_agentControl,_iid){this.fireEvent("newinteraction",_agentControl,_iid);},interactionData:function(_agentControl,_iid,_values){this.fireEvent("interactiondata",_agentControl,_iid,_values);},canGoReady:function(_agentControl,_can){this.fireEvent("cangoready",_agentControl,_can);},canGoNotReady:function(_agentControl,_can,_reasons,_mandatoryReason){this.fireEvent("cangonotready",_agentControl,_can,_reasons,_mandatoryReason);},userExists:function(_agentControl,_exists){this.fireEvent("userexists",_agentControl,_exists);},canLogin:function(_agentControl,_can,_dn){this.fireEvent("canlogin",_agentControl,_can,_dn);}}); 

SaaS.WebUI.MessageChannel=function(){var _instance=null;return{Instance:function(){if(_instance===null){_instance=new SaaS.WebUI._MessageChannel();}
return _instance;},Destroy:function(){if(_instance!=null&&_instance.destroy){_instance.destroy();}
_instance=null;}}}();SaaS.WebUI._MessageChannel=function(){this.Channels={};this.ConnectionInfo={};this.Connected=false;this.Ready=false;this.flashParams={allowNetworking:"all",allowScriptAccess:"always"};this.flashAttrs={id:"fproxy"};this.flashVars={};this.flashInstaller=UrlPrefix+"Flex/expressInstall.swf";this.addEvents('ready','connect','disconnect',"serveravailable","serverunavailable",'authreject','ioerror','securityerror');this.initEvents();}
Ext.extend(SaaS.WebUI._MessageChannel,Ext.util.Observable,{Start:function(messagechannel){this.MessageChannel=messagechannel;this.flashInstaller=UrlPrefix+"Flex/expressInstall.swf";Ext.Frs.SwfController.embedSWF(this.MessageChannel,Ext.getBody(),1,1,"9.0.0",this.flashInstaller,this.flashVars,this.flashParams,this.flashAttrs);Ext.EventManager.on(window,'unload',function(){this.destroy();},this);},initEvents:function(){this.on('ready',function(){this.Ready=true;},this);this.on('serveravailable',this.onServerAvailable,this);this.on('serverunavailable',this.onServerUnavailable,this);this.on('connect',function(){this.Connected=true;},this);this.on('disconnect',function(){this.Connected=false},this);this.on('securityerror',function(){this.Channels={};this.ConnectionInfo={};this.Connected=false;},this);},Connect:function(address,port,userid,authtoken,IPCMKey1,IPCMKey2){if(!window.fproxy&&!document.getElementById('fproxy'))return;this.fproxy=window.fproxy?window.fproxy:document.getElementById('fproxy');this.ConnectionInfo={"Address":address,"Port":port,"UserId":userid,"AuthToken":""+authtoken,"IPCMKey1":IPCMKey1,"IPCMKey2":IPCMKey2}
this.fproxy.connectToServer(this.ConnectionInfo.Address,this.ConnectionInfo.Port,""+this.ConnectionInfo.AuthToken,null,this.ConnectionInfo.IPCMKey1,this.ConnectionInfo.IPCMKey2);},Reconnect:function(){if(!this.ConnectionInfo.Address)return;this.Connect(this.ConnectionInfo.Address,this.ConnectionInfo.Port,this.ConnectionInfo.UserId,this.ConnectionInfo.AuthToken,this.ConnectionInfo.IPCMKey1,this.ConnectionInfo.IPCMKey2);},Disconnect:function(){if(!this.fproxy)return;try{this.fproxy.disconnectFromServer();delete this.fproxy;}catch(e){}},onServerAvailable:function(party){if(!this.Channels[party])this.Channels[party]={};this.Channels[party].Connected=true;},onServerUnavailable:function(party){var channel=this.Channels[party];if(!channel)return;channel.Connected=false;},deleteProxy:function deleteProxy(){var obj=window.fproxy?window.fproxy:document.getElementById('fproxy');if(!obj||!obj.parentNode)return;if(Ext.isIE)for(var i in obj)if(typeof obj[i]=="function")obj[i]=function(){};obj.parentNode.removeChild(obj);fproxyRegistry=new Array();if(this.fproxy)delete this.fproxy;},destroy:function(){delete this["Channels"];if(!this.fproxy)return;this.on('disconnect',this.deleteProxy,this);if(this.Connected)this.Disconnect();this.deleteProxy();}}); 

Ext.ns("IPCM");IPCM.ImageLabel=function(config){IPCM.ImageLabel.superclass.constructor.call(this,config);};Ext.extend(IPCM.ImageLabel,Ext.BoxComponent,{template:{html:"<div class='ipcm-state-icon'></div><div class='ipcm-state-text'></div><div class='x-clear'></div>"},onRender:function(ct,position){this.el=ct.createChild(Ext.apply({id:this.id},this.template),position);if(this.text)this.setText(this.text);this.qt=new Ext.ToolTip({target:this.el.id,html:''+this.tooltip});if(this.tooltip)this.setTooltip(this.tooltip);if(this.iconCls)this.setIcon(this.iconCls);if(this.textCls)this.setTextCls(this.textCls);},setIcon:function setIcon(cls){if(!this.el)return;this.el.child("div.ipcm-state-icon").replaceClass(this.iconCls,cls);this.iconCls=cls;},setTooltip:function setIcon(text){this.tooltip=text;if(!this.qt)return;if(this.qt.rendered)
this.qt.body.update(text);else
this.qt.html=text;},getTooltip:function setIcon(){return this.tooltip;},setText:function setIcon(text){this.text=text;if(this.el){this.el.child("div.ipcm-state-text").update(text);}},setTextCls:function setTextCls(cls){if(!this.el)return;this.el.child("div.ipcm-state-text").replaceClass(this.textCls,cls);this.textCls=cls;},getText:function(){return this.text;}});Ext.reg('ipcmimagelabel',IPCM.ImageLabel); 

if("object"!=typeof IPCM)IPCM={};IPCM.UI=function(controller,ct){this.Controller=controller;this.ct=ct;this.CCEvents=new IPCM.ExtCallControlAdapter();this.AgentEvents=new IPCM.ExtAgentControlAdapter();this.renderItems=[];this.ACControlsCreated=false;this.CCControlsCreated=false;this.initEvents();this.initSettingsPanel();this._currentAgentState=IPCM.AGENT_STATE.UNKNOWN;}
Ext.extend(IPCM.UI,Ext.util.Observable,{noReasonText:String.format("&lt;{0}&gt;",'No Reason'),initEvents:function(){this.Controller.on("serveravailable",this.onServerAvailable,this);this.Controller.on("serverunavailable",this.onServerUnavailable,this);this.CCEvents.on("onLoginFailed",this.onLoginFailed,this);this.CCEvents.on("monitorstarted",this.addCallControls,this);this.CCEvents.on("canhangup",this.canHangUp,this);this.CCEvents.on("cananswer",this.canAnswer,this);this.CCEvents.on("canhold",this.canHold,this);this.CCEvents.on("canretrieve",this.canRetrieve,this);this.CCEvents.on("cantransfer",this.canTransfer,this);this.CCEvents.on("cancomplete",this.canComplete,this);this.CCEvents.on("candialconsult",this.canDialConsult,this);this.CCEvents.on("candial",this.canDial,this);this.CCEvents.on("canalternate",this.canAlternate,this);this.CCEvents.on("displaycall",this.displayCall,this);this.CCEvents.on("canSetUpConference",this.canSetUpConference,this);this.CCEvents.on("canConferSingleStep",this.canConferSingleStep,this);this.CCEvents.on("onCallEstablished",this.onCallEstablished,this);this.AgentEvents.on('canlogin',this.tryLoginAgentControl,this);this.AgentEvents.on('agentloginfailed',this.agentLoginFailed,this);this.AgentEvents.on('statechanged',this.stateChanged,this);this.AgentEvents.on('newinteraction',this.newInteraction,this);this.AgentEvents.on('interactiondata',this.interactionData,this);this.AgentEvents.on('cangoready',this.canGoReady,this);this.AgentEvents.on('cangonotready',this.canGoNotReady,this);},initSettingsPanel:function(){this.ipcmEtnRadio=new Ext.form.Radio({name:'ipcmgroup',boxLabel:'IPCM Extension',checked:true,handler:this.onIPCMExtnRadioClckd.createDelegate(this),style:'margin-top:10px'});this.IPCMNumberField=new Ext.form.TextField({style:'margin-left:20px;margin-bottom:10px;margin-top:5px',disabled:true});this.otherExtnTextField=new Ext.form.TextField({style:'margin-left:20px;margin-bottom:10px;margin-top:5px',disabled:true});this.otherExtnRadio=new Ext.form.Radio({name:'ipcmgroup',boxLabel:'Other Extension',checked:false});this.settingOKBtn=new Ext.Button({text:'Ok',handler:this.saveOverriddenExtn,scope:this});this.SettingPanel=new Ext.Window({width:250,id:'IPCMSetting',title:'IPCM Settings',items:[new Ext.form.Label({text:'Login with:'}),this.ipcmEtnRadio,this.IPCMNumberField,this.otherExtnRadio,this.otherExtnTextField],buttons:[this.settingOKBtn,{text:'Cancel',handler:function(){this.SettingPanel.hide();},scope:this}],bodyStyle:'padding:10px',labelStyle:'font-size:11px',closable:false});},saveOverriddenExtn:function(){var overdnExtn=this.otherExtnTextField.getValue();if(!this.otherExtnRadio.getValue()){overdnExtn=null;}else if(!overdnExtn||overdnExtn==''){Ext.Frs.alert('Invalid Other Extension value');return;}
Ext.Msg.confirm("",'Changes to IPCM setting requires page reload, any unsaved data will be lost. Perform change?',function(btn){if(btn!='yes')return;var dataService=new Ext.Frs.ServiceAdapter(UrlPrefix+"IPCM/Services/IPCMIntegration.asmx");dataService.call("SetCurrentUserIPCMExtension",{ipcmextn:overdnExtn},this.afterSetExtension.createDelegate(this),this.onSetExtFailure.createDelegate(this),this);},this);},afterSetExtension:function(d){if(d&&d.errorMessages&&d.errorMessages!=''){Ext.Frs.alert(d.errorMessages);}else{this.CallControl.StopMonitor();window.location.reload(true);}},onSetExtFailure:function(d){if(d&&d.responseText){var resp=Sys.Serialization.JavaScriptSerializer.deserialize(d.responseText);Ext.Frs.alert(resp.Message);}},setOverRiddenExtension:function(){var dataService=new Ext.Frs.ServiceAdapter(UrlPrefix+"IPCM/Services/IPCMIntegration.asmx");dataService.call("GetCurrentUserIPCMExtension",null,this.updateExtension.createDelegate(this),null,this);},updateExtension:function(d,c,m){if(d&&d!=''){if(this.otherExtnTextField.rendered){this.otherExtnTextField.setValue(d);this.otherExtnTextField.setDisabled(false);}else{this.otherExtnTextField.value=d;this.otherExtnTextField.disabled=false;}
if(this.otherExtnRadio.rendered){this.otherExtnRadio.setValue(true);}else{this.otherExtnRadio.checked=true;}}},onIPCMExtnRadioClckd:function(chkbox,checked){if(checked){this.otherExtnTextField.setDisabled(true);}else{this.otherExtnTextField.setDisabled(false);}},destroy:function(){if(this.acavailable&&this.AgentControl&&this.AgentControl.Logout)
this.AgentControl.Logout();},onServerAvailable:function onServerAvailable(party){var ci=this.Controller.ConnectionInfo;switch(party){case"sipcsta":if(!this.CallControl)
this.CallControl=new IPCM.CallControl(function(){},this.CCEvents);this.tryLoginCallControl();this.ccavailable=true;break;case"Server:IPCM_Server":if(!this.AgentControl){this.AgentControl=new IPCM.AgentControl(this.AgentEvents);}
if(this.UserOverrideDN){this.AgentControl.UserOverrideDN=this.UserOverrideDN;}
this.AgentControl.Register.defer(10,this.AgentControl,[ci.UserId]);this.acavailable=true;break;}
if(this.ACControlsCreated||this.CCControlsCreated)this.ct.show();},onServerUnavailable:function onServerUnavailable(party){switch(party){case"sipcsta":this.ccavailable=false;break;case"Server:IPCM_Server":this.acavailable=false;break;}
if(!this.ccavailable&&!this.acavailable){this.ct.hide();Application.layout.layout();}},tryLoginAgentControl:function tryLoginAgentControl(control,can,dn){var ci=this.Controller.ConnectionInfo;if(dn){ci.DN=dn;this.tryLoginCallControl();}
if(!can||!ci.DN)return;control.Login(ci.DN);this.addAgentControls();},tryLoginCallControl:function tryLoginCallControl(){var ci=this.Controller.ConnectionInfo;if(!ci||!ci.DN||!this.CallControl)return;if(this.UserOverrideDN){this.CallControl.StartMonitor.defer(100,this.CallControl,[this.UserOverrideDN]);}else{this.CallControl.StartMonitor.defer(100,this.CallControl,[ci.DN]);}},onCallButtonClick:function onCallButtonClick(btn,evt){var action=btn.id;switch(action){case"IPCM.CC.Answer":this.CallControl.Answer();break;case"IPCM.CC.Hangup":this.CallControl.HangUp();break;case"IPCM.CC.Hold":this.CallControl.Hold();break;case"IPCM.CC.Retrieve":this.CallControl.Retrieve();break;case"IPCM.CC.Alternate":this.CallControl.Alternate();break;case"IPCM.CC.Dial":var number=this.ct.items.get("IPCM.CC.Number").getValue();this.CallControl.Dial(""+number);this.ct.items.get("IPCM.CC.Number").setValue('');this.disableDialBasedFeatures();break;case"IPCM.CC.SingleStepTransfer":var number=this.ct.items.get("IPCM.CC.Number").getValue();this.CallControl.Transfer(number);this.ct.items.get("IPCM.CC.Number").setValue('');this.disableDialBasedFeatures();break;case"IPCM.CC.Transfer":this.CallControl.Complete();break;case"IPCM.CC.Conference":this.CallControl.Conference();break;case"IPCM.CC.Settings":if(this.AgentControl){this.IPCMNumberField.setValue(this.AgentControl.loginDN);}
this.SettingPanel.show();this.setOverRiddenExtension();break;case"IPCM.CC.SingleStepConference":var number=this.ct.items.get("IPCM.CC.Number").getValue();this.CallControl.SingleStepConference(""+number);this.ct.items.get("IPCM.CC.Number").setValue('');this.disableDialBasedFeatures();break;}},addCallControls:function addCallControls(){if(!this.ct)return;if(this.CCControlsCreated)return;var index=this.ct.items.findIndex('Marker','IPCM.CallControls');if(index==-1)return;for(var i=0;i<this.UICallControls.length;i++){var o=this.UICallControls[i];if(o.id=='IPCM.CC.Number'){o.listeners={keyup:this.onNumberFieldKeyUp.createDelegate(this)};}
if(o.handler==true)o.handler=this.onCallButtonClick.createDelegate(this);this.ct.insertButton(index++,o);}
this.CCControlsCreated=true;if(this.ct.hidden){if(!this.ct.rendered){this.ct.ownerCt.doLayout(false,true);}
this.ct.show();delete Application.WorkspaceSelector.lastSize;Application.doLayout();}else{this.ct.doLayout();}},addAgentControls:function addAgentControls(){if(!this.ct)return;if(this.ACControlsCreated)return;var index=this.ct.items.findIndex('Marker','IPCM.AgentControls');if(index==-1)return;for(var i=0;i<this.UIAgentControls.length;i++){var o=this.UIAgentControls[i];if(o.handler==true)o.handler=this.onAgentButtonClick.createDelegate(this);this.ct.insertButton(index++,o);}
this.ACControlsCreated=true;if(this.ct&&this.ct.hidden){this.ct.show();if(!this.ct.rendered){this.ct.ownerCt.doLayout(false,true);}
delete Application.WorkspaceSelector.lastSize;Application.doLayout();}},onAgentButtonClick:function onAgentButtonClick(btn,event){var action=btn.id;switch(action){case"IPCM.Agent.Ready":this.AgentControl.SetReady();break;}},agentLoginFailed:function agentLoginFailed(_agentControl,_message){Ext.Frs.alert('IPCM Login failed: '+_agentControl);},stateChanged:function stateChanged(_agentControl,_state,_reason,_acwtimeout){var label=this.ct.items.get("IPCM.Agent.Status");this._currentAgentState=_state;if(!this._AgentState)return;var s=this._AgentState[_state];if(!s)return s=this._AgentState[IPCM.AGENT_STATE.UNKNOWN];label.setText(s.label);if(_reason)
label.setTooltip(s.tooltip+" ("+_reason+")");else
label.setTooltip(s.tooltip);label.setIcon(s.iconCls);},newInteraction:function newInteraction(_agentControl,_iid){var names=["ANI","SAAS_Action","SAAS_ProfileRecId","SAAS_BO_Type","SAAS_BO_Prefill_Fields","SAAS_BO_Relationships","SAAS_Search_Criteria"];this.AgentControl.GetInteractionData(_iid,names);},interactionData:function interactionData(_agentControl,_rc,_vals){if(_rc!=0)return;var p={Scope:"ObjectWorkspace",Confirmation:null};switch(""+_vals.SAAS_Action){case"NewBO":p.CommandId="NewObject";var linkToExistent=Ext.decode(_vals.SAAS_BO_Relationships||"[]");for(var i=0,n=linkToExistent.length;i<n;++i){linkToExistent[i].RelationshipName=linkToExistent[i].Relation;linkToExistent[i].Relation=null;linkToExistent[i].ObjectType=null;}
p.CommandData={ObjectType:_vals.SAAS_BO_Type,ANI:_vals.ANI||"",ProfileRecId:_vals.SAAS_ProfileRecId||null,Fields:Ext.decode(_vals.SAAS_BO_Prefill_Fields||"[]"),LinkToExistent:linkToExistent};p.Scope="TabByObjectRef:"+p.CommandData.ObjectType+":ObjectWorkspace";top.Application.doCommand(p);break;case"ShowBO":p.CommandId="EditObject";p.CommandData={ObjectType:_vals.SAAS_BO_Type,ANI:_vals.ANI||"",ProfileRecId:_vals.SAAS_ProfileRecId||null,Fields:Ext.decode(_vals.SAAS_BO_Prefill_Fields||"[]"),LinkActions:Ext.decode(_vals.SAAS_BO_Relationships||"[]"),SearchCriteria:Ext.decode(_vals.SAAS_Search_Criteria)};p.Scope="TabByObjectRef:"+p.CommandData.ObjectType+":ObjectWorkspace";p.CommandData.SearchCriteria.ObjectId=_vals.SAAS_BO_Type;top.Application.doCommand(p);break;case"Search":p.CommandId="Search";p.CommandData={"ObjectType":_vals.SAAS_BO_Type,"SearchCriteria":Ext.decode(_vals.SAAS_Search_Criteria)};top.Application.doCommand(p);break;default:p.CommandId="ShowCaller";p.CommandData={ANI:_vals.ANI||"",ProfileRecId:_vals.SAAS_ProfileRecId||null};p.Scope="CurrentTab";top.Application.doCommand(p);break;}},onCallEstablished:function(_call){if(IPCM.AGENT_STATE.READY==this._currentAgentState){this.AgentControl.SetNotReady(null);}},canGoReady:function canGoReady(_agentControl,_can){this._canGoReady=_can;var btn=this.ct.items.get("IPCM.Agent.Ready");if(!btn)return;btn.setDisabled(!_can);},canGoNotReady:function canGoNotReady(_agentControl,_can,_reasons,_mandatoryReason){this._canGoNotReady=_can;var btn=this.ct.items.get("IPCM.Agent.NotReady");if(!btn)return;if(this.reasons){}
else{var h=function(item,event){if(item.text!=this.noReasonText)
this.AgentControl.SetNotReady(item.text);else
this.AgentControl.SetNotReady(null);btn.menu.items.each(function(i){if(i.id==item.id)i.disable();else i.enable();},this);}
h=h.createDelegate(this);if(!_mandatoryReason&&btn.menu.items.length==0)
btn.menu.addItem(new Ext.menu.Item({text:this.noReasonText,handler:h}));if(_reasons&&_reasons.length>0){this.reasons=_reasons;this.__reasons={};for(var i=0;i<_reasons.length;i++){btn.menu.addItem(new Ext.menu.Item({text:_reasons[i].label,handler:h}));}}}
btn.setDisabled(!_can);},onLoginFailed:function onLoginFailed(_callControl,_message){Ext.Frs.alert(_message);},canHangUp:function canHangUp(_callControl,_can){this._canHangUp=_can;this.ct.items.get("IPCM.CC.Hangup").setDisabled(!_can);},canAnswer:function canAnswer(_callControl,_can){this._canAnswer=_can;this.ct.items.get("IPCM.CC.Answer").setDisabled(!_can);},canHold:function canHold(_callControl,_can){this._canHold=_can;this.ct.items.get("IPCM.CC.Hold").setDisabled(!_can);},canRetrieve:function canRetrieve(_callControl,_can){this._canRetrieve=_can;this.ct.items.get("IPCM.CC.Retrieve").setDisabled(!_can);},canTransfer:function canTransfer(_callControl,_can){this._canTransfer=_can;if(this.ct.items.get("IPCM.CC.Dial").disabled)
this.ct.items.get("IPCM.CC.Number").setDisabled(!_can);},canComplete:function canComplete(_callControl,_can){this._canComplete=_can;this.ct.items.get("IPCM.CC.Transfer").setDisabled(!_can);},canDialConsult:function canDialConsult(_callControl,_can){this._canDialConsult=_can;},canSetUpConference:function canSetUpConference(_callControl,_can){this._canConference=this.CallControl.monitor.canSetUpConference();this.ct.items.get("IPCM.CC.Conference").setDisabled(!this._canConference);},canConferSingleStep:function canConferSingleStep(_callControl,_can){this._canConferSingleStep=_can;if(this._canConferSingleStep&&this.dialNumberExists()){this.ct.items.get("IPCM.CC.SingleStepConference").setDisabled(false);}else{this.ct.items.get("IPCM.CC.SingleStepConference").setDisabled(true);}},dialNumberExists:function(){return Ext.isNumber(parseInt(this.ct.items.get("IPCM.CC.Number").getValue()));},onNumberFieldKeyUp:function(field,e){if(this.dialNumberExists()){if(this._canDial){this.ct.items.get("IPCM.CC.Dial").setDisabled(false);}else{this.ct.items.get("IPCM.CC.Dial").setDisabled(true);}
if(this._canConferSingleStep){this.ct.items.get("IPCM.CC.SingleStepConference").setDisabled(false);}else{this.ct.items.get("IPCM.CC.SingleStepConference").setDisabled(true);}
if(this._canTransfer){this.ct.items.get("IPCM.CC.SingleStepTransfer").setDisabled(false);}else{this.ct.items.get("IPCM.CC.SingleStepTransfer").setDisabled(true);}}else{this.disableDialBasedFeatures();}},disableDialBasedFeatures:function(){this.ct.items.get("IPCM.CC.Dial").setDisabled(true);this.ct.items.get("IPCM.CC.SingleStepConference").setDisabled(true);this.ct.items.get("IPCM.CC.Number").setValue('');this.ct.items.get("IPCM.CC.SingleStepTransfer").setDisabled(true);},canDial:function canDial(_callControl,_can){this._canDial=_can;if(this._canDial&&this.dialNumberExists()){this.ct.items.get("IPCM.CC.Dial").setDisabled(!_can);}
if(this.ct.items.get("IPCM.CC.Transfer").disabled)
this.ct.items.get("IPCM.CC.Number").setDisabled(!_can);},canAlternate:function canAlternate(_callControl,_can){this._canAlternate=_can;this.ct.items.get("IPCM.CC.Alternate").setDisabled(!_can);},displayCall:function displayCall(_callControl,_frCall){if(null==_frCall)
this.ct.items.get("IPCM.CC.RemoteNumber").setText("idle");else{var displayName=_frCall.remoteDeviceID;if(null!=_frCall.remoteName)
displayName+="/"+_frCall.remoteName;this.ct.items.get("IPCM.CC.RemoteNumber").setText(displayName);}},doCommand:function doCommand(command,onload){switch(command.CommandId){case"Dial":if(!this.ccavailable||!this._canDial)return false;var number=(command.CommandData||{}).Number||"";this.ct.items.get("IPCM.CC.Number").setValue(number);this.CallControl.Dial(""+number);break;case"Answer":if(!this.ccavailable||!this._canAnswer)return false;this.CallControl.Answer();break;case"Hangup":if(!this.ccavailable||!this._canHangup)return false;this.CallControl.HangUp();break;case"Hold":if(!this.ccavailable||!this._canHold)return false;this.CallControl.Hold();break;case"Retrieve":if(!this.ccavailable||!this._canRetrieve)return false;this.CallControl.Retrieve();break;case"Alternate":if(!this.ccavailable||!this._canAlternate)return false;this.CallControl.Alternate();break;case"Transfer":if(!this.ccavailable||!this._canTransfer)return false;var number=(command.CommandData||{}).Number||"";this.ct.items.get("IPCM.CC.Number").setValue(number);this.CallControl.Transfer(number);break;case"AgentReady":if(!this.acavailable||!this._canGoReady)return false;this.AgentControl.SetReady();break;case"AgentNotReady":if(!this.acavailable||!this._canGoNotReady)return false;var btn=this.ct.items.get("IPCM.Agent.NotReady");if(!btn)return false;var d=(command.CommandData||{})
if(d.ReasonText!=this.noReasonText)
this.AgentControl.SetNotReady(d.ReasonText);else
this.AgentControl.SetNotReady(null);btn.menu.items.each(function(i){if(i.text==d.ReasonText)i.disable();else i.enable();},this);break;default:return false;}
return true;},DoIPCMCallback:function DoIPCMCallback(){this.popUp=new Ext.Window({width:400,labelWidth:140,closeAction:'close',plain:true,autoScroll:true,buttonAlign:"right",layout:'form',title:'Enter phone number',cls:'x-search-prompt-popup-win',modal:true,items:[new Ext.form.TextField({id:'phone-number',fieldLabel:'Phone Number'})],buttons:[{text:'OK',handler:function(){var phoneNumber=this.popUp.findById('phone-number').getValue();var dataService=new Ext.Frs.ServiceAdapter(UrlPrefix+"Services/IPCMIntegration.asmx");dataService.call("RequestCallback",{phoneNumber:phoneNumber},function(d,c,m){},null,this);this.popUp.close();},scope:this},{text:'Cancel',handler:function(){this.popUp.close();},scope:this}]});this.popUp.show();}});IPCM.UI.prototype.UIAgentControls=[{id:"IPCM.Agent.Status",text:'Unknown',width:100,iconCls:"ipcm-icon-asunknown",xtype:"ipcmimagelabel",cls:'ipcm-toolbar-label'},{xtype:"tbseparator"},{id:"IPCM.Agent.Ready",handler:true,iconCls:"ipcm-icon-asready",disabled:true,tooltip:'Ready'},{id:"IPCM.Agent.NotReady",handler:true,menu:[],iconCls:"ipcm-icon-asnotready",disabled:true,tooltip:'Not Ready'}];IPCM.UI.prototype.UICallControls=[{xtype:"tbseparator"},{id:"IPCM.CC.RemoteNumber",xtype:"label",cls:"ipcm-toolbar-label",text:'Ready'},{xtype:"tbseparator"},{id:"IPCM.CC.Answer",iconCls:"ipcm-icon-answer",handler:true,disabled:true,tooltip:'Answer call'},{id:"IPCM.CC.Alternate",iconCls:"ipcm-icon-alternate",handler:true,disabled:true,tooltip:'Alternate call',style:'margin-left:20px'},{id:"IPCM.CC.Hold",iconCls:"ipcm-icon-hold",handler:true,disabled:true,tooltip:'Hold call'},{id:"IPCM.CC.Retrieve",iconCls:"ipcm-icon-retrieve",handler:true,disabled:true,tooltip:'Retrieve call'},{id:"IPCM.CC.Dial",iconCls:"ipcm-icon-call",handler:true,disabled:true,tooltip:'Dial call',style:'margin-left:20px'},{id:"IPCM.CC.Number",xtype:"textfield",style:"padding-top:4px;",emptyText:'Phone',value:"",validateOnBlur:false,width:80,disabled:true,allowBlank:true,enableKeyEvents:true},{id:"IPCM.CC.SingleStepTransfer",iconCls:"ipcm-icon-singlestep-transfer",handler:true,disabled:true,tooltip:'Single Step Transfer'},{id:"IPCM.CC.SingleStepConference",iconCls:"ipcm-icon-singlestep-conference",handler:true,disabled:true,tooltip:'Single Step Conference'},{id:"IPCM.CC.Transfer",iconCls:"ipcm-icon-singletransfer",handler:true,disabled:true,tooltip:'Transfer call',style:'margin-left:20px'},{id:"IPCM.CC.Conference",iconCls:"ipcm-icon-conference",handler:true,disabled:true,tooltip:'Conference'},{id:"IPCM.CC.Hangup",iconCls:"ipcm-icon-hangup",handler:true,disabled:true,tooltip:'Hangup call',style:'margin-left:20px'},{id:"IPCM.CC.Settings",iconCls:"ipcm-icon-settings",handler:true,tooltip:'IPCM Settings'}];_AS=[];_S=IPCM.AGENT_STATE;_AS[_S.LOGGED_OUT]={label:'Logged Out',iconCls:"ipcm-icon-asloggedout",tooltip:'Not logged into the system',Description:'The user IS an IPCM agent but he is not logged in the server yet'};_AS[_S.NOT_READY]={label:'Not Ready',iconCls:"ipcm-icon-asnotready",tooltip:'Not ready to take calls',Description:'The agent is not ready to take calls from the ACD queue. This status may have optional reason (test string) – the reason should be appended to the tooltip string, if specified'};_AS[_S.READY]={label:'Ready',iconCls:"ipcm-icon-asready",tooltip:'Ready to take calls',Description:'The agent is not busy and can take calls from the ACD queue'};_AS[_S.RESERVED]={label:'Reserved',iconCls:"ipcm-icon-asreserved",tooltip:'Reserved for customer call',Description:'The IPCM started to deliver the queued call to this agent; agent cannot get other calls; system is waiting for agent to pick up the ringing phone call'};_AS[_S.BUSY]={label:'Busy',iconCls:"ipcm-icon-asbusy",tooltip:'Busy with customer call',Description:'The agent is actively talking with the customer on the phone (or working on another media interaction, like chat – future functionality)'};_AS[_S.AFTER_CALL_WORK]={label:'After Call Work',iconCls:"ipcm-icon-aswrapup",tooltip:'Doing after-call work',Description:'The agent finished phone conversation with the customer and wrapping up the call (adding information into the database, for example)'};_AS[_S.UNKNOWN]={label:'Unknown',iconCls:"ipcm-icon-asunknown",tooltip:'Agent status unknown',Description:'The system does not know if user is an agent or did not receive any status information from the IPCM server yet'};IPCM.UI.prototype._AgentState=_AS;delete _AS;delete _S; 

IPCM.CommandHandler=function(config){};Ext.override(IPCM.CommandHandler,{doCommand:function(command){if(!top.Application.IPCMUI||!top.Application.IPCMUI.doCommand)return false;return top.Application.IPCMUI.doCommand(command);},doUrlCommand:function(command){var scmd={Scope:command.Scope,CommandId:command.CommandId};switch(command.CommandId){case"Dial":return this.doCommand(scmd);break;default:return this.doCommand(command);break;}},getCommandUrl:function(command){var dcmd={Scope:command.Scope,CommandId:command.CommandId,ObjectType:command.CommandData.ObjectType}
switch(command.CommandId){case"Dial":return UrlPrefix;break;default:return top.Navigation.buildCommandUrl(cmd);break;}}}); 

SaaS.WebUI.Click2TalkDialog=Ext.extend(Ext.Window,{layout:'card',DataService:"",modal:true,border:false,resizable:false,deferredRender:true,header:false,closable:false,title:'Click to Talk',activeItem:0,width:360,height:200,statusInterval:1000,statusIcon:{"Dialing":"cps-icon-dialing","Queued":"cps-icon-queued","Connected":"cps-icon-connected","SelfService":"cps-icon-selfservice","Voicemail":"cps-icon-voicemail","CallFailed":"cps-icon-failed","Completed":"cps-icon-completed"},statusText:{"Dialing":'Dialing your selected phone number.',"Queued":'Waiting for the next available service technician.',"Connected":'Connected to the service technician',"SelfService":'Request is being handled by Voice Self Service Application.',"Voicemail":'Recording voice message.',"CallFailed":'Unable to dial user`s phone.',"Completed":'The request is completed'},initComponent:function(){this.DataService=UrlPrefix+"IPCM/services/IPCMIntegration.asmx";this.items=[{xtype:"form",labelWidth:120,bodyStyle:'padding:5px 5px 0',border:false,bodyBorder:false,defaultType:'textfield',items:[{xtype:"box",autoEl:{tag:'div',style:'margin-bottom:5px;',html:'Please select a phone number from the list or enter the number you wish to be contacted at. The system will call you at that number and you will be connected to service technician.\n'}},(this.typeSelector=new Ext.form.ComboBox({id:'c2t-phonetype',typeAhead:true,triggerAction:'all',lazyRender:true,mode:'local',width:200,fieldLabel:'Use&nbsp;number',store:new Ext.data.ArrayStore({fields:[{name:'FieldName',mapping:'FieldName'},{name:'DisplayName',mapping:'DisplayName'},{name:'FieldValue',mapping:'FieldValue'}],data:[]}),valueField:'FieldName',displayField:'DisplayName'})),(this.numberField=new Ext.form.TextField({id:"c2t-phonenumber",enableKeyEvents:true,width:200,fieldLabel:'Phone#'}))],buttons:[{id:'c2t-doconnect',text:'Connect',handler:this.onRequest.createDelegate(this)},{id:'c2t-close',text:'Close',handler:this.onCancelRequest.createDelegate(this)}]},{xtype:"panel",layout:'hbox',border:false,bodyBorder:false,bodyStyle:'padding-left:5px;padding-right:5px;',layoutConfig:{align:"middle"},flex:1,items:[this.statusLabel=new IPCM.ImageLabel({iconCls:'cps-icon-dialing',text:'Dialing...',tooltip:'Call in progress',textCls:'x-frs-form-label ipcm-c2c-statustext'})],buttons:[{id:"c2t-cancel",text:'Cancel Request',handler:this.onCancelRequest.createDelegate(this)}]}];SaaS.WebUI.Click2TalkDialog.superclass.initComponent.call(this);this.statusTask={run:function(){this.getCallStatus();},interval:this.statusInterval,repeat:1,scope:this};this.typeSelector.on('select',this.doNumberSelect,this);this.numberField.on('blur',this.validateControls,this);this.numberField.on('keyup',function(f,event){this.validateControls();},this);this.numberField.on('specialkey',function(f,event){if(event.getKey()==event.ENTER){if(this.numberField.getValue())this.onRequest();}},this);this.canClose=true;},initialize:function initialize(){this.getInitData();},getInitData:function(){var service=new Ext.Frs.ServiceAdapter(this.DataService);service.call("C2T_GetUserPhones",{},function(d,c,m){Loader.HideProgress();if(!d)d=new Array();if(d.push)
d.push({FieldName:'custom',FieldValue:'',DisplayName:'Custom'})
c.typeSelector.store.loadData(d);if(d[0]){c.typeSelector.setValue(d[0].FieldName||"");c.numberField.setValue(d[0].FieldValue||"");c.validateControls();}
c.show();},function(e,c,m){Loader.HideProgress();},this);},doNumberSelect:function doNumberSelect(ct,data,idx){this.numberField.setValue(data.data.FieldValue||"");this.validateControls();},validateControls:function invalidateControls(){if(!this.numberField.getValue()){Ext.getCmp("c2t-doconnect").disable();}
else{Ext.getCmp("c2t-doconnect").enable();}},onRequest:function(){Loader.ShowProgress('Initiating call...');this.initiateCall(this.numberField.getValue(),this.getCallContext());},onCancelRequest:function(){if(this.Token&&this.canCancel){this.stopPolling();Ext.Msg.show({title:'Confirmation',msg:'Do you want to cancel call?',buttons:Ext.Msg.YESNO,fn:(function(btn){if(btn=='yes'){this.cancelRequest(this.Token);this.statusLabel.setText('Waiting for status...');this.statusLabel.setIcon(this.statusIcon["Dialing"]);this.layout.setActiveItem(0);if(this.canClose)this.close();this.canCancel=false;this.canClose=true;}else{this.startPolling.defer(this.statusInterval,this);}}).createDelegate(this),scope:this,icon:Ext.MessageBox.QUESTION});}
else
if(this.canClose)this.close();},onRender:function(ct,position){SaaS.WebUI.Click2TalkDialog.superclass.onRender.call(this,ct,position);},startPolling:function(){if(this.statusTask.started)return;Ext.TaskMgr.start(this.statusTask);this.statusTask.started=true;},stopPolling:function(){if(!this.statusTask.started)return;Ext.TaskMgr.stop(this.statusTask);this.statusTask.started=false;},initiateCall:function(number,obj){this.canCancel=true;this.canClose=false;this.FinalPoll=-1;var service=new Ext.Frs.ServiceAdapter(this.DataService);service.call("C2T_Request",{"number":number,"objectType":obj.type,"objectId":obj.id},function(d,c,m){Loader.HideProgress();if(!d){return;}
c.Token=d;c.StatusCounter=0;c.statusLabel.setText('Waiting for status...');c.statusLabel.setIcon(c.statusIcon["Dialing"]);c.layout.setActiveItem(1);c.startPolling();},function(e,c,m){Loader.HideProgress();c.stopPolling();Ext.Frs.alert(_$QL("Can't initiate session, please contact with administrator !"));c.canCancel=true;c.canClose=true;},this);},updateStatus:function(token){var service=new Ext.Frs.ServiceAdapter(this.DataService);service.call("C2T_Status",{"token":token},function(d,c,m){c.doStatusUpdate(d);},function(e,c,m){c.stopPolling();c.statusLabel.setText('Communication Error!');c.statusLabel.setIcon(this.statusIcon["CallFailed"]);c.statusLabel.setTooltip(""+e);Ext.getCmp("c2t-cancel").enable();Ext.getCmp("c2t-cancel").setText('Close');},this);},doStatusUpdate:function doStatusUpdate(status){if(!status||!status.__type=="SaaS.WebUI.IPCM.CallStatus"){this.statusLabel.setText('Waiting for status...');this.statusLabel.setIcon(this.statusIcon["Dialing"]);Ext.getCmp("c2t-cancel").enable();this.canCancel=true;this.canClose=true;this.startPolling.defer(this.statusInterval,this);this.doFinalPoll=false;return;}
this.statusLabel.setText(status.Reason||this.statusText[status.Status]||'Waiting for status...');this.statusLabel.setTooltip(status.Reason?this.statusText[status.Status]:"");this.statusLabel.setIcon(this.statusIcon[status.Status]||this.statusIcon["Dialing"]);if(!status.CanClose&&this.canClose){this.FinalPoll=-1;this.doFinalPoll=false;}
this.canCancel=status.CanCancel;this.canClose=status.CanClose;if(this.FinalPoll<0&&status.CanClose&&status.PollTimeAfterStatusFinal){this.FinalPoll=status.PollTimeAfterStatusFinal*1000;this.CountDown=status.PollTimeAfterStatusFinal;this.doFinalPoll=true;}
if(status.CanCancel||status.CanClose){Ext.getCmp("c2t-cancel").enable();}
else
Ext.getCmp("c2t-cancel").disable();if(status.CanClose){Ext.getCmp("c2t-cancel").setText('Close');this.FinalPoll-=this.statusInterval;if(this.doFinalPoll&&this.FinalPoll<1){this.doFinalPoll=false;this.statusLabel.setText('Waiting for status...');this.statusLabel.setIcon(this.statusIcon["Dialing"]);this.layout.setActiveItem(0);this.close();return;};if(this.doFinalPoll&&this.CountDown)this.statusLabel.setText(this.statusText[status.Status]+" "+--this.CountDown);if(this.FinalPoll>0)
this.startPolling.defer(this.statusInterval,this);}else{Ext.getCmp("c2t-cancel").setText('Cancel Request');this.startPolling.defer(this.statusInterval,this);}},cancelRequest:function(token){if(!token)return false;var service=new Ext.Frs.ServiceAdapter(this.DataService);service.call("C2T_Cancel",{"token":token},function(d,c,m){if(d)c.Token=null;c.stopPolling();c.layout.setActiveItem(0);},null,this);},getCallStatus:function getCallStatus(){this.stopPolling.defer(1,this);if(this.Token)
this.updateStatus(this.Token);},getCallContext:function getCallContext(){var res={type:null,id:null};if(!Application.WorkspaceSelector)return res;var ws=Application.WorkspaceSelector.getTabWorkspace(Application.WorkspaceSelector.tabs.activeTab);if(!ws)return ws;res.type=ws.getC2TContextType?ws.getC2TContextType():null;res.id=ws.getC2TContextId?ws.getC2TContextId():null;return res;},destroy:function destroy(){this.stopPolling();SaaS.WebUI.Click2TalkDialog.superclass.destroy.call(this);}}); 
                                               
