(function($) {
  'use strict';

  const STATUS_UNAUTHENTICATED = 401;
  const STATUS_SERVER_ERROR = 500;
  const STATUS_TOO_MANY_REQUEST = 429;
  const STATUS_BAD_REQUEST = 400;
  const STATUS_SUCCESS = 200;
  const STORAGE_TAG = 'prize_';
  const STORAGE_FIELD_SAVE = 'field_auto_save';
  const API_URL = '/api/v1.0.0';
  const STORAGE_API_TOKEN = 'api_token';
    let TOKEN_API = null;


    let SPINNER = '<div class="spinner spinner-8">';
    SPINNER += '<div class="ms-circle1 ms-child"></div>';
    SPINNER += '<div class="ms-circle2 ms-child"></div>';
    SPINNER += '<div class="ms-circle3 ms-child"></div>';
    SPINNER += '<div class="ms-circle4 ms-child"></div>';
    SPINNER += '<div class="ms-circle5 ms-child"></div>';
    SPINNER += '<div class="ms-circle6 ms-child"></div>';
    SPINNER += '<div class="ms-circle7 ms-child"></div>';
    SPINNER += '<div class="ms-circle8 ms-child"></div>';
    SPINNER += '<div class="ms-circle9 ms-child"></div>';
    SPINNER += '<div class="ms-circle10 ms-child"></div>';
    SPINNER += '<div class="ms-circle11 ms-child"></div>';
    SPINNER += '<div class="ms-circle12 ms-child"></div>';
    SPINNER += '</div>';

    const random_times_const = 5;
    let random_times = 5;
    let interval_random  = null;
    const tombola_size = 16;
    const prize_size_max = 5;
    let prize_size = 5;
    let tombola_moving = false;

    const speed_tombola = 50;

    let action_sort = 'stick-sort';

    /*========= forex Framework ===========*/
  const prizeFramework = (function(){


    /* Initialize all required functions */
    function init(){

      TOKEN_API =  localStorage.getItem(STORAGE_TAG + STORAGE_API_TOKEN);

      displayHelp('<p>' + getText('messageHelp1') + '</p>');

      translate();

      patternField();

      autoSetField();

      linkSubmitForm();

      linkSubmitFormChildTagA();

      linkFilterTable();

      sendDataModal();

      checkTokenLoginRequested();
      checkTokenMakeVisibleElement();

      formValidation();

      checkValidateAccount();

      openLoginModal();

      openSetupNewPasswordModal();

      userDetails();

      //from here new things from website

      ajaxCall('/user/prize-list', 'GET', 'json', true, 'prizeList', '');

      lotti();
      //load sound
      checkMouseOverBall();
      clickBall();
      resetTombola();
      setUpTombola();

      betBtn();
      playBtn();
      sortBtn();
    }

    function setSaida(result) {

        const saida = $('.slot-saida');
        let orange = [], green = [], purple = [];

        if(result.prize_orange !== undefined && result.prize_orange !== ''){
            orange = result.prize_orange.split(' ');
        }

        if(result.prize_green !== undefined && result.prize_green !== ''){
            green = result.prize_green.split(' ');
        }

        if(result.prize_purple !== undefined && result.prize_purple !== ''){
            purple = result.prize_purple.split(' ');
        }

        let total = $.merge(orange , green, purple);
            total = $.merge(total , purple);

        if(saida.length){
            let t = 0;
            saida.each( function () {
                $(this).text(total[t++]);
            });
        }
    }

    function betBtn(){

        const bet = $('#apostBet');

        if(bet.length){
            bet.on('click', function () {

                //setTimeout( function () {
                    checkBallSelected(action_sort);

                    if(!$('#apostSort').is(':hidden')){
                        blockAllSetUpButton();
                        clearInterval(interval_random);
                        interval_random = window.setInterval(function(){
                            random( false, true);
                        }, speed_tombola);
                        displayHelp('<p>' + getText('messageHelp4') + '</p>');
                        setTimeout( function () {
                            $('#apostSort').show();
                        },100);
                    }else{
                        displayHelp('<p>' + getText('messageHelp3') + '</p>');
                        setTimeout( function () {
                            $('#apostBet').show();
                            const star = $('#d4w4 .star');
                            if(star.length){
                                star.removeClass('opacity-hover');
                            }
                        },100);
                    }

                //}, 100);

            });
        }

    }


    function playBtn(){

          const play = $('#apostPlay');

          if(play.length){
              play.on('click', function () {
                    displayHelp('<p>' + getText('messageHelp2') + '</p>');
                    setTimeout( function () {
                        const star = $('#d4w4 .star');
                        if(star.length){
                            star.removeClass('opacity-hover');
                        }
                        lotti(false);
                        orderCleanBlue();
                        $('#apostBet').show();
                        $('#apostPlay').hide();
                    }, 100);

              });
          }

      }

    function sortBtn(){

        const bet = $('#apostSort');

        if(bet.length){
          bet.on('click', function () {
              collectAndSort(action_sort);
          });
        }

    }

    window.prizeSuccess = function prizeSuccess(resp) {
        //display message
        let message_success = '<p>Error</p>';

        setTimeout( function(){

                orderCleanBlue();

                //stop tambola
                stopTombola();
                if(resp.data.prize_orange !== undefined){
                    setTambolaBall('orange', resp.data.prize_orange);
                    setTambolaBall('green', resp.data.prize_green);
                    setTambolaBall('purple', resp.data.prize_purple);

                    setSaida(resp.data);
                }

            }, 100);

        if(resp.display_message){

            if(resp.message !== undefined){

                const m = resp.message;
                if(m.length){
                    message_success = Object.values(m).map( (value) => {
                            return '<p>'+value+'</p>';
                        }
                    );
                    message_success = '<div>' + message_success.join('') + '</div>';
                }

            }

            setTimeout(function () {
                Swal.fire({
                    position: 'top-start',
                    type: 'success',
                    html: message_success,
                    showCloseButton: true,
                    focusConfirm: false,
                    confirmButtonText: 'OK!',
                    confirmButtonAriaLabel: 'Thumbs up, great!',
                    backdrop: false
                });
                resetBtnApost();
            }, 100);
        }


        //ajaxCall('/user/prize-list', 'GET', 'json', true, 'prizeList', '');
    };

    window.prizeError = function prizeError(error) {

        let message_error = '<p>Failed! Try again please.</p>';

        if(error.responseJSON.message !== undefined){

            const m = error.responseJSON.message;
            if(m.length){
                message_error = Object.values(m).map( (value) => {
                        return '<p>'+value+'</p>';
                    }
                );
                message_error = '<div>' + message_error.join('') + '</div>';
            }

        }

        orderCleanBlue();
        stopTombola();

        setTimeout(function () {
            Swal.fire({
                type: 'warning',
                html: message_error,
                showCloseButton: true,
                focusConfirm: false,
                confirmButtonText: 'OK!',
                backdrop: false
            });
            resetBtnApost();
        }, 200);
    };

    window.prizeListSuccess = function prizeListSuccess(resp) {
            if(resp.data !== undefined){

                const elem = $('#list-prize').empty();
                let list = Object.values(resp.data).map( (value) => {
                        return '<li>'+value.pick_number + '  ###  ' + value.prize_draw + '</li>';
                    }
                );

                list = '<div>' + list.join('') + '</div>';

                elem.append(list);
            }
    };

    window.prizeListError = function prizeListError() {
          let message_error = '<p>Failed load list! Try again please.</p>';
          setTimeout(function () {
              Swal.fire({
                  type: 'warning',
                  html: message_error,
                  showCloseButton: true,
                  focusConfirm: false,
                  confirmButtonText: 'OK!',
              });
          }, 1000);
      };

    function checkTokenLoginRequested() {
        const check_token = $('.check-token');

        if(check_token.length){
            const target = check_token.data('target');
            if(target !== undefined){
                if(!TOKEN_API){
                    check_token.attr('data-target', '#login-modal');
                }
            }
        }
    }

    function checkTokenMakeVisibleElement() {
        const el = $('.check-token-visibility');

        if(el.length){
            if(TOKEN_API){
              el.css('visibility', 'visible');
            }
        }
    }

    function linkSubmitForm() {
        $('.submit-form').click(
            function (){
                takeAction($(this));
            }
        );
    }

    function linkFilterTable() {
        $('.filter-table').click(
            function (){
                const click_element = $(this);
                const filter = click_element.data('filter');
                const field = click_element.data('field');

                if(filter !== undefined  && field !== undefined){

                    const runFunction = click_element.data('runfunction');
                    if(runFunction !== undefined){
                        if ( $.isFunction(window[runFunction]) ) {
                            window[runFunction](click_element);
                        }else{
                            console.log('function ' + runFunction + ' not exist');
                        }
                    }
                }

            }
        );
    }

    function linkSubmitFormChildTagA() {
        $('.submit-form-a').click(
            function (event){
                //get the target to get the closest a and get all info
                takeAction($(event.target).closest('a'));
            }
        );
    }

    function sendDataModal() {
        $('.send-data-modal').click(
            function (event){
                //get the target to get the closest a and get all info
                const el = $(event.target).closest('a');
                if(el.length){
                    if(el.data('sendvalue') !== undefined && el.data('sendname') && el.data('target') !== undefined){
                        const names = el.data('sendname').split(',');
                        let values = el.data('sendvalue') + '';
                            values = values.split(',');

                        const target = el.data('target');
                        const modal = $(target).find('form');

                        if(names.length && modal.length && values.length === names.length ){
                            let input;
                            for(let i=0; i<names.length; i++){
                                input = modal.find('input[name='+names[i]+']');
                                if(input.length){
                                    input.val(values[i]);
                                }else{
                                    modal.append('<input type="hidden" name="' + names[i] + '" value="' + values[i] + '">');
                                }
                            }
                        }
                    }
                }

            }
        );
    }

    function userDetails() {
        if(TOKEN_API){
            const url = '/user/auth';
            const data = [];
            callAPIGetData(url, data , 'userDetails');
        }else{
            $('.user-not-auth').css('visibility', 'visible');
        }

    }

    window.userDetailsSuccess = function userDetailsSuccess(resp) {
        if(resp.data !== undefined){
            $('.user-auth').css('visibility', 'visible');
            userUpdateFields({first_name: resp.data.first_name, last_name: resp.data.last_name})

        }else{
            $('.user-not-auth').css('visibility', 'hidden');
        }

    };

    window.userDetailsError = function userDetailsError(error) {
        redirectToMainPageNotAuthenticate(error.status);
    };

    function userUpdateFields(data) {

          if(data.first_name !== undefined){
              $('#user-name').html(data.first_name);
              $('#validationCustom61').val(data.first_name);
          }

          if(data.last_name !== undefined){
              $('#validationCustom62').val(data.last_name);
          }

    }

    function callAPIGetData(action, data, type) {
        ajaxCall(action, 'GET', 'json', true, type, data,null, true);
    }

    function translate(){
        $('.trans').each(function() {
            const field = $(this).data('message');
            if(field !== undefined){
                const text = getText(field);
                if(text !== undefined){
                    $(this).html(text);

                    const placeholder = $(this).data('placeholder');

                    if( placeholder !== undefined ){
                        const elem = $('#'+placeholder);
                        if(elem.length){
                            elem.attr('placeholder', text);
                        }
                    }
                }
            }
        });
    }

    function patternField(){
      $('.pat').each(function() {
          const field = $(this).data('pattern');
          if(field !== undefined){
              const text = getPattern(field);
              if(text !== undefined){
                  $(this).attr('pattern', text);
              }
          }
      });
    }

    /* Store to local storage */
    function storeToLocal(key, items){
      localStorage[key] = JSON.stringify(items);
    }

    /* Get from local storage */
    function getFromLocal(key){
      if(localStorage[key])
        return JSON.parse(localStorage[key]);
      else
        return [];
    }


    /* Form Validation */
    function formValidation(){
      window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        const forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        const validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {

           const checkVal = form.checkValidity();

           const thisForm = $(this);

            //check if any checkbox needs to validate and is checkedin the form
           const checkBox = thisForm.find('.form-check-input validate');

           let checkBoxAllow = true;
           if(checkBox.length){
               checkBox.each( function () {
                   if($(this).is(':checked') === false){
                       checkBoxAllow = false;
                       $(this).parent().find('.invalid-feedback').show();
                   }else{
                       $(this).parent().find('.invalid-feedback').hide();
                   }

               })
           }

           //check if there is any field to compare with other field if field1 = field 2 that's ok!
           const checkConfirmFields = thisForm.find('.validate-confirm');

           let checkConfirmFieldsAllow = true;
           if(checkConfirmFields.length){
              let fieldConfirm, fieldConfirmVal;
              checkConfirmFields.each( function () {
                  fieldConfirm = $(this).data('confirm');
                  if(fieldConfirm !== undefined){
                      fieldConfirmVal = $('#'+fieldConfirm);
                      if(fieldConfirmVal.length){
                          if(fieldConfirmVal.val() !== $(this).val()){
                              checkConfirmFieldsAllow = false;
                              $(this).parent().find('.invalid-feedback').show();
                          }else{
                              $(this).parent().find('.invalid-feedback').hide();
                          }
                      }
                  }
              })
           }

            event.preventDefault();
            event.stopPropagation();
            //stop submitting to show error
            if (checkVal === true && checkBoxAllow && checkConfirmFieldsAllow) {
                const thisFormSerializeArray = thisForm.serializeArray();

                if(thisForm.data('openanotherwindow') !== undefined){
                    openAnotherWindow(thisForm, thisFormSerializeArray);
                }else{
                    takeAction(thisForm);
                }

            }

            form.classList.add('was-validated');

          }, false);
        });


      }, false);
    }

    function openAnotherWindow(form, formSerializeArray) {
        const type = form.data('openanotherwindow');
        const data = { 'field' : formSerializeArray, 'href': form.attr('href'), 'method': form.attr('method') };
        // switch (type) {
        //     case 'payment-option': openPaymentOption(data); break;
        // }
    }

    function getLinkUrl(link) {
        let resp = '';
        // switch (link) {
        //     case 'jobFileUrlID': resp = jobFileUrlID; break;
        //     case 'jobEmailPaymentUrlID': resp = jobEmailPaymentUrlID; break;
        //     default: resp = '';
        // }

        return resp;
    }

    function takeAction(elem) {

        let action, method, data, params = '', download = undefined;

        let processData = false;
        let requestToken = false;

        if(elem.is('form')){
            action = elem.attr('href');
            method = elem.attr('method');
            data = decodeURI(elem.serialize());
            //check if exist params to send
            //example   url/param1/param2
            params = checkActionParams(elem);
            action += params;
        }

        if(elem.is('a')){

            if(elem.data('href') !== undefined){
                action = elem.data('href');
            } else {
                action = getLinkUrl(elem.data('hreflink'))
            }

            method = elem.data('method');
            data = elem.data('send') !== undefined ? getDataByIds(elem.data('send').split(',')) : [];
            processData = true;
            // download = elem.data('download');

        }

        spinnerLoading();

        ajaxCall(action, method, 'json', true, 'takeAction', data, elem, requestToken,  processData);

    }

    window.takeActionSuccess = function takeActionSuccess(data,elem) {

        const waitSeconds = 3;
        //check if we want o save any field on storage
        autoSaveField(elem);

        //save on storage any success response
        storageSuccessData(elem, data);

        //remove storage  on success response
        storageRemoveData(elem);

        if(elem !== null){
            //timer in case if you need to get back to home page after x amount of time
            if(elem.data('timerclose') !== undefined){
                //time in seconds
                if(elem.data('timerclose')>0){
                    setTimeout(function(){  window.location.href = '/'; }, 1000*elem.data('timerclose'));
                }
            }
        }

        const redirectOnSuccess = elem.data('redirectonsuccess');

        //redirect to another page page if requested
        if(data.data !== undefined && data.data.redirect !== undefined){

            window.location.href = data.data.redirect;
        }
        //redirect to home page if requested
        else if(redirectOnSuccess === true){
            window.location.href = '/';
        }else{
            // console.log('message : ', data.message);
            //if not redirect check if there is any data to update the html
            //update any html data on success response
            updateHtmlData(elem);

            //display message
            let message_success = '<p>No success message to display</p>';

            if(data.message !== undefined){

                const m = data.message;
                if(m.length){
                    message_success = Object.values(m).map( (value) => {
                            return '<p>'+value+'</p>';
                        }
                    );
                    message_success = '<div>' + message_success.join('') + '</div>';
                }
            }

            setTimeout(function () {
                Swal.fire({
                    type: 'success',
                    html: message_success,
                    showCloseButton: true,
                    focusConfirm: false,
                    confirmButtonText: 'OK!',
                    confirmButtonAriaLabel: 'Thumbs up, great!',
                });
            }, waitSeconds*1000);
        }
    };

    window.takeActionError = function takeActionError(error) {
        const waitSeconds = 3;
        setTimeout(function () {
            if(error.status === STATUS_SERVER_ERROR){
                Swal.fire({
                    type: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!'
                });
            }else{
                let message = '<p>No error to display</p>';

                if(error.status === STATUS_TOO_MANY_REQUEST){
                    if(error.responseJSON.message !== undefined){
                        message = '<p>' + getText('tooManyAttempts1Minute') + '</p>';
                    }
                }

                if(error.status === STATUS_BAD_REQUEST){
                    if(error.responseJSON.message !== undefined){

                        const m = error.responseJSON.message;

                        if(m.length){

                            message = Object.values(m).map( (value,key) => {
                                    return '<p>'+value+'</p>';
                                }
                            );
                            message = message.join('');

                        }
                    }
                }

                redirectToMainPageNotAuthenticate(error.status);

                //console.log(message);
                Swal.fire({
                    type: 'error',
                    html: '<div>' + message + '</div>'
                });
            }
        }, waitSeconds*1000);
    };

    function getDataByIds(data) {
            let resp = '';
            let e;

            data.forEach(function (el) {
                 e = $('#'+el);
                 if(e.length){
                     resp += '&' + e.serialize();
                 }
            });

            if(resp !== ''){
                resp = resp.substring(1, resp.length);
            }
            // console.log(resp);
            return resp;
    }
    function spinnerLoading() {
        Swal.fire({
            html: '<img width="50" class="rotate" alt="" src="/assets/img/loading-gif.png" />',
            showCloseButton: false,
            showCancelButton: false,
            showConfirmButton: false,
            background: 'transparent',
            allowOutsideClick: false
        });
    }

    //contact the api to update data
    function updateHtmlData(elem){
        let update = elem.data('updatecallapi');
        if (update !== undefined) {

            switch (update) {
                case 'user-details': userDetails();break;
                //case 'user-apps': userApps();break;
                default: userDetails();
            }
        }
    }

    function autoSaveField(elem) {

        if (elem !== null){
            const remember = elem.find('.autosave');
            if (remember !== undefined) {
                let items_save = remember.data('autosave');
                if (items_save !== undefined) {

                    items_save = items_save.split(',');
                    if (items_save.length) {
                        //get the old array
                        let array_storage_save = getFromLocal(STORAGE_TAG + STORAGE_FIELD_SAVE);

                        const save = remember.is(':checked');
                        let val_index, type;

                        items_save.forEach(
                            function (it) {

                                const el = $('#' + it);

                                if(el.length){

                                    val_index = array_storage_save.indexOf(it);


                                    //save if is checked
                                    if(save){
                                        //update or insert more fields
                                        if(val_index === -1){
                                            array_storage_save.push(it);
                                        }
                                        //check the type of input
                                        type = el.attr('type');
                                        let val;
                                        if(type === 'checkbox'){
                                            val = el.is(':checked');
                                        }else{
                                            val = el.val();
                                        }

                                        localStorage.setItem(STORAGE_TAG + STORAGE_FIELD_SAVE + '_' + it, val);
                                    }else{
                                        //if not that means field need to be removed from the storage
                                        //remove fields
                                        if(val_index > -1){
                                            array_storage_save = $.grep(array_storage_save, function(value) {
                                                return value !== it;
                                            });
                                            localStorage.removeItem(STORAGE_TAG + STORAGE_FIELD_SAVE + '_' + it);
                                        }
                                    }

                                }
                            }
                        );

                        //update save fields as array thats why we not using localStorage.setItem
                        storeToLocal(STORAGE_TAG + STORAGE_FIELD_SAVE, array_storage_save)
                    }
                }

            }
        }

    }

    function autoSetField() {
        //its array so we use getFromlocal
        const array_storage_save = getFromLocal(STORAGE_TAG + STORAGE_FIELD_SAVE);
        if(array_storage_save.length){
            let value, el;
            array_storage_save.forEach( function (it) {
                value = localStorage.getItem(STORAGE_TAG + STORAGE_FIELD_SAVE + '_' + it);
                if(!(Array.isArray(value))){
                    el = $('#'+it);
                    if(el.length){
                        if(el.attr('type') === 'checkbox'){
                            el.prop('checked', value);
                        }else{
                            el.val(value);
                        }
                    }
                }
            });
        }
    }

    function storageSuccessData(form, data) {

        if(data !== null && form !== null){
            const storage = form.data('storage');
            if(storage !== undefined){
                const items = storage.split(',');
                if(items.length){
                    items.forEach(
                        function (it) {
                            // console.log(data.data[it]);
                            //get th e success data and save on storage like example token from login
                            if(data.data[it] !== undefined){
                                localStorage.setItem(STORAGE_TAG + it, data.data[it]);
                            }
                        }
                    )
                }
            }

        }
    }

    function storageRemoveData(form) {

        if( form !== null ){
            const storage_remove = form.data('storageremove');

            if( storage_remove !== undefined){
                const items = storage_remove.split(',');
                if(items.length){
                    items.forEach(
                        function (it) {
                            localStorage.removeItem(STORAGE_TAG + it);
                        }
                    )
                }
            }
        }

    }

    function redirectToMainPageNotAuthenticate(status) {
        if(status === STATUS_UNAUTHENTICATED){
            //just remove the token when is not auth
            localStorage.removeItem(STORAGE_TAG + STORAGE_API_TOKEN);
            window.location.href = '/';
        }
    }

    function ajaxCall(url, method, dataType, async, response, data, elem = null, requestToken = false, processData = false) {


        if( !requestToken || TOKEN_API) {

            let data_send = data;
            //check if is the upload files
            if (elem && elem.attr('enctype') === 'multipart/form-data') {

                const data_form = data.split('&');
                if(data_form.length){
                    let field;
                    data_send  = new FormData();
                    data_form.forEach(
                        function (it) {
                            field = it.split('=');
                            data_send.append(field[0], field[1]);
                        }
                    );
                }

                const files = elem.find("[type=file]");
                if(files.length){
                    if(files[0].files[0] !== undefined){
                        data_send.append(files.attr('name'), files[0].files[0]);
                    }
                }
            }

            let ajax_obj = {
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Authorization': `Bearer ${TOKEN_API}`,
                },
                url: API_URL + url,
                type: method,
                data: data_send,
                dataType: dataType,
                async: async,
                processData: processData,
                success: function (data) {
                    ajaxCallSuccess(response, data, elem);
                },
                error: function (error) {
                    ajaxCallError(response, error);
                }
            };

            if (elem && elem.attr('enctype') === 'multipart/form-data') {
                ajax_obj.contentType= false;
            }

            $.ajax(
                ajax_obj
            );
        }
    }

    function ajaxCallSuccess(response, data, elem = null) {

        const resp = response + 'Success';
        //check if the function exist and call
        if ( $.isFunction(window[resp]) ) {
            window[resp](data, elem);
        }else{
            console.log('function ' + resp + ' not exist');
        }

    }

    function ajaxCallError(response, error) {

        const resp = response + 'Error';

        //check if the function exist and call
        if ( $.isFunction(window[resp]) ) {
            window[resp](error);
        }else{
            console.log('function ' + resp + ' not exist');
        }

    }

    function checkValidateAccount() {
            const page = $('#alert-activate');
            if(page.length){
                const message = page.data('message');
                const error = page.data('error');
                const type = error ? 'error' : 'success';
                const url = error ? '/' : '/?auto-login=' + page.data('email');

                Swal.fire({
                    type: type,
                    html: message,
                    showCloseButton: true,
                    focusConfirm: false,
                    confirmButtonText: 'OK!',
                    confirmButtonAriaLabel: 'Thumbs up, great!',
                }).then(function() {
                    window.location = url;
                });
            }
    }

    function openLoginModal() {
        const autoLogin = getUrlParameter('auto-login');
        if(autoLogin !== undefined){
            $('#validationCustom05').val(autoLogin);
            $('#login-modal').modal('show');
        }
    }

    function openSetupNewPasswordModal() {
          const email = getUrlParameter('setup-new-password-email');
          const token = getUrlParameter('token');
          if(email !== undefined && token !== undefined){
              $('#setup-password-email').val(email);
              $('#setup-password-token').val(token);
              $('#setup-new-password-modal').modal('show');
          }
    }

    function getUrlParameter(sParam) {
      let sPageURL = window.location.search.substring(1),
          sURLVariables = sPageURL.split('&'),
          sParameterName,
          i;

      for (i = 0; i < sURLVariables.length; i++) {
          sParameterName = sURLVariables[i].split('=');

          if (sParameterName[0] === sParam) {
              return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
          }
      }
    }

    function checkActionParams(form) {
       let result = '';
       let params = form.data('params');
       if (params !== undefined) {
          params = params.split(',');
          if(params.length){
              params.forEach(
                  function (it) {
                      const field = $('#' + it);
                      if(field.length){
                          result += '/' + field.val();
                      }
                  }
              );
          }
       }
       return result;
    }



    //website

      function resetTombola() {
          const btn = $('#reset-green');

          if(btn.length){
              btn.on('click', function () {
                  lotti(false);
                  resetBtnApost();
              });
          }
      }

      function resetBtnApost(){
          $('#apostSort').hide();
          $('#apostPlay').show();
          $('#apostBet').hide();
          const star = $('#d4w4 .star');
          if(star.length){
              star.addClass('opacity-hover');
          }
      }

      function lotti(rodar = false) {

          // block any entry
          tombola_moving = true;

          slotEntry();

          if(rodar){
              blockAllSetUpButton();
              clearInterval(interval_random);
              interval_random = window.setInterval(function(){
                  random( true, false);
              }, speed_tombola);
          }else{
              tombola_moving = false;
          }

      }

      function slotEntry() {
          let el = null;
          for ( let i = 1;i <= tombola_size;i++ ) {
              el = $('#star'+i);
              if(el.length === 0){
                  $('<span class="star opacity-hover" id="star'+i+'">'+i+'</span>').appendTo('#d4w4');
              }
          }

          for ( let i = 1;i <= prize_size;i++ ) {
              el = $('#number'+i);
              if(el.length === 0){
                  $('<div class="slot orange" id="number'+i+'">?</div>').appendTo('#d4w3');
              }else{
                  // orange(el);
                  el.text('?');
              }
          }

          for ( let i = 1;i <= prize_size;i++ ) {
              el = $('#saida-number'+i);
              if(el.length === 0){
                  $('<div class="slot-saida orange" id="saida-number'+i+'">?</div>').appendTo('#d4w2');
              }else{
                  // orange(el);
                  el.text('?');
              }
          }

          for ( let i = prize_size +1;i <= prize_size_max;i++ ) {
              el = $('#number'+i);
              if(el.length>0){
                  el.remove();
              }

              el = $('#saida-number'+i);
              if(el.length>0){
                  el.remove();
              }
          }
      }
      function random(clean, infinity_time) {

          let refresh = false;

          $('.star').removeClass('clicked');
          if(random_times-- <= 0 && !infinity_time){
              if(clean){
                  refresh = true;
              }
              stopTombola();
          }

          let board = [];
          do { board.push(board.length+1);} while(board.length < tombola_size);

          let randomstars = board.slice().shuffle();
          $(board).each(function(i) {
              const star = $('#star'+this);
              star.html(randomstars[i]);
              blue(star);
          });

          let normal_numbers = randomstars.slice().shuffle();
          let selected_normal_numbers = normal_numbers.slice(0, prize_size);
          $(selected_normal_numbers).each(function(i, value) {
              normal_numbers.splice($.inArray(value, normal_numbers), 1);
              $(board).each(function(i) {
                  if( parseInt($('#star'+this).text()) === value && !refresh){

                      //orange('#star'+value);
                      const slot = $('.slot');
                      let colors = 1;
                      if(slot.length > 0 ){
                          for(let f=1; f<= slot.length; f++) {
                              let g = $('#number'+f);
                                  if (g.hasClass('orange')) {
                                      colors = 1;
                                  }

                                  if (g.hasClass('green')) {
                                      colors =2;
                                  }

                                  if (g.hasClass('purple')) {
                                      colors = 3;
                                  }
                          }
                      }

                      const decide_color = Math.floor((Math.random() * colors) + 1);

                      if(decide_color === 1){
                          orange('#star'+value);
                      }

                      if(decide_color === 2){
                          green('#star'+value);
                      }

                      if(decide_color === 3){
                          purple('#star'+value);
                      }
                  }
              });
          });

      }

      Array.prototype.shuffle = function() {
          var i = this.length, j, temp;
          if ( i == 0 ) return this;
          while ( --i ) {
              j = Math.floor( Math.random() * ( i + 1 ) );
              temp = this[i];
              this[i] = this[j];
              this[j] = temp;
          }
          return this;
      };

      function checkMouseOverBall() {
          const star = $('#d4w4 .star');
          if(star.length>0){
              star.mouseover(function() {
                  if( tombola_moving ) return;
                  if($(this).hasClass('clicked')) return;
                  orange($(this));
              });

              star.mouseleave(function() {
                  if( tombola_moving || $(this).hasClass('clicked')) return;
                  blue($(this));
              });
          }

      }

      function clickBall() {
          const star = $('#d4w4 .star');
          let number_el = null;
          let number = 0;

          if(star.length>0){
              star.click(function() {
                  number_el = $(this);
                  if( tombola_moving ) return;
                  if(number_el.hasClass('opacity-hover')){
                    return;
                  }
                  let set_ball = false;

                  number = number_el.text();
                  if(number_el.hasClass('purple')) return;
                  const slot_orange = $('.slot');
                  if( slot_orange.length>0 ){
                      slot_orange.each( function () {
                          if($(this).text() === '?' && !set_ball){
                              $(this).text(number);

                              number_el.addClass('clicked');
                              if($(this).hasClass('orange')){
                                  orange(number_el);
                              }

                              if($(this).hasClass('green')){
                                  green(number_el);
                              }

                              if($(this).hasClass('purple')){
                                  purple(number_el);
                              }

                              set_ball = true;
                          }
                      });

                      //ordering
                      //orderingBalls();
                  }
              });
          }
      }

      function orderingBalls() {
          while (true) {
              let order_change = false;
              let ball_prev, ball_next, ball_prev_number, ball_next_number;
              for(let y=1; y <= 5; y++){
                  ball_prev = $('#number'+y);
                  ball_next = $('#number'+(y+1));
                  if(ball_prev.length && ball_next.length){

                      if( ball_prev.text() !== '?' && ball_next.text() !== '?'){

                          ball_prev_number = parseInt(ball_prev.text());
                          ball_next_number = parseInt(ball_next.text());

                          if(ball_prev_number > ball_next_number){
                              console.log('ball prev: ', ball_prev_number, ' ball next', ball_next_number);
                              ball_prev.text(ball_next_number);
                              ball_next.text(ball_prev_number);
                              order_change = true;
                          }
                      }
                  }
              }
              if(!order_change){
                  break;
              }
          }
      }

      function setUpTombola() {
          const btn = $('.btn-menu');
          if(btn.length >0){
              btn.click(
                  function () {
                      if( tombola_moving ) return;
                      const el = $(this);

                      if(el.hasClass('btn-saida')){
                          $('.btn-saida').removeClass('active');
                      }

                      if(el.hasClass('btn-pool')){
                          $('.btn-pool').removeClass('active');
                      }

                      if(el.hasClass('btn-sort')){
                          $('.btn-sort').removeClass('active');
                      }

                      el.addClass('active');

                      if(el.data('action') === 'saida'){
                          prize_size = parseInt(el.data('value'));
                          orderCleanBlue();
                          slotEntry();
                      }

                      if(el.data('action') === 'pool'){
                          orderCleanBlue();
                          slotEntry();
                          setPool(parseInt(el.data('value')));
                      }

                      if(el.data('action') === 'stick-sort'
                          || el.data('action') === 'random-sort'
                          || el.data('action') === 'fix-sort'
                          || el.data('action') === 'only-sort'){

                          action_sort = el.data('action');

                      }

                  }
              );
          }
      }

      function checkBallSelected(action) {
          const slot = $('.slot');
          let set_ball = false;
          let val = 1;
          let array_val = [];
          let i=0;
          if( slot.length>0 ){

              if(action === 'random-sort'){
                  slot.each( function () {

                      while (true){
                          val = Math.floor((Math.random() * 16) + 1);
                          if(!(array_val.indexOf(val) > -1)){
                              array_val[i++]=val;
                              $(this).text(val);
                              break;
                          }
                      }
                  });

                  //orderingBalls();
              }else{
                  slot.each( function () {
                      if($(this).text() === '?' && !set_ball){
                          set_ball = true;
                      }
                  });
              }
          }

          if(!set_ball){
              $('#apostSort').show();
              //call tombola
          }
      }

      function collectAndSort(action) {
          clearInterval(interval_random);
          interval_random = window.setInterval(function(){
              random( true, true);
          }, speed_tombola);

          tombola_moving = true;
          blockAllSetUpButton();

          let data = null;
          let i_orange = 0;
          let number_orange = [], number_green = [], number_purple = [];
          for ( let i = 1; i <= prize_size_max; i++ ) {
              const el = $('#number'+i);
              if(el.length>0){
                  if(el.hasClass('orange')){
                      number_orange[i_orange++] = el.text();
                  }

                  if(el.hasClass('green')){
                      number_green[0] = el.text();
                  }

                  if(el.hasClass('purple')){
                      number_purple[0] = el.text();
                  }

              }
          }

          data = {'number_orange': number_orange, 'number_green': number_green, 'number_purple': number_purple, 'action': action};

          ajaxCall('/user/prize', 'POST', 'json', true, 'prize', data, null, false, true);
      }

      function refreshPrizeColor() {
          let el;
          for ( let i = prize_size_max;i > 0;i-- ) {
              el = $('#number'+i);
              if(el.length>0){
                  orange(el);
              }

              el = $('#saida-number'+i);
              if(el.length>0){
                  orange(el);
              }
          }
      }

      function setPool(pool) {

          refreshPrizeColor();

          let el = null;
          if(pool === 2){
              el = $('#number'+prize_size);
              if(el.length>0){
                  green(el);
              }

              el = $('#saida-number'+prize_size);
              if(el.length>0){
                  green(el);
              }
          }

          if(pool === 3){
              el = $('#number'+prize_size);
              if(el.length>0){
                  purple(el);
              }

              el = $('#saida-number'+prize_size);
              if(el.length>0){
                  purple(el);
              }

              el = $('#number'+(prize_size-1));
              if(el.length>0){
                  green(el);
              }

              el = $('#saida-number'+(prize_size-1));
              if(el.length>0){
                  green(el);
              }
          }

      }

      function blockAllSetUpButton() {
          $('.btn-menu').attr('disabled', true);
      }

      function unblockAllSetUpButton() {
          //$('.btn-menu').attr('disabled', true);
      }

      function unblockSortSetUpButton() {
          //$('.btn-sort').attr('disabled', false);
      }

      function unblockPoolSaidaSetUpButton() {
          $('.btn-menu').attr('disabled', false);
      }

      function setTambolaBall(color, prize) {
          if(prize !== undefined && prize !== ''){
              let ball = prize.split(' ');
              if(ball.length){
                  ball.forEach(function (value) {
                      const board = $('.star');
                      if(board.length){
                          $(board).each(function(index, el) {
                              if($(el).text() === value){
                                  if(color === 'orange'){
                                      orange(el);
                                  }
                                  if(color === 'green'){
                                      green(el);
                                  }
                                  if(color === 'purple'){
                                      purple(el);
                                  }
                              }
                          });
                      }
                  });
              }
          }
      }

      function stopTombola() {

          orderCleanBlue();

          //stop tambola
          clearInterval(interval_random);
          random_times = random_times_const;
          tombola_moving = false;
          unblockPoolSaidaSetUpButton();
      }

      function orderCleanBlue() {
          const board = $('.star');
          if(board.length){
              let t = 1;
              $(board).each(function(index, el) {
                  blue(el);
                  $(el).text(t++);
              });
          }
      }

      function displayHelp(message){
          setTimeout(function () {
              Swal.fire({
                  position: 'top-start',
                  type: 'success',
                  html: message,
                  showCloseButton: true,
                  focusConfirm: false,
                  confirmButtonText: 'OK!',
                  confirmButtonAriaLabel: 'Thumbs up, great!',
                  backdrop: false,
              });
              resetBtnApost();
          }, 100);
      }

      const orange = function(el) {
          $(el).removeClass('blue').removeClass('green').removeClass('purple').addClass('orange');
      };
      const blue = function(el) {
          $(el).removeClass('orange').removeClass('green').removeClass('purple').addClass('blue');
      };
      const green = function(el) {
          $(el).removeClass('orange').removeClass('blue').removeClass('purple').addClass('green');
      };
      const purple = function(el) {
          $(el).removeClass('orange').removeClass('blue').removeClass('green').addClass('purple');
      };


      return {
      init: init
    }

  })();

  prizeFramework.init();

})(jQuery);
