/*********************************************************************************
 * The content of this file is subject to the ITS4YouKanbanView license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is IT-Solutions4You s.r.o.
 * Portions created by IT-Solutions4You s.r.o. are Copyright(C) IT-Solutions4You s.r.o.
 * All Rights Reserved.
 ********************************************************************************/

jQuery.Class("ITS4YouKanbanView_ITS4YouKanbanView_Js", {}, {
    getModuleName : function(){
        return "ITS4YouKanbanView";
    },
    clearExistingCustomScroll : function(){},
    registerTaskDragEvent: function () {
        var container = jQuery('#taskManagementContainer');
        container.find('.ui-draggable').draggable({
            appendTo: ".data-body",
            helper: "clone",
            cursor: 'move',
            drag:function(e, ui) {
                ui.helper.css({
                    'width': '15%',
                    'background-color':'white',
                    'height':'auto'
                });
            }
        });
    },
    registerTaskDropEvent: function() {
        var thisInstance = this;
        var container = jQuery('#taskManagementContainer');
        var colors = JSON.parse(jQuery('input[name="colors"]').val());
        container.find(".ui-droppable").droppable({
            'accept' : '.ui-draggable',
            drop: function( event, ui ) {
                var currentBlock = jQuery(this);
                var picklistValueName = currentBlock.find('.content').data("picklist_value_name");

                var draggedElement = jQuery(ui.draggable);
                var draggedElementTask = draggedElement.find(".task");
                var draggedElementPicklistValueName = draggedElementTask.data("picklist_value_name");

                var draggedElementHeaderSpan = jQuery(draggedElement).closest('div.content').siblings('div.header').find('.title').find('span');
                var draggedElementCountOfItems = draggedElementHeaderSpan.data('coi');
                var newDraggedElementCountOfItems = draggedElementCountOfItems - 1;
                draggedElementHeaderSpan.html(newDraggedElementCountOfItems);
                draggedElementHeaderSpan.data("coi", newDraggedElementCountOfItems);

                var currentBlockHeaderSpan = currentBlock.find('.title').find('span');
                var oldCountOfItemsInCurrentBlock = currentBlockHeaderSpan.data('coi');
                var newCountOfItemsInCurrentBlock = oldCountOfItemsInCurrentBlock + 1;
                currentBlockHeaderSpan.data('coi', newCountOfItemsInCurrentBlock);
                currentBlockHeaderSpan.html(newCountOfItemsInCurrentBlock);

                var color = colors[picklistValueName];

                if (draggedElementPicklistValueName !== picklistValueName) {
                    var draggedElementrecordID = draggedElementTask.data("recordid");
                    var fieldNameValueMap = {
                        "task_picklist_value_name" : picklistValueName,
                    };

                    var progressIndicatorElement = jQuery.progressIndicator({
                        'position' : 'html',
                        'blockInfo' : {
                            'enabled' : true
                        }
                    });

                    thisInstance.saveFieldValue(draggedElementrecordID, fieldNameValueMap).then(
                        function (data) {
                            progressIndicatorElement.progressIndicator({'mode': 'hide'});
                            draggedElementTask.attr("data-picklist_value_name",picklistValueName).data('picklist_value_name',picklistValueName);
                            draggedElementTask.css({"border-left":"4px solid " + color});
                            currentBlock.find("."+picklistValueName.replace(/[\ \.]/g, '-').toLowerCase()+"-entries").prepend(draggedElement);

                            thisInstance.updateRecordContent(draggedElementrecordID);
                        }
                    );
                }
            }
        });
    },
    saveFieldValue : function (recordId, fieldNameValueMap) {
        var aDeferred = jQuery.Deferred();

        var data = {};
        if(typeof fieldNameValueMap != 'undefined'){
            data = fieldNameValueMap;
        }

        data['record'] = recordId;
        data['module'] = this.getModuleName();
        data['source_module'] = jQuery('#source_module_name').val();
        data['action'] = 'SaveAjax';

        AppConnector.request(data).then(
            function (responseData) {
                Vtiger_Helper_Js.showMessage({
                    text:app.vtranslate('JS_RECORD_MOVED_SUCCESSFULLY'),
                    type: 'success'
                });
                aDeferred.resolve(responseData);
            },
            function (error) {
                Vtiger_Helper_Js.showMessage({
                    text: error,
                    type: 'error'
                });
            }
        );

        return aDeferred.promise();
    },
    updateRecordContent: function (recordId) {
        var aDeferred = jQuery.Deferred();

        var data = {};
        data['record'] = recordId;
        data['module'] = this.getModuleName();
        data['source_module'] = jQuery('#source_module_name').val();
        data['view'] = 'AjaxRecordContent';

        AppConnector.request(data).then(
            function (responseData) {
                var recordDetail = jQuery('#kanbanRecordContent_'+recordId);
                recordDetail.empty();
                recordDetail.html(responseData);
                Vtiger_Index_Js.registerTooltipEvents();
                aDeferred.resolve(responseData);
            },
            function (error) {
                Vtiger_Helper_Js.showMessage({
                    text:error,
                    type: 'error'
                });
            }
        );

        return aDeferred.promise();
    },
    registerQuickPreview : function() {},
    registerChangeCustomViewEvent: function () {
        var thisInstance = this;
        var sourceModuleName = jQuery('#source_module_name').val();
        var moduleName = app.getModuleName();

        jQuery('#moduleFilters').change(function () {
            var viewId = jQuery(this).val();
            var content = jQuery('.datacontent');

            var progressIndicatorElement = jQuery.progressIndicator({
                'position' : 'html',
                'blockInfo' : {
                    'enabled' : true
                }
            });

            var params = {
                'module': moduleName,
                'view': 'List',
                'sourceModule': sourceModuleName,
                'viewname': viewId
            };

            AppConnector.request(params).then(
                function (response) {
                    content.empty();
                    content.html(response);
                    progressIndicatorElement.progressIndicator({'mode': 'hide'});
                    thisInstance.registerTaskDragEvent();
                    thisInstance.registerTaskDropEvent();
                    thisInstance.registerQuickPreview();
                    Vtiger_Index_Js.registerTooltipEvents();
                },
                function (error) {
                }
            );
        });
    },
    registerTooltipEvents: function() {
        var references = jQuery.merge(jQuery('[data-field-type="reference"] > a'), jQuery('[data-field-type="multireference"] > a'));
    },
    registerEvents : function () {
        var thisInstance = this;
        thisInstance.registerTaskDragEvent();
        thisInstance.registerTaskDropEvent();
        thisInstance.registerQuickPreview();
        thisInstance.registerChangeCustomViewEvent();
        thisInstance.registerTooltipEvents();
        app.showScrollBar(jQuery('.scrollableTab'), {'width': '100%', 'height':'600px'});
    }
});

jQuery(document).ready(function () {
    var instance = new ITS4YouKanbanView_ITS4YouKanbanView_Js();
    instance.registerEvents();
});