define(['jquery', 'underscore', 'backbone','text!modules/settings/settingsViewTemplate.html', 'modules/base/baseView', 'classes/profile'],
    function($, _, Backbone, settingsViewTemplate, BaseView, Profile){

        var SettingsView = BaseView.extend({

            //initialize template
            template:_.template(settingsViewTemplate),
            _flagSave: false,

            initialize: function () {
                var self = this;
                this.id = "SettingsView";
                SettingsView.__super__.initialize.call(this);                
            },

            events: {
                "click #saveBtn": "saveBtn",
                "change #spacc-PMChk": "spaccPMClick",
                "change #stato": "statoChange"
            },

            statoChange: function(){
                if(this.$el.find('#stato').val() !== "ITALIA")
                {
                    this.$el.find('#provTxt').parent().show();
                    this.$el.find('#prov').parent().hide();
                }
                else
                {
                    this.$el.find('#provTxt').parent().hide();
                    this.$el.find('#prov').parent().show();
                }
            },

            saveBtn:function(e){
                var self = this;

                if(self._flagSave)
                    return;

                self._flagSave = true;
                e.preventDefault();
                Profile.data.risRic = this.$el.find('#nResult').val();
                Profile.data.tema = this.$el.find('#theme').val();
                if($('#mapSpacc').is(':visible'))
                {
                    Profile.data.isSpacc = this.$el.find('#spacc-PMChk').prop('checked')?"1":"0";
                    if(Profile.data.isSpacc==="1")
                    {
                        Profile.data.email = this.$el.find('#email').val();
                        Profile.data.dataSpacc.stato = this.$el.find('#stato').val();
                        if(this.$el.find('#stato').val() !== "ITALIA"){
                            Profile.data.dataSpacc.provincia = this.$el.find('#provTxt').val();
                        }
                        else{
                            Profile.data.dataSpacc.provincia = this.$el.find('#prov').val();
                        }
                        
                        Profile.data.dataSpacc.comune = this.$el.find('#comune').val();
                        Profile.data.dataSpacc.cap = this.$el.find('#CAP').val();
                        Profile.data.dataSpacc.tipopm = this.$el.find('#tPM').val();
                        Profile.data.dataSpacc.note = this.$el.find('#note').val();
                        Profile.data.dataSpacc.privacy = this.$el.find('#privacyChk').prop('checked')?"1":"0";

                        if(Profile.data.email === "" ||
                            Profile.data.dataSpacc.stato === "" ||
                           Profile.data.dataSpacc.provincia === "" ||
                           Profile.data.dataSpacc.comune === "" ||
                           Profile.data.dataSpacc.cap === "" ||
                           Profile.data.dataSpacc.tipopm === "")
                        {
                            self.$el.find('#titlePopup').html("Campi obbligatori");
                            self.$el.find('#messaggio').html("<center><h1 style='color: red;'>ATTENZIONE</h1> devono essere settate tutte i campi</center>");                            
                            self.$el.find('#popupDialog').popup("open");
                            self._flagSave = false;
                            return;
                        }

                        if(Profile.data.dataSpacc.privacy==="0")
                        {
                            self.$el.find('#titlePopup').html("Informativa privacy");
                            self.$el.find('#messaggio').html("<center><h1 style='color: red;'>ATTENZIONE</h1> per proseguire è obbligatorio accettare l'informativa privacy</center>");
                            self.$el.find('#popupDialog').popup("open");
                            self._flagSave = false;
                            return;
                        }

                        $.ajax({
                            url: "http://maps.google.com/maps/api/geocode/json?address=" + 
                                        Profile.data.dataSpacc.comune + "+" + 
                                        Profile.data.dataSpacc.cap + "+" + 
                                        Profile.data.dataSpacc.provincia + "+" + Profile.data.dataSpacc.stato + "&sensor=false",
                            Type: "GET"
                        }).then(function ( response ) {
                            if(response.results.length > 0)
                            {
                               Profile.data.dataSpacc.lat = response.results[0].geometry.location.lat;
                               Profile.data.dataSpacc.long = response.results[0].geometry.location.lng;                               
                            }
                            
                            if(Profile.data.dataSpacc.lat === "" && 
                               Profile.data.dataSpacc.long === ""){
                                self._flagSave = false;
                                return;
                            }

                            Profile.updateProfile(function(){
                                self._flagSave = false;       
                                self.$el.find('#titlePopup').html("Salvataggio");                             
                                self.$el.find('#messaggio').html("Impostazioni salvate con successo");
                                self.$el.find('#popupDialog').popup("open");
                            });
                        });
                    }
                    else
                    {
                        Profile.updateProfile(function(){
                            self._flagSave = false;       
                            self.$el.find('#titlePopup').html("Salvataggio");                             
                            self.$el.find('#messaggio').html("Impostazioni salvate con successo");
                            self.$el.find('#popupDialog').popup("open");
                        });
                    }
                }                
                else
                {
                    Profile.updateProfile(function(){
                        self._flagSave = false;
                        self.$el.find('#titlePopup').html("Salvataggio");
                        self.$el.find('#messaggio').html("Impostazioni salvate con successo");
                        self.$el.find('#popupDialog').popup("open");
                        //Backbone.history.loadUrl(Backbone.history.getFragment());
                    });
                }
            },
            onShowed: function(){
                var self = this;
                if(Profile.data.isSpacc==="0"){
                    this.$el.find('#mapSpacc > :not(.ui-checkbox:has(#spacc-PMChk))').hide();
                }
                else
                    this.$el.find('#mapSpacc > :not(.ui-checkbox:has(#spacc-PMChk))').show();

                if(this.$el.find('#stato').val() !== "ITALIA")
                {
                    this.$el.find('#provTxt').parent().show();
                    this.$el.find('#prov').parent().hide();
                }
                else
                {
                    this.$el.find('#provTxt').parent().hide();
                    this.$el.find('#prov').parent().show();
                }

                $( "#autocomplete_comune" ).on( "filterablebeforefilter", function ( e, data ) {
                    if(self.$el.find('#stato').val() !== "ITALIA")
                        return;

                        var $ul = $( this ),
                            $input = $( data.input ),
                            value = $input.val(),
                            html = "";
                        $ul.html( "" );
                        if ( value && value.length > 0 ) {
                            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
                            $ul.listview( "refresh" );
                            $.ajax({
                                url: myManifest.Settings.DefaultURL + "/api/profile/comuni/" + self.$el.find('#prov').val() + "/" + $input.val(),
                                Type: "GET"
                            })
                            .then( function ( response ) {
                                $.each( response, function ( i, val ) {
                                    html += "<li>" + unescape(val.Comune) + "<input id='hdnCAP" + i + "'' type='hidden' value='" + val.CAP + "'></li>";
                                });
                                $ul.html( html );
                                $ul.listview( "refresh" );
                                $ul.trigger( "updatelayout");
                                $ul.find('li').on("click", function(e){
                                    $input.val($(this).text());
                                    self.$el.find('#CAP').val($(this).find(":hidden").val());
                                    $ul.html( "" );
                                    $ul.listview( "refresh" );
                                    $ul.trigger( "updatelayout");
                                });
                            });
                        }
                    });
            },

            spaccPMClick: function(e){
                if(this.$el.find('#spacc-PMChk').prop('checked')){
                    this.$el.find('#mapSpacc > :not(.ui-checkbox:has(#spacc-PMChk))').show();
                }
                else
                    this.$el.find('#mapSpacc > :not(.ui-checkbox:has(#spacc-PMChk))').hide();

                if(this.$el.find('#stato').val() !== "ITALIA")
                {
                    this.$el.find('#provTxt').parent().show();
                    this.$el.find('#prov').parent().hide();
                }
                else
                {
                    this.$el.find('#provTxt').parent().hide();
                    this.$el.find('#prov').parent().show();
                }
            },

            //render the content into div of view
            render: function(){
                if(this.created === true)
                {
                    SettingsView.__super__.render.call(this);
                    //this.el is the root element of Backbone.View. By default, it is a div.
                    //$el is cached jQuery object for the view's element.
                    //append the compiled template into view div container
                    this.$el.append(this.header.$el);
                    this.$el.append(this.template());
                    this.$el.append(this.footer.$el);
                }

                this.$el.find('#nResult').val(Profile.data.risRic);
                this.$el.find('#theme').val(Profile.data.tema);

                this.$el.find('#spacc-PMChk').prop('checked', Profile.data.isSpacc==="0"?false:true);
                this.$el.find('#email').val(Profile.data.email);
                this.$el.find('#stato').val(Profile.data.dataSpacc.stato);
                this.$el.find('#provTxt').parent().hide();
                this.$el.find('#prov').parent().hide();
                if(this.$el.find('#stato').val() !== "ITALIA")
                {
                    this.$el.find('#provTxt').parent().show();
                    this.$el.find('#prov').parent().hide();
                    this.$el.find('#provTxt').val(Profile.data.dataSpacc.provincia);
                }
                else
                {
                    this.$el.find('#provTxt').parent().hide();
                    this.$el.find('#prov').parent().show();
                    this.$el.find('#prov').val(Profile.data.dataSpacc.provincia);
                }
                
                this.$el.find('#comune').val(Profile.data.dataSpacc.comune);
                this.$el.find('#CAP').val(Profile.data.dataSpacc.cap);
                this.$el.find('#note').val(Profile.data.dataSpacc.note);
                this.$el.find('#tPM').val(Profile.data.dataSpacc.tipopm);
                this.$el.find('#privacyChk').prop('checked', Profile.data.dataSpacc.privacy==="0"?false:true);

                this.$el.find("#moreBtn").addClass("ui-btn-active");
                //$("#homeBtn").addClass("ui-btn-active");
                //return to enable chained calls
                return this;
            }
        });
        return SettingsView;
    });