DataObjects/ProjectDirectory.php
[Pman.Core] / Pman.js
1 //<script type="text/javascript">
2
3 /**
4  * 
5  * >>> Pman.layout.getRegion('center').tabs.stripWrap
6  * ==> tab.???
7  * var tbh = Pman.layout.getRegion('center').tabs.stripWrap.child('div').createChild(
8  * 
9  * {tag: 'div', style: 'display:block;position:absolute;top:2;left:300;width:100%;height:25px'});
10  * 
11  * 
12  *  CHANGES
13  *  - gtranslate moved to Pman.GoogleTranslate
14  * 
15  * 
16  */
17  
18 if (typeof(_T) == 'undefined') { _T={};}
19  
20
21
22   
23
24 Pman = new Roo.Document(
25 {
26    /// appVersion: '1.7', // fixme = needs to be removed - use Global AppVersion
27     subMenuItems : [],
28     topMenuItems : [],
29     rightNames: { }, /// register right names here - so they can be translated and rendered.
30     buildCompleted : false, // flag to say if we are building interface..
31     events : {
32         'beforeload' : true, // fired after page ready, before module building.
33         'load' : true, // fired after module building
34         'authrefreshed' : true // fire on auth updated?? - should be on Login?!?!?
35     },
36     
37     listeners : {
38         'ready' : function()
39         {
40             // kludge to fix firebug debugger
41             if (typeof(console) == 'undefined') {
42                 console = { log : function() {  } };
43             }
44             
45             // remove loader..
46             if (Roo.get('loading')) {
47                 Roo.get('loading').remove();
48             }
49             
50             Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
51             
52             // link errors...
53             
54             if (AppLinkError.length) {
55                 Roo.MessageBox.alert("Error", AppLinkError, function() {
56                     Pman.Login.onLoad();
57                 });
58                 return;
59             }
60             
61             
62             // reset password!!!!
63             if (showNewPass.length) {
64                 Pman.PasswordChange.show(  { passwordReset : showNewPass },
65                     function(data) {
66                         // fail and success we do  a load...
67                         Pman.Login.onLoad();
68                     }
69                 );
70                 return;
71             }
72              
73             Pman.Login.onLoad();
74             
75         },
76         'load' : function()
77         {
78             if (Roo.get('loading-logo-tile')) {
79                 Roo.get('loading-logo-tile').remove();
80             }
81             if (Roo.get('loading-logo-tile-top')) {
82                 Roo.get('loading-logo-tile-top').remove();
83             }
84             if (Roo.get('loading-logo-bottom')) {
85                 Roo.get('loading-logo-bottom').remove();
86             }
87             if (Roo.get('loading-logo-center')) {
88                 Roo.get('loading-logo-center').remove();
89             }
90         }   
91         
92     },
93    
94
95     
96     layout: false,
97     
98     onload: function() {
99         //this.fireEvent('beforeload',this);
100         
101         
102         
103         if (this.layout) {
104             return; // already loaded
105         } 
106         if (Roo.get('loading')) {
107             Roo.get('loading').remove();
108         }
109         if (Roo.get('loading-mask')) {
110             Roo.get('loading-mask').show();
111         }
112         
113         
114        
115         
116         /*
117         Roo.MessageBox.show({
118            title: "Please wait...",
119            msg: "Building Interface...",
120            width:340,
121            progress:true,
122            closable:false
123           
124         });
125         */
126         //Pman.onLoadBuild();
127         //Roo.get(document.body).mask("Building Interface");
128         //Pman.onLoadBuild.defer(100, Pman);
129        //Pman.onLoadBuild();
130                     
131    // },
132     //onLoadBuild : function() {
133         
134         var _this = this;
135         this.stime = new Date();
136         this.layout = new Roo.BorderLayout(document.body, {
137             north: {
138                 split:false,
139                 initialSize: 25,
140                 titlebar: false
141             },
142          
143              
144             center: {
145                 titlebar: false,
146                 autoScroll:false,
147                 closeOnTab: true,
148                 tabPosition: 'top',
149                 //resizeTabs: true,
150                 alwaysShowTabs: true,
151                 minTabWidth: 140
152             } ,
153             south: {
154                 collapsible : true,
155                 collapsed : true,
156                 split:false,
157                 height: 120,
158                 titlebar: false
159             }
160             
161         });
162         
163         this.fireEvent('beforeload',this);
164         
165         
166         
167         this.layout.beginUpdate();
168         this.layout.add('north', new Roo.ContentPanel('title', 'North'));
169         var au = Pman.Login.authUser;
170         if (au.id > 0 && au.company_id_background_color && au.company_id_background_color.length) {
171             Roo.get('title').dom.style.backgroundColor = '#' + au.company_id_background_color;
172             Roo.get('headerInformation').dom.style.color = this.invertColor('#' + au.company_id_background_color);
173         }
174         if (au.id > 0 && au.company_id_logo_id * 1 > 0) {
175             Roo.get('headerInformation-company-logo').dom.src =  baseURL + 
176                 '/Images/' + au.company_id_logo_id + '/' + au.company_id_logo_id_filename;
177         } else {
178             Roo.get('headerInformation-company-logo').dom.src = Roo.BLANK_IMAGE_URL;
179         }
180         
181         Roo.get('headerInformation').dom.innerHTML = String.format(
182                 "You are Logged in as <b>{0} ({1})</b>", // to {4} v{3}", // for <b>{2}</b>",
183                 au.name, au.email, au.company_id_name, 
184                 AppVersion , appNameShort
185         );
186         
187         
188         document.title = appName + ' v' + AppVersion + ' - ' + au.company_id_name;
189         Roo.QuickTips.init(); 
190         if (Roo.isGecko) {
191            Roo.useShims = true;
192         }
193        
194         //this.mainLayout.beginUpdate();
195         //var maskDom = Roo.get(document.body)._maskMsg.dom
196         this.layout.beginUpdate();
197         
198         Pman.building = true;
199         
200         this.buildModules(this, 
201             function() {
202                 
203                 _this.layout.getRegion('center').showPanel(0);
204                 _this.layout.endUpdate(); 
205                 _this.addTopToolbar();  
206                 _this.finalize();
207                 _this.fireEvent('load',this);
208             }
209         );
210         
211         
212      
213     },
214     
215     addTopToolbar : function()
216     {
217           //console.log( "t6:" + ((new Date())-stime));
218         //this.mainLayout.endUpdate();
219         // make a new tab to hold administration stuff...
220         
221        
222         //console.log( "t7:" + ((new Date())-stime));
223         var se = Pman.layout.getRegion('center').tabs.stripEl;
224         var tbh = se.createChild( 
225                 { tag: 'td', style: 'width:100%;'  });
226         
227         var lotb = new Roo.Toolbar(tbh);
228         
229         if (Roo.isSafari) {
230             var tbl = se.child('table', true);
231             tbl.setAttribute('width', '100%');
232         }
233         lotb.add(
234             new Roo.Toolbar.Fill(), 
235      
236             {
237                 text: "Change Password",
238                 cls: 'x-btn-text-icon',
239                 icon: rootURL + '/Pman/templates/images/change-password.gif',
240                 handler : function(){
241                     Pman.PasswordChange.show({});
242                 }
243             }, '-'
244         );
245          
246         
247         if (this.topMenuItems.length) {
248             
249             Roo.each(this.topMenuItems, function (mi) {
250                 lotb.add(mi);
251             });
252             lotb.add('-');
253         }
254         
255         
256         
257         if (this.subMenuItems.length) {
258             
259             this.subMenuItems.sort(function (a,b) {
260                 return a.seqid > b.seqid ? 1 : -1;
261             });
262             // chop off last seperator.
263             // since we always add it.. just chop of last item
264             this.subMenuItems.pop(); 
265             
266             lotb.add(
267                 {
268                      
269                     text: "Add New Item",
270                     cls: 'x-btn-text-icon',
271                     icon: Roo.rootURL + 'images/default/dd/drop-add.gif',
272                     menu : {
273                         items : this.subMenuItems
274                     }     
275                 } ,'-'
276             );
277         }
278        
279         lotb.add(
280             {
281                 text: "Logout",
282                 cls: 'x-btn-text-icon',
283                 icon: rootURL + '/Pman/templates/images/logout.gif',
284                 handler: function() {
285                     Pman.Login.logout();
286                 }
287                  
288             }
289         );
290       
291        // this.layout.endUpdate();
292     },
293     
294     
295     finalize : function() {
296         
297       
298        
299         window.onbeforeunload = function(e) { 
300             var e = e || window.event;
301             var r = "Closing this window will loose changes, are you sure you want to do that?";
302
303             // For IE and Firefox
304             if (e) {
305                 e.returnValue = r;
306             }
307
308             // For Safari
309             return r;
310             
311         };
312         
313         Roo.MessageBox.hide();
314         if (Roo.get('loading-mask')) {
315            Roo.get('loading-mask').remove();
316         }
317         
318         
319         this.buildCompleted = true; // now we can force refreshes on everything..
320         
321         
322         // does the URL indicate we want to see a system..
323         if (AppTrackOnLoad * 1 > 0) {
324             this.onLoadTrack(AppTrackOnLoad,false);
325         }
326         
327         // Open system..
328         
329         var forceAdmin = function(data)
330         {
331             if (!data || !data.id) {
332                 //Roo.log("Force Admin");
333                 Pman.Dialog.PersonStaff.show( 
334                     { 
335                         id : 0, 
336                         company_id : Pman.Login.authUser.company_id_id * 1, 
337                         company_id_name : Pman.Login.authUser.company_id_name
338                     }, function(data) {
339                         forceAdmin(data);
340                     }
341                 );
342                 return;
343             }
344             Roo.state.Manager.set('Pman.Login.username', data.email),
345             window.onbeforeunload = false;
346             document.location = baseURL + '?ts=' + Math.random();
347         }
348         
349         var forceCompany = function(data) {
350             if (Pman.Login.authUser.company_id * 1 > 0) {
351                 forceAdmin();
352                 return;
353             }
354             if (!data || !data.id) {
355                 Pman.Dialog.Companies.show( { id : 0, isOwner : 1, comptype: 'OWNER' }, function(data) {
356                     forceCompany(data);
357                 });
358                 return;
359             }
360             Pman.Login.authUser.company_id_id  = data.id;
361             Pman.Login.authUser.company_id  = data.id;
362             Pman.Login.authUser.company_id_name  = data.name;
363             forceAdmin();
364         }
365         
366         if (Pman.Login.authUser.id < 0) {
367             // admin company has been created - create the user..
368             if (Pman.Login.authUser.company_id_id* 1 > 0) {
369                 forceAdmin();
370                 return;
371             }
372             
373             forceCompany();
374             /// create account..
375             
376             
377         }
378         
379
380     },
381     
382     
383     
384     
385      
386     onLoadTrack : function(id,cb) {
387         this.onLoadTrackCall(id, cb, 'DocumentsCirc_');
388     },
389     onLoadTrackEdit : function(id,cb) {
390         this.onLoadTrackCall(id, cb, 'Documents_');
391     },
392     
393     
394     /// ----------- FIXME -----
395     
396     
397     onLoadTrackCall : function(id,cb, cls) {
398         Roo.get(document.body).mask("Loading Document details");
399
400         Pman.request({
401             url: baseURL + '/Roo/Documents.html',  
402             params: {
403                 _id: id
404             },  
405             method: 'GET',  
406             success : function(data) {
407                 Roo.get(document.body).unmask();
408              
409                 
410                 switch(data.in_out) {
411                     case 'IN' : cls+='In';break;
412                     case 'OUT' : cls+='Out';break;
413                     case 'WIP' : cls+='Wip';break;
414                     default: 
415                         Roo.MessageBox.alert("Error", "invalid in_out");
416                         return;
417                 }
418                 Pman.Dialog[cls].show(data, cb ? cb : Pman.refreshActivePanel);
419             }, 
420             
421             failure: function() {
422                 Roo.get(document.body).unmask();
423                 //if (cb) {
424                 //    cb.call(false);
425                 //}
426                  
427            }
428         });
429           
430     },
431     
432     /**
433      * eg. has Pman.hasPerm('Admin.Admin_Tab', 'S') == showlist..
434      * 
435      */
436     hasPerm: function(name, lvl) {
437         if (typeof(Pman.Login.authUser) != 'object') {
438             return false;
439         }
440         if (typeof(Pman.Login.authUser.perms[name]) != 'string') {
441             return false;
442         }
443         return Pman.Login.authUser.perms[name].indexOf(lvl) > -1;
444         
445     },
446     
447     
448     
449     
450     
451     
452     
453     
454     Readers : {},
455     ColModels : {},
456     Forms : {},
457     Tab : {},
458     Dialog : {},
459     
460     processResponse : function (response)
461     {
462         var res = '';
463         try {
464             res = Roo.decode(response.responseText);
465             // oops...
466             if (typeof(res) != 'object') {
467                 res = { success : false, errorMsg : res, errors : true };
468             }
469             if (typeof(res.success) == 'undefined') {
470                 res.success = false;
471             }
472             
473         } catch(e) {
474             res = { success : false,  errorMsg : response.responseText, errors : true };
475         }
476         return res;
477     },
478     genericDelete : function(tab,tbl) {
479         
480         var r = [];
481         
482             
483         var s = tab.grid.getSelectionModel().getSelections();
484         if (!s.length)  {
485             Roo.MessageBox.alert("Error", "Select at least one Row to delete" );
486             return '';
487         }
488         
489         for(var i = 0; i < s.length; i++) {
490             r.push(s[i].data.id);
491         }
492     
493         Roo.MessageBox.confirm("Confirm", "Are you sure you want to delete that?",
494             function(btn) {
495                 if (btn != 'yes') {
496                     return;
497                 }
498                 // what about the toolbar??
499                 tab.grid.getView().mainWrap.mask("Deleting");
500                 Pman.request({
501                     url: baseURL + '/Roo/'+tbl+'.php',
502                     method: 'GET',
503                     params: {
504                         _delete : r.join(',')
505                     },
506                     success: function(response) {
507                         tab.grid.getView().mainWrap.unmask();
508                         if ( tab.paging ) {
509                             tab.paging.onClick('refresh');   
510                         } else if (tab.refresh) {
511                             tab.refresh();
512                         } else if (tab.grid.footer && tab.grid.footer.onClick) {
513                             // new xtype built grids
514                             tab.grid.footer.onClick('refresh');   
515                         } else {
516                             tab.grid.getDataSource().load();
517                         }
518                         
519                         
520                         
521                     },
522                     failure: function(act) {
523                         tab.grid.getView().mainWrap.unmask();
524                         Roo.MessageBox.alert("Error", "Error Deleting");
525                     }
526                     
527                 });
528             }
529         );
530     },
531     refreshActivePanel : function() {
532         var actpan = this.layout.getRegion('center').getActivePanel();
533         if (actpan.controller && actpan.controller.paging) {
534             actpan.controller.paging.onClick('refresh');
535             return;
536         }
537         
538         var agid = Pman.layout.getRegion('center').getActivePanel().id;
539         if (!agid) {
540             return;
541         }
542         Pman.Tab[agid].paging.onClick('refresh');
543     },
544     toCidV : function(data) {
545         return 'C' + data.in_out.substring(0,1) + data.cid;
546     },
547     
548     standardActionFailed :  function(f, act, cb) {
549     
550         if (act.failureType == 'client') {
551             Roo.MessageBox.alert("Error", "Please Correct all the errors in red", cb);
552             return;
553         }
554         if (act.failureType == 'connect') {
555             Roo.MessageBox.alert("Error", "Problem Connecting to Server - please try again.", cb);
556             return;
557         }
558         
559         if (act.type == 'submit') {
560             
561             Roo.MessageBox.alert("Error", typeof(act.result.errorMsg) == 'string' ?
562                 String.format('{0}', act.result.errorMsg) : 
563                 "Saving failed = fix errors and try again", cb);
564             return;
565         }
566         
567         // what about load failing..
568         Roo.MessageBox.alert("Error", "Error loading details",cb); 
569     },
570     /**
571      * 
572      * similar to Roo.Ajax, but handles our responses better...
573      * c.url
574      * c.method
575      * c.params
576      * c.failure() == failure function..
577      * c.success(data) == success function..
578      * 
579      * 
580      */
581     request : function(c) {
582         var r= new Roo.data.Connection({
583             timeout : typeof(c.timeout) == 'undefined' ?  30000 : c.timeout
584         });
585         r.request({
586             url: c.url,
587             method : c.method,
588             params: c.params,
589             xmlData : c.xmlData,
590             success:  function(response, opts)  {  // check successfull...
591                
592                 var res = Pman.processResponse(response);
593                 
594                 if (!res.success) { // error!
595                     if (c.failure) {
596                         if (true === c.failure.call(this,response, opts)) {
597                             return;
598                         }
599                     }
600                     Roo.MessageBox.hide();
601                     Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg : "Error Sending");
602                     return;
603                 }
604                 
605                 c.success.call(this, res.data);
606                 
607                 return; 
608             },
609             failure :  function(response, opts)  {  // check successfull...
610                 
611                 if (c.failure) {
612                     if (true === c.failure.call(this,response, opts)) {
613                         return;
614                     }
615                 }
616                 Roo.MessageBox.hide();
617                 Roo.MessageBox.alert("Error", "Connection timed out sending");
618                 Roo.log(response);
619                 
620             },
621             scope: this
622             
623         });
624     },
625     
626     
627     // depreciated - use Pman.Download()
628     
629     download : function(c) {
630         
631         return new Pman.Download(c);
632     },
633     
634     // fixme - move to document manager...
635     downloadRevision : function(doc, rev)
636     {
637         this.download({
638             url: baseURL + '/Documents/Doc/DownloadRev/'+ doc.id + '/' + rev + '/' +
639                 doc.project_id_code + '-' + doc.cidV + '-' + rev  + '-' +  doc.filename
640         }); 
641                     
642     },
643     
644     
645     exportCSV : function(c) {
646         
647         for(var i=0;i < c.csvFormat.length;i++) {
648             c.params['csvCols['+i+']'] = c.csvFormat[i][0];
649             c.params['csvTitles['+i+']'] = c.csvFormat[i][1];
650         }
651         c.url +=  '?' + Roo.urlEncode(c.params);
652         this.download(c);
653
654     },
655     
656     
657     prettyDate : function (value) 
658     {
659         if (typeof(value) == 'string') {
660             var ds = Date.parseDate(value, 'Y-m-d H:i:s');
661             if (ds) {
662                 return this.prettyDate(ds);
663             }
664             ds = Date.parseDate(value, 'Y-m-d');
665             if (ds) {
666                 return this.prettyDate(ds);
667             }
668             return '';
669         }
670 // last 7 days...
671         if (!value) {
672             return '';
673         }
674         var td = new Date();
675         var daysSince = Math.floor(td.getElapsed(value) / (1000 * 60*60*24));
676         if (daysSince < 7) {
677             return value.dateFormat('D H:i');
678         }
679         
680         // same month
681         if (td.dateFormat('m') == value.dateFormat('m')) {
682             return value.dateFormat('dS D');
683         }
684         // same year?
685         if (td.dateFormat('Y') == value.dateFormat('Y')) {
686             return value.dateFormat('dS M');
687         }
688         return value.dateFormat('d M Y');
689     },
690     loadException : function(a,b,c,d)
691     {
692         if (d && d.authFailure) {
693             Pman.Login.show();
694             return;
695         }
696         Roo.MessageBox.alert("Problem Loading Data", a.message || c.statusText);
697     },
698     
699     
700     /**
701      * 
702      * Routine to flash alerts in the title bar..
703      * 
704      * 
705      */
706     
707     notifyActive : false,
708     
709     notifyTitle: function(msg)
710     {
711         if (this.notifyActive ) {
712             return;
713         }
714         var stop = false;
715         
716         var stopper = function() {
717             stop = true;
718              document.title = oldtitle;
719         };
720         
721         Roo.get(document.body).on('mousemove', stopper, this);
722         var oldtitle = document.title;
723         var s = 1;
724         var _this = this;
725         var ivl = window.setInterval(function() {
726             
727             if (stop) {
728                 Roo.get(document.body).un('mousemove', stopper, this);
729                 _this.notifyActive = false;
730                 document.title = oldtitle;
731                 window.clearInterval(ivl);
732                 return true;
733             }
734             s = !s;
735             document.title = s ? msg : oldtitle;
736                   
737         }, 1000); // every 120 secs = 2mins..
738          document.title =   msg;
739         
740         
741         
742     },
743     
744     modules : false,
745     /**
746      * example:
747      * 
748      * Pman.register({
749           modKey : '00-admin-xxxx',
750           module : Pman.Tab.projectMgr,
751           region : 'center',
752           parent : Pman.layout
753         })
754      * 
755      */
756     register : function(obj) {
757         if (!obj.parent) {
758             if (obj.parent === false) {
759                 //console.log('skip module (no parent)' + obj.modkey);
760                 return;
761             }
762             
763             console.log(obj);
764         }
765         if (!obj.parent.modules) {
766             obj.parent.modules = new Roo.util.MixedCollection(false, function(o) { return o.modKey });
767         }
768         
769         obj.parent.modules.add(obj);
770         
771     },
772     
773     buildModules : function(parent, onComplete) 
774     {
775         
776         var _this = this;
777         var cmp = function(a,b) {   
778             return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
779             
780         };
781         if (!parent.modules) {
782             return;
783         }
784         parent.modules.keySort('ASC',  cmp );
785         var mods = [];
786         
787         
788         // add modules to their parents..
789         var addMod = function(m) {
790            // console.log(m.modKey);
791             
792             mods.push(m);
793             if (m.module.modules) {
794                 m.module.modules.keySort('ASC',  cmp );
795                 m.module.modules.each(addMod);
796             }
797             if (m.finalize) {
798                 m.finalize.name = m.name + " (clean up) ";
799                 mods.push(m.finalize);
800             }
801             
802         }
803  
804         parent.modules.each(addMod);
805         //this.allmods = mods;
806         //console.log(mods);
807         //return;
808         if (!mods.length) {
809             if (onComplete) onComplete();
810             return;
811         }
812         // flash it up as modal - so we store the mask!?
813         Roo.MessageBox.show({ title: 'loading' });
814         Roo.MessageBox.show({
815            title: "Please wait...",
816            msg: "Building Interface...",
817            width:450,
818            progress:true,
819            closable:false,
820            modal: false
821           
822         });
823         var n = 0;
824         var progressRun = function() {
825             
826             var mod = mods[n];
827             
828             
829             Roo.MessageBox.updateProgress(
830                 (n+1)/mods.length,  "Building Interface " + (n+1) + 
831                     " of " + mods.length + 
832                     (mod.name ? (' - ' + mod.name) : '')
833                     );
834             
835             
836             
837             if (typeof(mod) == 'function') {
838                 mod();
839                 
840             } else  if (mod.parent.layout && !mod.module.disabled) {
841                 // honour permname setings..
842                 if (mod.permname && mod.permname.length) {
843                     if (Pman.hasPerm(mod.permname, 'S')) {
844                         mod.module.add(mod.parent.layout, mod.region);    
845                     }
846                 } else {
847                     mod.module.add(mod.parent.layout, mod.region);    
848                 }
849                     
850                  
851             }
852             
853             
854             n++;
855             if (n >= mods.length) {
856                 onComplete();  
857                 return;
858             }
859                 
860             
861             progressRun.defer(10, Pman);    
862         }
863         progressRun.defer(1, Pman);
864      
865         
866         
867     },
868     
869     invertColor : function(c)
870     {
871         // read..
872         var ca = [];
873         for(var i = 0; i < 3; i++){
874             ca[i] = parseInt(c.charAt((i*2)+1) + c.charAt((i*2)+2), 16);
875         }
876             
877         // invert..
878         var col = '';
879         Roo.each(ca, function(hi) {
880             var h = parseInt(255-hi).toString(16);
881             if(h < 16){
882                 h = '0' + h;
883             }
884             col += h;
885         });
886         return '#' + col;
887         
888     }
889     
890     
891     
892     
893     
894     
895     
896 });
897