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