
define(['jquery', 'underscore', 'backbone', 'text!modules/editmulino/editmulinoViewTemplate.html', 'modules/base/baseView',
    'controls/window/window', 'modules/addingr/addingr', 'jqx'],
        function($, _, Backbone, editmulinoViewTemplate, BaseView, Window, AddIngrDlg) {
            var FarineEnum = {
                Tipo00:     1,
                Tipo0:      2,
                Tipo1:      4,
                Integrale:  8,
                Manitoba:  16,
                Semola:    32,
                Speciale:  64
            };

            var MacinaturaEnum = {
                Rulli:     1,
                Pietra:    2
            };

            var EditMuliniView = BaseView.extend({
                dataAdapter: undefined,
                //initialize template
                template: _.template(editmulinoViewTemplate),
                addIngrDlg: null,
                fullScrDlg: null,
                initialize: function() {
                    EditMuliniView.__super__.initialize.call(this);
                    //this.header.title = "pippo";
                },
                mulinoEditing: null,                
                checkValue: function(val, check){
                    return (val & check) == check;
                },
                openMulino: function(mulino_id) {

                    if (mulino_id)
                    {
                        var self = this;
                        $.ajax({
                            url: myManifest.Settings.DefaultURL + "/backend/mulino/body/" + mulino_id,
                            dataType: "jsonp",
                            crossDomain: true
                        }).then(function(response) {
                            var mulino = response[0];
                            self.mulinoEditing = mulino;
                            $('#jqxTabs').jqxTabs('select', 0);
                            $("#mulinoID").val(mulino.mulino_id);
                            $("#nomeMulino").val(unescape(mulino.nome));
                            $("#email").val(mulino.email);
                            $("#telefono").val(mulino.telefono);
                            $("#linkWebSite").val(mulino.linkWebSite);
                            $('#address').val(unescape(mulino.address));
                            $('#comune').val(unescape(mulino.comune));
                            $('#CAP').val(mulino.CAP);
                            $('#provincia').val(mulino.provincia);
                            $('#regione').val(mulino.regione);
                            
                            // show the popup window.
                            $("#popupWindow").jqxWindow('open');
                        });
                    }
                    else
                    {
                        $('#jqxTabs').jqxTabs('select', 0);
                        // $("#mulinoID").val('');
                        // $("#categoria").jqxDropDownList('selectIndex', -1 );
                        // $("#titolo").val('');
                        // $("#autore").val('');
                        // $("#lvlDiff").val(0);
                        // $("#linkFonte").val('');
                        // $("#linkYouTube").val('');
                        // $('#procedimento').val('');

                        $("#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 = {
                            "mulinoID": $("#mulinoID").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/mulino/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";
                    EditMuliniView.__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)
                                    {                                      
                                        $("#nomeMulino").jqxInput({placeHolder: "Nome:", width: '350px', height: 25});
                                        $("#email").jqxInput({placeHolder: "Email:", width: '350px', height: 25});
                                        $("#telefono").jqxInput({placeHolder: "Telefono:", width: '350px', height: 25});
                                        $("#linkWebSite").jqxInput({placeHolder: "Sito Web:", width: '350px', height: 25});

                                        $('#logoUpload').jqxFileUpload({ width: '50%', 
                                            fileInputName: 'image',
                                            multipleFilesUpload: false, 
                                            accept: 'image/*',
                                            uploadUrl: myManifest.Settings.DefaultURL + '/backend/photo/mulino' });

                                        $('#logoUpload').on('uploadStart', function (event) {
                                            $('form[action="' + myManifest.Settings.DefaultURL + '/backend/photo/mulino' + '"]').
                                                        append('<input type="hidden" name="mulino_name" value="' + escape($("#nomeMulino").val()) +'" />');
                                        });
                                    }
                                    else if (tab === 1)
                                    {
                                        $("#address").jqxInput({placeHolder: "Indirizzo:", width: '350px', height: 25});
                                        $("#provincia").jqxInput({placeHolder: "Provincia:", width: '350px', height: 25,
                                            source: function (query, response) {
                                                var dataAdapter = new $.jqx.dataAdapter
                                                (
                                                    {
                                                        datatype: "jsonp",
                                                        datafields:
                                                        [
                                                            { name: 'Provincia' }, 
                                                            { name: 'Regione' }
                                                        ],
                                                        url: myManifest.Settings.DefaultURL + "/profile/province/"+query
                                                    },
                                                    {
                                                        autoBind: true,
                                                        loadComplete: function (data) {
                                                            response(data);
                                                        }
                                                    }
                                                );
                                            }
                                        });
                                        $("#comune").jqxInput({placeHolder: "Comune:", width: '350px', height: 25,
                                            source: function (query, response) {
                                                var dataAdapter = new $.jqx.dataAdapter
                                                (
                                                    {
                                                        datatype: "jsonp",
                                                        datafields:
                                                        [
                                                            { name: 'Comune' }, 
                                                            { name: 'CAP' }
                                                        ],
                                                        url: myManifest.Settings.DefaultURL + "/profile/comuni/" + $("#provincia").val() + "/"+query
                                                    },
                                                    {
                                                        autoBind: true,
                                                        loadComplete: function (data) {
                                                            response(data);
                                                        }
                                                    }
                                                );
                                            }
                                        });
                                        $("#CAP").jqxInput({placeHolder: "CAP:", width: '350px', height: 25});
                                        $("#regione").jqxInput({placeHolder: "Regione:", width: '350px', height: 25});
                                    }
                                    else if (tab === 3)
                                    {
                                        $("#farine").jqxDropDownList(
                                                {
                                                    width: "250px",
                                                    height: "25px",
                                                    source: new $.jqx.dataAdapter({
                                                        datatype: 'array',
                                                        datafields: [
                                                            {name: 'value'},
                                                            {name: 'label'}
                                                        ],
                                                        localdata: [
                                                            {value: '1', label: 'Tipo00'},
                                                            {value: '2', label: 'Tipo0'},
                                                            {value: '4', label: 'Tipo1'},
                                                            {value: '8', label: 'Integrale'},
                                                            {value: '16', label: 'Manitoba'},
                                                            {value: '32', label: 'Semola'},
                                                            {value: '64', label: 'Speciale'}
                                                        ]
                                                    }),
                                                    //selectedIndex: -1,
                                                    displayMember: "label",
                                                    valueMember: "value"
                                                });
                                        $("#farSpeciali").jqxInput({placeHolder: "Farine Speciali:", width: '350px', height: 25});
                                        $("#macinatura").jqxDropDownList(
                                                {
                                                    width: "250px",
                                                    height: "25px",
                                                    source: new $.jqx.dataAdapter({
                                                        datatype: 'array',
                                                        datafields: [
                                                            {name: 'value'},
                                                            {name: 'label'}
                                                        ],
                                                        localdata: [
                                                            {value: '1', label: 'Rulli'},
                                                            {value: '2', label: 'Pietra'}
                                                        ]
                                                    }),
                                                    //selectedIndex: -1,
                                                    displayMember: "label",
                                                    valueMember: "value"
                                                });

                                        $("#prezzo").jqxSlider({height: 60, min: 0, max: 10, value: 0, step: 0.10});

                                        var text = $('#spedizione').val();
                                        $('#spedizione').jqxEditor({width: '100%', height: "20%"});
                                        if (text)
                                            $('#spedizione').jqxEditor('val', text);
                                    }
                                    else if (tab === 3)
                                    {
                                        var text = $('#procedimento').val();
                                        $('#procedimento').jqxEditor({width: '100%', height: "50%"});
                                        if (text)
                                            $('#procedimento').jqxEditor('val', text);

                                        var text = $('#note').val();
                                        $('#note').jqxEditor({width: '100%', height: "50%"});
                                        if (text)
                                            $('#note').jqxEditor('val', text);
                                    }
                                }
                            });

                            $("#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});
                        }
                    });
                    return this;
                }
            });
            return EditMuliniView;
        });