/*
 * Zipwhip Web 2.0 Messaging Product 1.0.
 * Copyright(c) 2008, 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.features.login.SprintWelcomeWindow=Ext.extend(Zw.controls.Window,{cls:'zw-window zw-window-welcome sprint',title:'Sign On',maximizable:false,code:'window',width:610,height:374,resizable:false,securityMode:false,layout:'fit',REGULAR_TEXT:'<div class="header">Get Texting</div> To begin texting you must first sign on with your Sprint login and password.',SECURITY_TEXT:'<div>Thanks for using the Sprint Web Texter</div><br>To log back in please visit www.sprint.com',actionButton:new Zw.controls.ActionButton({iconCls:'zw-button-icon-login',style:'margin-top: 10px;',text:'Sign On To My Sprint',code:'button',handler:function(sender,e){if(!this.window)
this.window=this.findParentBy(function(f){return f.code=='window'});this.window.onSignOn.call(this.window.scope||this.window,this,e);}}),setSecurityMode:function(value){},getItems:function(){return[{xtype:'div',defaultType:'div',items:[{cls:'left side',html:'Welcome to the Sprint Web Texter! This new texting utility has some powerful features.  Get ready to experience the next generation of texting!<ul><li>Send texts to all major U.S. mobile carriers</li><li>Send and receive text messages <strong>(2-way)</strong></li><li>Smart Forwarding to your mobile</li></ul>'},{cls:'right side',code:'rightside',items:[{xtype:'div',html:this.securityMode?this.SECURITY_TEXT:this.REGULAR_TEXT},{xtype:'div',cls:'signInWrap',items:[this.actionButton]},{xtype:'div',html:'Having trouble Logging in?  Click Here.',cls:'loginTroubleLink',code:'loginTrouble',scope:this,handler:this.openSecureLoginPage}]}]}];},openSecureLoginPage:function(sender,e){document.location="https://sprint.zipwhip.com";},openRegistrationWizard:function(sender,e){if(this.context){Zw.console('this.context.publish -- ',this.context);this.context.publish('/desktop/user/register');}else{Zw.Application.Context.publish('/desktop/user/register');}}});Zw.features.login.SprintIFrameWindow=Ext.extend(Zw.controls.Window,{cls:'zw-window',title:'Sign On via Sprint: loading...',DEV_url:'http://dlsa0499.dev.sprint.com:20780/sso/redirect.do?deeplink=zipwhip',LIVE_url:'https://sso.sprintpcs.com/sso/redirect.do?deeplink=zipwhip',maximizable:false,code:'window',width:700,height:450,resizable:true,layout:'fit',getItems:function(){this.url=this.LIVE_url;this.title="Sign On via Sprint: "+this.url;return[{id:'iframe',xtype:'iframepanel',layout:'fit',defaultSrc:this.url,defaultType:'div'}];},onIFramePathChanged:function(sender){Zw.console(sender.src);Zw.console(sender.getDocumentURI());}});

Zw.features.login.SprintSSOFeature=Ext.extend(Zw.Feature,{monitorGuestState:true,onInit:function(){this.SECURITY_TIMEOUT=this.ONE_HOUR;},publishSecurityMessage:function(){this.context.publish('/desktop/error/show',{title:'Sprint Single Signon',msg:'Due to a security precaution, you cannot login via Zipwhip directly. ',scope:this,onClose:this.onAlertClose,handler:this.bringWindowToFront});},clearSecurityCredential:function(){var cp=window.cookieProvider;cp.clear('timeout');Ext.destroy(cp);cp=null;Zw.inSecurityMode=false;Zw.securityTimeout=null;},getSecurityCredential:function(){Zw.console("Discovering security situation");if(Zw.inSecurityMode){Zw.console("We are in a security lockout. It is over at ",Zw.securityTimeout);var attemptDate=new Date();if((attemptDate>Zw.securityTimeout)){this.clearSecurityCredential();return false;}}
Zw.console("We didn't find any security information, lets look in the cookie");var cp=new Ext.state.CookieProvider({path:"/",expires:new Date(new Date().getTime()+(this.SECURITY_TIMEOUT)),domain:"zipwhip.com"});var value=cp.get('timeout');Zw.securityTimeout=cp.get('securityTimeout');Zw.console("We checked the cookie and found",Zw.securityTimeout);Ext.destroy(cp);cp=null;var result=(Zw.securityTimeout>new Date());Zw.console("We are in securityMode: ",result);return result;},onStart:function(){Zw.Application.Context.on('login',this.onLogin,this);},onLogin:function(){this.showWelcomeScreen();},onAuthenticatedAsGuest:function(){Zw.inSecurityMode=this.getSecurityCredential();if(!Zw.capabilities.ALLOW_GUEST){this.onLogin();}},onAuthenticatedAsUser:function(){if(this.window){if(this.iframe)
this.iframe.destroy();this.window.destroy();delete this.iframe;delete this.window;}},bringWindowToFront:function(sender){sender.toFront();},onAlertClose:function(){this.preventWindow=false;this.onLogin();},showWelcomeScreen:function(){if(!this.window){this.window=this.context.Desktop.registerWindow(new Zw.features.login.SprintWelcomeWindow({closable:false,scope:this,onSignOn:this.onSignOn}));}
this.window.show();this.window.setSecurityMode(Zw.inSecurityMode);},showIFrame:function(){this.iframe=this.context.Desktop.registerWindow(new Zw.features.login.SprintIFrameWindow({}));this.addHandlers();this.iframe.show();},onIntegratedLogin:function(sender,uuid){if(sender==this.context){this.iframe.close();this.removeHandlers();}},onSignOn:function(sender,e){if(e.ctrlKey){this.showIFrame();this.window.close();}else{window.location='https://sso.sprintpcs.com/sso/redirect.do?deeplink=zipwhip';}},removeHandlers:function(){Zw.Application.un('integrated-login',this.onIntegratedLogin,this);},addHandlers:function(){Zw.Application.on('integrated-login',this.onIntegratedLogin,this);},onDestroy:function(){Ext.destroy(this.iframe);delete this.iframe;Ext.destroy(this.window);delete this.window;this.removeHandlers();}});Zw.features.Factory.replace('Zw.features.login.LoginFeature',Zw.features.login.SprintSSOFeature);

Zw.features.login.SprintLoginFeature=Ext.extend(Zw.features.login.LoginFeature,{m_package:'login.sprint',m_loginWindow:'Zw.features.login.SprintLoginWindow',m_extraWindowArgs:{xtype:'Zw.features.login.SprintLoginWindow',closable:Zw.capabilities.ALLOW_GUEST},getWindowArgs:function(){return({xtype:'Zw.features.login.SprintLoginWindow',onToolbarClick:this.login_onToolbarClick,scope:this,onSubmit:this.login_onSubmit.createDelegate(this)});},login_onSubmit:function(args){this.carrierLogin(args);},login_onSuccess:function(sender,args){var jsonResult=Ext.util.JSON.decode(sender.responseText);var serverResponse=jsonResult.response;if(serverResponse){if(this.window)
this.window.close();var cookieProvider=this.getCookieProvider();cookieProvider.set('sessions',[serverResponse.key]);Zw.Application.createContext({account:{session:serverResponse.key,validated:true},active:true});}},carrierLogin:function(args){if(args){var username=args.mobileNumber;var rememberMe=args.remember;Ext.Ajax.request({url:'/sprint/carrier_login',params:{userId:username,password:args.password,rememberMe:rememberMe,portal:Zw.portal},scope:this,success:this.onSuccess,failure:this.onFailure});}},onFailure:function(response){var msg=response||'please try again later.';Ext.Msg.alert('Network Failure',msg);},onSuccess:function(response){var jsonResult=Ext.util.JSON.decode(response.responseText);var serverResponse=jsonResult.response;if(serverResponse){if(jsonResult.success){var cookieProvider=this.getCookieProvider();cookieProvider.set('sessions',serverResponse.key);Zw.Application.createContext({account:{session:serverResponse.key,validated:true},active:true});}
else{var msg="";var ec=serverResponse.errorCode;if(ec){if(ec=='-130'){msg='Invalid username/password.';}
else if(ec=='-131'){msg='No subscriber info found.';}
else if(ec=='-132'){msg='Problem creating account';}
else{msg='Please Check your username and password and try again.';}}
Ext.Msg.alert('Login failed',msg);if(this.window){this.window.clearValue('pw');}
Zw.console("Login Failed. \n Error: ",serverResponse.errorCode," Message: ",serverResponse.message);}}
else{Ext.Msg.alert("Login Failed. No repsonse.");}},getCookieProvider:function(){var cookieProvider=new Ext.state.CookieProvider({path:'/',domain:Zw.cookieDomain||'zipwhip.com'});return cookieProvider;}});if(Ext.isSecure){Zw.features.Factory.replace('Zw.features.login.SprintSSOFeature','Zw.features.login.SprintLoginFeature');}

Zw.app.SprintAdvertsPlugin=Ext.extend(Zw.Plugin,{adverts:[{id:1,text:'Get Pandora on your phone',cls:'generic',style:'background-position: 0 0',url:'http://www.pandora.com/sprint'},{id:2,text:'Ziptip: Ctrl+Enter instead of Send Button',cls:'generic',style:'background-position: 0 -99px'},{id:5,text:'Ziptip: Double click a contact card to text.',cls:'generic',style:'background-position: 0 -396px'},{id:6,text:'Ziptip: Right click a contact card for handy menu.',cls:'generic',style:'background-position: 0 -495px'},{id:3,text:'Guitar Hero while on the bus.',cls:'generic',style:'background-position: 0 -198px',url:'https://manage.sprintpcs.com/Manage/portal/!ut/p/c1/04_SB8K8xLLM9MSSzPy8xBz9CP0os3hPZ3fHQE8TIwMLY29TAyMfLxcDJwNjI09PQ_1wkA6zeAMcwNFA388jPzdVP1I_yhynOY4m-pE5qemJyZX6Bdl55fmOiooAei8iqA!!/dl2/d1/L0lJSklna21DU1EhIS9JRGpBQU15QUJFUkNKRXFnL1lGTkExTkk1MC01Rjg5dyEvN19JQ0dBUUk0MjA4M0s1MDJMSkQwQjAzMklBNC9PMmZfXzU4Ni9zYS5zcGZfQWN0aW9uTGlzdGVuZXI!/?PC_7_ICGAQI42083K502LJD0B032IA4_spf_strutsAction=!2fselectProduct.do!3fproductId%3dPCS622048'},{id:4,text:'You should check out Beyonce Ringtones.',cls:'generic',style:'background-position: 0 -297px',url:'https://manage.sprintpcs.com/Manage/portal/!ut/p/c1/04_SB8K8xLLM9MSSzPy8xBz9CP0os3hPZ3fHQE8TIwMLY29TAyMfLxcDJwNjI09PQ_1wkA6zeAMcwNFA388jPzdVvyA7rxwAdJ9AwA!!/dl2/d1/L0lDU0lKSWdrbUNTUS9JUFJBQUlpQ2dBek15cXpHWUEhIS9ZQkpKMU5BMU5JNTAtNUY4OXchIS83X0lDR0FRSTQyMDgzSzUwMkxKRDBCMDMySUE0LzVFdl9fODQ2L3NhLnNwZl9BY3Rpb25MaXN0ZW5lcg!!/?PC_7_ICGAQI42083K502LJD0B032IA4_spf_strutsAction=!2fsearchCatalog.do!3fsearchString%3dbeyonce!26zone%3dOverview!26searchType%3dartist&Media_Id=Overview_PromoL_Beyonce'},{id:1000,text:'Meet the Palm Pixi.',cls:'generic',style:'background-position: 0 -594px',url:'http://www.palm.com/pixi'}],onInit:function(){this.client.adverts=this.adverts;}});if(Zw.portal=='Sprint'){Zw.features.PluginFactory.register('/desktop/message/advert',function(){return new Zw.app.SprintAdvertsPlugin();});}

Zw.features.app.SprintOmnitureTagsFeature=Ext.extend(Zw.Feature,{onInit:function(){var c=this.context;c.subscribe('/desktop/corkboard/show',this.onCorkboard,this);c.subscribe('/desktop/contacts/show',this.onContacts,this);c.subscribe('/account/message/send',this.onOutgoingMessage,this);c.subscribe('/account/message/receive',this.onIncomingMessage,this);if(Analytics.MetricData)
Analytics.MetricData.zwSessionId=this.getSessionKey();},reportException:function(method,er){try{this.context.publish('/app/error',{name:'Sprint Omniture '+method,data:'',err:er});}catch(err){}},onContacts:function(){try{var key='contactsWindowOpenHandler';if(Analytics.DigLouZW){this.callMethod(Analytics.DigLouZW,key);}}catch(er){this.reportException(key,er);}},onOutgoingMessage:function(){try{var key='sendButtonHandler';if(Analytics.DigLouZW){this.callMethod(Analytics.DigLouZW,key);}}catch(er){this.reportException(key,er);}},onIncomingMessage:function(){try{var key='receivedWindowHandler';if(Analytics.DigLouZW){this.callMethod(Analytics.DigLouZW,key);}}catch(er){this.reportException(key,er);}},onCorkboard:function(){try{var key='corkboardButtonHandler';if(Analytics.DigLouZW){this.callMethod(Analytics.DigLouZW,key);}}catch(er){this.reportException(key,er);}},callMethod:function(scope,method){if(scope){method=scope[method];if(method){method.call(scope,[this.getSessionKey()]);}}},getSessionKey:function(){return this.context.Account.getSessionKey();}});if(Zw.portal=='Sprint'){Zw.features.Factory.register('Zw.features.app.SprintOmnitureTagsFeature');}

Zw.namespace('Zw.features.feedback');Zw.features.feedback.SprintSurveyFeature=Ext.extend(Zw.Feature,{surveyWindow:undefined,onInit:function(){var context=this.context;if(context){context.subscribe('/account/message/sendComplete',this.askForSurvey,this);}},askForSurvey:function(){var context=this.context;if(context){var websiteDeviceId=Zw.data.get(this.context.Account.identity,'websiteDeviceId');Ext.Ajax.request({url:'/SprintSurvey/survey/query',params:{deviceId:websiteDeviceId},success:this.askForSurveyComplete,scope:this});}},askForSurveyComplete:function(response){var result=Ext.util.JSON.decode(response.responseText);if(result.showSurvey){this.showSurveyWindow(result.surveyUrl);}
if(result.stopRequesting){var context=this.context;if(context){context.unsubscribe('/account/message/sendComplete',this.askForSurvey,this);}}},showSurveyWindow:function(baseUrl){var context=this.context;if(context){var surveyWindow=this.buildSurveyWindow(baseUrl);context.subscribe('/desktop/survey/complete',this.onSurveyComplete,this);surveyWindow.show();this.surveyWindow=surveyWindow;}},onSurveyComplete:function(){this.surveyWindow.close();var context=this.context;if(context){var websiteDeviceId=Zw.data.get(this.context.Account.identity,'websiteDeviceId');Ext.Ajax.request({url:'/SprintSurvey/survey/complete',params:{deviceId:websiteDeviceId}});}},buildSurveyWindow:function(baseUrl){var identity=this.context.Account.identity;var extRef=Zw.data.get(identity,'mobileNumber');var userName=(Zw.data.get(identity,'firstName')+' '+Zw.data.get(identity,'lastName')).replace(' ','_');var url=baseUrl;if(baseUrl.indexOf('?')===-1){url+='?';}else{url+='&';}
url+='ext_ref='+extRef+'&user_name='+userName;return new Zw.controls.Window({title:'Sprint Web Texter Survey',renderTo:Ext.getBody(),cls:'zw-window zw-window-sprintSurvey',width:467,height:460,layout:'fit',items:{xtype:'iframepanel',defaultSrc:url,border:false}});},onDestroy:function(){var context=this.context;if(context){context.unsubscribe('/account/message/sendComplete',this.askForSurvey,this);}}});Zw.features.Factory.register('Zw.features.feedback.SprintSurveyFeature');

Zw.util.PaginationPlugin=Ext.extend(Zw.Plugin,{page:0,pageSize:50,totalContacts:null,onInit:function(){this.client.store.filterDataBy=this.filterDataBy.createDelegate(this);this.client.store.syncData();if(this.client.paginationSettings&&this.client.paginationSettings.buttons){this.client.on('beforerender',this.onRender,this);this.client.store.on('datachanged',this.onDatachanged,this);}},onDatachanged:function(){if(this.client.filter&&this.client.filter!=""){this.totalContacts=this.client.store.getCount();}
else{var client=this.client;if(client){var store=client.store;if(store&&store._store&&store._store.data&&store._store.data.length){this.totalContacts=store._store.data.length;}
else if(store.getCount){this.totalContacts=store.getCount();}}}
this.updatePagination();},getMaxPages:function(){return Math.floor(this.totalContacts/this.pageSize);},filterDataBy:function(data,fn,scope){var count=1;var pageSize=this.pageSize;var r=new Ext.util.MixedCollection();r.getKey=data.getKey;var k=data.keys,it=data.items;for(var i=this.page*pageSize,len=it.length;i<len;i++){if(fn.call(scope||this,it[i],k[i])){r.add(k[i],it[i]);count++;Zw.console("We got a filterDataBy match! It's match number ",count," of ",pageSize,"it passed our fn test ",fn);}
if(count>pageSize){Zw.console("Because ",count," is larger than ",pageSize," we are stopping.");break;}}
return r;},setPage:function(page){var maxPages=this.getMaxPages();if(page<0)page=0;if(page>maxPages)page=maxPages;this.page=page;this.updateUI();},getPaginationPosition:function(){return'Now viewing '+(this.page+1)+' of '+(this.getMaxPages()+1);},updatePagination:function(){this.div.field('label').el.update(this.getPaginationPosition());},refilterDateView:function(){if(this.client.filter&&this.client.filter!=""){var dataView=this.client;dataView.store.filterBy(Zw.controls.ContactCard.generateHighlighterFilterFn(dataView.highlighterStrategyLookup,null,dataView.filter));this.totalContacts=dataView.store.getCount();}else{Zw.console('No Filter found.');}},updateUI:function(){Zw.console("Update UI",this);this.client.store.syncData();this.refilterDateView();this.updatePagination();Zw.console("this.getMaxPages()",this.getMaxPages())
Zw.console("this.getPaginationPosition()",this.getPaginationPosition())
this.client.refresh();},onRender:function(){var el=this.client.ownerCt.insert(0,this.div=new Zw.controls.Div({plugins:[new Zw.util.FieldinatorPlugin()],cls:'paginationContainer',items:[{xtype:'Zw.controls.ActionButton',text:'Back',cls:'paginationBackButton zw-wizard-nav next zw-action-button',scope:this,handler:function(){this.setPage(this.page-=1);}},{xtype:'Zw.controls.ActionButton',text:'Next',cls:'paginationNextButton zw-wizard-nav next zw-action-button',scope:this,handler:function(){this.setPage(this.page+=1);}},{xtype:'label',code:'label',cls:'paginationLabel',html:this.getPaginationPosition()}]}));var el=this.client.ownerCt.el;Ext.DomHelper.append(el,{html:'',tag:'html'});}});

Zw.namespace("Zw.features.registration");Zw.features.registration.SprintTemporaryRegistrationFeature=Ext.extend(Zw.features.registration.RegistrationFeature,{packages:['wizard.all','registration.all','registration.sprint'],createWizardController:function(){return new Zw.features.registration.ZipwhipRegistrationWizardControllerPlugin({plugins:['Zw.features.registration.EnterMobilePlugin','Zw.features.registration.SprintCarrierLookupPlugin','Zw.features.registration.SendVerificationCodePlugin','Zw.features.registration.EnterVerificationCodePlugin','Zw.features.registration.PersonalDetailsPlugin','Zw.features.registration.PickPhonePlugin','Zw.features.registration.GuessPhonePlugin','Zw.features.registration.MissingPhonePlugin','Zw.features.registration.GoodbyeForNowPlugin','Zw.features.registration.SprintTemporaryTermsOfServicePlugin','Zw.features.registration.CompletePlugin'],context:this.context,modal:!Zw.capabilities.ALLOW_GUEST});}});Zw.features.Factory.replace('Zw.features.registration.RegistrationFeature',Zw.features.registration.SprintTemporaryRegistrationFeature);
