define(['jquery', 'underscore', 'backbone', 'text!modules/editricetta/editricettaViewTemplate.html', 'modules/base/baseView',
    'controls/window/window', 'modules/addingr/addingr', 'jqxbuttons', 'jqxgrid', 'jqxcombobox', 'jqxdata', 'jqxdropdownlist',
    'jqxgrid', 'jqxgrid_selection', 'jqxgrid_columnsresize', 'jqxgrid_filter',
    'jqxtabs', 'jqxeditor', 'jqxinput', 'jqxrating', 'jqxnumberinput', 'jqxlistbox'],
        function($, _, Backbone, editricettaViewTemplate, BaseView, Window, AddIngrDlg) {

            var EditRicetteView = BaseView.extend({
                dataAdapter: undefined,
                //initialize template
                template: _.template(editricettaViewTemplate),
                addIngrDlg: null,
                initialize: function() {
                    EditRicetteView.__super__.initialize.call(this);
                    //this.header.title = "pippo";
                },
                ricettaEditing: null,
                openRicetta: function(ricetta_id) {

                    if (ricetta_id)
                    {
                        var self = this;
                        $.ajax({
                            url: myManifest.Settings.DefaultURL + "/backend/ricetta/body/" + ricetta_id,
                            dataType: "jsonp",
                            crossDomain: true
                        }).then(function(response) {
                            var ricetta = response[0];
                            self.ricettaEditing = ricetta;
                            $('#jqxTabs').jqxTabs('select', 0);
                            $("#ricettaID").val(ricetta.ricetta_id);
                            $("#categoria").val(ricetta.id_categoria);
                            $("#titolo").val(unescape(ricetta.titolo));
                            $("#autore").val(unescape(ricetta.autore));
                            $("#lvlDiff").val(ricetta.difficolta);
                            $("#linkFonte").val(ricetta.link_fonte);
                            $("#linkYouTube").val(ricetta.link_youtube);
                            $('#procedimento').val(ricetta.procedimento);

                            $("#listbox").jqxListBox({source: ricetta.ingredienti, itemHeight: 30, height: '90%', width: '100%', theme: 'arctic'});

                            // show the popup window.
                            $("#popupWindow").jqxWindow('open');
                        });
                    }
                    else
                    {
                        $('#jqxTabs').jqxTabs('select', 0);
                        $("#ricettaID").val('');
                        $("#categoria").jqxDropDownList('selectIndex', -1 );
                        $("#titolo").val('');
                        $("#autore").val('');
                        $("#lvlDiff").val(0);
                        $("#linkFonte").val('');
                        $("#linkYouTube").val('');
                        $('#procedimento').val('');

                        $("#listbox").jqxListBox({source: []});
                        $("#popupWindow").jqxWindow('open');
                    }
                },
                validate: function()
                {
                    if ($("#categoria").val() > 0 &&
                            $("#titolo").val() !== "")
                        return true;
                    return false;
                },
                //render the content into div of view
                render: function() {
                    //this.header.title = "pippo";
                    EditRicetteView.__super__.render.call(this);
                    var self = this;

                    this.$el.append(this.template());

                    this.$el.find("#popupWindow").jqxWindow({
                        width: "750px",
                        height: "500px",
                        resizable: true,
                        isModal: true,
                        autoOpen: false,
                        cancelButton: this.$el.find("#Cancel"),
                        modalOpacity: 0.01,
                        initContent: function() {
                            $('#jqxTabs').jqxTabs({
                                width: '100%',
                                height: "90%",
                                position: 'top',
                                initTabContent: function(tab) {
                                    if (tab === 0)
                                    {
                                        // get the clicked row's data and initialize the input fields.
                                        var source =
                                                {
                                                    datatype: "jsonp",
                                                    datafields: [
                                                        {name: 'category_id'},
                                                        {name: 'name'}
                                                    ],
                                                    url: myManifest.Settings.DefaultURL + "/backend/categories",
                                                    data: {
                                                    }
                                                };
                                        var dataAdapter = new $.jqx.dataAdapter(source);
                                        $("#categoria").on('bindingComplete', function (event) {                                             
                                            if(self.ricettaEditing !== null)
                                                $("#categoria").val(self.ricettaEditing.id_categoria);
                                        });
                                        $("#categoria").jqxDropDownList(
                                                {
                                                    width: "350px",
                                                    height: "25px",
                                                    source: dataAdapter,
                                                    //selectedIndex: -1,
                                                    displayMember: "name",
                                                    valueMember: "category_id"
                                                });                                        
                                        $("#titolo").jqxInput({placeHolder: "Titolo:", width: '350px', height: 25});
                                        $("#autore").jqxInput({
                                            placeHolder: "Autore:", width: '350px', height: 25,
                                            source: function (query, response) {
                                                var dataAdapter = new $.jqx.dataAdapter
                                                (
                                                    {
                                                        datatype: "jsonp",
                                                        datafields: [
                                                            {name: 'autore'}
                                                        ],
                                                        url: myManifest.Settings.DefaultURL + "/api/ricette/authors/" + query,
                                                        data: {
                                                        }
                                                    },
                                                    {
                                                        autoBind: true,
                                                        loadComplete: function (data) {
                                                            if (data.length > 0) {
                                                                response($.map(data, function (item) {
                                                                    return {
                                                                        label: item.autore,
                                                                        value: item.autore
                                                                    };
                                                                }));
                                                            }
                                                        }
                                                    }
                                                );
                                            }
                                        });
                                        $("#lvlDiff").jqxRating({width: 350, height: 35, theme: 'classic'});
                                        $("#linkFonte").jqxInput({placeHolder: "Link Fonte:", width: '350px', height: 25});
                                        $("#linkYouTube").jqxInput({placeHolder: "Link Youtube:", width: '350px', height: 25});
                                    }
                                    else if (tab === 1)
                                    {
                                        $("#add").jqxButton({width: '37%'});
                                        $("#remove").jqxButton({disabled: true, width: '37%'});

                                        $('#add').on('click', function() {
                                            self.addIngrDlg.openDlg();
                                        });

                                        $('#remove').on('click', function() {
                                            var indexSelected = $('#listbox').jqxListBox('getSelectedIndex');

                                            var items = $("#listbox").jqxListBox('source');
                                            items.splice(indexSelected, 1);

                                            $("#listbox").jqxListBox('source', items);
                                        });

                                        $("#up").jqxButton({disabled: true, width: '8%'});
                                        $("#down").jqxButton({disabled: true, width: '8%'});
                                        $('#up').on('click', function() {
                                            var indexSelected = $('#listbox').jqxListBox('getSelectedIndex');

                                            var items = $("#listbox").jqxListBox('source');
                                            items.move(indexSelected, indexSelected - 1);

                                            $("#listbox").jqxListBox('source', items);

                                            $("#listbox").jqxListBox('selectIndex', indexSelected - 1);
                                        });

                                        $('#down').on('click', function() {
                                            var indexSelected = $('#listbox').jqxListBox('getSelectedIndex');

                                            var items = $("#listbox").jqxListBox('source');
                                            items.move(indexSelected, indexSelected + 1);

                                            $("#listbox").jqxListBox('source', items);

                                            $("#listbox").jqxListBox('selectIndex', indexSelected + 1);
                                        });

                                        var dataAdapter = $('#listbox').jqxListBox('source');

                                        if (dataAdapter === undefined)
                                        {
                                            source = {
                                                localdata: [],
                                                datafields: [
                                                    {name: 'id_tipo_ingredienti'},
                                                    {name: 'id_tipo_quantita'},
                                                    {name: 'nome_ingrediente'},
                                                    {name: 'note'},
                                                    {name: 'posizione'},
                                                    {name: 'quantita'},
                                                    {name: 'unita'}
                                                ],
                                                datatype: "array"
                                            };

                                            dataAdapter = new $.jqx.dataAdapter(source);
                                        }

                                        $('#listbox').jqxListBox({
                                            //allowDrag: true, 
                                            source: dataAdapter, itemHeight: 30, height: '90%', width: '100%', theme: 'arctic',
                                            renderer: function(index, label, value) {
                                                var datarecord = this.source[index];
                                                if (datarecord)
                                                {
                                                    var div = '';
                                                    if (datarecord.id_tipo_ingredienti === "22")
                                                    {
                                                        div = '<div><b>' + datarecord.nome_ingrediente + '</b>: <i>' + unescape(datarecord.note) + '</i></div>';
                                                    }
                                                    else
                                                    {
                                                        div = '<div><b>' + datarecord.nome_ingrediente + '</b>: ' + datarecord.quantita + ' ' + datarecord.unita + ' <i>' + unescape(datarecord.note) + '</i></div>';
                                                    }
                                                    return div;
                                                }
                                                return "";
                                            },
                                            dragEnd: function(dragItem, dropItem) {
                                                this.source.move(dragItem.index, dropItem.index);
                                                return true;
                                            }
                                        });

                                        $('#listbox').on('select', function(event) {
                                            var args = event.args;
                                            if (args) {
                                                $("#remove").jqxButton({disabled: false});
                                                if (args.index === 0)
                                                {
                                                    $("#up").jqxButton({disabled: true});
                                                    $("#down").jqxButton({disabled: false});
                                                }
                                                else if (args.index === event.owner.source.length - 1)
                                                {
                                                    $("#up").jqxButton({disabled: false});
                                                    $("#down").jqxButton({disabled: true});
                                                }
                                                else
                                                {
                                                    $("#up").jqxButton({disabled: false});
                                                    $("#down").jqxButton({disabled: false});
                                                }
                                            }
                                        });
                                        $('#listbox').on('unselect', function(event) {
                                            var args = event.args;
                                            if (args) {
                                                $("#remove").jqxButton({disabled: true});
                                            }
                                        });
                                    }
                                    else if (tab === 2)
                                    {
                                        var text = $('#procedimento').val();
                                        $('#procedimento').jqxEditor({width: '100%', height: "100%"});
                                        if (text)
                                            $('#procedimento').jqxEditor('val', text);
                                    }
                                }
                            });

                            $("#Save").jqxButton({width: '48%', height: 40});

                            $('#Save').on('click', function() {
                                if (self.validate()) {
                                    var diffi = $('#lvlDiff').val();

                                    var ingr = $('#listbox').jqxListBox('source');

                                    var sendobj = {
                                        "ricettaID": $("#ricettaID").val(),
                                        "categoria_id": $("#categoria").val(),
                                        "titolo": escape($("#titolo").val()),
                                        "ingredienti": [],
                                        "preparazione": $("#procedimento").val(),
                                        "autore": escape($("#autore").val()),
                                        "linkFonte": $("#linkFonte").val(),
                                        "linkVideo": $("#linkYouTube").val(),
                                        "difficolta": diffi
                                    };

                                    $.each(ingr, function(i, val) {
                                        var newItem = {
                                            "ingrediente_id": val.id_tipo_ingredienti,
                                            "quantita": val.quantita,
                                            "tipo_quantita_id": val.id_tipo_quantita,
                                            "note": escape(val.note)
                                        };
                                        sendobj.ingredienti.push(newItem);
                                    });

                                    $.ajax({
                                        url: myManifest.Settings.DefaultURL + "/backend/ricetta/body",
                                        //dataType: "json",
                                        type: 'POST',
                                        data: {bodydata: JSON.stringify(sendobj)}
                                    }).then(function(response) {
                                        var msg = response;
                                        alert(msg.message);
                                        if (msg.result)
                                            $("#popupWindow").jqxWindow('close');
                                    });
                                }
                                else
                                    alert("Inserire almeno categoria e titolo");
                            });

                            $("#Cancel").jqxButton({width: '48%', height: 40});
                        }
                    });
//                    
//                    $('#popupWindow').on('resized', function (event) {
//                        $('#procedimento').jqxEditor({width: '100%', height: 380});
//                    }); 


                    this.addIngrDlg = new AddIngrDlg();
                    this.$el.find("#content").append(this.addIngrDlg.$el);

                    this.addIngrDlg.render();

                    this.addIngrDlg.addBtnFn = function(item) {
                        var items = $("#listbox").jqxListBox('source');
                        items.push(item);
                        $("#listbox").jqxListBox('source', items);
                    };

                    return this;
                }
            });
            return EditRicetteView;
        });