Removed duplicate variables and added infinite scroll to all content types
[ajatus.git] / js / ajatus.document.js
blob14b4e1479e613113036e1ead163121aa27f58a7e
1 /*
2  * This file is part of
3  *
4  * Ajatus - Distributed CRM
5  * @requires jQuery v1.2.1
6  * 
7  * Copyright (c) 2007 Jerry Jalava <jerry.jalava@gmail.com>
8  * Copyright (c) 2007 Nemein Oy <http://nemein.com>
9  * Website: http://ajatus.info
10  * Licensed under the GPL license
11  * http://www.gnu.org/licenses/gpl.html
12  * 
13  */
15 (function($){
17     $.ajatus.document = function(doc, check_metadata, check_schema) {
18         if (typeof check_metadata == 'undefined') {
19             var check_metadata = true;
20         }
21         if (typeof check_schema == 'undefined') {
22             var check_schema = false;
23         }
24         
25         // console.log("Check schema: "+check_schema);
26         // console.log("Check metadata: "+check_metadata);
27                 
28         var self = this;
29         this.ready_doc = {};
30         
31         $.each(doc, function(i,n){
32             if (   (i == '_id' && n != '')
33                 || i == 'id' && n != '') {
34                 self.ready_doc['_id'] = n;
35             } else if (i == '_rev' && n != '') {
36                 self.ready_doc[i] = n;
37             } else if (i == 'key' && n != '') {
38                 self.ready_doc[i] = n;
39             } else if (i == 'value' && n != '') {
40                 self.ready_doc[i] = n;
41             }
42         });
43         
44         if (typeof this.ready_doc['value'] == 'undefined') {
45             $.ajatus.debug("Error: Document didn't have value field defined!", "ajatus.document");            
46             return this.ready_doc;
47         }
48         
49         if (check_metadata) {
50             if (! this.ready_doc.value.metadata) {
51                 this.add_metadata();
52             } else {
53                 this.check_metadata();
54             }
55         }
57         if (! $.ajatus.preferences.client.content_types[this.ready_doc.value._type]) {
58             this.ready_doc.value._type = 'note';
59         }
61         if (check_schema) {
62             this.check_schema();
63         }
64         
65         this.prepare_doc_title();
66         
67         return this.ready_doc;
68     }
69     $.extend($.ajatus.document.prototype, {
70         check_schema: function() {
71             var self = this;
72             var type = $.ajatus.preferences.client.content_types[this.ready_doc.value._type];
73             var changed = false;
74             var new_schema_parts = {};
76             $.each(type.original_schema, function(k,si){
77                 // console.log("self.ready_doc.value.metadata["+k+"]:"+self.ready_doc.value.metadata[k])
78                 if (typeof(self.ready_doc.value[k]) == 'undefined') {
79                     def_val = '';
80                     if (typeof si['def_val'] != 'undefined') {
81                         def_val = si['def_val'];
82                     }
83                     new_schema_parts[k] = {
84                         val: def_val,
85                         widget: si.widget
86                     };
87                     changed = true;
88                 } else {
89                     def_val = self.ready_doc.value[k].val || '';
90                     if (typeof si['def_val'] != 'undefined') {
91                         def_val = si['def_val'];
92                     }                    
93                     self.ready_doc.value[k] = $.extend({
94                         val: def_val,
95                         widget: si.widget                        
96                     }, self.ready_doc.value[k]);
97                 }
98             });
99             
100             if (changed) {
101                 // console.log("Found schema parts that need to be updated:");
102                 // console.log(new_schema_parts);
103                 self._fix_doc_schema(new_schema_parts);
104             }            
105         },
106         _fix_doc_schema: function(new_parts) {
107             // console.log("FIX SCHEMA:");
108             // console.log(new_parts);
109             var _self = this;
111             doc = _self.ready_doc;//new $.ajatus.document.loader(_self.ready_doc._id, _self.ready_doc._rev, false, false);
112             doc.value = $.extend(doc.value, new_parts);
113             
114             var db_path = $.ajatus.preferences.client.content_database;
115             
116             $.jqCouch.connection('doc').save(db_path, doc);
117             _self.ready_doc = doc;//new $.ajatus.document(doc);
118         },
119         add_metadata: function() {
120             var self = this;
121             this.ready_doc.value.metadata = {};
122             $.each($.ajatus.document.metadata, function(k,m){
123                 self.ready_doc.value.metadata[k] = {
124                     val: '',
125                     widget: m.widget
126                 };
127             });
128         },
129         check_metadata: function() {
130             // console.log("check metadata");
131             var self = this;
132             var changed = false;
133             var new_md_parts = {};
134             $.each($.ajatus.document.metadata, function(k,m){
135                 // console.log("self.ready_doc.value.metadata["+k+"]:"+self.ready_doc.value.metadata[k])
136                 if (typeof(self.ready_doc.value.metadata[k]) == 'undefined') {
137                     def_val = '';
138                     if (typeof m['def_val'] != 'undefined') {
139                         def_val = m['def_val'];
140                     }
141                     new_md_parts[k] = {
142                         val: def_val,
143                         widget: m.widget
144                     };
145                     changed = true;
146                 } else {
147                     def_val = self.ready_doc.value.metadata[k].val || '';
148                     if (typeof m['def_val'] != 'undefined') {
149                         def_val = m['def_val'];
150                     }                    
151                     self.ready_doc.value.metadata[k] = $.extend({
152                         val: def_val,
153                         widget: m.widget                        
154                     }, self.ready_doc.value.metadata[k]);
155                 }
156             });
157             
158             if (changed) {
159                 self._fix_metadata(new_md_parts);
160             }
161         },
162         _fix_metadata: function(new_metadata) {
163             var _self = this;
164             
165             // console.log("_fix_metadata for: "+_self.ready_doc._id);
166             // console.log(new_metadata);
167             
168             doc = new $.ajatus.document.loader(_self.ready_doc._id, _self.ready_doc._rev, false);
170             // console.log("Before:");
171             // console.log(doc.value.metadata);
172             
173             doc.value.metadata = $.extend({}, doc.value.metadata, new_metadata);
174             
175             // console.log("After:");
176             // console.log(doc.value.metadata);
177             
178             var db_path = $.ajatus.preferences.client.content_database;
179             
180             $.jqCouch.connection('doc').save(db_path, doc);
181             _self.ready_doc = new $.ajatus.document(doc);
182         },
183         prepare_doc_title: function() {
184             var self = this;
186             if (   $.ajatus.preferences.client.content_types[this.ready_doc.value._type]['title_item'] )
187                 // && (   typeof(this.ready_doc.value['title']) == 'undefined'
188                 //     || this.ready_doc.value['title'].val != '') )
189             {
190                 $.ajatus.preferences.client.content_types[this.ready_doc.value._type].schema['title'] = {
191                     label: 'Title',
192                     widget: {
193                         name: 'text',
194                         config: {}
195                     },
196                     hidden: true
197                 };
199                 var title_val = '';
200                 $.each($.ajatus.preferences.client.content_types[this.ready_doc.value._type]['title_item'], function(i,part){
201                     if (self.ready_doc.value[part]) {
202                         var widget = new $.ajatus.widget(self.ready_doc.value[part].widget.name, self.ready_doc.value[part].widget.config);
203                         var val = widget.value_on_view(self.ready_doc.value[part].val, 'plain');
204                         if (typeof val != 'string') {
205                             val = self.ready_doc.value[part].val;
206                         }
207                         title_val += val;
208                     } else {
209                         title_val += $.ajatus.i10n.get(part);
210                     }
211                 });
213                 this.ready_doc.value['title'] = {
214                     val: title_val,
215                     widget: $.ajatus.preferences.client.content_types[this.ready_doc.value._type].schema['title'].widget
216                 };
217             }
218         }
219     });
220     $.ajatus.document.loader = function(id, rev, check_metadata) {
221         if (typeof check_metadata == 'undefined') {
222             var check_metadata = true;            
223         }
224         
225         var args = {};
226         if (   typeof rev != 'undefined'
227             && rev != '')
228         {
229             args['rev'] = rev;
230         }
231         
232         return new $.ajatus.document(
233             $.jqCouch.connection('doc').get($.ajatus.preferences.client.content_database + '/' + id, args),
234             check_metadata,
235             true
236         );
237     };
238     $.ajatus.document.revisions = {
239         get: function(doc) {
240             // console.log("get_revisions for "+doc._id);
241             if (typeof doc._revs_info == 'undefined') {
242                 doc = $.jqCouch.connection('doc').get($.ajatus.preferences.client.content_database + '/' + doc._id, {
243                     _rev: doc._rev,
244                     revs_info: true
245                 });
246             }
248             var available_revs = [];
249             var active_rev_status = false;
250             $.each(doc._revs_info, function(i,n){
251                 if (n.rev == doc._rev) {
252                     active_rev_status = n.status;
253                 } else {
254                     if (n.status == 'disk') {
255                         available_revs.push(n);
256                     }
257                 }
258             });
260             var revs_data = {};
261             revs_data['active'] = {
262                 rev: doc._rev,
263                 status: active_rev_status
264             };
265             revs_data['available'] = available_revs;
266             revs_data['all'] = doc._revs_info;
268             // console.log("Revs data:");
269             // console.log(revs_data);
271             return revs_data;            
272         },
273         navigate_to: function(pos, current, rev_data) {
274             // console.log("Navigate_to ("+pos+"), current rev: "+current);
275             
276             var behind = [];
277             var ahead = [];
278             var revisions = rev_data.all;
279             
280             var put_behind = true;
281             var rev_idxs = {};
282             $.each(revisions, function(i,n){
283                 rev_idxs[n.rev] = i;
284                 if (n.rev == current) {
285                     put_behind = false;
286                     return;
287                 }
288                 if (put_behind) {
289                     behind.push(n.rev);
290                 } else {
291                     ahead.push(n.rev);
292                 }
293             });
294             
295             var curr_key = rev_idxs[current];
296             
297             // console.log("Behind:");
298             // console.log(behind);
299             // console.log("Ahead:");
300             // console.log(ahead);
301             
302             var return_rev = null;
303             
304             switch(pos) {
305                 case 'first':
306                     if (typeof ahead[(ahead.length-1)] != 'undefined') {
307                         return_rev = ahead[(ahead.length-1)];
308                         curr_key = rev_idxs[return_rev];
309                     }
310                 break;
311                 case 'last':
312                     if (typeof behind[0] != 'undefined') {
313                         return_rev = behind[0];
314                         curr_key = rev_idxs[return_rev];
315                     }
316                     if (rev_data.active.rev == current) {
317                         curr_key = rev_idxs[current];
318                         return_rev = null;
319                     }
320                 break;
321                 case 'next':
322                     if (typeof behind[(behind.length-1)] != 'undefined') {
323                         return_rev = behind[(behind.length-1)];
324                         curr_key = rev_idxs[return_rev];                        
325                     } else if (typeof ahead[0] != 'undefined') {
326                         return_rev = ahead[0];
327                         curr_key = rev_idxs[return_rev];
328                     }
329                     
330                     if (rev_data.active.rev == current) {
331                         curr_key = rev_idxs[current];
332                         return_rev = null;
333                     }
334                 break;
335                 case 'prev':
336                     if (typeof ahead[0] != 'undefined') {
337                         return_rev = ahead[0];
338                         curr_key = rev_idxs[return_rev];
339                     }
340                 break
341             }
343             // console.log("Total revs: "+revisions.length);
344             // console.log("curr_key: "+curr_key);
345             // console.log("Current: "+(revisions.length - (curr_key)));
346             // 
347             // console.log("Return rev: "+return_rev);
348             
349             return {
350                 total: revisions.length,
351                 current: (revisions.length - curr_key),
352                 rev: return_rev
353             };
354         }
355     };
356     $.ajatus.document.metadata = {
357         creator: {
358             label: 'Creator',
359             widget: {
360                 name: 'text',
361                 config: {}
362             }
363         },
364         created: {
365             label: 'Created',
366             widget: {
367                 name: 'date',
368                 config: {
369                     use_time: true
370                 }
371             }
372         },
373         revisor: {
374             label: 'Revisor',
375             widget: {
376                 name: 'text',
377                 config: {}
378             }
379         },
380         revised: {
381             label: 'Revised',
382             widget: {
383                 name: 'date',
384                 config: {
385                     use_time: true
386                 }
387             }
388         },
389         archived: {
390             label: 'Archived',
391             widget: {
392                 name: 'boolean',
393                 config: {}
394             },
395             def_val: false
396         },
397         deleted: {
398             label: 'Deleted',
399             widget: {
400                 name: 'boolean',
401                 config: {}
402             },
403             def_val: false
404         }
405     };
406     $.ajatus.document.modify_metadata = function(doc, metadata) {
407         $.each(metadata, function(k,v){
408             if ($.ajatus.document.metadata[k])
409             {
410                 var wdgt = new $.ajatus.widget($.ajatus.document.metadata[k].widget.name, $.ajatus.document.metadata[k].widget.config);
411                 doc.value.metadata[k] = {
412                     val: wdgt.value_on_save(wdgt.value_on_save(v)),
413                     widget: $.ajatus.document.metadata[k].widget
414                 };
415             }
416         });
417         
418         return doc;
419     };
420     $.ajatus.document.actions = {        
421         execute: function(action, tmpdoc) {
422             if (   typeof tmpdoc._rev != 'undefined'
423                 && tmpdoc._rev != null)
424             {
425                 var doc = new $.ajatus.document.loader(tmpdoc._id, tmpdoc._rev);                
426             } else {
427                 var doc = new $.ajatus.document.loader(tmpdoc._id);
428             }
429             
430             var act_info = $.ajatus.document.actions._get_action_info(action);
431             if (! act_info) {
432                 var msg = $.ajatus.elements.messages.create(
433                     $.ajatus.i10n.get('Unknown document action'),
434                     $.ajatus.i10n.get('Unknown action %s requested for object %s!', [action, doc.value.title.val])
435                 );
436                 return false;
437             }
438             
439             if (act_info.pool_action)
440             {
441                 var pa = act_info.pool_action;
442                 var pai = $.ajatus.document.actions._get_action_info(fa);
443                 if (pai) {
444                     var pool_action = {
445                         action: fa,
446                         doc: doc
447                     };
448                     var pool_id = $.ajatus.document.history.pool.add(pool_action);
449                 }
450             }
451             
452             if (act_info.undoable) {                
453                 $.ajatus.document.actions._execute_temp(act_info.action, doc);
454             } else {
455                 $.ajatus.document.actions._execute_final(act_info.action, doc);
456             }
457         },
458         _execute_temp: function(action, doc) {
459             // console.log("_execute_temp: "+action);
460             switch(action) {
461                 case 'delete':
462                     var on_success = function(data) {
463                         var tmpdoc = {
464                             _id: doc._id,
465                             _rev: doc._rev
466                         };
467                         var msg = $.ajatus.elements.messages.create(
468                             $.ajatus.i10n.get('Object deleted'),
469                             $.ajatus.i10n.get('Object %s moved to trash.', [doc.value.title.val]) + ' <a href="#undelete.'+doc.value._type+'.'+doc._id+'" class="undo">' + $.ajatus.i10n.get('Undo') + '</a>'
470                         );
471                         msg.bind_in_content('click', 'a.undo', function(e){
472                             $.ajatus.document.actions.execute("undelete", tmpdoc);
473                             msg.fade('out', true);
474                         });
475                         
476                         return data;
477                     };
479                     doc = $.ajatus.document.modify_metadata(doc, {
480                         deleted: true,
481                         revised: $.ajatus.formatter.date.js_to_iso8601(new Date()),
482                         revisor: $.ajatus.preferences.local.user.email
483                     });
484                     
485                     $.jqCouch.connection('doc', on_success).save($.ajatus.preferences.client.content_database, doc);
486                     
487                     $('#object_'+doc._id, $.ajatus.application_content_area).hide().addClass('deleted');
488                 break;
489                 case 'archive':
490                     var on_success = function(data) {
491                         var tmpdoc = {
492                             _id: doc._id,
493                             _rev: doc._rev
494                         };
495                         var msg = $.ajatus.elements.messages.create(
496                             $.ajatus.i10n.get('Object archived'),
497                             $.ajatus.i10n.get('Object %s moved to archive.', [doc.value.title.val]) + ' <a href="#unarchive.'+doc.value._type+'.'+doc._id+'" class="undo">' + $.ajatus.i10n.get('Undo') + '</a>'
498                         );
499                         msg.bind_in_content('click', 'a.undo', function(e){
500                             $.ajatus.document.actions.execute("unarchive", tmpdoc);
501                             msg.fade('out', true);
502                         });
503                         
504                         return data;
505                     };
507                     doc = $.ajatus.document.modify_metadata(doc, {
508                         revised: $.ajatus.formatter.date.js_to_iso8601(new Date()),
509                         revisor: $.ajatus.preferences.local.user.email,
510                         archived: true
511                     });
512                     
513                     $.jqCouch.connection('doc', on_success).save($.ajatus.preferences.client.content_database, doc);
514                     
515                     $('#object_'+doc._id, $.ajatus.application_content_area).hide().addClass('archived');
516                 break;
517             };
518         },
519         _execute_final: function(action, doc) {
520             switch(action) {
521                 case 'delete':
522                     var on_success = function(data) {
523                         var msg = $.ajatus.elements.messages.create(
524                             $.ajatus.i10n.get('Object deleted'),
525                             $.ajatus.i10n.get('Object %s removed from Ajatus.', [doc.value.title.val])
526                         );
527                         
528                         return data;
529                     };
530                     $.jqCouch.connection('doc', on_success).del($.ajatus.preferences.client.content_database, doc);
531                     $('#object_'+doc._id, $.ajatus.application_content_area).remove();
532                 break;
533                 case 'undelete':
534                     var on_success = function(data) {
535                         var msg = $.ajatus.elements.messages.create(
536                             $.ajatus.i10n.get('Object restored'),
537                             $.ajatus.i10n.get('Object %s restored succesfully.', [doc.value.title.val])
538                         );
539                         
540                         return data;
541                     };
542                     doc = $.ajatus.document.modify_metadata(doc, {
543                         deleted: false,
544                         revised: $.ajatus.formatter.date.js_to_iso8601(new Date()),
545                         revisor: $.ajatus.preferences.local.user.email
546                     });
547                     $.jqCouch.connection('doc', on_success).save($.ajatus.preferences.client.content_database, doc);
548                     
549                     $('#object_'+doc._id, $.ajatus.application_content_area).not('.deleted').remove();
550                     $('#object_'+doc._id, $.ajatus.application_content_area).filter('.deleted').show().removeClass('deleted');
551                 break;
552                 case 'unarchive':
553                     var on_success = function(data) {
554                         var msg = $.ajatus.elements.messages.create(
555                             $.ajatus.i10n.get('Object restored'),
556                             $.ajatus.i10n.get('Object %s restored succesfully.', [doc.value.title.val])
557                         );
558                         
559                         return data;
560                     };
561                     doc = $.ajatus.document.modify_metadata(doc, {
562                         revised: $.ajatus.formatter.date.js_to_iso8601(new Date()),
563                         revisor: $.ajatus.preferences.local.user.email,
564                         archived: false
565                     });
566                     $.jqCouch.connection('doc', on_success).save($.ajatus.preferences.client.content_database, doc);
567                     
568                     $('#object_'+doc._id, $.ajatus.application_content_area).filter('.archived').show().removeClass('archived');
569                 break;
570             };
571         },
572         empty_pool: function () {
573             var items = $.ajatus.document.history.pool.get_all();
574             if (items.length > 0) {
575                 var msg = $.ajatus.elements.messages.create(
576                     $.ajatus.i10n.get('Emptying action pool'),
577                     $.ajatus.i10n.get('Running %d pooled actions.', [items.length])
578                 );                
579             }
580             $.each(items, function(i,item){
581                 $.ajatus.document.history.pool.remove(i);
582                 $.ajatus.document.actions.execute(item.action, item.doc);
583             });
584         },
585         _get_action_info: function(action) {
586             switch(action) {
587                 case 'delete':
588                     return {
589                         action: 'delete',
590                         label: $.ajatus.i10n.get('Delete'),
591                         undoable: true,
592                         undo_label: $.ajatus.i10n.get('Undelete'),
593                         pool_action: false
594                     }
595                 break;
596                 case 'delete_final':
597                     return {
598                         action: 'delete',
599                         label: $.ajatus.i10n.get('Delete'),
600                         undoable: false,
601                         pool_action: false
602                     }
603                 break;
604                 case 'undelete':
605                     return {
606                         action: 'undelete',
607                         label: $.ajatus.i10n.get('Undelete'),
608                         undoable: false,
609                         pool_action: false
610                     }
611                 break;
612                 case 'archive':
613                     return {
614                         action: 'archive',
615                         label: $.ajatus.i10n.get('Archive'),
616                         undoable: true,
617                         undo_label: $.ajatus.i10n.get('Restore'),
618                         pool_action: false
619                     }
620                 break;
621                 case 'unarchive':
622                     return {
623                         action: 'unarchive',
624                         label: $.ajatus.i10n.get('Restore'),
625                         undoable: false,
626                         pool_action: false
627                     }
628                 break;
629                 default:
630                     return false;
631             }
632         }
633     };
634     
635     $.ajatus.document.history = {};
636     $.ajatus.document.history.pool = {
637         items: [],
638         
639         add: function(action) {
640             var new_length = $.ajatus.document.history.pool.items.push(action);
641             var pool_id = new_length-1;
642             return pool_id;
643         },        
644         remove: function(item_id) {
645             $.ajatus.document.history.pool.items = $.grep($.ajatus.document.history.pool.items, function(n,i){
646                 return i != item_id;
647             });
648         },        
649         get_item: function(item_id) {
650             if (items[item_id]) {
651                 return items[item_id];
652             } else {
653                 return false;
654             }
655         },        
656         get_all: function() {
657             return $.ajatus.document.history.pool.items;
658         }
659     };
660     
661     $.ajatus.document.additionals = {
662         defaults: {
663             auto_show: true
664         },
665         open: [],
666         active: null,
667         top_start: 22,
668         left_start: 20
669     };
670     $.extend($.ajatus.document.additionals, {
671         create: function(content_type, row_holder, opts) {
672             $.ajatus.document.additionals._reset();
673             
674             var id = $.ajatus.document.additionals._generate_id();
675             
676             var options = $.ajatus.document.additionals.defaults;
677             options = $.extend(
678                 options,
679                 opts || {}
680             );
682             var af_win = $.ajatus.document.additionals._create_structure(id, options);
683             $('.title', af_win).html($.ajatus.i10n.get('Add field'));
684             
685             var jqform = $('.form', af_win);
686             var contents = $('.contents', af_win);
687             
688             var wdgts = $.ajatus.document.additionals._generate_widget_list();
689                         
690             $('<label for="widget"/>').html($.ajatus.i10n.get('Widget')).appendTo(contents);
691             var wdgt_sel_holder = $('<div id="widget_selection_holder"/>');
692             wdgt_sel_holder.html(wdgts).appendTo(contents);
693             
694             var wdgt_details = $('<div id="widget_details_holder"/>');
695             wdgt_details.appendTo(contents);
696             
697             var wdgts_on_change = function(e){
698                 var sel_w = e.currentTarget.value;
699                 if (sel_w != '') {
700                     wdgt_sel_holder.html($.ajatus.i10n.get(sel_w));
701                     wdgt_sel_holder.addClass('selected');
702                     wdgt_details.html($.ajatus.document.additionals._generate_widget_details(sel_w));
704                     var field = $('<input type="hidden" />').attr({
705                         name: '_widget',
706                         value: sel_w
707                     });
708                     field.appendTo(jqform);
709                 }
710             };
711             
712             wdgts.bind('change', wdgts_on_change);
713             
714             wdgt_sel_holder.bind('dblclick', function(e){
715                 wdgt_sel_holder.removeClass('selected');
716                 wdgt_sel_holder.html(wdgts);
717                 wdgts.bind('change', wdgts_on_change);
718             });
719             
720             $('.actions #submit_save', af_win).bind('click', function(e){
721                 var result = $.ajatus.document.additionals.save_widget(jqform.formToArray(false), jqform);
722                 
723                 if (result) {
724                     $.ajatus.document.additionals.close(id);
725                 }
726                 
727                 return false;
728             });
729             
730             if (options.auto_show) {
731                 $.ajatus.document.additionals.show(id);
732             }
733         },
734         edit: function(content_type, row_holder, data, opts) {
735             $.ajatus.document.additionals._reset();
736             
737             var id = $.ajatus.document.additionals._generate_id();
738             console.log("Edit win id: "+id);
739             
740             var options = $.ajatus.document.additionals.defaults;
741             options = $.extend(
742                 options,
743                 opts || {}
744             );
746             var af_win = $.ajatus.document.additionals._create_structure(id, options);
747             $('.title', af_win).html($.ajatus.i10n.get('Edit field %s', [data.name]));
748             
749             $('.actions #submit_save', af_win).bind('click', function(e){
750                 console.log("save additional field (on edit)");
751                 $.ajatus.document.additionals.close(id);
752             });
753             
754             if (options.auto_show) {
755                 $.ajatus.document.additionals.show(id);
756             }
757         },
758         config: function(widget, prev_vals, on_save) {
759             if (typeof prev_vals == 'undefined') {
760                 var prev_vals = {};
761             }
762             if (typeof on_save == 'undefined') {
763                 var on_save = '$.ajatus.document.additionals.save_widget_settings';
764             }
765             
766             var id = $.ajatus.document.additionals._generate_id();
767             
768             var af_win = $.ajatus.document.additionals._create_structure(id);
769             $('.title', af_win).html($.ajatus.i10n.get('Configure widget %s', [$.ajatus.i10n.get(widget.name)]));
770             
771             var jqform = $('.form', af_win);
772             var contents = $('.contents', af_win);
773             
774             var wdgt_settings = $('<div id="widget_settings_holder" />');
775             wdgt_settings.appendTo(contents);
776             wdgt_settings.html($.ajatus.document.additionals._generate_widget_settings(widget, prev_vals));
777             
778             $('.actions #submit_save', af_win).bind('click', function(e){                
779                 var parent_win = $.ajatus.document.additionals._get_parent();
781                 var fn = on_save;
782                     if (typeof on_save == 'string') {
783                     fn = eval(on_save);
784                 }
785                 var result = fn.apply(fn, [jqform.formToArray(false), parent_win, jqform]);
786                 
787                 if (result) {
788                     $.ajatus.document.additionals.close(id);
789                 }
790             });
791             
792             $.ajatus.document.additionals.show(id);
793         },
794         show: function(id) {
795             $.ajatus.document.additionals.active = id;
796             $.ajatus.document.additionals.open.push(id);
797             $.ajatus.document.additionals._position(id);
798                         
799             $('#'+id).show();
800         },
801         close: function(id) {            
802             if (typeof id == 'undefined') {
803                 var id = $.ajatus.document.additionals.active;
804             }
805             
806             $('#'+id).hide();
807             
808             var active_idx = null;
809             var still_open = $.grep($.ajatus.document.additionals.open, function(n,i){
810                 if (n != id) {
811                     return true;
812                 } else {
813                     active_idx = i;
814                     return false;
815                 }
816             });
817             
818             if (   active_idx > 0
819                 && $.ajatus.document.additionals.open.length-1 >= (active_idx-1))
820             {
821                 $.ajatus.document.additionals.active = still_open[active_idx-1];
822             } else {
823                 $.ajatus.document.additionals.active = null;
824             }
825             
826             $.ajatus.document.additionals.open = still_open;
827         },
828         save_widget_settings: function(form_data, parent_win_id, form) {
829             var form_values = {};
830             
831             $.each(form_data, function(i,row){
832                 if (row.name.toString().match(/__(.*?)/)) {
833                     return;
834                 }
835                     if (row.name.substr(0,6) != "widget") {
836                         var item = {};
837                         var widget = {};
838                         var prev_val = false;
839                         var name_parts = [];
840                         var name_parts_count = 0;
841                         if (row.name.toString().match(/;/g)) {
842                             name_parts = row.name.toString().split(";");
843                             name_parts_count = name_parts.length;
844                         }
845                         
846                         $.each(form_data, function(x,r){
847                             if (r.name == 'widget['+row.name+':name]') {
848                                 widget['name'] = r.value;
849                             } else if (r.name == 'widget['+row.name+':config]') {
850                             widget['config'] = $.ajatus.converter.parseJSON(r.value);
851                         } else if (r.name == 'widget['+row.name+':prev_val]') {
852                             prev_val = $.ajatus.converter.parseJSON(r.value);
853                         }
854                     });
856                     var wdgt = new $.ajatus.widget(widget['name'], widget['config']);
858                         item['val'] = wdgt.value_on_save(row.value, prev_val);
859                         item['widget'] = widget;
860                         
861                         if (name_parts_count > 0) {
862                             var prevs = [];
863                             for (var i=0; i < name_parts_count; i++) {
864                                 var key = "['"+name_parts[i]+"']";
865                             
866                             if (prevs.length > 0) {
867                                 var key_prefix = '';
868                                 $.each(prevs, function(pi, pk){
869                                     key_prefix = "['" + pk + "']" + key_prefix;
870                                 });
871                                 key = key_prefix + key;
872                             }
873                             
874                                 if (typeof eval("form_values"+key) == 'undefined') {
875                                     eval("form_values"+key+"={};");
876                                 }
877                                 
878                                 prevs.push(name_parts[i]);
879                             if (i == name_parts_count-1) {
880                                 if ($.browser.mozilla) {
881                                     if (typeof item == 'object') {
882                                         eval("form_values"+key+"="+item.toSource()+";");
883                                     } else {
884                                         eval("form_values"+key+"="+item+";");
885                                     }
886                                 } else {
887                                     eval("form_values"+key+"="+item+";");
888                                 }
889                             }
890                             }
891                         } else {
892                             form_values[row.name] = item;
893                         }
894                     }
895             });
896             
897             var config_holder = $('#'+parent_win_id+' .saved_settings');
898             config_holder.html('');
899             
900             $.each(form_values, function(k,item){
901                 var field = $('<input type="hidden" />').attr({
902                     name: 'config;'+k,
903                     value: $.ajatus.converter.toJSON(item.val)
904                 });
905                 field.appendTo(config_holder);
906             });
907             
908             return true;
909         },
910         save_widget: function(form_data, form) {
911             var form_values = {};
912             var sel_widget = 'text';
913             
914             // console.log(form_values);
915             
916             $.each(form_data, function(i,row){                  
917                 if (row.name.toString().match(/__(.*?)/)) {
918                     return;
919                 }
920                 if (row.name == '_widget') {
921                     sel_widget = String(row.value);
922                 }
923                     else if (row.name.substr(0,6) != "widget") {                        
924                         var item = {};
925                         var widget = {};
926                         var prev_val = false;
927                         var name_parts = [];
928                         var name_parts_count = 0;
929                         
930                         if (row.name.toString().match(/;/g)) {
931                             name_parts = row.name.toString().split(";");
932                             name_parts_count = name_parts.length;
933                         }
934                         
935                         $.each(form_data, function(x,r){
936                             if (r.name == 'widget['+row.name+':name]') {
937                                 widget['name'] = r.value;
938                             } else if (r.name == 'widget['+row.name+':config]') {
939                             widget['config'] = $.ajatus.converter.parseJSON(r.value);
940                         } else if (r.name == 'widget['+row.name+':prev_val]') {
941                             prev_val = $.ajatus.converter.parseJSON(r.value);
942                         }
943                     });
944                     
945                     if (typeof widget['name'] == 'undefined') {
946                         return;
947                     }
949                     var wdgt = new $.ajatus.widget(widget['name'], widget['config']);
951                         item['val'] = wdgt.value_on_save(row.value, prev_val);
952                         item['widget'] = widget;
953                         
954                         if (name_parts_count > 0) {
955                         // console.log("name_parts_count > 0");
956                             var prevs = [];
957                             for (var i=0; i < name_parts_count; i++) {
958                                 var key = "['"+name_parts[i]+"']";
959                             
960                             if (prevs.length > 0) {
961                                 var key_prefix = '';
962                                 $.each(prevs, function(pi, pk){
963                                     key_prefix = "['" + pk + "']" + key_prefix;
964                                 });
965                                 key = key_prefix + key;
966                             }
967                             
968                                 if (typeof eval("form_values"+key) == 'undefined') {
969                                     eval("form_values"+key+"={};");
970                                 }
971                                 
972                                 prevs.push(name_parts[i]);
973                             if (i == name_parts_count-1) {
974                                 if ($.browser.mozilla) {
975                                     if (typeof item == 'object') {
976                                         eval("form_values"+key+"="+item.toSource()+";");
977                                     } else {
978                                         eval("form_values"+key+"="+item+";");
979                                     }
980                                 } else {
981                                     eval("form_values"+key+"="+item+";");
982                                 }
983                             }
984                             }
985                         } else {
986                             form_values[row.name] = item;
987                         }
988                     }
989             });
990             
991             // var additional_items = {};
992             
993             var config = {};
994             if (typeof form_values['config'] != 'undefined') {
995                 $.each(form_values['config'], function(i,n){
996                     if (typeof n == 'object') {
997                         config[i] = $.ajatus.converter.parseJSON(n.val);
998                     } else {
999                         config[i] = n;
1000                     }
1001                 });                
1002             }
1003             
1004             var item_name = form_values.name.val.toString().toLowerCase();
1005             
1006             if (item_name == '') {
1007                 return false;
1008             }
1009             
1010             var additional_item = {
1011                 label: form_values.label.val,
1012                 widget: {
1013                     name: sel_widget,
1014                     config: config
1015                 },
1016                 def_val: form_values.def_val.val,
1017                 required: form_values.required.val
1018             };
1019             // additional_items[item_name] = additional_item;
1020             // console.log(additional_items);
1021             // console.log(additional_item);
1022             
1023             var row_holder = $('.form_structure ul.row_holder:eq(0)', $.ajatus.forms.active);
1025             $.ajatus.renderer.form_helpers._add_additional_row('create', row_holder, item_name, additional_item);
1026             
1027             return true;
1028         },
1029         generate_item_actions_tpl: function(name, widget, doc) {
1030             return [
1031                 'img', { className: 'additional_edit_btn', src: $.ajatus.preferences.client.theme_icons_url + 'edit.png', title: $.ajatus.i10n.get('Edit'), alt: $.ajatus.i10n.get('Edit') }, '',
1032                 'img', { className: 'additional_delete_btn', src: $.ajatus.preferences.client.theme_icons_url + 'trash.png', title: $.ajatus.i10n.get('Delete'), alt: $.ajatus.i10n.get('Delete') }, '',
1033             ];
1034         },
1035         _get_parent: function() {            
1036             var prev_id = $.ajatus.document.additionals.open[$.ajatus.document.additionals.open.length-2];
1037             
1038             return prev_id;
1039         },
1040         _position: function(id) {
1041             var win = $('#' + id);
1042             var top = $.ajatus.document.additionals.top_start;
1043             var left = $.ajatus.document.additionals.left_start;
1044             
1045             if ($.ajatus.document.additionals.open.length > 1) {
1046                 var incr = $.ajatus.document.additionals.open.length * 2;
1047                 top += incr;
1048                 left += incr;
1049             }
1051             win.css({
1052                 top: top+'%',
1053                 left: left+'%'
1054             });
1055         },
1056         _create_structure: function(id, options) {            
1057             var af_win = $('<div class="additionals_window" />').attr({
1058                 id: id
1059             }).hide();
1060             var title = $('<h2 class="title"/>');
1061             var form = $('<form id="additionals_window_form" class="form" />');
1062             var content_area = $('<div class="contents"/>');
1063             var actions = $('<div class="actions" />').html('<input type="submit" id="submit_save" name="save" value="' + $.ajatus.i10n.get('Save') + '" /><input type="submit" id="submit_cancel" name="cancel" value="' + $.ajatus.i10n.get('Cancel') + '" />');
1064                                     
1065             af_win.appendTo($.ajatus.application_dynamic_elements);
1066             title.appendTo(af_win);
1067             form.appendTo(af_win);
1068             content_area.appendTo(form);
1069             actions.appendTo(af_win);
1071             $('#submit_cancel', actions).bind('click', function(e){
1072                 $.ajatus.document.additionals.close(id);
1073                 return false;
1074             });
1075             
1076             return af_win;
1077         },
1078         _generate_widget_list: function() {
1079             var select = $('<select id="widget" name="widget" />');
1080                         
1081             $.each($.ajatus.widgets.loaded_widgets, function(i,w){
1082                 var opt = $('<option />').attr({
1083                     value: w
1084                 }).html($.ajatus.i10n.get(w));
1085                 opt.appendTo(select);
1086             });
1088             var opt = $('<option />').attr({
1089                 value: '',
1090                 selected: 'selected'
1091             }).html($.ajatus.i10n.get('Select one') + '&nbsp;');
1092             opt.prependTo(select);
1093             
1094             return select;
1095         },
1096         _generate_widget_details: function(widget_name, data) {
1097             var widget = $.ajatus.widget(widget_name);
1098             var details = $('<p>' + $.ajatus.i10n.get("Widget %s doesn't support dynamic creation.", [$.ajatus.i10n.get(widget_name)]) + '</p>');
1099             if (typeof(widget['create_widget_details']) == 'function') {
1100                 details = widget.create_widget_details(data || {});
1101             }
1102             
1103             return details;
1104         },
1105         _generate_widget_settings: function(widget_name, data) {
1106             var widget = $.ajatus.widget(widget_name);
1107             var details = $('<p>' + $.ajatus.i10n.get("Widget %s doesn't support dynamic settings.", [$.ajatus.i10n.get(widget_name)]) + '</p>');
1108             if (typeof(widget['create_widget_settings']) == 'function') {
1109                 details = widget.create_widget_settings(data || {});
1110             }
1111             
1112             return details;
1113         },
1114         _reset: function() {
1115             $.ajatus.document.additionals.open = [];
1116             $.ajatus.document.additionals.active = null;
1117             $.ajatus.application_dynamic_elements.html('');
1118         },
1119         _generate_id: function()
1120         {
1121             return "additionals_window_" + $.ajatus.utils.generate_id();
1122         }
1123     });
1125 })(jQuery);