cmsMain.controller('paginaprenotazione2', ['$scope', '$rootScope', '$window', '$http', '$timeout', '$filter', '$location',
    function ($scope, $rootScope, $window, $http, $timeout, $filter, $location) {

        $scope.getProtocolIsHttp = function () {
            if ($location.host()=='localhost') return false;
            return $window.location.protocol=="http:";
        }

        $scope.startApp = function () {
            if (__errorePaypal == 1)
                return;
            
            $scope.storageVar = "objPrenotazione_xenion_14";
            
            $scope.labels = {};
            $scope.labels.title1 = "";
            $scope.labels.title2 = "";
            $scope.labels.title3 = "";
            $scope.labels.title4 = "";

            $scope.today = new Date();
            $scope.today.setDate($scope.today.getDate() - 1);
            $scope.today = $filter('date')($scope.today, 'yyyy-MM-dd');
            
            $scope.campobbnote = __campobbnote;
            
            //////////////////////////////////
            $scope.steps = [];
            $scope.steps[1] = {
                label: "cms.pagepren.StepDate.label",
                labelActive: "cms.pagepren.StepDate.labelActive",
                labelModifica: "cms.pagepren.StepDate.modifica",
                actionModifica: $scope.aggiungiAlloggio,
                testShowModifica: function () {
                    return true;
                },
                callToActionMsg: function () {
                    return $filter('mytranslate')('cms.pagepren.general.btn.Prenota');
                },
                callToAction: $scope.prenotazioneNext,
                azioneDescr: "cms.pagepren.StepDate.AzioneDescr",
                testShowAction: function () {
                    return ($scope.prenotazione.cartrows.length > 0);
                }
            }
            $scope.steps[2] = {
                label: "cms.pagepren.StepDatipers.label",
                labelActive: "cms.pagepren.StepDatipers.labelActive",
                labelModifica: "cms.pagepren.general.btn.Modifica",
                actionModifica: $scope.modificaStep,
                testShowModifica: function () {
                    return $scope.prenotazione.anagraficanoncompleta == true;
                },
                callToActionMsg: function () {
                    if ($scope.prenotazione.solorichiesta == 0) {
                        return $filter('mytranslate')('cms.pagepren.StepDatipers.Procedi');
                    } else {
                        return $filter('mytranslate')('cms.pagepren.StepDatipersInfo.Procedi');
                    }
                },
                callToAction: $scope.prenotazioneNext,
                azioneDescr: "cms.pagepren.StepDatipers.AzioneDescr",
                testAction: function () {
                    if ($scope.prenotazione.nome == undefined)
                        $scope.prenotazione.nome = "";
                    if ($scope.prenotazione.cognome == undefined)
                        $scope.prenotazione.cognome = "";
                    if ($scope.prenotazione.mail == undefined)
                        $scope.prenotazione.mail = "";
                    if ($scope.prenotazione.indirizzo == undefined)
                        $scope.prenotazione.indirizzo = "";
                    if ($scope.prenotazione.citta == undefined)
                        $scope.prenotazione.citta = "";
                    if ($scope.prenotazione.nazione == undefined)
                        $scope.prenotazione.nazione = "";
                    if ($scope.prenotazione.telefono == undefined)
                        $scope.prenotazione.telefono = "";
                    if ($scope.prenotazione.note == undefined)
                        $scope.prenotazione.note = "";

                    if ($scope.prenotazione.nome.trim() == "" ||
                            $scope.prenotazione.cognome.trim() == "" ||
                            $scope.prenotazione.mail.trim() == "" ||
                            $scope.prenotazione.telefono.trim() == "") {
                        $scope.prenotazione.anagraficanoncompleta = false;
                        $scope.summaryError = $filter('mytranslate')('cms.pagepren.StepDatipers.Err1');
                        return false;
                    }

                    if ($scope.checkMail($scope.prenotazione.mail) == false) {
                        $scope.prenotazione.anagraficanoncompleta = false;
                        $scope.summaryError = $filter('mytranslate')('cms.pagepren.StepDatipers.Err2');
                        return false;
                    }

                    $scope.prenotazione.anagraficanoncompleta = true;
                    $scope.summaryError = "";
                    
                    console.log('step: ' + $scope.prenotazione.step);
                    if ($scope.presenzaServizi() == false) {
                        $scope.prenotazione.step++;
                        console.log('step2: ' + $scope.prenotazione.step);
                    }
                    
                    return true;
                }
            }
            $scope.steps[3] = {
                label: "cms.pagepren.StepServizi.label",
                labelActive: "cms.pagepren.StepServizi.labelActive",
                labelModifica: "cms.pagepren.general.btn.Modifica",
                actionModifica: $scope.modificaStep,
                testShowModifica: function () {
                    return $scope.prenotazione.anagraficanoncompleta == true;
                },
                callToActionMsg: function () {
                    return $filter('mytranslate')('cms.pagepren.StepServizi.Procedi');
                },
                callToAction: $scope.prenotazioneNext,
                azioneDescr: "cms.pagepren.StepServizi.labelActive",
            }
            $scope.steps[4] = {
                label: "cms.pagepren.StepRiepilogo.label",
                labelActive: "cms.pagepren.StepRiepilogo.label",
                callToActionMsg: function () {
                    return $filter('mytranslate')('cms.pagepren.StepRiepilogo.Procedi');
                },
                callToAction: function () {
                    $scope.prenotaOra();
                },
                testDisableAction: function () {
                    return !($scope.enabledTastoPrenota());
                },
                azioneDescr: "cms.pagepren.StepRiepilogo.AzioneDescr",
                testAction: function () {
                    if ($scope.campobbnote == 1) {
                        if ($scope.prenotazione.note == undefined)
                            $scope.prenotazione.note = "";

                        if ($scope.prenotazione.note.trim() == "") {
                            $scope.summaryError = $filter('mytranslate')('cms.pagepren.StepRiepilogo.Err1');
                            $scope.campobbnoteMancante = true;

                            return false;
                        } else {
                            $scope.summaryError = "";
                            $scope.campobbnoteMancante = false;
                        }
                    }
                    
                    $scope.summaryError = "";
                    return true;
                }
            }

            ///////////////////////////////////////
            if (typeof (Storage) !== "undefined") {
                var _startVal = localStorage.getItem($scope.storageVar);
                if (_startVal != undefined) {
                    $scope.prenotazione = JSON.parse(_startVal);

                    if ($scope.prenotazione.dataDa != undefined)
                        $scope.prenotazione.dataDa = new Date($scope.prenotazione.dataDa);
                    if ($scope.prenotazione.dataAl != undefined)
                        $scope.prenotazione.dataAl = new Date($scope.prenotazione.dataAl);

                    for (var i = 0; i < $scope.prenotazione.cartrows.length; i++) {
                        if ($scope.prenotazione.cartrows[i].dataDa != undefined)
                            $scope.prenotazione.cartrows[i].dataDa = new Date($scope.prenotazione.cartrows[i].dataDa);
                        if ($scope.prenotazione.cartrows[i].dataAl != undefined)
                            $scope.prenotazione.cartrows[i].dataAl = new Date($scope.prenotazione.cartrows[i].dataAl);
                    }

                    localStorage.removeItem($scope.storageVar);
                }
            }

            if ($scope.prenotazione == undefined) {
                $scope.prenotazione = {};

                $scope.prenotazione.hystoryAction = [];

                $scope.prenotazione.step = 1;

                $scope.prenotazione.numAlloggi = 1;

                $scope.prenotazione.idsession = new Date().getTime();

                $scope.prenotazione.alloggiInRicerca = [];

                $scope.prenotazione.alloggiInRicerca.push({
                    numAdulti: 2,
                    numBambini: 0,
                    etaBambini: angular.copy(__prenotazioneEtaBambini)
                })

                $scope.prenotazione.idmacrotipologiaall = 0;

                $scope.prenotazione.ignorarestrizioni = __ignorarestrizioni;

                $scope.prenotazione.idcanalevendita = __idcanalevendita;
                
                $scope.prenotazione.alloggi = [];
                $scope.prenotazione.possibilita = [];

                $scope.prenotazione.cartrows = [];
            }

            $scope.prenotazione.datiStruttura = __struttura;
            $scope.prenotazione.language = __preferredLanguage;

            $scope.prenotazione.idstructure = __idstructure;
            $scope.prenotazione.idstructureRequest = __idstructureRequest;

            if (__numadulti != "")
                $scope.prenotazione.alloggiInRicerca[0].numAdulti = __numadulti;
            if (__numbambini != "")
                $scope.prenotazione.alloggiInRicerca[0].numBambini = __numbambini;
            if (__idmacrotipologiaall != "")
                $scope.prenotazione.idmacrotipologiaall = __idmacrotipologiaall;
            if (__datada != undefined && __datada != "") {
                $scope.prenotazione.dataDa = new Date(__datada.split("-")[0], (__datada.split("-")[1]*1)-1, __datada.split("-")[2]);
                $scope.prenotazione.dataDaStr = $filter('date')($scope.prenotazione.dataDa, 'dd/MM/yyyy');
            }
            if (__dataal != undefined && __dataal != "") {
                $scope.prenotazione.dataAl = new Date(__dataal.split("-")[0], (__dataal.split("-")[1]*1)-1, __dataal.split("-")[2]);
                $scope.prenotazione.dataAlStr = $filter('date')($scope.prenotazione.dataAl, 'dd/MM/yyyy');
            }
            
            for (let a=0;a<$scope.prenotazione.alloggiInRicerca.length;a++) {
                for (let i=0;i<=$scope.prenotazione.alloggiInRicerca[a].numBambini;i++) {
                    if ($scope.prenotazione.alloggiInRicerca[a].etaBambini[i] == null) {
                        $scope.prenotazione.alloggiInRicerca[a].etaBambini[i] = 8;
                    }
                }
            }

            $scope.prenotazione.Idpreventivo = 0;
            if (__idpreventivo > 0) {
                $scope.prenotazione.Idpreventivo = __idpreventivo;
            }
            
            ///////
            $scope.modPagamenti = [];
            if (__thankupage != 1 &&
                __datada != undefined && __datada != "" &&
                __dataal != undefined && __dataal != "") {
                $scope.checkDate();
                if ($scope.prenotazione.dateOK == true) {
                    $scope.ricercaDisponibilita();
                }
            } else {
                $scope.updateStatus();
            }

            $scope.checkHeightBoxRiepilogo();

            ///////
            $http.get("pacifik/client/modules/hotels/services/readopen/getinfoutili?Idindirizzoanag=" + $scope.prenotazione.idstructure + "&Idindirizzoanagall=" + $scope.prenotazione.idstructureRequest + "&numprenotazione=" + __numprenotazione).then(function (resp) {
                $scope.infoutili = resp.data;
                $scope.modPagamenti = $scope.infoutili.modpag;
                $scope.languages = $scope.infoutili.languages;
                $scope.arrMacrotipologieall = $scope.infoutili.macrotipologieall;
                $scope.roomsrooms = $scope.infoutili.roomsrooms;

                $scope.prenotazione.coordinateBanca = "";
                $scope.prenotazione.coordinateBanca += "<table>";                
                $scope.prenotazione.coordinateBanca += "<tr><td>Intestare a:<td>&nbsp;<td>" + $scope.infoutili.ragioneSociale + "<br>";
                $scope.prenotazione.coordinateBanca += "<tr><td>Iban:<td>&nbsp;<td>" + $scope.infoutili.iban + "<br>";
                $scope.prenotazione.coordinateBanca += "<tr><td>" + $filter('mytranslate')('cms.pagepren.general.banca') + ":<td>&nbsp;<td>" + $scope.infoutili.nomebanca + "<br>";
                $scope.prenotazione.coordinateBanca += "<tr><td>Bic/Swift:<td>&nbsp;<td>" + $scope.infoutili.swift;
                $scope.prenotazione.coordinateBanca += "</table>";

                for (var i=0;i<$scope.modPagamenti.length;i++) {
                    var _modPag = $scope.modPagamenti[i];

                    if (_modPag['Image'].length > 0) {
                        _modPag['immagine'] = _modPag['Image'][0].url;
                    } else {
                        _modPag['immagine'] = "";
                    }

                    if (_modPag.Htmodpagacaparres != null) {
                        for (var a=0;a<_modPag.Htmodpagacaparres.length;a++) {
                            if (_modPag.Htmodpagacaparres[a].Giorniprimaarrivo == -10000) {
                                _modPag.Tipopagamento = _modPag.Htmodpagacaparres[a].Tipopagamento;
                                _modPag.Importominimo = _modPag.Htmodpagacaparres[a].Importominimo;
                                if (_modPag.Htmodpagacaparres[a].Tipopagamento == "PERC") {
                                    _modPag.Percentcaparra = _modPag.Htmodpagacaparres[a].Valore;
                                }
                                if (_modPag.Htmodpagacaparres[a].Tipopagamento == "NOTTI") {
                                    _modPag.Notticaparra = _modPag.Htmodpagacaparres[a].Valore;
                                }
                            }
                        }
                    }
                }

                if ($scope.infoutili.jsonPren != undefined) {
                    $scope.prenotazione = $scope.infoutili.jsonPren;
                    if (__thankupage == 1) {
                        $scope.statoPagina = 'THANKUPAGE';
                    } else {
                        $scope.statoPagina = 'PAGINAPREN';
                    }
                } else {
                    $scope.statoPagina = 'PAGINAPREN';
                }

                $scope.scrollToId('ancoraStep1');

                $timeout(function () {
                    if (__struttura.latitudine != '' && __struttura.latitudine != 0 && __struttura.longitudine != '' && __struttura.longitudine != 0) {
                        initMap();
                    }
                }, 100);

            });

        }
        
        $scope.resetDisponibilita = function () {
            $scope.prenotazione.possibilita = [];
        }
        
        // gestione navigazione
        $scope.ricercaDisponibilita = function (scroll) {

            $scope.prenotazione.cartrows = [];

            let _arr = [];
            for (let i=0;i<$scope.prenotazione.numAlloggi;i++) {
                var _mess = {};
    
                if ($scope.prenotazione.dataDa==undefined || $scope.prenotazione.dataDa=="") return;
                if ($scope.prenotazione.dataAl==undefined || $scope.prenotazione.dataAl=="") return;
    
                _mess.dataDa = $filter('date')($scope.prenotazione.dataDa, 'yyyy-MM-dd');
                _mess.dataAl = $filter('date')($scope.prenotazione.dataAl, 'yyyy-MM-dd');
    
                _mess.ignorarestrizioni = $scope.prenotazione.ignorarestrizioni;
    
                _mess.idcanalevendita = $scope.prenotazione.idcanalevendita;
    
                _mess.idmacrotipologiaall = $scope.prenotazione.idmacrotipologiaall;
    
                _mess.numAdulti = $scope.prenotazione.alloggiInRicerca[i].numAdulti;
                _mess.numBambini = $scope.prenotazione.alloggiInRicerca[i].numBambini;
                for (let a=_mess.numBambini;a<100;a++) {
                    delete $scope.prenotazione.alloggiInRicerca[i].etaBambini[a];
                }
                _mess.etaBambini = $scope.prenotazione.alloggiInRicerca[i].etaBambini;
    
                _mess.idindirizzoanag = $scope.prenotazione.idstructureRequest;
    
                _mess.calculateImporti = 1;
                _mess.calculateServizi = 1;
                _mess.checkPostiLetto = 1;
                
                _mess.nascondisenzatariffa = 1;
                _mess.noprenotazioninelpassato = 1;
                _mess.dalbookingengine = 1;
                
                if (__idpreventivo != 0) {
                    _mess.mostraMaxPersonExceeded = 0;
                }
                
                _mess.Fields = [];
                _mess.Fields.push({from:"a.immagini", as:"immagini"});
                _mess.Fields.push({from:"a.immaginicarosello", as:"immaginicarosello"});
                _mess.Fields.push({from:"a.name", as:"roomtypename"});
                _mess.Fields.push({from:"a.descrizionebreve", as:"descrizionebreve"});
                _mess.Fields.push({from:"a.descrizione", as:"descrizione"});
                
                _mess.Filters = [];
                _mess.Filters.push("a.visibilesubookeng = 1");
                
                if (__fromgoogle == 1) {
                    _mess.fromgoogle = 1;
                }

                _arr.push(_mess);
            }

            $scope.updateStatus();  

            $rootScope.showLoading(true);
            $http.post("pacifik/client/modules/hotels/services/readopen/calcoladisponibilitaArr?language="+__preferredLanguage, _arr).then(function (resp) {

                $scope.possxxx = {};
                
                for (let r=0;r<resp.data.return.length;r++) {
                    $scope.prenotazione.possibilita = resp.data.return[r];

                    for (let x=0; x<$scope.prenotazione.possibilita.length; x++) {
                        var _possibilita = $scope.prenotazione.possibilita[x];

                        if (_possibilita.MaxPersonExceeded != 1) {
                            var _idroomtype = _possibilita.Idroomtype;
                            var _condVenditas = _possibilita.Condizionivend;
                            
                            if ($scope.possxxx[_idroomtype]==null) {
                                delete _possibilita.Condizionivend;
    
                                $scope.possxxx[_idroomtype] = _possibilita;
                                $scope.possxxx[_idroomtype].Condizionivend = {}; 
                            }
                            
                            for (let a=0; a<_condVenditas.length; a++) {
                                var _condVendita = _condVenditas[a];
    
                                _condVendita.MaxPostiLetto = _possibilita.MaxPostiLetto;
    
                                var _idcondizionevendita = _condVendita.Idcondizionevendita;
    
                                if ($scope.possxxx[_idroomtype].Condizionivend[_idcondizionevendita] == null) {
                                    $scope.possxxx[_idroomtype].Condizionivend[_idcondizionevendita] = [];
                                }

                                let _trovato = 0;

                                for (let c=0;c<$scope.possxxx[_idroomtype].Condizionivend[_idcondizionevendita].length;c++) {
                                    let _testCond = $scope.possxxx[_idroomtype].Condizionivend[_idcondizionevendita][c];
                                    if (_testCond.NumAdulti == _condVendita.NumAdulti && 
                                        _testCond.NumBambini == _condVendita.NumBambini &&
                                        JSON.stringify(_testCond.EtaBambini) == JSON.stringify(_condVendita.EtaBambini) ) {
                                        _trovato = 1;
                                    }
                                }

                                if (_trovato == 0) {
                                    $scope.possxxx[_idroomtype].Condizionivend[_idcondizionevendita].push(_condVendita);
                                }
                            }
                        }


                    }
                }

                $scope.prenotazione.possibilita = [];
                for(row in $scope.possxxx) {
                    $scope.prenotazione.possibilita.push($scope.possxxx[row]);
                }


                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                $scope.prenotazione.numNotti = Math.round(Math.abs(($scope.prenotazione.dataDa.getTime() - $scope.prenotazione.dataAl.getTime()) / (oneDay)));

                for (var x=0; x<$scope.prenotazione.possibilita.length; x++) {
                    var _possibilita = $scope.prenotazione.possibilita[x];

                    var _condVenditas = _possibilita.Condizionivend;                    
                    delete _possibilita.Condizionivend;
                    _possibilita.Condizionivend = [];
                    for (row in _condVenditas) {
                        _possibilita.Condizionivend.push(_condVenditas[row]);
                    }
                    var _condVenditas = _possibilita.Condizionivend;   

                    _possibilita.mostraDettagli = 0;
                    _possibilita.mostraApartireda = 1;

                    ///////////////////////////
                    var _serviziAggiuntiviAfter = [];

                    for (var s=0;s<_possibilita.Servizi.length;s++) {
                        servagg = _possibilita.Servizi[s];

                        servagg.Quantita = 1;
                        servagg.Moltiplicatore = 1;

                        if (servagg.Tiposervizio!=null && servagg.Tiposervizio.Tipopag!=null) {
                            if (servagg.Tiposervizio.Tipopag.indexOf("DAY") === 0) {
                                servagg.Moltiplicatore = $scope.prenotazione.numNotti;
                            }
                            if (servagg.Tiposervizio.Tipopag.indexOf("WEEK") === 0) {
                                servagg.Moltiplicatore = Math.ceil($scope.prenotazione.numNotti / 7);
                            }
                            if (servagg.Tiposervizio.Tipopag.indexOf("SOGG") === 0) {
                                servagg.Moltiplicatore = 1;
                            }

                            if (servagg.Tiposervizio.Tipopag.indexOf("xPERS") >= 0) {
                                servagg.Quantita = ($scope.prenotazione.numAdulti*1 + $scope.prenotazione.numBambini*1);                        
                                servagg.Maxdisponibilita = ($scope.prenotazione.numAdulti*1 + $scope.prenotazione.numBambini*1);
                            }

                            if (servagg.Tiposervizio.Tipopag.indexOf("xADULTO") >= 0) {
                                servagg.Quantita = $scope.prenotazione.numAdulti;
                                servagg.Maxdisponibilita = $scope.prenotazione.numAdulti;
                            }

                            if (servagg.Tiposervizio.Tipopag.indexOf("xBAMB") >= 0) {
                                if (servagg.Tiposervizio.Etada!=null && servagg.Tiposervizio.Etaa!=null) {
                                    var _numBamb = 0;

                                    for (let i=0;i<$scope.prenotazione.numBambini;i++) {
                                        var _eta = 8;
                                        if ($scope.prenotazione.etaBambini!=null && $scope.prenotazione.etaBambini[i]!=null) {
                                            _eta = $scope.prenotazione.etaBambini[i];
                                        }
                                        if (_eta>=servagg.Tiposervizio.Etada && _eta<=servagg.Tiposervizio.Etaa) {
                                            _numBamb++;
                                        }
                                    }
                                    
                                    servagg.Quantita = _numBamb;
                                    servagg.Maxdisponibilita = _numBamb
                                } else {
                                    servagg.Quantita = $scope.prenotazione.numBambini;
                                    servagg.Maxdisponibilita = $scope.prenotazione.numBambini;
                                }
                            }
                        }

                        if (servagg.Forzaprezzo != undefined ) {
                            servagg.Quantita = 1;
                            servagg.Moltiplicatore = 1;    
                        }

                        if (servagg.Maxdisponibilita == undefined) {
                            servagg.Maxdisponibilita = 100;
                        }
                        if ( servagg.Idhtroomtypeserviceobb == 1 ||
                            servagg.Idhtroomtypeserviceobb == 2 ) {
                            if (servagg.Maxdisponibilita > 0) {
                                _serviziAggiuntiviAfter.push (servagg);
                            }
                        }
                    }

                    _possibilita.Servizi = _serviziAggiuntiviAfter;
                    
                    ///////////////////////            
                    /*        
                    BEV2
                    for (var i=0; i<_condVenditas.length; i++) {
                        if (_condVenditas[i].Ok == 1) {
                            _possibilita.mostraDettagli = 0;
                        }
                        
                        _condVenditas[i].Nascondi = 0;
                        if (__idpreventivo > 0) {
                            if (_condVenditas[i].Ok == 0) {
                                _condVenditas[i].Nascondi = 1;
                            }
                        }
                        for (d in __preventividifferenze) {
                            if ( _condVenditas[i].Idcondizionevendita == __preventividifferenze[d].Idcondizionevendita &&
                                 _possibilita.Idroomtype ==  __preventividifferenze[d].Idroomtype
                                ) {
                                if (__preventividifferenze[d].Nascondi == 1) {
                                    _condVenditas[i].Nascondi = 1;
                                }
                                if (__preventividifferenze[d].Prezzo != undefined) {
                                    _condVenditas[i].PrezzoTot = __preventividifferenze[d].Prezzo;
                                }
                            }
                        }
                        
                    }
                    */
                    
                    /*
                    BEV2
                    var _numCondVendita = 0;
                    for (var i=0; i<_condVenditas.length; i++) {
                        if (_condVenditas[i].Ok==1 && _condVenditas[i].Nascondi==0) {
                            _numCondVendita++;

                            /*
                            if (__fromgoogle == 1) {
                                var _descrRimbGoogle = "";

                                if (_condVenditas[i].Rimborsabile == 1) {
                                    _descrRimbGoogle = "Refundable up to " + _condVenditas[i].Rimborsabilefinoa + " days before arrival";
                                } else {
                                    _descrRimbGoogle = "Non refundable";
                                }

                                _condVenditas[i].Descrcondvendita = "<b>" + _descrRimbGoogle + "</b><br>" + _condVenditas[i].Descrcondvendita;
                            }
                            /
                        }
                    }
                    if (_numCondVendita == 1) {
                        _possibilita.mostraDettagli = 1;
                        _possibilita.mostraApartireda = 0;
                    }
                    
                    if (__mostraSempreDettagli == 1) {
                        _possibilita.mostraDettagli = 1;
                        _possibilita.mostraApartireda = 0;
                    }
                    
                    if (_possibilita.MaxPersonExceeded == 1) {
                        _possibilita.mostraDettagli = 1;
                    }
                    */
                }
                
                $scope.prenotazione.possibilita.sort(function (a, b) {
                    var _prezzoA = 10000000;
                    var _prezzoB = 10000000;

                    for (var i=0; i<a.Condizionivend.length; i++) {
                        for (var p=0; p<a.Condizionivend[i].length; p++) {
                            var _prezzo = a.Condizionivend[i][p];

                            if (_prezzo.Ok == 1 && _prezzo.PrezzoTot < _prezzoA)
                                _prezzoA = _prezzo.PrezzoTot*1;
                        }
                    }

                    for (var i=0; i<b.Condizionivend.length; i++) {
                        for (var p=0; p<b.Condizionivend[i].length; p++) {
                            var _prezzo = b.Condizionivend[i][p];

                            if (_prezzo.Ok == 1 && _prezzo.PrezzoTot < _prezzoB)
                                _prezzoB = _prezzo.PrezzoTot*1;
                        }
                    }
                    
                    return _prezzoA - _prezzoB;
                })
                
                $scope.prenotazione.errorMsg = undefined;

                var _trovato = false;
                $scope.prenotazione.prezzopiubasso = 10000000;

                for (var x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                    var _possibilita = $scope.prenotazione.possibilita[x];
                    
                    if (_possibilita['immagini'].length > 0) {
                        _possibilita['immagine'] = _possibilita['immagini'][0].url;
                    } else {
                        _possibilita['immagine'] = "";
                    }
                    
                    /* BEV2
                    _possibilita.Condizionivend.sort(function (a, b) {
                        _prezzoA = a.PrezzoTot*1;
                        _prezzoB = b.PrezzoTot*1;
                        
                        if (a.Ok != 1) _prezzoA += 10000;
                        if (b.Ok != 1) _prezzoB += 10000;
                        
                        return _prezzoA - _prezzoB;
                    });
                    */

                    var _condVenditas = _possibilita.Condizionivend;
                    for (var i=0; i<_condVenditas.length; i++) {
                        var _condVendita = _condVenditas[i];

                        for (var p=0; p<_condVendita.length; p++) {         
                            var _prezzo = _condVendita[p];                   

                            _prezzo['roomtypename'] = _possibilita['roomtypename'];
                            _prezzo['idroomtype'] = _possibilita['Idroomtype'];
                            _prezzo['immagine'] = _possibilita['immagine'];
                            _prezzo['immaginicarosello'] = _possibilita['immaginicarosello'];
                            _prezzo['descrizione'] = _possibilita['descrizione'];
                            _prezzo['Confletti'] = _possibilita['Confletti'];
                            _prezzo['ConflettiAggiuntivi'] = _possibilita['ConflettiAggiuntivi'];
                            _prezzo['serviziAggiuntivi'] = _possibilita['Servizi'];
                            _prezzo['descrizionebreve'] = _possibilita['Descrizionebreve'];
                            
                            for (var a = 0; a < _prezzo.serviziAggiuntivi.length; a++) {
                                var _servizio = _prezzo.serviziAggiuntivi[a];
                                var _immagini = _servizio['Photo'];
                                if (_immagini!=null && _immagini.length > 0) {
                                    _servizio['immagine'] = _immagini[0].url;
                                } else {
                                    _servizio['immagine'] = "";
                                }
                            }
                        }

                    }
                    
                }

                $scope.prenotazione.disponibilitaMsg = false;

                if ($scope.getNumeroTutteSoluzioni() == 0) {
                    $scope.prenotazione.disponibilitaMsg = true;
                } else {
                    $scope.prenotazione.disponibilitaMsg = false;
                }

                $scope.messCameraNonDisponibile = $filter('mytranslate')('cms.pagepren.StepDate.Messdisp') + ":";

                $scope.updateStatus();
                $rootScope.showLoading(false);
                
                if (scroll == "SCROLLTOP") {
                    $scope.scrollToId('ancoraStep1');
                } else {
                    if (scroll != "NOSCROLL") {
                        if (_trovato == false) {
                            $scope.scrollToId('boxaltrepossibilita');
                        } else {
                            $scope.scrollToId('alloggioscelto');
                        }
                    }
                }
                
            }, function (resp) {
                $scope.prenotazione.errorMsg = "<b>Errore durante la procedura di ricerca.</b>";
                $scope.prenotazione.possibilita = [];
                $rootScope.showLoading(false);
            });
        }

        $scope.changeDate = function () {
            $scope.checkDate();
            if ($scope.prenotazione.dateOK == true) {
                //$scope.ricercaDisponibilita("NOSCROLL");
            }

            for (let a=0;a<$scope.prenotazione.alloggiInRicerca.length;a++) {
                for (let i=0;i<=$scope.prenotazione.alloggiInRicerca[a].numBambini;i++) {
                    if ($scope.prenotazione.alloggiInRicerca[a].etaBambini[i] == null) {
                        $scope.prenotazione.alloggiInRicerca[a].etaBambini[i] = 8;
                    }
                }
            }
        }

        $scope.checkDate = function () {
            $scope.addHystoryAct("data da=" + $filter('date')($scope.prenotazione.dataDa, 'dd/MM/yyyy') + " - data a=" + $filter('date')($scope.prenotazione.dataAl, 'dd/MM/yyyy') + " - " + JSON.stringify($scope.prenotazione.alloggiInRicerca) + " - tipologia=" + $scope.prenotazione.idmacrotipologiaall);

            if (($scope.prenotazione.dataDa != undefined && $scope.prenotazione.dataAl == undefined) ||
                    ($scope.prenotazione.dataDa != undefined && $scope.prenotazione.dataAl != undefined &&
                            $scope.prenotazione.dataDa.getTime() >= $scope.prenotazione.dataAl.getTime())
                    ) {
                $scope.prenotazione.dataAl = angular.copy($scope.prenotazione.dataDa);
                $scope.prenotazione.dataAl.setDate($scope.prenotazione.dataAl.getDate() + 1);
            }

            if ($scope.prenotazione.dataDa != undefined && $scope.prenotazione.dataAl != undefined) {
                if ($scope.prenotazione.dataDa.getTime() > $scope.prenotazione.dataAl.getTime()) {
                    $scope.prenotazione.dataAl = undefined;
                    $scope.prenotazione.dateOK = undefined;
                    return;
                }
                $scope.prenotazione.dateOK = true;
            } else {
                $scope.prenotazione.dateOK = undefined;
            }
        }

        $scope.prenotazioneNext = function () {
            var _go = true;
            if ($scope.steps[$scope.prenotazione.step].testAction != undefined) {
                _go = $scope.steps[$scope.prenotazione.step].testAction();
            }
            if (_go == true) {
                if ($scope.prenotazione.step==3 && $scope.prenotazione.solorichiesta==1) {
                    
                    for (var i = 0; i < $scope.prenotazione.cartrows.length; i++) {
                        $scope.prenotazione.cartrows[i].dataDaStr = $filter('date')($scope.prenotazione.cartrows[i].dataDa, 'yyyy-MM-dd')
                        $scope.prenotazione.cartrows[i].dataAlStr = $filter('date')($scope.prenotazione.cartrows[i].dataAl, 'yyyy-MM-dd')
                    }
                    
                    $rootScope.showLoading(true);
                    $http.post("pacifik/client/modules/hotels/services/readopen/soloRichiesta", $scope.prenotazione).then(function (resp) {
                        $rootScope.showLoading(false);
                    });
                    $scope.statoPagina = 'THANKUPAGE2';
                    $scope.scrollToId("container-thankupage");
                    
                    return;
                }               
                if ($scope.prenotazione.laststep != undefined &&
                        $scope.prenotazione.step != $scope.prenotazione.laststep &&
                        $scope.prenotazione.step < $scope.prenotazione.laststep) {
                    $scope.prenotazione.step = $scope.prenotazione.laststep;
                } else {
                    $scope.prenotazione.step++;
                }
                $scope.prenotazione.laststep = undefined;
                $scope.updateStatus();
                $scope.scrollToId("ancoraStep" + $scope.prenotazione.step);
            }
        }
        
        $scope.attivamodPagamento = function () {
            $timeout(function () {
                if (document.getElementById("card-element")!=null) {
                    if (__stripeUserID == "") {
                        alert ("Attenzione, Stripe non è configurato correttamente. Contattare la assistenza");
                        return;
                    }
                    
                    $scope.stripeObj = Stripe("pk_live_jmwLFGQ2NyAjd6jUraSkUAYs", {'stripeAccount': __stripeUserID}); 
                    var elements = $scope.stripeObj.elements();
                    $scope.cardElement = elements.create('card');
                    $scope.cardElement.mount('#card-element');

                    $scope.prenotazione.cardStripeValid = false;

                    $scope.cardElement.addEventListener('change', function(event) {
                        if (event.error) {
                            $scope.erroreInserimentoCarta = event.error.message;
                        } else {
                            $scope.erroreInserimentoCarta = undefined;
                        }

                        $scope.prenotazione.cardStripeValid = false;
                        if (event.complete == true) {
                            $scope.prenotazione.cardStripeValid = true;
                        }

                        $scope.$apply();
                    });
                }
            },100);
        }
        
        $scope.onChangeQtaRooms = function (itemExt, prezzo) {    
            let _rooms = {};

            let _roomsFigle = {};
            for (let i=0; i<$scope.roomsrooms.length; i++) {
                _roomsFigle[$scope.roomsrooms[i].Idroomfiglia] = 1;
            }

            for (let x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                let _possibilita = $scope.prenotazione.possibilita[x]
                for (let i = 0; i<_possibilita.Rooms.length; i++) {
                    _rooms[_possibilita.Rooms[i].Idroom] = 0; 
                }
            }

            for (let x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                let _possibilita = $scope.prenotazione.possibilita[x]
                for (let i = 0; i<_possibilita.Condizionivend.length; i++) {
                    let condvend = _possibilita.Condizionivend[i];
                    for (let a = 0; a<condvend.length; a++) {
                        if( (condvend[a].Quantita) == undefined ){
                            condvend[a].Quantita = 0;
                        }
                        
                        for (let b=0; b<condvend[a].Quantita;b++) {
                            var _found = 0;

                            for (let i=0; i<_possibilita.Rooms.length; i++) {
                                if (_roomsFigle[_possibilita.Rooms[i].Idroom] == undefined) {
                                    if (_rooms[_possibilita.Rooms[i].Idroom] == 0) {
                                        _rooms[_possibilita.Rooms[i].Idroom] = 1;
                                        i = _possibilita.Rooms.length;
                                        _found = 1;
                                    }
                                }
                            }

                            if (_found == 0) {
                                for (let i=0; i<_possibilita.Rooms.length; i++) {
                                    if (_rooms[_possibilita.Rooms[i].Idroom] == 0) {
                                        _rooms[_possibilita.Rooms[i].Idroom] = 1;
                                        i = _possibilita.Rooms.length;
                                    }
                                }
                            }

                        }
    
                    }
                }
            }

            for (let i=0; i<$scope.roomsrooms.length; i++) {
                if (_rooms[$scope.roomsrooms[i].Idroom] == 1) {
                    _rooms[$scope.roomsrooms[i].Idroomfiglia] = 1;
                }
            }

            for (let i=0; i<$scope.roomsrooms.length; i++) {
                if (_rooms[$scope.roomsrooms[i].Idroomfiglia] == 1) {
                    _rooms[$scope.roomsrooms[i].Idroom] = 1;
                }
            }

            for (let x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                let _possibilita = $scope.prenotazione.possibilita[x]

                let qtaInUso = 0;
                let qtaMax = parseInt(_possibilita.Rooms.length);

                for (let i = 0; i<_possibilita.Rooms.length; i++) {
                    if (_rooms[_possibilita.Rooms[i].Idroom] == 1) {
                        qtaInUso++;
                    }
                }

                for (let i = 0; i<_possibilita.Condizionivend.length; i++) {
                    let condvend = _possibilita.Condizionivend[i];
                    for (let a = 0; a<condvend.length; a++) {
                        condvend[a].QuantitaMassima = (condvend[a].Quantita*1) + (qtaMax - qtaInUso);
                    }
                }
            }

            $scope.addToCart(prezzo);
        }

        $scope.aggiungiAlloggio = function () {
            $scope.summaryError = "";
            $scope.prenotazione.laststep = undefined;
            $scope.prenotazione.step = 1;
            $scope.updateStatus()
            $scope.ricercaDisponibilita();
        }

        $scope.modificaStep = function (step) {
            $scope.summaryError = "";
            $scope.prenotazione.laststep = $scope.prenotazione.step;
            $scope.prenotazione.step = step;
            $scope.updateStatus()
            $scope.scrollToId("ancoraStep" + $scope.prenotazione.step);
        }

        //
        $scope.getTotaleXNotti = function (notti) {
            var _importoCaparra = 0;

            for (var i=0; i<$scope.prenotazione.cartrows.length; i++) {
                var _notte = 1;
                var _dataDa = angular.copy($scope.prenotazione.cartrows[i].dataDa);
                while (_dataDa.getTime() < $scope.prenotazione.cartrows[i].dataAl.getTime()) {
                    if (_notte <= notti) {
                        var _prezzoGiorno = $scope.prenotazione.cartrows[i].PrezziAlGiorno[$filter('date')(_dataDa, 'yyyy-MM-dd')];
                        if (_prezzoGiorno!=null && isNaN(_prezzoGiorno*1)==false) {
                            _importoCaparra += _prezzoGiorno * 1;
                        }
                    }
                    _dataDa.setDate(_dataDa.getDate()+1);
                    _notte++;
                }
            }

            return _importoCaparra;
        }

        // funzioni GET
        $scope.getTotalePrenotazione = function (modPagamento, noAumento) {            
            var _tot = 0;
            
            if (modPagamento == null) {
                $scope.prenotazione.codiceScontoInEuro = 0;
                $scope.prenotazione.commModPagamento = 0;
            }
                    
            for (var i=0; i<$scope.prenotazione.cartrows.length; i++) {
                var _prezzoRiga = $scope.prenotazione.cartrows[i].PrezzoTot;
                var _scontoRiga = 0;
                var _aumento = 0;
                
                if (noAumento != true) {
                    if (modPagamento != null) {
                        if (modPagamento.Aumentototale!=null) {
                            if (modPagamento.Tipopagamento == "PERC") {
                                _aumento = (_prezzoRiga * (modPagamento.Percentcaparra/100)) * (modPagamento.Aumentototale/100);
                            }
                            if (modPagamento.Tipopagamento == "NOTTI") {
                                var _notte = 1;
                                var _importoCaparra = 0;
                                var _dataDa = angular.copy($scope.prenotazione.cartrows[i].dataDa);
                                while (_dataDa.getTime() < $scope.prenotazione.cartrows[i].dataAl.getTime()) {
                                    if (_notte <= modPagamento.Notticaparra) {
                                        _importoCaparra += $scope.prenotazione.cartrows[i].PrezziAlGiorno[$filter('date')(_dataDa, 'yyyy-MM-dd')];
                                    }
                                    _dataDa.setDate(_dataDa.getDate()+1);
                                    _notte++;
                                }
                                _aumento = _importoCaparra * (modPagamento.Aumentototale/100);
                            }
                        }
                    } else {
                        if ($scope.prenotazione.modPagamento!=null && $scope.prenotazione.modPagamento.Aumentototale!=null) {
                            if ($scope.prenotazione.modPagamento.Tipopagamento == "PERC") {
                                _aumento = (_prezzoRiga * ($scope.prenotazione.modPagamento.Percentcaparra/100)) * ($scope.prenotazione.modPagamento.Aumentototale/100);
                            }
                            if ($scope.prenotazione.modPagamento.Tipopagamento == "NOTTI") {
                                var _notte = 1;
                                var _importoCaparra = 0;
                                var _dataDa = angular.copy($scope.prenotazione.cartrows[i].dataDa);
                                while (_dataDa.getTime() < $scope.prenotazione.cartrows[i].dataAl.getTime()) {
                                    if (_notte <= $scope.prenotazione.modPagamento.Notticaparra) {
                                        _importoCaparra += $scope.prenotazione.cartrows[i].PrezziAlGiorno[$filter('date')(_dataDa, 'yyyy-MM-dd')];
                                    }
                                    _dataDa.setDate(_dataDa.getDate()+1);
                                    _notte++;
                                }
                                _aumento = _importoCaparra * ($scope.prenotazione.modPagamento.Aumentototale/100);
                            }
                        }
                    }
                    _aumento = Math.round(_aumento*10)/10;
                }
                _prezzoRiga = _prezzoRiga + _aumento;
                
                if (modPagamento == null) {
                    $scope.prenotazione.commModPagamento += (_prezzoRiga - $scope.prenotazione.cartrows[i].PrezzoTot);
                }
                
                if ($scope.prenotazione.codiceScontoValore != null) {
                    if ($scope.prenotazione.codiceScontoTipo == "PERC") {
                        _scontoRiga = _prezzoRiga * $scope.prenotazione.codiceScontoValore / 100;                        
                    }
                    if ($scope.prenotazione.codiceScontoTipo == "VALORE") {
                        _scontoRiga = $scope.prenotazione.codiceScontoValore / $scope.prenotazione.cartrows.length;
                    }
                    _prezzoRiga = _prezzoRiga - _scontoRiga;
                    if (_prezzoRiga<0) _prezzoRiga = 0;                     
                }
                
                if (modPagamento == null) {
                    $scope.prenotazione.cartrows[i].PrezzoTotScontato = _prezzoRiga;
                    $scope.prenotazione.codiceScontoInEuro += _scontoRiga;
                }
                
                _tot += _prezzoRiga;
                
                var _cartrow = $scope.prenotazione.cartrows[i];
                
                for (var a=0; a<_cartrow.serviziAggiuntivi.length; a++) {
                    var servagg = _cartrow.serviziAggiuntivi[a];
                    if (servagg.Idhtroomtypeserviceobb==2 && servagg.enable==1) {
                        _tot += servagg.Prezzo * servagg.Quantita * servagg.Moltiplicatore;
                    }
                }
            }
            
            if (modPagamento == null) {
                $scope.prenotazione.codiceScontoInEuro = Math.round($scope.prenotazione.codiceScontoInEuro*100)/100;
                $scope.prenotazione.commModPagamento = Math.round($scope.prenotazione.commModPagamento*100)/100;
            }
            
            _tot = Math.round(_tot*100)/100;
            
            return _tot;
        }
        
        $scope.showDetails = function (item, value) {
            item.mostraDettagli = value;
            $timeout(function () {
                $scope.$apply();
            }, 10);
        }
        
        $scope.getShowDescrcondvendita = function(type, idroomtype, idcondizionevendita) {
            var _id = "Descrcondvendita_" + type + "_" + idroomtype + "_" + idcondizionevendita;
            if (document.getElementById(_id) == null) {
                return false;
            }
            var _height = document.getElementById(_id).offsetHeight;
            
            if (_height > 85) {
                return true;
            } else {
                return false;
            }
        }
        
        $scope.showDescrcondvendita = function(item, type, idroomtype, idcondizionevendita) {
            if (item.showAllDescription == 1) {
                item.showAllDescription = undefined;
            } else {
                item.showAllDescription = 1;
            }
        }
        
        $scope.getNumeroTutteSoluzioni = function () {
            var _num = 0;

            for (var x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                var _possibilita = $scope.prenotazione.possibilita[x];
                var _condVenditas = _possibilita.Condizionivend;
            
                for (var i = 0; i < _condVenditas.length; i++) {
                    var _valido = true;
                    var _condVendita = _condVenditas[i];

                    var _qta = _condVendita.qtadisp * 1;
                    for (var a = 0; a < $scope.prenotazione.cartrows.length; a++) {
                        if (_condVendita['idroomtype'] == $scope.prenotazione.cartrows[a].idroomtype) {
                            _qta--;
                        }
                    }
                    if (_qta <= 0) {
                        _valido = false;
                    }

                    if (_valido == true) {
                        _num++;
                    }
                }
            }

            return _num;
        }

        $scope.getNumNotti = function (prenotazione) {
            if (prenotazione.dataAl != undefined && prenotazione.dataAl) {
                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.round(Math.abs((prenotazione.dataDa.getTime() - prenotazione.dataAl.getTime()) / (oneDay)));
                return diffDays;
            }
            return "-";
        }

        $scope.getNumNottiRow = function (item) {
            if (item == undefined) {
                return "-";
            }
            return item.NumDays;
        }
        
        $scope.getCurrAlloggio = function () {
            _ret = $scope.prenotazione.cartrows.length + 1;
            return _ret;
        }
        
        $scope.getLabelConfletto = function (confletto) {
            var _ret = "<p>" + $scope.strlang(confletto.Descrizionebreve) + "</p>";
            _ret = _ret.replace("<p>", "<p>" + confletto.Qta + " x ")
            return _ret;
        }

        $scope.getLabelPersone = function (pren) {
            var _mess = "";
            _mess += pren.NumAdulti + " ";
            if (pren.NumAdulti == 1) {
                _mess += $filter('mytranslate')('cms.pagepren.general.Adulto');
            } else {
                _mess += $filter('mytranslate')('cms.pagepren.general.Adulti');
            }
            if (pren.NumBambini > 0) {
                _mess += ", " + pren.NumBambini + " ";
                if (pren.NumBambini == 1) {
                    _mess += $filter('mytranslate')('cms.pagepren.general.Bambino');
                } else {
                    _mess += $filter('mytranslate')('cms.pagepren.general.Bambini');
                }
            }
            return _mess;
        }
        
        $scope.getFirstPrice = function (condVendita, maxPersonExceeded) {
            var _ret = 10000000;

            if (maxPersonExceeded != 1) {
                for (var i=0;i<condVendita.length;i++) {
                    for (var a=0;a<condVendita[i].length;a++) {
                        var _prezzo = condVendita[i][a];

                        if (_prezzo.Nascondi == undefined) {
                            _prezzo.Nascondi = 0;
                        }
    
                        if (_prezzo.Ok==1 && _prezzo.Nascondi==0) {
                            if (_prezzo.PrezzoTot < _ret) {
                                _ret = _prezzo.PrezzoTot;
                            }
                        }
                    }
                }
            }
            
            if (_ret == 10000000) {
                _ret = "-";
            }

            return _ret;
        }
        
        $scope.getRoomMessKo = function (input) {
            if (input == undefined) {
                return "";
            }
            if (input.message == 'NO_MINSTAY') {
                return $filter('mytranslate')('cms.pagepren.general.MessErr.Minstay').replace("%NUM%", input.minstay);
            }
            ;
            
            if (input.message == 'NO_MAXSTAY') {
                return $filter('mytranslate')('cms.pagepren.general.MessErr.Maxstay').replace("%NUM%", input.maxstay);
            }
            ;

            if (input.message == 'CHECKIN_ON') {
                return $filter('mytranslate')('cms.pagepren.general.MessErr.Checkin');
            }
            ;

            if (input.message == 'CHECKOUT_ON') {
                return $filter('mytranslate')('cms.pagepren.general.MessErr.Checkout');
            }
            ;

            return input;
        }

        $scope.getPagaConBonifico = function () {
            if ($scope.prenotazione.modPagamento.Type == "BON") {
                return true;
            }
            return false;
        }

        $scope.getLabelNotti = function (numNotti) {
            if (numNotti == 1) {
                return $filter('mytranslate')('cms.pagepren.general.Mess.Notte');
            } else {
                var _ret = $filter('mytranslate')('cms.pagepren.general.Mess.Notti');
                _ret = _ret.replace('%NUM%', numNotti);
                return _ret;
            }
        }

        $scope.getLabelNotti2 = function (pren) {
            var _mess = "";
            _mess += pren.numNotti + " ";
            if (pren.numNotti == 1) {
                _mess += $filter('mytranslate')('cms.pagepren.general.Notte');
            } else {
                _mess += $filter('mytranslate')('cms.pagepren.general.Notti');
            }
            return _mess;
        }

        $scope.getLabelRicordaBonifico = function () {
            var _str = $scope.strlang($scope.prenotazione.modPagamento.Descrizione);
            return _str.replace(/_CAPARRA_/g, $filter('mycurrency')($scope.prenotazione.modPagamento.Importocaparra));
        }

        $scope.getLabelPolicyCanc = function (modpag) {
            var _str = $scope.strlang(modpag.Policycancellazione);
            return _str.replace(/_CAPARRA_/g, $filter('mycurrency')(modpag.Importocaparra));
        }

        $scope.getRichiediCaparra = function () {
            for (var i=0;i<$scope.prenotazione.cartrows.length;i++) {
                for (var x=0;x<$scope.prenotazione.possibilita.length;x++) {
                    var _possibilita = $scope.prenotazione.possibilita[x];
                    var _condVenditas = _possibilita.Condizionivend;

                    for (var a=0;a<_condVenditas.length;a++) {
                        if (_condVenditas[a].Idcondizionevendita == $scope.prenotazione.cartrows[i].Idcondizionevendita) {
                            if (_condVenditas[a].Richiedicaparra == 1) {
                                $scope.prenotazione.Richiedicaparra = 1;

                                if ($scope.getModPagamenti().length > 0) {
                                    return true;
                                }
                            }
                        }
                    }
                }
                
            }
            $scope.prenotazione.Richiedicaparra = 0;
            return false;
        }
        
        $scope.getModPagamenti = function () {
            var _ret = {};
            
            ////////////
            for (var a=0;a<$scope.modPagamenti.length;a++) { 
                var modpag = $scope.modPagamenti[a];

                _totPrenNoAumento = $scope.getTotalePrenotazione(modpag, true);
                _totPren = $scope.getTotalePrenotazione(modpag);
                
                if (modpag.Tipopagamento == "PERC") {
                    modpag.Importocaparra = Math.round(_totPrenNoAumento * modpag.Percentcaparra / 100);
                }
                if (modpag.Tipopagamento == "NOTTI") {
                    modpag.Importocaparra = $scope.getTotaleXNotti(modpag.Notticaparra);
                }

                if (modpag.Importominimo != null) {
                    if (modpag.Importocaparra < modpag.Importominimo) {
                        modpag.Importocaparra = modpag.Importominimo;
                    }
                }
                
                modpag.Importocaparra += (_totPren - _totPrenNoAumento);

                if (modpag.Importocaparra > _totPren) {
                    modpag.Importocaparra = _totPren;
                }
            }

            ////////////
            for (var i=0;i<$scope.prenotazione.cartrows.length;i++) {
                var _idcondizionevendita = $scope.prenotazione.cartrows[i].Idcondizionevendita;
                
                for (var a=0;a<$scope.modPagamenti.length;a++) {
                    if ($scope.modPagamenti[a].Htcondizionivenditamodpagams != null) {
                        var _condizionivenditamodpagams = $scope.modPagamenti[a].Htcondizionivenditamodpagams;
                        
                        for (var b=0;b<_condizionivenditamodpagams.length;b++) {
                            if (_idcondizionevendita == _condizionivenditamodpagams[b].Idcondizionevendita) {
                                var _modPagIsGood = 0;
                                
                                if (_ret[$scope.modPagamenti[a].Type] == undefined) {
                                    _modPagIsGood = 1;
                                } else {
                                    if ($scope.modPagamenti[a].Importocaparra > _ret[$scope.modPagamenti[a].Type].Importocaparra) {
                                        _modPagIsGood = 1;
                                    }
                                }

                                if ($scope.modPagamenti[a].Disabsottodata != null) {
                                    for (var c=0;c<$scope.prenotazione.cartrows.length;c++) {
                                        var _diff = ($scope.prenotazione.cartrows[c].dataDa).getTime() - (new Date()).getTime(); 
                                        _diff = _diff / (1000 * 3600 * 24); 
                                        _diff = _diff + 1;
                                        if (_diff <= $scope.modPagamenti[a].Disabsottodata) {
                                            _modPagIsGood = 0;
                                        }
                                    }
                                }

                                if ($scope.modPagamenti[a].Disabapartireda != null) {
                                    for (var c=0;c<$scope.prenotazione.cartrows.length;c++) {
                                        var _diff = ($scope.prenotazione.cartrows[c].dataDa).getTime() - (new Date()).getTime(); 
                                        _diff = _diff / (1000 * 3600 * 24); 
                                        _diff = _diff + 1;
                                        if (_diff > $scope.modPagamenti[a].Disabapartireda) {
                                            _modPagIsGood = 0;
                                        }
                                    }
                                }
                                
                                if (_modPagIsGood == 1) {
                                    _ret[$scope.modPagamenti[a].Type] = {
                                        Idmodpagamento: $scope.modPagamenti[a].Idmodpagamento,
                                        Importocaparra: $scope.modPagamenti[a].Importocaparra
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            var _ret2 = [];
            
            for (var i in _ret) {
                for (var a=0;a<$scope.modPagamenti.length;a++) {
                    if (_ret[i].Idmodpagamento == $scope.modPagamenti[a].Idmodpagamento) {
                        _ret2.push($scope.modPagamenti[a]);
                    }
                }
            }
            
            return _ret2;
        }
        
        $scope.getQuantitaArr = function (servagg) {
            if (servagg.MaxdisponibilitaReale == undefined) {
                servagg.MaxdisponibilitaReale = servagg.Maxdisponibilita;
            }

            var _ret = [];
            for (var i=1;i<=servagg.MaxdisponibilitaReale;i++) {
                _ret.push (i);
            }
            return _ret;
        }

        $scope.onChangeQtaservizi = function () {
            _serviziAggiuntivoTest = {};

            for (var i=0;i<$scope.prenotazione.cartrows.length;i++) {
                var _pren = $scope.prenotazione.cartrows[i];
                var _serviziAggiuntivi = _pren.serviziAggiuntivi;

                for (var a=0;a<_serviziAggiuntivi.length;a++) {
                    var _serviziAggiuntivo = _serviziAggiuntivi[a];
                    if (_serviziAggiuntivo.Idroomtype != undefined) {

                        if (_serviziAggiuntivoTest[_serviziAggiuntivo.Idservice] == undefined ) {
                            _serviziAggiuntivoTest[_serviziAggiuntivo.Idservice] = (_serviziAggiuntivo.Maxdisponibilita*1);
                        }

                        if (_serviziAggiuntivo.enable == 1) {
                            if (_serviziAggiuntivo.Quantita == undefined) {
                                _serviziAggiuntivo.Quantita = 1;
                            }
                            if (_serviziAggiuntivo.Quantita == 0) {
                                _serviziAggiuntivo.Quantita = 1;
                            }
                            var _qta = (_serviziAggiuntivo.Quantita*1);

                            _serviziAggiuntivoTest[_serviziAggiuntivo.Idservice] -= _qta;
                        }
                    }
                }
            }

            for (var i=0;i<$scope.prenotazione.cartrows.length;i++) {
                var _pren = $scope.prenotazione.cartrows[i];
                var _serviziAggiuntivi = _pren.serviziAggiuntivi;

                for (var a=0;a<_serviziAggiuntivi.length;a++) {
                    var _serviziAggiuntivo = _serviziAggiuntivi[a];
                    if (_serviziAggiuntivo.Idroomtype != undefined) {
                        if (_serviziAggiuntivo.enable==undefined || _serviziAggiuntivo.enable==0) {
                            _serviziAggiuntivo.Quantita = 0;
                        }
                        _serviziAggiuntivo.MaxdisponibilitaReale = (_serviziAggiuntivo.Quantita*1) + _serviziAggiuntivoTest[_serviziAggiuntivo.Idservice];
                    }
                }
            }


            console.log(_serviziAggiuntivoTest);
        }

        $scope.getServiziAggiuntiviAttivi = function (serviziAggiuntivi) {
            var _ret = [];
            for (var i=0;i<serviziAggiuntivi.length;i++) {
                if ( serviziAggiuntivi[i].Idhtroomtypeserviceobb == 1 ||
                     serviziAggiuntivi[i].Idhtroomtypeserviceobb == 2 ) {
                    if (serviziAggiuntivi[i].Idhtroomtypeserviceobb==1 || serviziAggiuntivi[i].enable==1) {
                        _ret.push (serviziAggiuntivi[i]);
                    }
                }
            }
            return _ret;
        }
        
        // funzioni di TEST
        $scope.testShowAction = function () {
            if ($scope.steps[$scope.prenotazione.step].testShowAction != undefined) {
                return $scope.steps[$scope.prenotazione.step].testShowAction();
            }
            return true;
        }

        $scope.testDisableAction = function () {
            if ($scope.steps[$scope.prenotazione.step].testDisableAction != undefined) {
                return $scope.steps[$scope.prenotazione.step].testDisableAction();
            }
            return false;
        }

        $scope.testShowModifica = function (step) {
            if ($scope.steps[step].testShowModifica != undefined) {
                return $scope.steps[step].testShowModifica();
            }
            return false;
        }

        // funzioni Varie
        $scope.updateStatus = function () {
            $scope.prenotazione.summary1 = "";
            if ($scope.prenotazione.cartrows.length > 0) {
                for (var i = 0; i < $scope.prenotazione.cartrows.length; i++) {
                    $scope.prenotazione.summary1 += "<b>" + $scope.strlang($scope.prenotazione.cartrows[i].roomtypename) + "</b>";
                    $scope.prenotazione.summary1 += " {{'cms.pagepren.general.Mess.Dal' | mytranslate}} " + $filter('date')($scope.prenotazione.cartrows[i].dataDa, 'dd/MM/yyyy') + " {{'cms.pagepren.general.Mess.Al' | mytranslate}} " + $filter('date')($scope.prenotazione.cartrows[i].dataAl, 'dd/MM/yyyy');
                    $scope.prenotazione.summary1 += "<div class='boxsummaryBtn'><span class='boxsummaryBtnLink' ng-click='viewRowCart(" + i + ")'>{{'cms.pagepren.general.btn.Visualizza' | mytranslate}}</span>";                
                    $scope.prenotazione.summary1 += "</div>";
                }
            }

            if ($scope.prenotazione.anagraficanoncompleta == true) {
                $scope.prenotazione.summary2 = "";
                $scope.prenotazione.summary2 += $scope.prenotazione.nome + " " + $scope.prenotazione.cognome + "<br>";
                $scope.prenotazione.summary2 += $scope.prenotazione.mail + " - tel:" + $scope.prenotazione.telefono + "<br>";
                $scope.prenotazione.summary2 += $scope.prenotazione.indirizzo + " " + $scope.prenotazione.citta + " " + $scope.prenotazione.nazione + "<br>";
                $scope.prenotazione.summary2 += $scope.prenotazione.note;
            }

            if ($scope.serviziAggiuntivi != undefined) {
                $scope.prenotazione.summary3 = "";
                for (var i = 0; i < $scope.serviziAggiuntivi.length; i++) {
                    if ($scope.serviziAggiuntivi[i].selected == true) {
                        $scope.prenotazione.summary3 += $scope.serviziAggiuntivi[i].name + "<br>";
                    }
                }
                if ($scope.prenotazione.step >= 3 && $scope.prenotazione.summary3 == "") {
                    $scope.prenotazione.summary3 = "Nessuno";
                }
            }

            $scope.labels = {};
            for (var i = 1; i < $scope.steps.length; i++) {
                $scope.labels["title" + i] = $scope.steps[i].label;

                if ($scope.prenotazione.step == i) {
                    $scope.labels["title" + i] = $scope.steps[i].labelActive;
                    $scope.azioneDescr = $scope.steps[i].azioneDescr;
                }
            }

            $scope.checkHeightBoxRiepilogo();

            if ($scope.prenotazione.dateOK == true) {
                if (__nolog == "") {
                    var _mess = angular.copy($scope.prenotazione);
                    _mess.dataDa = $filter('date')(_mess.dataDa, 'yyyy-MM-dd');
                    _mess.dataAl = $filter('date')(_mess.dataAl, 'yyyy-MM-dd');
                
                    $http.post("pacifik/client/modules/hotels/services/readopen/insertbookengstats", _mess).then(function (resp) {});
                }

            }
        }

        $scope.scrollToId = function (id) {
            $timeout(function () {
                if (id == "ancoraStep1") {
                    dest = 0;
                } else {
                    dest = $("#" + id).offset().top;
                    dest -= 63;
                }

                $('html,body').animate({
                    scrollTop: dest
                }, 300, 'swing');

            }, 300);
        }

        $scope.openDetailsRoom = function (itemExt) {
            $scope.showPageDetail = true;
            $scope.roomInDetail = itemExt;
            
            if ($scope.roomInDetail == undefined) {
                if (itemExt.Condizionivend!=undefined && itemExt.Condizionivend.length>0) {
                    $scope.roomInDetail = itemExt.Condizionivend[0];
                } else if (itemExt.Idcondizionevendita!=undefined) {
                    $scope.roomInDetail = itemExt;
                }
            }
            
            if ($scope.roomInDetail == undefined) {
                return;
            }
            
            $scope.roomInDetail.dataDa = $scope.prenotazione.dataDa;
            $scope.roomInDetail.dataAl = $scope.prenotazione.dataAl;
            $scope.scrollToId('ancoraStep1');
        }

        $scope.closeDetailsRoom = function () {
            $scope.showPageDetail = false;
        }

        $scope.setcaparra = function (modpag) {
            var _str = $scope.strlang(modpag.Descrizione);
            return _str.replace(/_CAPARRA_/g, $filter('mycurrency')(modpag.Importocaparra));
        }

        $scope.cartaCreditoValida = function (item, numeroCarta, mese, anno, cardname, numeroValido, meseValido, annoValido, cvc) {
            var _ret = undefined;
            $scope.prenotazione.cardValid = true;

            var _numeroNonValido = 0;
            var _dataNonValido = 0;
            var _intestataNonValido = 0;
            var _cvcNonValido = 0;

            if (numeroCarta == undefined) {
                $scope.prenotazione.cardValid = false;
            } else {
                if (numeroCarta.trim() == "") {
                    $scope.prenotazione.cardValid = false;
                }
            }

            if (numeroValido == false) {
                $scope.prenotazione.cardValid = false;
                _numeroNonValido = 1;
            }
            if ($scope.prenotazione.cardValid == true && (
                    mese == undefined ||
                    mese == "" ||
                    anno == undefined ||
                    anno == "" ||
                    meseValido == false ||
                    annoValido == false)) {
                _dataNonValido = 1;
                $scope.prenotazione.cardValid = false;
            }
            if (item.Mostraintestatario==1) {
                if ($scope.prenotazione.cardValid == true && (
                        cardname == undefined ||
                        cardname == "")) {
                    $scope.prenotazione.cardValid = false;
                }
            }
            if (item.Mostracvc==1) {
                if ( cvc == undefined ||
                     cvc == "") {
                    $scope.prenotazione.cardValid = false;
                } else if ( (cvc.length!=3 && cvc.length!=4) ||
                     /^\d+$/.test(cvc)==false ) {
                    _cvcNonValido = 1;
                    $scope.prenotazione.cardValid = false;
                }
            }

            _numeroCartaReal = document.getElementById("cardNumber").value;
            _cardMonthReal = document.getElementById("cardMonth").value;
            _cardYearReal = document.getElementById("cardYear").value;

            if (_numeroNonValido==1 && _numeroCartaReal!= undefined && _numeroCartaReal.length == 16) {
                _ret = $filter('mytranslate')('cms.pagepren.Lacartadicreditononècorretta');    
            } else if (_dataNonValido==1 && 
                       _cardMonthReal!=undefined && _cardMonthReal!="" && _cardMonthReal!="0" && 
                       (_cardMonthReal.length==1 || _cardMonthReal.length==2) && 
                       _cardYearReal!=undefined && _cardYearReal!="" && 
                       _cardYearReal.length==2) {
                _ret = $filter('mytranslate')('cms.pagepren.Ladatadiscadenzanonecorretta');
            } else if (_cvcNonValido==1 && cvc.length>=3) {
                _ret = $filter('mytranslate')('cms.pagepren.IlcampoCVCnonenelformatocorretto');
            } else if (_numeroNonValido==1 && _numeroCartaReal!= undefined && _numeroCartaReal.length < 16 &&
                       _cardMonthReal!=undefined && _cardMonthReal!="" &&
                       _cardYearReal!=undefined && _cardYearReal!="" && 
                       cvc!=undefined && cvc!=""
                      ) {
                _ret = $filter('mytranslate')('cms.pagepren.Lacartadicreditononècorretta');    
            } else if (_numeroNonValido!=1 && _numeroCartaReal!= undefined && (_numeroCartaReal.length == 16 || _numeroCartaReal.length == 15) ) {
                if ($scope.prenotazione.modPagamento.Noamericanexpress==1 && _numeroCartaReal[0]==3 && _numeroCartaReal.length == 15) {
                    _ret = $filter('mytranslate')('cms.pagepren.Questacartadicreditononeaccettata');
                }                
                if ($scope.prenotazione.modPagamento.Novisa==1 && _numeroCartaReal[0]==4 && _numeroCartaReal.length == 16) {
                    _ret = $filter('mytranslate')('cms.pagepren.Questacartadicreditononeaccettata');
                }                
                if ($scope.prenotazione.modPagamento.Nomastercard==1 && (_numeroCartaReal[0]==5 || _numeroCartaReal[0]==2) && _numeroCartaReal.length == 16) {
                    _ret = $filter('mytranslate')('cms.pagepren.Questacartadicreditononeaccettata');
                }                
                if ($scope.prenotazione.modPagamento.Nodiscovercard==1 && _numeroCartaReal[0]==6 && _numeroCartaReal.length == 16) {
                    _ret = $filter('mytranslate')('cms.pagepren.Questacartadicreditononeaccettata');
                }                
            }

            //_ret = "Valorizzare il campo 'Intestata a'";
            //_ret = "Valorizzare il campo 'CVC', si trova dietro la tua carta di credito";

            return _ret;
        }

        $scope.enabledTastoPrenota = function () {
            if ($scope.getRichiediCaparra() == false) {
                return true;
            }
            
            if ($scope.prenotazione.modPagamento == undefined) {
                return false;
            }
            if ($scope.prenotazione.modPagamento.Type == "CC" && $scope.prenotazione.cardValid == false) {
                return false;
            }
            if ($scope.prenotazione.modPagamento.Type == "Stripe" && $scope.prenotazione.cardStripeValid == false) {
                return false;
            }
            return true;
        }
        
        $scope.getStatoCodiceSconto = function () {            
            if ($scope.prenotazione.codiceSconto == null) {$scope.prenotazione.codiceScontoValore=null; return null;}
            if ((""+$scope.prenotazione.codiceSconto).trim() == "") {$scope.prenotazione.codiceScontoValore=null; return null;}
            
            if ($scope.prenotazione.codiceScontoValore != null) {
                return "OK";
            } else {
                if ($scope.modificatoCodiceSconto == 1) {
                    return "KO";
                } else {
                    return "INSERIMENTO";
                }
            }
        }
        
        $scope.onChangeCodiceSconto = function (modificato) {
            if (modificato==1) {
                $scope.modificatoCodiceSconto = 1;
            }
            
            var _mess = {};
            _mess.language = $scope.prenotazione.language;
            _mess.codiceSconto = $scope.prenotazione.codiceSconto;
            _mess.idcondizionevendita = [];
            
            var _idcondizionevenditaArr = {};
            
            if ($scope.prenotazione.cartrows.length>0) {
                _mess.dataCheckin = $filter('date')($scope.prenotazione.cartrows[0].dataDa, 'yyyy-MM-dd');                
                _mess.numNotti = $scope.prenotazione.cartrows[0].numNotti;

                for (var i=0;i<$scope.prenotazione.cartrows.length;i++) {
                    _idcondizionevenditaArr[$scope.prenotazione.cartrows[i].Idcondizionevendita] = 123;
                }
            } else {
                return;
            }
            
            for (_idcondizionevendita in _idcondizionevenditaArr) {                
                _mess.idcondizionevendita.push(_idcondizionevendita);
            }
            
            if ($scope.prenotazione.codiceScontoCalcolo == undefined) $scope.prenotazione.codiceScontoCalcolo = 0; 
            
            $scope.prenotazione.codiceScontoCalcolo++;
            $http.post("pacifik/client/modules/hotels/services/readopen/getcodicesconto", _mess).then(function (resp) {
                $scope.prenotazione.codiceScontoCalcolo--;
                
                var _sconto = resp.data;
                
                if (_sconto.codiceSconto == $scope.prenotazione.codiceSconto) {
                    if (_sconto.Valore != null) {
                        $scope.prenotazione.Idcodicesconto = _sconto.Idcodicesconto;
                        $scope.prenotazione.codiceScontoValore = _sconto.Valore;
                        $scope.prenotazione.codiceScontoTipo = _sconto.Tipo;
                        if (_sconto.testobookingengine!=null && _sconto.testobookingengine!="") {
                            $scope.prenotazione.testobookingengine = _sconto.testobookingengine;
                        }
                    } else {
                        $scope.prenotazione.Idcodicesconto = null; 
                        $scope.prenotazione.codiceScontoValore = null; 
                    }                
                }
            });
        }
        
        // gestione carrello
        $scope.addToCart = function (pren, solorichiesta) {
            $scope.prenotazione.solorichiesta = solorichiesta;
            if ($scope.prenotazione.solorichiesta == undefined) $scope.prenotazione.solorichiesta = 0;
            
            var _pren = angular.copy(pren);

            if (_pren['Ok'] != 1) {
                return false;
            }

            _pren.dataDa = angular.copy($scope.prenotazione.dataDa);
            _pren.dataAl = angular.copy($scope.prenotazione.dataAl);

            for (i=_pren.NumBambini;i<100;i++) {
                delete _pren.EtaBambini[i];
            }
                        
            _pren.numNotti = $scope.getNumNotti($scope.prenotazione);

            var _qtaInserita = 0;
            for (let i=0;i<$scope.prenotazione.cartrows.length;i++) {
                if ($scope.prenotazione.cartrows[i].UniqueKey == pren.UniqueKey) {
                    _qtaInserita++;
                }
            }

            for (let a=0;a<(_qtaInserita-pren.Quantita); a++) {
                for (let i=0;i<$scope.prenotazione.cartrows.length; i++) {
                    if ($scope.prenotazione.cartrows[i].UniqueKey == pren.UniqueKey) {
                        $scope.prenotazione.cartrows.splice(i, 1); 
                        i = $scope.prenotazione.cartrows.length;
                    }
                }
            }

            for (let i=0;i<(pren.Quantita-_qtaInserita); i++) {
                _pren.idrowpren = (new Date()).getTime();
                $scope.prenotazione.cartrows.push(_pren);
            }
        }
        
        $scope.addARoom = function () {
            for (var i=$scope.prenotazione.alloggiInRicerca.length;i<=$scope.prenotazione.numAlloggi;i++) {
                $scope.prenotazione.alloggiInRicerca.push({
                    numAdulti: 2,
                    numBambini: 0,
                    etaBambini: angular.copy(__prenotazioneEtaBambini)
                })
            }
        }
        
        $scope.viewRowCart = function (pos) {
            $scope.openDetailsRoom($scope.prenotazione.cartrows[pos]);
        }

        $scope.deleteFromCart = function (pos) {
            $scope.prenotazione.codiceSconto = "";
            $scope.prenotazione.cartrows.splice(pos, 1);
            if ($scope.prenotazione.cartrows.length == 0) {
                $scope.aggiungiAlloggio();
            } else {
                $scope.updateStatus();
            }
        }

        $scope.prenotaOra = function () {
            if ($scope.enabledTastoPrenota() == false) {
                return;
            }

            if (typeof(goog_report_conversion) == 'function') {
                goog_report_conversion();
            }

            var _go = true;
            if ($scope.steps[$scope.prenotazione.step].testAction != undefined) {
                _go = $scope.steps[$scope.prenotazione.step].testAction();
            }
            if (_go != true) {
                return;
            }

            for (var i = 0; i < $scope.prenotazione.cartrows.length; i++) {
                $scope.prenotazione.cartrows[i].dataDaStr = $filter('date')($scope.prenotazione.cartrows[i].dataDa, 'yyyy-MM-dd')
                $scope.prenotazione.cartrows[i].dataAlStr = $filter('date')($scope.prenotazione.cartrows[i].dataAl, 'yyyy-MM-dd')

                $scope.prenotazione.cartrows[i]["etaBambini"] = $scope.prenotazione.cartrows[i]["EtaBambini"];
                $scope.prenotazione.cartrows[i]["numAdulti"] = $scope.prenotazione.cartrows[i]["NumAdulti"];
                $scope.prenotazione.cartrows[i]["numBambini"] = $scope.prenotazione.cartrows[i]["NumBambini"];
            }

            $scope.prenotazione.idcanalevendita = __idcanalevendita;

            $rootScope.showLoading(true);
            $http.post("pacifik/client/modules/hotels/services/readopen/insertPrenotazionev2", $scope.prenotazione).then(function (resp) {
                var _resp = resp.data;

                if (_resp.indexOf("ERROR_10") >= 0) {
                    var _pos = _resp.split(";")[1];
                    var _mess = $filter('mytranslate')('cms.pagepren.general.ErrorecamNoDisp');
                    _mess = _mess.replace("%TIPO_CAM%", $scope.strlang($scope.prenotazione.cartrows[_pos].roomtypename));
                    alert(_mess);
                    $scope.prenotazione.cartrows.splice(_pos, 1);
                    $rootScope.showLoading(false);
                    if ($scope.prenotazione.cartrows.length == 0) {
                        $scope.aggiungiAlloggio();
                    } else {
                        $scope.updateStatus();
                    }
                    return;
                }

                $scope.prenotazione.numprenotazione = _resp;

                if ($scope.prenotazione.Richiedicaparra==0 || $scope.prenotazione.modPagamento.Type=='Generico' || $scope.prenotazione.modPagamento.Type=='BON' || $scope.prenotazione.modPagamento.Type=='CC') {
                    //$scope.statoPagina = 'THANKUPAGE';
                    //$scope.scrollToId('ancoraStep1');

                    $http.get("pacifik/client/modules/hotels/services/readopen/sendMailPrenotazione?numprenotazione=" + $scope.prenotazione.numprenotazione).then(function(){
                        var _url = window.location.href + "&thankupage=1&numprenotazione=" + $scope.prenotazione.numprenotazione;
                        _url = _url.replace("paginaprenotazione", "thankupage")
                        _url = _url.replace("thankupagev2", "thankupage")
                        $rootScope.showLoading(false);
                        window.location.href = _url;
                    })
                }
                if ($scope.prenotazione.modPagamento.Type == 'Paypal') {
                    $scope.startPaymentPayPal();
                }
                if ($scope.prenotazione.modPagamento.Type == 'Stripe') {
                    $rootScope.showLoading(false);
                    $scope.startPaymentStripe();
                }
                if ($scope.prenotazione.modPagamento.Type == 'BancaSella') {
                    $rootScope.showLoading(false);
                    $scope.startPaymentBancaSella();
                }
            });
        }
        
        ////////////////////////////////////////////////////////////
        $scope.startPaymentStripe = function () {
            var _mess = {};

            if (__stripeUserID == "") {
                alert ("Attenzione, Stripe non è configurato correttamente. Contattare la assistenza");
                return;
            }

            _mess.Importo = $scope.prenotazione.modPagamento.Importocaparra * 100;
            
            //if ($scope.prenotazione.mail == "piccinini.luca@gmail.com") {
            //    _mess.Importo = 0.5 * 100;
            //}
            
            _mess.Email = $scope.prenotazione.mail;
            _mess.stripeUserID = __stripeUserID;
            
            _mess.Description = "Xenion Book.Eng. - " + 
                                $scope.prenotazione.nome + " " + 
                                $scope.prenotazione.cognome + " - " + 
                                $scope.prenotazione.numprenotazione; 
            
            _mess.Metadata = {};
            _mess.Metadata.source = "BookEngineXenion";
            _mess.Metadata.numprenotazione = $scope.prenotazione.numprenotazione;
            _mess.Metadata.idstructure = $scope.prenotazione.idstructure;
            _mess.Metadata.importocaparra = $scope.prenotazione.modPagamento.Importocaparra;
            _mess.Metadata.databasename = __nomeCartellaServer;

            $rootScope.showLoading(true);
            
            $scope.summaryError = "";
            
            $http.post("pacifik/client/modules/common/services/readopen/stripeGetPaymentIntent", _mess).then(function (resp) {
                $scope.stripeObj.handleCardPayment( resp.data, $scope.cardElement, {
                        payment_method_data: {}
                    }
                ).then(function(result) {
                    if (result.error) {
                        $rootScope.showLoading(false);
                        $scope.summaryError = result.error.message;
                        $scope.$apply();
                    } else {
                        var _url = window.location.href + "&thankupage=1&numprenotazione=" + $scope.prenotazione.numprenotazione;
                        _url = _url.replace("paginaprenotazione", "thankupage")
                        $rootScope.showLoading(false);
                        window.location.href = _url;
                    }
                });
            });
        };
        
        $scope.startPaymentBancaSella = function () {
            $url = "https://ecomms2s.sella.it/api/v1/payment/create/";

            if (__bancasellaShoplogin == "" || __bancasellaApikey == "") {
                alert ("Attenzione, Banca Sella non è configurato correttamente. Contattare la assistenza");
                return;
            }

            var _mess = {};
            _mess.shopLogin = __bancasellaShoplogin;
            _mess.amount = $scope.prenotazione.modPagamento.Importocaparra;
            _mess.currency = "EUR";
            _mess.shopTransactionID = $scope.prenotazione.numprenotazione;

            var _headers = {};
            _headers.headers = {};
            _headers.headers["Authorization"] = 'apikey ' + __bancasellaApikey;
            _headers.headers["Content-Type"] = 'application/json';

            $rootScope.showLoading(true);

            $http.post($url, _mess, _headers).then(function (resp) {
                $rootScope.showLoading(false);
                resp = resp.data;
                if (resp.error.code == 0) {
                    axerve.lightBox.shop = __bancasellaShoplogin;
                    axerve.lightBox.open(resp.payload.paymentID, resp.payload.paymentToken, function (response) {
                        $rootScope.showLoading(true);
                        if (response.status == "OK") {
                            //console.log(response.paymentId);

                            $scope.prenotazione.bancaSellaPaymentId = response.status;
    
                            $http.post("pacifik/client/modules/hotels/services/readopen/registerBancaSellaTrans", $scope.prenotazione).then(function (resp) {                                
                                var _url = window.location.href + "&thankupage=1&numprenotazione=" + $scope.prenotazione.numprenotazione;
                                _url = _url.replace("paginaprenotazione", "thankupage")
                                $rootScope.showLoading(false);
                                window.location.href = _url;
                            });                        
                        } else {
                            $scope.summaryError = "Mi spiace, si è verificato un errore durante la procedura di pagamento! Non possiamo al momento accettare la tua prenotazione. Riprova ad effettuare il pagamento, o utilizza un altro metodo di pagamento.";
                            $rootScope.showLoading(false);
                            $scope.$apply();
                        }                        
                    });
                } else {
                    alert ("ERRORE:  " + resp.error.description);
                }
            });
        }

        $scope.startPaymentPayPal = function () {
            $rootScope.showLoading(true);

            $scope.payPalName = $scope.prenotazione.datiStruttura.nome;
            $scope.payPalOrderNumber = $scope.prenotazione.numprenotazione;
            $scope.payPalTotCartPrice = $scope.prenotazione.modPagamento.Importocaparra;
            
            var _url = window.location.href + "&thankupage=1&numprenotazione=" + $scope.prenotazione.numprenotazione;
            _url = _url.replace("paginaprenotazione", "thankupage")
            $scope.payPalRet = _url;

            var _url = window.location.href;
            $scope.payPalNotifyUrl = "https://my." + _url.split('/')[2].split('.')[1] + "." + _url.split('/')[2].split('.')[2] + "/" + _url.split('/')[3];
            $scope.payPalNotifyUrl += "/pacifik/client/modules/hotels/services/readopen/registerPaypalTrans";
            
            //if ($scope.prenotazione.cognome == "Piccinini") {
            //    $scope.payPalTotCartPrice = 0.1;
            //}
            
            $timeout(function () {
                document.getElementById("payPalForm").submit();
            }, 800);
        }

        // funzioni relative ai servizi aggiuntivi
        $scope.abilitaservizio = function (servagg, pren) {
            if (servagg.Idhtroomtypeserviceobb == 1) {
                return;
            }
            if (servagg.enable == undefined) servagg.enable = 0;
            servagg.enable = !servagg.enable;
            
            $scope.updateStatus();
            $scope.onChangeQtaservizi();
        }

        // funzioni utilità varie
        $scope.addHystoryAct = function (descr) {
            $scope.prenotazione.hystoryAction.push({
                descr: descr
            });
        }

        $scope.changelanguage = function (lang) {
            $scope.prenotazione.language = lang;

            if (typeof (Storage) !== "undefined") {
                localStorage.removeItem($scope.storageVar);
            }

            location.href = "paginaprenotazione?idstructure=" + __idstructureRequest + "&lang=" + lang;
        }

        $scope.strlang = function (input) {
            if (input == undefined)
                input = "";
            input = (""+input).trim();

            _json = input.replace("multilanguage=", "");
            try {
                _json = JSON.parse(_json);
                _out = _json[__preferredLanguage];
                if (_out == undefined || _out == "") {
                    _out = _json["en"];
                }
                if (_out == undefined || _out == "") {
                    _out = "";
                    for (i in _json) {
                        _out = _json[i];
                        break;
                    }
                }
            } catch (e) {
                _out = input;
            }
            return _out.trim();
        };

        $scope.range = function (min, max, step) {
            step = step || 1;
            var input = [];
            for (var i = min; i < max; i += step) {
                input.push(i);
            }
            return input;
        };

        $scope.checkMail = function (val) {
            if (val == "") {
                return false;
            }
            var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
            return re.test(val.trim());
        }

        angular.element($window).unbind("scroll");
        angular.element($window).bind("resize", function (evt) {
            $scope.checkHeightBoxRiepilogo();
        });

        $scope.checkHeightBoxRiepilogo = function () {
            $timeout(function () {
                var div = $("#boxriepilogo").height();
                var win = $(window).height();

                if ((div + 90) > win) {
                    $scope.boxriepilogoFixed = false;
                } else {
                    $scope.boxriepilogoFixed = true;
                }
                if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
                    $scope.$apply();
                }
            }, 200);
        }

        $scope.presenzaServizi = function () {
            if ($scope.prenotazione.solorichiesta == 1) {
                return false;
            }
            
            var servizi = false;
            if ($scope.prenotazione.cartrows.length > 0) {
                for (var x = 0; x < $scope.prenotazione.cartrows.length; x++) {
                    var arrServizi = $scope.prenotazione.cartrows[x].serviziAggiuntivi;
                    
                    for (var s=0;s<arrServizi.length;s++) {
                        if (arrServizi[s].Idhtroomtypeserviceobb==1 || arrServizi[s].Idhtroomtypeserviceobb==2) {
                            servizi = true;
                        }
                    }
                }
            } else {
                servizi = true;
            }
            
            if (servizi == true) {
                impostaNumeriStep(4);
            } else {
                impostaNumeriStep(3);
            }
            
            return servizi;
        }

        $scope.presenzaRiepilogo = function () {
            if ($scope.prenotazione.solorichiesta == 1) {
                return false;
            }
            return true;
        }
        
//        $scope.mostraServizi = function () {
//            if ($scope.presenzaServizi == true || $scope.prenotazione.step==3) {
//                return true;
//            } else {
//                return false;
//            }
//        }

        $scope.startApp();

    }]);


cmsMain.config(function ($datepickerProvider) {
    angular.extend($datepickerProvider.defaults, {
        dateFormat: 'dd/MM/yyyy',
        startWeek: 1,
        autoclose: true
    });
});

function initMap() {
    var latitudine = __struttura.latitudine * 1;
    var longitudine = __struttura.longitudine * 1;
    var coordinate = {lat: latitudine, lng: longitudine};
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: coordinate
    });
    var marker = new google.maps.Marker({
        position: coordinate,
        map: map
    });
}

function impostaNumeriStep(num) {
    $('#prenotazione-step4 .numbersezione').html(num);
}