/*
A set of common application views and utility functions.
*/

EDIT_VIEW = {};
EDIT_VIEW.DEFAULT_VIEW_WIDTH = 700;

EDIT_VIEW.list_view = function(url, paging, options) {
    /* Display a list of records */
    
    paging = paging || new Object();
    options = options || new Object();
    
    // Human readable
    var verbose_name = options['verbose_name'] || 'record';
    var verbose_name_plural = options['verbose_name_plural'] || options['verbose_name'] + 's';
    var title = options['title'] || verbose_name_plural.substr(0, 1).toUpperCase() + verbose_name_plural.substr(1) + ' (#COUNT#)';
    
    // Set up the view
    var view = new UI.View(app.modal_panel, 
        null, 
        {title: title, 
        icon: options['icon'], 
        can_close: true});
    view.size([options['width'] || EDIT_VIEW.DEFAULT_VIEW_WIDTH, 'auto']);
    view.show(false);
    
    // Support for closing the view
    view.bind('close', null, function(ev) {
        app.modal(false);
        view.destroy();
    });
    
    // Add button
    var add_btn;
    if (options['add_record']) {
        view.top_panel.add_class('wui-area');
        add_btn = new UI.Button(view.top_panel,
            null,
            {text:'Add ' + verbose_name, icon:RESOURCES.ICONS.ADD, css_list:['wui-button-simple']});
        add_btn.bind('click', null, function(ev) {
            app.busy(true,true);
            view.destroy();
            options['add_record'](paging);
        });         
    }
    
    // Set up pagination
    function page_change(paging) {
    
        app.busy(true, true);  
        $.post(url, paging, function(data) {
            // Assign this function to the new page each time
            _page.page_change = page_change;
            
            // Bind the row select event
            if (options['select_record']) {
                _page.row_select = function(ev) {
                    app.busy(true,true);
                    view.destroy();
                    options['select_record'](ev.data.data.id, paging);
                };
            }       
            
            // Render the page to the view
            view.content = function(content_node) {
                switch (_page.row_count) {
                    case 0:
                        view.title(title.replace('#COUNT#', 'no ' + verbose_name_plural));
                        break;
                    case 1:
                        view.title(title.replace('#COUNT#', '1 ' + verbose_name));
                        break;
                    default:
                        view.title(title.replace('#COUNT#', _page.row_count.toString() + ' ' + verbose_name_plural));
                }
                _page.render(content_node);
            };
            
            // Update paging for add button
            if (add_btn) {
                add_btn.unbind();
                add_btn.bind('click', null, function(ev) {
                    app.busy(true,true);
                    view.destroy();
                    options['add_record'](paging);
                });
            }
            
            // Ready to display
            app.busy(false);  
            view.show(); 
            view.refresh();
        }, 'script');
    }
    
    // Add breadcrumbs
    view.breadcrumb_path.clear_path();
    if (options['breadcrumb_path']) {
        for (var i=0; i<options['breadcrumb_path'].length; i++) {
            view.breadcrumb_path.add_breadcrumb(options['breadcrumb_path'][i]);
        }
        view.breadcrumb_path.add_breadcrumb(new UI.Breadcrumb('Add ' + verbose_name));
        view.breadcrumb_path.show();
    }    
    
    var _refresh = true;
    if (options['pre_ready']) {
        _refresh = options['pre_ready']();
    }            
    
    // Ready to display
    if (_refresh || _refresh===undefined) {
        page_change(paging);
    }
    
    if (options['ready']) {
        options['ready'](view);
    }
}

EDIT_VIEW.add_view = function(url, paging, options) {
    /* Add a record */
    
    paging = paging || new Object();
    options = options || new Object();
    
    // Human readable
    var verbose_name = options['verbose_name'] || 'record';
    var verbose_name_plural = options['verbose_name_plural'] || options['verbose_name'] + 's';
    var title = options['title'] || 'Add ' + verbose_name;
    
    // Load the add form
    $.post(url,options['data']||{},function(data) {
        
        // Set up the view
        var view = new UI.View(app.modal_panel, 
            null, 
            {title: title, 
            icon: options['icon'], 
            can_close: true});
        view.size([options['width'] || EDIT_VIEW.DEFAULT_VIEW_WIDTH, 'auto']);
        view.show(false);        
        
        // Support for closing the view
        view.bind('close', null, function() {
            app.modal(false);
            view.destroy();
        });        
        
        // Handle pre-submissions
        _form.pre_callback = function(form, changed, valid, args) {
            if (changed || !valid) {
                if (valid) {
                    app.busy();
                } else {
                    view.refresh_content();
                }
            } else {
                return false;
            }
        };
        
        // Handle post-submissions
        _form.post_callback = function(form, data, args) {
            app.busy(false);
            app.notify(data.status_message);
            if (data.status=='OK') {
                app.busy(true,true);
                view.destroy();
                if (options['record_added']) {
                    options['record_added'](data.data.record_id, paging);
                }
            } else {
                form.post_errors(data.error_map);
                view.refresh_content();
            }
        };        
        
        // Render the form
        view.content = function(content_node) {
            _form.render(content_node);
        };        

        // Add breadcrumbs
        view.breadcrumb_path.clear_path();
        if (options['breadcrumb_path']) {
            for (var i=0; i<options['breadcrumb_path'].length; i++) {
                view.breadcrumb_path.add_breadcrumb(options['breadcrumb_path'][i]);
            }
            view.breadcrumb_path.add_breadcrumb(new UI.Breadcrumb('Add ' + verbose_name));
            view.breadcrumb_path.show();
        }
        
        var _refresh = true;
        if (options['pre_ready']) {
            _refresh = options['pre_ready'](record_data);
        }            
        
        // Ready to display
        if (_refresh || _refresh===undefined) {
            app.busy(false);
            view.show();
            view.refresh();
            
            // Focus on the first field
            _form.focus_first(); 
        }
        
        if (options['ready']) {
            options['ready']();
        }               
    },'script');     
}


EDIT_VIEW.manage_view = function(url, record_id, paging, options) {
    /* Manage a record */
    
    paging = paging || new Object();
    options = options || new Object();
    
    // Human readable
    var verbose_name = options['verbose_name'] || 'record';
    var verbose_name_plural = options['verbose_name_plural'] || options['verbose_name'] + 's';
    var title = options['title'] || 'Manage ' + verbose_name;
    
    var timestamp = new Date().getTime();
    $.post(url, {'record_id': record_id, 'timestamp': timestamp}, function(data) {
    
        // Collect the initial record data
        var record_data = _form.get_dict();
        record_data['_form'] = _form;
        
        // Set up the view
        var view = new UI.View(app.modal_panel, 
            null, 
            {title: title, 
            icon: options['icon'], 
            can_close: true});
        view.size([options['width'] || EDIT_VIEW.DEFAULT_VIEW_WIDTH, 'auto']);
        view.show(false);        
        
        // Support for closing the view
        view.bind('close', null, function() {
            app.modal(false);
            view.destroy();
        });
        
       // Delete button
        if (options['delete_url']) {
            view.bottom_panel.add_class('wui-area');
            var delete_btn = new UI.Button(view.bottom_panel,
                null,
                {text:'Delete ' + verbose_name, icon:RESOURCES.ICONS.DELETE, css_list:['wui-button-simple wui-right']});
            delete_btn.bind('click', null, function(ev) {
                var delete_title = options['delete_message'] || 'Please confirm you wish to delete this record.';
                for (var field_name in record_data) {
                    delete_title = delete_title.replace('#'+field_name.toUpperCase()+'#', record_data[field_name]);
                }
                app.confirm(options['delete_title'] || 'Delete ' + verbose_name + '?',
                    options['delete_icon'],
                    delete_title,
                    {},
                    function (result, data) {
                        if (result) {
                            app.busy(true,true);
                            $.post(options['delete_url'], {'record_id': record_id}, function(data) {
                                app.notify(data.status_message);
                                if (data.status=='OK') {
                                    view.destroy();
                                    options['record_deleted'](paging);
                                }
                            }, 'json');
                        } else {
                            view.show();
                        }    
                    }
                );
            });         
        }        
        
        // Handle form resizes
        _form.resize_callback = function(){
            view.calc_max_height(); 
            view.centre();
        };    
        
        // Handle pre-submissions
        _form.pre_callback = function(form, changed, valid, args) {
            if (changed || !valid) {
                if (valid) {
                    app.busy();
                } else {
                    view.refresh_content();
                }
            } else {
                return false;
            }
        }; 
        
        // Handle post-submissions
        _form.post_callback = function(form, data, args) {
            app.busy(false);
            if (data.status!='OK') {
                form.post_errors(data.error_map);
            }
            app.notify(data.status_message);
            view.refresh_content();
            
            // Update the record data
            record_data = form.get_dict();
            
            if (options['record_updated']) {
                options['record_updated']();
            }              
        };           
        
        // Render the form in the view
        view.content = function(content_node) {
            _form.render(content_node,'edit-in-place');
    
            // Set the title
            for (var field_name in record_data) {
                title = title.replace('#'+field_name.toUpperCase()+'#', record_data[field_name]);
            }
            view.title(title);
            
            // Add breadcrumbs
            view.breadcrumb_path.clear_path();
            if (options['breadcrumb_path']) {
                for (var i=0; i<options['breadcrumb_path'].length; i++) {
                    view.breadcrumb_path.add_breadcrumb(options['breadcrumb_path'][i]);
                }
                view.breadcrumb_path.add_breadcrumb(new UI.Breadcrumb('Update ' + verbose_name));
                view.breadcrumb_path.show();
            }
        }
        
        var _refresh = true;
        if (options['pre_ready']) {
            _refresh = options['pre_ready'](record_data);
        }            
        
        // Ready to display
        if (_refresh || _refresh===undefined) {
            app.busy(false);
            view.show();
            view.refresh();
        }
        
        if (options['ready']) {
            options['ready'](record_data);
        }               
    }, 'script');
}
