var url = window.location.href;
var URL = url.substring(0, ((url.indexOf('?') === -1) ? url.length : url.indexOf('?')));

// set country code
function setSettingsCountry(country_code) {
    return ((typeof settingsObject[country_code] !== 'undefined') ? settingsObject[country_code] : settingsObject[defaultCountry])
}

$(document).ready(function () {

    // Find default country
    var country_code = $('body').find('select[name="country_code"]').val();
    var settings = setSettingsCountry(country_code);


    // Update select field from settings country
    function updateCountrySelect() {
        let html = '';
        $.each(settingsObject, function (index, value) {
            html += '<option value="' + index + '">' + value.name + '</option>';
        });

        $('select[name="country_code"]').html(html);
    }
    // Update country inputs
// updateCountrySelect();


    // Set label error 
    $.each($('input'), function (index, value) {
        let type = $(value).attr('type');
        // Label ne treba za hidden inpute
        if (type != 'hidden') {
            $('<label id="' + $(value).attr('name') + '-error" class="errorValidate" for="' + $(value).attr('name') + '" style="display:none;"></label>').insertBefore(this);
        }
        // Ugasi autocomplete
        $(this).attr('autocomplete', 'off');

    });

    let formRender = {

        form: '',
        selectPackage: 'select[name="product"]',
        phoneInput: 'input[name="phone"]',
        updatePackageOption: function () {
            let html = '';
            $.each(settings.paketi, function (index, value) {
                html += '<option value="' + value.productId + '">' + value.name + '</option>';
            });
            $(this.form).find(this.selectPackage).html(html);
        },
        updatePhoneInput: function () {
            $(this.form).find("input[name='phone']").val(settings.phonePrefix);
        },
        updateHidden: function () {
            $(this.form).find("input[name='company']").val(settings.company);
        },
        updateFirstPrice: function () {
            $('.'+oldPriceClass).text(getPrice(settings.paketi[0].oldPrice));
            $('.'+newPriceClass).text(getPrice(settings.paketi[0].newPrice));
        },
    }

    $.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "Provjerite polje."
    );


    $.validator.messages.required = 'Popunite ovo polje';

    var first = '';

    function getRegExPhoneText() {
        return settings.phonePrefix + 'xxxxxxxx';
    }

    var validator = [];
    function createValidate() {

        $.each($('form'), function (index, value) {

            // ponisti prije validator i kreiraj novi
            if (validator[index]) {
                validator[index].destroy();
            }

            // Select
            $.each($(value).find('select'), function (index2, value2) {
                let name = $(value2).attr('name');
                formRender.form = value;
                if (name == 'product') {
                    console.log('to');
                    formRender.updatePackageOption();
                }
            })

            validator[index] = $(value).validate({
                errorClass: "errorValidate",
                highlight: function (element) {

                    $(element).addClass("errorBorder");

                    if (!first) {
                        first = element;
                        $(element).focus();
                    }

                    return false;
                },
                unhighlight: function (element) {

                    $(element).removeClass("errorBorder");

                    first = '';
                    return false;
                },
                rules: {
                    'name': {
                        required: true,
                        regex: '^[A-Za-z ]{3,30}$'
                    },
                    'phone': {
                        required: true,
                        //regex: '^\\' + settings.phonePrefix + '[0-9]{6,10}$'
                        regex: '^[\\+ 0-9]{7,15}$'
                    }

                },
                messages: {
                    'name': {
                        required: 'Unesite ime',
                        regex: 'Unesite ime'
                    },
                    'phone': {
                        required: getRegExPhoneText(),
                        regex: getRegExPhoneText()
                    }
                }
            });

        });
    }

    // When change
    $('body').on('change', 'select', function () {
        let element = $(this);

        // Set form
        let form = $(this).closest('form')[0];
        formRender.form = form;

        if ($(element).attr('name') == 'country_code') {
            // Setuj za ostale forme
            $('[name="country_code"]').val(this.value);

            refreshCountry(form);
        }

        console.log('change');
    });

    function refreshCountry(form = '') {
        // Get settings for country code
        settings = setSettingsCountry($(form).find('[name="country_code"]').val());


        // refresh option
        formRender.updatePackageOption();

        // refresh broj
        formRender.updatePhoneInput();

        // first cijene update
        formRender.updateFirstPrice();

        // update hidden
        formRender.updateHidden();

        // refresh vadliacija
        createValidate();

    }
    function getPrice(price) {
        return price + ' ' + settings.currency;
    }

    // Auto load
    refreshCountry();

    $('form').on('click', 'button', function (event) {

        event.preventDefault();

        let form = $(this).closest('form')[0];

        /*try {
            ga('send', {
                hitType: 'event',
                eventCategory: 'form0',
                eventAction: 'submit',
                eventLabel: ''
              });
        } catch(error) {
            console.error(error);
        }*/

        // ako je sve ok verifikacija idemo dalje
        if ($(form).valid()) {
            console.log('forma validna');
            console.log(form);

            $(form).submit();
        }
        return false;
    });

});

