/* Minification failed. Returning unminified contents.
(24,45-46): run-time warning JS1195: Expected expression: >
(25,32-33): run-time warning JS1014: Invalid character: `
 */
var ViewEngine = angular.module('ViewEngine', []);

ViewEngine.run(function () {
    console.info('HWeb.ViewEngine: Running!');
    $('body').addClass('show-body');
    var lazyLoadInstance = new LazyLoad({ // Init LazyLoad
        elements_selector: ".lazyload"
    });

    addQueryStringsToLinks();
    
});

function addQueryStringsToLinks() {
    $('a').each(function () {
        var url = $(this).attr('href');

        if (url && url !== '#' && !url.includes('tel:') && !url.includes('mailto:')) {

            var arrayOfUTM = Object.entries(_UTMParameters);

            if (Object.keys(_UTMParameters).length > 0) {
                if (url.includes('?')) {
                    arrayOfUTM.forEach(utm => {
                        url += `&${utm[0]}=${utm[1]}`;
                    });
                } else {
                    arrayOfUTM.forEach((utm, index) => {
                        if (index === 0) {
                            url += `?${utm[0]}=${utm[1]}`;
                        } else {
                            url += `&${utm[0]}=${utm[1]}`;
                        }
                    });
                }
            } else {
                if (url.includes("hbook.hsystem.com.br/booking?companyId=")) {
                    url += '&utm_source=website&utm_medium=book-button&utm_campaign=website';
                }
            }

            if (_lang !== 'pt') {
                if (url.includes("hbook.hsystem.com.br/booking?companyId=")) {
                    url += `&language=${_lang}`;
                } else {
                    if (url.includes("?")) {
                        url += `&lang=${_lang}`;
                    } else {
                        url += `?lang=${_lang}`;
                    }
                }
            }

            $(this).attr('href', url);
        }
    });
}

var TooltipUtils = function (attrsId, selector, status, attrSelect) {
    attrSelect !== null ? attrSelect : 'ng-model';
    if (status === "hide") {
        $('#' + attrsId + ' [' + attrSelect + '="' + selector + '"]').tooltip('hide');
    } else {
        $('#' + attrsId + ' [' + attrSelect + '="' + selector + '"]').tooltip('show');
    }
};

var SelectorElement = function (attrsId, selector) {
    return $('#' + attrsId + ' [ng-model="' + selector + '"]').val();
};

ViewEngine.controller('BookingBoxController', ['$scope', '$rootScope', '$attrs', function ($scope, $rootScope, $attrs) {

    $scope.calendar = {};
    $scope.calendar.input = {};
    $scope.showPromotion = false;

    $scope.showAgeSelection = false;

    $scope.calendar.listChildren = [];
    $scope.calendar.listAdults = [];

    $scope.calendar.input.children = null;
    $scope.calendar.input.promotionCode = null;
    $scope.calendar.input.adults = null;

    $scope.DropUp = false;

    $scope.ItemAgesSelected = null;

    $scope.ChildAges = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];

    $scope.childrenCount = 0;
    $scope.adultsCount = 0;
    $scope.initialAdultsCount = 0;

    $scope.setInitialParameters = function (childrenCount, adultsCount, initialAdultsCount) {
        $scope.childrenCount = parseInt(childrenCount);
        $scope.adultsCount = parseInt(adultsCount);
        $scope.initialAdultsCount = parseInt(initialAdultsCount);
        initializeComponents();
    }

    var initializeComponents = function () {

        //List Children
        for (var i = 0; i <= $scope.childrenCount; i++) {
            var s = '';

            if (i == 0) {
                s = window.TextResources.lblBookingBoxChild;
            } else if (i == 1) {
                s = '1 ' + window.TextResources.lblBookingBoxChild;
            } else {
                s = i + " " + window.TextResources.lblBookingBoxChildren;
            }

            var itemChild = { key: i, value: s };
            $scope.calendar.listChildren.push(itemChild);
        }

        //HBook URL
        $rootScope.UrlHBook = _urlHbook ? _urlHbook : '';

        // List Adults
        for (var i = 1; i <= $scope.adultsCount; i++) {
            var itemAdult = { key: i, value: i > 1 ? i + " " + window.TextResources.lblBookingBoxAdults : '1 ' + window.TextResources.lblBookingBoxAdult };
            $scope.calendar.listAdults.push(itemAdult);
        };

        // Set Initial Adults and Children
        $scope.calendar.input.adults = $scope.calendar.listAdults[$scope.initialAdultsCount-1];
        $scope.calendar.input.children = $scope.calendar.listChildren[0];

    };

    var setInputListChildren = function () {
        $scope.ItemAgesSelected = null;

        $scope.ListInputChilren = [];

        for (var j = 1; j < $scope.calendar.input.children.key + 1; j++) {
            var inputItem = { key: j, caption: window.TextResources.lblBookingBoxChild + ' ' + j, value: "0" }
            $scope.ListInputChilren.push(inputItem);
        }

    };

    $scope.$watch('calendar.input.children', function (newValue, oldValue) {
        if (newValue.key != oldValue.key) {
            if (newValue.key <= 0) {
                $scope.ListInputChilren = [];
                $scope.ItemAges = null;
                $scope.showAgeSelection = false;
            } else {
                if (typeof AgesModalFitViewport != 'undefined') {
                    if (!AgesModalFitViewport($scope.calendar.input.children.key)) {
                        $scope.DropUp = true;
                    } else {
                        $scope.DropUp = false;
                    }
                }
                $scope.showAgeSelection = true;
            }
            setInputListChildren();
        }
    });

    $scope.AgesInputClick = function () {
        if ($scope.showAgeSelection == true) {
            $scope.showAgeSelection = false;
        } else if ($scope.calendar.input.children && $scope.calendar.input.children.key > 0) {
            $scope.showAgeSelection = true;
        }
    };

    $scope.SaveAges = function () {
        $scope.showAgeSelection = false;
        $scope.ItemAgesSelected = '';

        for (var i = 0; i < $scope.calendar.input.children.key; i++) {
            if ($scope.calendar.input.children.key == i + 1) {
                $scope.ItemAgesSelected += $scope.ListInputChilren[i].value;
            } else {
                $scope.ItemAgesSelected += $scope.ListInputChilren[i].value + ",";
            }
        }
    }

    $scope.PromoCodeButton = function () {
        if ($scope.showPromotion == true) {
            $scope.showPromotion = false;
        } else {
            $scope.showPromotion = true;
        }
    };

    $scope.Book = function (BookingId, hbookChain) {

        if (BookingId === undefined || BookingId.length <= 0) {
            BookingId = null;
        }

        var paramsHBook;
        var hasError;

        if (!hbookChain)
            BookingURL = BookingId !== null ? 'https://hbook.hsystem.com.br/booking?companyId=' + BookingId : $rootScope.UrlHBook;
        else
            BookingURL = 'https://hbook.hsystem.com.br/BookingChain?chainId=' + BookingId;

        if (BookingURL !== null && BookingURL.length > 0) {
            paramsHBook = BookingURL;
            TooltipUtils($attrs.id, "ChainItemSelected", "hide", "tool-select");
        } else {
            TooltipUtils($attrs.id, "ChainItemSelected", "show", "tool-select");
            hasError = true;
        }
        if (SelectorElement($attrs.id, "calendar.input.checkin")) {
            paramsHBook += "&checkin=" + SelectorElement($attrs.id, "calendar.input.checkin");
            TooltipUtils($attrs.id, "calendar.input.checkin", "hide");
        } else {
            hasError = true;
            TooltipUtils($attrs.id, "calendar.input.checkin", "show");
        }
        if (SelectorElement($attrs.id, "calendar.input.checkout")) {
            paramsHBook += "&checkout=" + SelectorElement($attrs.id, "calendar.input.checkout");
            TooltipUtils($attrs.id, "calendar.input.checkout", "hide");
        } else {
            hasError = true;
            TooltipUtils($attrs.id, "calendar.input.checkout", "show");
        }
        if ($scope.calendar.input.adults) {
            paramsHBook += "&adults=" + $scope.calendar.input.adults.key;
            TooltipUtils($attrs.id, "calendar.input.adults", "hide");
        } else {
            hasError = true;
            TooltipUtils($attrs.id, "calendar.input.adults", "show");
        }
        if ($scope.calendar.input.children.key > 0) {
            paramsHBook += "&children=" + $scope.calendar.input.children.key;
            TooltipUtils($attrs.id, "calendar.input.children", "hide");

            if ($scope.calendar.input.children.key != null) {
                var ages = $scope.ItemAgesSelected.split(",");
                for (var i = 0; i < ages.length; i++) {
                    paramsHBook += "&childrenage=" + ages[i];
                }
                TooltipUtils($attrs.id, "ItemAgesSelected", "hide");
            } else {
                hasError = true;
                TooltipUtils($attrs.id, "ItemAgesSelected", "show");
            }
        }

        if ($scope.calendar.input.promotionCode) {
            paramsHBook += "&promocode=" + $scope.calendar.input.promotionCode;
        }

        paramsHBook += Resources.getUTMParameters();

        if (_lang !== 'pt') {
            paramsHBook += `&language=${_lang}`;
        }

        if (!hasError) {
            window.open(paramsHBook);
        }
    };
    
}]);

ViewEngine.controller('BookingBoxChainController', ['$scope', '$rootScope', '$attrs', function ($scope, $rootScope, $attrs) {
    $scope.ListChainItem = [];
    $scope.ChainItemSelected = null;
    $rootScope.UrlHBook = null;

    $scope.SelectChainItem = function (item, arrival, departure, idForm) {

        TooltipUtils(idForm, "ChainItemSelected", "hide", "tool-select");

        $scope.ChainItemSelected = item;

        $rootScope.UrlHBook = item.UrlHBook;

        $(arrival).removeAttr('disabled');
        $(departure).removeAttr('disabled');

        var initialDateChain = moment().format("DD/MM/YYYY");
        $(arrival).val(initialDateChain);

        initialDateChain = moment(initialDateChain, 'DD/MM/YYYY').add(1, 'days');
        $(departure).val(initialDateChain.format('DD/MM/YYYY'));

        widgetScript.buildCalendar(arrival, departure, item.CompanyHbookId, null);
    };
    var init = function () {
        $scope.ListChainItem = listChainItem;
    };
    init();
}]);

ViewEngine.controller('ContactFormController', ['$scope', '$rootScope', function ($scope, $rootScope) {

    $scope.FormWidgetId = "";

    $scope.Name = "";
    $scope.NameError = false;

    $scope.Phone = "";
    $scope.PhoneError = false;

    $scope.Email = "";
    $scope.EmailError = false;
    $scope.EmailInvalid = false;

    $scope.Message = "";
    $scope.MessageError = false;

    $rootScope.CompanyId = _companyId;
    $rootScope.CompanyIdError = false;

    $scope.SendMail = function () {

        var error = false;

        var contact = {
            Name: $scope.Name,
            Email: $scope.Email,
            Phone: $scope.Phone,
            Message: $scope.Message,
            CompanyId: $rootScope.CompanyId,
            FormWidgetId: $scope.FormWidgetId
        };

        if (validate($scope.Name)) {
            $scope.NameError = false;
        } else {
            error = true;
            $scope.NameError = true;
        }

        if (validate($scope.Phone)) {
            $scope.PhoneError = false;
        } else {
            error = true;
            $scope.PhoneError = true;
        }

        if (validate($scope.Email)) {
            $scope.EmailError = false;
            if (validateEmail($scope.Email) == false) {
                error = true;
                $scope.EmailInvalid = true;
            } else {
                $scope.EmailInvalid = false;

            }
        } else {
            error = true;
            $scope.EmailError = true;
        }

        if (validate($scope.Message)) {
            $scope.MessageError = false;
        }
        else {
            error = true;
            $scope.MessageError = true;
        }

        if (validate($rootScope.CompanyId)) {
            $rootScope.CompanyIdError = false;
        }
        else {
            error = true;
            $rootScope.CompanyIdError = true;
        }

        if (!error) {

            var url = _urlGuestContact;

            $.ajax({
                url: url,
                method: 'POST',
                dataType: 'json',
                data: contact,
                success: function (result) {

                    if (result.Success) {
                        error = false;

                        if (result.Action == 'Redirect') {
                            window.location.href = result.Content;
                            return;
                        } else if (result.Action == 'Script') {
                            eval(result.Content);
                        }

                        alert(window.TextResources.msgContactFormSuccess);

                        $scope.$apply(function () {
                            $scope.Name = '';
                            $scope.Phone = '';
                            $scope.Email = '';
                            $scope.Message = '';
                        });

                    } else {
                        console.error('if=false : error');
                        console.error(result);
                    }
                },
                error: function (a, b, c) {
                    console.error(a);
                    console.error(b);
                    console.error(c);
                }
            });
        }
    };

    var init = function () {

    };

    var validate = function (value) {
        if (value == null || value == undefined || value == '') {
            return false;
        } else {
            return true;
        }
    };

    init();

}]);

ViewEngine.controller('ContactFormChainController', ['$scope', '$rootScope', function ($scope, $rootScope) {

    var init = function () {
        $rootScope.CompanyId = '';
    };

    init();

}]);

ViewEngine.controller('SubscribeFormController', ['$scope', '$rootScope', function ($scope, $rootScope) {

    $scope.Name = "";

    $scope.Email = "";
    $scope.EmailError = false;
    $scope.EmailInvalid = false;

    $scope.Origin = "";

    $scope.SendSubsricbe = function () {

        var error = false;

        var subscribe = {
            Name: $scope.Name,
            Origin: $scope.Origin,
            Email: $scope.Email,
            FormWidgetId: $scope.FormWidgetId
        };


        if (validate($scope.Email)) {
            $scope.EmailError = false;
            error = false;
            if (validateEmail($scope.Email) == false) {
                error = true;
                $scope.EmailInvalid = true;
            } else {
                $scope.EmailInvalid = false;
            }
        } else {
            error = true;
            $scope.EmailError = true;
        }

        if (!error) {

            var url = _urlGuestSubscribe;

            $.ajax({
                url: url,
                method: 'POST',
                dataType: 'json',
                data: subscribe,
                success: function (result) {

                    if (result.Success) {

                        $scope.$apply(function () {
                            $scope.Email = '';
                            $scope.Name = '';
                        });

                        if (result.Action == 'Redirect') {
                            window.location.href = result.Content;
                            return;
                        } else if (result.Action == 'Script') {
                            eval(result.Content);
                        }


                        alert(window.TextResources.msgNewsletterSuccess);

                    } else {
                        console.error('if=false : error');
                    }
                },
                error: function (a, b, c) {
                    console.error(a);
                    console.error(b);
                    console.error(c);
                }
            });
        }
    };

    var init = function () {

    };

    var validate = function (value) {
        if (value == null || value == undefined || value == '') {
            return false;
        } else {
            return true;
        }
    };


    init();
}]);

ViewEngine.controller('ContactFormCustomController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {

    $scope.FormWidgetId = "";

    $scope.CustomFieldTemplate = function (field) {
        if (field.FieldTypeStr == "TextBox") {
            return 'CustomFieldTextBox';
        }
        if (field.FieldTypeStr == "Email") {
            return 'CustomFieldEmail';
        }
        else if (field.FieldTypeStr == "File") {
            return 'CustomFieldFile';
        }
        else if (field.FieldTypeStr == "Select") {
            return 'CustomFieldSelect';
        }
        else if (field.FieldTypeStr == "CheckBox") {
            return 'CustomFieldCheckBox';
        }
        else if (field.FieldTypeStr == "Radio") {
            return 'CustomFieldRadio';
        }
        else if (field.FieldTypeStr == "TextArea") {
            return 'CustomFieldTextArea';
        }
    };

    $scope.GetGridField = function (field) {

        if (field.GridStr == 'Col1')
            return 'col-lg-1';
        else if (field.GridStr == 'Col2')
            return 'col-lg-2';
        else if (field.GridStr == 'Col3')
            return 'col-lg-3';
        else if (field.GridStr == 'Col4')
            return 'col-lg-4';
        else if (field.GridStr == 'Col5')
            return 'col-lg-5';
        else if (field.GridStr == 'Col6')
            return 'col-lg-6';
        else if (field.GridStr == 'Col7')
            return 'col-lg-7';
        else if (field.GridStr == 'Col8')
            return 'col-lg-8';
        else if (field.GridStr == 'Col9')
            return 'col-lg-9';
        else if (field.GridStr == 'Col10')
            return 'col-lg-10';
        else if (field.GridStr == 'Col11')
            return 'col-lg-11';
        else
            return 'col-lg-12';
    };

    $rootScope.CompanyId = _companyId;
    $rootScope.CompanyIdError = false;

    var convertItemsToCheck = function () {

        angular.forEach($scope.ContactFormCustom.Fields, function (field) {

            if (field.FieldTypeStr == 'CheckBox') {
                var itemsCheck = []

                angular.forEach(field.Items, function (item) {
                    var itemCheck = { Caption: item, Check: false };
                    itemsCheck.push(itemCheck);
                });

                field.Items = itemsCheck;
            }
        });
    };

    $scope.SendMailCustomForm = function () {


        var fd = new FormData();

        var error = false;

        var fileCount = 0;

        angular.forEach($scope.ContactFormCustom.Fields, function (field, index) {

            if (field.FieldTypeStr == "File") {
                fd.append('file', field.Value);
                fd.append('Fields[' + index + '][Value]', "");
                fd.append('Fields[' + index + '][FieldTypeStr]', field.FieldTypeStr);
                fd.append('Fields[' + index + '][Label]', field.Label);

                fileCount++;
            }
            else {
                //itens de checkbox
                if (field.FieldTypeStr == "CheckBox") {
                    var values = "";
                    angular.forEach(field.Items, function (item) {
                        if (item.Check) {
                            values += values.length == 0 ? item.Caption : ', ' + item.Caption;
                        }
                    });

                    field.Value = values;
                }

                fd.append('Fields[' + index + '][Label]', field.Label);
                fd.append('Fields[' + index + '][Value]', field.Value);
                fd.append('Fields[' + index + '][FieldTypeStr]', field.FieldTypeStr);
                fd.append('Fields[' + index + '][IsTitleEmail]', field.IsTitleEmail);
            }



            if (validate(field.Value)) {
                field.Error = false;
            } else {
                if (field.Required == true) {
                    error = true;
                    field.Error = true;
                }
            }

            if (validate(field.Value) && field.FieldTypeStr == "Email") {
                if (validateEmail(field.Value) == false) {
                    error = true;
                    field.ErrorEmail = true;
                }
                else {
                    field.ErrorEmail = false;
                }
            }
        });

        fd.append('MailTo', $scope.ContactFormCustom.MailTo);
        fd.append('Title', $scope.ContactFormCustom.Title);

        fd.append('FormWidgetId', $scope.FormWidgetId);
        fd.append('PageId', window._activePageId);

        if (!error) {

            var url = window._urlGuestCustomForm;

            $http.post(url, fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
                .success(function (result) {
                    if (result.Success) {
                        error = false;

                        angular.forEach($scope.ContactFormCustom.Fields, function (field) {
                            field.Value = "";
                            clearCheckItems(field);
                            $('#' + $scope.FormWidgetId).find("input[type='file']").each(function (idx, input) {
                                // Do your DOM manipulation here
                                $(input).val(null);
                            });
                        });

                        if (result.Action == 'Redirect') {
                            window.location.href = result.Content;
                            return;
                        } else if (result.Action == 'Script') {
                            eval(result.Content);
                        }

                        alert(window.TextResources.msgContactFormSuccess);

                    } else {
                        console.error('if=false : error');
                    }
                })
                .error(function (a, b, c) {
                    console.error(a);
                    console.error(b);
                    console.error(c);
                });
        }
    };

    var clearCheckItems = function (field) {
        if (field.FieldTypeStr == "CheckBox") {
            angular.forEach(field.Items, function (item) {
                item.Check = false;
            });
        }
    };

    $scope.initWidgetForm = function (FormWidgetId) {
        $scope.FormWidgetId = FormWidgetId;
        $scope.ContactFormCustom = window._contactFormCustom[$scope.FormWidgetId];
        convertItemsToCheck();
    };

    var validate = function (value) {
        if (value == null || value == undefined || value == '') {
            return false;
        } else {
            return true;
        }
    };

}]);

ViewEngine.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

var Resources = new function () {
    this.getCookie = function (cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    };

    this.getUTMParameters = function () {
        if (Object.keys(_UTMParameters).length > 0) {
            var arrayOfUTMParameters = Object.entries(_UTMParameters);
            var utms = '';

            arrayOfUTMParameters.forEach(utm => {
                utms += `&${utm[0]}=${utm[1]}`
            });

            return utms;
        } else {
            return '&utm_source=website&utm_medium=search-box&utm_campaign=website';
        }
    };
};

var validateEmail = function (value) {

    var EMAIL_REGEXP = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var isMatchRegex = EMAIL_REGEXP.test(value);
    return isMatchRegex;
};


var setCookie = function (cname, cvalue, exdays) {

    if (exdays == undefined || exdays == null || exdays == '') {
        exdays = 3;
    }

    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
};

var getCookie = function (cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
};;