/**
 * Document JTable Data source
 * 
 * @author pradeep.mishra
 * @version 1.0
 * @date May 20, 2015
 */
$(document).ready(function() {
    $(document)
        .ajaxStart($.blockUI({
            message: ''
        }))
        .ajaxStop($.unblockUI); // Blocks UI till Ajax Call
    // finishes working.
    var baseURL = getBaseUrl();
    var globalRecords = [];
    // setup the jTable that will display the results
    $('#documentSearchDiv').jtable({
        title: 'Document',
        paging: false,
        pageSize: 30,
        sorting: false,
        pageSizeChangeArea: false,
        selecting: true,
        multiselect: false,
        selectingCheckboxes: false,
        columnResizable: false,
        columnSelectable: false,
        loadingAnimationDelay: 2000,
        dialogShowEffect: 'scale',
        dialogHideEffect: 'scale',
        actions: {
            listAction: baseURL + '/document/search',
            updateAction: baseURL + '/document/update',
            deleteAction: baseURL + '/document/remove',
        },
        fields: {
            id: {
                key: true,
                create: false,
                edit: false,
                list: false
            },
            // CHILD TABLE DEFINITION FOR
            // "Document Relationship"
            DocumentRelationship: {
                title: '',
                width: '5%',
                sorting: true,
                edit: false,
                create: false,
                display: function(data) {
                    // Create an image that will
                    // be used to open child
                    // table
                    var $img = $('<img src="' + baseURL + '/static/css/themes/metro/ThemedExpand.png" title="Modify Code and Value" />');
                    // Open child table when
                    // user clicks the image
                    $img.click(function() {
                        var check = $img.attr('src');
                        if (check == baseURL + '/static/css/themes/metro/ThemedExpand.png') {
                            $img.attr('src', '' + baseURL + '/static/css/themes/metro/ThemedCollap.png');
                            $('#documentSearchDiv')
                                .jtable('openChildTable',
                                    $img.closest('tr'), {
                                        title: 'please enter your information',
                                        selecting: true,
                                        actions: {
                                            listAction: function(postData, jtParams) {
                                                return {
                                                    "Result": "OK",
                                                    "Records": data.record.relationships,
                                                    "TotalRecordCount": 2
                                                };
                                            },
                                            updateAction: function(data) {
                                                var docData = JSON.parse(jTableSelect('documentSearchDiv'));
                                                var docRelData = postStringToJson(data);
                                                docRelData = JSON.parse(docRelData);
                                                var id = docData[0].id;
                                                var document = {};
                                                document.id = id;
                                                docRelData.document = document;
                                                return $.Deferred(function($dfd) {
                                                    function success(data) {
                                                        $dfd.resolve(data);
                                                    }
                                                    function failure() {
                                                        $dfd.reject();
                                                    }
                                                    post(baseURL + '/documentRelationship/update', 'POST', JSON
                                                        .stringify(docRelData), success, failure);
                                                });
                                            },
                                            deleteAction: baseURL + '/documentRelationship/remove',
                                        },
                                        fields: {
                                            id: {
                                                key: true,
                                                create: false,
                                                edit: false,
                                                list: false
                                            },
                                            relationshipCode: {
                                                title: 'Code',
                                                width: '15%',
                                                inputClass: 'validate[required]',
                                            },
                                            relationshipValue: {
                                                title: 'Value',
                                                width: '15%',
                                                inputClass: 'validate[required]',
                                            },
                                        },
                                        formCreated: function(event, data) {
                                            data.form.validationEngine('attach', {
                                                binded: false
                                            });
                                        },
                                        // Validate
                                        // inner
                                        // form
                                        // when
                                        // it
                                        // is
                                        // being
                                        // submitted
                                        formSubmitting: function(event, data) {
                                            return data.form.validationEngine('validate');
                                        },
                                        // Dispose
                                        // validation
                                        // logic
                                        // when
                                        // form
                                        // is
                                        // closed
                                        formClosed: function(event, data) {
                                            data.form.validationEngine('hide');
                                            data.form.validationEngine('detach');
                                        },
                                        loadingRecords: function() {
                                            $('.jtable-child-table-container div.jtable-main-container table.jtable thead').html(
                                                '<tr><th class="jtable-column-header" style="width: 15%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Code</span><div class="jtable-column-resize-handler"></div></div></th><th class="jtable-column-header" style="width: 15%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Value</span></div></th><th class="jtable-command-column-header" style="width: 1%;" colspan="2"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Action</span></div></th></tr>')
                                        }
                                    },
                                    function(data) {
                                        data.childTable.jtable('load');
                                    });
                        } else {
                            $('#documentSearchDiv')
                                .jtable('closeChildTable', $img.closest('tr'));
                            $img.attr('src', '' + baseURL + '/static/css/themes/metro/ThemedExpand.png');
                        }
                    });
                    return $img;
                }
            },
            fileName: {
                title: 'File Name',
                width: '15%',
                inputClass: 'validate[required]',
            },
            description: {
                title: 'Description',
                width: '30%',
                inputClass: 'validate[required]',
            },
            type: {
                title: 'Document Type',
                width: '15%',
                inputClass: 'validate[required]',
            },
            mimeType: {
                title: 'MIME Type',
                width: '15%',
                inputClass: 'validate[required]',
            },
        },
        // Initialize validation logic when a
        // form is created
        formCreated: function(event, data) {
            data.form.validationEngine('attach', {
                binded: false
            });
        },
        // Validate form when it is being
        // submitted
        formSubmitting: function(event, data) {
            return data.form.validationEngine('validate');
        },
        // Dispose validation logic when form is
        // closed
        formClosed: function(event, data) {
            data.form.validationEngine('hide');
            data.form.validationEngine('detach');
        },
        recordsLoaded: function(event, data) {
            var headers = JSON.parse('{"0": { "sorter": "text" },"1" : {"sorter" : "text" },"2": {"sorter" : "text"},"3": {"sorter" : "text"}}');
            initializeTableSorter(headers);
        },
        loadingRecords: function() {
            $('.jtable-main-container table.jtable thead').html(
                    '<tr><th class="jtable-column-header" style="width: 2%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text"></span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">File Name</span></div></th><th class="jtable-column-header" style="width: 36.7372%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Description</span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Document Type</span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">MIME Type</span></div></th><th class="jtable-command-column-header" style="width: 1%;" colspan="2"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Action</span></div></th></tr>')
            $('.jtable').addClass("tablesorter");
        }
    });
    $('#documentSearchDiv').jtable('load');
    $('#documentSearchInnerDiv') jtable({
        title: 'Document Relationship',
        paging: false,
        pageSize: 30,
        sorting: false,
        clientOnly: true,
        useBootstrap: true,
        editinline: {
            enable: true
        },
        pageSizeChangeArea: false,
        selecting: true,
        multiselect: false,
        selectingCheckboxes: false,
        columnResizable: false,
        columnSelectable: false,
        loadingAnimationDelay: 2000,
        dialogShowEffect: 'scale',
        dialogHideEffect: 'scale',
        actions: {
            createAction: function(data) {
                console.info(postStringToJson(data));
                var dat = postStringToJson(data);
                return {
                    "Result": "OK",
                    "Record": JSON.parse(dat)
                };
            },
        },
        fields: {
            id: {
                type: 'hidden',
            },
            relationshipCode: {
                title: 'Code',
                width: '15%',
                inputClass: 'validate[required]',
            },
            relationshipValue: {
                title: 'Value',
                width: '15%',
                inputClass: 'validate[required]',
            },
        },
        // Initialize validation logic when a
        // form is created
        formCreated: function(event, data) {
            data.form.validationEngine('attach', {
                binded: false
            });
        },
        // Validate form when it is being
        // submitted
        formSubmitting: function(event, data) {
            return data.form.validationEngine('validate');
        },
        // Dispose validation logic when form is
        // closed
        formClosed: function(event, data) {
            data.form.validationEngine('hide');
            data.form.validationEngine('detach');
        },
        recordAdded: function(event, data) {
            globalRecords.push(data.record);
        }
    });
    $("#documentAddNew")
        .submit(function(e) {
            e.preventDefault();
            var data = form2js('documentAddNew', '.', false);
            data.relationships = globalRecords;
            return $.Deferred(function($dfd) {
                function success() {
                    $("#documentSearchInnerDiv tr")
                        .remove();
                    globalRecords = [];
                    $('#documentModal')
                        .modal('hide');
                    $('#documentSearchDiv')
                        .jtable('reload');
                }
                function failure() {
                    $dfd.reject();
                }
                post(baseURL + '/document/save', "POST", JSON.stringify(data), success, failure);
                $("#documentAddNew")[0].reset();
            });
        });
});