
var __storageVar = "objPrenotazione_xenion_13";
cmsMain.controller('paginaacquisto', ['$scope', '$rootScope', '$window', '$http', '$timeout', '$filter',
    function ($scope, $rootScope, $window, $http, $timeout, $filter) {

        $scope.startApp = function () {
            if (__errorePaypal == 1)
                return;
            $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.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 () {
//                    if ($scope.prenotazione.cartrows.length > 0) {
//                        if ($scope.getIfroomchoosed() == true) {
//                            return $filter('mytranslate')('cms.pagepren.StepDate.btn.Prenotaancheqst');
//                        } else {
//                            return $filter('mytranslate')('cms.pagepren.StepDate.btn.Procedinoaggiungere');
//                        }
//                    }
//                    return $filter('mytranslate')('cms.pagepren.general.btn.Prenota');
//                },
//                callToAction: $scope.addToCart,
//                azioneDescr: "cms.pagepren.StepDate.AzioneDescr",
//                testShowAction: function () {
//                    return $scope.getIfroomchoosed() || ($scope.prenotazione.cartrows.length > 0);
//                }
//            }
//            
//            
            $scope.steps[1] = {
                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 () {
                    return $filter('mytranslate')('cms.pagepren.StepDatipers.Procedi');
                },
                callToAction: $scope.prenotazioneNext,
                azioneDescr: "cms.pagepren.StepDatipers.AzioneDescr",
                testAction: function () {

//                    $scope.prenotazione.nome = "Massimiliano";
//                    $scope.prenotazione.cognome = "Bacchini";
//                    $scope.prenotazione.mail = "massimiliano.bacchini@gmail.com";
//                    $scope.prenotazione.mailrep = "massimiliano.bacchini@gmail.com";
//                    $scope.prenotazione.indirizzo = "Via delle Regioni 53";
//                    $scope.prenotazione.citta = "Siena";
//                    $scope.prenotazione.nazione = "Italia";
//                    $scope.prenotazione.cap = "53100";
//                    $scope.prenotazione.telefono = "3401438239";
//                    $scope.prenotazione.presso = "Pippo Paperino";
//                    $scope.prenotazione.indirizzospedizione = "Via Roma 123";
//                    $scope.prenotazione.cittaspedizione = "Sidney";
//                    $scope.prenotazione.nazionespedizione = "Australia";
//                    $scope.prenotazione.capspedizione = "12345";

                    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.cap == undefined)
                        $scope.prenotazione.cap = "";
                    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.telefono.trim() == "" ||
                            $scope.prenotazione.indirizzo.trim() == "" ||
                            $scope.prenotazione.citta.trim() == "" ||
                            $scope.prenotazione.nazione.trim() == "" ||
                            $scope.prenotazione.cap.trim() == "" ||
                            $scope.prenotazione.mail.trim() == "") {
                        $scope.prenotazione.anagraficanoncompleta = false;
                        $scope.summaryError = $filter('mytranslate')('cms.pagepren.StepDatipers.ErrCampiObbligatori');
                        return false;
                    }

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

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

                    if ($scope.prenotazione.checkspedizione) {
                        if ($scope.prenotazione.presso == undefined)
                            $scope.prenotazione.presso = "";
                        if ($scope.prenotazione.cittaspedizione == undefined)
                            $scope.prenotazione.cittaspedizione = "";
                        if ($scope.prenotazione.nazionespedizione == undefined)
                            $scope.prenotazione.nazionespedizione = "";
                        if ($scope.prenotazione.nazionespedizione == undefined)
                            $scope.prenotazione.nazionespedizione = "";
                        if ($scope.prenotazione.capspedizione == undefined)
                            $scope.prenotazione.capspedizione = "";
                        if ($scope.prenotazione.presso.trim() == "" ||
                                $scope.prenotazione.indirizzospedizione.trim() == "" ||
                                $scope.prenotazione.cittaspedizione.trim() == "" ||
                                $scope.prenotazione.nazionespedizione.trim() == "" ||
                                $scope.prenotazione.capspedizione.trim() == "") {
                            $scope.prenotazione.anagraficanoncompleta = false;
                            $scope.summaryError = $filter('mytranslate')('cms.pagepren.StepDatipers.ErrCampiObbligatori');
                            return false;
                        }
                    }

                    $scope.prenotazione.anagraficanoncompleta = true;
                    $scope.summaryError = "";
                    return true;
                }
            }
            $scope.steps[2] = {
                label: "cms.pagepren.StepRiepilogoCarrello.label",
                labelActive: "cms.pagepren.StepRiepilogoCarrello.label",
                callToActionMsg: function () {
                    return $filter('mytranslate')('cms.pagepren.StepRiepilogo.Acquista');
                },
                callToAction: function () {
                    $scope.prenotaOra();
                },
                testDisableAction: function () {
                    return !($scope.enabledTastoPrenota());
                },
                azioneDescr: "cms.pagepren.StepRiepilogo.AzioneAcquista"
            }

            $scope.controllaCheck = function () {
                if ($scope.prenotazione.checkspedizione) {
                    $('#contenitore-indirizzo-spedizione').show(400);
                } else {
                    $('#contenitore-indirizzo-spedizione').hide(400);
                }
            }


            ///////////////////////////////////////
            if (typeof (Storage) !== "undefined") {
                var _startVal = localStorage.getItem(__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(__storageVar);
                }
            }

            if ($scope.prenotazione == undefined) {
                $scope.prenotazione = {};
                $scope.prenotazione.hystoryAction = [];
                $scope.prenotazione.step = 1;
//                $scope.prenotazione.idsession = new Date().getTime();
                $scope.prenotazione.numAdulti = 2;
                $scope.prenotazione.numBambini = 0;
                $scope.prenotazione.etaBambini = {};
                $scope.prenotazione.idmacrotipologiaall = 0;
                $scope.prenotazione.alloggi = [];
                $scope.prenotazione.possibilita = [];
                $scope.prenotazione.mostraaltrepossibilita = false;
                $scope.prenotazione.cartrows = [];
                if (__idprodotto > 0) {
                    $scope.prenotazione.roomchoosed = {};
                    $scope.prenotazione.roomchoosed.idprodotto = __idprodotto;
                }
            }

            $scope.prenotazione.datiStruttura = __struttura;
            $scope.prenotazione.language = __preferredLanguage;
            $scope.prenotazione.idstructure = __idstructure;
            $scope.prenotazione.idsessionecarrello = getUrlParameter('idsessionecarrello');
            ///////
            $scope.modPagamenti = [];

            $scope.checkHeightBoxRiepilogo();
            $scope.recuperaCarrello();
            ///////
            $http.get("pacifik/client/modules/merkurio/services/readopen/getinfoutili?Idindirizzoanag=" + $scope.prenotazione.idstructure + "&codordine=" + __codOrdine).then(function (resp) {

                $scope.infoutili = resp.data;
                $scope.modPagamenti = $scope.infoutili.modpag;
                $scope.languages = $scope.infoutili.languages;
                $scope.arrMacrotipologieall = $scope.infoutili.macrotipologieall;
                $scope.prenotazione.coordinateBanca = "";
                $scope.prenotazione.coordinateBanca += "<table>";
                $scope.prenotazione.coordinateBanca += "<tr><td>" + $filter('mytranslate')('cms.pagepren.general.intestazioneBonifico') + ":<td>&nbsp;<td>" + $scope.infoutili.intestatario + "<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>Swift:<td>&nbsp;<td>" + $scope.infoutili.swift;
                $scope.prenotazione.coordinateBanca += "<tr><td>" + $filter('mytranslate')('cms.pagepren.general.causaleBonifico') + ":<td>&nbsp;<td>Codice ordine ricevuto a seguito dell'acquisto";
                $scope.prenotazione.coordinateBanca += "</table>";
                for (var i = 0; i < $scope.modPagamenti.length; i++) {
                    var _modPag = $scope.modPagamenti[i];
                    if (_modPag['immagini']!=undefined && _modPag['immagini'].length > 0) {
                        _modPag['immagine'] = _modPag['immagini'][0].url;
                    } else {
                        _modPag['immagine'] = "";
                    }
                }

                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');
            });
        }

        $scope.changeRoom = function (room) {
            //$scope.addHystoryAct( "changeRoom="+$scope.strlang(room.roomtypename) );

            $scope.prenotazione.roomchoosed = room;
            $scope.prenotazione.roomchoosed.trovata = true;
            $scope.prenotazione.roomchoosed.show = false;
            $scope.prenotazione.mostraaltrepossibilita = false;
            $scope.updateStatus();
            $scope.scrollToId('alloggioscelto');
        }

        $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.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.aggiungiAlloggio = function () {
            $scope.summaryError = "";
            $scope.prenotazione.laststep = undefined;
            $scope.prenotazione.step = 1;
            $scope.prenotazione.roomchoosed = undefined;
            $scope.updateStatus();
        }

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

        // gestione stato
        $scope.getIfroomchoosed = function () {
            return ($scope.prenotazione.roomchoosed != undefined &&
                    $scope.prenotazione.roomchoosed.trovata == true
                    );
        }

        $scope.getTotalePrenotazione = function () {
            var _tot = $scope.getTotaleCarrello();

            if ($scope.prenotazione.nazione != null) {
                _tot += $scope.getTotaleSpedizione(_tot);
            }

            if ($scope.prenotazione.totSconto > 0) {
                _tot -= $scope.prenotazione.totSconto;
            }


            _tot = Math.round(_tot * 100) / 100;
            return _tot;
        }

        $scope.getTotaleRiga = function (riga) {
            var prezzo = calcolaPrezzo(riga.Mkprodotti.Prezzonetto, riga.Mkprodotti.MkivaRelatedByIdiva.Percentuale);
            return prezzo * riga.Quantita;
        }

        $scope.getNumItemAttivi = function (items) {
            return 1;
            var _ret = 0;
            for (var i = 0; i < items.length; i++) {
                if ($scope.getMostraInAltreSoluzioni(items[i]))
                    _ret++;
            }
            return _ret;
        }

        $scope.getMostraInAltreSoluzioni = function (room) {
            var _ret = true;
            return _ret;
            if ($scope.prenotazione.roomchoosed != undefined) {
                if (room['idroomtype'] == $scope.prenotazione.roomchoosed.idroomtype &&
                        room['idcondizionevendita'] == $scope.prenotazione.roomchoosed.idcondizionevendita) {
                    _ret = false;
                }
            }

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

            return _ret;
        }

        $scope.getNumeroAltreSoluzioni = function () {
            $scope.prenotazione.mostraaltrepossibilita = true;
            return 1;
            var _num = 0;
            for (var x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                for (var i = 0; i < $scope.prenotazione.possibilita[x].length; i++) {
                    if ($scope.getMostraInAltreSoluzioni($scope.prenotazione.possibilita[x][i]) == true) {
                        _num++;
                    }
                }
            }
            if (_num == 0) {
                $scope.prenotazione.mostraaltrepossibilita = false;
            }
            return _num;
        }

        $scope.getNumeroTutteSoluzioni = function () {
            return 1;
            var _num = 0;
            for (var x = 0; x < $scope.prenotazione.possibilita.length; x++) {
                for (var i = 0; i < $scope.prenotazione.possibilita[x].length; i++) {
                    var _valido = true;
                    var _room = $scope.prenotazione.possibilita[x][i];
                    var _qta = _room.qtadisp * 1;
                    for (var a = 0; a < $scope.prenotazione.cartrows.length; a++) {
                        if (_room['idroomtype'] == $scope.prenotazione.cartrows[a].idroomtype) {

                            if ($scope.prenotazione.roomchoosed != undefined) {
                                if (_room['idroomtype'] != $scope.prenotazione.roomchoosed.idroomtype ||
                                        _room['idcondizionevendita'] != $scope.prenotazione.roomchoosed.idcondizionevendita) {
                                    _qta--;
                                }
                            } else {
                                _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.getLabelConfletto = function (confletto) {
            var _ret = $scope.strlang(confletto.Descrizione);
            _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.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;
        }

        $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 += $scope.strlang($scope.prenotazione.cartrows[i].Nome);
//                    $scope.prenotazione.summary1 += "<div class='boxsummaryBtn'>(<span class='boxsummaryBtnLink' ng-click='viewRowCart(" + i + ")'>{{'cms.pagepren.general.btn.Visualizza' | mytranslate}}</span> - ";
//                    $scope.prenotazione.summary1 += "<span class='boxsummaryBtnLink' ng-click='deleteFromCart(" + i + ")'>{{'cms.pagepren.general.btn.Elimina' | mytranslate}}</span>)</div>";
//                }
//            }
            console.log('angrafica: ' + $scope.prenotazione.anagraficanoncompleta);
            if ($scope.prenotazione.anagraficanoncompleta == true) {
                var presso = $filter('mytranslate')('cms.pagepren.StepDatipers.label.presso');
                var indFatturazione = $filter('mytranslate')('cms.pagepren.StepDatipers.label.indirizzofatturazione');
                var indSpedizione = $filter('mytranslate')('cms.pagepren.StepDatipers.label.indirizzospedizione');
                $scope.prenotazione.summary1 = "";
                $scope.prenotazione.summary1 += $scope.prenotazione.nome + " " + $scope.prenotazione.cognome + "<br>";
                $scope.prenotazione.summary1 += $scope.prenotazione.mail + " - tel: " + $scope.prenotazione.telefono + "<br>";
                if ($scope.prenotazione.checkspedizione) {
                    $scope.prenotazione.summary1 += indFatturazione + ': ' + $scope.prenotazione.indirizzo + ", " + $scope.prenotazione.cap + " " + $scope.prenotazione.citta + " " + $scope.prenotazione.nazione + "<br>";
                    $scope.prenotazione.summary1 += indSpedizione + ': ' + presso + ' ' + $scope.prenotazione.indirizzospedizione + ", " + $scope.prenotazione.capspedizione + " " + $scope.prenotazione.cittaspedizione + " " + $scope.prenotazione.nazionespedizione + "<br>";
                } else {
                    $scope.prenotazione.summary1 += indSpedizione + ': ' + $scope.prenotazione.indirizzo + ", " + $scope.prenotazione.cap + " " + $scope.prenotazione.citta + " " + $scope.prenotazione.nazione + "<br>";
                }
                $scope.prenotazione.summary1 += $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) {
                var _mess = angular.copy($scope.prenotazione);
                _mess.dataDa = $filter('date')(_mess.dataDa, 'yyyy-MM-dd');
                _mess.dataAl = $filter('date')(_mess.dataAl, 'yyyy-MM-dd');
                if (__nolog == "") {
                    $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 (row) {
            $scope.showPageDetail = true;
            $scope.roomInDetail = row;
            $scope.scrollToId('ancoraStep1');
        }

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

        $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 == '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 = $filter('mytranslate')('cms.pagepren.general.messRicordaBonifico');
            return _str.replace(/%IMPORTODAPAG%/g, $filter('mycurrency')($scope.prenotazione.totalePagare));
        }

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

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

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

            if (numeroValido == false) {
                _ret = "La carta di credito non è corretta";
                $scope.prenotazione.cardValid = false;
            }
            if ($scope.prenotazione.cardValid == true && (
                    mese == undefined ||
                    mese == "" ||
                    anno == undefined ||
                    anno == "" ||
                    meseValido == false ||
                    annoValido == false)) {
                _ret = "La data di scadenza non è corretta";
                $scope.prenotazione.cardValid = false;
            }
            if ($scope.prenotazione.cardValid == true && (
                    cardname == undefined ||
                    cardname == "")) {
                _ret = "Valorizzare il campo 'Intestata a'";
                $scope.prenotazione.cardValid = false;
            }

            if ($scope.prenotazione.cardValid == true) {
                _ret = "La carta è corretta, puoi procedere con la prenotazione";
            }

            return _ret;
        }

        $scope.enabledTastoPrenota = function () {
            if ($scope.prenotazione.modPagamento == undefined) {
                return false;
            }
            if ($scope.prenotazione.modPagamento.Type == "CC" && $scope.prenotazione.cardValid == false) {
                return false;
            }
            return true;
        }

        // gestione carrello
        $scope.addToCart = function (pren) {
            var _pren;
            if (pren != undefined) {
                _pren = pren;
            } else {
                _pren = $scope.prenotazione.roomchoosed;
            }

            if (_pren == undefined) {
                $scope.prenotazioneNext()
            }

            _pren.idrowpren = (new Date()).getTime();
            $scope.prenotazione.cartrows.push(angular.copy(_pren));
            _pren = undefined;
            $scope.prenotazioneNext()
        }

        $scope.viewRowCart = function (pos) {
            $scope.openDetailsRoom($scope.prenotazione.cartrows[pos]);
        }

        $scope.deleteFromCart = function (pos) {
            $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;
            }
            //$scope.startPaymentPayPal ();
            //return;

            $scope.prenotazione.totalePagare = $scope.getTotalePrenotazione();
            $rootScope.showLoading(true);
            $http.post("pacifik/client/modules/merkurio/services/readopen/insertOrdineWeb", $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.codOrdine = _resp;
                if ($scope.prenotazione.modPagamento.Type == 'BON' || $scope.prenotazione.modPagamento.Type == 'CC' || $scope.prenotazione.modPagamento.Type == 'CON') {
                    $scope.statoPagina = 'THANKUPAGE';
                    $scope.scrollToId('ancoraStep1');
                    $rootScope.showLoading(false);
                    $http.get("pacifik/client/modules/merkurio/services/readopen/sendMailOrdine?codOrdine=" + $scope.prenotazione.codOrdine + "&lang=" + __preferredLanguage);
                }
                if ($scope.prenotazione.modPagamento.Type == 'Paypal') {
                    $scope.startPaymentPayPal();
                }
                if ($scope.prenotazione.modPagamento.Type == 'Stripe') {
                    $rootScope.showLoading(false);
                    $scope.startPaymentStripe();
                }
            });
        }

        //*****************         TODO: configurare url di ritorno paypal sul vecchio dominio senza https e verificare il funzionamento

        $scope.startPaymentPayPal = function () {
            $rootScope.showLoading(true);
            $scope.payPalName = $scope.prenotazione.datiStruttura.nome;
            $scope.payPalOrderNumber = $scope.prenotazione.codOrdine;
            $scope.payPalTotCartPrice = $scope.prenotazione.totalePagare;
            $scope.payPalRet = window.location.href +
                    "&thankupage=1&codordine=" + $scope.prenotazione.codOrdine;
            var _url = window.location.href;
            $scope.payPalNotifyUrl = "http://my.merkurio.it/"+_url.split('/')[3]+"/pacifik/client/modules/merkurio/services/readopen/registerPaypalTrans";
//            console.log('ret: ' + $scope.payPalRet);
//            console.log('url: ' + $scope.payPalNotifyUrl);
            $timeout(function () {
                document.getElementById("payPalForm").submit();
            }, 800);
        }

        $scope.startPaymentStripe = function () {
            var _mess = {};

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

            _mess.Importo = $scope.prenotazione.totalePagare * 100;
            
            //if ($scope.prenotazione.mail == "piccinini.luca@gmail.com") {
            //    _mess.Importo = 0.5 * 100;
            //}
            
            _mess.Email = $scope.prenotazione.mail;
            _mess.stripeUserID = __stripeUserID;
            
            _mess.Description = "Sito Web - " + 
                                $scope.prenotazione.nome + " " + 
                                $scope.prenotazione.cognome + " - " + 
                                $scope.prenotazione.codOrdine; 
            
            $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 {
                        $scope.prenotazione.tokenStripe = result.paymentIntent.id;
                        $scope.prenotazione.paymentmethod = result.paymentIntent.payment_method;
                        $scope.prenotazione.stripeUserID = __stripeUserID;

                        //$http.post("pacifik/client/modules/hotels/services/readopen/registerStripeTrans", $scope.prenotazione).then(function (resp) {
                            $scope.statoPagina = 'THANKUPAGE';
                            $scope.scrollToId('ancoraStep1');
                            $rootScope.showLoading(false);
                            $http.get("pacifik/client/modules/merkurio/services/readopen/sendMailOrdine?codOrdine=" + $scope.prenotazione.codOrdine + "&lang=" + __preferredLanguage);
                        //});                        
                    }
                });
            });
        };

        // funzioni relative ai servizi aggiuntivi
        $scope.abilitaservizio = function (servagg) {
            if (servagg.obbligatorio == 1) {
                return;
            }
            servagg.enable = !servagg.enable;
            $scope.updateStatus();
        }

        // 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.setItem(__storageVar, JSON.stringify($scope.prenotazione));
            }

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

        $scope.getTotSconto = function () {
            var sconto = $scope.prenotazione.totSconto;
            return  -Math.round(sconto * 100) / 100;
        }


        $scope.changeCodicesconto = function () {
            $scope.prenotazione.totSconto = 0;
            $scope.prenotazione.codicescontoStato = 0;
            $scope.prenotazione.codicesconto = $scope.prenotazione.codicesconto.toUpperCase();

            var contenitoreSconto = document.getElementById('cont-sconto');
            for (var key in __codiciSconto) {
                if (__codiciSconto[key]['nome'] == $scope.prenotazione.codicesconto) {
                    var percSconto = __codiciSconto[key]['val'];
                    var carrello = $scope.prenotazione.totCarrello;
                    $scope.prenotazione.percentualeSconto = percSconto;
                    $scope.prenotazione.totSconto = carrello / 100 * percSconto;
                    contenitoreSconto.style.display = 'block';
                    break;
                } else {
                    contenitoreSconto.style.display = 'none';
                }
            }


//            if ($scope.prenotazione.codicesconto == 'BEA845' ||
//                    $scope.prenotazione.codicesconto == 'SPIG22' ||
//                    $scope.prenotazione.codicesconto == 'WELO46' ||
//                    $scope.prenotazione.codicesconto == 'BIOC16' ||
//                    $scope.prenotazione.codicesconto == 'FOBI85' ||
//                    $scope.prenotazione.codicesconto == 'INSB77' ||
//                    $scope.prenotazione.codicesconto == 'CUNA55' ||
//                    $scope.prenotazione.codicesconto == 'EDEN16' ||
//                    $scope.prenotazione.codicesconto == 'AUPR99' ||
//                    $scope.prenotazione.codicesconto == 'VERD16' ||
//                    $scope.prenotazione.codicesconto == 'PATT05' ||
//                    $scope.prenotazione.codicesconto == 'BIOM21' ||
//                    $scope.prenotazione.codicesconto == 'PAVO16' ||
//                    $scope.prenotazione.codicesconto == 'NIFE16' ||
//                    $scope.prenotazione.codicesconto == 'BBLOG8' ||
//                    $scope.prenotazione.codicesconto == 'SBIO16' ||
//                    $scope.prenotazione.codicesconto == 'SANA16' ||
//                    $scope.prenotazione.codicesconto == 'IDEA16' ||
//                    $scope.prenotazione.codicesconto == 'BBCL74'
//                    ) {
//                $scope.prenotazione.totSconto = 5;
//            }
//            if ($scope.prenotazione.codicesconto == 'BBB744') {
//                $scope.prenotazione.totSconto = 10;
//            }
//            if ($scope.prenotazione.codicesconto == 'XXXmotoguzziXXX'.toUpperCase()) {
//                $scope.prenotazione.totSconto = 58.99;
//            }
            if ($scope.prenotazione.codicesconto != undefined && $scope.prenotazione.codicesconto != '' && $scope.prenotazione.totSconto > 0) {
                $scope.prenotazione.codicescontoStato = 2;
            } else {
                if ($scope.prenotazione.codicesconto != undefined && $scope.prenotazione.codicesconto != '' && $scope.prenotazione.totSconto == 0) {
                    $scope.prenotazione.codicescontoStato = 1;
                }
            }
        }

        $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.recuperaCarrello = function () {
            var idSessioneCarrello = getUrlParameter('idsessionecarrello');
            $http.get("pacifik/client/modules/merkurio/services/plugin/getcarrello?idsessionecarrello=" + idSessioneCarrello + "&language=it").then(function (resp) {
                $scope.prenotazione.cartrows = resp.data;
            })
        }

        $scope.getTotaleSpedizione = function () {
            if ($scope.prenotazione != undefined && $scope.prenotazione.nazione != undefined) {
                var indirizzoSpedizione = "";
                if ($scope.prenotazione.checkspedizione != undefined && $scope.prenotazione.checkspedizione != false && $scope.prenotazione.nazionespedizione != undefined) {
                    indirizzoSpedizione = $scope.prenotazione.nazionespedizione;
                } else {
                    indirizzoSpedizione = $scope.prenotazione.nazione;
                }
                var metodoPagamento = "";
                if ($scope.prenotazione.modPagamento != null && $scope.prenotazione.modPagamento.item != null) {
                    metodoPagamento = $scope.prenotazione.modPagamento.item;
                }
                var totSpedizione = calcolaTotSpedizione($scope.prenotazione.totCarrello, indirizzoSpedizione, metodoPagamento);
                $scope.prenotazione.totSpedizione = totSpedizione;
                return totSpedizione;
            }
        }

        $scope.getTotaleCarrello = function () {
            var _tot = 0;
            var prezzo = 0;
            for (var i = 0; i < $scope.prenotazione.cartrows.length; i++) {
                if ($scope.prenotazione.cartrows[i].Quantita == undefined)
                    $scope.prenotazione.cartrows[i].Quantita = 1;

                prezzo = calcolaPrezzo($scope.prenotazione.cartrows[i].Mkprodotti.Prezzonetto, $scope.prenotazione.cartrows[i].Mkprodotti.MkivaRelatedByIdiva.Percentuale);
                _tot += prezzo * $scope.prenotazione.cartrows[i].Quantita;
            }
            $scope.prenotazione.totCarrello = _tot;
            return Math.round(_tot * 100) / 100;
        }

        $scope.attivamodPagamento = function () {
            $scope.getTotaleSpedizione();
            $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);
        }

        var messContra = $filter('mytranslate')('cms.pagepren.general.messAcquistaContrassegno');
        //$scope.labelcontrassegno = messContra.replace("%COSTOCONTRASSEGNO%", __contrassegno);

        $scope.startApp();
    }]);
cmsMain.config(function ($datepickerProvider) {
    angular.extend($datepickerProvider.defaults, {
        dateFormat: 'dd/MM/yyyy',
        startWeek: 1,
        autoclose: true
    });
});
function getUrlParameter(param, dummyPath) {
    var sPageURL = dummyPath || window.location.search.substring(1),
            sURLVariables = sPageURL.split(/[&||?]/),
            res;
    for (var i = 0; i < sURLVariables.length; i += 1) {
        var paramName = sURLVariables[i],
                sParameterName = (paramName || '').split('=');
        if (sParameterName[0] === param) {
            res = sParameterName[1];
        }
    }

    return res;
}

function calcolaPrezzo(prezzoNetto = 0, percentualeIva = 0) {
    if (percentualeIva > 0) {
        return prezzoNetto + (prezzoNetto / 100 * percentualeIva);
    } else {
        return prezzoNetto;
}
}