
define(['jquery', 'underscore', 'backbone', 'text!modules/editricetta/editricettaViewTemplate.html', 'modules/base/baseView',
    'controls/window/window', 'modules/addingr/addingr', 'jqx'],
        function($, _, Backbone, editricettaViewTemplate, BaseView, Window, AddIngrDlg) {

            var EditRicetteView = BaseView.extend({
                dataAdapter: undefined,
                //initialize template
                template: _.template(editricettaViewTemplate),
                addIngrDlg: null,
                fullScrDlg: 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'});

                            var photoFields = [
                                {name: 'id_photo', type: 'int'},
                                {name: 'type_format', type: 'string'},
                                {name: 'from_profile_id', type: 'string'},
                                {name: 'uploaded_date', type: 'datetime'},
                                {name: 'profile_name', type: 'string'},
                                {name: 'published', type: 'bool'},
                                {name: 'bCover', type: 'bool'}
                            ];
                            var photoAdapter = new $.jqx.dataAdapter({
                                datatype: "jsonp",
                                datafields: photoFields,
                                id: 'id_photo',
                                url: myManifest.Settings.DefaultURL + "/backend/ricetta/" + ricetta_id + "/photos",
                                data: {
                                }
                            });

                            $("#gridPhotos").jqxGrid({
                                            source: photoAdapter});

                            // 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;
                },
                save:function(callback)
                {
                    if (this.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(unescape(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) {
                            if(callback)
                                callback(response);
                        });
                    }
                    else
                        alert("Inserire almeno categoria e titolo");
                },
                //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() {
                            $('#listbox').jqxListBox({
                                renderer: function(index, label, value) {
                                    var datarecord = this.source[index];
                                    if (datarecord)
                                    {
                                        datarecord.note = unescape(datarecord.note);
                                        var div = '';
                                        if (datarecord.id_tipo_ingredienti === "22" || datarecord.id_tipo_ingredienti === "152")
                                        {
                                            div = '<div><b>' + datarecord.nome_ingrediente + '</b>: <i>' + datarecord.note + '</i></div>';
                                        }
                                        else
                                        {
                                            div = '<div><b>' + datarecord.nome_ingrediente + '</b>: ' + datarecord.quantita + ' ' + datarecord.unita + ' <i>' + datarecord.note + '</i></div>';
                                        }
                                        return div;
                                    }
                                    return "";
                                },
                                dragEnd: function(dragItem, dropItem) {
                                    this.source.move(dragItem.index, dropItem.index);
                                    return true;
                                }
                            });

                            $('#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: unescape(item.autore),
                                                                        value: unescape(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: '22%'});
                                        $("#remove").jqxButton({disabled: true, width: '22%'});
										$("#modify").jqxButton({disabled: true, width: '22%'});

                                        $('#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);
                                        });
										
										$('#modify').on('click', function() {
                                            var indexSelected = $('#listbox').jqxListBox('getSelectedIndex');

                                            var items = $("#listbox").jqxListBox('source');
                                            var item = items[indexSelected];

                                            self.addIngrDlg.openDlg(indexSelected, item);
                                        });

                                        $("#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'
                                        });

                                        $('#listbox').on('select', function(event) {
                                            var args = event.args;
                                            if (args) {
												$("#modify").jqxButton({disabled: false});
                                                $("#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});
												$("#modify").jqxButton({disabled: true});
                                            }
                                        });
                                    }
                                    else if (tab === 2)
                                    {
                                        var text = $('#procedimento').val();
                                        $('#procedimento').jqxEditor({width: '100%', height: "100%"});
                                        if (text)
                                            $('#procedimento').jqxEditor('val', text);
                                    }
                                    else if (tab === 3)
                                    {
                                        var source =
                                                {
                                                    datatype: "jsonp",
                                                    datafields: [
                                                    {name: 'id'},
                                                        {name: 'name'}
                                                    ],
                                                    url: myManifest.Settings.DefaultURL + "/backend/profiles",
                                                    data: {
                                                    }
                                                };
                                        var dataAdapter = new $.jqx.dataAdapter(source);
                                        $("#autorePhoto").jqxDropDownList(
                                                {
                                                    width: "250px",
                                                    height: "25px",
                                                    source: dataAdapter,
                                                    //selectedIndex: -1,
                                                    displayMember: "name",
                                                    valueMember: "id"
                                                });
                                        $('#jqxFileUpload').jqxFileUpload({ width: '50%', 
                                            fileInputName: 'image',
                                            multipleFilesUpload: false, 
                                            accept: 'image/*',
                                            uploadUrl: myManifest.Settings.DefaultURL + '/backend/photo' });

                                        $('#jqxFileUpload').on('uploadStart', function (event) {
                                            self.save(function(msg){
                                                //alert(msg.message);
                                                if (msg.result)
                                                {
                                                    if($("#ricettaID").val() == "")
                                                        $("#ricettaID").val(msg.ricettaID);

                                                    var profileID = "10203753344023406";

                                                    if($("#autorePhoto").val() != 0)
                                                        profileID = $("#autorePhoto").val();

                                                    $('form[action="' + myManifest.Settings.DefaultURL + '/backend/photo' + '"]').
                                                        append('<input type="hidden" name="ricetta_id" value="' + msg.ricettaID +'" />').
                                                        append('<input type="hidden" name="keyStore" value="' + profileID + '" />');
                                                }
                                            });
                                        });
                                        $('#jqxFileUpload').on('uploadEnd', function (event) {
                                            $("#gridPhotos").jqxGrid('updatebounddata');
                                        });
                                        $("#gridPhotos").jqxGrid({
                                            width: "100%",
                                            height: "100%",
                                            //source: photoAdapter,
                                            rowsheight: 100,
                                            //filterable: true,
                                            autoshowfiltericon: true,
                                            columns: [
                                                {text: 'Autore', dataField: 'profile_name', width: "170px"},
                                                {text: 'Image', dataField: 'image', height: "100px",
                                                    cellsrenderer: function(index, datafield, value, defaultvalue, column, rowdata) {
                                                        return '<center><img style="margin-left: 5px;height: 100px;" src="' + myManifest.Settings.DefaultURL + '/api/photo/thumbnail/' + rowdata.id_photo + '"/></center>';
                                                    }
                                                },
                                                {text: 'Published', editable: false, dataField: 'published', width: "70px",
                                                    cellsrenderer: function(index, datafield, value, defaultvalue, column, rowdata) {
                                                        var valueBool = rowdata.published;
                                                        return "<div style='margin: 4px;' class='jqx-center-align'>" + valueBool + "</div>";
                                                    }
                                                },
                                                {text: 'Cover', editable: false, dataField: 'bCover', width: "70px",
                                                    cellsrenderer: function(index, datafield, value, defaultvalue, column, rowdata) {
                                                        var valueBool = rowdata.bCover;
                                                        return "<div style='margin: 4px;' class='jqx-center-align'>" + valueBool + "</div>";
                                                    }
                                                },
                                                {text: '', datafield: 'FullView', columntype: 'button', width: '10%',
                                                    cellsrenderer: function() {
                                                        return "View Full";
                                                    },
                                                    buttonclick: function(row) {
                                                        var items = $("#gridPhotos").jqxGrid('source');
                                                        var item = items.records[row];
                                                        self.fullScrDlg.$el.find('#imgFullScr').attr('src', myManifest.Settings.DefaultURL + '/api/photo/' + item.id_photo);
                                                        self.fullScrDlg.open();
                                                    }
                                                },
                                                {text: '', datafield: 'Pubblica', columntype: 'button', width: '10%',
                                                    cellsrenderer: function() {
                                                        return "Pubblica";
                                                    },
                                                    buttonclick: function(row) {
                                                        var items = $("#gridPhotos").jqxGrid('source');
                                                        var item = items.records[row];
                                                        if(item.published === false)
                                                        {
                                                            $.ajax({
                                                                url: myManifest.Settings.DefaultURL + "/backend/photo/publish/" + item.id_photo,
                                                                //dataType: "json",
                                                                type: 'GET'
                                                            }).then(function (response) {
                                                                $("#gridPhotos").jqxGrid('updatebounddata');
                                                            });
                                                        }
                                                    }
                                                },
                                                {text: '', datafield: 'Cover', columntype: 'button', width: '10%',
                                                    cellsrenderer: function() {
                                                        return "Copertina";
                                                    },
                                                    buttonclick: function(row) {
                                                        var items = $("#gridPhotos").jqxGrid('source');
                                                        var item = items.records[row];
                                                        if(item.bCover === false)
                                                        {
                                                            $.ajax({
                                                                url: myManifest.Settings.DefaultURL + "/backend/photo/set_cover/" + item.id_photo,
                                                                //dataType: "json",
                                                                type: 'GET'
                                                            }).then(function (response) {
                                                                $("#gridPhotos").jqxGrid('updatebounddata');
                                                            });
                                                        }
                                                    }
                                                },
                                                {text: '', datafield: 'Cancella', columntype: 'button', width: '10%',
                                                    cellsrenderer: function() {
                                                        return "Cancella";
                                                    },
                                                    buttonclick: function(row) {
                                                        var items = $("#gridPhotos").jqxGrid('source');
                                                        var item = items.records[row];
                                                        $.ajax({
                                                            url: myManifest.Settings.DefaultURL + "/backend/photo/" + item.id_photo,
                                                            //dataType: "json",
                                                            type: 'DELETE'
                                                        }).then(function (response) {
                                                            $("#gridPhotos").jqxGrid('updatebounddata');
                                                        });
                                                    }
                                                }
                                            ]
                                        });
                                    }
                                }
                            });

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

                            $('#Save').on('click', function() {
                                self.save(function(msg){
                                    alert(msg.message);
                                    if (msg.result)
                                        $("#popupWindow").jqxWindow('close');
                                });
                            });

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


                    this.fullScrDlg = new Window({
                        title: "Foto Full Screen",
                        width: "600px",
                        height: "600px",
                        margin_top: "50px",
                        id: "fullScrDlg",
                        showCloseButton: true,
                        resizable: true,
                        isModal: true,
                        autoOpen: false,
                        content: "<img id='imgFullScr' style='margin-left: 5px;width: 565px;' src='' />",
                        initContentFn: null                
                    });

                    self.$el.find("#content").append(this.fullScrDlg.$el);
                    this.fullScrDlg.render();

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

                    this.addIngrDlg.render();

                    this.addIngrDlg.addBtnFn = function(index, item) {
                        var items = $("#listbox").jqxListBox('source');
						if(index === null){
							items.push(item);
						}
						else
						{
							items.splice(index, 1, item);
						}
                        $("#listbox").jqxListBox('source', items);
                    };

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