Vue.component("loading",{template:`<div class="loadingSpinner text-center">
    <i class="fas fa-spinner fa-spin fa-3x" style="color: #169AD7;"></i>
    <p>Loading...</p>
</div>`});
const makeSearchComponentStore=function(){return new Vuex.Store({state:{loading:!0,context:{url:null,searchFields:[]},query:{defaultKeywords:null,userKeywords:null,searchFields:[],filterExpression:null,orderBy:null,itemLimit:10,skip:0,facetFields:[],facetFilters:{},language:null,otherSearchOptions:{}},results:{totalCount:0,search:[],facets:[]},error:null,router:null,storeType:"search"},mutations:{init(state,payload){payload.context&&(state.context=Object.assign(Object.assign({},state.context),payload.context));payload.query&&(state.query=Object.assign(Object.assign({},state.query),payload.query))},loading(state,isLoading){state.loading=isLoading},results(state,payload){state.results=payload},userKeywords(state,keywords){state.query.userKeywords=keywords},filterExpression(state,filterExpression){state.query.filterExpression=filterExpression},skipResults(state,skipResults){state.query.skip=skipResults},addFacetFilterValue(state,facet){let filterValues=state.query.facetFilters[facet.id]||[];filterValues.includes(facet.value)?filterValues=filterValues.filter(f=>f!==facet.value):filterValues.push(facet.value);let newFilters=Object.assign({},state.query.facetFilters);filterValues.length?newFilters[facet.id]=filterValues:delete newFilters[facet.id];state.query.facetFilters=newFilters},setFacetFilter(state,facet){let filterValues=state.query.facetFilters[facet.id],newFilters=Object.assign({},state.query.facetFilters);!facet&&filterValues?delete newFilters[facet.id]:newFilters[facet.id]=facet.values;state.query.facetFilters=newFilters},setOtherSearchOptions(state,otherSearchOptions){state.query.otherSearchOptions=Object.assign(Object.assign({},state.query.otherSearchOptions),otherSearchOptions)},setFromRoute(state){let query=state.router.currentRoute.query;state.query.userKeywords=query.k||null;state.query.facetFilters=query.f?JSON.parse(query.f):{};state.query.skip=parseInt(query.s)||0},setRouter(state,router){state.router=router},removeFiltersForFacet(state,facetId){let newFilters=Object.assign({},state.query.facetFilters);delete newFilters[facetId];state.query.facetFilters=newFilters},removeFiltersForFacets(state,facetIds){let newFilters=Object.assign({},state.query.facetFilters);facetIds.forEach(id=>{delete newFilters[id]});state.query.facetFilters=newFilters},clearAllFacetFilters(state){state.query.facetFilters={}},reset(state){state.query.facetFilters={};state.query.userKeywords=null;state.query.skip=0},error(state,error){state.error=error}},actions:{init({commit,dispatch,state},initialState){if(initialState.router&&commit("setRouter",initialState.router),commit("init",{context:initialState.context,query:initialState.query}),state.router&&(commit("setFromRoute"),window.addEventListener("popstate",()=>{dispatch("updateFromRoute")})),initialState.fetch!==!1)return dispatch("fetchResults")},skipResults({commit,dispatch},skipResults){return commit("skipResults",skipResults),dispatch("fetchResults")},newKeywordQuery({commit,dispatch},keywords){return commit("userKeywords",keywords),commit("skipResults",0),dispatch("fetchResults")},newFilterExpression({commit,dispatch},filterExpression){return commit("filterExpression",filterExpression),commit("skipResults",0),dispatch("fetchResults")},addFacetFilterValue({commit,dispatch},facet){return commit("addFacetFilterValue",facet),commit("skipResults",0),dispatch("fetchResults")},setFacetFilter({commit,dispatch},facet){return commit("setFacetFilter",facet),commit("skipResults",0),dispatch("fetchResults")},setMultipleFacetFilters({commit,dispatch},facets){return facets.forEach(facet=>{commit("setFacetFilter",facet)}),commit("skipResults",0),dispatch("fetchResults")},setOtherSearchOptions({commit,dispatch},otherSearchOptions){return commit("setOtherSearchOptions",otherSearchOptions),dispatch("fetchResults")},removeFiltersForFacet({commit,dispatch},facetId){return commit("removeFiltersForFacet",facetId),commit("skipResults",0),dispatch("fetchResults")},removeFiltersForFacets({commit,dispatch},facetIds){return commit("removeFiltersForFacets",facetIds),commit("skipResults",0),dispatch("fetchResults")},clearAllFacetFilters({commit,dispatch}){return commit("clearAllFacetFilters"),commit("skipResults",0),dispatch("fetchResults")},reset({commit,dispatch}){return commit("reset"),dispatch("fetchResults")},updateFromRoute({commit,dispatch}){return commit("setFromRoute"),dispatch("fetchResults")},updateRoute({state}){let route=state.router.currentRoute,query=Object.assign({},route.query);state.query.userKeywords?query.k=state.query.userKeywords:delete query.k;Object.keys(state.query.facetFilters).length?query.f=JSON.stringify(state.query.facetFilters):delete query.f;state.query.skip?query.s=state.query.skip:delete query.s;JSON.stringify(query)!=JSON.stringify(route.query)&&state.router.push({query})},fetchResults({commit,dispatch,state}){return commit("loading",!0),new Promise((resolve,reject)=>{var _a,_b;let requestBody={searchQuery:state.query.userKeywords,filterKeywords:state.query.defaultKeywords,searchFields:state.query.searchFields,filterExpression:state.query.filterExpression,orderBy:state.query.orderBy,itemLimit:state.query.itemLimit,skip:state.query.skip,facetFields:state.query.facetFields,language:state.query.language};((_a=Object.keys(state.query.facetFilters))===null||_a===void 0?void 0:_a.length)&&(requestBody.facetFilters=state.query.facetFilters);((_b=Object.keys(state.query.otherSearchOptions))===null||_b===void 0?void 0:_b.length)&&(requestBody.otherOptions=state.query.otherSearchOptions);$.ajax({url:state.context.url,method:"POST",contentType:"application/json",data:JSON.stringify(requestBody)}).then(response=>{commit("results",{totalCount:response.totalCount,search:response.results,facets:response.facets}),state.router&&dispatch("updateRoute"),commit("error",null),commit("loading",!1),resolve()}).fail(error=>{commit("error",error),commit("loading",!1),reject(error)})})}}})};
Vue.component("search-base",{props:{url:String,searchQuery:String,defaultKeywords:String,searchFields:{type:Array,"default":function(){return[]}},itemLimit:{type:Number,"default":0},facetFields:{type:Array,"default":function(){return[]}},otherOptions:{type:Object,"default":function(){return{}}}},router:Daktronics.Components.GetVueRouter(),created(){this.$store.commit("setRouter",this.$router);this.$store.dispatch("init",{context:{url:this.url},query:{userKeywords:this.searchQuery,defaultKeywords:this.defaultKeywords,searchFields:this.searchFields,itemLimit:this.itemLimit,facetFields:this.facetFields,otherSearchOptions:this.otherOptions}}).then(()=>{this.$root.$emit("search-loaded")})},template:"<div><\/div>"});
Vue.component("search-box",{props:{searchValue:String,title:{type:String,"default":"Search"},placeholder:{type:String,"default":"Search..."},showReset:{type:Boolean,"default":!0}},data:function(){return{textValue:""}},watch:{searchValue(searchValue){!this.textValue&&searchValue&&(this.textValue=searchValue)}},methods:{updateSearchValue:function(){this.$emit("update-search-value",this.textValue)},reset:function(){this.textValue="";this.$emit("reset")}},mounted(){!this.textValue&&this.searchValue&&(this.textValue=this.searchValue)},template:`
<div class="input-group dak-search-box">
    <input type="text"
            class="form-control"
            :aria-label="title"
            :placeholder="placeholder"
            v-model="textValue"
            @keyup.enter="updateSearchValue" />
    <div class="input-group-append search-button">
        <span class="input-group-text" @click="updateSearchValue" :title="title"><i class="fas fa-search"></i></span>
        <span v-if="showReset" class="input-group-text" @click="reset" title="Reset"><i class="fas fa-undo-alt"></i></span>
	</div>
</div>`});$(".search-box-content-block").length&&$(".search-box-content-block").each(function(){let id=$(this).attr("id");new Vue({el:"#"+id,methods:{updateUserSearchQuery(keywords){let url=this.$el.getAttribute("data-search-page"),queryParam=this.$el.getAttribute("data-query-param");window.location.href=encodeURI(`${url}?${queryParam}=${keywords}`)}}})});
Vue.component("search-facets",{props:{facetResults:{type:Array,"default":function(){return[]}}},data(){return{facetsShowing:null}},computed:{dropDownRefiners(){return this.facetResults.filter(facet=>!facet.advancedOnly)}},watch:{facetResults(){this.$nextTick(()=>this.showHideDropdowns())}},methods:{clearFilters(){this.$store.dispatch("clearAllFacetFilters");this.$root.$emit("clear-facets")},showHideDropdowns(){let $buttons=$(".facet-dropdowns>*"),containerWidth=$buttons.parent().width(),widthReducer=(acc,button)=>acc+$(button).outerWidth(),$dropdowns=$buttons.filter(":not(a)"),buttonsWidth=$buttons.get().reduce(widthReducer,0),$hiddenDropdowns=$dropdowns.filter(":hidden");for($hiddenDropdowns.length&&buttonsWidth<containerWidth&&($hiddenDropdowns.first().removeClass("d-none"),buttonsWidth=$buttons.get().reduce(widthReducer,0));buttonsWidth>0&&buttonsWidth>=containerWidth;)$dropdowns.filter(":visible").last().addClass("d-none"),buttonsWidth=$buttons.get().reduce(widthReducer,0);this.facetsShowing=$dropdowns.filter(":visible").length}},created(){$(window).on("resize",()=>{setTimeout(()=>{this.showHideDropdowns()},20)});this.showHideDropdowns()},template:`
<div>
    <div class="facet-dropdowns text-center d-none d-md-flex flex-nowrap justify-content-center">
        <search-facet-dropdown v-for="(facet, index) in dropDownRefiners" :key="index"
                                :facet="facet"></search-facet-dropdown>
        <a v-show="facetResults !== null && facetsShowing < facetResults.length"
            class="btn btn-outline-primary dak-btn-refiner my-3 mx-1 py-2 px-3 text-nowrap"
            href="#" role="button" data-toggle="modal" data-target="#allRefinersModal"><i class="fas fa-filter"></i> More Filters...</a>
    </div>
    <div class="text-center d-md-none">
        <a class="btn btn-block w-50 btn-outline-primary dak-btn-refiner my-3 mx-auto py-2 px-3"
            href="#" role="button" data-toggle="modal" data-target="#allRefinersModal"><i class="fas fa-filter"></i> Filter...</a>
    </div>
    <div class="modal fade" id="allRefinersModal" tabindex="-1" role="dialog" aria-labelledby="allRefinersModalTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="allRefinersModalTitle">All Filters</h3>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body text-left">
                    <div class="accordion" id="allRefinersAccordion">
                        <search-facet-collapse v-for="facet in facetResults" :key="facet.id"
                                                :facet="facet"
                                                parent-selector="#allRefinersAccordion"></search-facet-collapse>
                        <slot></slot>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" @click="clearFilters">Clear</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Done</button>
                </div>
            </div>
        </div>
    </div>
</div>`});Vue.component("search-facet-dropdown",{props:{facet:Object},computed:{selections(){return this.$store.state.query.facetFilters[this.facet.id]||[]},label(){let label="All "+this.facet.pluralLabel;return this.selections.length===1?label=this.selections[0]:this.selections.length>1&&(label=this.selections[0]+" and others"),label},topResults(){let results=[];return this.facet.results&&(results=[...this.facet.results].filter((result,index)=>index<15)),results}},methods:{applyFacetFilter(result){this.$store.dispatch("addFacetFilterValue",{id:this.facet.id,value:result.label})},clearRefinement(){this.$store.dispatch("removeFiltersForFacet",this.facet.id)},facetResultIsSelected(result){return this.selections.includes(result.label)}},template:`
<div>
  <div class="btn-group dropdown">
      <button class="btn btn-outline-primary dak-btn-refiner dropdown-toggle my-3 mx-1 py-2 px-3"
          href="#" type="button" data-toggle="dropdown"
          aria-haspopup="true" aria-expanded="false"
          :disabled="!facet.results || facet.results.length === 0"
      >{{ label }}</button>
      <div class="dropdown-menu">
          <a class="dropdown-item dak-refiner-result"
              v-show="selections.length > 0"
              v-on:click="clearRefinement()"
          ><span>All {{ facet.pluralLabel }}</span></a>
          <a v-for="result in topResults"
              v-on:click="applyFacetFilter(result)"
              v-bind:class="{ 'font-weight-bold': facetResultIsSelected(result) }"
              class="dropdown-item dak-refiner-result"
          ><span>{{ result.label }}</span>
            <span class="dak-refiner-result-count">({{ result.count }})</span></a>
      </div>
  </div>
</div>`});Vue.component("search-facet-collapse",{props:{facet:Object,parentSelector:String},data:function(){return{columnCount:2}},computed:{id(){return this.facet.id},selections(){return this.$store.state.query.facetFilters[this.facet.id]||[]},sortedResults(){let results=[];return this.facet.results&&(results=[...this.facet.results].sort((a,b)=>{let labelA=a.label.toUpperCase(),labelB=b.label.toUpperCase();return labelA<labelB?-1:labelA>labelB?1:0})),results},columns(){let columns=[],resultsInColumns=0;for(let i=0;i<this.columnCount;i++){let columnCount=this.facet.results.length/this.columnCount,startIndex=resultsInColumns,stopIndex=columnCount+startIndex,column={"class":`col-lg-${12/this.columnCount}`,results:this.sortedResults.filter((r,i)=>i>=startIndex&&i<stopIndex)};columns.push(column);resultsInColumns=stopIndex}return columns}},methods:{isSelected(result){return this.selections.some(selection=>selection===result.label)},onChange(result){let filter={id:this.facet.id,value:result.label};this.$store.dispatch("addFacetFilterValue",filter)}},template:`
<div>
    <div class="accordionHeading invert position-relative">
        <h2><a :href="'#' + id"
                class="stretched-link"
                data-toggle="collapse"
                aria-expanded="false"
                :aria-controls="id">{{facet.label}}</a></h2>
    </div>
    <div class="collapse container-fluid" :id="id" :data-parent="parentSelector">
        <div class="row pt-2 pb-3">
            <div v-for="(column, index) in columns" :key="index" :class="column.class">
                <div v-for="(result, index) in column.results" :key="result.value" class="form-check">
                    <input class="form-check-input"
                            type="checkbox"
                            :id="id + index.toString()"
                            :value="result.label"
                            :checked="isSelected(result)"
                            @change="onChange(result)">
                    <label class="form-check-label" :for="id + index.toString()">
                        {{ result.label || '(Not specified)' }} <span class="dak-refiner-result-count">({{ result.count }})</span>
                    </label>
                </div>
            </div>
        </div>
    </div>
    <hr class="my-2">
</div>`});
Vue.component("search-paging",{props:{totalRows:Number,startRow:Number,rowLimit:Number,pageLimit:Number},data:function(){return{pages:[]}},computed:{pageCount:function(){return Math.ceil(this.totalRows/this.rowLimit)},onFirstPage:function(){return this.currentPageNumber<=1},onLastPage:function(){return this.currentPageNumber>=this.pageCount},currentPageNumber:function(){return this.getPageNumber(this.startRow,this.rowLimit)},currentPage:function(){return this.pages.find(p=>p.number===this.currentPageNumber)}},watch:{startRow:function(){this.setPages()},rowLimit:function(){this.setPages()},totalRows:function(){this.setPages()}},methods:{getPageByNumber:function(pageNumber){return this.pages.find(page=>page.number===pageNumber)},goToNextPage:function(goBack,event){let iterator=goBack?-1:1,nextPageNumber=this.currentPageNumber+iterator;nextPage=this.getPageByNumber(nextPageNumber);this.goToPage(nextPage,event)},goToPage:function(page,event){return event&&event.preventDefault(),this.$emit("change-page",page.startRow),this.$nextTick(function(){this.emitPagingData()}),!1},getPageNumber:function(startRow,rowLimit){return startRow===0?1:Math.floor(startRow/rowLimit+1)},getStartRowForPage:function(pageNumber,rowLimit){return pageNumber===1?0:pageNumber*rowLimit},setPages:function(){let pages=[],currentPageNumber=this.getPageNumber(this.startRow,this.rowLimit),startingPageNumber=Math.max(currentPageNumber-Math.ceil(this.pageLimit/2),0),endingPageNumber=Math.min(startingPageNumber+this.pageLimit,this.pageCount),pageIncrementer=startingPageNumber;while(pageIncrementer>=startingPageNumber&&pageIncrementer<endingPageNumber)pages.push({number:pageIncrementer+1,startRow:pageIncrementer*this.rowLimit}),pageIncrementer++;this.pages=pages;this.emitPagingData()},emitPagingData:function(){let pagingData={pages:this.pages,currentPage:this.currentPage};this.$emit("update-paging-data",pagingData)}},created:function(){this.setPages()},template:`
<ul v-if="totalRows > rowLimit" class="pagination justify-content-center">
    <li class="page-item" v-bind:class="{disabled: onFirstPage}">
        <a class="page-link dak-page-link" href="#"
        v-bind:tabindex="onFirstPage ? -1 : 0"
        v-bind:aria-disabled="onFirstPage ? 'true' : 'false'"
        v-on:click="goToNextPage(true, $event)"
        >Previous</a>
    </li>
    <li class="page-item" v-for="page in pages" v-bind:class="{active: page.number === currentPageNumber}">
        <a class="page-link dak-page-link" href="#" v-on:click="goToPage(page, $event)">{{ page.number }}</a>
    </li>
    <li class="page-item" v-bind:class="{disabled: onLastPage}">
        <a class="page-link dak-page-link" href="#" 
        v-bind:tabindex="onLastPage ? -1 : 0"
        v-bind:aria-disabled="onLastPage ? 'true' : 'false'"
        v-on:click="goToNextPage(false, $event)"
        >Next</a>
    </li>
</ul>`});
