<?php
  // error_reporting(0);
  $env = 'stag';
  if ($env == 'prod') {
    $root_api = 'https://app.1ticks.com/1ticks/api/public/api/';
    $host_url = 'https://1ticks.com';
    $base_url = '/';
    $public_url = 'https://1ticks.com/';
  } else {
    $root_api = 'https://inbots.io/ttt/api/public/api/';
    $host_url = 'https://www.signhub.io';
    $base_url = '/ticktactoe/staging/';
    $public_url = 'https://www.signhub.io/ticktactoe/staging/';
  }
  $get_url = "https://inbots.io/ttt/api/public/api/events/".$_GET['event'];
  $event_json = @file_get_contents($get_url);
  $event = json_decode($event_json, true)["data"] ?? [];
  $event_name = $event['fields']['default']['title'];
  $event_name = preg_replace("/\"/", "\\\"", $event_name);
  $event_desc = $event['fields']['default']['description'] ?? '';
  if($event_desc){
    $event_desc = preg_replace("/<.*?>/", "", $event_desc);
    $event_desc = preg_replace("/\"/", "\\\"", $event_desc);
    if(strlen($event_desc) > 180){
      $event_desc = substr($event_desc, 0, 150) . "⋯";
    }
  }
  $event_image =$event['fields']['default']['image_url'];
  
  $event_start_date =$event['start_date'];
  $event_end_date =$event['end_date'];
  $event_venue =$event['fields']['default']['venue'];
  $event_venue = preg_replace("/\"/", "\\\"", $event_venue);
  $event_address =$event['fields']['default']['address'];
  $event_address = preg_replace("/\"/", "\\\"", $event_address);
  
  $event_tickets = $event['tickets'] ?? [];

  $organizer_name =$event['organizer']['fields']['default']['title'];
  $organizer_name = preg_replace("/\"/", "\\\"", $organizer_name);
  $organizer_email =$event['organizer']['email'];
  $organizer_phone = preg_replace('/,/','',($event['organizer']['phone']));
  $organizer_logo =$event['organizer']['picture_url'];
  $organizer_url_string =$event['organizer']['url_string'];
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <?php if ($env !='prod'):?>
      <!-- no crawling -->
      <meta name="robots" content="none" /> 
    <?php else: ?>
      <meta name="keywords" content="1ticks,ticketing,ticketing tools,event ticketing,free ticketing system,event promotion,MacauTicket,kktix,juven,澳門售票,售票網,廣星,售票平台,舉辦活動,免費舉辦活動,活動推廣,活動行銷,宣傳活動">
      <meta name="robots" content="index,follow">
    <?php endif;?>

    <title><?=$event_name;?></title>
    <link rel="shortcut icon" href="<?=$public_url;?>favicon.ico" type="image/x-icon">
    <meta property="og:title" content="<?=$event_name?$event_name:'1TICKS - 活動行銷就係1TICKS咁簡單';?>" />
    <meta name="twitter:title" content="<?=$event_name?$event_name:'1TICKS - 活動行銷就係1TICKS咁簡單';?>" />
    <meta name="description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta property="og:description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta name="twitter:description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta property="og:image" content="<?=$event_image?$event_image:'<?=$public_url;?>static/preview.png';?>" />
    <meta name="twitter:image" content="<?=$event_image?$event_image:'<?=$public_url;?>static/preview.png';?>" />
    <meta property="og:url" content="<?=$public_url;?>event/<?=$eid;?>" />
    <script type=application/ld+json>{
      "@context": "https://www.schema.org",
      "@type": "Event",
      "name": "<?=$event_name;?>",
      "image": "<?=$event_image;?>",
      "url": "<?=$public_url;?>event/<?=$eid;?>",
      "description": "<?=$event_desc;?>",
      "startDate": "<?=$event_start_date;?>",
      "endDate": "<?=$event_end_date;?>",
      "location": {
        "@type" : "Place",
        "name" : "<?=$event_venue;?>",
        "address" : "<?=$event_address;?>"
      },
      "offers": [
      <?php for($i = 0; $i < count($event_tickets); $i++):?>
        {
          "@type": "Offer",
          "name": "<?=preg_replace("/\"/", "\\\"", $event_tickets[$i]->fields->default->title);?>",
          "price": <?=$event_tickets[$i]->price;?>,
          "priceCurrency": "<?=$event_tickets[$i]->currency;?>",
          "url": "<?=$public_url;?>event/<?=$eid;?>",
          "availability": "<?=($event_tickets[$i]->remainder>0)?'http://schema.org/InStock':'https://schema.org/SoldOut';?>",
          "priceValidUntil": "<?=!empty($event_tickets[$i]->active_end_date)?$event_tickets[$i]->active_end_date:$event_end_date;?>",
          "validFrom": "<?=!empty($event_tickets[$i]->active_start_date)?$event_tickets[$i]->active_start_date:$event_start_date;?>"
        }
        <?php if($i<(count($event_tickets)-1)):?>,<?php endif;?>
      <?php endfor;?>
      ],
      "organizer": {
        "@type": "Organization",
        "name": "<?=$organizer_name;?>",
        "email": "<?=$organizer_email;?>",
        "phone": "<?=$organizer_phone;?>",
        "logo": "<?=$organizer_logo;?>",
        "url": "<?=$public_url;?>organizer/<?=$organizer_url_string;?>"
      }
    }</script>
    <meta name="apple-mobile-web-app-capable" content="no">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="1TICKS">
    <link rel="apple-touch-icon" href="<?=$public_url;?>static/apple-icons-150.png">
    <meta property="og:type" content="website" />
    <meta property="og:site_name" content="1TICKS" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@1TICKS" />
      
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      <link rel="preload" href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" as="style">
      <link rel="preload" href="https://cdn.jsdelivr.net/npm/vuetify@2.2.4/dist/vuetify.min.css" as="style">
      <link rel="preload" href="http://cdn.quilljs.com/1.3.6/quill.core.css" as="style">
      <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
      <link href="https://cdn.jsdelivr.net/npm/vuetify@2.2.4/dist/vuetify.min.css" rel="stylesheet">
      <link href="http://cdn.quilljs.com/1.3.6/quill.core.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
      <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
      <!-- polyfill (IE only) -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.8.3/polyfill.min.js" type="text/javascript"></script>
      <!-- End polyfill (IE only) -->
      <!-- Babel -->
      <script src="https://unpkg.com/@babel/standalone@7.7.7/babel.min.js"></script>
      <!-- End Babel -->
      <style>
        [v-cloak] {
          display:none;
        }
        iframe {
          width: 100%;
          height: 50vh;
          max-height: 400px;
        }
        img {
          max-width: 100%;
        }
        .swal-modal {
          font-family: 'Verdana', 'Geneva', sans-serif !important;
        }
        .hide-input input {
          display: none;
        }
        .x-dense .v-input__slot {
          min-height: 32px !important;
        }
        .x-dense .v-input__slot .v-input__append-inner {
          margin-top: 4px;
        }
        
      </style>
  </head>

  <body>
    <noscript>
      <strong>We're sorry but 1ticks doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app">
      <v-app>
        <loading-widget :loading="loading_widget.loading"></loading-widget>
        <app-toolbar :is_whitelabel="_get(event,'is_white_label',false)" :settings="_get(event,'settings',{})"></app-toolbar>
        <v-content style="padding-top: 40px;">
          <div class="page-wrapper">
            <v-container class="pa-0" fluid v-cloak>
              <section>
                <v-row dense>
                  <v-col lg="8" offset-lg="2">
                    <v-card :flat="$vuetify.breakpoint.xsOnly">
                      <blur-image :src="_f(event.fields, 'image_url')" alt="event banner" :ratio="$vuetify.breakpoint.mdAndUp?3:1.91" :contain="$vuetify.breakpoint.mdAndUp?true:false"></blur-image>
                      <v-divider></v-divider>
                      <!-- title and share button -->
                      <v-card-title id="event-title" class="py-2">
                        <v-row dense align="center">
                          <v-col>
                            <h1 :class="'font-weight-bold '+($vuetify.breakpoint.mdAndUp?'headline':'title')">{{_f(event.fields, 'title')}}</h1>
                          </v-col>
                          <v-col cols="auto">
                            <share-options 
                              flat 
                              icon 
                              color="primary" 
                              :is_mobile="is_mobile" 
                              :event_fields="event.fields" 
                              :url="getEventURL(event)"
                            ></share-options>
                          </v-col>
                        </v-row>
                      </v-card-title>
                      <!-- event basic info -->
                      <v-divider></v-divider>
                      <v-card-text id="event-basic-info">
						            <event-basic-info :event="event"></event-detail-description>
                      </v-card-text>
                      <!-- event tickets -->
                      <v-divider></v-divider>
                      <v-card-text id="event-tickets" v-if="event.tickets.length > 0">
                        <v-row dense align="center">
                          <v-col cols="auto">
                            <v-icon>mdi-ticket</v-icon>
                          </v-col>
                          <v-col>
                            <h3 class="title">{{(isPaidEvent())?$t('ticket.paid.title'):$t('ticket.free.title')}}</h3>
                          </v-col>
                        </v-row>
                        <v-expansion-panels>
                          <v-expansion-panel class="mx-n3" v-for="group_id in event.tickets.map(o=>o.event_ticket_group_id).filter((val, i, self) => (val && val!='' && self.indexOf(val)===i))" :key="group_id">
                            <v-expansion-panel-header class="px-3">{{_f((event.ticket_groups.filter(g=>g.id == group_id)[0]||{}).fields, 'title')}}</v-expansion-panel-header>
                            <v-expansion-panel-content class="mx-n3">
                              <div>
                                <v-alert
                                  outlined
                                  border="left"
                                  color="primary"
                                  dense
                                  class="px-3"
                                  :value="true"
                                  v-for="(ticket, index) in event.tickets.filter(t=>(t.event_ticket_group_id==group_id))"
                                  :key="index"
                                >
                                  <v-row dense class="black--text subtitle-2" align="center">
                                    <v-col>
                                      <div>{{_f(ticket.fields, 'title')}}</div>
                                      <div class='grey--text lighten-1'>{{_f(ticket.fields, 'remark')}}</div>
                                    </v-col>
                                    <v-col cols="auto" order-md="2">
                                      <v-select
                                        :items="Array.from(Array(Math.min(ticket.purchase_limit, ticket.remainder)+1).keys()).map(v=>({text: v}))" 
                                        v-model="ticket.purchase_quantity" 
                                        class="hide-input x-dense"
                                        single-line 
                                        hide-details 
                                        outlined
                                      ></v-select>
                                    </v-col>
                                    <v-col cols="12" md="auto" order-md="1">
                                      <template v-if="ticket.price > 0">
                                        <span class="subheading">{{ ticket.currency + '' + ticket.price }}</span>
                                        <span class='grey--text lighten-1' v-if="ticket.user_fee > 0">
                                          (+{{ticket.currency + ticket.user_fee}} {{$t('ticket.serviceFee')}})
                                        </span>
                                      </template>
                                      <template v-else-if="!~~(event.settings && event.settings.hide_free_ticket_price)">
                                        <h5>{{$t('page.EventPayment.free')}}</h5>
                                      </template>
                                    </v-col>
                                  </v-row>
                                </v-alert>
                              </div>
                            </v-expansion-panel-content>
                          </v-expansion-panel>
                        </v-expansion-panels>
                      </v-card-text>
                      <!-- event description -->
                      <v-divider></v-divider>
                      <v-card-text id="event-description" v-if="_get(event, 'fields.default.description.length',0)>0">
                        <v-row dense align="center">
                          <v-col cols="auto">
                            <v-icon>mdi-calendar-text</v-icon>
                          </v-col>
                          <v-col>
                            <h3 class="title">{{$t('event.details')}}</h3>
                          </v-col>
                        </v-row>
                        <p class='description ql-editor pa-0 black--text' v-html="changeLinkColor(_f(event.fields, 'description'))"></p>
                      </v-card-text>
                      <!-- event organizer (white label) -->
                      <v-divider></v-divider>
                      <v-card-text id="event-organizer" v-if="event.is_white_label">
                        <v-row dense align="center">
                          <v-col cols="auto">
                            <v-icon>mdi-domain</v-icon>
                          </v-col>
                          <v-col>
                            <h3 class="title">{{$t('event.organizer')}}</h3>
                          </v-col>
                        </v-row>
                        <v-row dense>
                          <v-col class="text-center">
                            <v-avatar size="100" color="primary">
                              <v-img v-if="event.organizer.picture_url && event.organizer.picture_url!='null'" aspect-ratio="1" :src="event.organizer.picture_url" :alt="event.settings.white_label_name"></v-img>
                              <span v-else class="display-3" :class="(event.settings.white_label_mode=='dark')?'white--text':'black--text'">{{event.settings.white_label_name.substr(0,1).toUpperCase()}}</span>
                            </v-avatar>
                            <div class="mt-3 title font-weight-bold">{{ _f(event.organizer.fields, 'title') }}</div>
                          </v-col>
                        </v-row>
                        <v-row dense justify="center">
                          <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.phone">
                            <v-icon small class="mr-1">mdi-phone</v-icon><a :href="'tel:'+event.organizer.phone.replace(',', '')" class="font-weight-bold">{{ event.organizer.phone.replace(',', '') }}</a>
                          </v-col>
                          <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.email">
                            <v-icon small class="mr-1">mdi-email</v-icon><a :href="'mailto:'+event.organizer.email" class="font-weight-bold">{{ event.organizer.email }}</a>
                          </v-col>
                          <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.website_url">
                            <v-icon small class="mr-1">mdi-web</v-icon><a :href="event.organizer.website_url" target="_blank" class="font-weight-bold">{{ event.organizer.website_url }}</a>
                          </v-col>
                        </v-row>
                        <v-row dense justify="center">
                          <v-col>
                            <p class='description ql-editor' v-html="_f(event.organizer.fields, 'description')"></p>
                          </v-col>
                        </v-row>
                      </v-card-text>
                    </v-card>
                  </v-col>
                </v-row>
              </section>
            </v-container>
          </div>
        </v-content>
        <app-footer></app-footer>
        <v-snackbar v-cloak
          bottom
          right
          class="d-flex"
          style="height: auto; user-select: none;"
          :style="snackbar.zindex?'z-index:'+snackbar.zindex:''"
          :timeout="snackbar.timeout"
          :color="snackbar.color"
          v-model="snackbar.show"
        >
          <v-icon v-if="snackbar.icon" :dark="snackbar.dark" style="cursor:pointer" @click="snackbar.show = false">{{snackbar.icon}}</v-icon>
          <span class="font-weight-bold px-2">{{ snackbar.text }}</span>
          <template v-slot:action="{ attrs }">
            <v-btn v-bind="attrs" v-if="snackbar.timeout<=0" dark @click.native="snackbar.show = false" icon> 
              <v-icon>mdi-close</v-icon>
            </v-btn>
          </template>
        </v-snackbar> 
      </v-app>
    </div>
    <!-- vue script -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.2.4/dist/vuetify.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-i18n@8.21.1/dist/vue-i18n.min.js"></script>
    <script src="https://unpkg.com/axios@0.20.0/dist/axios.min.js"></script>
    <script type="text/babel" data-presets="es2015, es2016, es2017, stage-3">
    "use strict";
    (function() {
      <?php include("./components/loadingWidget.vue");?>
      <?php include("./components/appToolbar.vue");?>
      <?php include("./components/appFooter.vue");?>
      <?php include("./components/blurImage.vue");?>
      <?php include("./components/shareOptions.vue");?>
      <?php include("./components/eventBasicInfo.vue");?>

      const i18n = new VueI18n({
        locale: 'zh_TW',
         messages: {
          zh_TW: {
            lang: {
              'zh_TW': '繁體中文',
              'zh_CN': '简体中文',
              'en': 'English',
              'ja': '日本語',
            },
            lang_abbr: {
              'zh_TW': '繁中',
              'zh_CN': '簡中',
              'en': '英',
              'ja': '日',
            },
            event: {
              datetime: '活動時間',
              location: '活動地點',
              organizer: '主辦單位',
              details: '活動詳情',
            },
            ticket: {
              details: '門票詳情',
              serviceFee: '手續費',
              paid: {
                title: '活動門票',
              },
              free: {
                title: '活動登記',
              },
            },
            every_weekday: '逢星期',
            weekday: [
              {name:'星期日', abbr:'日'},
              {name:'星期一', abbr:'一'},
              {name:'星期二', abbr:'二'},
              {name:'星期三', abbr:'三'},
              {name:'星期四', abbr:'四'},
              {name:'星期五', abbr:'五'},
              {name:'星期六', abbr:'六'},
            ],
            footer: {
              blog: '部落格',
              instruction: '如何購買門票',
              faq: '常見問題',
              termsOfUse: '使用條款',
              privacyPolicy: '隱私政策',
              paymentAccept: '支付方法',
            },
          },
          en: {
            lang: {
              'zh_TW': '繁體中文',
              'zh_CN': '简体中文',
              'en': 'English',
              'ja': '日本語',
            },
            lang_abbr: {
              'zh_TW': '繁中',
              'zh_CN': '簡中',
              'en': '英',
              'ja': '日',
            },
            event: {
              datetime: 'When',
              location: 'Where',
              organizer: 'Organizer',
              details: 'Event Details',
              
            },
            ticket: {
              details: 'Details',
              serviceFee: 'Handling Fee',
              paid: {
                title: 'Event Tickets',
              },
              free: {
                title: 'Event Registration',
              },
            },
            every_weekday: 'Every ',
            weekday: [
              {name:'Sunday', abbr:'Sun'},
              {name:'Monday', abbr:'Mon'},
              {name:'Tuesday', abbr:'Tue'},
              {name:'Wednesday', abbr:'Wed'},
              {name:'Thursday', abbr:'Thu'},
              {name:'Friday', abbr:'Fri'},
              {name:'Saturday', abbr:'Sat'},
            ],
            footer: {
              blog: 'Blog',
              instruction: 'How To Get Tickets',
              faq: 'FAQ',
              termsOfUse: 'Terms of Use',
              privacyPolicy: 'Privacy Policy',
              paymentAccept: 'We Accept',
            },
          }
        }
      })
      Vue.prototype.is_mobile = /android|webos|iphone|ipad|ipod|blackberry|mobile|opera mini/i.test(navigator.userAgent.toLowerCase());
      Vue.prototype.is_iOS = /iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase());
      Vue.prototype.is_safari = /apple/i.test(navigator.vendor.toLowerCase());
      var app = new Vue({
        el: '#app',
        i18n,
        vuetify: new Vuetify({
          theme: {
            themes: {
              light: {
                primary: "#ff5000",
                secondary: "#424242",
                accent: "#82B1FF",
                error: "#FF5252",
                info: "#2196F3",
                success: "#4CAF50",
                warning: "#FFC107",
                facebook: "#4266b2",
                whatsapp: "#47c057",
                wechat: "#2dc100",
                line: "#00b900",
              },
              dark: {
                primary: "#ff5000",
                secondary: "#424242",
                accent: "#82B1FF",
                error: "#FF5252",
                info: "#2196F3",
                success: "#4CAF50",
                warning: "#FFC107",
                facebook: "#4266b2",
                whatsapp: "#47c057",
                wechat: "#2dc100",
                line: "#00b900",
              },
            },
          }
        }),
        data: {
          event: <?=json_encode($event);?>,
          loading: false,
          loading_widget: {
            loading: false,
          },
          transaction: {tickets:[]},
          snackbar: {
            show: false,
            timeout: -1,
            text: '',
            color: '',
          },
        },
        mounted () {
          window.app = this
          console.log(this.clone(this.event));
          // let id = this.getUrlParam('event'); // location.pathname.split("/").pop();
          // this.getEvent(id);
          if (this.event.is_white_label && this.event.settings.white_label_color) {
            this.$vuetify.theme.themes.light.primary = this.event.settings.white_label_color;
            this.$vuetify.theme.themes.dark.primary = this.event.settings.white_label_color;
          }
        },
        provide () {
          return {
            _f: this._f,
            copyText: this.copyText,
            showToast: this.showToast, // together with copytext
            getUrlParam: this.getUrlParam,
            updateUrlParam: this.updateUrlParam,
          }
        },
        methods: {
          // general methods
            showToast (args, style = false) {
              this.snackbar.show = false;
              switch (style) {
                case 'success': 
                  args = {
                    timeout: 3000,
                    color: 'success',
                    icon: 'mdi-check',
                    ...args,
                  }
                  break;
                case 'warning':
                  args = {
                    timeout: 3000,
                    color: 'warning',
                    icon: 'mdi-close',
                    ...args,
                  }
                  break;
                case 'error':
                  args = {
                    timeout: 3000,
                    color: 'error',
                    icon: 'mdi-close',
                    ...args,
                  }
                  break;
              }
              this.$nextTick().then(()=>{
                let opts = {
                  text: '', 
                  color: 'primary', 
                  timeout: -1, 
                  icon: false, 
                  dark: true,
                  zindex: 201,
                  ...args
                };
                this.snackbar = {
                  ...opts,
                  show: true
                };
              });
            },
            sha256: function sha256(text) {
              function rightRotate(value, amount) {
                return (value>>>amount) | (value<<(32 - amount));
              };
              
              var mathPow = Math.pow;
              var maxWord = mathPow(2, 32);
              var lengthProperty = 'length'
              var i, j; // Used as a counter across the whole file
              var result = ''

              var words = [];
              var textBitLength = text[lengthProperty]*8;
              
              //* caching results is optional - remove/add slash from front of this line to toggle
              // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
              // (we actually calculate the first 64, but extra values are just ignored)
              var hash = sha256.h = sha256.h || [];
              // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
              var k = sha256.k = sha256.k || [];
              var primeCounter = k[lengthProperty];
              /*/
              var hash = [], k = [];
              var primeCounter = 0;
              //*/

              var isComposite = {};
              for (var candidate = 2; primeCounter < 64; candidate++) {
                if (!isComposite[candidate]) {
                  for (i = 0; i < 313; i += candidate) {
                    isComposite[i] = candidate;
                  }
                  hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
                  k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
                }
              }
              
              text += '\x80' // Append Ƈ' bit (plus zero padding)
              while (text[lengthProperty]%64 - 56) text += '\x00' // More zero padding
              for (i = 0; i < text[lengthProperty]; i++) {
                j = text.charCodeAt(i);
                if (j>>8) return; // text check: only accept characters in range 0-255
                words[i>>2] |= j << ((3 - i)%4)*8;
              }
              words[words[lengthProperty]] = ((textBitLength/maxWord)|0);
              words[words[lengthProperty]] = (textBitLength)
              
              // process each chunk
              for (j = 0; j < words[lengthProperty];) {
                var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
                var oldHash = hash;
                // This is now the undefinedworking hash", often labelled as variables a...g
                // (we have to truncate as well, otherwise extra entries at the end accumulate
                hash = hash.slice(0, 8);
                
                for (i = 0; i < 64; i++) {
                  var i2 = i + j;
                  // Expand the message into 64 words
                  // Used below if 
                  var w15 = w[i - 15], w2 = w[i - 2];

                  // Iterate
                  var a = hash[0], e = hash[4];
                  var temp1 = hash[7]
                    + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
                    + ((e&hash[5])^((~e)&hash[6])) // ch
                    + k[i]
                    // Expand the message schedule if needed
                    + (w[i] = (i < 16) ? w[i] : (
                        w[i - 16]
                        + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0
                        + w[i - 7]
                        + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1
                      )|0
                    );
                  // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
                  var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
                    + ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj
                  
                  hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
                  hash[4] = (hash[4] + temp1)|0;
                }
                
                for (i = 0; i < 8; i++) {
                  hash[i] = (hash[i] + oldHash[i])|0;
                }
              }
              
              for (i = 0; i < 8; i++) {
                for (j = 3; j + 1; j--) {
                  var b = (hash[i]>>(j*8))&255;
                  result += ((b < 16) ? 0 : '') + b.toString(16);
                }
              }
              return result;
            },
            handleError (err = {}) {
              if (err.status === 418) {
                return this.$swal(err.data.error.message, "", "error");
              } else {
                console.error(err);
                return this.$swal(this.$t('error.general.error'), "", "error");
              }
            },
            getUrlParam (param) {
              const params = new URLSearchParams(window.location.search);
              return params.get(param);
            },
            updateUrlParam (data) {
              const params = new URLSearchParams(window.location.search);
              if (Array.isArray(data)) {
                data.forEach(d => {
                  params.set(d.name, d.value);
                });
              } else {
                params.set(data.name, data.value);
              }
              window.history.replaceState({}, document.title, decodeURIComponent(`${window.location.pathname}?${params}`));
            },
            params: function params (data, keys = [], isArray = false) {
              const p = Object.keys(data).map(key => {
                let val = data[key]
                if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
                  if (Array.isArray(data)) {
                    keys.push("")
                  } else {
                    keys.push(key)
                  }
                  return params(val, keys, Array.isArray(val))
                } else {
                  let tKey = key
                  if (keys.length > 0) {
                    const tKeys = isArray ? keys : [...keys, key]
                    tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
                  }
                  if (isArray) {
                    return `${ tKey }[]=${ val }`
                  } else {
                    return `${ tKey }=${ val }`
                  }
                }
              }).join('&')
              keys.pop()
              return p
            },
            getQuery () {
              var urlParams = new URLSearchParams(location.search);
              var entries = urlParams.entries();
              let result = {}
              for(let entry of entries) { // each 'entry' is a [key, value] tupple
                var [key, value] = entry;
                result[key] = value;
              }
              return result; 
            },
          // utils
            clone (o) {
              return JSON.parse(JSON.stringify(o));
            },
            _get (object, keys, defaultVal) {
              if (object) {
                if (keys) {
                  keys = Array.isArray(keys) ? keys : keys.split('.');
                } else {
                  keys = [];
                }
                object = object[keys[0]];
                if (object && keys.length > 1) {
                  return this._get(object, keys.slice(1), defaultVal);
                }
                return object === undefined ? defaultVal : object;
              } else {
                return defaultVal;
              }
            },
            _f (data, attr, lang) {
              if (lang) {
                return this._get(data, lang + '.' + attr, data['default'][attr]);
              } else {
                return this._get(data, this.$i18n.locale + '.' + attr, data['default'][attr]);
              }
            },
            getISODateString (date) {
              // ISO 8601 TZ
              var iso_format_date;
              if (typeof date === "number") {
                iso_format_date = new Date(date);
              } else {
                iso_format_date = new Date((date&&date.toString().split('+')[0]));
              }
              // locale datetime
              return  new Date(iso_format_date).toLocaleDateString("fr-CA");
            },
            copyText (text, toast = true) {
              let is_iOS = /iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase());
              let is_safari = /apple/i.test(navigator.vendor.toLowerCase());
              if (is_iOS || is_safari){
                var textArea = document.createElement('textArea');
                textArea.value = text;
                document.body.appendChild(textArea);
                var range = document.createRange();
                range.selectNodeContents(textArea);
                var selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
                textArea.setSelectionRange(0, 999999);
                document.execCommand('copy');
                document.body.removeChild(textArea);
              } else {
                navigator.clipboard.writeText(text);
              }
              
              if (toast) {
                this.showToast({text: "Copy Successfully", zindex:301}, "success");
              }
            },
          // event methods
          getEvent(id) {
            this.loading_widget.loading=true;
            let query = this.params({
              log_view: true,
              url_params: this.getQuery(),
            });
            axios.get("<?=$root_api;?>"+`events/${id}?${query}`, {
              headers: {
                'Content-Type': 'multipart/form-data',
              }
            }).then(res => {
              this.event = res.data.data;
              // this.applyEventSettings();
              // init purchase quantity to 0
              // this.event.tickets = this.event.tickets.map(ticket => ({...ticket, purchase_quantity: 0 }));
              // dataLayer.push({
              //   'event': 'eec.detail',
              //   'ecommerce': {
              //     'detail': {
              //       'products': [{
              //         'id': this.event.id,
              //         'name': this.event.fields.default.title,
              //         'category': this.event.event_category.fields.default.title, // this.event.event_category_id,
              //         'brand': this.event.organizer.fields.default.title, // this.event.organizer_id,
              //         'event_tag': this.event.tags.join(',') ? this.event.tags.join(',') + ',' : ''
              //       }]
              //     }
              //   }
              // });
              
              // let _this = this;
              // setTimeout(function() {
              //   fbq('track', 'ViewContent', { 
              //     env: process.env.VUE_APP_ENV,
              //     event_id: _this.event.id,
              //     event_tag: _this.event.tags.join(',') ? _this.event.tags.join(',') + ',' : '',
              //     event_category_id: _this.event.event_category_id,
              //     event_country_id: _this.event.country_id,
              //   });
              // }, 3000);
              
            }).catch(err => {
              if (err.status === 404) {
                this.$router.push({ name: 'NotFound' });
              } else {
                this.showError(err);
              }
            }).finally(()=> {
              this.loading_widget.loading = false;
            });
          },
          getEventURL(event) {
            if (window.location === window.parent.location) {
              return this.public_url + 'event/' + (event.url_string||event.id);
            } else {
              return document.referrer;
            }
          },
          isPaidEvent() {
            return (this.event.tickets && this.event.tickets.length>0 && this.event.tickets.filter(t=>t.price>0).length>0);
          },
          checkStatus (ticket) {
            return 'available';
          },
          changeLinkColor(html) {
            return this.event.is_white_label ? html.replace(/<a /g, "<a style=\"color: " + this.event.settings.white_label_color + "\" ") : html
          },
        }
      });
    })();
    </script>
  </body>
</html>
