/*
 * Zipwhip Web 2.0 Messaging Product 1.0.
 * Copyright(c) 2008-2011, Zipwhip.
 * 
 * 
 * This product is not currently available for public release. Only Zipwhip employees and authorized Carriers, and their customers are permitted to access this product during the authorized beta.
 */


Zw.namespace('Zw.features.z');Zw.features.z.ZButton=Ext.extend(Zw.controls.LargeButton,{text:Zw.localize('generic.btn.zButton'),name:"Z Menu",minWidth:54,cls:'x-menu x-menu-undo zw-toptoolbar-btn',iconCls:"zw-toptoolbar-icon-z"});

Zw.features.z.ZButtonGroup=Ext.extend(Zw.controls.LargeButtonGroup,{name:"Z Group",initComponent:function(){this.items=[new Zw.features.z.ZButton()]
Zw.features.z.ZButtonGroup.superclass.initComponent.call(this);}});Ext.reg('Zw.features.z.ZButtonGroup',Zw.features.z.ZButtonGroup);

Zw.namespace('Zw.features.z');Zw.features.z.ZFeature=Ext.extend(Zw.Feature,{group:'Zw.features.z.ZButtonGroup',disableGroupIfGuest:Zw.capabilities.ALLOW_GUEST,defaultConfig:{closeAction:'destroy'},menuCorporateItems:{clsAddl:'zw-windowtbar-corporate',items:[{text:Zw.localize('generic.btn.aboutZipwhip'),iconCls:'about',colspan:2},{text:Zw.localize('generic.btn.terms'),iconCls:'terms'},{text:Zw.localize('generic.btn.privacy'),iconCls:'privacy'}]},menuApplicationItems:{clsAddl:'zw-windowtbar-application',items:[{text:Zw.localize('generic.btn.support'),iconCls:'support'},{text:Zw.localize('generic.btn.tour'),iconCls:'tour',code:'tour'},{text:Zw.localize('generic.btn.feedback'),iconCls:'feedback'},{text:Zw.localize('generic.btn.faqs'),iconCls:'faqs'}]},onInit:function(){this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/feature/z'}));this.setProxies();},setProxies:function(){this.addProxy(['/desktop/interlink/about%20zipwhip','/desktop/interlink/about','/desktop/about/show'],'showAboutWindow');this.addProxy(['/desktop/interlink/privacy','/desktop/interlink/terms','/desktop/interlink/legal','/desktop/legal/show'],'showLegalWindow');this.addProxy(['/desktop/interlink/support','/desktop/support/show'],'showSupportWindow');this.addProxy(['/desktop/interlink/feedback','/desktop/feedback/show'],'showFeedbackWindow');this.addProxy(['/desktop/interlink/help','/desktop/interlink/faq','/desktop/faq/show'],'showFaqWindow');},addProxy:function(uris,callback){this[callback]=this.createProxyFunction(this['_'+callback]);Ext.each(uris,function(uri){this.context.subscribe(uri,this[callback],this);},this);},createProxyFunction:function(callback){return function(queryObject){Zw.Packages.get('about.all',callback,this,[queryObject]);}},onGroupClick:function(){Zw.Packages.get(['menu.all','about.all'],this.showDropdownMenu,this);},showWindow:function(key,constructor,config,showConfig){key='_'+key+'Window';var thing=this[key];if(!thing){config=Ext.apply(config||{},showConfig,this.defaultConfig);thing=this.context.Desktop.registerWindow(new constructor(config));thing.on('destroy',function(sender){delete this[key];},this);this[key]=thing;}
thing.show();},_showLegalWindow:function(queryObject){this.showWindow('legal',Zw.features.z.LegalWindow,queryObject);},_showAboutWindow:function(){this.showWindow('about',Zw.features.z.AboutZipwhipWindow);},_showSupportWindow:function(){this.showWindow('support',Zw.features.z.SupportWindow,{ajax:Zw.Application.Net.sendComment,context:this.context,email:this.getEmail()});},_showFeedbackWindow:function(){this.showWindow('feedback',Zw.features.z.FeedbackWindow,{ajax:Zw.Application.Net.sendComment,context:this.context,email:this.getEmail()});},_showFaqWindow:function(queryObject){this.showWindow('faq',Zw.features.z.FaqWindow,{context:this.context});},getEmail:function(){var identity=this.context.Account.m_identity;return identity?identity.get('email'):'';},dropdownHandler:function(sender){var text=sender.text.toLowerCase();switch(text){case Zw.localize('generic.btn.aboutZipwhip').toLowerCase():this.context.publish('/desktop/about/show');break;case Zw.localize('generic.btn.terms').toLowerCase():case Zw.localize('generic.btn.privacy').toLowerCase():this.context.publish('/desktop/legal/show',{tab:text});break;case Zw.localize('generic.btn.support').toLowerCase():this.context.publish('/desktop/support/show');break;case Zw.localize('generic.btn.tour').toLowerCase():this.context.publish('/desktop/tour/show');break;case Zw.localize('generic.btn.feedback').toLowerCase():this.context.publish('/desktop/feedback/show');break;case Zw.localize('generic.btn.help').toLowerCase():this.context.publish('/desktop/faq/show');break;case Zw.localize('generic.btn.faq').toLowerCase():this.context.publish('/desktop/faq/show');break;case Zw.localize('generic.btn.faqs').toLowerCase():this.context.publish('/desktop/faq/show');break;case Zw.localize('generic.btn.settings').toLowerCase():this.context.publish('/desktop/settings/edit');break;}
this.menu.destroy();delete this.menu;},showDropdownMenu:function(){if(!this.menu){var items=[this.menuApplicationItems];items.push(this.menuCorporateItems);this.menu=new Zw.controls.FloatingPanel({cls:'x-menu zw-dropdown z z-zw-dropdown',height:153,autoWidth:true,allowOtherMenus:true,hidden:false,frame:false,border:false,bodyStyle:'',preventContextMenu:true,defaults:{xtype:'Zw.controls.WindowToolbarButtonGroup',cls:'zw-windowtbar-btn-group zw-windowtbar-btn-group-tall',columns:2,rows:2,scale:'tall',defaults:{xtype:'Zw.controls.WindowToolbarButton',scope:this,handler:this.dropdownHandler,iconAlign:'left',scale:'smallish'}},items:items});var bl=this.getDropdownAlignEl();if(bl){bl=bl.getAnchorXY('bl');}else{throw"you did not provide a dropdown element (zfeature.js)";}
this.applyDropdownOffsets(bl);this.menu.showAt(bl);this.menu.on('hide',function(){this.menu.destroy();this.menu=null;},this);if(this.context.Account.isGuest(true)){var tourItem=this.menu.find('code','tour')[0];if(tourItem){tourItem.disable();}}}else{this.menu.hide();}},getDropdownAlignEl:function(){return this.group.el;},applyDropdownOffsets:function(bl){bl[1]-=11;bl[0]+=2;},_destroyWindow:function(key){key='_'+key+'Window';var thing=this[key];if(thing){Ext.destroy(thing);delete this[key];}},onDestroy:function(){this._destroyWindow('about');this._destroyWindow('terms');this._destroyWindow('privacy');this._destroyWindow('feedback');}});Zw.features.Factory.register('Zw.features.z.ZFeature');

Zw.namespace('Zw.features.z');Zw.features.z.ZMenu=Ext.extend(Ext.menu.Menu,{initComponent:function(){this.items=['<div style="width:195px;height:136px;background:transparent url(\'images/TempDemoImages/ZdropdownMenu.png\');"></div>',{text:'Extended View',handler:function(){}}]
Zw.features.z.ZMenu.superclass.initComponent.call(this);}});Ext.reg('Zw.features.z.ZMenu',Zw.features.z.ZMenu);Zw.features.z.ZMenuItem=Ext.extend(Ext.menu.Adapter,{cls:"zw-zmenu-item",initComponent:function(){this.items=[{xtype:"div",style:"width:195px;height:136px;background:transparent url('images/TempDemoImages/ZdropdownMenu.png');",html:""}];Zw.features.z.ZMenuItem.superclass.initComponent.call(this);}});Ext.reg('Zw.features.z.ZMenuItem',Zw.features.z.ZMenuItem);

Zw.namespace('Zw.features.messages');Zw.features.messages.SendMessageToolbarActionButtonGroup=Ext.extend(Zw.controls.WindowToolbarButtonGroup,{clsAddl:'zw-windowtbar-action',columns:3,handler:Ext.emptyFn,initComponent:function(){this.defaults={xtype:"Zw.controls.WindowToolbarButton",handler:this.handler,scope:this.scope||this};this.items=[{text:Zw.localize('generic.btn.reply'),code:'reply',iconCls:"zw-windowtbar-icon-reply",rowspan:2},{text:Zw.localize('generic.btn.fwd'),code:'fwd',iconCls:"zw-windowtbar-icon-fwd",rowspan:2},{text:Zw.localize('generic.btn.resend'),code:'resend',iconCls:"zw-windowtbar-icon-resend",scale:'small',iconAlign:'left'},{text:Zw.localize('generic.btn.del'),code:'delete',disabled:!this.deleteEnabled,iconCls:"zw-windowtbar-icon-del",scale:'small',iconAlign:'left'}];Zw.features.messages.SendMessageToolbarActionButtonGroup.superclass.initComponent.call(this);},garbage:null});Zw.features.messages.SendMessageToolbarJumpButtonGroup=Ext.extend(Zw.controls.WindowToolbarButtonGroup,{clsAddl:'zw-windowtbar-jump',initComponent:function(){Ext.apply(this,{items:[{xtype:"Zw.controls.WindowToolbarButton",text:Zw.localize('generic.btn.conversation'),code:'convo',handler:this.handler,iconCls:"zw-windowtbar-icon-conv",tooltip:"Jump to Conversation window for this Contact"}]});Zw.features.messages.SendMessageToolbarJumpButtonGroup.superclass.initComponent.call(this);},garbage:null});Zw.features.messages.NubbyToolbarButtonGroup=Ext.extend(Zw.controls.WindowToolbarButtonGroup,{clsAddl:'zw-windowtbar-btn-group-short zw-windowtbar-btn-group-short-plain',initComponent:function(){this.setDefaults({scale:'small',iconAlign:'top'});this.items=[{text:Ext.isIE6?Zw.localize('generic.btn.newZipgroup'):Zw.localize('generic.btn.newBrZipgroup'),code:'createGroupButton',iconCls:'createGroupButton',iconAlign:'left',scale:'smallish'},{xtype:'Zw.controls.DetailSeparator'},{text:Zw.localize('generic.btn.tiny'),code:'small',iconCls:'zw-windowtbar-icon-tiny',enableToggle:true,toggleGroup:this.id},{text:Zw.localize('generic.btn.small'),code:'medium',iconCls:'zw-windowtbar-icon-small',enableToggle:true,toggleGroup:this.id},{text:Zw.localize('generic.btn.normal'),code:'normal',iconCls:'zw-windowtbar-icon-normal',enableToggle:true,toggleGroup:this.id}];Zw.features.messages.NubbyToolbarButtonGroup.superclass.initComponent.call(this);}});Ext.reg('Zw.features.messages.NubbyToolbarButtonGroup',Zw.features.messages.NubbyToolbarButtonGroup);

Zw.features.messages.SignatureDropdownPlugin=Ext.extend(Zw.Plugin,{tpl:new Ext.Template('<span class="">{name}</span> - <span class="">{example}</span>'),nameDiv:null,onInit:function(){var client=this.client;if(!client)return;var clientClient=client.client;if(!clientClient)return;var textarea=client.getTextarea();if(!textarea)return;this.host=clientClient;this.window=client.window;this.textarea=textarea;this.host.on('render',this.onClientRender,this,{single:true});client.on('GoalChange',this.onGoalChange,this);client.on('IdentityChange',this.onIdentityChange,this);},onIdentityChange:function(){if(this.panel){this.panel.destroy();delete this.panel;}},onGoalChange:function(){var client=this.client;if(client){var goal=client.goal;if(this.nameDiv){this.nameDiv.child('.c').update(goal);}
this.goal=goal;}},_setIdentity:function(){if(this.panel)
this.panel.hide();if(this.window){this.window.identityManager.editIdentity();}},_doChange:function(c){if(!c)return;var mode=c.mode;var preventSave=c.preventSave;var client=this.client;if(client){client.setMode(mode,c.result,preventSave);}
if(this.panel)
this.panel.hide();},updateNameDiv:function(){this.goal=this.goal||'';this.nameDiv.child('.c').update(this.goal.replace(' ','&nbsp;'));},onClientRender:function(){if(this.window&&this.window.toStore){this.window.toStore.on('add',this.makeSureNotJustIdentityCard,this,{buffer:true});this.window.toStore.on('remove',this.makeSureNotJustIdentityCard,this,{buffer:true});}
this.nameDivParent=this.host.getEl().child('.x-panel-body');this.nameDiv=this.nameDivParent.createChild('<div class="zw-window-sendmessage-name-wrap"><div class="x-menu zw-window-sendmessage-name"><div class="l"><div class="r"><div class="indicator"></div><div class="c"></div></div></div></div></div>');this.nameDivParent.addClass('nameenforcer');this.nameDivParent.setStyle('padding-left','10px');this.updateNameDiv();this.client.window.nameDiv=this.nameDiv;this.nameDiv.unselectable();this.host.getField().on('render',this.onFieldRender,this,{single:true});Zw.console('>>> onClientRender after');},onFieldRender:function(){var xOffset=(Ext.isSafari)?-9:-6;this.nameDiv.alignTo(this.nameDivParent.child('textarea'),'tl-tl',[xOffset,2]);this.nameDiv.on('click',this.showMenu,this);this.nameDiv.addClassOnOver('mo');this.nameDiv.addClassOnClick('md');this.textareaDom=this.host.getField().getEl().dom;this.makeSureNotJustIdentityCard();},makeSureNotJustIdentityCard:function(){if(this.window.toStore.getCount()==1){if(this.window.toStore.getAt(0).id==-1){var client=this.client;if(client){this.lastMode=client.mode;if(client.mode==='custom'){this.lastGoal=client.context.Settings.get('signature_custom');}
else{this.lastGoal=client.goal.substring(0,this.goal.length-1);client.setText(this.goal+(this.host.text?(this.host.text):' '));}}
this._doChange({mode:'Off',result:'Off',highlight:true,preventSave:true});this.client.killedForIdentityCard=true;return;}}
if(this.client.killedForIdentityCard){this._doChange({mode:this.lastMode,result:this.lastGoal,highlight:true});this.client.killedForIdentityCard=false;}},highlightDropdownOption:function(mode){if(!this.modeCache)
this.modeCache={};if(this.panel){if(!this.modeCache[mode]){this.modeCache[mode]=this.panel.find('mode',mode)[0];}
if(this.modeCache[mode]){if(this.modeCache[mode].onClick)
this.modeCache[mode].onClick();}}},buildMenu:function(){var client=this.client;if(!client)return;var d=client.identity;var fName=d.firstName;var lName=d.lastName;this.panel=new Zw.controls.ContextMenu({cls:'zw-name-signature zw-dropdown-medium gradient x-menu zw-dropdown',height:221,layout:'anchor',items:[{xtype:'Zw.controls.ContextMenu.Group',layout:'anchor',image:'from-name',cls:'zw-menu-single-item zw-menu-item-padding',anchor:'100% -2',xdefaults:{xtype:'Zw.features.messages.menus.NameItem',firstName:fName,lastName:lName,handler:this._doChange.createDelegate(this),group:new Zw.controls.ContextMenu.SelectionGroup()},items:this._getSignatureItems()}]},this);},_getSignatureItems:function(){var client=this.client;var allowed=client.supportedModes;var items=[];items.push({mode:'full',label:Zw.localize('generic.label.full'),disabled:!allowed['full']});items.push({mode:'first',label:Zw.localize('generic.label.first'),disabled:!allowed['first']});items.push({mode:'last',label:Zw.localize('generic.label.last'),disabled:!allowed['last']});items.push({mode:'lastinitial',label:Zw.localize('generic.label.lastInitial'),disabled:!allowed['lastinitial']});items.push({mode:'firstinitial',label:Zw.localize('generic.label.firstInitial'),disabled:!allowed['firstinitial']});items.push({mode:'initials',label:Zw.localize('generic.label.initials'),disabled:!allowed['initials']});items.push({xtype:'div',cls:'white-horizontal-bar',anchor:'-28'});if(Zw.capabilities.ALLOW_CUSTOM_SIGNATURE){items.push({xtype:'Zw.features.messages.menus.TextFieldNameItem',mode:'custom',label:Zw.localize('generic.label.custom'),value:this.client.context.Settings.get('signature_custom')||this.fromName});}
items.push({xtype:'div',cls:'white-horizontal-bar',anchor:'-28'});items.push({mode:'off',label:Zw.localize('generic.label.off'),disabled:!allowed['off']});items.push({xtype:'div',cls:'white-horizontal-bar',anchor:'-28'});if(Zw.capabilities.EDIT_SELF){items.push({xtype:'Zw.controls.ContextMenu.Item',text:Zw.localize('generic.btn.editIdentity'),closeOnClick:true,cls:'edit-identity ',disabled:!Zw.capabilities.EDIT_SELF,handler:this._setIdentity,scope:this});}
return items;},showMenu:function(){Zw.Packages.get('menu.all',function(){if(!this.panel){this.buildMenu();}
var p=this.panel;if(!p.hidden){p.hide();}else{p.showBy(this.nameDiv);p.doLayout();var largestDelta=0;p.getEl().select('.nameitem .example').each(function(el){var delta=el.dom.scrollWidth-el.dom.offsetWidth;if(delta>largestDelta){largestDelta=delta;}});if(largestDelta){p.setWidth(p.getEl().getWidth()+largestDelta);p.doLayout();}
var client=this.client;if(client){this.highlightDropdownOption(client.mode);}}},this);},onDestroy:function(){if(this.window){this.window.toStore.un('add',this.makeSureNotJustIdentityCard,this);this.window.toStore.un('remove',this.makeSureNotJustIdentityCard,this);}
delete this.window;delete this.account;Ext.destroy(this.panel);delete this.panel;delete this.nameDivParent;Ext.destroy(this.nameDiv);delete this.nameDiv;}});Ext.reg('Zw.features.messages.SignatureDropdownPlugin',Zw.features.messages.SignatureDropdownPlugin);

Zw.features.messages.SignatureEnforcerPlugin=Ext.extend(Zw.Plugin,{textarea:undefined,protectedTextLength:undefined,mouseUpOriginalTarget:undefined,onInit:function(){var client=this.client;if(client){client.on('GoalChange',this.updateProtectedText,this);this.textarea=client.getTextarea();this.textarea.on('render',this.attachListeners,this);}},attachListeners:function(textarea){textarea.on('keyup',this.protectSignature,this);textarea.on('keypress',this.protectSignature,this);textarea.on('keydown',this.protectSignatureFromMeanKeyPresses,this);textarea.el.on('mousedown',this.setMouseUpOriginalTarget,this);Ext.getBody().on('mouseup',this.protectSignatureOnMouseUp,this);},setMouseUpOriginalTarget:function(e,textarea){this.mouseUpOriginalTarget=textarea;},protectSignatureOnMouseUp:function(e,textarea){if(this.mouseUpOriginalTarget===textarea){this.protectSignature(textarea);}},updateProtectedText:function(client,oldGoal,newGoal,preventSave){oldGoal=oldGoal||'';Zw.console('>> UpdateProtectedText',client,oldGoal,newGoal,preventSave);this.textarea.setValue(newGoal+this.client.getText().substring(oldGoal.length));this.protectedTextLength=newGoal.length;},protectSignatureFromMeanKeyPresses:function(textarea,e){var preventDefault=false;var body=this.getSelectionRange(textarea.el.dom);if(e.ctrlKey){if(body.trimLength<=this.protectedTextLength||body.precedingTrimLength<=this.protectedTextLength){preventDefault=true;}}else{if(body.textLength<=this.protectedTextLength||body.end<=this.protectedTextLength){preventDefault=true;}}
if(preventDefault){switch(e.getKey()){case e.BACKSPACE:case e.LEFT:case e.HOME:e.preventDefault();}}},protectSignature:function(textarea,e){textarea=textarea.el?textarea.el.dom:textarea;var protectedTextLength=this.protectedTextLength;var selectionRange=this.getSelectionRange(textarea);if((selectionRange.start<=protectedTextLength)||(selectionRange.end<=protectedTextLength)){this.setSelectionRange(textarea,{start:protectedTextLength,end:Math.max(protectedTextLength,selectionRange.end)});}},getSelectionRange:function(textarea){var result={};if(textarea.selectionStart!==undefined&&!isNaN(textarea.selectionStart)){var precedingTrim=textarea.value.substring(0,textarea.selectionStart).trim();result={start:textarea.selectionStart,end:textarea.selectionEnd,textLength:textarea.textLength,trimLength:textarea.value.trim().length,precedingTrimLength:precedingTrim.length};}else{var selectionRange=document.selection.createRange().duplicate();if(selectionRange.parentElement()==textarea){var beforeRange=document.body.createTextRange();beforeRange.moveToElementText(textarea);beforeRange.setEndPoint('EndToStart',selectionRange);var afterRange=document.body.createTextRange();afterRange.moveToElementText(textarea);afterRange.setEndPoint('StartToEnd',selectionRange);var beforeFinished=false,selectionFinished=false,afterFinished=false;var beforeText,untrimmedBeforeText,selectionText,untrimmedSelectionText,afterText,untrimmedAfterText;beforeText=untrimmedBeforeText=beforeRange.text;selectionText=untrimmedSelectionText=selectionRange.text;afterText=untrimmedAfterText=afterRange.text;do{if(!beforeFinished){if(beforeRange.compareEndPoints('StartToEnd',beforeRange)==0){beforeFinished=true;}else{beforeRange.moveEnd('character',-1);if(beforeRange.text==beforeText){untrimmedBeforeText+='\r\n';}else{beforeFinished=true;}}}
if(!selectionFinished){if(selectionRange.compareEndPoints('StartToEnd',selectionRange)==0){selectionFinished=true;}else{selectionRange.moveEnd('character',-1);if(selectionRange.text==selectionText){untrimmedSelectionText+='\r\n';}else{selectionFinished=true;}}}
if(!afterFinished){if(afterRange.compareEndPoints('StartToEnd',afterRange)==0){afterFinished=true;}else{afterRange.moveEnd('character',-1);if(afterRange.text==afterText){untrimmedAfterText+='\r\n';}else{afterFinished=true;}}}}while(!beforeFinished||!selectionFinished||!afterFinished);var untrimmedText=untrimmedBeforeText+untrimmedSelectionText+untrimmedAfterText;var untrimmedSuccessful=false;if(textarea.value==untrimmedText){untrimmedSuccessful=true;}
var startPoint=untrimmedBeforeText.length;var endPoint=startPoint+untrimmedSelectionText.length;var precedingTrim=untrimmedText.substring(0,startPoint).trim();result={start:startPoint,end:endPoint,textLength:untrimmedText.length,trimLength:untrimmedText.trim().length,precedingTrimLength:precedingTrim.length};}}
return result;},setSelectionRange:function(textarea,selectionRange){if(textarea.createTextRange){var selectionRangeLength=selectionRange.end-selectionRange.start;var textRange=textarea.createTextRange();textRange.collapse(true);textRange.moveStart('character',selectionRange.start);textRange.moveEnd('character',selectionRangeLength);textRange.select();}else if(textarea.setSelectionRange){textarea.setSelectionRange(selectionRange.start,selectionRange.end);}},onDestroy:function(){var client=this.client;if(client){client.un('GoalChange',this.onProtectedTextChange,this);var textarea=this.textarea;if(textarea){textarea.un('keyup',this.protectSignature,this);textarea.un('keypress',this.protectSignature,this);textarea.un('mouseup',this.protectSignature,this);}}
delete this.textarea;delete this.protectedText;}});Ext.reg('Zw.features.messages.SignatureEnforcerPlugin',Zw.features.messages.SignatureEnforcerPlugin);

Zw.namespace('Zw.features.messages');Zw.features.messages.NameSignaturePlugin=Ext.extend(Zw.Plugin,{window:null,context:null,account:null,goalObject:null,defaultMode:'firstinitial',mode:null,supportedModes:null,plugins:['Zw.features.messages.SignatureEnforcerPlugin','Zw.features.messages.WindowWidthPlugin','Zw.features.messages.GuestModeStrategyPlugin'],onInit:function onInit(){var client=this.client;if(!client)return;Ext.apply(this,this.pluginConfig);if(!this.supportedModes)
this.supportedModes={};this.addEvents({'BeforeModeChange':true,'ModeChanged':true,'BeforeGoalChange':true,'GoalChange':true,'BeforeIdentityChange':true,'IdentityChange':true});this.context=this.context||Zw.Application.Context;this.account=this.account||this.context.Account;this.signatureObject=client.pluginConfig.signature;this.mode=this.signatureObject.mode||this.mode;var identity=this.signatureObject.names;this.customValue=this.getCustomSignature();client.getText=this.getTextWithoutSignature.createDelegate(this);client.getFromName=this.getSignature.createDelegate(this);var textarea=this.getTextarea();if(textarea){textarea.on('render',this.onTextareaRender,this,{single:true});}
this.on('GoalChange',this.saveSignatureSettings,this,{buffer:true});this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/desktop/newtextwindow/namesignature'}));if(Zw.capabilities.ALLOW_NAME_SIGNATURE){this.addPlugin(new Zw.features.messages.SignatureDropdownPlugin());}
this.account.on('userData',this.checkForNewGoal,this);this.setIdentity(identity,true);},saveSignatureSettings:function saveSignatureSettings(sender,oldGoal,newGoal,preventSave){Zw.console("saveSignatureSettings(",sender,oldGoal,newGoal,preventSave,")");if(!preventSave){this.saveMode(this.mode);if(this.mode=='custom'){var old=this.getCustomSignature();old=old?old:'';var _new=this.customValue;_new=_new?_new:'';if(_new!==old){this.saveCustom(_new);}}}},saveMode:function(sig){if(this.context){this.context.Settings.set({'signature_mode':sig});}},saveCustom:function(sig){if(this.context){this.context.Settings.set({'signature_custom':sig});}},onDestroy:function(){this.account.un('userData',this.checkForNewGoal,this);delete this.textareaDom;delete this.signatureObject;delete this.context;delete this.account;var client=this.client;if(client){client.un('IdentityChange',this.onIdentityChange,this);client.un('DetermineGoal',this.onDetermineGoal,this);delete client.getText;delete client.getFromName;}},onTextareaRender:function(){var textarea=this.getTextarea();if(textarea){this.textareaDom=textarea.getEl().dom;}},getCustomSignature:function(){if(this.context){return this.context.Settings.get('signature_custom');}},determineGoalFromMode:function determineGoalFromMode(identity,mode){var G='';if(mode=='custom'){G=this.customValue;if((G!=='')&&!G){G=this.getCustomSignature();}}else{if(!identity){identity={firstName:'',lastName:''};}
G=Zw.util.formatName(identity.firstName,identity.lastName,mode);}
var e={goal:G};if(this.fireEvent('DetermineGoal',this,e,identity,mode)){if(e.goal){return String.format('{0}:',e.goal);}else{return'';}}
return this.goal;},getTextWithoutSignature:function(){var T=this.getText().substring(this.goal.length);return T;},getSignature:function(){if(this.goal){if(''!=this.goal)
return this.goal.substring(0,this.goal.length-1);}
return'';},setIdentity:function setIdentity(identity,preventSave){if(this.fireEvent('BeforeIdentityChange',this,this.identity,identity)){var old=this.identity;this._setIdentity(identity);this.fireEvent('IdentityChange',this,old,this.identity);this.onIdentityChange(preventSave);return this.identity;}
return this.identity;},_setIdentity:function(identity){var f=(Ext.isEmpty(identity.firstName)?this.defaultFirstName:(identity.firstName==Zw.localize('generic.text.unnamed'))?this.defaultFirstName:identity.firstName);if(Ext.isEmpty(f))
f='';var result={firstName:f,lastName:Ext.isEmpty(identity.lastName)?(Ext.isEmpty(f)?'':this.defaultLastName):identity.lastName};this.identity=result;},onIdentityChange:function onIdentityChange(preventSave){var goal=this.determineGoalFromMode(this.identity,this.mode);this.setGoal(goal,preventSave);},checkForNewGoal:function(account){if(!account.getAllNames)
return;this.mode=account.context.Settings.get('signature_mode');this.setIdentity(account.getAllNames());},setGoal:function setGoal(goal,preventSave){var oldGoal=this.goal;var newGoal=goal;if(this.fireEvent('BeforeGoalChange',oldGoal,newGoal,preventSave)){this.goal=goal;this.fireEvent('GoalChange',this,oldGoal,newGoal,preventSave);}},getGoal:function(){return this.goal;},getMode:function(){return this.mode;},setMode:function setMode(mode,customValue,preventSave){var oldMode=this.mode;var newMode=mode;if(this.fireEvent('BeforeModeChange',oldMode,newMode)){this.mode=mode;if(mode=='custom'){this.customValue=customValue;}
this.fireEvent('ModeChange',this,oldMode,newMode);}
this.onIdentityChange(preventSave);},getTextarea:function(){var client=this.client;if(client){return client.getField();}},getText:function(){var textarea=this.getTextarea();if(textarea){return textarea.getValue();}else{return'';}},setText:function(text){var textarea=this.getTextarea();if(textarea){textarea.setValue(text);if(this.textareaDom){this.textareaDom.selectionStart=this.len+1;this.textareaDom.selectionEnd=this.len+1;}
var client=this.client;if(client){client.fireTextChange();}}}});Zw.features.messages.GuestModeStrategyPlugin=Ext.extend(Zw.Plugin,{defaultFirstName:Zw.localize('generic.text.defaultFirstName'),defaultLastName:'',regularSupportedModes:{'first':true,'firstinitial':true,'last':true,'lastinitial':true,'full':true,'custom':true,'off':true,'initials':true},guestSupportedModes:{'first':true,'firstinitial':false,'last':false,'lastinitial':false,'full':false,'custom':false,'initials':false,'off':false},onInit:function(){this.setSupportedModes();var client=this.client;if(client){client.on('IdentityChange',this.onIdentityChange,this);client.on('DetermineGoal',this.onDetermineGoal,this);}},onDetermineGoal:function onDetermineGoal(sender,e){var forceMobileNumberEvenIfGuest=false;if(Zw.capabilities.REQUIRE_MOBILENUMBER_SIGNATURE){if(this.isGuest(true)&&!forceMobileNumberEvenIfGuest){}else{var client=this.client;if(client){var m=client.account.getMobileNumber();if(!m){m='55555555555';}
m=Zw.util.formatMobileNumber(m);if(e.goal){e.goal=e.goal+String.format(' {0}',m);}
else{e.goal=String.format('{0}',m);}}}}else{}},onIdentityChange:function onIdentityChange(sender,oldIdentity,newIdentity){if(!newIdentity.firstName&&!newIdentity.lastName){newIdentity.firstName=this.defaultFirstName;newIdentity.lastName=this.defaultLastName;}
this.setSupportedModes();},updateMode:function updateMode(reason){var m=this.determineMode();var client=this.client;if(client){client.setMode(m,client.customValue,reason);}},setSupportedModes:function setSupportedModes(){var client=this.client;if(client){if(this.isGuest()){client.supportedModes=this.guestSupportedModes;}else{client.supportedModes=this.regularSupportedModes;}}},isGuest:function(){var client=this.client;var identity=client.identity;if(identity)return identity.firstName==Zw.localize('generic.text.defaultFirstName');return true;},determineMode:function(){if(this.isGuest()){return'first';}else{var client=this.client;return(client&&client.mode)?client.mode:'firstinitial';}}});Ext.reg('Zw.features.messages.GuestModeStrategyPlugin',Zw.features.messages.GuestModeStrategyPlugin);

Zw.namespace('Zw.features.mapping');Zw.features.mapping.MappingFeature=Ext.extend(Zw.Feature,{_createWindow:function(args){return this.context.Desktop.registerWindow(new Zw.features.mapping.MappingWindow(Ext.apply(args,{contactCardFactory:this.context.getContactCardFactory(),messageManager:this.context.getMessageManager(),contactManager:this.context.getContactManager()})));},onInitLevel4:function(){var ctx=this.context;ctx.getMessageManager().mapMessages=ctx.getMessageManager().mapMessage=this.onMapMessage.createDelegate(this);ctx.getIdentityManager().mapContacts=ctx.getIdentityManager().mapContact=ctx.getContactManager().mapContact=ctx.getContactManager().mapContacts=this.onMapContacts.createDelegate(this);},onMapContacts:function(contacts){Zw.Packages.get('mapping.all',function(){Ext.each(contacts,function(contact){this._createWindow({loc:contact.get('loc'),latlong:contact.get('latlong'),contact:contact}).show();},this);},this);},onMapMessage:function(messages){Zw.Packages.get('mapping.all',function(){Ext.each(messages,function(message){var w=this._createWindow({loc:Zw.util.dynamicGetValue(message,'loc'),latlong:Zw.util.dynamicGetValue(message,'latlong'),contact:this.context.getContactManager().resolveContactFromMessage(message)});w.show();},this);},this);}});Zw.features.Factory.register(Zw.features.mapping.MappingFeature);

Zw.namespace('Zw.features.messages');Zw.features.messages.SmartForwardingIndicatorFeature=Ext.extend(Zw.Feature,{m_weMaskedThem:false,onInit:function(){this.setSettinglet({xtype:'Zw.features.messages.SmartForwardingSettinglet',tab:Zw.localize('generic.tab.forwarding'),pkg:'forwarding.settings'});},onStart:function(){this.context.Signals.on('settings',this.onSettingsSignal,this);this.context.Account.on('userData',this.onUserData,this);},onUserData:function(sender,user,settings){this.onSettingsSignal(sender,settings);},onSettingsSignal:function(sender,settings){if(!settings)return;if(Ext.type(settings)=='array')settings=settings[0];this.setting=Zw.util.formatMinutes(settings.smartForwarding_timeout,false);var instantMode=settings.smartForwarding_instant;if(instantMode){this.mask();}else{this.unmask();}},exitSmartForwardingMode:function(el){this.unmask();this.context.Settings.set({smartForwarding_instant:false});},createMaskMessage:function(){if(!this.maskEl){this.maskEl=Ext.getBody().createChild({tag:'div',cls:'ext-el-mask-msg',id:'smart-forwarding-mask-msg',children:[{tag:'div',cls:'title',html:Zw.localize('generic.settings.smartForwarding.active.title')},{tag:'div',cls:'content',html:String.format(Zw.localize('generic.settings.smartForwarding.active.text'),this.setting)},{tag:'div',id:'smart-forwarding-mask-btn'}]});this.btn=new Zw.controls.ActionButton({text:Zw.localize('generic.settings.smartForwarding.btn.imBack'),renderTo:'smart-forwarding-mask-btn',handler:this.exitSmartForwardingMode,scope:this})
this.maskEl.alignTo(Ext.getBody(),'c-c');}},mask:function(){this.m_weMaskedThem=true;this.context.Desktop.mask();this.createMaskMessage();},unmask:function(){if(!this.m_weMaskedThem)
return;this.context.Desktop.unmask();Ext.destroy(this.btn);Ext.destroy(this.maskEl);delete this.maskEl;}});Zw.features.Factory.register('Zw.features.messages.SmartForwardingIndicatorFeature');

Zw.features.messages.CharacterCounterWarningPlugin=Ext.extend(Zw.Plugin,{showFloatingWarningSetting:null,onInit:function(){var client=this.client;if(client){client.on('render',this.onRender,this,{buffer:true,single:true});this.showFloatingWarningSetting=this.context.Settings.get('sendMessage_characterCounterAlert');}},onRender:function(){var client=this.client;if(client){this.field=client.getField();client.on('textchange',this.onTick,this,{buffer:true});}},onDestroy:function(){delete this.field;if(this.floatingWarning){Ext.destroy(this.floatingWarning)}
if(this.el){Ext.destroy(this.el);delete this.el;}
delete this.token;delete this.metrics;delete this.showFloatingWarningSetting;},onTick:function(field,text,tokens){var client=this.client;if(!client)return;if(tokens&&tokens[0]){if(!tokens[0].w){if(!this.metrics){this.addPlugin(this.metrics=new Zw.util.FontMetricsPlugin({el:this.field.el}));}
var w=client.getField().el.getWidth(true);if(Ext.isIE){this.metrics.augmentTokens(tokens,w+2);}else{this.metrics.augmentTokens(tokens,w);}}}
this.token=null;if(tokens&&tokens.length>0){var t=tokens[tokens.length-1];if((t.pos+t.value.length)>140){for(var i=tokens.length-1;i>0;i--){var token=tokens[i];if(token){if(token.pos<=140){this.token=token;break;}}}}}
if(this.token){this.showIndicator(this.token);}else{this.hideIndicator();}},onWarningMouseOut:function(){this.el.removeClass('zw-length-warning-over');},onWarningMouseOver:function(){if(!this.floatingWarning){this.el.addClass('zw-length-warning-over');}},onWarningClick:function(){this.showFloatingWarning(true);},showIndicator:function(token){var el=this.field.el.parent();if(!this.el){this.el=el.createChild('<div class=\'zw-length-warning\' />');this.el.addClassOnOver('zw-length-warning-mo');this.el.on('click',this.onWarningClick,this);}
this.el.show();this.showFloatingWarning();this.updateIndicatorPosition(token);},updateIndicatorPosition:function(token){var L=this.el.getPadding('l')+this.field.el.getPadding('l')+10;var T=this.el.getPadding('t')+this.field.el.getPadding('t')+13;this.el.setLeftTop(L+token.x,T+token.y);this.updateFloatingWarningPosition();},hideIndicator:function(){if(this.el){this.el.hide();this.closeFloatingWarning();}},showFloatingWarning:function(showOnClick){if(showOnClick||this.showFloatingWarningSetting){if(!this.floatingWarning){this.floatingWarning=new Zw.controls.Window({renderTo:Ext.get(document.body),title:Zw.localize('generic.alert.characterLimit.title'),minimizable:false,maximizable:false,draggable:false,closeAction:'close',preventStatusBar:true,footer:false,resizable:false,shadow:false,cls:'zw-window-floatingLimitWarning',width:234,items:[{xtype:'div',cls:'text',html:Zw.localize('generic.alert.characterLimit.text')},{xtype:'div',cls:'confirmation',html:'<label><input type="checkbox" />'+Zw.localize('generic.alert.characterLimit.confirmation')+'</label>'}]});this.floatingWarning.on('close',this.floatingWarningClose,this);this.floatingWarning.on('beforeclose',this.floatingWarningBeforeClose,this);this.floatingWarning.on('show',this.focusTextarea,this);this.floatingWarning.show();this.floatingWarning.getEl().child('input').dom.checked=!this.showFloatingWarningSetting;if(showOnClick){this.updateFloatingWarningPosition(showOnClick);}}}},updateFloatingWarningPosition:function(showOnClick){if(this.floatingWarning){var floatingWarningEl=this.floatingWarning.getEl();this.floatingWarning.setPosition(floatingWarningEl.getAlignToXY(this.el.findParentNode('.zw-window-sendmessage'),'br-bl')[0]+28,floatingWarningEl.getAlignToXY(this.el,'br-tl')[1]+(showOnClick?14:5));}},focusTextarea:function(){if(this.field){this.field.focus();}},closeFloatingWarning:function(){var floatingWarning=this.floatingWarning;if(floatingWarning){floatingWarning.close();}
this.focusTextarea();},floatingWarningClose:function(){var floatingWarning=this.floatingWarning;if(floatingWarning){floatingWarning.un('close',this.floatingWarningClose,this);floatingWarning.un('beforeclose',this.floatingWarningBeforeClose,this);floatingWarning.un('show',this.focusTextarea,this);Ext.destroy(floatingWarning);delete this.floatingWarning;}},floatingWarningBeforeClose:function(){var floatingWarning=this.floatingWarning;if(floatingWarning){this.showFloatingWarningSetting=!floatingWarning.getEl().child('input').dom.checked;this.context.Settings.set({sendMessage_characterCounterAlert:this.showFloatingWarningSetting});}}});

Zw.namespace('Zw.controls');Zw.controls.CharacterCounterProgressBar=Ext.extend(Ext.ProgressBar,{chars:0,max:140,getTooltipText:function(){return String.format(Zw.localize('generic.tooltip.characterLimit'),this.chars,this.max)},updateTooltipText:function(){if(!this.tip){return;}
if(this.tip.rendered){this.tip.body.update(this.getTooltipText());}},initComponent:function(){Zw.controls.CharacterCounterProgressBar.superclass.initComponent.call(this);this.on('render',this._onRender);this.updateProgress=this.updateProgress.createInterceptor(function(percent,chars,max){this.chars=chars;this.max=max;return true;});},_onRender:function(sender){this.tip=new Ext.ToolTip({target:this.getEl(),html:this.getTooltipText()});this.tip.on('show',this.updateTooltipText,this);},onDestroy:function(){this.un('render',this._onRender);if(this.tip){this.tip.un('show',this.updateTooltipText,this);this.tip.destroy();}}});Ext.reg('Zw.controls.CharacterCounterProgressBar',Zw.controls.CharacterCounterProgressBar);

Zw.namespace('Zw.features.messages');Zw.features.messages.SendMessagePanel=Ext.extend(Zw.controls.Div,{layout:'border',cls:'swirl',code:'SendMessagePanel',toBoxMargins:'8 15 0 15',msgBoxMargins:'0 15 5 15',window:null,validateBeforeSend:false,contactCardFactory:null,referenceContactList:null,creationManager:null,maxChars:Zw.capabilities.MESSAGE_CHARACTER_LIMIT,toStore:null,defaults:{collapsible:false,extraCls:'zw-sendmessage-boxes',bodyStyle:'padding: 0'},initComponent:function(){this.addEvents({'keypress':true,'send':true});this.attachToStore(this.toStore);this.attachToGlobalStore();this.addPlugin(new Zw.util.FieldinatorPlugin());this.items=this.getItems();Zw.features.messages.SendMessagePanel.superclass.initComponent.call(this);},getItems:function(){if(Ext.form.DateField&&Ext.form.TimeField){this.deliveryPanel=new Ext.Panel({frame:true,hidden:true,hideMode:'offsets',baseCls:'deliveryPanel',items:[{xtype:'div',cls:'legend',html:Zw.localize('generic.btn.chooseDeliveryTime')},this.deliveryDatePicker=new Ext.form.DateField({cls:'delivery-date',width:110}),this.deliveryTimePicker=new Ext.form.TimeField({cls:'delivery-time',width:95}),{xtype:'div',cls:'timezone',html:Zw.util.getTimezone()},this.deliveryPanelCloseButton=new Zw.controls.Div({cls:'closeButton',baseMouseCls:'closeButton',addMouseClasses:true,addMouseEvents:true,listeners:{scope:this,'click':this.hideDeliveryPanel}})]});}
else{this.deliveryPanel=new Ext.Panel({frame:true,hidden:true,hideMode:'offsets',baseCls:'deliveryPanel'});}
return[{xtype:'Zw.controls.ToBox',code:'toBox',split:true,region:'north',height:41,maxHeight:150,margins:this.toBoxMargins,cmargins:'0 0 0 0',context:this.context,referenceContactList:this.referenceContactList,creationManager:this.creationManager,contactCardFactory:this.contactCardFactory,toStore:this.toStore,plugins:[new Zw.util.ProxyPlugin({namespace:'/desktop/message/window/panel/tobox'})]},{xtype:'div',cls:'zw-sendmessage-msgbox',collapsible:false,region:'center',height:150,border:false,split:true,margins:this.msgBoxMargins,cmargins:'0 0 0 0',layout:'border',items:[{xtype:'div',region:'center',border:false,layout:'border',code:'stuffBelowToolbar',items:[{xtype:'div',region:'center',border:false,layout:'fit',items:[{code:'textbox',xtype:'Zw.features.messages.SendMessageTextBox',pluginConfig:Ext.applyIf(this.pluginConfig||{},{context:this.context,window:this.window,from:this.from,signature:this.signature}),text:Zw.data.get(this.message,'body',' '),tabRoot:this.tabRoot,plugins:new Zw.util.ProxyPlugin({namespace:'/desktop/message/window/panel/textbox',args:{window:this.window,pluginConfig:this.pluginConfig}}),listeners:{'textChange':{fn:this._updateStatus,scope:this,buffer:true},'submit':{fn:this.send,scope:this,single:true},'keypress':{fn:this.onTextboxKeypress,scope:this,single:true}}},{xtype:'div',cls:'hardedge'}]},{region:'south',code:'southRegion',style:'margin-top: 5px',height:35,border:false,items:[{border:false,xtype:'div',cls:'zw-visual-counter-container',items:[{border:false,xtype:'div',cls:'zw-visual-counter',items:{xtype:'Zw.controls.CharacterCounterProgressBar',code:'characterCounterProgressBar',width:112,max:this.maxChars}},{xtype:'panel',code:'characterCounterTextIndicator',hidden:false,columnWidth:1,border:false,cls:'mouse-default zw-text-counter'}]},this.deliveryPanel,{xtype:'div',cls:'sendMessageButtonWrapper',items:{xtype:'Zw.controls.ActionButton',splitButton:Zw.capabilities.SEND_MESSAGE_WINDOW_SEND_OPTIONS_DROPDOWN,splitButtonHandler:this.showSendOptionsDropdown,iconCls:'zw-button-icon-send',code:'send',text:Zw.localize('generic.btn.send'),scope:this,disabled:this.readonly,handler:this._handleSend}}]}]}]}];},showDeliveryPanel:function(){this.delayedDelivery=true;this.deliveryPanel.show();this.field('southRegion').setHeight(105);this.doLayout();this.deliveryDatePicker.setValue((new Date()).format('n/j/Y'));this.deliveryTimePicker.setValue((new Date()).format('g:i A'));},hideDeliveryPanel:function(){this.delayedDelivery=false;this.deliveryPanel.hide();this.field('southRegion').setHeight(35);this.doLayout();},showSendOptionsDropdown:function(e,el){e.stopPropagation();Zw.Packages.get('menu.all',this._showSendOptionsDropdown,this,[e,el]);},_showSendOptionsDropdown:function(e,el){if(!this.sendOptionsDropdown){this.sendOptionsDropdown=new Zw.controls.FloatingPanel({allowOtherMenus:true,hidden:false,layout:'anchor',cls:'zw-oneButtonDropdown zw-corkboard-bodypanel x-menu',hideMode:'offsets',frame:false,border:false,preventContextMenu:true,items:[{xtype:'Zw.controls.WindowToolbarButtonGroup',clsAddl:'zw-windowtbar-scheduleDeliveryTime zw-windowtbar-btn-group-short',columns:1,items:[{xtype:'Zw.controls.WindowToolbarButton',text:Zw.localize('generic.btn.scheduleDeliveryTime'),iconCls:'zw-windowtbar-icon-scheduleDeliveryTime',iconAlign:'left',scale:'smallish',handler:this.showDeliveryPanel,scope:this}]}]});this.on('destroy',this.destroySendOptionsDropdown,this,{single:true});this.sendOptionsDropdown.showBy(this.field('send').el,'tl-bl?',[-2,-3]);this.sendOptionsDropdown.el.on('click',this.hideSendOptionsDropdown,this);}else{this.sendOptionsDropdown.show();}
var sideButtonWrap=Ext.get(el).parent();sideButtonWrap.addClass('x-btn-side-md');this.sendOptionsDropdown.on('hide',this.sideButtonRemoveMD,sideButtonWrap,{single:true});},hideSendOptionsDropdown:function(){this.sendOptionsDropdown.hide();},sideButtonRemoveMD:function(){this.removeClass('x-btn-side-md');},destroySendOptionsDropdown:function(){if(this.sendOptionsDropdown){this.sendOptionsDropdown.destroy();}},getFromAddress:function(){return this.field('textbox').getFromAddress();},getFromName:function(){return this.field('textbox').getFromName();},getBody:function(){return this.field('textbox').getText();},setBody:function(body){this.field('textbox').setText(body);},validate:function(){this._updateStatus();return!this.disabledFromSending;},_handleSend:function(){if(this.validateBeforeSend){if(!this.validate()){Ext.Msg.show({modal:false,msg:this.disabledFromSendingMessage,title:Zw.localize('generic.alert.cantSendYet'),closable:true,buttons:Ext.Msg.OK});}else{var message=this.getSendToken();this.fireEvent('send',this,message);}}else{this.fireEvent('send',this);}},getSendToken:function(){var message={to:this.toStore.getRange(),body:this.getBody(),from:this.from,fromName:this.getFromName(),fromAddress:this.getFromAddress(),get:function(field){return this[field];}};Zw.console('>>> this.message',message);if(this.delayedDelivery){var deliveryDate=this.deliveryDatePicker.getValue();var deliveryTime=this.deliveryTimePicker.getValue();var parsedTime=/(\d+):(\d+) (AM|PM)/.exec(deliveryTime);var timeHours=parseInt(parsedTime[1]);if((parsedTime[3]==='PM')&&(timeHours<12)){timeHours+=12;}
if((parsedTime[3]==='AM')&&(timeHours===12)){timeHours-=12;}
var timeMinutes=parseInt(parsedTime[2],10);Zw.console('time',timeHours,timeMinutes);deliveryDate=deliveryDate.add(Date.HOUR,timeHours).add(Date.MINUTE,timeMinutes);message.delayedDelivery=true;message.deliveryDate=deliveryDate.getTime();message.deliveryDateLocal=deliveryDate.getTime();}
return message;},attachToStore:function(store){this.toStore=store;this.toStore.on('add',this._updateStatus,this);this.toStore.on('remove',this._updateStatus,this);},detachToStore:function(store){},onTextboxKeypress:function(){this.fireEvent('keypress',this,arguments);},onContactsRemoved:function(sender,record){var id=record.id;if(this.toStore){var rec=this.toStore.findBy(function(rec){return(rec.id==id);});if(rec!=-1)
this.toStore.remove(this.toStore.getAt(rec));}},onContactsUpdated:function(sender,record){var id=record.id;if(!this.toStore)
return;var rec=this.toStore.findBy(function(rec){return(id==rec.id);});if(-1!=rec){this.toStore.fireEvent('update',this.toStore,this.toStore.getAt(rec),'forced');}},attachToGlobalStore:function(){var c=this.contactManager.getContacts();if(c){c.on('update',this.onContactsUpdated,this);c.on('remove',this.onContactsRemoved,this);}},detachToGlobalStore:function(){var c=this.contactManager.getContacts();if(c){c.un('update',this.onContactsUpdated,this);c.un('remove',this.onContactsRemoved,this);}},_updateStatus:function(){if(this.destroyed){return;}
var value=this.field('textbox').getField().getValue()||'';var length=Zw.util.StringUtil.getInstance().getUTF8Length(value);var percent=parseInt((length/this.maxChars)*14)/14;var isTooLong=(length>this.maxChars);if(this.field('characterCounterProgressBar').rendered){this.field('characterCounterProgressBar').updateProgress(percent,length,this.maxChars);}
if(this.field('characterCounterTextIndicator').rendered){if(length>(this.maxChars*.8))
this.field('characterCounterTextIndicator').getEl().update(String.format('{0}/{1}',length,this.maxChars));else
this.field('characterCounterTextIndicator').getEl().update('');}
var disabled=false;var needMoreContacts=Zw.localize('generic.alert.messageValidations.text1');var needMessage=Zw.localize('generic.alert.messageValidations.text2');var tooLong=String.format(Zw.localize('generic.alert.messageValidations.text3'),this.maxChars);var notDoneWithContacts=Zw.localize('generic.alert.messageValidations.text4');if(this.field('textbox').getField().getValue()==''){disabled=needMessage;}else if(isTooLong){disabled=tooLong;}else if(this.toStore.getCount()==0){disabled=needMoreContacts;}else if(this.numberOfProcessingContacts){if(this.numberOfProcessingContacts>0){disabled=notDoneWithContacts;}}else{disabled=false;}
this.toStore.each(function(contact){if(Zw.util.isZipgroupContact(contact)){var context=Zw.Application.Context;var device=context.Account.getDevice(contact.get('targetGroupDevice'));if(device){if(device.getContactsCount()==0){disabled=Zw.localize('generic.alert.noMembers');return false;}}}},this);this.disabledFromSending=disabled;this.disabledFromSendingMessage=disabled;},onDestroy:function(){this.detachToGlobalStore();Zw.features.messages.SendMessagePanel.superclass.onDestroy.apply(this,arguments);}});Ext.reg('Zw.features.messages.SendMessagePanel',Zw.features.messages.SendMessagePanel);Zw.features.PluginFactory.register('/desktop/message/window/panel/textbox',function(args){var plugins=[];args=args||{};if(!args.readonly){plugins.push(new Zw.features.messages.NameSignaturePlugin(args.pluginConfig));}
if(!Ext.isAir&&Zw.capabilities.ALLOW_TEXT_SUGGEST&&Zw.features.messages.SendMessageWindowTextSuggestPlugin){plugins.push(new Zw.features.messages.SendMessageWindowTextSuggestPlugin({setting:args.pluginConfig.textSuggestSetting,window:args.window}));}
return plugins;});

Zw.namespace('Zw.features.messages');Zw.features.messages.SendMessageWindow=Ext.extend(Zw.controls.Window,{title:Zw.localize('window.title.sendText'),dirty:false,layout:'fit',readonly:false,stuffBelowToolbarReadonlyAnchor:'0, 12',width:280,height:360,minWidth:100,minHeight:150,closeAction:'destroy',disabledFromSending:true,delayedDelivery:false,cls:'zw-window zw-window-sendmessage',listeners:{'beforelayout':function(){if(!this.addedAfterLayoutHandler){this.addedAfterLayoutHandler=true;this.field('field').getSplitBar().on('beforeresize',this.markToBoxDragHandleDirty,this);}},'show':function(){var fontMetrics=new Zw.util.FontMetricsPlugin(this.nameDiv);var textareaEl=this.field('textbox').find('code','body')[0].el;var textareaInnerWidth=textareaEl.getWidth()-textareaEl.getBorderWidth('lr');if(this.nameDiv){var nameDivText=Zw.util.stripHTML(this.nameDiv.child('.c').dom.innerHTML);var nameDivTextWidth=fontMetrics.getMeasurement(nameDivText);var delta=nameDivTextWidth-textareaInnerWidth+30;if(delta>0){this.setWidth(this.width+delta);}}}},isWindow:true,html:'',toBoxVisible:true,initEvents:function(){Zw.features.messages.SendMessageWindow.superclass.initEvents.call(this);this.addEvents({'send':true,'readonly':true,'tochange':true,'command':true});this.on('send',function(sender,message){if(message.deliveryDate){this.context.publish('/desktop/corkboard/show',{tab:'scheduled'});}},this);this.on('sendTextAjaxSuccess',function(sender,message){if(message.deliveryDate){this.close.defer(5000,this);}},this);},initComponent:function(){this.toStore=Zw.util.createToStoreForDropdown(this.to);this.addPlugin(new Zw.controls.plugins.WindowKeyMapPlugin({keyMapConfig:{key:[Ext.EventObject.ENTER],ctrl:true,scope:this,fn:this.onCtrlEnter}}));this.bbar=new Zw.controls.StatusBar({statusAlign:"left",defaultText:'',defaultIconCls:'default-icon',text:'',iconCls:'ready-icon'});this.tbar=[];if(this.readonly){this.tbar=[new Zw.features.messages.SendMessageToolbarActionButtonGroup({handler:this._readOnlyToolbarHandler.createDelegate(this),deleteEnabled:(this.message?(Ext.type(this.message.get)=='function'):false)}),new Zw.features.messages.SendMessageToolbarJumpButtonGroup({handler:this._readOnlyToolbarHandler.createDelegate(this)})];}
if(Ext.isEmpty(this.referenceContactList)){this.referenceContactList=this.context.getContactManager().getContacts({debug:false,alias:'SendMessageWindow.Contacts'});}
this.items={xtype:'Zw.features.messages.SendMessagePanel',referenceContactList:this.referenceContactList,creationManager:this.context.getContactManager(),contactManager:this.context.getContactManager(),contactCardFactory:this.context.getContactCardFactory(),window:this,context:this.context,pluginConfig:this.pluginConfig,message:this.message,toStore:this.toStore,listeners:{scope:this,'keypress':{fn:this._onSendMessageTextBoxDirty,scope:this,single:true},'send':this.attemptSend}};Zw.features.messages.SendMessageWindow.superclass.initComponent.call(this);},_onSendMessageTextBoxDirty:function(){this.dirty=true;},setToBoxVisibleState:function(state){var lower=this.field('toBoxLowerItems');if(this.toBoxVisible&&state){}else if(this.toBoxVisible&&!state){var t=this.find('code','tobox')[0];t.remove(lower);var w=this.find('code','toboxupper')[0];w.anchor='100%, 0';delete w.anchorSpec;}else if(!this.toBoxVisible&&state){var t=this.find('code','tobox')[0];t.add(lower);var w=this.find('code','toboxupper')[0];w.anchor='100%, -31';delete w.anchorSpec;}
this.doLayout();this.toBoxVisible=state;},hideToBox:function(){this.setToBoxVisibleState(false);},showToBox:function(){this.setToBoxVisibleState(true);},determineDisplayForUpdateTitle:function(record){var firstName=record.get('firstName');var lastName=record.get('lastName');var hasLastName=!Ext.isEmpty(lastName);var hasFirstName=!Ext.isEmpty(firstName);var isUnnamed=!hasLastName&&!hasFirstName;var isGroup=record.get('targetGroupDevice');if(isUnnamed){return isGroup?null:Zw.util.formatMobileNumber(record.get('mobileNumber'));}else if(hasLastName){return String.format("{0} {1}",firstName,lastName);}else{return firstName;}},updateTitle:function(){var numberOfContacts=this.toStore.getCount();if(numberOfContacts>=1){var max=this.toStore.getCount();if(max>3)max=3;var text='';var things=[];var record,recordTitle;for(var i=0;i<max;i++){record=this.toStore.getAt(i);recordTitle=this.determineDisplayForUpdateTitle(record);if(recordTitle){things.push(recordTitle);}}
if(things.length){text=things.join(', ');this.setTitle(String.format("{0} - "+Zw.localize('window.title.sendText'),text));}}else{this.setTitle(Zw.localize('window.title.sendText'));}},_handleSendMessage:function(){this.send();},markToBoxDragHandleDirty:function(){this.dirtyResize=true;this.toBox.getSplitBar().un('beforeresize',this.markToBoxDragHandleDirty,this);},focus:function(delay){delay=Ext.isEmpty(delay)?true:delay;if(this.toStore.getCount()>0){this.field('textbox').focus(false,delay);}},_readOnlyToolbarHandler:function(sender){this.fireEvent('command',this,sender.code);},_syncSize:function(){this.syncSize();},setToolbarVisibleState:function(state){if(state&&!this.tbarVisible&&Zw.capabilities.SHOW_SEND_MESSAGE_WINDOW_TOOLBAR){if(!this.tbarCache){var t=this.getTopToolbar();t.add(new Zw.features.messages.SendMessageToolbarActionButtonGroup({handler:this._readOnlyToolbarHandler,scope:this}));t.add(new Zw.features.messages.SendMessageToolbarJumpButtonGroup({handler:this._readOnlyToolbarHandler,scope:this}));this.tbarCache=true;}
this.getTopToolbar().getEl().slideIn('t',{scope:this,callback:this._syncSize});this.tbarVisible=true;}else if(!state&&this.tbarVisible){this.tbarVisible=false;this.getTopToolbar().getEl().slideOut('t',{scope:this,callback:this._syncSize});}},setReadonly:function(value){var e=null;this.readonly=value;if(value)
this.getEl().addClass('zw-readonly');else
this.getEl().removeClass('zw-readonly');if(value){var toolbar=this.find('code','toolbar')[0];if(toolbar)
toolbar.hide();var stuffBelowToolbar=this.find('code','stuffBelowToolbar')[0];if(stuffBelowToolbar)
stuffBelowToolbar.anchor=this.stuffBelowToolbarReadonlyAnchor;}
this.doLayout();e=this.field('textbox').getField().getEl();if(value){e.addClass('x-item-disabled');e.set({'readonly':true});}
this.field('send').setDisabled(value);this.fireEvent('readonly',this,this.readonly);},setFromAddress:function(mode,always){this.from={mode:mode,always:always};},addPhoneNumber:function(mobileNumber){if(mobileNumber){this.field('toBox').addPhoneNumber(null,mobileNumber);}},afterRender:function(){Zw.features.messages.SendMessageWindow.superclass.afterRender.call(this);this.focus();this.setReadonly.defer(30,this,[this.readonly]);},getFromAddress:function(){return this.field('textbox').getFromAddress();},getFromName:function(){return this.field('textbox').getFromName();},getBody:function(){return this.field('textbox').getText();},setBody:function(body){this.field('textbox').setText(body);},attemptSend:function(){var field=this.field('SendMessagePanel');if(!field.validate()){Ext.Msg.show({modal:false,msg:field.disabledFromSendingMessage,title:Zw.localize('generic.alert.cantSendYet'),closable:true,buttons:Ext.Msg.OK});}else{var message=field.getSendToken();if(!this.message){this.message=message;}
this.fireEvent('send',this,message);}},onCtrlEnter:function(){this.attemptSend();},destroy:function(){Zw.features.messages.SendMessageWindow.superclass.destroy.call(this);Ext.destroy(this.toStore);delete this.toStore;}});Ext.reg('Zw.features.messages.SendMessageWindow',Zw.features.messages.SendMessageWindow);

Zw.features.messages.NewTextButtonGroup=Ext.extend(Zw.controls.LargeButtonGroup,{name:'New Text Group',showSplit:true,initComponent:function(){this.items=[{xtype:'Zw.controls.LargeButton',text:Zw.localize('generic.btn.newText'),minWidth:105,iconCls:'zw-toptoolbar-icon-newtext',disabled:true}];if(this.showSplit){this.items.push({xtype:'Zw.controls.DetailSeparator'});this.items.push({xtype:'Zw.controls.LargeButton',text:'',code:'newtextsplit',iconCls:'zw-toptoolbar-icon-newtextsplit',handler:this.showNewTextButtonDropdown,scope:this});}
Zw.features.messages.NewTextButtonGroup.superclass.initComponent.call(this);},showNewTextButtonDropdown:function(button,e){Zw.Packages.get('menu.all',this._showNewTextButtonDropdown,this,[button,e]);},_showNewTextButtonDropdown:function(button,e){if(!this.newTextDropdown){this.newTextDropdown=new Zw.controls.FloatingPanel({allowOtherMenus:true,hidden:false,layout:'anchor',cls:'zw-newTextButtonDropdown zw-corkboard-bodypanel x-menu',hideMode:'offsets',frame:false,border:false,preventContextMenu:true,items:[{xtype:'Zw.controls.WindowToolbarButtonGroup',clsAddl:'zw-windowtbar-btn-group-tall zw-windowtbar-action zw-windowtbar-tall-action',columns:1,items:[{xtype:'Zw.controls.WindowToolbarButton',text:Zw.localize('generic.btn.newZipgroupText'),iconCls:'zw-windowtbar-icon-newZipgroupText',iconAlign:'left',scale:'smallish',handler:this.fireNewZipgroup,scope:this},{xtype:'div',cls:'zw-ec-action-line'},{xtype:'Zw.controls.WindowToolbarButton',text:Zw.localize('generic.btn.newScheduledText'),iconCls:'zw-windowtbar-icon-newScheduledText',iconAlign:'left',scale:'smallish',handler:this.fireNewScheduled,scope:this}]}]});this.on('destroy',this.destroyNewTextDropdown,this,{single:true});this.newTextDropdown.showBy(this.getEl(),'tl-bl?',[2,-10]);}else{this.newTextDropdown.show();}
button.addClass('x-btn-click');this.newTextDropdown.on('hide',this.sideButtonnRemoveMD,button,{single:true});},fireNewScheduled:function(){this.fireEvent('newscheduled',this);this.newTextDropdown.hide();},fireNewZipgroup:function(){this.fireEvent('newzipgroup',this);this.newTextDropdown.hide();},sideButtonnRemoveMD:function(){this.removeClass('x-btn-click');},destroyNewTextDropdown:function(){if(this.newTextDropdown){this.newTextDropdown.destroy();}}});Ext.reg('Zw.features.messages.NewTextButtonGroup',Zw.features.messages.NewTextButtonGroup);

Zw.features.messages.SendMessageLifecycleManagementPlugin=Ext.extend(Zw.Plugin,{closeClientWindowDelay:1500,routes:null,onInit:function(){var client=this.client;if(client){this.routes=new Ext.util.MixedCollection();this.addEvents({'beforeClose':true,'sendingComplete':true});this.on('sendingComplete',this.context.Signals.exitCriticalRegion);this.on('sendingComplete',this.closeClientWindow,this);this.on('sendingComplete',this.showClientToolbar,this);this.on('sendingComplete',this.resumeClient,this);this.closeClientWindowTask=new Ext.util.DelayedTask(this.closeClientWindow,this);client.addEvents({'sendTextAjaxSuccess':true});client.on('send',this.onSendMessage,this);if(this.blind){this.blind.on('show',this.onBlindShow,this);}}},onBlindShow:function(){if(this.task){this.task.invoke();}},getWindowKeepOpenSetting:function(){var context=this.context;if(context){return context.Settings.get('sendMessage_keepOpen');}},closeClientWindow:function(instantly){if((this.getWindowKeepOpenSetting()===false)&&!this.bar.error){this.closeClientWindowTask.cancel();if(this.fireEvent('beforeClose')){var client=this.client;if(client){if(instantly){client.close();}else{this.closeClientWindowTask.delay(this.closeClientWindowDelay,undefined,undefined,[true]);}}}}},showClientToolbar:function(){if(this.getWindowKeepOpenSetting()===true){var client=this.client;if(client&&client.setToolbarVisibleState){client.setToolbarVisibleState(true);}}},_resumeClient:function(){var client=this.client;if(client){client.onResume();}
if(this.blind){this.blind.hide();}},resumeClient:function(){if(this.getWindowKeepOpenSetting()==='resume'){var client=this.client;if(client&&this.blind){this.blind.doMinimize({callback:this._resumeClient,scope:this});}}},onSendMessage:function(sender,message){var window=this.client;if(window){window.setReadonly(true);}
this.message=message;var bar=null;if(this.blind){bar=((this.bar=this.blind.getProgressBar()));}
var isMultiple=message.to.length>1;if(!isMultiple){var contact=message.to[0];isMultiple=Zw.util.isAdhocGroupContact(contact)||Zw.util.isZipgroupContact(contact);}
if(bar){bar.multiple=isMultiple;bar.initDescriptionPlugins(isMultiple);bar.setContact(message.to);}
var blind=this.blind;if(blind){blind.delayedDelivery=message.delayedDelivery;blind.deliveryDateLocal=message.deliveryDateLocal;}
this.task=this.createTask(message);this.keys=this.task.contacts;this.expectReceipt=false;if(blind&&bar){blind.show();blind.getEl().focus();bar.setValue(1);}else{this.task.invoke();}},onAjaxSuccess:function(sender,e){var client=this.client;if(client){if(this.bar){this.bar.setValue(2);}
if(e){if(e.success){var message=this.message;this.client.fireEvent('sendTextAjaxSuccess',this,message);if(!this.bar||!this.blind){return;}
if(e.response){this.addMessageRoutes(e.response.tokens);}
this.context.Signals.enterCriticalRegion();}else{var r=e.response;if(r&&r.result){r=r.result;}
if(this.bar){this.bar.setError({value:2,desc:(r||Zw.localize('generic.alert.messageRejected'))});}}}}},onAjaxFailure:function(content){if(this.bar){this.bar.setError({value:1,desc:Zw.localize('generic.alert.couldntCommunicateWithServer')});}},createTask:function(message){return Zw.Application.Net.sendMessage({delayInvoke:true,identity:this.context.Account.getMobileNumber(),context:this.context,message:message,success:this.onAjaxSuccess,failure:this.onAjaxFailure,scope:this});},_addMessageRoute:function(route){var key=route.message;var error=false;var prog=0;if(route.progress){if(route.progress.error){prog=Zw.util.convertServerStatusToProgress(route.progress.value);error=true;}}
this.routes.add(key,{progress:prog,route:route,error:error});this.blind.addChildProgressBar(route);var progress=route.progress;if(progress){if(progress.error){this.bar.setError(progress);this.blind.updateProgress({complete:false,route:route,error:progress});}}else{this.blind.updateProgress({complete:false,route:route,progress:2});}
this.context.Signals.addMessageStatusRoute(key,this.onIncomingSignal,this);},addMessageRoutes:function(keys){Ext.each(keys,this._addMessageRoute,this);},onIncomingSignal:function(sender,key,serverCode){var bar=this.bar;var blind=this.blind;if(!bar||!blind)
return;var obj=this.routes.get(key);if(Ext.type(serverCode)=="object"){var defaultMsg=Zw.localize('generic.alert.unableToSendMessage');var desc=serverCode?(serverCode.desc?serverCode.desc:defaultMsg):defaultMsg;var error={value:3,desc:desc,code:serverCode.code};bar.setError(error);if(obj){obj.error=error;obj.progress=Zw.util.convertServerStatusToProgress(serverCode);blind.updateProgress({complete:false,route:obj.route,progress:obj.progress,error:error});}
this.context.Signals.exitCriticalRegion();this.context.Signals.removeMessageStatusRoute(key,this.onIncomingSignal,this);}else{obj.progress=Zw.util.convertServerStatusToProgress(serverCode);obj.complete=this.isComplete(obj.progress);blind.updateProgress({complete:obj.complete,route:obj.route,progress:obj.progress});}
var LCD=this.findLCD();bar.setValue(LCD);if(this.isComplete(LCD)){bar.setComplete();}
this.testForClose();},isComplete:function(progress){return(progress==5&&!this.expectReceipt)||(progress==6);},findLCD:function(){var result=null;this.routes.each(function(route){Zw.console('ROUTE:',route);if(!route.error){if(route.progress<result||(result==null)){result=route.progress;}}});return result;},testForClose:function(){var context=this.context;if(context){var signals=context.Signals;if(signals){var allCompleteOrInError=true;var toRemove=[];this.routes.each(function(value){if(!value.complete){var route=value.route;var progress=value.progress;var key=route.message;if(this.isComplete(progress)){toRemove.push(key);Zw.console("This route",route,"is complete. So we're removing it");signals.removeMessageStatusRoute(key,this.onIncomingSignal,this);}else{Zw.console("This route",route,"is NOT complete. So we're waiting.");allCompleteOrInError=false;}}},this);Ext.each(toRemove,this._removeRoute,this);if(allCompleteOrInError){this.fireEvent('sendingComplete',this);}}}},_removeRoute:function(item){this.routes.removeKey(item);},onDestroy:function(){var client=this.client;if(client){client.un('send',this.onSendMessage,this);}
delete this.blind;delete this.bar;delete this.task;delete this.context;}});

Zw.namespace('Zw.features.messages');Zw.features.messages.NewTextFeature=Ext.extend(Zw.Feature,{textSuggestSetting:null,settingletKey:'newtext',group:'Zw.features.messages.NewTextButtonGroup',windows:null,onInit:function(){this.referenceContactList=this.context.getContactManager().getContacts({debug:false,alias:'SendMessageWindow.Contacts'})
this.windows=[];var sendMsgObj={xtype:'Zw.features.messages.SendMessageWindowSettinglet',pkg:'messages.settings',tab:Zw.localize('generic.tab.messaging')};var nameSigObj={xtype:'Zw.features.messages.NameSignatureSettinglet',pkg:'messages.settings',tab:Zw.localize('generic.tab.contacts')};var textSugObj={xtype:'Zw.features.messages.TextSuggestSettinglet',pkg:'messages.settings',tab:Zw.localize('generic.tab.messaging')};var settingsList=Zw.capabilities.ALLOW_TEXT_SUGGEST?[sendMsgObj,nameSigObj,textSugObj]:[sendMsgObj,nameSigObj];this.setSettinglet(settingsList);this.textSuggestSetting={enabled:true};var context=this.context;if(context){context.subscribe('/desktop/message/new',this.newMessage,this);context.subscribe('/app/exit/before',this.onBeforeNavigateAway,this);context.subscribe('/desktop/message/open',this.openMessage,this);context.subscribe('/desktop/message/reply',this.replyMessage,this);context.subscribe('/desktop/message/replyGroup',this.replyGroupMessage,this);context.subscribe('/desktop/message/fwd',this.fwdMessage,this);context.subscribe('/desktop/message/resend',this.resendMessage,this);context.subscribe('/desktop/zipgroup/text',this.onNewZipgroupText,this);context.subscribe('/account/user/data',this.onAuthenticated,this);context.subscribe('/account/user/registered',this.onRegistered,this);context.Settings.on('changed',this.onSettingsChanged,this,{buffer:true});context.subscribe('/account/contacts/load',this.onContactsLoaded,this);}
this.group.on('newscheduled',this.onNewScheduledText,this);this.group.on('newzipgroup',this.onNewZipgroupText,this);},onInitLevel4:function(){var mmanager=this.context.getMessageManager();mmanager.openMessage=this.openMessage.createDelegate(this);mmanager.newMessage=this.newMessage.createDelegate(this);mmanager.resendMessage=this.resendMessage.createDelegate(this);mmanager.replyMessage=this.replyMessage.createDelegate(this);mmanager.fwdMessage=this.fwdMessage.createDelegate(this);},onNewScheduledText:function(){this.context.publish('/desktop/message/new',{callback:this.onNewScheduledTextCallback});},onNewScheduledTextCallback:function(sendTextWindow){sendTextWindow.field('SendMessagePanel').showDeliveryPanel();},onNewZipgroupText:function(){this.context.publish('/account/device/save',{lazySave:true,scope:this,callback:function(sender,e){var contact=e.contact;this.context.publish('/desktop/message/new',{contacts:contact,callback:function(window){var contactCard=window.field('toBoxUpperItems').getControlByRecord(contact);if(contactCard){contactCard.showZoomGroup();}}});}});},onBeforeNavigateAway:function(e){for(var i=0;i<this.windows.length;i++){var window=this.windows[i];if(window.dirty){e.cancel=true;return;}}},onStart:function(){var context=this.context;if(context){context.publish('/app/cache/add',{triggerChannel:'/desktop/message',cls:'zw-send-progress-bar-cached',delay:'10000'});}
this.updateIsGuest();if(this.m_window)
this.m_window.setActive(true);},newMessage:function(args){if(!Zw.capabilities.ALLOW_GUEST&&this.context.Account.isGuest()){return;}
var contacts;var handler=Ext.emptyFn;var scope;if(args){if(Ext.type(args)=='array'){contacts=args;}else{scope=args.scope||this;handler=args.callback||args.handler||handler;contacts=args.contacts;}}
args=args||{};if(Ext.type(contacts)!='array')contacts=[contacts];if(contacts){if(contacts.length==1){var c=contacts[0];if(!c){contacts=[];}else if(c.id==-1){if(Zw.data.get(c,'mobileNumber')=='5555555555'){return;}}}
var result=[];var deviceId=this.context.Account.getWebsiteDeviceId();var contactManager=this.context.getContactManager();Ext.each(contacts,function(contact){if(Zw.util.isAdhocGroupContact(contact)){var list=contactManager.expandContactsFromGroup(contact);if(Ext.type(list)=='array'){Ext.each(list,function(L){result.push(L);},this);}else{result.push(list);}}else if(Zw.data.get(contact,'deviceId')!=deviceId){result.push(contactManager.findContactByAddressOrCreateContact(Zw.data.get(contact,'address'),{firstName:Zw.data.get(contact,'firstName'),lastName:Zw.data.get(contact,'lastName'),mobileNumber:Zw.data.get(contact,'mobileNumber'),phoneKey:Zw.data.get(contact,'phoneKey')}));}else{result.push(contact);}},this);contacts=result;}
var w=null;if(!args.reuse){w=this._createWindow({to:contacts||[]});w.show();}else{w=this.windows[0];if(!w){w=this._createWindow({to:contacts||[]});w.show();}}
handler.call(scope,w);return w;},replyGroupMessage:function(messages){if(!messages){return;}
Ext.each(messages,function(message){var deviceId=Zw.data.get(message,'fromDeviceId');var device=this.context.Account.getDeviceById(deviceId);var deviceAddress=null;if(device){deviceAddress=device.getAddress();}
var contact=this.context.getContactManager().findContactByMobileNumber(deviceAddress);if(!contact){return;}
contact=Ext.isArray(contact)?contact:[contact];this.context.publish('/desktop/message/new',{contacts:contact});},this);},replyMessage:function(messages){if(!messages){return;}
Ext.each(messages,function(message){var contact=this.context.getContactManager().getContactFromMessage(message);contact=Ext.isArray(contact)?contact:[contact];this.context.publish('/desktop/message/new',{contacts:contact});},this);},resendMessage:function(messages){if(!messages){return;}
Ext.each(messages,this._resendSingleMessage,this);},_resendSingleMessage:function(message){var contact=this.context.getContactManager().getContactFromMessage(message);contact=Ext.isArray(contact)?contact:[contact];this._createWindow({to:contact,message:message}).show();},fwdMessage:function(messages){Ext.each(messages,this._fwdSingleMessage,this);},_fwdSingleMessage:function(message){this._createWindow({message:message}).show();},openMessage:function(messages,args){Ext.each(messages,function(message){var contact=this.context.getContactManager().getContactFromMessage(message);Zw.console('Contacts from message',contact);if(Ext.type(contact)!='array'){contact=[contact];}
this._createWindow({to:contact,message:message,readonly:true}).show();},this);},updateIsGuest:function(){if(!Zw.capabilities.ALLOW_GUEST){if(this.context.Account.isGuest(true))
this.group.items.itemAt(0).disable();else
this.group.items.itemAt(0).enable();}else{this.group.items.itemAt(0).enable();}},onAuthenticated:function(args){if(this.context.Account.isGuest()){this.wasGuest=true;}
this.updateIsGuest();if(args.reason&&(args.reason!=='registration')&&(args.reason!=='identityUpdate')){this.loadInitialSendMessageWindow();}},onRegistered:function(){this.loadInitialSendMessageWindow();},onSettingsChanged:function(){this.textSuggestSetting.enabled=this.context.Settings.get('textSuggest_enabled');Zw.console("NextTextFeature - Text Suggest is enabled ",this.textSuggestSetting.enabled);},loadInitialSendMessageWindow:function(){if(!Zw.capabilities.FORCE_INITIAL_SENDTEXT_WINDOW&&!Zw.capabilities.ALLOW_GUEST&&this.context.Account.isGuest(true))
return;if(Zw.capabilities.FORCE_NO_INITIAL_SENDTEXT_WINDOW)
return;var isLive=true;if(isLive||Zw.preloadedMobileNumber){var w=this._loadWindow();if(w){if(Zw.preloadedMobileNumber){this.context.Account.getContacts().on('load',function(){w.addPhoneNumber(Zw.preloadedMobileNumber);Zw.preloadedMobileNumber=null;},this,{single:true});}}}},_handleToolbarClick:function(window,message,contacts,code){var m=this.context.getMessageManager();switch(code){case'reply':m.replyMessage(message);break;case'fwd':m.fwdMessage(message);break;case'resend':m.resendMessage(message);break;case'delete':m.deleteMessage(message);window.close();break;case'convo':this.publish('/desktop/conversation/view',{contact:window.toStore.getRange()});break;}},onBlindSettingsChanged:function(blind,key,value){if(key=='ding'&&value===true)
this.context.publish('/app/sound/play',{sound:'outgoingMessage',volume:this.context.Settings.get('riser_volume')});},onBlindDestroy:function(blind){blind.un('SettingsChanged',this.onBlindSettingsChanged,this);},_createWindow:function(a){if(!a){a={};}
if(Ext.isEmpty(a.to)){a.to=[];}
if(Ext.type(a.to)!=='array'){a=[a];}
var context=this.context;if(!context)return;var account=context.Account;var c=context.getContactManager();var blindPlugins=[];if(Zw.capabilities.ALLOW_TEXTADS){var advert=null;if(context.Adverts){advert=context.Adverts.getAdvert();}
if(advert){blindPlugins.push(new Zw.features.messages.PostSendDisplayAdvertBarPlugin({advert:advert,plugins:[new Zw.features.messages.PostSendDisplayAdvertBarClickTrackingPlugin({sessionKey:context.Account.getSessionKey()})]}));}}
var blind=new Zw.controls.PostSendDisplay({header:true,plugins:blindPlugins,settings:context.Settings,context:context});blind.on('SettingsChanged',this.onBlindSettingsChanged,this);blind.on('destroy',this.onBlindDestroy,this,{singe:true});a=Ext.applyIf(a,{to:a.to,readonly:a.readonly,message:a.message,contactManager:c,context:context,referenceContactList:this.referenceContactList,pluginConfig:{textSuggestSetting:this.textSuggestSetting,signature:{names:account.getAllNames(),mode:this.context.Settings.get('signature_mode')}},plugins:[new Zw.util.ProxyPlugin({namespace:'/desktop/message/window'}),new Zw.util.FieldinatorPlugin(),new Zw.util.SendMessageWindowTabinatorPlugin(),blind,new Zw.features.messages.SendMessageLifecycleManagementPlugin({context:this.context,blind:blind,plugins:[new Zw.features.messages.PreventCloseForSendProgressBarNotCompletePlugin(),new Zw.features.messages.PreventCloseForPostSendDisplayMOPlugin(),new Zw.features.messages.PreventCloseForZiptipMOPlugin(),new Zw.features.messages.PreventCloseForSettingsDropdownIsVisiblePlugin()]})],contactCardFactory:context.getContactCardFactory(),identityManager:context.getIdentityManager()});a.plugins.push(new Zw.util.ProxyPlugin({namespace:'/desktop/newtextwindow/create'}));var result=context.Desktop.registerWindow(new Zw.features.messages.SendMessageWindow(a));result.on('command',this.onWindowToolbarCommand,this);result.blind=blind;this.onWindowOpen(result);result.on('destroy',this.onWindowClose,this,{single:true});return result;},onWindowOpen:function(window){this.windows.push(window);window.toStore.on('remove',this.onToStore_remove,this);},onToStore_remove:function(store,contact){this.removeContactIfNotSaved(contact);},removeContactIfNotSaved:function(contact){if(Zw.util.isZipgroupContact(contact)){var device=this.context.Account.getDevice(Zw.data.get(contact,'targetGroupDevice'));if(device&&!device.saved){this.context.publish('/account/device/delete',{device:device});}}},onWindowClose:function(window){window.toStore.un('remove',this.onToStore_remove,this);window.toStore.each(this.removeContactIfNotSaved,this);this.windows.remove(window);},onWindowToolbarCommand:function(sender,code){var message=sender.message;var contacts=sender.toStore.getRange();this._handleToolbarClick(sender,message,contacts,code);},_loadWindow:function(){var isGuest=this.context.Account.isGuest();var allowGuest=Zw.capabilities.ALLOW_GUEST;if(isGuest&&!allowGuest){return;}
var w=this._createWindow();w.show();this.m_window=w;return w;},onGroupClick:function(targetGroup,targetButton){if(targetButton.code==='newtextsplit'){return;}
this.context.publish('/desktop/message/new');},onDestroy:function(){this.context.un('BeforeNavigateAway',this.onBeforeNavigateAway,this);var mmanager=this.context.getMessageManager();if(mmanager){delete mmanager.openMessage;delete mmanager.newMessage;delete mmanager.resendMessage;delete mmanager.replyMessage;delete mmanager.fwdMessage;}}});Zw.features.Factory.register('Zw.features.messages.NewTextFeature');

Zw.namespace('Zw.examples');Zw.features.messages.RiserAdapterFeature=Ext.extend(Zw.Feature,{pkg:'riser.all',onInit:function(){this.setSettinglet({xtype:'Zw.features.messages.RiserWindowSettinglet',pkg:'riser.settings',tab:Zw.localize('generic.tab.messaging')});var context=this.context;if(context){context.subscribe('/account/message/receive',this.downloadPackage,this);}},onStart:function(){var context=this.context;if(context){context.publish('/app/cache/add',{triggerChannel:'/desktop/message',cls:['zw-riser-bubblevert-cached','zw-riser-bubblehoriz-cached','zw-riser-bubblevert-readonly-cached','zw-riser-bubblehoriz-readonly-cached','zw-riser-bubblehoriz-mo-cached','zw-riser-bubblehoriz-md-cached'],delay:'15000'});}},onDownloadPackageComplete:function(records){Zw.console("RiserAdapterFeature is processing records",records);var s=this.context.Settings;if(!s.get('riser_enabled')){Zw.console("Quitting because the riser is not enabled");return;}
Ext.each(records,this._onEachRecord,this);},_onEachRecord:function(item){Zw.console("Showing Riser?",item);if(item.get('deviceId')==this.context.Account.getWebsiteDeviceId()){if(item.get('type')=='MO'&&!item.get('deleted')&&!item.get('isRead')){Zw.console("Showing Riser for ",item);this.context.Desktop.showIncomingMessageNotification(item);}}}});Zw.features.Factory.register('Zw.features.messages.RiserAdapterFeature',Zw.features.messages.RiserAdapterFeature);

Zw.namespace('Zw.features.conversation');Zw.features.conversation.ConversationFeature=Ext.extend(Zw.Feature,{windows:null,onInit:function(){this.windows=new Ext.util.MixedCollection();this.context.subscribe('/desktop/conversation/view',this.showConversationForSomething,this);},checkoutWindow:function(data){var address=Zw.data.get(data,'address');var w=this.windows.get(address);if(!w){w=this.context.Desktop.registerWindow(new Zw.features.conversation.ConversationWindow({address:address,context:this.context,plugins:[new Zw.util.ProxyPlugin({namespace:'/desktop/conversation/window',args:{context:this.context}})]}));w.on('destroy',function(){this.windows.removeKey(address);},this,{single:true});this.windows.add(address,w);}
return w;},showConversationForMessage:function(messages){if(Ext.isArray(messages)){Ext.each(messages,function(message){this.checkoutWindow(message).show();},this);}else{this.checkoutWindow(messages).show();}},showConversationForContact:function(contact){if(Ext.isArray(contact)){Ext.each(contact,function(contact){this.checkoutWindow(contact).show();},this);}else{this.checkoutWindow(contact).show();}},showConversationForSomething:function(args){var contact=args.contact;var message=args.message;if(contact){Zw.Packages.get('conversation.all',this.showConversationForContact,this,[contact]);}else{Zw.Packages.get('conversation.all',this.showConversationForMessage,this,[message]);}}});Zw.features.Factory.register(Zw.features.conversation.ConversationFeature);

Zw.namespace('Zw.features.corkboard');Zw.features.corkboard.CorkboardButton=Ext.extend(Zw.controls.LargeButton,{text:Zw.localize('generic.btn.corkboard'),minWidth:62,iconCls:"zw-toptoolbar-icon-corkboard"});

Zw.features.corkboard.CorkboardButtonGroup=Ext.extend(Zw.controls.LargeButtonGroup,{name:Zw.localize('generic.toolbar.name.corkboardGroup'),initComponent:function(){this.detailUnread=new Zw.features.corkboard.UnreadToolbarDetail({unreadCount:this.unreadCount||0,startHidden:false});this.separator=new Zw.controls.ToolbarDetail({cls:"zw-toptoolbar-sep",startHidden:false});Ext.apply(this,{items:[new Zw.features.corkboard.CorkboardButton(),this.separator,this.detailUnread]});Zw.features.corkboard.CorkboardButtonGroup.superclass.initComponent.call(this);},onAfterRender:function(){Zw.features.corkboard.CorkboardButtonGroup.superclass.onAfterRender.call(this);},setUnreadCount:function(count){if(this.detailUnread)
this.detailUnread.setUnreadCount(count);},getUnreadCount:function(){if(this.detailUnread)
return this.detailUnread.getUnreadCount();else
return undefined;},showUnread:function(){if(Ext.isIE){return;}
this.el.scale(130,undefined,{easing:'easeOut',remove:false,duration:0.5,scope:this});this.detailUnread.show();this.separator.show();},hideUnread:function(){if(Ext.isIE){return;}
this.el.scale((Ext.isSafari?89:83),undefined,{easing:'easeOut',remove:false,duration:1,scope:this});this.detailUnread.hide();this.separator.hide();if(Ext.isIE){var tdEl=this.el.parent();tdEl.scale(78,undefined,{easing:'easeOut',remove:false,duration:0.5,scope:this});}},xshowUnread:function(){var totalWidthToAdd=this.separator.el.getWidth()+this.detailUnread.el.getWidth();var newWidth=this.el.getWidth()+totalWidthToAdd;this.el.scale(newWidth,undefined,{easing:'easeOut',remove:false,duration:0.5,scope:this});this.detailUnread.el.pause(0.5).slideIn('l',{easing:'easeOut',remove:false,duration:0.4,scope:this});this.separator.el.pause(0.4).slideIn('l',{remove:false,duration:0.2,scope:this});},xhideUnread:function(){var totalWidthToRemove=this.separator.el.getWidth()+this.detailUnread.el.getWidth();var newWidth=this.el.getWidth()-totalWidthToRemove;this.detailUnread.el.slideOut('l',{easing:'easeOut',remove:false,duration:0.3});this.separator.el.slideOut('l',{easing:'easeOut',remove:false,duration:0.1});this.el.scale(newWidth,undefined,{easing:'easeOut',remove:false,duration:0.5});}});Ext.reg('Zw.features.corkboard.CorkboardButtonGroup',Zw.features.corkboard.CorkboardButtonGroup);


Zw.features.corkboard.CorkboardToolbarActionButtonGroup=Ext.extend(Zw.controls.WindowToolbarButtonGroup,{clsAddl:'zw-windowtbar-action',handler:Ext.emptyFn,columns:4,initComponent:function(){this.defaults={xtype:"Zw.controls.WindowToolbarButton",handler:this.handler,disabled:true,scope:this.scope};this.items=[{text:Zw.localize('generic.btn.open'),code:'open',iconCls:"zw-windowtbar-icon-open",rowspan:2},{text:Zw.localize('generic.btn.reply'),code:'reply',iconCls:"zw-windowtbar-icon-reply",rowspan:2},{text:Zw.localize('generic.btn.fwd'),code:'fwd',iconCls:"zw-windowtbar-icon-fwd",rowspan:2},{text:Zw.localize('generic.btn.resend'),code:'resend',iconCls:"zw-windowtbar-icon-resend",scale:'small',iconAlign:'left'},{text:Zw.localize('generic.btn.del'),code:'delete',iconCls:"zw-windowtbar-icon-del",scale:'small',iconAlign:'left'}];Zw.features.corkboard.CorkboardToolbarActionButtonGroup.superclass.initComponent.call(this);}});Zw.features.corkboard.CorkboardToolbarJumpButtonGroup=Ext.extend(Zw.controls.WindowToolbarButtonGroup,{clsAddl:'zw-windowtbar-jump',initComponent:function(){this.items=[{xtype:"Zw.controls.WindowToolbarButton",text:Zw.localize('generic.btn.conversation'),code:'conversation',disabled:true,handler:this.handler,scope:this.scope||this,iconCls:"zw-windowtbar-icon-conv"}];Zw.features.corkboard.CorkboardToolbarActionButtonGroup.superclass.initComponent.call(this);}});

Ext.namespace('Zw','Zw.features','Zw.features.corkboard');Zw.features.corkboard.UnreadToolbarDetail=Ext.extend(Zw.controls.ToolbarDetail,{unreadCount:0,initComponent:function(){Zw.features.corkboard.UnreadToolbarDetail.superclass.initComponent.call(this);var title=Zw.localize('generic.text.unread');this.template=new Ext.Template('<div class="zw-toptoolbar-detail {hiddenCls}" style="{style}">','<div class="zw-toptoolbar-detail-unread">','<div class="zw-toptoolbar-detail-unreadcount">{count}</div>','<div class="zw-toptoolbar-detail-text">'+title+'</div>','</div>','</div>');this.unreadCountElSelector="div.zw-toptoolbar-detail-unreadcount";},getTemplateArgs:function(){var args=Zw.features.corkboard.UnreadToolbarDetail.superclass.getTemplateArgs.call(this);args=Ext.apply(args,{count:this.unreadCount});return args;},setUnreadCount:function(count){if(count<0)
count=0;if(!this.countEl)
this.countEl=this.el.child(this.unreadCountElSelector);this.unreadCount=count;this.countEl.dom.innerHTML=count;},getUnreadCount:function(){return this.unreadCount;}});

Ext.namespace('Zw.examples');Zw.features.corkboard.CorkboardFeature=Ext.extend(Zw.Feature,{m_window:null,group:'Zw.features.corkboard.CorkboardButtonGroup',pkg:['riser.all','corkboard.window'],proxy:{x:16,y:115,w:275},monitorGuestState:true,disableGroupIfGuest:function(){return!Zw.capabilities.ALLOW_GUEST;},onInit:function(){this.proxy.h=Zw.util.getBrowserSize().height-103-40;this.setSettinglet({xtype:'Zw.features.corkboard.CorkboardWindowSettinglet',tab:Zw.localize('generic.tab.messaging'),pkg:'corkboard.settings'});this.context.on('afterstart',this.onAfterStart,this,{single:true});this.context.subscribe('/desktop/corkboard/show',this.showCorkboard,this);if(!Zw.Application.debug){this.preloadCorkboardWindow.defer(20000,this);}
this.unreadMessages=[];},markMessageAsRead:function(message){delete this.unreadMessages[message.id]},markMessageAsUnread:function(){this.unreadMessages[message.id]=true;},preloadCorkboardWindow:function(){var context=this.context;if(context){context.publish('/app/cache/add',{cls:['zw-window-corkboard-cached','zw-tabs-cached'],pkg:['riser.all','corkboard.window'],delay:10});}},onAfterStart:function(){var m=this.context.Account.getMessages();m.on('add',this.onMessageAdd,this);m.on('update',this.onMessageUpdate,this);m.on('datachanged',this.onDataChanged,this);m.on('remove',this.onMessageRemoved,this);},showCorkboard:function(args){this.downloadPackage(args);},onDownloadPackageComplete:function(args){if(!this.m_window){this.m_window=this.context.Desktop.registerWindow(new Zw.features.corkboard.CorkboardWindow({plugins:[new Zw.util.ProxyPlugin({namespace:'/desktop/corkboard/window',args:{context:this.context}})],title:Zw.localize('window.title.corkboard'),messageManager:this.context.getMessageManager(),contactCardFactory:this.context.getContactCardFactory()}));}
this.m_window.show();this.m_window.toFront();if(args&&args.tab){this.m_window.activateTab(args.tab);}
if(args&&args.handler){var scope=args.scope||this;args.handler.call(scope,this.m_window);}},onGroupClick:function(sender,e){if(e.name==Zw.localize('generic.btn.corkboard')){this.context.publish('/desktop/corkboard/show',{tab:'all'});}},updateGroup:function(count){this.count=count;var g=this.group;if(count>0){g.setUnreadCount(count);g.showUnread();}else{this.count=0;g.setUnreadCount(0);g.hideUnread();}},_onMessageRemoved:function(record){if(!record.get('isRead')){this.updateGroup(this.count-1);}},_onMessageAdd:function(record){if(record.get('type')=='MO'){if(record.get('isRead'))
this.updateGroup(this.count);else
this.updateGroup(this.count+1);}},onMessageRemoved:function(sender,records){Ext.each(records,this._onMessageRemoved,this);},onMessageAdd:function(store,records){Ext.each(records,this._onMessageAdd,this);var tx=false;var rx=false;var t=Ext.type(records);if(t=='array'){for(var i=0;i<records.length;i++){(records[i].get('type').toLowerCase()=='zo')?(tx=true):(rx=true);}}else{(records.get('type').toLowerCase()=='zo')?(tx=true):(rx=true);}
var onTx=this.context.Settings.get('corkboard_send');var onRx=this.context.Settings.get('corkboard_receive');if((onRx&&rx)||(onTx&&tx)){this.context.publish("/desktop/corkboard/show");}},_onMessageUpdate:function(record){if(record.get('type')=='MO'){if(record.get('isRead'))
this.updateGroup(this.count-1);else
this.updateGroup(this.count+1);}},onMessageUpdate:function(store,records){Ext.each(records,this._onMessageUpdate,this);},onDataChanged:function(store,records){var items=store.query('isRead',false).filterBy(function(item){return item.get('type')=='MO';});this.updateGroup(items.getCount());},onDestroy:function(){var m=this.context.Account.getMessages();m.un('add',this.onMessageAdd,this);m.un('update',this.onMessageUpdate,this);m.un('datachanged',this.onDataChanged,this);m.un('remove',this.onMessageRemoved,this);Ext.destroy(this.m_window);delete this.m_window;}});Zw.features.Factory.register(Zw.features.corkboard.CorkboardFeature);

Zw.namespace('Zw.features.contacts');Zw.features.contacts.ContactsButton=Ext.extend(Zw.controls.LargeButton,{text:this.text||Zw.localize('generic.btn.contacts'),minWidth:68,iconCls:"zw-toptoolbar-icon-contacts"});Ext.reg('Zw.features.contacts.ContactsButton',Zw.features.contacts.ContactsButton);

Zw.features.contacts.NewContactButton=Ext.extend(Zw.controls.LargeButton,{text:Zw.localize('generic.btn.newContact'),name:Zw.localize('generic.btn.newContact'),minWidth:68,iconCls:"zw-toptoolbar-icon-newcontact"});Ext.reg('Zw.features.contacts.NewContactButton',Zw.features.contacts.NewContactButton);

Zw.features.contacts.ContactsButtonGroup=Ext.extend(Zw.controls.LargeButtonGroup,{name:Zw.localize('generic.toolbar.name.contactsGroup'),initComponent:function(){var superclass=Zw.features.contacts.ContactsButtonGroup.superclass;this.items=[{xtype:'Zw.features.contacts.ContactsButton'}];if(Zw.capabilities.ALLOW_NEW_CONTACT){this.items.push({xtype:'Zw.controls.DetailSeparator'});this.items.push({xtype:'Zw.features.contacts.NewContactButton'});}
superclass.initComponent.call(this);},onAfterRender:function(){Zw.features.contacts.ContactsButtonGroup.superclass.onAfterRender.call(this);}});Ext.reg('Zw.features.contacts.ContactsButtonGroup',Zw.features.contacts.ContactsButtonGroup);

Ext.namespace('Zw.features.contacts');Zw.features.contacts.ContactsFeature=Ext.extend(Zw.Feature,{pkg:'contact.view',group:'Zw.features.contacts.ContactsButtonGroup',monitorGuestState:true,editContactWindowXType:'Zw.features.contacts.EditContactWindow',editGroupWindowXType:'Zw.features.contacts.EditGroupWindow',disableGroupIfGuest:function(){return!Zw.capabilities.ALLOW_GUEST;},onInit:function(){this.m_windows=[];this.m_availableWindows=[];this.setSettinglet({xtype:'Zw.features.contacts.MyContactSettinglet',pkg:'contact.settings',tab:Zw.localize('generic.tab.account')});this.context.subscribe('/desktop/contact/new',this._createNewContact,this);this.context.subscribe('/desktop/contact/edit',this._editContact,this);this.context.subscribe('/desktop/contact/find',this._targetContact,this);this.context.subscribe('/desktop/phone/zoom',this.packagedViewZoomWindow,this);this.context.subscribe('/desktop/contacts/show',this._downloadPackageThenShowContactsWindow,this);this.context.subscribe('/desktop/device/new',this._createNewDevice,this);this.onAuthenticatedAsGuest();this.preloadContactsWindow.defer(30000,this);},_createNewContact:function(args){Zw.Packages.get('contact.edit',this.__createNewContact,this,args?[args]:undefined);},__createNewContact:function(args){var w=this._createEditContactWindowFor(new Zw.data.Contact({}));if(args&&args.handler){args.handler.call(args.scope||this,w);}},_createNewDevice:function(args){Zw.Packages.get('contact.edit',this.__createNewDevice,this,args?[args]:undefined);},__createNewDevice:function(args){var contacts=[];Ext.each(args.contacts,function(contact){contacts.push(contact.copy());},this);var real=(contacts&&contacts.length>0);this.publish('/account/device/save',{lazySave:!real,contactsSeed:contacts,scope:this,callback:function(sender,e){var contact=e.contact;var device=e.device;var w=this._createEditContactWindowFor(contact,{zipgroup:true,device:device});w.show();}});if(args&&args.handler){args.handler.call(args.scope||this,w);}},preloadContactsWindow:function(){var context=this.context;if(context){context.publish('/app/cache/add',{cls:['zw-window-contacts-cached'],pkg:'contact.view',delay:10});}},packagedViewZoomWindow:function(phone){if(!Zw.features.phone||!Zw.features.phone.ZoomWindow){this.context.publish('/app/packages/get',{pkg:'phone.edit',fn:this._showZoomPhoneWindowFor,scope:this,params:[phone]});}else{this._showZoomPhoneWindowFor(phone);}},onInitLevel4:function(){var c=this.context.getContactManager();var i=this.context.getIdentityManager();c.choosePhone=this._choosePhone.createDelegate(this);i.choosePhone=this._choosePhone.createDelegate(this);c.editContact=this._editContact.createDelegate(this);c.createNewContact=this._createNewContact;c.__createNewContact=this.__createNewContact.createDelegate(this);c.targetContact=this._targetContact.createDelegate(this);i.targetContact=this._targetContact.createDelegate(this);},__targetContact:function(contact){this._onContactsClick({handler:function(){this.m_contactsWindow.targetContact(contact);},scope:this});},_targetContact:function(contact){Zw.Packages.get('contact.view',this.__targetContact,this,[contact]);},_choosePhone:function(args){Zw.Packages.get('phone.edit',function(){var w=this.context.Desktop.registerWindow(new Zw.features.phone.ChoosePhoneWindow({phoneKey:args.phoneKey,listeners:{scope:args.scope||this,'phonesaved':args.callback}}));w.show();},this);},_editContact:function(args){Zw.Packages.get('contact.edit',this.__editContact,this,[args]);},__editContact:function(args){if(args.contact.id==-1){this.context.publish('/desktop/identity/edit',args);}else{this._createEditContactWindowFor(args.contact);}},onGroupClick:function(sender,e){if(e.name==Zw.localize('generic.btn.contacts')){this._onContactsClick();}else
this._onNewClick();},_onContactsClick:function(args){this.context.publish('/desktop/contacts/show',args);},_onNewClick:function(){this.context.getContactManager().createNewContact();},onDownloadPackageComplete:function(args){this._showContactsWindow(args);},_downloadPackageThenShowContactsWindow:function(args){this.downloadPackage(args);},_showContactsWindow:function(args){if(!this.m_contactsWindow){var c=this.context.Account.getContacts();if(!Zw.preventContactsSort){c.sort('firstName','ASC');}
this.m_contactsWindow=this.context.Desktop.registerWindow(new Zw.features.contacts.ContactsWindow({title:Zw.localize('window.title.contacts'),messageManager:this.context.getMessageManager(),contactManager:this.context.getContactManager(),plugins:[new Zw.util.ProxyPlugin({namespace:'/desktop/contacts/window',args:{context:this.context}})],contactCardFactory:this.context.getContactCardFactory(),contacts:new Zw.data.ClonedStore({debug:false,alias:'ContactsList',store:c})}));}
this.m_contactsWindow.show();if(args){if(args.handler){var scope=args.scope||this;args.handler.call(scope,this.m_contactsWindow);}}},_createEditContactWindowFor:function(contact,args){if(!args)args={};var m;if(contact.id==-1){m=this.context.getIdentityManager();}else{m=this.context.getContactManager();}
var editWindow;var editWindowArgs=Ext.apply({contactCardFactory:this.context.getContactCardFactory(),contact:contact,context:this.context},args);var isZipgroupContact=Zw.util.isZipgroupContact(contact)||args.zipgroup;var foo=!Ext.isEmpty(isZipgroupContact)?this.editGroupWindowXType:this.editContactWindowXType;var obj=eval(!Ext.isEmpty(isZipgroupContact)?this.editGroupWindowXType:this.editContactWindowXType);editWindow=new obj(editWindowArgs);this.context.Desktop.registerWindow(editWindow);editWindow.show();return editWindow;},_showEditContactWindow:function(){Zw.Packages.get('contact.edit',function(){var w=this._createEditContactWindowFor();w.show();w.toFront();},this);},_showZoomPhoneWindowFor:function(phone){var zoomPhoneWnd=this.context.Desktop.registerWindow(new Zw.features.phone.ZoomWindow({phone:phone}));zoomPhoneWnd.show();return zoomPhoneWnd;},onDestroy:function(){var c=this.context.getContactManager;delete c.createNewContact;delete c.__createNewContact;delete c.editContact;if(this.m_contactsWindow){Ext.destroy(this.m_contactsWindow);delete this.m_contactsWindow;}}});Zw.features.Factory.register(Zw.features.contacts.ContactsFeature);

Zw.namespace('Zw.features.contacts');Zw.features.contacts.ContactCardFactoryFeature=Ext.extend(Zw.Feature,{onInit:function(){this.context.getContactCardFactory=Zw.util.returnScope(this);},onInitLevel5:function(){this.context.un('initLevel5',this.onInitLevel5,this);this.identityManager=this.context.getIdentityManager();this.contactManager=this.context.getContactManager();this.messageManager=this.context.getMessageManager();},createContactCard:function(args){return new Zw.controls.ContactCard(this.wrapContactCardArgs(args));},resolveContact:function(contact){return this.contactManager.findContactByAddress(Zw.data.get(contact,'address'));},wrapContactCardArgs:function(args){var websiteDeviceId=this.context.Account.getWebsiteDeviceId();args=Ext.isEmpty(args)?{}:args;args=Ext.applyIf(args,{xtype:'Zw.controls.ContactCard',factory:this,plugins:[],extendedView:true});var p=args.plugins;if(!p){p=[];}
var isZipgroup=false;if(args.resolveContact){if(args.isSelf){args.contact=this.context.getContactManager().getContact(-1);}else if(args.contactId){if(args.contactDeviceId){args.contact=this.context.getContactManager().getContactByIdAndDeviceId(args.contactId,args.contactDeviceId);}else{args.contact=this.context.getContactManager().getContact(args.contactId);}}
if(!args.contact&&args.address){if(Zw.util.isZipgroupAddress(args.address)){isZipgroup=!!this.context.Account.getDevice(args.address);args.contact=this.context.getContactManager().findContactByAddress(args.address);}else{args.contact=this.context.getContactManager().findContactByAddress(args.address);}}
if(!args.contact&&args.contactId&&(args.contactDeviceId==this.context.Account.getWebsiteDeviceId())){args.plugins.push({init:function(client){this.client=client;this.store=this.client.factory.context.Account.getContacts();this.store.on('add',this.onAdd,this);},onAdd:function(store,records){Ext.each(records,function(record){if(record.id==args.contactId){this.client.setContact(record);this.destroy();return false;}},this);},destroy:function(){this.store.un('add',this.onAdd,this);delete this.store;delete this.client;}});}}
var contactArgs=args;if(args.contact){contactArgs=args.contact;}
var address=Zw.data.get(contactArgs,'address');isZipgroup=Zw.util.isZipgroupAddress(address);var isAdHocGroup=Zw.util.isAdhocGroupAddress(address);var contactDeviceId=args.contactDeviceId||Zw.data.get(args.contact,'deviceId');var isMembershipCard=Zw.util.isMembershipContact(contactDeviceId,websiteDeviceId);if(isMembershipCard){if(!args.preventMembershipCard){p.push(new Zw.controls.plugins.ContactCardMembershipCardPlugin({device:contactDeviceId,context:this.context,bubblePanel:args.bubblePanel}));}
if(!args.contact){p.push(new Zw.controls.plugins.ContactCardDelayLoadPropertiesPlugin({context:this.context,contactId:args.contactId,deviceId:contactDeviceId}));}
args.preventEditContact=true;args.preventFindInContacts=true;}
if(isAdHocGroup===true){p.push(new Zw.controls.plugins.ContactCardAdHocGroupPlugin());if(Zw.controls.plugins.ContactCardZoomGroupPlugin)
p.push(new Zw.controls.plugins.ContactCardZoomGroupPlugin());args.preventPhoneIcon=true;args.preventEditContact=true;}
if(isZipgroup===true||args.isGroupCard){p.push(new Zw.controls.plugins.ContactCardZipgroupPlugin());if(Zw.controls.plugins.ContactCardZoomGroupPlugin){p.push(new Zw.controls.plugins.ContactCardZoomGroupPlugin());}
args.preventPhoneIcon=true;}
if(!args.preventPopup){p.push(new Zw.controls.plugins.ContactCardPopupPlugin());}
if(!args.preventDropdown&&!Zw.capabilities.PREVENT_CONTACT_CARD_DROPDOWN){p.push(new Zw.controls.plugins.ContactCardDropdownPlugin({context:this.context}));}
if(!args.preventPhoneIcon){p.push(new Zw.controls.plugins.ContactCardPhoneIconPlugin());}
if(!args.preventExtendedView){p.push(new Zw.controls.plugins.ContactCardExtendedViewPlugin());}
if(!args.preventEditContact){p.push(new Zw.controls.plugins.ContactCardEditNamePlugin());}
var carrierId=Zw.data.get(args.contact,'carrier');var isCarrierSupported=Zw.data.isCarrierSupported(carrierId);if(!Zw.data.isCarrierSupported(carrierId)){p.push(new Zw.controls.plugins.ContactCardCarrierUnsupportedErrorPlugin({context:this.context,carrierId:carrierId,isCarrierSupported:isCarrierSupported}));}
p.push(new Zw.util.ProxyPlugin({namespace:'/desktop/contact/card',args:args}));return args;},getContactCardPopupMenu:function(card){var contact=card.getContact();if(this.cardMenu){this.cardMenu.card.destroy();delete this.cardMenu.card;this.cardMenu.destroy();delete this.cardMenu;}
var _card=this.createContactCard({closebox:false,popup:true,contact:contact});this.cardMenu=new Ext.menu.Menu({cls:'zw-cleanmenu zw-ppa-flip',onMouseOver:Ext.emptyFn,shadow:false,allowOtherMenus:true,minWidth:199,items:[new Ext.menu.Adapter(_card,{hideOnClick:false,hideDelay:0,stateful:false})]});this.cardMenu.card=_card;return this.cardMenu;},showContactCardPopupMenu:function(card){var menu=this.getContactCardPopupMenu(card);if(menu.el){menu.card.setContact(card.getContact());menu.showAt(menu.el.getAlignToXY(card.el,'c-c'));}else{menu.card.setContact(card.getContact());menu.show(card.el);menu.showAt(menu.el.getAlignToXY(card.el,'c-c'));}
return menu;},onViewContacts:function(){this.card.showZoomGroup();},getFlipViewMenu:function(phoneRecord,flipped){var h=flipped?phoneRecord.get('normal_flip_h')+9:42;var w='34';var cls=Zw.data.Phone.GetBasePhoneIconClass(phoneRecord.get('phoneKey'));var url=Zw.data.Phone.GetBaseSprite(phoneRecord.get('phoneKey'));Zw.util.log("creating the flip view menu. key:"+phoneRecord.get('phoneKey'));Zw.util.log("creating the flip view menu. height:"+h);Zw.util.log("creating the flip view menu. URL:"+url);Zw.util.log("creating the flip view menu. class:"+cls);if(!this.flipMenu){var div=new Zw.controls.Div({cls:"zw-flip-icon "+cls,style:['width:'+w+'px;height:'+h+'px;','background-image:url(\''+url+'\');'].join(''),addMouseClasses:true});var adapter=new Ext.menu.Adapter(div,{hideOnClick:false,hideDelay:0,stateful:false});this.flipMenu=new Ext.menu.Menu({allowOtherMenus:true,cls:"zw-cleanmenu zw-ppa-flip",shadow:false,onClickReaction:this.__hidePhone,items:[adapter]});this.flipMenu.on('hide',this.onFlipViewHide,this);this.flipMenu.on('click',function(sender,e){this.flipMenu.onClickReaction.call(this,sender,e);},this);}
if(this.flipMenu.el){if(!this.flipEl)
this.flipEl=this.flipMenu.el.child('.zw-flip-icon');var e=this.flipEl;Zw.util.log('setting background image '+url);Zw.util.log('setting class '+cls);e.setHeight(h);e.setWidth(w);e.setStyle('background-image','url(\''+url+'\')');e.dom.className="zw-flip-icon "+cls}
return this.flipMenu;},onFlipViewHide:function(menu){var fn=menu._hideFn;if(Ext.type(fn)=='function')
fn.call(menu._hideScope||this);},__flipPhone:function(sender,e){Zw.util.log('Delay flipping the phone');if(!this.flipEl)
this.flipEl=this.flipMenu.el.child('.zw-flip-icon');var phoneRecord=this.flipMenu.phoneRecord;var el=this.flipEl;el.toggleClass('zw-flip-icon-flipped');var flipped=el.is('.zw-flip-icon-flipped');var menu=this.getFlipViewMenu(phoneRecord,flipped);menu.showAt(this.__getMenuPosition(menu.showByEl,phoneRecord,flipped));if(!flipped)
menu.onClickReaction=this.__hidePhone;},__hidePhone:function(sender,e){Zw.util.log('hiding phone');sender.hide();},flipPhoneBy:function(args){var size=args.size||'normal';var flipped=(size=='normal');var firstShow=false;if(!this.flipMenu)
firstShow=true;if(Ext.isEmpty(args))return;var el=args.el;var card=args.card;var phoneRecord=args.phoneRecord;if(!el||!phoneRecord)return;el=Ext.get(el);Zw.util.log('Showing the phone menu by '+el);Zw.util.log('Showing this phone record '+phoneRecord);Zw.util.log('Showing for size '+size);var menu=this.getFlipViewMenu(phoneRecord,size=='normal');menu.phoneRecord=phoneRecord;menu.card=card;menu.showByEl=el;menu._hideScope=args.scope||this;menu._hideFn=args.callback||Ext.emptyFn;if(size=='normal')
menu.onClickReaction=this.__hidePhone;else
menu.onClickReaction=this.__flipPhone;menu.showAt(this.__getMenuPosition(el,phoneRecord,flipped));if(!flipped)
menu.el.child('.zw-flip-icon').removeClass('zw-flip-icon-flipped');else
menu.el.child('.zw-flip-icon').addClass('zw-flip-icon-flipped');if(firstShow)
this.flipMenu.el.unselectable();},__getMenuPosition:function(el,phoneRecord,flipped){var NORMAL_HEIGHT=42;var NORMAL_WIDTH=34;var FUDGE_X=3;var FUDGE_Y=-4;var xy=el.getXY();var pos=this.___getGenericMenuPosition({x:xy[0],y:xy[1]},el.getSize(),{width:NORMAL_WIDTH,height:NORMAL_HEIGHT});if(flipped){FUDGE_Y=-((phoneRecord.get('normal_flip_h')-NORMAL_HEIGHT))-12;}
return[pos[0]+FUDGE_X,pos[1]+FUDGE_Y];},___getGenericMenuPosition:function(staticElementPosition,staticElementSize,movableElementSize){var Xmenu;var Ymenu;var Xel=staticElementPosition.x;var Wmenu=movableElementSize.width;var Wel=staticElementSize.width;var a=(Wmenu-Wel)/2;Xmenu=Xel-a;var Yel=staticElementPosition.y;var Hmenu=movableElementSize.height;var Hel=staticElementSize.height;var b=(Hmenu-Hel)/2;Ymenu=Yel-b;return[Xmenu,Ymenu];},onDestroy:function(){delete this.identityManager;delete this.contactManager;delete this.messageManager;}});Zw.features.Factory.register(Zw.features.contacts.ContactCardFactoryFeature);

Zw.namespace('Zw.features.settings');Zw.features.settings.SettingsButton=Ext.extend(Zw.controls.LargeButton,{text:Zw.localize('generic.btn.settings'),name:Zw.localize('generic.text.settings'),minWidth:60,iconCls:"zw-toptoolbar-icon-settings"});

Zw.features.settings.SettingsButtonGroup=Ext.extend(Zw.controls.LargeButtonGroup,{cls:'zw-toptoolbar-btn-group zw-toptoolbar-btn-group-Settings',name:Zw.localize('generic.toolbar.name.settingsGroup'),updateStatusText:function(enabled){if(!this.statusText){this.statusText=this.find('code','statusText')[0];}
if(this.statusText){this.statusText.getEl().update(enabled?Zw.localize('generic.label.on'):Zw.localize('generic.label.off'));}},setForwardingState:function(args){var enabled=args.enabled;var timeout=args.timeout;if(!this.checkbox)
this.checkbox=this.find('code','checkbox')[0];if(!this.checkbox)
return;this.checkbox.setEnabled(enabled);this.checkbox.timeout=timeout;this.slider.setValue(Zw.util.convertMinutesToValue(timeout));this.updateStatusText(enabled);},initComponent:function(){if(Zw.portal=='TMobileLEC'||Zw.portal=='ATTLEC'){Ext.apply(this,{items:[new Zw.features.settings.SettingsButton()]});return Zw.features.settings.SettingsButtonGroup.superclass.initComponent.call(this);}
var that=this;Ext.apply(this,{items:[new Zw.features.settings.SettingsButton(),new Zw.controls.DetailSeparator(),{xtype:'div',style:'height:52px;width:112px;padding-left:3px;padding-top:2px;',items:[{code:'checkbox',xtype:"div",addMouseClasses:true,addMouseEvents:true,cls:'zw-smart-forwarding-group-wrap',html:'<div class="zw-smart-forwarding-group-lc">'+'<div class="zw-smart-forwarding-group-rc">'+'<div class="zw-smart-forwarding-group-cr">'+'<div class="zw-smart-forwarding-button"></div>'+'<div class="zw-smart-forwarding-text">'+Zw.localize('generic.text.instantly')+'</div>'+'<div class="zw-smart-forwarding-slider"></div>'+'</div></div></div>',checkClass:function(el,fn,cls){if(el.hasClass('zw-smart-forwarding-button')){el[fn](cls);}else if(el.hasClass('x-slider-thumb')){el[fn](cls);}},initEvents:function(){var that=this;var max=6;this.ownerCt.ownerCt.slider=new Ext.Slider({code:'slider',maxValue:max,renderTo:this.el.child('.zw-smart-forwarding-slider'),listeners:{'change':function(slider,value){if(!this.checkbox)
this.checkbox=that;var v=Math.floor((value/max)*6);var i=0;var result='';i=Zw.util.convertSliderToMinutes(v);result=Zw.util.formatMinutes(i,true);this.checkbox.timeout=i;that.el.child('.zw-smart-forwarding-text').update(result);},'changecomplete':function(slider,value){this.checkbox.toggleOn(true);}}});},listeners:{'mouseover':function(sender,e){e=Ext.get(e);this.checkClass(e,'addClass','mo');},'mouseout':function(sender,e){e=Ext.get(e);this.checkClass(e,'removeClass','mo')},'mousedown':function(sender,e){e=Ext.get(e);this.checkClass(e,'addClass','md');},'mouseup':function(sender,e){e=Ext.get(e);this.checkClass(e,'removeClass','md');if(this.change){this.change=false;}},'click':function(sender,e){if(!Ext.get(e).hasClass('x-slider-thumb')){this.toggleOn();}}},setEnabled:function(enabled){this.selected=enabled;if(this.selected)
this.el.addClass('x-selected');else
this.el.removeClass('x-selected');},toggleOn:function(forceOn){if(this.selected&&!forceOn)
this.selected=false;else
this.selected=true;if(this.selected)
this.el.addClass('x-selected');else
this.el.removeClass('x-selected');that.updateStatusText(this.selected);if(!this._delayedTask)
this._delayedTask=new Ext.util.DelayedTask(function(){that.fireEvent('changed',this.selected,this.timeout);},this);this._delayedTask.delay(1000);}},{xtype:'div',style:"height:14px;width:100px;text-align:center;white-space: nowrap;-moz-user-select:none;font:normal "+((Zw.portal=='Telcel')?'9px':(Ext.isIE6?'11px':'12px'))+" Segoe UI, calibri, arial, helvetica;cursor:default;line-height:16px;",items:[{xtype:'span',html:Zw.localize('generic.btn.smartForward')+' '},{xtype:'span',style:'font-weight: bold',code:'statusText',html:''}]}]}]});Zw.features.settings.SettingsButtonGroup.superclass.initComponent.call(this);}});Ext.reg('Zw.features.settings.SettingsButtonGroup',Zw.features.settings.SettingsButtonGroup);

Zw.namespace('Zw.features.settings');Zw.features.settings.SettingsFeature=Ext.extend(Zw.Feature,{group:'Zw.features.settings.SettingsButtonGroup',pkg:'settings.all',monitorGuestState:true,disableGroupIfGuest:true,onDownloadPackageComplete:Ext.emptyFn,onInit:function(){this.onDownloadPackageComplete=this._showSettingsWindow;this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/feature/settings'}));this.context.Settings.on('changed',this.onSettingsChanged,this,{buffer:true});this.setSettinglet({xtype:'Zw.features.settings.MobilePhoneIconSettinglet',tab:Zw.localize('generic.tab.privacy'),pkg:'phone.settings'});this.context.subscribe('/desktop/settings/edit',this._onSettingsClick,this);},onStart:function(){},_onSettingsClick:function(){this.downloadPackage();},_showSettingsWindow:function(){if(!this.m_window){this.m_window=this._createSettingsWindow();this.m_window.on('destroy',function(){delete this.m_window;},this,{single:true});}
this.m_window.show();},_createSettingsWindow:function(){return this.context.Desktop.registerWindow(new Zw.features.settings.SettingsWindow({plugins:this.context.Settings.getSettingletList()}));},onSettingsChanged:function(sender){this.initialSettings={enabled:sender.get('smartForwarding_enabled'),timeout:sender.get('smartForwarding_timeout')};if(this.group){this.setSettings(this.initialSettings);}
Zw.console("Received settings:",this.initialSettings);},setSettings:function(settings){if(this.group.setForwardingState){this.group.setForwardingState(settings);}},initGroup:function(){Zw.features.settings.SettingsFeature.superclass.initGroup.call(this);this.group.on('changed',function(enabled,minutes){this.context.Settings.set({smartForwarding:true,smartForwarding_enabled:enabled,smartForwarding_timeout:minutes});Zw.console("Group settings changed",{smartForwarding:true,smartForwarding_enabled:enabled,smartForwarding_timeout:minutes});},this);if(this.initialSettings){this.group.setForwardingState(this.initialSettings);}},onGroupClick:function(sender,e){if(e.name==Zw.localize('generic.btn.settings')){this.context.publish('/desktop/settings/edit');}},onDestroy:function(){Zw.console("Destroying SettingsFeature");this.context.Settings.un('changed',this.onSettingsChanged,this);}});Zw.features.Factory.register(Zw.features.settings.SettingsFeature);

Zw.features.settings.BasicSettingletsFeature=Ext.extend(Zw.Feature,{onInit:function(){this.setSettinglet({xtype:'Zw.features.settings.MobilePhoneIconSettinglet',tab:Zw.localize('generic.tab.privacy'),pkg:'phone.settings'});}});Zw.features.Factory.register(Zw.features.settings.BasicSettingletsFeature);

Ext.namespace('Zw.features.contacts');Zw.features.contacts.IdentityFeature=Ext.extend(Zw.Feature,{m_card:null,m_group:null,m_parent:null,m_identityContact:null,getIdentityContactCardPlugins:function(){var identityCardPlugins=[];if(Zw.capabilities.EDIT_SELF){identityCardPlugins.push(new Zw.controls.plugins.ContactCardEditNamePlugin());identityCardPlugins.push(new Zw.controls.plugins.ContactCardEditIdentityWindowPlugin());}
return identityCardPlugins;},_renderCard:function(delayRender){if(this.m_card)
this.m_card.destroy();var a=this.context.Account;var plugins=this.getIdentityContactCardPlugins();this.m_card=this.context.getContactCardFactory().createContactCard({style:'float:right;',contact:this.m_identityContact,preventGlobalAccess:true,closebox:false,preventEditContact:true,isIdentityCard:true,type:'identity',plugins:plugins});this.m_card.on('render',function(){if(!this.m_parent)
this.m_parent=this.m_group.el.parent();var p=this.m_card.el.parent();p.setStyle('width','100%');},this);if(!delayRender)
this.m_card.render(this.m_parent);return this.m_card;},_createEditContactWindowForIdentity:function(){var a=this.context.getIdentityManager();var result=this.context.Desktop.registerWindow(new Zw.features.contacts.EditContactWindow({isIdentity:true,contact:this.m_identityContact,messageManager:this.context.getMessageManager(),contactCardFactory:this.context.getContactCardFactory(),context:this.context}));result.show();return result;},onInit:function(){this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/desktop/identity/card'}));this.setupCard();},setupCard:function(){this.m_group=this.context.Desktop.getToolbarGroup('identity',this._renderCard(true));this.subscribe('/account/user/data',this.renderCard,this);this.subscribe('/desktop/identity/edit',this.editIdentity,this);this.context.on('initlevel4',this.initLevel4,this);},onDestroy:function(){var context=this.context;if(context){context.un('initlevel4',this.initLevel4,this);context.unsubscribe('/account/user/data',this.renderCard,this);}
delete this.m_identityContact},renderCard:function(){this._renderCard(false);},initLevel4:function(){this.m_identityContact=this.context.Account.identity;this.context.getIdentityManager().editIdentity=this.editIdentity.createDelegate(this);},editIdentity:function(args){Zw.Packages.get('contact.edit',this._editIdentity,this,[args]);},_editIdentity:function(args){var result=this._createEditContactWindowForIdentity();if(args&&args.handler){args.handler.call(args.scope||this,result);}}});Zw.features.Factory.register(Zw.features.contacts.IdentityFeature);

Zw.namespace('Zw.features.help');Zw.features.help.WelcomeWizardFeature=Ext.extend(Zw.Feature,{monitorGuestState:true,pkg:['wizard.all','wizard.help'],onInit:function(client){this.context.subscribe('/desktop/tour/show',this.downloadPackage,this);this.context.subscribe('/desktop/interlink/tour',this.downloadPackage,this);},_onBeforeShow:function(){if(this.helpPanel){this.helpPanel.setPosition(-9999,-9999);}},_onBeforeDestroy:function(){if(!this.wnd)
this.context.publish('/desktop/message/new');this.touring=false;Zw.console("Destroyed the WizardPanel");},onAuthenticatedAsUser:function(){var isWizardSeen=this.context.Settings.get('wizard_seen');if(!isWizardSeen){this.downloadPackage();this.context.Settings.set({'wizard_seen':true});}},onDownloadPackageComplete:function(){if(this.touring)return;this.touring=true;this.showWelcomeWizard();},setTitle:function(text){if(this.helpPanel)
this.helpPanel.find('code','title')[0].el.update(text);},showWelcomeWizard:function(){this.helpPanel=new Zw.controls.Div({cls:'welcomeWizardWindow x-hidden',renderTo:Ext.getBody(),context:this.context,plugins:[new Zw.features.help.WelcomeWizardControllerPlugin()],defaults:{xtype:'div'},items:[{xtype:'div',cls:'header',items:[{xtype:'div',cls:'icon'},{xtype:'div',cls:'title',code:'title',html:Zw.localize('generic.btn.send')},{xtype:'div',cls:'close',baseMouseCls:'close',addMouseClasses:true,scope:this,handler:this.closeHelpPanel}]},{layout:'card',cls:'canvas',code:'canvas'},{cls:'buttons',defaults:{xtype:'Zw.controls.ActionButton'},items:[{cls:'zw-wizard-nav back zw-action-button',code:'back',text:'<'},{cls:'zw-wizard-nav next zw-action-button',code:'next',text:Zw.localize('generic.btn.next')+' >'},{cls:'zw-wizard-nav zw-wizard-nav-close zw-action-button',code:'finish',text:Zw.localize('generic.btn.finish')}]}],setWindow:this.setWindow.createDelegate(this),getWindow:this.getWindow.createDelegate(this),setTitle:this.setTitle.createDelegate(this),setBox:this.setBox.createDelegate(this)});this.helpPanel.show();this.helpPanel.on("beforedestroy",this._onBeforeDestroy,this,{single:true});},onWindowDestroy:function(w){delete this.wnd;},getWindow:function(w){return this.wnd;},setWindow:function(w){if(this.wnd!=w){w.on('destroy',this.onWindowDestroy,this,{single:true});this.wnd=w;}},setBox:function(el,width,height,position,offset){this.helpPanel.setWidth(width);this.helpPanel.setHeight(height);this.helpPanel.getEl().alignTo(el,position,offset);this.helpPanel.doLayout();},closeHelpPanel:function(){this.helpPanel.close();delete this.helpPanel;},onDestroy:function(){if(this.helpPanel){this.closeHelpPanel();}}});Zw.features.Factory.register('Zw.features.help.WelcomeWizardFeature');

Ext.namespace('Zw');Zw.TooltipMgr=Ext.extend(Ext.util.Observable,{tooltips:{},baseStyle:'z-index: 99999; ',register:function(config){config.target=Ext.get(config.target);if(config.target){config.style=this.baseStyle+(config.style||'');return((this.tooltips[config.target.id]=new Ext.ToolTip(config)));}},unregister:function(target){target=Ext.get(target);if(target){var tooltip=this.tooltips[target.id];if(tooltip){Ext.destroy(tooltip);}}}});Zw.TooltipMgr=new Zw.TooltipMgr();

Ext.namespace('Zw','Zw.app');Zw.app.Adverts=Ext.extend(Zw.app.ContextModule,{strategy:'randomStrategy',pickAdIndex:Ext.emptyFn,adverts:[{id:2,text:Zw.localize('adverts.zw.text1'),cls:'generic',style:'background-position: 0 -99px'},{id:5,text:Zw.localize('adverts.zw.text2'),cls:'generic',style:'background-position: 0 -396px'},{id:6,text:Zw.localize('adverts.zw.text3'),cls:'generic',style:'background-position: 0 -495px'}],onInit:function(){this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/desktop/message/advert'}));this.pickAdIndex=this[this.strategy];},randomStrategy:function(){return Math.floor(Math.random()*this.adverts.length);},staticStrategy:function(){return 3;},getAdvert:function(){if(this.adverts){var index=this.pickAdIndex();return this.adverts[index];}else{return null;}}});

Zw.namespace('Zw.features.app');Zw.features.app.PreloaderFeature=Ext.extend(Zw.Feature,{cache:[],triggers:null,DESTROY_DELAY:5000,log:Ext.emptyFn,onInit:function(){this.triggers=new Ext.util.MixedCollection();this.context.subscribe('/app/cache/add',this.onCacheAdd,this);this.context.subscribe('/app/cache/trigger',this.onCacheTrigger,this);this.log('PreloaderFeature initialized');},onStart:function(){},test:function(){var cls=['zw-send-progress-bar-cached','zw-test2'];var pkg=['wizard.all','menu.all'];var trigger='post-send';this.context.publish('/app/cache/add',{delay:5000,trigger:trigger,cls:cls,pkg:pkg});this.context.publish('/app/cache/trigger',trigger);},onCacheAdd:function(args){if(!args)return;var delay=args.delay||-1;var cls=args.cls;var trigger=args.trigger;var scope=args.scope||this;var pkg=args.pkg;var triggerChannel=args.triggerChannel;var context=this.context;if(!context)return;var doPreload=null;var type=Ext.type(trigger);if(type=='function'){doPreload=this.onTrigger.createDelegate(this,[args]);args.trigger=trigger.createSequence(doPreload);}else if(type='string'){if(!this.triggers.containsKey(trigger))
this.triggers.add(trigger,args);doPreload=true;}
if(triggerChannel){if(!Ext.type(doPreload)!='function')
doPreload=this.onTrigger.createDelegate(this,[args]);context.subscribe(triggerChannel,doPreload)}
if(delay>=0){if(!Ext.type(doPreload)!='function')
doPreload=this.onTrigger.createDelegate(this,[args]);doPreload.defer(delay,this);}
if(!doPreload){this.onTrigger(args);}},onTrigger:function(args){if(args.cls){Ext.each(args.cls,function(item){if(!this.exists(item)){this.preloadCls(item);}},this);}
var pkg=args.pkg;var context=this.context;if(pkg&&context){context.publish('/app/packages/get',pkg);}},exists:function(css){if(!css)return true;return this.cache.indexOf(css)!=-1;},preloadCls:function(cls){var items=[];Ext.each(cls,function(CLS){items.push({tag:'div',cls:CLS+' preloader',html:'preload'});this.cache.push(CLS);},this);var el=Ext.get(Ext.DomHelper.append(Ext.getBody(),items));el.remove.defer(this.DESTROY_DELAY,el);},onCacheTrigger:function(trigger){this.log("Someone has fired a cache trigger",trigger);if(!this.triggers)return;if(!trigger)return;var args=this.triggers.key(trigger);if(!args)return;this.log('We found the args',args,'for trigger',trigger,'. So we cached it.');this.triggers.removeKey(trigger);this.onTrigger(args);}});Zw.features.Factory.register('Zw.features.app.PreloaderFeature');

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ToBoxGroupStrategyPlugin=Ext.extend(Zw.Plugin,{earlyInit:true,onInit:function(){if(!this.earlyInitialized){if(!this.adhoc){this.defaultAddToStore=this.client.addToStore;this.client.addToStore=this.addToStore;}
Ext.apply(this.client,{toBoxUpperItems:{creationManager:this},creationManager:this,blacklistStrategy:this.blacklistStrategy,addToStoreFix:false,contactCardSize:'small',contactCardFactoryConfig:{preventMembershipCard:true,arrow:false,preventDropdown:true,preventExtendedView:true,preventEditContact:true}});this.client.toStore.on('remove',this.onToStoreRemove,this);this.client.on('beforeToStoreSet',this.beforeToStoreSet,this);this.client.on('toStoreSet',this.toStoreSet,this);}},blacklistStrategy:function(blacklist,record){var isGroup=(record.get('targetGroupDevice')>-1);var isAlreadyInBlacklist=(blacklist.find('mobileNumber',record.get('mobileNumber'))!=-1);var result=isGroup||isAlreadyInBlacklist;return!result;},onToStoreRemove:function(store,record){this.context.publish('/account/device/member/remove',{device:this.getDevice(),member:record});},getGroupAddress:function(){return this.getDevice().getAddress();},getDevice:function(){var deviceId=this.getDeviceId();this.device=this.context.Account.getDeviceById(deviceId);return this.device;},getDeviceId:function(){if(this.device)
return this.device.deviceId;else
return this.deviceId;},addToStore:function(record,method){var contact=null;if(this.toStore.indexOf(record)!=-1){return;}
contact=new Zw.data.Contact({mobileNumber:Zw.data.get(record,'mobileNumber'),firstName:Zw.data.get(record,'firstName'),lastName:Zw.data.get(record,'lastName'),phoneKey:Zw.data.get(record,'phoneKey'),deviceId:this.creationManager.getDeviceId()});if(method=='created'){}else{this.creationManager.createContact({contact:contact});}},createContact:function(fArgs){var store=this.client.referenceContactList;if(!fArgs)return;var deviceAddress=this.getDevice().getAddress();var cArgs=Ext.applyIf(fArgs.contact,{});cArgs=Ext.apply(cArgs,{});var contactRecord;var index=store.find('mobileNumber',cArgs.mobileNumber);if(index!=-1){contactRecord=store.getAt(index);contactRecord=contactRecord.copy();}else{contactRecord=cArgs;if(!contactRecord.get){contactRecord=new Zw.data.Contact(contactRecord);}}
this.context.publish('/account/device/member/add',{device:deviceAddress,member:contactRecord});return contactRecord;},beforeToStoreSet:function(membersStore,groupDevice,isAdhocGroupContact){this.client.toStore.un('remove',this.onToStoreRemove,this);},toStoreSet:function(membersStore,groupDevice,isAdhocGroupContact){var client=this.client;if(client){this.adhoc=isAdhocGroupContact;this.device=groupDevice;client.deviceId=this.getDeviceId();client.addToStore=this.adhoc?this.defaultAddToStore:this.addToStore;if(client.toStore&&client.toStore.on){client.toStore.on('remove',this.onToStoreRemove,this);}}},onDestroy:function(){this.client.toStore.un('remove',this.onToStoreRemove,this);delete this.client.creationManager;delete this.context;delete this.device;}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.SendProgressBarBlinkingPlugin=Ext.extend(Zw.Plugin,{stopBlinkingOnError:false,error:false,onInit:function(){this.client._setValue=this.client.setValue;this.client.setValue=this.setValue.createDelegate(this);this.client.on('error',this.onError,this);this.client._setComplete=this.client.setComplete;this.client.setComplete=this.onComplete.createDelegate(this);},onComplete:function(){this.complete=true;this.stopBlink();this.setValue(5);},onError:function(sender,args){var stage=args.value;this.error=true;if(this.stopBlinkingOnError){this.stopBlink();this.client._setValue(stage);}},setValue:function(value){if(this.error){this.animateTo(value);}else{this.startBlink();this.animateTo(value);}},stopAnimate:function(){if(this.atask){this.atask.running=false;Ext.TaskMgr.stop(this.atask);}
this.fireEvent('stopanimate',this,this.value);if(this.complete&&this.client){this.client._setComplete(true);}},startAnimate:function(){if(!this.atask){this.atask={interval:1000,run:this.atask_run,scope:this}}
if(!this.atask.running){this.atask.running=true;Ext.TaskMgr.start(this.atask);}},atask_run:function(){var scope=this.client;if(scope){var c=scope.value;var g=scope.goalValue;this.removeBlink(c);if(c==g){this.stopAnimate();}else if(c>g){scope._setValue(c-1);}else if(c<g){scope._setValue(c+1);}}else{this.stopAnimate();}},animateTo:function(value){this.client.goalValue=value;this.startAnimate();},btask_run:function(){var scope=this.client;if(scope&&!this.complete){var e=scope.getEl();var stage=scope.value;var ch=e.child(".stage"+stage);if(ch)
ch.toggleClass('stage'+stage+'-blink');}else{this.stopBlink();}},removeBlink:function(stage){var e=this.client.getEl();var ch=e.child('.stage'+stage);if(ch){ch.removeClass('stage'+stage+'-blink');}},startBlink:function(){if(this.error)return;var scope=this.client;if(!this.btask){this.btask={scope:this,run:this.btask_run,interval:1000}
Ext.TaskMgr.start(this.btask);this.btask.running=true;}
if(!this.btask.running)
Ext.TaskMgr.start(this.btask);},stopBlink:function(){if(!this.btask)
return;if(!this.btask.running)
return;Ext.TaskMgr.stop(this.btask);this.btask.running=false;var client=this.client;if(client)
this.removeBlink(client.value);},onDestroy:function(){this.client.setValue=this.client._setValue;this.client.setComplete=this.client._setComplete;}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.SendProgressBarMultipleDescriptionPlugin=Ext.extend(Zw.Plugin,{errorsCounter:0,tpl:'<span class="success-status">'+Zw.localize('generic.status.textSent')+'</span>',errorsTpl:' <span class="error-status"><img class="errorIcon" src="images/s.gif" alt="" />'+Zw.localize('generic.status.textError')+'.</span>',onInit:function(){this.client.setSuccessCount=this.setSuccessCount.createDelegate(this);this.client.on('render',this.onRender,this);this.client.on('show',this.onShow,this,{single:true});},onRender:function(){this.client.status.on('mouseover',this.onStatusMouseOver,this);this.client.status.on('mouseout',this.onStatusMouseOut,this);this.client.status.on('click',this.onStatusClick,this);},onShow:function(){var status=this.client.status;if(status&&status.el){status.el.toggleClass('error-status');status.el.toggleClass('error-status');}},onStatusMouseOver:function(e,el){var errorStatusEl=Ext.fly(el).findParent('.error-status',undefined,true);if(errorStatusEl){errorStatusEl.addClass('error-status-mo');}},onStatusMouseOut:function(e,el){var errorStatusEl=Ext.fly(el).findParent('.error-status',undefined,true);if(errorStatusEl){errorStatusEl.removeClass('error-status-mo');}},onStatusClick:function(e,el){if(this.client.errorClickHandler){if(Ext.fly(el).hasClass('error-status')){this.client.errorClickHandler.call(this.client.scope||this);}}},setSuccessCount:function(args){var text=String.format(this.tpl,args.count,args.total);if(args.error){this.errorsCounter+=1;}
if(this.errorsCounter){text+=String.format(this.errorsTpl,this.errorsCounter,(this.errorsCounter===1?'':'s'));}
this.client.setStatus(text);}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.SendProgressBarSimpleDescriptionPlugin=Ext.extend(Zw.Plugin,{DEFAULT_ERROR_TEXT:Zw.localize('generic.alert.unknownTransmissionError'),onInit:function(){var client=this.client;if(client){client.on('error',this.setError,this);client.on('valuechanged',this.onValueChanged,this);client.on('contactchanged',this.onContactChanged,this);var contact=client.contact;if(contact){this.onContactChanged(this,contact);}}},onValueChanged:function(){if(!this.client.error){var stage=this.client.value;var text=this['stage'+stage];this.client.setStatus(text);}},onContactChanged:function(sender,contact){var hasMany=Ext.isArray(contact)?(contact.length>1):false;contact=Ext.isArray(contact)?contact[0]:contact;var carrier;var mobileNumber;if(!hasMany){carrier=Zw.data.get(contact,'carrier');mobileNumber=Zw.util.formatMobileNum(Zw.data.get(contact,'mobileNumber'));this.carrierRecord=Zw.data.Carrier.CarrierList.getById(carrier);if(this.carrierRecord){carrier=this.carrierRecord.get('name');}else{carrier=carrier||Zw.localize('generic.text.carrier');}}else{alert(Zw.localize('generic.alert.single.lowercase'));}
for(var i=1;i<=5;i++){var tips=this.getTips({prefix:i,hasMany:hasMany,carrier:carrier,mobileNumber:contact});Ext.apply(this,tips);}
Ext.apply(this,this.getTips({prefix:'Receipt',hasMany:hasMany,carrier:carrier,mobileNumber:mobileNumber}));},stage1:Zw.localize('sendingStatus.stage1.text'),stage2:Zw.localize('sendingStatus.stage2.text'),stage3:Zw.localize('sendingStatus.stage3.text'),stage4:Zw.localize('sendingStatus.stage4.text'),stage5:Zw.localize('sendingStatus.stage5.text'),stageReceipt:Zw.localize('sendingStatus.stageReceipt.text'),stage1TooltipHeader:Zw.localize('sendingStatus.stage1.tooltip.header'),stage1TooltipBody:Zw.localize('sendingStatus.stage1.tooltip.text'),stage2TooltipHeader:Zw.localize('sendingStatus.stage2.tooltip.header'),stage2TooltipBody:Zw.localize('sendingStatus.stage2.tooltip.text'),stage3TooltipHeader:Zw.localize('sendingStatus.stage3.tooltip.header'),stage3TooltipBody:Zw.localize('sendingStatus.stage3.tooltip.text'),stage4TooltipHeader:Zw.localize('sendingStatus.stage4.tooltip.header'),stage4TooltipBody:Zw.localize('sendingStatus.stage4.tooltip.text'),stage5TooltipHeader:Zw.localize('sendingStatus.stage5.tooltip.header'),stage5TooltipBody:Zw.localize('sendingStatus.stage5.tooltip.text'),stageReceiptTooltipHeader:Zw.localize('sendingStatus.stageReceipt.tooltip.header'),stageReceiptTooltipBody:Zw.localize('sendingStatus.stageReceipt.tooltip.text'),stage1MultiTooltipHeader:Zw.localize('sendingStatus.stage1.multi.tooltip.header'),stage1MultiTooltipBody:Zw.localize('sendingStatus.stage1.multi.tooltip.text'),stage2MultiTooltipHeader:Zw.localize('sendingStatus.stage2.multi.tooltip.header'),stage2MultiTooltipBody:Zw.localize('sendingStatus.stage2.multi.tooltip.text'),stage3MultiTooltipHeader:Zw.localize('sendingStatus.stage3.multi.tooltip.header'),stage3MultiTooltipBody:Zw.localize('sendingStatus.stage3.multi.tooltip.text'),stage4MultiTooltipHeader:Zw.localize('sendingStatus.stage4.multi.tooltip.header'),stage4MultiTooltipBody:Zw.localize('sendingStatus.stage4.multi.tooltip.text'),stage5MultiTooltipHeader:Zw.localize('sendingStatus.stage5.multi.tooltip.header'),stage5MultiTooltipBody:Zw.localize('sendingStatus.stage5.multi.tooltip.text'),stageReceiptMultiTooltipHeader:Zw.localize('sendingStatus.stageReceipt.multi.tooltip.header'),stageReceiptMultiTooltipBody:Zw.localize('sendingStatus.stageReceipt.multi.tooltip.text'),stage1Template:Zw.localize('sendingStatus.stage1.template'),stage2Template:Zw.localize('sendingStatus.stage2.template'),stage3Template:Zw.localize('sendingStatus.stage3.template'),stage4Template:Zw.localize('sendingStatus.stage4.template'),stage5Template:Zw.localize('sendingStatus.stage5.template'),stageReceiptTemplate:Zw.localize('sendingStatus.stageReceipt.template'),stage1MultiTemplate:Zw.localize('sendingStatus.stage1.multi.template'),stage2MultiTemplate:Zw.localize('sendingStatus.stage2.multi.template'),stage3MultiTemplate:Zw.localize('sendingStatus.stage3.multi.template'),stage4MultiTemplate:Zw.localize('sendingStatus.stage4.multi.template'),stage5MultiTemplate:Zw.localize('sendingStatus.stage5.multi.template'),stageReceiptMultiTemplate:Zw.localize('sendingStatus.stageReceipt.multi.template'),getTips:function(args){var prefix=args.prefix;var mobileNumber=args.mobileNumber;var carrier=args.carrier;var hasMany=args.hasMany;var result={};var stage=String.format("stage{0}",prefix);var stageTemplate=hasMany?String.format("stage{0}MultiTemplate",prefix):String.format("stage{0}Template",prefix);stageTemplate=this[stageTemplate];var tooltipHeaderTemplate=hasMany?String.format("stage{0}MultiTooltipHeader",prefix):String.format("stage{0}TooltipHeader",prefix);var tooltipBodyTemplate=hasMany?String.format("stage{0}MultiTooltipBody",prefix):String.format("stage{0}TooltipBody",prefix);var tooltipHeader=String.format("stage{0}TooltipHeader",prefix);var tooltipBody=String.format("stage{0}TooltipBody",prefix);result[stage]=stageTemplate.replace('{carrier}',carrier);result[stage]=result[stage].replace('{mobile}',mobileNumber);result[tooltipHeader]=this[tooltipHeaderTemplate].replace('{carrier}',carrier);result[tooltipHeader]=result[tooltipHeader].replace('{mobile}',mobileNumber);this.log(String.format("Setting this[{0}] = {1}",tooltipHeader,result[tooltipHeader]));result[tooltipBody]=this[tooltipBodyTemplate].replace("{carrier}",carrier);result[tooltipBody]=result[tooltipBody].replace('{mobile}',mobileNumber);this.log(String.format("Setting this[{0}] = {1}",tooltipBody,result[tooltipBody]));return result;},convertProgressToText:function(progress,contact){var carrier='';var mobileNumber='';var moreThanOne=Ext.isArray(contact);if(!moreThanOne){mobileNumber=contact.get('mobileNumber');carrier=contact.get('carrier');this.carrierRecord=Zw.data.Carrier.CarrierList.getById(carrier);carrier=this.carrierRecord.get('name');}
return this[String.format('stage{0}',progress)];},setError:function(sender,args){this.error=true;var msg=args.desc||this.DEFAULT_ERROR_TEXT;var stage=args.value||this.client.value;this.client.setValue(stage);this.client.setStatus(String.format(Zw.localize('generic.alert.error.titleUppercase')+': {0}',msg));},clearError:function(){var e=this.client.getEl();e.removeClass('error');for(var stage=1;stage<6;stage+=1){var ch=e.child(".stage.stage"+stage);if(ch)
ch.removeClass("stage"+stage+"-error");}
this.error=false;}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardMembershipCardPlugin=Ext.extend(Zw.Plugin,{onInit:function(){this.client.type='membership';if(this.context){this.context.subscribe('/account/contact/save',this.onDeviceChange,this);}
this.client.on('beforeRender',this.onBeforeRender,this,{single:true});this.client.on('render',this.setupContactCard,this,{single:true});},onDeviceChange:function(args){if(this.client){if(!this.client.getEl()){return;}}
var contact=args.contact;if(this.isOurContact(contact)){this.updateContactCard(Zw.util.getFullName(contact));}},isOurContact:function(contact){var targetGroupDevice=Zw.data.get(contact,'targetGroupDevice');var deviceId=this.getDevice().deviceId;if(deviceId==targetGroupDevice){return true;}},updateContactCard:function(fullName){this.client.getEl().child('.deviceName').update(fullName);},getDevice:function(){return this.context.Account.getDevice(this.device);},onBeforeRender:function(){this.setupExtension();},setupExtension:function(){this.args=this.getMembershipTemplateArgs();this.client.additionalTemplateBefore=this.getMembershipTemplate().apply(this);},setupContactCard:function(){this.client.el.addClass('zw-membershipContactCard');if(this.bubblePanel){this.bubblePanel.addClass('zw-bubble-membership');}},getMembershipTemplateArgs:function(){var device=this.getDevice();var name=Zw.localize('generic.text.unnamedGroup');if(device){name=device.getName();}
return{deviceName:name};},getMembershipTemplate:function(){return Zw.util.getTemplate(Zw.controls.plugins.ContactCardMembershipCardPlugin.tpl,true);},onDestroy:function(){this.context.unsubscribe('/account/contact/save',this.onDeviceChange,this);this.client.un('beforeRender',this.onBeforeRender,this);this.client.un('render',this.setupContactCard,this);delete this.context;delete this.args;}});Zw.controls.plugins.ContactCardMembershipCardPlugin.tpl='<div class="zw-contactcard-membershipFlyout">'+'<span class="deviceName">{values.args.deviceName}</span>'+'</div>';

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardPopupPlugin=Ext.extend(Zw.Plugin,{onInit:function(){var client=this.client;if(client){client.on('nameclick',this.onNameClick,this);}},onNameClick:function(){if(!this.client)return;if(this.client.determineSize()!='normal'){var contact=this.client.setContact(this.client.__unsafeResolveContactGlobally());Zw.console("Set the contact",contact);this.client.factory.showContactCardPopupMenu(this.client);}},onDestroy:function(){this.client.un('nameclick',this.onNameClick,this);}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardZoomGroupPlugin=Ext.extend(Zw.Plugin,{onInit:function(){var client=this.client;if(client){this.context=client.factory.context;client.on('phoneclick',this._showZoomGroup,this);client.showZoomGroup=this._showZoomGroup.createDelegate(this);}},_showZoomGroup:function(){var client=this.client;if(this.context&&client){this.publish('/desktop/contact/zoomgroup',{contactCard:client});}},publish:function(uri,args){args=args||{};this.context.publish('/app/service/run',{pkg:'contact.services',service:'Zw.services.ZoomGroupService',uri:uri,args:Ext.apply(args,{context:this.context})});}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardDataViewSearchablePlugin=Ext.extend(Zw.Plugin,{searchFieldCode:'searchField',cancelSearchButtonCode:'cancelSearchButton',dataViewCode:'toBoxUpperItems',onInit:function(){if(!this.searchField)
this.searchField=this.client.field(this.searchFieldCode);if(this.searchField){this.searchField.on('keyup',this.onSearchFieldKeyup,this);}
if(!this.cancelSearchButton)
this.cancelSearchButton=this.client.field(this.cancelSearchButtonCode);if(this.cancelSearchButton){this.cancelSearchButton.on('click',this.onCancelSearchButtonClick,this);}},onSearchFieldKeyupTask:undefined,onSearchFieldKeyup:function(){if(!this.onSearchFieldKeyupTask){this.onSearchFieldKeyupTask=new Ext.util.DelayedTask(this.filterContacts,this);}
this.onSearchFieldKeyupTask.delay(250);},onCancelSearchButtonClick:function(){this.searchField.setRawValue('');this.filterContacts();},getDataView:function(){return this.client.field(this.dataViewCode);},filterContacts:function(){var dataView=this.getDataView();dataView.filter=(this.searchField.getValue()||'').toLowerCase();if(dataView.filter==''){dataView.store.clearFilter();if(this.cancelSearchButton)
this.cancelSearchButton.getEl().addClass('x-hidden');this.filtered=false;}else{dataView.store.filterBy(Zw.controls.ContactCard.generateHighlighterFilterFn(dataView.highlighterStrategyLookup,null,dataView.filter));if(this.cancelSearchButton)
this.cancelSearchButton.getEl().removeClass('x-hidden');this.filtered=true;}}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardDelayLoadPropertiesPlugin=Ext.extend(Zw.Plugin,{contactId:null,deviceId:null,deviceAddress:null,context:null,onInit:function(){var device=null;if(this.deviceId){device=this.deviceId;}else{device=this.deviceAddress;}
device=this.context.Account.getDevice(device);if(device){var contact=device.contacts.getById(this.contactId);if(contact){this.setContact(contact);}else{this.setStore(device.contacts);this.context.publish('/account/device/contacts/load',{device:device});}}
Zw.console("ContactCardDelayLoadPropertiesPlugin",device,contact);},setStore:function(store){if(this.store){this.store.un('load',this.update,this,{single:true});}
this.store=store;if(this.store){this.store.on('load',this.update,this);}},update:function(){var contact=this.context.getContactManager().getContactByIdAndDeviceId(this.contactId,this.deviceId);if(contact){this.setContact(contact);}},setContact:function(contact){this.client.setContact(contact);this.destroy();},onDestroy:function(){this.setStore(null);}});

Zw.namespace('Zw.controls');Zw.controls.ContactCardComboBox=Ext.extend(Ext.form.ComboBox,{contactCardHighlighterStrategyLookup:new Ext.util.MixedCollection(true),enableKeyEvents:true,log:Zw.util.log,lazyInit:true,contactCardFactoryConfig:null,onKeyPressMonitorEmptyTextDeferId:null,onLoad:function(store,records,options){if(arguments.length==0){Zw.controls.ContactCardComboBox.superclass.onLoad.call(this);}},minChars:0,initComponent:function(){Zw.controls.ContactCardComboBox.superclass.initComponent.call(this);this.selectedClass="x-item-selected";this.itemSelector="div.zw-contact-dropdown-item";this.resizable=false;this.minHeight=60;this.minListWidth=220;this.listAlign="tl-bl";},collapseIf:function(e){if(!e.within(this.wrap)&&!e.within(this.list)&&!e.getTarget('.x-menu')){this.collapse();}},emptyClass:'',applyEmptyText:function(){},onRender:function(ct,pos){Zw.controls.ContactCardComboBox.superclass.onRender.call(this,ct,pos);this.emptyTextEl=this.trigger.insertSibling({tag:'div',cls:'zw-combobox-emptytext x-form-empty-field',html:this.emptyText},'after');this.etShown=Ext.isEmpty(this.getValue());if(Ext.isIE){this.emptyTextEl.on('click',function(){this.el.focus();},this);}
this.el.on('keydown',function(e){this.onKeyPressMonitorEmptyTextDeferId=this.onKeyPressMonitorEmptyText.defer(10,this,[e]);},this);this.el.on('blur',function(){this.onKeyPressMonitorEmptyTextDeferId=this.onKeyPressMonitorEmptyText.defer(10,this);},this);},clearValue:function(){Zw.controls.ContactCardComboBox.superclass.clearValue.call(this);this.setEmptyTextState(true);},setEmptyTextState:function(hidden){if(hidden){this.emptyTextEl.removeClass('x-hidden');}else{this.emptyTextEl.addClass('x-hidden');}
this.etShown=!this.emptyTextEl.is('.x-hidden');},onKeyPressMonitorEmptyText:function(evt){this.onKeyPressMonitorEmptyTextDeferId=null;var v=this.getValue();var e=Ext.isEmpty(v);if(e!=this.etShown){this.setEmptyTextState(e);}
if(evt&&evt.getKey){if(evt.getKey()===evt.DELETE){this.setEmptyTextState(false);}}},doQuery:function(q,forceAll){this.hasFocus=true;this.contactCardHighlighterStrategyLookup.clear();this.view.tpl.filter='';if(q===undefined||q===null){q='';}
var qe={query:q,forceAll:forceAll,combo:this,cancel:false};if(this.fireEvent('beforequery',qe)===false||qe.cancel){return false;}
q=qe.query;forceAll=qe.forceAll;if(forceAll===true||(q.length>=this.minChars)){if(this.lastQuery!==q||true){this.lastQuery=q;if(this.mode=='local'){this.selectedIndex=-1;if(forceAll){var isFunction=(Ext.type(this.blacklistStrategy)=='function');this.store.filterBy(function(record,id){if(isFunction){return this.blacklistStrategy(this.blacklist,record);}else if(this.blacklistStrategy=='mobileNumber'){return this.blacklist.find('mobileNumber',record.get('mobileNumber'))==-1;}else{return!this.blacklist.getById(id);}},this);}else{var filter=q.toLowerCase();this.view.filter=filter;var highlighterFilterFn=Zw.controls.ContactCard.generateHighlighterFilterFn(this.contactCardHighlighterStrategyLookup,{store:this.blacklist,strategy:this.blacklistStrategy},filter);this.store.filterBy(highlighterFilterFn);}
this.onLoad();var reg=new RegExp(/^\s*\d+\s*$/);var numbersOnly=reg.test(q);if(Zw.capabilities.ALLOW_SHORT_CODE&&numbersOnly){this.select(-1);}}else{this.store.baseParams[this.queryParam]=q;this.store.load({params:this.getParams(q)});this.expand();}}else{this.selectedIndex=-1;this.onLoad();}}},onViewClick:function(doFocus,d,g,e){if(e){if(e.getTarget('.x-menu')){return;}}
var index=this.view.getSelectedIndexes()[0];var r=this.store.getAt(index);if(r){this.onSelect(r,index);}
if(doFocus!==false){this.el.focus();}},initList:function(){if(!this.list){var cls='x-combo-list';cls='x-c-l';this.list=new Ext.Layer({cls:[cls,this.listClass].join(' '),constrain:false});var lw=this.listWidth||Math.max(this.wrap.getWidth(),this.minListWidth);this.list.setWidth(lw);this.list.swallowEvent('mousewheel');this.assetHeight=0;if(this.title){this.header=this.list.createChild({cls:cls+'-hd',html:this.title});this.assetHeight+=this.header.getHeight();}
this.innerList=this.list.createChild({cls:cls+'-inner'});this.innerList.on('mouseover',this.onViewOver,this);this.innerList.on('mousemove',this.onViewMove,this);this.innerList.setWidth(lw-this.list.getFrameWidth('lr'));if(this.pageSize){this.footer=this.list.createChild({cls:cls+'-ft'});this.pageTb=new Ext.PagingToolbar({store:this.store,pageSize:this.pageSize,renderTo:this.footer});this.assetHeight+=this.footer.getHeight();}
if(!this.tpl){this.tpl='<tpl for="."><div class="'+cls+'-item">{'+this.displayField+'}</div></tpl>';}
this.contactCardFactoryConfig=Ext.applyIf(this.contactCardFactoryConfig,{preventEditName:true,preventDropdown:false,preventPhoneIcon:true});this.view=new Zw.controls.ContactCardDataView({name:"ContactCardComboBoxDataView",highlighterStrategyLookup:this.contactCardHighlighterStrategyLookup,overrideTpl:this.contactCardTpl,width:this.innerList.width,singleSelect:true,cls:'zw-contact-dropdown-dataview zw-contactcard-size',overClass:'zw-view-over',contactCardFactoryConfig:this.contactCardFactoryConfig,contactCardFactory:this.contactCardFactory,itemSelector:'div.contacts-wrap',emptyText:'No contact cards to display',closebox:false,arrow:true});this.view.on('selectionchange',function(sender,items){if(items.length==1){var parent=sender.el.up('.zw-contact-dropdown-body');Ext.fly(items[0]).scrollIntoView(parent);}},this);this.curvyPanel=new Ext.Panel({applyTo:this.innerList,baseCls:"zw-contact-dropdown",shadow:false,frame:true,items:this.view});this.view.on('click',this.onViewClick,this);this.bindStore(this.store,true);if(this.resizable){this.resizer=new Ext.Resizable(this.list,{pinned:true,handles:'se'});this.resizer.on('resize',function(r,w,h){this.maxHeight=h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;this.listWidth=w;this.innerList.setWidth(w-this.list.getFrameWidth('lr'));this.restrictHeight();},this);this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom',this.handleHeight+'px');}}},expand:function(){Zw.controls.ContactCardComboBox.superclass.expand.call(this);this.innerList.setOverflow('hidden');this.list.alignTo(this.wrap,this.listAlign);},restrictHeight:function(){this.curvyPanel.setHeight(this.maxHeight);var innerEl=this.curvyPanel.getEl().child("div.zw-contact-dropdown-body");if(innerEl){innerEl.dom.style.height='';var inner=innerEl.dom;var pad=this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight;var h=Math.max(inner.clientHeight,inner.offsetHeight,inner.scrollHeight);var ha=this.getPosition()[1]-Ext.getBody().getScroll().top;var hb=Ext.lib.Dom.getViewHeight()-ha-this.getSize().height;var space=Math.max(ha,hb,this.minHeight||0)-this.list.shadowOffset-pad-5;h=Math.min(h,space,this.maxHeight);h=Math.min(h,hb);innerEl.dom.style.height=h+"px";this.list.alignTo(this.wrap,this.listAlign);}},onDestroy:function(){if(this.onKeyPressMonitorEmptyTextDeferId){clearTimeout(this.onKeyPressMonitorEmptyTextDeferId);}
Ext.destroy(this.contactCardHighlighterStrategyLookup);delete this.contactCardHighlighterStrategyLookup;Ext.destroy(this.pageTb);delete this.pageTb;Ext.destroy(this.curvyPanel);delete this.curvyPanel;Ext.destroy(this.view);delete this.view;Ext.destroy(this.list);delete this.list;Zw.controls.ContactCardComboBox.superclass.onDestroy.call(this);}});Ext.reg('Zw.controls.ContactCardComboBox',Zw.controls.ContactCardComboBox);

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.SendProgressBarClickablePlugin=Ext.extend(Zw.Plugin,{barWrapperCls:'zw-send-progress-bar-wrapper',onInit:function(){var client=this.client;if(client){this.client.on('render',this.activateProgressBarBehaviour,this);}},activateProgressBarBehaviour:function(){var client=this.client;if(client){var barWrapper=client.getEl().child('.'+this.barWrapperCls);barWrapper.addClassOnOver(this.barWrapperCls+'-mo');barWrapper.addClassOnClick(this.barWrapperCls+'-md');barWrapper.on('click',this.handler,this.scope||this);}}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardAdHocGroupPlugin=Ext.extend(Zw.Plugin,{onInit:function(){this.client.getMemberCount=this.getMemberCount;this.client.getMobileNumberAreaText=this.getMobileNumberAreaText;this.client.determineName=this.determineName;this.client.on('render',this.setupContactCard,this,{single:true});},setupContactCard:function(){this.client.el.addClass('zw-groupContactCard');this.client.el.addClass('zw-adhocGroupContactCard');},getMemberCount:function(){var address=this.get('address');if(!address&&this.contact){address=Zw.data.get(this.contact,'address');}
return address?(address.split(',').length-1):0;},getMobileNumberAreaText:function(previewStore){var count=this.getMemberCount();return(count==1)?'1 '+Zw.localize('generic.text.member'):count+' '+Zw.localize('generic.text.members');},determineName:function(){this.fullName=Zw.localize('generic.text.multipleRecipients');this.displayName=this.fullName;this.text=this.displayName;},onDestroy:function(){delete this.client.getMemberCount;delete this.client.getMobileNumberAreaText;delete this.client.determineName;this.client.un('render',this.setupContactCard,this);}});

Zw.namespace('Zw.features.messages');Zw.features.messages.PostSendDisplayAdvertBarClickTrackingPlugin=Ext.extend(Zw.Plugin,{advertId:undefined,textExposureTime:0,textClicksCounter:0,pictureExposureTime:0,pictureExposuresCounter:0,pictureClicksCounter:0,textCurrentExposureStartTime:null,pictureCurrentExposureStartTime:null,onInit:function(){this.client.onInit=this.client.onInit.createSequence(this.initializeTracking,this);},initializeTracking:function(){this.client.client.on('show',this._initializeTracking,this);},_initializeTracking:function(){var client=this.client;if(client){this.advertId=client.advert.id;this.startTextExposureTimer();client.advertBarContent.el.on('click',this.recordTextClick,this);var target=client.advertBubble;if(target.el){this.activateTarget(target);}else{target.on('render',this.activateTarget,this,{single:true});}}},activateTarget:function(target){target.el.on('click',this.recordPictureClick,this);target.on('show',this.recordPictureExposure,this);target.on('show',this.startPictureExposureTimer,this);target.on('hide',this.stopPictureExposureTimer,this);},recordPictureClick:function(){this.pictureClicksCounter+=1;},recordTextClick:function(){this.textClicksCounter+=1;},recordPictureExposure:function(){this.pictureExposuresCounter+=1;},startTextExposureTimer:function(){if(this.textCurrentExposureStartTime===null){this.textCurrentExposureStartTime=new Date();}},stopTextExposureTimer:function(){if(this.textCurrentExposureStartTime!==null){this.textExposureTime+=(new Date()-this.textCurrentExposureStartTime);this.textCurrentExposureStartTime=null;}},startPictureExposureTimer:function(){if(this.pictureCurrentExposureStartTime===null){this.pictureCurrentExposureStartTime=new Date();}},stopPictureExposureTimer:function(){if(this.pictureCurrentExposureStartTime!==null){this.pictureExposureTime+=(new Date()-this.pictureCurrentExposureStartTime);this.pictureCurrentExposureStartTime=null;}},saveResults:function(){if(this.advertId!==undefined){this.stopTextExposureTimer();this.stopPictureExposureTimer();Zw.Application.Net.advertRecord({params:{sessionKey:this.sessionKey,advertId:this.advertId,textExposureTime:this.textExposureTime,textClicksCounter:this.textClicksCounter,pictureExposureTime:this.pictureExposureTime,pictureExposuresCounter:this.pictureExposuresCounter,pictureClicksCounter:this.pictureClicksCounter}});}},onDestroy:function(){this.saveResults();var client=this.client;if(client){if(client.advertBubble){client.advertBubble.un('render',this.activateTarget,this);}
if(client.client){client.client.un('show',this._initializeTracking,this);}}}});

Zw.features.messages.PostSendDisplayAdvertBarPlugin=Ext.extend(Zw.Plugin,{advertBarTextContentTpl:'<div class="m">{text}</div>',advertBarLinkContentTpl:'<a class="m action" href="{url}" target="_blank">{text}</a>',isAdvertBubbleVisible:false,onInit:function(){var advert=this.advert;this.advertBarContent=new Zw.controls.Div({url:advert.url,text:advert.text,tpl:advert.url?this.advertBarLinkContentTpl:this.advertBarTextContentTpl});this.advertBar=new Zw.controls.Div({ctCls:'postSendAdvertising-wrap',cls:'postSendAdvertising',baseMouseCls:'postSendAdvertising',addMouseClasses:true,enableMouseEvents:true,items:[{xtype:'div',cls:'ml',items:[{xtype:'div',cls:'mr',items:this.advertBarContent}]}]});this.advertBubble=new Zw.controls.Div({cls:'advWindow advWindow-'+advert.cls,enableMouseEvents:true,styleX:advert.style?advert.style:'',hidden:true,hideMode:'offsets',html:advert.url?'<a class="action" href="'+advert.url+'" target="_blank"></a>':undefined,listeners:{scope:this,'mouseover':this.showAdvertBubble,'mouseout':this.hideAdvertBubble,'render':this.notUsingClosuresIsSuchAPainInTheAss}});this.advertBubbleHideTask=new Ext.util.DelayedTask();this.advertBar.on('render',this.attachMouseEventsListeners,this,{single:true});this.advertBar.on('render',this.setupMetricsPlugin,this,{single:true});this.client.on('show',this.trimAdvertText,this,{single:true});this.client.on('resize',this.trimAdvertText,this,{buffer:true});this.client.southWrap.add(this.advertBar);},notUsingClosuresIsSuchAPainInTheAss:function(advertBubble){this.client.fireEvent('advertBubbleRender',advertBubble);},attachMouseEventsListeners:function(){var advertBar=this.advertBar;if(advertBar){advertBar.on('mouseover',this.showAdvertBubble,this);advertBar.on('mouseout',this.hideAdvertBubble,this);}},setupMetricsPlugin:function(){this.metrics=new Zw.util.FontMetricsPlugin({el:this.advertBarContent.el});this.addPlugin(this.metrics);},getAdvertThatFitsWidth:function(advertText,maxWidth){if(!advertText||advertText.length<10)return advertText;if(!maxWidth||maxWidth<=100)return advertText;if(advertText.length&&(this.metrics.getMeasurement(advertText)>maxWidth)){return this.getAdvertThatFitsWidth((advertText.slice(0,-5)+'...'),maxWidth);}else{return advertText;}},trimAdvertText:function(){if(this.advert.text){var el=this.advertBarContent.el;if(el){el.update(this.getAdvertThatFitsWidth(this.advert.text,el.getWidth()));}}},showAdvertBubble:function(){if(!this.advertBubble.el){this.advertBubble.render(Ext.getBody());}
this.advertBubbleHideTask.cancel();if(!this.isAdvertBubbleVisible){this.advertBubble.show();this.advertBubble.el.alignTo(this.advertBar.el,'bl-br',[13,0]);this.isAdvertBubbleVisible=true;}},hideAdvertBubble:function(){var advertBubbleHideTask=this.advertBubbleHideTask;if(advertBubbleHideTask){advertBubbleHideTask.delay(1250,this._hideAdvertBubble,this);}},_hideAdvertBubble:function(){this.advertBubble.hide();this.isAdvertBubbleVisible=false;},onDestroy:function(){var client=this.client;if(client){client.un('show',this.trimAdvertText,this,{single:true});client.un('resize',this.trimAdvertText,this,{buffer:true});}
var advertBar=this.advertBar;if(advertBar){advertBar.un('render',this.attachMouseEventsListeners,this,{single:true});advertBar.un('render',this.setupMetricsPlugin,this,{single:true});advertBar.un('mouseover',this.showAdvertBubble,this);advertBar.un('mouseout',this.hideAdvertBubble,this);delete this.advertBar;}
var advertBubble=this.advertBubble;if(advertBubble){advertBubble.destroy();delete this.advertBubble;}
var advertBubbleHideTask=this.advertBubbleHideTask;if(advertBubbleHideTask){advertBubbleHideTask.cancel();delete this.advertBubbleHideTask;}}});

Zw.namespace('Zw.controls');Zw.controls.PostSendDisplay=Ext.extend(Ext.ux.PanelBlind,{prg:null,expandedProgressAreaHeight:256,childrenStatuses:null,constructor:function(config){config=Ext.applyIf(config,{autoHeight:false,height:119,floating:true,cls:'zw-send-progress-blind',baseCls:'x-blind',layout:'anchor',header:true,tools:[{id:'minimize',scope:this,on:{'mouseover':this.onToolMouseOver,'mouseout':this.onToolMouseOut},handler:this.doMinimize},{id:'resize',scope:this}],defaults:{xtype:'div'},items:[this.scheduleInfo=new Zw.controls.Div({hidden:true,anchor:'0',height:79,cls:'postSendScheduledBlind',items:[{xtype:'div',cls:'icon'},{xtype:'div',cls:'intro',html:Zw.localize('generic.alert.scheduledSuccess')},{xtype:'div',cls:'datetime',code:'datetime',html:(new Date()).format('F jS, Y \\a\\t g:i A T')}]}),this.northWrap=new Zw.controls.Div({anchor:'0',height:79,items:[new Zw.controls.SendProgressBar({code:'progressbar',anchor:'r',context:config.context,plugins:[new Zw.controls.plugins.SendProgressBarClickablePlugin({handler:this.expandProgressArea,scope:this}),new Zw.features.messages.SendProgressBarStatusTrimPlugin()],errorClickHandler:this.expandProgressArea,scope:this,height:78}),{xtype:'div',cls:'settingsDropdownShowButton x-menu x-menu-undo',baseMouseCls:'settingsDropdownShowButton',code:'settingsDropdownShowButton',addMouseClasses:true,enableMouseEvents:true,scope:this,handler:this.showSettingsDropdown}]}),this.middleWrap=new Zw.controls.Div({anchor:'0 -101',cls:'zw-send-progress-blind-progressArea zw-contactcard-size-medium zw-send-progress-bar-size-small',code:'progressArea',layout:'card',layoutConfig:{deferredRender:true},activeItem:0,items:[{xtype:'div'},{xtype:'div',cls:'progressAreaContents',code:'progressAreaContents'}]}),this.southWrap=new Zw.controls.Div({anchor:'0',cls:'postSendDisplayFooter',height:22})],buttons:[]});Zw.controls.PostSendDisplay.superclass.constructor.apply(this,[config]);},initComponent:function(){this.success=0;this.childrenStatuses=new Ext.util.MixedCollection();this.fieldinator=new Zw.util.FieldinatorPlugin({scope:this});this.fieldinator.init(this);this.addEvents({'SettingsChanged':true,'settingsDropdownRender':true});this.on('render',this.onThisRender,this);this.on('destroy',this._onDestroy,this);Zw.controls.PostSendDisplay.superclass.initComponent.call(this);},onThisRender:function(){this.settingsDropdownShowButton=this.field('settingsDropdownShowButton');this.resizer=new Ext.Resizable(this.getEl(),{handles:'n',minHeight:120,listeners:{scope:this,'resize':this._onResize}});if(this.delayedDelivery){this.field('datetime').html=(new Date(this.deliveryDateLocal)).format('F jS, Y \\a\\t g:i A T');this.showScheduleInfo();}},_onResize:function(){this.syncSize();if(this.layout){if(this.getEl().getHeight()>150){this.field('progressArea').layout.setActiveItem(1);}else{this.field('progressArea').layout.setActiveItem(0);}
this.doLayout();}},expandProgressArea:function(){var thisEl=this.getEl();var posShift=this.expandedProgressAreaHeight-thisEl.getHeight();if(posShift>0){thisEl.setHeight(this.expandedProgressAreaHeight);var blindPosition=this.getPosition(true);this.setPosition(blindPosition[0],blindPosition[1]-posShift);this._onResize();}},showScheduleInfo:function(){this.scheduleText=true;this.northWrap.hide();this.scheduleInfo.show();this.middleWrap.addClass('zw-send-progress-blind-progressArea-plain');},hideScheduleInfo:function(){this.scheduleText=false;this.scheduleInfo.hide();this.northWrap.show();this.middleWrap.removeClass('zw-send-progress-blind-progressArea-plain');},getProgressBar:function(value){if(!this.prg)
this.prg=this.field('progressbar');return this.prg;},getResizerGrip:function(){if(!this.resizerGrip)
this.resizerGrip=this.getEl().child('.x-tool-resize');return this.resizerGrip;},setResizable:function(allowed){var resizerGrip=this.getResizerGrip();var el=this.resizer.north.el;if(allowed){el.show();resizerGrip.show();}else{el.hide();resizerGrip.hide();}},addChildProgressBar:function(args){this.barCount++;var contact=args.contact;var device=args.device;var key=contact+':'+device;if(!contact)contact=-1;var childrenStatus={contact:this.context.getContactManager().getContactByIdAndDeviceId(contact,device),contactCard:null,progressBar:null,status:null,key:key};var plugins=null;if(!childrenStatus.contact){var plugin=new Zw.controls.plugins.ContactCardDelayLoadPropertiesPlugin({contactId:contact,deviceId:device,context:this.context});plugins=[plugin];}
this.childrenStatuses.add(key,childrenStatus);var progressArea=this.field('progressAreaContents');if(progressArea){var contactCard=this.context.getContactCardFactory().createContactCard({cls:'floatLeft',contact:childrenStatus.contact,plugins:plugins});childrenStatus.contactCard=contactCard;var status=new Zw.controls.Div({cls:'status'});childrenStatus.status=status;var progressBar=new Zw.controls.SendProgressBar({context:this.context,preventBlink:true,preventReceipt:true,status:status,multiple:false,contact:childrenStatus.contact,statusCls:'x-hidden-important'});childrenStatus.progressBar=progressBar;progressArea.add({xtype:'div',cls:'progressAreaContentsItem',items:[contactCard,progressBar,status,{xtype:'div',style:'clear:both'}]});if(progressArea.rendered)
progressArea.doLayout();}},onShowComplete:function(){this.field('progressArea').removeClass('zw-send-progress-blind-progressArea-hidden');this.resizer.north.el.show();if(!this.scheduleText){this.setResizable(true);}},onHideStart:function(){this.field('progressArea').addClass('zw-send-progress-blind-progressArea-hidden');this.setResizable(false);},updateProgress:function(args){var route=args.route;var key=route.contact+':'+route.device;var progress=args.progress;var childStatus=this.childrenStatuses.get(key);if(childStatus){childStatus.progressBar.setValue(progress);if(args.error){if(!childStatus.progressBar.error){this.errorCount++;}
childStatus.progressBar.setError(args.error);}
if(args.complete){var wasCompletedAlready=!childStatus.progressBar.setComplete();}}
var max=this.childrenStatuses.getCount();if(args.complete){if(!wasCompletedAlready){this.success++;}}
this.getProgressBar().setSuccessCount({count:this.success,total:max,error:args.error});},doMinimize:function(args){var callback=Ext.emptyFn;var scope=this;if(args){if(args.callback){callback=args.callback;scope=args.scope||scope;}}
this.el.visible=false;this.el.enableShadow(false);if(this.undoObj){var el=this.el.child('.x-tool-minimize');if(el){el.removeClass('x-tool-minimized');el.removeClass(['x-tool-minimized-mo','x-tool-minimize-mo']);}
this.undoObj.undo({callback:this.onShowComplete,scope:this,undoFn:this.syncSizeWithClient.createDelegate(this)});delete this.undoObj;}else{this.onHideStart();this.undoObj=this.el.slideOutOffset('b',{offset:20,scope:this,callback:function(){this.down=true;var el=this.el.child('.x-tool-minimize');if(el){el.addClass('x-tool-minimized');el.removeClass(['x-tool-minimized-mo','x-tool-minimize-mo']);}
if(callback){callback.call(scope);}}});}},showSettingsDropdown:function(e,button){Zw.Packages.get('menu.all',this._showSettingsDropdown,this,[e,button]);},findFieldInDropdown:function(code){return this.settingsDropdown.find('code',code)[0];},_showSettingsDropdown:function(e,button){if(!this.settingsDropdown){this.settingsDropdown=new Zw.controls.FloatingPanel({cls:'x-menu zw-dropdown z z-zw-dropdown settingsDropdown',autoWidth:true,height:105,allowOtherMenus:true,hidden:false,frame:false,border:false,bodyStyle:'',preventContextMenu:true,defaults:{xtype:'Zw.controls.WindowToolbarButtonGroup'},items:[{clsAddl:'zw-windowtbar-audio',items:[{xtype:'div',cls:'icon'},{xtype:'checkbox',code:'ding',boxLabel:Zw.localize('generic.settings.postSend.alert'),checked:this.getSetting('ding'),width:200,listeners:{scope:this,'check':this._onAudioChange}}]},{clsAddl:'zw-windowtbar-window',items:[{xtype:'div',cls:'icon'},{xtype:'checkbox',code:'close',boxLabel:Zw.localize('generic.settings.postSend.close'),checked:!this.getSetting('keepOpen'),width:200,listeners:{scope:this,'check':this._onWindowChange}}]}]});this.settingsDropdown.on('show',this.onSettingsDropdownShow,this);this.settingsDropdown.on('hide',this.onSettingsDropdownHide,this);this.settingsDropdown.on('render',this.onSettingsDropdownRender,this);this.settingsDropdown.on('destroy',this.onSettingsDropdownDestroy,this);this.fieldinator.backupFieldProvider=this.findFieldInDropdown;}else{this.field('ding').setValue(this.getSetting('ding'));this.field('close').setValue(!this.getSetting('keepOpen'));}
if(this.settingsDropdown.isVisible()){this.settingsDropdown.hide();}else{if(this.field){this.settingsDropdown.showBy(Ext.get(button),'tl-bl');}else{Ext.destroy(this.settingsDropdown);}}},onSettingsDropdownRender:function(settingsDropdown){this.fireEvent('settingsDropdownRender',settingsDropdown);},onToolMouseOver:function(){var minimizeEl=Ext.get(this);if(minimizeEl)
minimizeEl.addClass(minimizeEl.hasClass('x-tool-minimized')?'x-tool-minimized-mo':'x-tool-minimize-mo');},onToolMouseOut:function(){var minimizeEl=Ext.get(this);if(minimizeEl)
minimizeEl.removeClass(['x-tool-minimized-mo','x-tool-minimize-mo']);},onSettingsDropdownShow:function(){if(this.settingsDropdown&&this.field){var el=this.field('settingsDropdownShowButton').el;if(el){el.addClass('settingsDropdownShowButton-target');}}},onSettingsDropdownHide:function(){if(this.settingsDropdown&&this.field){var el=this.field('settingsDropdownShowButton').getEl();if(el){el.removeClass('settingsDropdownShowButton-target');}}},_onAudioChange:function(sender,pressed){this.setSetting('ding',pressed);this.fireEvent('SettingsChanged',this,'ding',pressed);},_onWindowChange:function(sender,pressed){this.setSetting('keepOpen',!pressed);},setSetting:function(key,value){var obj={};obj['sendMessage_'+key]=value;this.settings.set(obj);},getSetting:function(key){return this.settings.get('sendMessage_'+key);},_onDestroy:function(){if(this.resizer){Ext.destroy(this.resizer);delete this.resizer;}
if(this.settingsDropdown){Ext.destroy(this.settingsDropdown);delete this.settingsDropdown;}
if(this.resizerGrip){Ext.destroy(this.resizerGrip);delete this.resizerGrip;}
if(this.childrenStatuses){Ext.each(this.childrenStatuses,function(childrenStatus){if(childrenStatus){delete childrenStatus.contact;delete childrenStatus.contactCard;delete childrenStatus.progressBar;delete childrenStatus.status;}},this);delete this.childrenStatuses;}
delete this.context;}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ToBoxNubbyToolbarPlugin=Ext.extend(Zw.Plugin,{wasInitialized:false,toolbarHeight:undefined,wasVisibleBefore:false,onInit:function(){if(!this.wasInitialized){this.wasInitialized=true;var client=this.client.insert(0,this.buildNubbyToolbar());client.on('render',this.buildNubbyButton,this);this.client.toStore.on('add',this.onToStore_add,this);}},onToStore_add:function(store){if(store.getCount()>2){this.nubbyToolbar.show();}},newZipgroup:function(){var contactsSeed=this.client.toStore.getRange();var contacts=null;var hasSeed=(contactsSeed.length>0);if(hasSeed){contacts=[];Ext.each(contactsSeed,function(contact){if(Zw.util.isValidForGroupMembership(contact)){contacts.push(contact.copy());}});}
this.client.context.publish('/account/device/save',{contactsSeed:contacts,lazySave:!hasSeed,scope:this,callback:function(sender,e){var contact=e.contact;this.client.toStore.add(contact);for(var i=0;i<contactsSeed.length;i+=1){var c=contactsSeed[i];if(Zw.util.isValidForGroupMembership(c)){this.client.toStore.remove(c);}}
var contactCard=this.client.toBoxUpperItems.getControlByRecord(contact);if(contactCard){contactCard.showZoomGroup();}}});},setContactCardSize:function(sender){this.client.setContactCardSize(sender.code,true);},buildNubbyToolbar:function(){var nubbyToolbar=this.nubbyToolbar=new Zw.controls.Div({region:'north',cls:'nubbyToolbar',code:'nubbyToolbar',hideMode:'offsets',hidden:true,items:[{xtype:'Zw.features.messages.NubbyToolbarButtonGroup'}],plugins:[new Zw.util.FieldinatorPlugin()]});nubbyToolbar.on('show',this.getNubbyToolbarHeight,this,{single:true});nubbyToolbar.on('show',this.onNubbyToolbarShow,this);nubbyToolbar.on('hide',this.onNubbyToolbarHide,this);nubbyToolbar.field('createGroupButton').on('click',this.newZipgroup,this);nubbyToolbar.field('small').on('click',this.setContactCardSize,this);nubbyToolbar.field('medium').on('click',this.setContactCardSize,this);nubbyToolbar.field('normal').on('click',this.setContactCardSize,this);return nubbyToolbar;},getNubbyToolbarHeight:function(){this.toolbarHeight=this.nubbyToolbar.getSize().height+1;},buildNubbyButton:function(tobox){this.nubbyButton=new Zw.controls.Div({cls:'nubbyButton',enableMouseEvents:true,items:[{xtype:'div',cls:'nubbyButtonIcon',baseMouseCls:'nubbyButtonIcon',addMouseClasses:true}]});this.nubbyButton.render(this.client.container);this.nubbyButton.on('click',this.toggleNubbyToolbar,this);return this.nubbyButton;},toggleNubbyToolbar:function(){this.nubbyToolbar.setVisible(!this.nubbyToolbar.isVisible());},onNubbyToolbarShow:function(){this.nubbyButton.removeClass('nubbyButton-down');this.nubbyButton.addClass('nubbyButton-up');if(!this.wasVisibleBefore){this.client.toStoreCountModifier+=1;this.client.toStoreCountModifierHeight+=this.toolbarHeight;this.client.fireEvent('nonContactCardAdd');this.wasVisibleBefore=true;}},onNubbyToolbarHide:function(){this.nubbyButton.removeClass('nubbyButton-up');this.nubbyButton.addClass('nubbyButton-down');if(this.wasVisibleBefore){this.client.toStoreCountModifier-=1;this.client.toStoreCountModifierHeight-=this.toolbarHeight;this.client.fireEvent('nonContactCardRemove');this.wasVisibleBefore=false;}},onDestroy:function(){var client=this.client;if(client){client.toStore.un('add',this.onToStore_add,this);}
if(this.nubbyButton){Ext.destroy(this.nubbyButton);delete this.nubbyButton;}
if(this.nubbyToolbar){Ext.destroy(this.nubbyToolbar);delete this.nubbyToolbar;}}});if(Zw.capabilities.SEND_MESSAGE_WINDOW_NUBBY){Zw.features.PluginFactory.register('/desktop/message/window/panel/tobox',function(){if(Zw.capabilities.SEND_MESSAGE_WINDOW_NUBBY){return new Zw.controls.plugins.ToBoxNubbyToolbarPlugin();}});}

Zw.namespace('Zw.controls');Zw.controls.ToBox=Ext.extend(Ext.Panel,{sizeNormal:'normal',sizeMedium:'medium',sizeSmall:'small',addToStoreFix:true,arrow:true,contactCardSize:'normal',userSelectedContactCardSize:'',cls:'zw-sendmessage-tobox zw-control-tobox',frame:true,margins:'8 15 0 15',cmargins:'0 0 0 0',autoScroll:false,border:false,layout:'border',readOnly:false,emptyText:Zw.localize('generic.emptyText.toNumber'),creationManager:null,blacklistStrategy:'id',toBoxUpperItems:undefined,toBoxLowerItems:undefined,contactCardFactory:undefined,contactManager:undefined,toStore:undefined,toStoreCountModifier:0,toStoreCountModifierHeight:9,initComponent:function(){var plugins=[new Zw.util.ProxyPlugin({namespace:'/desktop/dataview/contacts'}),new Zw.util.ProxyPlugin({namespace:'/desktop/dataview/contacts/tobox'})];if(Zw.capabilities.ALLOW_AREA_CODE){plugins.push(new Zw.features.messages.AreaCodeAnalysisPlugin());}
Zw.Plugin.initEarlyPlugins.call(this);this.bindToStore(this.toStore);this.initReferenceContactList();var size='zw-contactcard-size-'+this.contactCardSize;this.toBoxUpperItems=new Zw.controls.ContactCardDataView({code:'toBoxUpperItems',closebox:!this.readOnly,arrow:this.arrow,autoHeight:true,multiSelect:true,cls:'zw-contactcard-dv zw-contactcard-size '+size,overClass:'zw-view-over',itemSelector:'div.contacts-wrap',preventPopup:this.preventPopup,store:this.toStore,contactCardFactory:this.contactCardFactory,contactCardFactoryConfig:this.contactCardFactoryConfig,highlighterStrategyLookup:new Ext.util.MixedCollection()});this.toBoxLowerItems=new Zw.controls.ContactCardComboBox({code:'toBoxLowerItems',enableKeyEvents:false,maxHeight:200,resizable:true,disabled:this.readOnly,onBeforeLoad:Ext.emptyFn,store:this.referenceContactList,blacklist:this.toStore,blacklistStrategy:this.blacklistStrategy,contactCardFactory:this.contactCardFactory,displayField:'FullName',hideTrigger:false,mode:'local',triggerAction:'all',emptyText:this.emptyText,selectOnFocus:true,scope:this,plugins:plugins,listeners:{scope:this,'blur':this._onLowerItemsBlur,'keydown':this._onLowerItemsKeyDown,'select':this._onToBoxLowerChange}});this.items=this.items||[];this.items.push({region:'center',border:false,layout:'fit',autoScroll:true,cls:'zw-tobox-upper',items:this.toBoxUpperItems},{region:'south',border:false,layout:'fit',cls:'zw-tobox-lower',items:this.toBoxLowerItems,listeners:{scope:this,'render':this.onToBoxNonContactCardRemove,delay:true}});Zw.controls.ToBox.superclass.initComponent.call(this);this.on('nonContactCardAdd',this.onToBoxNonContactCardAdd,this,{buffer:true});this.on('nonContactCardRemove',this.onToBoxNonContactCardRemove,this,{buffer:true});},onToStoreRemove:function(store,record,index){if(store){this.changeToBoxSize(this.toBoxUpperItems,'remove',store);}},onToBoxNonContactCardRemove:function(){this.onToStoreRemove(this.toStore);},onToBoxNonContactCardAdd:function(){this.changeToBoxSize(this.toBoxUpperItems,'add',this.toStore);},onToStoreAdd:function(store,records,index){this.changeToBoxSize(this.toBoxUpperItems,'add',store);this.dirty=true;},changeToBoxSize:function(view,reason,store,records,index){var toBox=this;var count=store.getCount()+toBox.toStoreCountModifier;var size=this.sizeNormal;if(count>2){size=this.sizeSmall;}else if(count>1){size=this.sizeMedium;}else if(count==1){size=this.sizeNormal;}
var upper=this.toBoxUpperItems;toBox.setContactCardSize(size);if(!toBox.isDirty){var ownerCt=this.ownerCt;function measure(){upper.ownerCt.setVisible(true);var dataViewHeight=upper.getSize().height;if(count==0){dataViewHeight=0;}
var inputHeight=32;var modifierHeight=toBox.toStoreCountModifierHeight;var newToBoxHeight=inputHeight+modifierHeight+dataViewHeight;newToBoxHeight=(toBox.maxHeight)?Math.min(newToBoxHeight,toBox.maxHeight):newToBoxHeight;toBox.setHeight(newToBoxHeight);ownerCt.doLayout();}
if(!this.dirtyResize){measure();}
if(reason=='add'){if(count>3){var node=Ext.fly(view.getNode(store.getCount()-1));if(node){var container=node.up('.zw-contactcard-dv').parent();if(container){container.scroll('b',5000,true);}}}}}},initEvents:function(){this.addEvents("groupSaved");this.addEvents("contactAdded");this.addEvents("contactRemoved");this.addEvents("contactsChanged");this.addEvents('nonContactCardAdd');this.addEvents('nonContactCardRemove');Zw.controls.ToBox.superclass.initEvents.call(this);},bindToStore:function(store){this.unbindToStore();if(!store){store=new Ext.data.Store();}
this.toStore=store;store.on('add',this.onContactAdded,this);store.on('remove',this.onContactRemoved,this);store.on('add',this.onToStoreAdd,this,{buffer:true});store.on('remove',this.onToStoreRemove,this,{buffer:true});if(this.addToStoreFix){store._add=store.add;store.add=Zw.data.ClonedStore.add;}},unbindToStore:function(){if(this.toStore){this.toStore.un('add',this.onContactAdded,this);this.toStore.un('remove',this.onContactRemoved,this);this.toStore.un('add',this.onToStoreAdd,this);this.toStore.un('remove',this.onToStoreRemove,this);this.removeToStoreFix(this.toStore);}},removeToStoreFix:function(toStore){if(toStore&&this.addToStoreFix){toStore.add=toStore._add;}},setToStore:function(membersStore,groupDevice,isAdhocGroupContact){if(this.fireEvent('beforeToStoreSet',membersStore,groupDevice,isAdhocGroupContact)){this.bindToStore(membersStore);this.toBoxUpperItems.setStore(membersStore);this.toBoxLowerItems.blacklist=membersStore;this.fireEvent('toStoreSet',membersStore,groupDevice,isAdhocGroupContact);}},initReferenceContactList:function(){if(!this.referenceContactList&&this.contactManager)
this.referenceContactList=this.contactManager.getContacts();if(this.referenceContactList){this.referenceContactList.on('update',this._onReferenceContactListUpdate,this);this.referenceContactList.on('remove',this._onReferenceContactListRemove,this);}},_onLowerItemsBlur:function(sender,key){this.addPhoneNumber(sender,sender.getValue());},_onLowerItemsKeyDown:function(sender,e){var numberEntered=sender.getValue();if(sender&&((e.getKey()==e.ENTER)||(e.getKey()==e.TAB))){this.addPhoneNumber(sender,numberEntered);this.forceComboBoxCollapseIfNumber(numberEntered);}},forceComboBoxCollapseIfNumber:function(numberEntered){var reg=new RegExp(/^\s*\d+\s*$/);var numbersOnly=reg.test(numberEntered);if(Zw.capabilities.ALLOW_SHORT_CODE&&numbersOnly){this.toBoxLowerItems.collapse();}},setContactCardSize:function(size,userSelected){if(userSelected){this.userSelectedContactCardSize=(size!==this.contactCardSize)?size:'';}
if(userSelected||!this.userSelectedContactCardSize){if(size!==this.contactCardSize){var classNamePrefix='zw-contactcard-size-';this.toBoxUpperItems.el.removeClass(classNamePrefix+this.contactCardSize);this.toBoxUpperItems.el.addClass(classNamePrefix+size);this.contactCardSize=size;}}},_onReferenceContactListUpdate:function(sender,record){var id=record.id;var rec=this.toStore.getById(id);if(rec){Zw.console('firing event update',rec);this.toStore.fireEvent('update',this.toStore,rec,'forced');}},_onReferenceContactListRemove:function(sender,record){var id=record.id;var rec=this.toStore.findBy(function(rec){return(rec.id==id);});if(rec!=-1)
this.toStore.remove(this.toStore.getAt(rec));},onContactAdded:function(store,records,index){Zw.console('onContactAdded called. records:',records);this.fireEvent('contactAdded',this,{store:store,records:records});this.onContactsChanged(store,records,index);},onContactRemoved:function(store,records,index){Zw.console("onContactRemoved called");this.fireEvent('contactRemoved',this,{store:store,records:records});this.onContactsChanged(store,records,index);},onContactsChanged:function(store,records,index){this.fireEvent('contactsChanged',store,records,index);},addToStore:function(record){if(this.toStore.indexOf(record)==-1){this.toStore.add(record);}},_onToBoxLowerChange:function(e,record){if(Zw.util.isPhoneNumber(this.toBoxLowerItems.getValue())){return;}
this.addToStore(record);this.toBoxLowerItems.setValue('');this.toBoxLowerItems.fireEvent('focus');this.justAddedAnItem=true;this.turnOffJustAddedAnItem.defer(100,this);},turnOffJustAddedAnItem:function(){this.justAddedAnItem=false;},addPhoneNumber:function(comboBox,value){Zw.console('Adding Phone Number:',value);var receivers=Zw.util.tokenizePhoneNumbers(value);var receiver,i;for(i=0;((receiver=receivers[i]));i++){if(!Ext.isEmpty(receiver.number)&&Zw.util.isPhoneNumber(receiver.number)){if(comboBox){comboBox.setValue('');}
var contactCard;var contactIndex=this.referenceContactList.find('mobileNumber',Zw.util.getRawPhoneNumber(receiver.number));if(contactIndex!=-1&&!Zw.capabilities.ALLOW_SHORT_CODE){contactCard=this.referenceContactList.getAt(contactIndex);}else{if(!this.numberOfProcessingContacts){this.numberOfProcessingContacts=0;}
this.numberOfProcessingContacts++;var receiverNameParsed=((receiver.name)?Zw.util.getNameParts(receiver.name):{firstName:'',lastName:''});contactCard=this.createContact(receiver.number,receiverNameParsed,true);}
this.addToStore(contactCard,((contactIndex<0)?'created':undefined));}}},_onCreateContactSuccess:function(sender,contact,args){if(contact){if(contact.data){contact.data.preferGet=false;}else{contact.preferGet=false;}}
this.numberOfProcessingContacts--;},_onCreateContactFailure:function(sender,contact,args,reason){this.numberOfProcessingContacts--;Ext.Msg.alert(Zw.localize('generic.alert.couldNotSaveContact.title'),String.format(Zw.localize('generic.alert.couldNotSaveContact.title'),reason));this.toStore.remove(contact);},createContact:function(mobileNumber,parsedName,preferGet){return this.creationManager.createContact({scope:this,contact:{mobileNumber:mobileNumber,firstName:parsedName.firstName,lastName:parsedName.lastName,channel:' ',preferGet:preferGet},success:this._onCreateContactSuccess,failure:this._onCreateContactFailure});},onDestroy:function(){var r=this.referenceContactList;if(r){r.un('update',this._onReferenceContactListUpdate,this);r.un('remove',this._onReferenceContactListRemove,this);}
this.unbindToStore();}});Ext.reg('Zw.controls.ToBox',Zw.controls.ToBox);

Zw.features.messages.PreventCloseForPostSendDisplayMOPlugin=Ext.extend(Zw.Plugin,{isMouseOver:undefined,onInit:function(){var client=this.client;if(client){client.blind.on('render',this.initListeners,this);client.on('beforeClose',this.isMouseOverCheck,this);}},initListeners:function(){var client=this.client;if(client){client.blind.el.hover(this.onMouseOver,this.onMouseOut,this);}},onMouseOver:function(){this.isMouseOver=true;},onMouseOut:function(){this.isMouseOver=false;var client=this.client;if(client){client.closeClientWindow.call(client);}},isMouseOverCheck:function(){return!this.isMouseOver;}});

Zw.features.messages.PreventCloseForSendProgressBarNotCompletePlugin=Ext.extend(Zw.Plugin,{progressBar:undefined,onInit:function(){var client=this.client;if(client){this.progressBar=client.blind.getProgressBar();this.progressBar.on('complete',client.closeClientWindow,client);client.on('beforeClose',this.isCompleted,this);}},isCompleted:function(){return!!this.progressBar.completed;}});

Zw.features.messages.PreventCloseForSettingsDropdownIsVisiblePlugin=Ext.extend(Zw.Plugin,{settingsDropdown:undefined,onInit:function(){var client=this.client;if(client){client.blind.on('settingsDropdownRender',this.initListeners,this);}},initListeners:function(settingsDropdown){var client=this.client;if(client){client.on('beforeClose',this.isVisibleCheck,this);settingsDropdown.on('destroy',client.closeClientWindow,client);this.settingsDropdown=settingsDropdown;}},isVisibleCheck:function(){return!this.settingsDropdown.isVisible();}});

Zw.features.messages.PreventCloseForZiptipMOPlugin=Ext.extend(Zw.Plugin,{isMouseOver:undefined,onInit:function(){var client=this.client;if(client){client.blind.on('advertBubbleRender',this.initMOListeners,this);client.on('beforeClose',this.isMouseOverCheck,this);}},initMOListeners:function(advertBubble){advertBubble.el.hover(this.onMouseOver,this.onMouseOut,this);},onMouseOver:function(){this.isMouseOver=true;},onMouseOut:function(){this.isMouseOver=false;var client=this.client;if(client){client.closeClientWindow.call(client);}},isMouseOverCheck:function(){return!this.isMouseOver;}});

Zw.util.SendMessageWindowTabinatorPlugin=Ext.extend(Zw.util.TabinatorPlugin,{autoFocus:false,tabBoost:false,fields:['toBoxLowerItems','body','send'],keyNavArgs:{forceKeyDown:true},_init:function(client){if(!this.plugins)
this.plugins=[new Zw.util.TabinatorFocusPreviousTabStrategyPlugin()];Zw.util.SendMessageWindowTabinatorPlugin.superclass._init.call(this,client);},onInit:function(){Zw.util.SendMessageWindowTabinatorPlugin.superclass.onInit.call(this);this.on('render',this.applyKeyNavPropertyToClient,this);},applyKeyNavPropertyToClient:function(){this.client.keyNav=this.keyNav;},onTab:function(e){var lower=this.client.field('toBoxLowerItems');var toBox=this.client.field('toBox');var value=lower.getValue();var justAddedAnItem=toBox.justAddedAnItem;if(!Ext.isEmpty(value)||justAddedAnItem){this.tabBoost=true;}else{if(this.tabBoost===true){if(!e.ctrlKey){e.preventDefault();}
if(!e.shiftKey){this.focusFieldByIndex(1);}else{this.focusFieldByIndex(2);}
this.tabBoost=false;}else{Zw.util.SendMessageWindowTabinatorPlugin.superclass.onTab.call(this,e);}}},onDestroy:function(){delete this.client.keyNav;Zw.util.SendMessageWindowTabinatorPlugin.superclass.onDestroy.call(this);}});

Zw.namespace('Zw.features.messages');Zw.features.messages.SendMessageWindowTextSuggestPlugin=Ext.extend(Zw.features.messages.TextSuggestPlugin,{window:null,start:function(){if(!this.listening&&this.window.keyNav){this.window.keyNav.disable();}
Zw.features.messages.SendMessageWindowTextSuggestPlugin.superclass.start.call(this);},stop:function(){if(this.window.keyNav){this.window.keyNav.enable();}
Zw.features.messages.SendMessageWindowTextSuggestPlugin.superclass.stop.call(this);}});

Zw.features.messages.SendProgressBarStatusTrimPlugin=Ext.extend(Zw.Plugin,{maxHeight:32,onInit:function(){var client=this.client;if(client){this.client.on('statusUpdate',this.trimText,this);}},getTextThatFitsHeight:function(text,el,maxHeight){if(text.length&&(el.getHeight()>maxHeight)){var trimmedText=text.slice(0,-5)+'...';el.update(trimmedText);arguments.callee(trimmedText,el,maxHeight);}},trimText:function(text,el){this.getTextThatFitsHeight(text,el,this.maxHeight);},onDestroy:function(){var client=this.client;if(client){client.un('statusUpdate',this.trimText,this);}}});

Zw.namespace('Zw.controls.plugins');Zw.controls.plugins.ContactCardCarrierUnsupportedErrorPlugin=Ext.extend(Zw.controls.plugins.ContactCardErrorPlugin,{carrierId:undefined,updateErrorDescription:function(){this.errorDescription=[Zw.localize('generic.alert.unsupportedCarrier.text1'),Zw.data.getCarrierFormalName(this.carrierId),Zw.localize('generic.alert.unsupportedCarrier.text2'),' <a class="interlink" href="#faq?section=faq-who_can_i_zipwhip">'+Zw.localize('generic.alert.unsupportedCarrier.text3')+'</a>'].join('');},onInit:function(){if(this.isCarrierSupported===false){this.updateErrorDescription();this.client.on('show',this.showError,this);}else if(this.isCarrierSupported===undefined){this.client.on('Update',this.showErrorIfRequired,this);}},showErrorIfRequired:function(){var carrierId=Zw.data.get(this.client.contact,'carrier');var isCarrierSupported=Zw.data.isCarrierSupported(carrierId);this.carrierId=carrierId;this.isCarrierSupported=isCarrierSupported;if(this.isCarrierSupported===false){this.client.un('Update',this.showErrorIfRequired,this);this.updateErrorDescription();this.showError();}},onDestroy:function(){this.client.un('show',this.showError,this);this.client.un('Update',this.showErrorIfRequired,this);}});

Zw.namespace('Zw.features.taskbar');Zw.features.taskbar.FakeTaskbarPlugin=Ext.extend(Zw.Plugin,{onInit:function(){this.div=new Zw.controls.Div({renderTo:Ext.get('taskbar'),tpl:'<div><div class="minimize-all"></div></div>',onClick:this.onDivClick,initDiv:this.onInitDiv});},onInitDiv:function(el){var els=el.child('.minimize-all');els.addClassOnOver('minimize-all-mo');els.addClassOnClick('minimize-all-md');},onDivClick:function(){Zw.Application.Context.publish('/app/service/run',{pkg:'window.services',service:'Zw.features.taskbar.TaskbarService',uri:'/desktop/window/minimizeall'});},onDestroy:function(){if(this.div)
this.div.destroy();delete this.div;delete Zw.features.taskbar.FakeTaskbarPlugin;}});Zw.features.taskbar.FakeTaskbarPlugin.instance=new Zw.features.taskbar.FakeTaskbarPlugin();Zw.features.taskbar.FakeTaskbarPlugin.instance.init();

Zw.features.app.GenericURLFeature=Ext.extend(Zw.Feature,{onInit:function(){this.subscribe('/desktop/url/view',this.onViewURL,this);this.subscribe('/desktop/interlink/advert',this.onViewURL,this);},onViewURL:function(args){alert('hey%20dawg%20how%20are%20you'.replace(/%20/,' '));alert('hey%20dawg%20how%20are%20you'.replace(/%20/g,' '));alert(args.text);if(args&&args.text){args.text=(''+args.text).replace(/%20/g,' ');}
alert(args.text);var w=this.context.Desktop.registerWindow(new Zw.controls.Window({title:args.text,width:600,height:300,layout:'fit',items:[{xtype:'iframepanel',defaultSrc:args.url}]}));w.show();}});

Ext.namespace('Zw.controls.plugins');Zw.controls.plugins.BubblePanelMarkMessageAsReadByMouseOverPlugin=Ext.extend(Zw.Plugin,{onInit:function(){this.client.on('render',this.addHandlers,this,{single:true});},addHandlers:function(){this.client.el.on('mouseover',this.client.markMessageAsRead,this.client,{single:true});},onDestroy:function(){this.client.un('render',this.addHandlers,this);if(this.client.el)
this.client.el.un('mouseover',this.client.markMessageAsRead,this);}});Zw.features.PluginFactory.register('/desktop/bubblepanel',function(args){if((args.panelStyle=='unread')&&Zw.capabilities.markAsReadOnMO){return new Zw.controls.plugins.BubblePanelMarkMessageAsReadByMouseOverPlugin(args);}});

Zw.namespace('Zw.features.app');Zw.features.app.ErrorInterlinksAdapterService=Ext.extend(Zw.Service,{uri:'/desktop/interlink/error',onInit:function(){this.context.subscribe(this.uri,this.onErrorInterlink,this);},onErrorInterlink:function(args){var errorTitle=Ext.util.Format.defaultValue(args.error_title,'');var errorMsg=Ext.util.Format.defaultValue(args.error_message,'');this.context.publish('/desktop/error/show/',{title:errorTitle,msg:errorMsg});},onDestroy:function(){this.context.unsubscribe(this.uri,this.onErrorInterlink);}});

Zw.app.InterlinksUrlBridgePlugin=Ext.extend(Zw.Plugin,{onInit:function(){Zw.Application.subscribe('/app/start',this.onApplicationStart,this,{single:true});},onApplicationStart:function(){var url=location.href;if(url.indexOf("#")!=-1)
this.client.handleLink(location);}});Zw.app.PluginFactory.register('/app/interlinks','Zw.app.InterlinksUrlBridgePlugin');

Zw.namespace('Zw.app');Zw.app.ApplicationDesktopLoginButtonDisplayStrategyPluginBase=Ext.extend(Zw.Plugin,{login:null,logout:null,onInit:function(){Zw.Application.subscribe('/context/account/discovered',this.updateLoginUI,this);Zw.Application.subscribe('/app/context/activated',this.onContextActivated,this);Zw.Application.subscribe('/app/context/deactivated',this.onContextDeactivated,this);Zw.Application.subscribe('/app/start',this.onStart,this);},onStart:function(){this.login=Zw.Application.Desktop.login;this.logout=Zw.Application.Desktop.logout;},onContextActivated:function(context){this.showHideLoginButtons(context);},updateLoginUI:function(args){this.showHideLoginButtons(args.context);},showHideLoginButtons:Ext.emptyFn,onContextDeactivated:Ext.emptyFn});

Zw.namespace('Zw.app');Zw.app.ApplicationDesktopGuestLoginButtonDisplayStrategyPlugin=Ext.extend(Zw.app.ApplicationDesktopLoginButtonDisplayStrategyPluginBase,{showHideLoginButtons:function(context){if(Zw.Application.isActiveContext(context)&&this.logout){var isGuest=context.Account.isGuest(true);if(isGuest){var contextCount=Zw.Application.getContextCount();if(contextCount==1){this.logout.hide();}else{this.logout.show();}}else{this.logout.show();}}}});Zw.app.PluginFactory.register('/application/desktop','Zw.app.ApplicationDesktopGuestLoginButtonDisplayStrategyPlugin');

Zw.namespace('Zw.app');Zw.app.ApplicationDesktopUserLoginButtonDisplayStrategyPlugin=Ext.extend(Zw.app.ApplicationDesktopLoginButtonDisplayStrategyPluginBase,{showHideLoginButtons:function(context){if(Zw.Application.isActiveContext(context)&&this.login){var isGuest=context.Account.isGuest(true);if(isGuest){this.login.show();}else if(Zw.capabilities.ALLOW_MASQUERADE){this.login.show();}else{this.login.hide();}}}});Zw.app.PluginFactory.register('/application/desktop','Zw.app.ApplicationDesktopUserLoginButtonDisplayStrategyPlugin');

Zw.namespace('Zw.features.app');Zw.features.app.AccountGuestStateMonitorPlugin=Ext.extend(Zw.Plugin,{discovered:null,isGuest:null,onInit:function(){this.context=this.client.client;this.context.subscribe('/account/user/data',this.onTick,this);},onTick:function(args){var isGuest=this.context.Account.isGuest(true);if(this.discovered===null){this.announce(args,isGuest);this.discovered=true;}else if(this.isGuest&&!isGuest){this.announce(args,isGuest);}
this.isGuest=isGuest;},announce:function(args,isGuest){var extras=(isGuest)?'guest':'user';this.context.publish('/account/discovered/'+extras,args);Zw.Application.publish('/context/account/discovered/'+extras,{args:args,context:this.context});},onDestroy:function(){this.context.unsubscribe('/account/user/data',this.onTick,this);delete this.context;}});Zw.features.PluginFactory.register('/account','Zw.features.app.AccountGuestStateMonitorPlugin');

Zw.namespace('Zw.util');Zw.util.MobileNumberFormatterPlugin=Ext.extend(Zw.Plugin,{DEFAULT_FORMAT:'US',format:null,autoInit:true,phoneNumberDelimiters:'()-. ',addPlugin:function(p){p.init(this);},init:function(){this.addPlugin(new Zw.util.ProxyPlugin({namespace:'/desktop/mobileNumber/format'}));this.format=new Ext.util.MixedCollection();this.format.add('US',{numberLength:10,specialChars:{0:'(',4:')',5:' ',9:'-'}});this.format.add('AUS',{numberLength:11,specialChars:{3:' ',7:' ',11:' '}});this.format.add('VN11',{numberLength:11,specialChars:{3:'0',6:' '}});this.format.add('VN12',{numberLength:12,specialChars:{3:'0',7:' '}});this.format.add('MY1',{numberLength:11,specialChars:{3:' ',6:' '}});this.format.add('MY14',{numberLength:12,specialChars:{3:' ',6:'-',8:' '}});this.format.add('MY15',{numberLength:12,specialChars:{3:' ',7:' '}});this.format.add('SG',{numberLength:10,specialChars:{3:' ',8:' '}});this.format.add('IN',{numberLength:12,specialChars:{3:' ',8:'-'}});this.format.add('TH',{numberLength:11,specialChars:{3:' ',5:' ',10:' '}});this.format.add('ID',{numberLength:13,specialChars:{3:' ',8:' ',13:' '}});this.format.add('CN',{numberLength:13,specialChars:{3:' ',7:' ',12:' '}});this.format.add('PH',{numberLength:12,specialChars:{3:' ',7:' ',11:' '}});this.format.add('UNKNOWN',{numberLength:0,specialChars:{}});},onInit:function(){},display:function(num,format,counter){return this.formatNumber(num,format,counter);},formatNumber:function(num,format,counter){var result='';counter=(counter)?counter:0;format=(format)?format:this.getFormat(num);num=Zw.util.stripCharsInBag(num,this.phoneNumberDelimiters);var specialChars=format.specialChars;var i=0;while(i<num.length)
if(specialChars[counter]){result+=specialChars[counter];counter++;}else{result+=num.charAt(i);i++;counter++;}
return result;},detectFormat:function(mobileNumber){if(!mobileNumber)return'US';mobileNumber=mobileNumber.replace(/ /g,'');if(mobileNumber.indexOf('+61')==0){return'AUS';}else if(mobileNumber.indexOf('+849')==0){return'VN11';}else if(mobileNumber.indexOf('+841')==0){return'VN12';}else if(mobileNumber.indexOf('+6014')==0){return'MY14';}else if(mobileNumber.indexOf('+6015')==0){return'MY15';}else if(mobileNumber.indexOf('+601')==0){return'MY1';}else if(mobileNumber.indexOf('+65')==0){return'SG';}else if(mobileNumber.indexOf('+91')==0){return'IN';}else if(mobileNumber.indexOf('+66')==0){return'TH';}else if(mobileNumber.indexOf('+62')==0){return'ID';}else if(mobileNumber.indexOf('+86')==0){return'CN';}else if(mobileNumber.indexOf('+63')==0){return'PH';}
else{if(mobileNumber.length<9||mobileNumber.indexOf('device:/')!=-1){return'UNKNOWN';}
return this.DEFAULT_FORMAT;}},getFormat:function(mobileNumber){return this.format.get(this.detectFormat(mobileNumber));},getFormatNumberLength:function(mobileNumber){var format=this.getFormat(mobileNumber);if(format){return format.numberLength;}}});Zw.util.MobileNumberFormatterPlugin.getInstance=function(){if(!this.instance){this.instance=new Zw.util.MobileNumberFormatterPlugin();}
return this.instance;};

Zw.namespace('Zw.app');Zw.app.ApplicationPhoneIconDisplayStrategyPlugin=Ext.extend(Zw.Plugin,{_useCssClasses:false,onInit:function(){Zw.data.Phone.GetBasePhoneIconClass=this.GetBasePhoneIconClass.createDelegate(this);Zw.data.Phone.GetEditPhoneIconClass=this.GetEditPhoneIconClass.createDelegate(this);Zw.data.Phone.GetZoomPhoneIconClass=this.GetZoomPhoneIconClass.createDelegate(this);Zw.data.Phone.GetBaseSprite=this.GetBaseSprite.createDelegate(this);Zw.data.Phone.GetEditContactSprite=this.GetEditContactSprite.createDelegate(this);Zw.data.Phone.GetZoomSprite=this.GetZoomSprite.createDelegate(this);this._useCssClasses=(Ext.isIE)?true:false;},GetBasePhoneIconClass:function(phoneKey){if(this._useCssClasses){return phoneKey+'_base';}else{return'';}},GetEditPhoneIconClass:function(phoneKey){if(this._useCssClasses){return phoneKey+'_ec';}else{return'';}},GetZoomPhoneIconClass:function(phoneKey){if(this._useCssClasses){return phoneKey+'_zoom';}else{return'';}},GetBaseSprite:function(phoneKey){if(this._useCssClasses){return'';}else if(Zw.Application.debug){return"//beta.zipwhip.com/phones-dev/Base/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_base.png";}else{return"//beta.zipwhip.com/phones/Base/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_base.png";}},GetEditContactSprite:function(phoneKey){if(this._useCssClasses){return'';}else if(Zw.Application.debug){return"//beta.zipwhip.com/phones-dev/EditContact/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_ec.png";}else{return"//beta.zipwhip.com/phones/EditContact/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_ec.png";}},GetZoomSprite:function(phoneKey){if(this._useCssClasses){return'';}else if(Zw.Application.debug){return"//beta.zipwhip.com/phones-dev/Zoom/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_zoom.png";}else{return"//beta.zipwhip.com/phones/Zoom/"+(Ext.isIE6?"ie6/":"")+phoneKey+"_zoom.png";}}});if(Ext.isIE){(Ext.isIE6)?Zw.Packages.get('phone.icons_ie6'):Zw.Packages.get('phone.icons');}
Zw.app.PluginFactory.register('/application','Zw.app.ApplicationPhoneIconDisplayStrategyPlugin');

Zw.namespace('Zw.features.messages.plugins');Zw.features.messages.InterlinkNewTextFeature=Ext.extend(Zw.Feature,{monitorGuestState:true,show:false,onInit:function(){this.client.subscribe('/desktop/interlink/contact',this.showInterlinkContactNewText,this);this.client.subscribe('/account/contacts/loaded',this.onContactsLoaded,this);},onContactsLoaded:function(){this.contactsLoaded=true;this.tick();},tick:function(){Zw.console("InterlinkNewTextFeature - Should Show message: ",this.contactsLoaded+": "+!this.fired+": "+this.show);if(this.contactsLoaded&&!this.fired&&this.show){this.fired=true;this.client.publish('/desktop/message/new',{handler:this.handler,scope:this});}},onAuthenticatedAsUser:function(){this.tick();},showInterlinkContactNewText:function(){var args=(arguments)?arguments[0]:null;if(args)
this.mobileNumber=args.queryObject.mobileNumber;Zw.capabilities.FORCE_NO_INITIAL_SENDTEXT_WINDOW=true;this.show=true;this.tick();},handler:function(window){window.addPhoneNumber(this.mobileNumber);window.field('textbox').focus(false);},onDestroy:function(){this.client.unsubscribe('/desktop/interlink/contact',this.showInterlinkContactNewText,this);}});Zw.features.Factory.register('Zw.features.messages.InterlinkNewTextFeature');

