/* Minification failed. Returning unminified contents.
(726,62-63): run-time error JS1195: Expected expression: >
(726,87-88): run-time error JS1004: Expected ';': )
(727,9-10): run-time error JS1002: Syntax error: }
(728,55-56): run-time error JS1004: Expected ';': {
(733,62-63): run-time error JS1195: Expected expression: >
(733,103-104): run-time error JS1004: Expected ';': )
(776,5-6): run-time error JS1002: Syntax error: }
(778,46-47): run-time error JS1195: Expected expression: )
(778,48-49): run-time error JS1004: Expected ';': {
(879,45-46): run-time error JS1195: Expected expression: >
(879,78-79): run-time error JS1195: Expected expression: )
(881,45-46): run-time error JS1195: Expected expression: >
(881,87-88): run-time error JS1195: Expected expression: )
(883,45-46): run-time error JS1195: Expected expression: >
(883,87-88): run-time error JS1004: Expected ';': )
(885,45-46): run-time error JS1195: Expected expression: >
(885,80-81): run-time error JS1004: Expected ';': )
(895,47-48): run-time error JS1195: Expected expression: )
(895,49-50): run-time error JS1004: Expected ';': {
(939,69-70): run-time error JS1195: Expected expression: >
(993,45-46): run-time error JS1195: Expected expression: >
(993,78-79): run-time error JS1195: Expected expression: )
(997,5-6): run-time error JS1002: Syntax error: }
(999,5-16): run-time error JS1197: Too many errors. The file might not be a JavaScript file: lookupInput
(896,9-21): run-time error JS1018: 'return' statement outside of function: return false
(880,13-22): run-time error JS1018: 'return' statement outside of function: return ""
(779,9-86): run-time error JS1018: 'return' statement outside of function: return $scope.accessType != "MyVault" && $scope.searchModel.SuperType == null
(747,13-19): run-time error JS1018: 'return' statement outside of function: return
 */
/*
 * angular-ui-bootstrap
 * http://angular-ui.github.io/bootstrap/

 * Version: 2.5.0 - 2017-01-28
 * License: MIT
 */angular.module("ui.bootstrap",["ui.bootstrap.tpls","ui.bootstrap.modal","ui.bootstrap.multiMap","ui.bootstrap.stackedMap","ui.bootstrap.position"]),angular.module("ui.bootstrap.tpls",["uib/template/modal/window.html"]),angular.module("ui.bootstrap.modal",["ui.bootstrap.multiMap","ui.bootstrap.stackedMap","ui.bootstrap.position"]).provider("$uibResolve",function(){var t=this;this.resolver=null,this.setResolver=function(t){this.resolver=t},this.$get=["$injector","$q",function(e,o){var n=t.resolver?e.get(t.resolver):null;return{resolve:function(t,r,i,a){if(n)return n.resolve(t,r,i,a);var l=[];return angular.forEach(t,function(t){l.push(angular.isFunction(t)||angular.isArray(t)?o.resolve(e.invoke(t)):angular.isString(t)?o.resolve(e.get(t)):o.resolve(t))}),o.all(l).then(function(e){var o={},n=0;return angular.forEach(t,function(t,r){o[r]=e[n++]}),o})}}}]}).directive("uibModalBackdrop",["$animate","$injector","$uibModalStack",function(t,e,o){function n(e,n,r){r.modalInClass&&(t.addClass(n,r.modalInClass),e.$on(o.NOW_CLOSING_EVENT,function(o,i){var a=i();e.modalOptions.animation?t.removeClass(n,r.modalInClass).then(a):a()}))}return{restrict:"A",compile:function(t,e){return t.addClass(e.backdropClass),n}}}]).directive("uibModalWindow",["$uibModalStack","$q","$animateCss","$document",function(t,e,o,n){return{scope:{index:"@"},restrict:"A",transclude:!0,templateUrl:function(t,e){return e.templateUrl||"uib/template/modal/window.html"},link:function(r,i,a){i.addClass(a.windowTopClass||""),r.size=a.size,r.close=function(e){var o=t.getTop();o&&o.value.backdrop&&"static"!==o.value.backdrop&&e.target===e.currentTarget&&(e.preventDefault(),e.stopPropagation(),t.dismiss(o.key,"backdrop click"))},i.on("click",r.close),r.$isRendered=!0;var l=e.defer();r.$$postDigest(function(){l.resolve()}),l.promise.then(function(){var l=null;a.modalInClass&&(l=o(i,{addClass:a.modalInClass}).start(),r.$on(t.NOW_CLOSING_EVENT,function(t,e){var n=e();o(i,{removeClass:a.modalInClass}).start().then(n)})),e.when(l).then(function(){var e=t.getTop();if(e&&t.modalRendered(e.key),!n[0].activeElement||!i[0].contains(n[0].activeElement)){var o=i[0].querySelector("[autofocus]");o?o.focus():i[0].focus()}})})}}}]).directive("uibModalAnimationClass",function(){return{compile:function(t,e){e.modalAnimation&&t.addClass(e.uibModalAnimationClass)}}}).directive("uibModalTransclude",["$animate",function(t){return{link:function(e,o,n,r,i){i(e.$parent,function(e){o.empty(),t.enter(e,o)})}}}]).factory("$uibModalStack",["$animate","$animateCss","$document","$compile","$rootScope","$q","$$multiMap","$$stackedMap","$uibPosition",function(t,e,o,n,r,i,a,l,s){function d(t){var e="-";return t.replace(D,function(t,o){return(o?e:"")+t.toLowerCase()})}function u(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)}function c(){for(var t=-1,e=C.keys(),o=0;o<e.length;o++)C.get(e[o]).value.backdrop&&(t=o);return t>-1&&M>t&&(t=M),t}function p(t,e){var o=C.get(t).value,n=o.appendTo;C.remove(t),T=C.top(),T&&(M=parseInt(T.value.modalDomEl.attr("index"),10)),h(o.modalDomEl,o.modalScope,function(){var e=o.openedClass||k;S.remove(e,t);var r=S.hasKey(e);n.toggleClass(e,r),!r&&y&&y.heightOverflow&&y.scrollbarWidth&&(n.css(y.originalRight?{paddingRight:y.originalRight+"px"}:{paddingRight:""}),y=null),f(!0)},o.closedDeferred),m(),e&&e.focus?e.focus():n.focus&&n.focus()}function f(t){var e;C.length()>0&&(e=C.top().value,e.modalDomEl.toggleClass(e.windowTopClass||"",t))}function m(){if(w&&-1===c()){var t=$;h(w,$,function(){t=null}),w=void 0,$=void 0}}function h(e,o,n,r){function a(){a.done||(a.done=!0,t.leave(e).then(function(){n&&n(),e.remove(),r&&r.resolve()}),o.$destroy())}var l,s=null,d=function(){return l||(l=i.defer(),s=l.promise),function(){l.resolve()}};return o.$broadcast(E.NOW_CLOSING_EVENT,d),i.when(s).then(a)}function g(t){if(t.isDefaultPrevented())return t;var e=C.top();if(e)switch(t.which){case 27:e.value.keyboard&&(t.preventDefault(),r.$apply(function(){E.dismiss(e.key,"escape key press")}));break;case 9:var o=E.loadFocusElementList(e),n=!1;t.shiftKey?(E.isFocusInFirstItem(t,o)||E.isModalFocused(t,e))&&(n=E.focusLastFocusableElement(o)):E.isFocusInLastItem(t,o)&&(n=E.focusFirstFocusableElement(o)),n&&(t.preventDefault(),t.stopPropagation())}}function v(t,e,o){return!t.value.modalScope.$broadcast("modal.closing",e,o).defaultPrevented}function b(){Array.prototype.forEach.call(document.querySelectorAll("["+x+"]"),function(t){var e=parseInt(t.getAttribute(x),10),o=e-1;t.setAttribute(x,o),o||(t.removeAttribute(x),t.removeAttribute("aria-hidden"))})}var w,$,y,k="modal-open",C=l.createNew(),S=a.createNew(),E={NOW_CLOSING_EVENT:"modal.stack.now-closing"},M=0,T=null,x="data-bootstrap-modal-aria-hidden-count",N="a[href], area[href], input:not([disabled]):not([tabindex='-1']), button:not([disabled]):not([tabindex='-1']),select:not([disabled]):not([tabindex='-1']), textarea:not([disabled]):not([tabindex='-1']), iframe, object, embed, *[tabindex]:not([tabindex='-1']), *[contenteditable=true]",D=/[A-Z]/g;return r.$watch(c,function(t){$&&($.index=t)}),o.on("keydown",g),r.$on("$destroy",function(){o.off("keydown",g)}),E.open=function(e,i){function a(t){function e(t){var e=t.parent()?t.parent().children():[];return Array.prototype.filter.call(e,function(e){return e!==t[0]})}if(t&&"BODY"!==t[0].tagName)return e(t).forEach(function(t){var e="true"===t.getAttribute("aria-hidden"),o=parseInt(t.getAttribute(x),10);o||(o=e?1:0),t.setAttribute(x,o+1),t.setAttribute("aria-hidden","true")}),a(t.parent())}var l=o[0].activeElement,u=i.openedClass||k;f(!1),T=C.top(),C.add(e,{deferred:i.deferred,renderDeferred:i.renderDeferred,closedDeferred:i.closedDeferred,modalScope:i.scope,backdrop:i.backdrop,keyboard:i.keyboard,openedClass:i.openedClass,windowTopClass:i.windowTopClass,animation:i.animation,appendTo:i.appendTo}),S.put(u,e);var p=i.appendTo,m=c();m>=0&&!w&&($=r.$new(!0),$.modalOptions=i,$.index=m,w=angular.element('<div uib-modal-backdrop="modal-backdrop"></div>'),w.attr({"class":"modal-backdrop","ng-style":"{'z-index': 1040 + (index && 1 || 0) + index*10}","uib-modal-animation-class":"fade","modal-in-class":"in"}),i.backdropClass&&w.addClass(i.backdropClass),i.animation&&w.attr("modal-animation","true"),n(w)($),t.enter(w,p),s.isScrollable(p)&&(y=s.scrollbarPadding(p),y.heightOverflow&&y.scrollbarWidth&&p.css({paddingRight:y.right+"px"})));var h;i.component?(h=document.createElement(d(i.component.name)),h=angular.element(h),h.attr({resolve:"$resolve","modal-instance":"$uibModalInstance",close:"$close($value)",dismiss:"$dismiss($value)"})):h=i.content,M=T?parseInt(T.value.modalDomEl.attr("index"),10)+1:0;var g=angular.element('<div uib-modal-window="modal-window"></div>');g.attr({"class":"modal","template-url":i.windowTemplateUrl,"window-top-class":i.windowTopClass,role:"dialog","aria-labelledby":i.ariaLabelledBy,"aria-describedby":i.ariaDescribedBy,size:i.size,index:M,animate:"animate","ng-style":"{'z-index': 1050 + $$topModalIndex*10, display: 'block'}",tabindex:-1,"uib-modal-animation-class":"fade","modal-in-class":"in"}).append(h),i.windowClass&&g.addClass(i.windowClass),i.animation&&g.attr("modal-animation","true"),p.addClass(u),i.scope&&(i.scope.$$topModalIndex=M),t.enter(n(g)(i.scope),p),C.top().value.modalDomEl=g,C.top().value.modalOpener=l,a(g)},E.close=function(t,e){var o=C.get(t);return b(),o&&v(o,e,!0)?(o.value.modalScope.$$uibDestructionScheduled=!0,o.value.deferred.resolve(e),p(t,o.value.modalOpener),!0):!o},E.dismiss=function(t,e){var o=C.get(t);return b(),o&&v(o,e,!1)?(o.value.modalScope.$$uibDestructionScheduled=!0,o.value.deferred.reject(e),p(t,o.value.modalOpener),!0):!o},E.dismissAll=function(t){for(var e=this.getTop();e&&this.dismiss(e.key,t);)e=this.getTop()},E.getTop=function(){return C.top()},E.modalRendered=function(t){var e=C.get(t);e&&e.value.renderDeferred.resolve()},E.focusFirstFocusableElement=function(t){return t.length>0?(t[0].focus(),!0):!1},E.focusLastFocusableElement=function(t){return t.length>0?(t[t.length-1].focus(),!0):!1},E.isModalFocused=function(t,e){if(t&&e){var o=e.value.modalDomEl;if(o&&o.length)return(t.target||t.srcElement)===o[0]}return!1},E.isFocusInFirstItem=function(t,e){return e.length>0?(t.target||t.srcElement)===e[0]:!1},E.isFocusInLastItem=function(t,e){return e.length>0?(t.target||t.srcElement)===e[e.length-1]:!1},E.loadFocusElementList=function(t){if(t){var e=t.value.modalDomEl;if(e&&e.length){var o=e[0].querySelectorAll(N);return o?Array.prototype.filter.call(o,function(t){return u(t)}):o}}},E}]).provider("$uibModal",function(){var t={options:{animation:!0,backdrop:!0,keyboard:!0},$get:["$rootScope","$q","$document","$templateRequest","$controller","$uibResolve","$uibModalStack",function(e,o,n,r,i,a,l){function s(t){return t.template?o.when(t.template):r(angular.isFunction(t.templateUrl)?t.templateUrl():t.templateUrl)}var d={},u=null;return d.getPromiseChain=function(){return u},d.open=function(r){function d(){return g}var c=o.defer(),p=o.defer(),f=o.defer(),m=o.defer(),h={result:c.promise,opened:p.promise,closed:f.promise,rendered:m.promise,close:function(t){return l.close(h,t)},dismiss:function(t){return l.dismiss(h,t)}};if(r=angular.extend({},t.options,r),r.resolve=r.resolve||{},r.appendTo=r.appendTo||n.find("body").eq(0),!r.appendTo.length)throw new Error("appendTo element not found. Make sure that the element passed is in DOM.");if(!r.component&&!r.template&&!r.templateUrl)throw new Error("One of component or template or templateUrl options is required.");var g;g=r.component?o.when(a.resolve(r.resolve,{},null,null)):o.all([s(r),a.resolve(r.resolve,{},null,null)]);var v;return v=u=o.all([u]).then(d,d).then(function(t){function o(e,o,n,r){e.$scope=a,e.$scope.$resolve={},n?e.$scope.$uibModalInstance=h:e.$uibModalInstance=h;var i=o?t[1]:t;angular.forEach(i,function(t,o){r&&(e[o]=t),e.$scope.$resolve[o]=t})}var n=r.scope||e,a=n.$new();a.$close=h.close,a.$dismiss=h.dismiss,a.$on("$destroy",function(){a.$$uibDestructionScheduled||a.$dismiss("$uibUnscheduledDestruction")});var s,d,u={scope:a,deferred:c,renderDeferred:m,closedDeferred:f,animation:r.animation,backdrop:r.backdrop,keyboard:r.keyboard,backdropClass:r.backdropClass,windowTopClass:r.windowTopClass,windowClass:r.windowClass,windowTemplateUrl:r.windowTemplateUrl,ariaLabelledBy:r.ariaLabelledBy,ariaDescribedBy:r.ariaDescribedBy,size:r.size,openedClass:r.openedClass,appendTo:r.appendTo},g={},v={};r.component?(o(g,!1,!0,!1),g.name=r.component,u.component=g):r.controller&&(o(v,!0,!1,!0),d=i(r.controller,v,!0,r.controllerAs),r.controllerAs&&r.bindToController&&(s=d.instance,s.$close=a.$close,s.$dismiss=a.$dismiss,angular.extend(s,{$resolve:v.$scope.$resolve},n)),s=d(),angular.isFunction(s.$onInit)&&s.$onInit()),r.component||(u.content=t[0]),l.open(h,u),p.resolve(!0)},function(t){p.reject(t),c.reject(t)})["finally"](function(){u===v&&(u=null)}),h},d}]};return t}),angular.module("ui.bootstrap.multiMap",[]).factory("$$multiMap",function(){return{createNew:function(){var t={};return{entries:function(){return Object.keys(t).map(function(e){return{key:e,value:t[e]}})},get:function(e){return t[e]},hasKey:function(e){return!!t[e]},keys:function(){return Object.keys(t)},put:function(e,o){t[e]||(t[e]=[]),t[e].push(o)},remove:function(e,o){var n=t[e];if(n){var r=n.indexOf(o);-1!==r&&n.splice(r,1),n.length||delete t[e]}}}}}}),angular.module("ui.bootstrap.stackedMap",[]).factory("$$stackedMap",function(){return{createNew:function(){var t=[];return{add:function(e,o){t.push({key:e,value:o})},get:function(e){for(var o=0;o<t.length;o++)if(e===t[o].key)return t[o]},keys:function(){for(var e=[],o=0;o<t.length;o++)e.push(t[o].key);return e},top:function(){return t[t.length-1]},remove:function(e){for(var o=-1,n=0;n<t.length;n++)if(e===t[n].key){o=n;break}return t.splice(o,1)[0]},removeTop:function(){return t.pop()},length:function(){return t.length}}}}}),angular.module("ui.bootstrap.position",[]).factory("$uibPosition",["$document","$window",function(t,e){var o,n,r={normal:/(auto|scroll)/,hidden:/(auto|scroll|hidden)/},i={auto:/\s?auto?\s?/i,primary:/^(top|bottom|left|right)$/,secondary:/^(top|bottom|left|right|center)$/,vertical:/^(top|bottom)$/},a=/(HTML|BODY)/;return{getRawNode:function(t){return t.nodeName?t:t[0]||t},parseStyle:function(t){return t=parseFloat(t),isFinite(t)?t:0},offsetParent:function(o){function n(t){return"static"===(e.getComputedStyle(t).position||"static")}o=this.getRawNode(o);for(var r=o.offsetParent||t[0].documentElement;r&&r!==t[0].documentElement&&n(r);)r=r.offsetParent;return r||t[0].documentElement},scrollbarWidth:function(r){if(r){if(angular.isUndefined(n)){var i=t.find("body");i.addClass("uib-position-body-scrollbar-measure"),n=e.innerWidth-i[0].clientWidth,n=isFinite(n)?n:0,i.removeClass("uib-position-body-scrollbar-measure")}return n}if(angular.isUndefined(o)){var a=angular.element('<div class="uib-position-scrollbar-measure"></div>');t.find("body").append(a),o=a[0].offsetWidth-a[0].clientWidth,o=isFinite(o)?o:0,a.remove()}return o},scrollbarPadding:function(t){t=this.getRawNode(t);var o=e.getComputedStyle(t),n=this.parseStyle(o.paddingRight),r=this.parseStyle(o.paddingBottom),i=this.scrollParent(t,!1,!0),l=this.scrollbarWidth(a.test(i.tagName));return{scrollbarWidth:l,widthOverflow:i.scrollWidth>i.clientWidth,right:n+l,originalRight:n,heightOverflow:i.scrollHeight>i.clientHeight,bottom:r+l,originalBottom:r}},isScrollable:function(t,o){t=this.getRawNode(t);var n=o?r.hidden:r.normal,i=e.getComputedStyle(t);return n.test(i.overflow+i.overflowY+i.overflowX)},scrollParent:function(o,n,i){o=this.getRawNode(o);var a=n?r.hidden:r.normal,l=t[0].documentElement,s=e.getComputedStyle(o);if(i&&a.test(s.overflow+s.overflowY+s.overflowX))return o;var d="absolute"===s.position,u=o.parentElement||l;if(u===l||"fixed"===s.position)return l;for(;u.parentElement&&u!==l;){var c=e.getComputedStyle(u);if(d&&"static"!==c.position&&(d=!1),!d&&a.test(c.overflow+c.overflowY+c.overflowX))break;u=u.parentElement}return u},position:function(o,n){o=this.getRawNode(o);var r=this.offset(o);if(n){var i=e.getComputedStyle(o);r.top-=this.parseStyle(i.marginTop),r.left-=this.parseStyle(i.marginLeft)}var a=this.offsetParent(o),l={top:0,left:0};return a!==t[0].documentElement&&(l=this.offset(a),l.top+=a.clientTop-a.scrollTop,l.left+=a.clientLeft-a.scrollLeft),{width:Math.round(angular.isNumber(r.width)?r.width:o.offsetWidth),height:Math.round(angular.isNumber(r.height)?r.height:o.offsetHeight),top:Math.round(r.top-l.top),left:Math.round(r.left-l.left)}},offset:function(o){o=this.getRawNode(o);var n=o.getBoundingClientRect();return{width:Math.round(angular.isNumber(n.width)?n.width:o.offsetWidth),height:Math.round(angular.isNumber(n.height)?n.height:o.offsetHeight),top:Math.round(n.top+(e.pageYOffset||t[0].documentElement.scrollTop)),left:Math.round(n.left+(e.pageXOffset||t[0].documentElement.scrollLeft))}},viewportOffset:function(o,n,r){o=this.getRawNode(o),r=r!==!1?!0:!1;var i=o.getBoundingClientRect(),a={top:0,left:0,bottom:0,right:0},l=n?t[0].documentElement:this.scrollParent(o),s=l.getBoundingClientRect();if(a.top=s.top+l.clientTop,a.left=s.left+l.clientLeft,l===t[0].documentElement&&(a.top+=e.pageYOffset,a.left+=e.pageXOffset),a.bottom=a.top+l.clientHeight,a.right=a.left+l.clientWidth,r){var d=e.getComputedStyle(l);a.top+=this.parseStyle(d.paddingTop),a.bottom-=this.parseStyle(d.paddingBottom),a.left+=this.parseStyle(d.paddingLeft),a.right-=this.parseStyle(d.paddingRight)}return{top:Math.round(i.top-a.top),bottom:Math.round(a.bottom-i.bottom),left:Math.round(i.left-a.left),right:Math.round(a.right-i.right)}},parsePlacement:function(t){var e=i.auto.test(t);return e&&(t=t.replace(i.auto,"")),t=t.split("-"),t[0]=t[0]||"top",i.primary.test(t[0])||(t[0]="top"),t[1]=t[1]||"center",i.secondary.test(t[1])||(t[1]="center"),t[2]=e?!0:!1,t},positionElements:function(t,o,n,r){t=this.getRawNode(t),o=this.getRawNode(o);var a=angular.isDefined(o.offsetWidth)?o.offsetWidth:o.prop("offsetWidth"),l=angular.isDefined(o.offsetHeight)?o.offsetHeight:o.prop("offsetHeight");n=this.parsePlacement(n);var s=r?this.offset(t):this.position(t),d={top:0,left:0,placement:""};if(n[2]){var u=this.viewportOffset(t,r),c=e.getComputedStyle(o),p={width:a+Math.round(Math.abs(this.parseStyle(c.marginLeft)+this.parseStyle(c.marginRight))),height:l+Math.round(Math.abs(this.parseStyle(c.marginTop)+this.parseStyle(c.marginBottom)))};if(n[0]="top"===n[0]&&p.height>u.top&&p.height<=u.bottom?"bottom":"bottom"===n[0]&&p.height>u.bottom&&p.height<=u.top?"top":"left"===n[0]&&p.width>u.left&&p.width<=u.right?"right":"right"===n[0]&&p.width>u.right&&p.width<=u.left?"left":n[0],n[1]="top"===n[1]&&p.height-s.height>u.bottom&&p.height-s.height<=u.top?"bottom":"bottom"===n[1]&&p.height-s.height>u.top&&p.height-s.height<=u.bottom?"top":"left"===n[1]&&p.width-s.width>u.right&&p.width-s.width<=u.left?"right":"right"===n[1]&&p.width-s.width>u.left&&p.width-s.width<=u.right?"left":n[1],"center"===n[1])if(i.vertical.test(n[0])){var f=s.width/2-a/2;u.left+f<0&&p.width-s.width<=u.right?n[1]="left":u.right+f<0&&p.width-s.width<=u.left&&(n[1]="right")}else{var m=s.height/2-p.height/2;u.top+m<0&&p.height-s.height<=u.bottom?n[1]="top":u.bottom+m<0&&p.height-s.height<=u.top&&(n[1]="bottom")}}switch(n[0]){case"top":d.top=s.top-l;break;case"bottom":d.top=s.top+s.height;break;case"left":d.left=s.left-a;break;case"right":d.left=s.left+s.width}switch(n[1]){case"top":d.top=s.top;break;case"bottom":d.top=s.top+s.height-l;break;case"left":d.left=s.left;break;case"right":d.left=s.left+s.width-a;break;case"center":i.vertical.test(n[0])?d.left=s.left+s.width/2-a/2:d.top=s.top+s.height/2-l/2}return d.top=Math.round(d.top),d.left=Math.round(d.left),d.placement="center"===n[1]?n[0]:n[0]+"-"+n[1],d},adjustTop:function(t,e,o,n){return-1!==t.indexOf("top")&&o!==n?{top:e.top-n+"px"}:void 0},positionArrow:function(t,o){t=this.getRawNode(t);var n=t.querySelector(".tooltip-inner, .popover-inner");if(n){var r=angular.element(n).hasClass("tooltip-inner"),a=t.querySelector(r?".tooltip-arrow":".arrow");if(a){var l={top:"",bottom:"",left:"",right:""};if(o=this.parsePlacement(o),"center"===o[1])return void angular.element(a).css(l);var s="border-"+o[0]+"-width",d=e.getComputedStyle(a)[s],u="border-";u+=i.vertical.test(o[0])?o[0]+"-"+o[1]:o[1]+"-"+o[0],u+="-radius";var c=e.getComputedStyle(r?n:t)[u];switch(o[0]){case"top":l.bottom=r?"0":"-"+d;break;case"bottom":l.top=r?"0":"-"+d;break;case"left":l.right=r?"0":"-"+d;break;case"right":l.left=r?"0":"-"+d}l[o[1]]=c,angular.element(a).css(l)}}}}}]),angular.module("uib/template/modal/window.html",[]).run(["$templateCache",function(t){t.put("uib/template/modal/window.html","<div class=\"modal-dialog {{size ? 'modal-' + size : ''}}\"><div class=\"modal-content\" uib-modal-transclude></div></div>\n")}]),angular.module("ui.bootstrap.position").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibPositionCss&&angular.element(document).find("head").prepend('<style type="text/css">.uib-position-measure{display:block !important;visibility:hidden !important;position:absolute !important;top:-9999px !important;left:-9999px !important;}.uib-position-scrollbar-measure{position:absolute !important;top:-9999px !important;width:50px !important;height:50px !important;overflow:scroll !important;}.uib-position-body-scrollbar-measure{overflow:scroll !important;}</style>'),angular.$$uibPositionCss=!0});;
var myApp = angular.module('sbApp', ['ngFileUpload', 'angular-bacon', 'ui.bootstrap']);
    /*
    .config(function ($locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    }).hashPrefix('!');
});*/;
myApp.controller('SearchController', ['$scope', '$http', '$timeout', '$attrs', '$q', function ($scope, $http, $timeout, $attrs, $q) {

    var SearchTypeOption = 
    {
        Stolen_Start : 0,
        Stolen_Frame_Asset_No : 1,
        Stolen_Property_Vault_ID : 2,
        Stolen_Make_Plus : 3,
        Stolen_PV_No : 4,
        Stolen_Make_Plus_Reward : 14,
        Owner_Wanted_Start : 5,
        Owner_Wanted_Make_Plus : 6,
        Owner_Wanted_PV_No : 7,
        For_Sale_Start : 8,
        For_Sale_Frame_Asset_No : 9,
        For_Sale_Vault_ID : 10,
        For_Sale_Make_Plus : 11,
        For_Sale_PV_No: 12,
        SuperSearch_Start: 13
    }

    var SuperTypeOption =
    {
        Stolen: 0,
        Owner_Wanted: 1,
        For_Sale: 2
    }

    $scope.searchTypeOption = SearchTypeOption;
    $scope.superTypeOption = SuperTypeOption;
    $scope.superTypeOptions = Object.keys(SuperTypeOption).map(function (x) { return { name: x.replace("_", " "), key: x } });
    
    $scope.searchModel = {
        searchType : null,
        showInstructions : true,
        lookup: null,
        showLookup: false,
        lookupLocked: false,
        keywords: null,
        makePluses: [],
        keywordPlaceholder: null,
        location: null,
        locationLocked: false,
        colour: "#fddf08",
        assetNoInstruct: $attrs.assetNoInstruct
    }

    $scope.init = function () {
        if ($attrs.searchType) {
            var st = SearchTypeOption[$attrs.searchType];
            if (st >= SearchTypeOption.Stolen_Start && st <= SearchTypeOption.Stolen_PV_No) {
                $scope.searchModel.superType = SuperTypeOption.Stolen;
            }
            else if (st >= SearchTypeOption.Owner_Wanted_Start && st <= SearchTypeOption.Owner_Wanted_PV_No) {
                $scope.searchModel.superType = SuperTypeOption.Owner_Wanted;
            }
            else if (st >= SearchTypeOption.For_Sale_Start && st <= SearchTypeOption.For_Sale_PV_No) {
                $scope.searchModel.superType = SuperTypeOption.For_Sale;
            }
           
            $scope.setSearchType(SearchTypeOption[$attrs.searchType]);
            if ($attrs.makeid) {
                $scope.selectMakePlus({ MakeID: $attrs.makeid, PropertyTypeID: $attrs.propertytypeid, MakeName: $attrs.makename, TypeName: $attrs.typename },false);
            }
            if ($attrs.propertymodel) {
                $scope.searchModel.propertyModel = $attrs.propertymodel;
            }
            if ($attrs.keywords)
                $scope.searchModel.keywords = $attrs.keywords;

            $scope.searchModel.displayInPage = $attrs.displayInPage == "True";
            $scope.searchModel.isMainDomain = $attrs.domainVault == "Police" || $attrs.domainVault == "Property";
            $scope.searchModel.vaultAgnostic = $attrs.vault == "Police" || $attrs.vault == "Property" && !($attrs.vault == "Property" && $scope.searchModel.searchType == SearchTypeOption.Stolen_Property_Vault_ID);
            $scope.searchModel.startedFull = true;
            $scope.searchModel.isPolice = $attrs.domainVault == "Police";
            $scope.searchModel.isFull = $scope.searchModel.searchType == SearchTypeOption.SuperSearch_Start;
            $scope.searchModel.pathPrefix = $scope.searchModel.isPolice ? "/Police" : "";
            
            $http({
                method: 'GET',
                url: '/search/vaultsearchconfigs/',
            }).
                then(function (response) {
                    $scope.searchModel.vaults = response.data;
                    if (!$scope.searchModel.vaultAgnostic) {
                        $scope.skipFirstSearch = true;
                        $scope.searchModel.vault = $scope.searchModel.vaults.filter(function (x) { return x.VaultTag == ($attrs.vault == "Property" ? "IdSearch" : $attrs.vault) })[0];
                    }
                }, function (response) {
                    console.log("api cancel or failure - " + "/search/vaultsearchconfigs/");
                });
            
        }

        $scope.toolActions();
    }

    $scope.getVaults = function () {
        if (!$scope.searchModel.vaults)
            return [];
        switch ($scope.searchModel.superType) {
            case SuperTypeOption.Stolen:
                return $scope.searchModel.vaults.filter(function (x) { return x.HasStolen })
                break;
            case SuperTypeOption.Owner_Wanted:
                return $scope.searchModel.vaults.filter(function (x) { return x.HasRecovered })
                break;
            case SuperTypeOption.For_Sale:
                return $scope.searchModel.vaults.filter(function (x) { return x.HasForSale })
                break;
            default:
                return $scope.searchModel.vaults;
                break;
        }
    }

    $scope.getCurrentVaultImgSrc = function () {
        return !$scope.searchModel.vault ? "/Content/images/Vaults/Property/icon.svg" : $scope.searchModel.vault.VaultIcon.replace("-white","");
    }

    $scope.getCurrentVaultName = function () {
        return !$scope.searchModel.vault ? "Select VAULT First" : ''; // $scope.searchModel.vault.VaultName;
    }

    $scope.$watch('searchModel.vault', function (newValue, oldValue) {
        if ($scope.skipFirstSearch) {
            $scope.skipFirstSearch = false;
            return;
        }
        if (!newValue && !oldValue)
            return;
        var isChange = !$scope.searchModel.displayInPage && newValue != oldValue;
        // $scope.searchModel.vault = vault;
        $('.optionspin-vault .collapse').removeClass('show');
        if ($scope.searchModel.vault && $scope.searchModel.vault.VaultTag === "IdSearch") {
            $scope.setSearchType(SearchTypeOption.Stolen_Property_Vault_ID);
            return;
        }
        // reset if new vault? // $scope.setSuperType(null);
        if ($scope.searchModel.displayInPage || isChange)
            $scope.runSearch(!$scope.searchModel.displayInPage && vault.VaultTag != $attrs.domainVault);
    });

    $scope.getSuperTypes = function () {
        return $scope.superTypeOptions;
    }

    /*
    $scope.$watch('searchModel.superType', function (newValue, oldValue) {
        if (newValue)
            $scope.setSuperType(newValue.key);
    });
    */

    $scope.setSuperType = function (key) {
        var isChange = !$scope.searchModel.displayInPage;
        if (key == null) {
            $scope.setSearchType(SearchTypeOption.SuperSearch_Start);
            $scope.searchModel.isFull = true;
            return;
        }

        $scope.searchModel.superType = SuperTypeOption[key];
        switch ($scope.searchModel.superType) {
            case SuperTypeOption.Stolen:
                $scope.searchType = SearchTypeOption.Stolen_Start;
                break;
            case SuperTypeOption.Owner_Wanted:
                $scope.searchType = SearchTypeOption.Owner_Wanted_Start;
                break;
            case SuperTypeOption.For_Sale:
                $scope.searchType = SearchTypeOption.For_Sale_Start;
                break;
        }
        $scope.searchModel.isFull = false;
        $scope.setSearchType($scope.searchType, true);
        if ($scope.searchModel.displayInPage || isChange)
            $scope.runSearch();

        /*
        switch ($scope.searchModel.superType) {
            case SuperTypeOption.Stolen:
                $scope.searchType = SearchTypeOption.Stolen_Make_Plus;
                break;
            case SuperTypeOption.Owner_Wanted:
                $scope.searchType = SearchTypeOption.Owner_Wanted_Make_Plus;
                break;
            case SuperTypeOption.For_Sale:
                $scope.searchType = SearchTypeOption.For_Sale_Make_Plus;
                break;
        }
        */
        $scope.setSearchType($scope.searchType, true);
    }


    $scope.redirectToMainDomain = function () {
        window.location = $attrs.mainDomain;
    }

    $scope.resetToFull = function (vault) {
        //$scope.searchModel.vault = null;
        $scope.searchModel.isFull = true;
        $scope.searchModel.showLookup = false;
        $scope.searchModel.searchType = null;
        $scope.setSearchType(null);
    }   

    $scope.hasIdent = function () {
        if (!$scope.searchModel.vault)
            return true;
        return $scope.searchModel.vault.HasIdentPack;
    }

    $scope.hasRewards = function () {
        if (!$scope.searchModel.vault)
            return true;
        return $scope.searchModel.vault.HasRewards;
    }

    $scope.getCopy = function (tag,copy) {
        if (!$scope.searchModel.vault)
            return copy;
        return $scope.searchModel.vault.Copy[tag];
    }

    $scope.setSearchType = function(searchType, preventClose) {
        $scope.searchModel.searchType = searchType;
        $scope.searchModel.showInstructions = false;
        $scope.searchModel.showLookup = false;
        $scope.searchModel.showKeywords = false;
        $scope.searchModel.noArea = true;
        var runAfterChange = $scope.searchModel.searchType == SearchTypeOption.Stolen_Make_Plus_Reward;

        switch ($scope.searchModel.searchType)
        {
            case null:
            case SearchTypeOption.SuperSearch_Start:
                $scope.searchModel.showInstructions = true;
                $scope.colour = "#fddf08"
                break;
            case SearchTypeOption.Stolen_Start:
            case SearchTypeOption.Owner_Wanted_Start:
            case SearchTypeOption.For_Sale_Start:
                $scope.searchModel.showInstructions = true;
                break;
            case SearchTypeOption.Stolen_Frame_Asset_No:
            case SearchTypeOption.For_Sale_Frame_Asset_No:
                $scope.searchModel.showKeywords = true;
                $scope.searchModel.noArea = true;
                $scope.searchModel.keywordPlaceholder = $scope.getCopy("SuperSearch_AssetNo_Instructions", $scope.searchModel.assetNoInstruct);
                break;
            case SearchTypeOption.Stolen_Property_Vault_ID:
            case SearchTypeOption.For_Sale_Vault_ID:
                $scope.searchModel.showKeywords = true;
                $scope.searchModel.noArea = true;
                $scope.searchModel.keywordPlaceholder = "Enter ID";
                break;
            case SearchTypeOption.Stolen_Make_Plus:
            case SearchTypeOption.Stolen_Make_Plus_Reward:
            case SearchTypeOption.Owner_Wanted_Make_Plus:
            case SearchTypeOption.For_Sale_Make_Plus:
                $scope.searchModel.showLookup = true;
                $scope.searchModel.showKeywords = true;
                $scope.searchModel.keywordPlaceholder = "Optional Key Word";
                break;
            case SearchTypeOption.Stolen_PV_No:
            case SearchTypeOption.Owner_Wanted_PV_No:
            case SearchTypeOption.For_Sale_PV_No:
                $scope.searchModel.showKeywords = true;
                $scope.searchModel.noArea = true;
                $scope.searchModel.keywordPlaceholder = "Enter PropertyVAULT Number (PV No.)";
                break;
        }

        switch ($scope.searchModel.searchType) {
            case null:
                $scope.searchModel.colour = "#ffd000"
                break;
            case SearchTypeOption.Stolen_Start:
            case SearchTypeOption.Stolen_Frame_Asset_No:
            case SearchTypeOption.Stolen_Property_Vault_ID:
            case SearchTypeOption.Stolen_Make_Plus:
            case SearchTypeOption.Stolen_Make_Plus_Reward:
            case SearchTypeOption.Stolen_PV_No:
                $scope.searchModel.colour = "#ed1111"
                break;
            case SearchTypeOption.For_Sale_Start:
            case SearchTypeOption.For_Sale_Frame_Asset_No:
            case SearchTypeOption.For_Sale_Vault_ID:
            case SearchTypeOption.For_Sale_Make_Plus:
            case SearchTypeOption.For_Sale_PV_No:
                $scope.searchModel.colour = "#8fc400"
                break;
            case SearchTypeOption.Owner_Wanted_Start:
            case SearchTypeOption.Owner_Wanted_Make_Plus:
            case SearchTypeOption.Owner_Wanted_PV_No:
                $scope.searchModel.colour = "#244d7b"
                break;
        }

        $scope.colour = "#fddf08"
        $scope.searchModel.colour = "#ffd000"
        if (!preventClose) {
            $('.optionspin-vault .collapse').removeClass('show');
            $('.optionspin-searchtypes .collapse').removeClass('show');
        }

        if (runAfterChange)
            $scope.runSearch();
    }

    //Start MakeLookup
    var lookupInput = $scope.$watchAsProperty('searchModel.lookup');

    lookupInput.filter(function (x) { return !x || x.length <= 1; }).throttle(1000).onValue(function (x) {
        $scope.makePluses = [];
        if ($scope.canceller)
            $scope.canceller.resolve();
    });

    lookupInput.filter(function (x) { return x && x.length > 1; }).throttle(1000).onValue(function (x) {
        if ($scope.searchModel.lookupLocked)
            return;
        if ($scope.canceller)
            $scope.canceller.resolve();
        $scope.canceller = $q.defer();

        $http({
                method: 'POST',
                url: '/search/makeplussearch/',
                timeout: $scope.canceller.promise,
            data: { search: x, superTypeOption: $scope.searchModel.superType, vaultType: $scope.searchModel.vault ? $scope.searchModel.vault.Vault : null }
            }).
            then(function (response) {
                $scope.searchModel.makePluses = response.data;
            }, function (response) {
                console.log("api cancel or failure - " + "/search/makeplussearch/");
            });
    });

    $scope.selectMakePlus = function (makePlus,runSearch) {
        $scope.searchModel.lookupLocked = true;
        $scope.searchModel.selectedMakePlus = makePlus;
        $scope.searchModel.makePluses = [];
        $scope.searchModel.lookup = makePlus.MakeName + ' - ' + makePlus.TypeName;
        console.log($scope.searchModel.selectedMakePlus);
        if (runSearch)
            $scope.runSearch();
    }

    $scope.clearLookup = function () {
        $scope.searchModel.selectedMakePlus = null;
        $scope.searchModel.lookup = "";
        $scope.searchModel.lookupLocked = false;
        $scope.runSearch();
    }

    //Start ModelLookup
    var propertyModelInput = $scope.$watchAsProperty('searchModel.propertyModel');

    propertyModelInput.filter(function (x) { return !x || x.length <= 1; }).throttle(1000).onValue(function (x) {
        $scope.propertyModels = [];
        if ($scope.searchModel.propertyModelLocked && x == "") {
            $scope.searchModel.propertyModelLocked = null;
            $scope.triggerPropertyModelLookup(null);
            $scope.runSearch();
            return;
        }
        if ($scope.canceller)
            $scope.canceller.resolve();
    });

    propertyModelInput.filter(function (x) { return x && x.length > 1; }).throttle(1000).onValue(function (x) {
        $scope.triggerPropertyModelLookup(x);
    });

    $scope.triggerPropertyModelLookup = function (x) {
        
        if ($scope.searchModel.propertyModelLocked) {
            if ($scope.searchModel.propertyModelLocked == x)
                return;
            else
                $scope.searchModel.propertyModelLocked = null;
        }
            
        if ($scope.canceller)
            $scope.canceller.resolve();
        $scope.canceller = $q.defer();

        $http({
            method: 'POST',
            url: '/search/modelsearch/',
            timeout: $scope.canceller.promise,
            data: {
                search: x, superTypeOption: $scope.searchModel.superType, vaultType: $scope.searchModel.vault ? $scope.searchModel.vault.Vault : null,
                MakeID: $scope.searchModel.selectedMakePlus ? $scope.searchModel.selectedMakePlus.MakeID : null
            }
        }).
            then(function (response) {
                $scope.searchModel.propertyModels = response.data;
            }, function (response) {
                console.log("api cancel or failure - " + "/search/modelsearch/");
            });

    }

    $scope.propertyModelFocused = function () {
        if ($scope.searchModel.selectedMakePlus && !$scope.searchModel.propertyModels && !$scope.searchModel.propertyModel)
            $scope.triggerPropertyModelLookup(null);
    }

    $scope.selectPropertyModel = function (propertyModel) {
        $scope.searchModel.propertyModelLocked = propertyModel;
        $scope.searchModel.propertyModel = propertyModel;
        $scope.searchModel.propertyModels = [];
        console.log($scope.searchModel.propertyModel);
        $scope.runSearch();
    }

    //Start LocationLookup
    var locationInput = $scope.$watchAsProperty('searchModel.location');

    locationInput.filter(function (x) { return !x || x.length <= 1; }).throttle(250).onValue(function (x) {
        $scope.locations = [];
        if ($scope.canceller)
            $scope.canceller.resolve();
    });

    locationInput.filter(function (x) { return x && x.length > 1; }).throttle(250).onValue(function (x) {
        if ($scope.searchModel.locationLocked)
            return;
        if ($scope.canceller)
            $scope.canceller.resolve();
        $scope.canceller = $q.defer();

        $http({
            method: 'POST',
            url: '/search/locationsearch/',
            timeout: $scope.canceller.promise,
            data: { search: x }
        }).
            then(function (response) {
                $scope.searchModel.locations = response.data;
            }, function (response) {
                console.log("api cancel or failure - " + "/search/locationsearch/");
            });
    });

    $scope.selectLocation = function (location) {
        $scope.searchModel.locationLocked = true;
        $scope.searchModel.selectedLocation = location;
        $scope.searchModel.locations = [];
        $scope.searchModel.location = location.state + (location.postcode ? ( ' - ' + location.suburb + ' - ' + location.postcode ) : "" );
        console.log($scope.searchModel.selectedMakePlus);
        $scope.runSearch();
    }

    $scope.clearLocation = function () {
        $scope.searchModel.selectedLocation = null;
        $scope.searchModel.location = "";
        $scope.searchModel.locationLocked = false;
        $scope.runSearch();
    }

    $scope.showSupertype = function (superType) {
        if ($scope.searchModel.isFull) return false;
        return $scope.searchModel.superType == superType;
    }

    $scope.isSearchType = function (searchType) {
        return $scope.searchModel.searchType == searchType;
    }

    $scope.isSearchSuperTypeByKey = function (searchTypeKey) {
        return $scope.searchModel.superType == SuperTypeOption[searchTypeKey];
    }

    $scope.runSearch = function (forceRedirect,append) {
        var sendModel = {
            SearchType: $scope.searchModel.searchType,
            Keywords: $scope.searchModel.keywords
        }

        if ($scope.searchModel.selectedLocation) {
            sendModel.Postcode = $scope.searchModel.selectedLocation.postcode;
            sendModel.Suburb = $scope.searchModel.selectedLocation.suburb;

            if ($scope.searchModel.selectedLocation.ID > 0)
                sendModel.State = $scope.searchModel.selectedLocation.state;
            else
                sendModel.State = $scope.searchModel.selectedLocation.state.split(" ")[0];

            if (sendModel.Postcode == null) sendModel.Postcode = "";
            if (sendModel.Suburb == null) sendModel.Suburb = "";
            if (sendModel.State == null) sendModel.State = "";
        }

        if ($scope.searchModel.selectedMakePlus) {
            sendModel.MakeID = $scope.searchModel.selectedMakePlus.MakeID;
            sendModel.PropertyTypeID = $scope.searchModel.selectedMakePlus.PropertyTypeID;
            if($scope.searchModel.propertyModel)
                sendModel.PropertyModel = $scope.searchModel.propertyModel;
        }

        if ($scope.searchModel.vault) {
            sendModel.VaultType = $scope.searchModel.vault.Vault;
        }

        if (!append)
            $scope.pageNo = null;

        var param = "?" + $scope.serialize(sendModel);
        var path = "/search/";
        var pathParam = param;

        /*
        if ($scope.searchModel.vault && $scope.searchModel.vault.VaultTag !== "IdSearch" &&(
            sendModel.SearchType == SearchTypeOption.Stolen_Start ||
            sendModel.SearchType == SearchTypeOption.Owner_Wanted_Start ||
            sendModel.SearchType == SearchTypeOption.For_Sale_Start ||
            sendModel.SearchType == SearchTypeOption.SuperSearch_Start
            ))
        {
            pathParam = "";
            path += $scope.searchModel.vault.VaultPath + "/";
            if (false && sendModel.SearchType !== SearchTypeOption.SuperSearch_Start) {
                path += sendModel.SearchType == SearchTypeOption.Stolen_Start ? "stolen-" + $scope.searchModel.vault.VaultNamePlural.toLowerCase() + "/" :
                    sendModel.SearchType == SearchTypeOption.Owner_Wanted_Start ? "found-" + $scope.searchModel.vault.VaultNamePlural.toLowerCase() + "/" :
                        "for-sale-" + $scope.searchModel.vault.VaultNamePlural.toLowerCase() + "/";
            }
        }
        */

        if (append) 
            $(".load-more").replaceWith("<div style='text-align:center' class='search-loader'><img src='/content/images/design2/ajax-loader.gif'/></div>");
        else
            $('.found-list-box').prepend("<div style='text-align:center'><img src='/content/images/design2/ajax-loader.gif'/></div>")
        if ($scope.searchModel.displayInPage && !forceRedirect) {
            if (append) {
                $scope.pageNo = $scope.pageNo ? $scope.pageNo + 1 : 2;
                param += "&pageNo=" + $scope.pageNo;
            }
            $http({
                    method: 'POST',
                    url: '/search/results/' + param,
                }).
                then(function (result) {
                    if (result.data.indexOf("REDIRECT::") == 0) {
                        window.location = result.data.substring(10);
                        return;
                    }
                    if (append) {
                        $('.search-loader').remove();
                        $('.found-list-box').find(".load-more").remove();
                        var newData = $(result.data);
                        newData.find("h2").remove();
                        newData.find("orderby").remove();
                        $('.found-list-box').append(newData);
                        $(".found-list-box .lko").each(bootStrapAds);
                        $scope.toolActions();
                    }
                    else {
                        $('.found-list-box').html(result.data);
                        var resultTitle = $('.found-list-box').find("h2");
                        if (resultTitle.length) {
                            resultTitle.remove();
                            $(".search-description").html(resultTitle.html())
                        }
                        $(".found-list-box .lko").each(bootStrapAds);
                        document.title = "Property Vault Search Results";
                        window.history.pushState({ "html": result.data, "pageTitle": document.title }, "", path + pathParam);
                        $scope.toolActions();
                        // window.pvRunPagination();
                    }
                }, function (response) {
                    console.log("api cancel or failure - " + "/search/vaultsearchconfigs/");
                });
        }
        else {
            window.location = path + pathParam + "#search";
        }
    }

    $scope.toolActions = function () {
        $(".found-list-box .load-more button").click(function () {
            $scope.runSearch($(this).hasClass("redirect"), true);
            // $scope.apply();
        });
        $(".orderby button.action").click(function () {
            $scope.selectLocation({ state: $(this).data("val") });
        });
    }

    $scope.serialize = function (obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    $scope.init();

    if ($scope.searchModel.displayInPage) {
        window.onpopstate = function (e) {
            if (e.state) {
                $('.found-list-box').html(e.state.html);
                document.title = e.state.pageTitle;
            }
        };
    }

    $(document).click(function (event) {
        $(".searchoptions.show").each(function () {
            if (!$(this).has(event.target).length && $(this).attr("data-button")) {
                $(this).removeClass('show');
            }
        })
    });

}]);

$(function () {
    var resize = function () {
        var fbx = $("#filter-box");
        if ($(window).width() < 991) {
            if (fbx.hasClass("filter-wrap")) {
                fbx.removeClass("filter-wrap");
                fbx.addClass("filter-mob");
                //$('#filter-box').removeClass('is-open').hide(200);
            }
            return true;
        }
        else {
            if (fbx.hasClass("filter-mob")) {
                fbx.removeClass("filter-mob");
                fbx.addClass("filter-wrap");
                //$('#filter-box').addClass('is-open').show(200);
            }
            return false;
        }
    }

    $(document).on('click', '.property-search .btn-mob a', function (e) {
        e.preventDefault();
        let item = $('#filter-box');
        if (item.hasClass('is-open')) {
            item.removeClass('is-open').hide(200);
            $(this).html("FILTER");
        } else {
            item.addClass('is-open').show(200);
            $(this).html("HIDE FILTER");
        }
    });


    $(window).resize(function () {
        resize();
    });
    if (resize()) {
        $('#filter-box').addClass('is-open').show(200);
    }
    else {
        $('#filter-box').addClass('is-open').show(200);
    }


    
});;
myApp.controller('SmartSearchController', ['$scope', '$http', '$timeout', '$attrs', '$q', function ($scope, $http, $timeout, $attrs, $q) {
    $scope.searchMode = "smart";
    $scope.vaultSuggestions = [];
    $scope.vaultTypes = [];
    $scope.vaultStates = [];
    $scope.locations = [];
    $scope.superTypeSelecting = false;

    if (window.filters != undefined) {
        filters.listeners.push({
            filtersChanged: function () {
                $scope.vaultTypes = filters.vaultTypes || [];
                $scope.vaultStates = filters.vaultStates || [];
                $scope.locations = filters.locations || [];
            }
        });
        filters.notify();
    }

    if (window.smartSearchSuperTypes != undefined) {
        $scope.superTypes = window.smartSearchSuperTypes;
        $scope.superTypes.unshift({ SuperTypeName : "All Property", SuperType:null});
    }

    $scope.showFilter = false;

    $scope.searchModel = {
        input: "",
        suggestions: [],
        tags: []
    }

    $scope.init = function () {
        $scope.searchModel.displayInPage = $attrs.displayInPage == "True";
        $scope.accessType = $attrs.accesstype;
        $scope.isAdmin = $attrs.accesstype == "Admin";

        if ($attrs.vault && $scope.searchModel.vaults) {
            $scope.searchModel.VaultType = $attrs.vault;
            $scope.searchModel.vault = $scope.vaults.find(x => x.Vault == $attrs.vault);
        }
        else if ($attrs.vault && $attrs.vault != "0") {
            $scope.searchModel.VaultType = $attrs.vault
        }

        if ($attrs.supertype !== "") {
            $scope.chooseSuperType($scope.superTypes.find(x => x.SuperType == $attrs.supertype), false);
        }
        else {
            $scope.SuperType = null;
            $scope.superType = null;
        }

        if ($attrs.searchType == "Home_List")
            $scope.isHome = true;

        $scope.toolSetup();
        $scope.toolActions();

        if (!$scope.searchModel.displayInPage && !$scope.isAdmin)
            return;
        
        $http({
            method: 'POST',
            url: '/search/smartsearchinit/' + window.location.search,
        }).
            then(function (result) {
                /*
                if ($attrs.searchType == "ID_Serial") {
                    $scope.searchMode =  "assetid";
                    $scope.searchModel.input = $attrs.keywords;
                    $scope.searchModel.tags = result.data.filter(x => x.SuggestionProperty == "VaultType");
                }
                else {
                    if (result.data.some(x => x.SuggestionProperty == "Keywords")) {
                        $scope.searchModel.input = result.data.pop().SuggestionValue;
                    }
                    $scope.searchModel.tags = result.data;
                }
                */
                $scope.searchModel.tags = $scope.searchModel.tags.concat(result.data);
            });

        $scope.isMob = $(window).width() < 767;

        $(window).resize(function () {
            $scope.isMob = $(window).width() < 767;
            $scope.$apply();
        });
    }

    $scope.hasSuperTypesDropdown = function () {
        return $scope.accessType != "MyVault" && $scope.searchModel.SuperType == null;
    }

    $scope.showSuperTypes = function () {
        $scope.superTypeSelecting = true;
        if ($scope.searchModel.suggestions.length>0)
            $scope.searchModel.suggestions = [];
    }

    $scope.isGroupVault = function () {
        return $scope.searchModel.vault && $scope.searchModel.vault.Vault == 1000;
    }

    $scope.isMyVault = function () {
        return $scope.accessType == "MyVault";
    }

    $scope.chooseSuperType = function (superType,runSearch) {
        $scope.searchModel.superType = superType.SuperType != null ? superType : null;
        $scope.superTypeSelecting = false;
        $scope.searchModel.SuperType = superType.SuperType;
        $scope.searchModel.tags = [{
            Name: superType.SuperTypeName,
            SuggestionType : "Asset Type",
            SuggestionTypeName : "Asset types",
            SuggestionProperty : "SuperType",
            SuggestionIcon: superType.SuperTypeIcon.replace("-white", ""),
            SuperType: superType.SuperType
        }];
        if(runSearch)
            $scope.runSearch();
    }

    $scope.getCurrentSuperTypeImgSrc = function () {
        return !$scope.searchModel.superType ? "/Content/images/SuperTypes/Property/icon.svg" : $scope.searchModel.superType.SuperTypeIcon;
    }

    $scope.onInputFocus = function () {
        console.log('focus');
        if ($scope.superTypeSelecting)
            $scope.superTypeSelecting = false;
        if ($scope.searchMode != null || $scope.searchModel.suggestions.length>0)
            return;

        var sg1 = {
            Name: "Search Make +",
            SearchType: "Smart_Search",
            SuggestionType: "SearchType",
            SuggestionTypeValue: "Smart_Search",
            SuggestionTypeName: "Search mode",
        };

        var sg2 = {
            Name: "Search Asset ID +",
            SearchType: "ID_Serial",
            SuggestionType: "SearchType",
            SuggestionTypeValue: "ID_Serial",
            SuggestionTypeName: "Search mode",
        };

        $scope.searchModel.suggestions.push(sg1);
        $scope.searchModel.suggestions.push(sg2);
        /*
        $http({
            method: 'POST',
            url: '/search/SmartSearch/',
            data: { search: null }
        }).
            then(function (response) {
                $scope.superTypeSuggestions = response.data;
                $scope.searchModel.suggestions = response.data;

            }, function (response) {
                console.log("api cancel or failure - " + "/search/superTypesearchconfigs/");
            })
        */
    }

    $scope.setSmart = function (smart) {
        if ($scope.searchMode != smart);
            $scope.searchModel.input = "";
        $scope.searchMode = smart;
        $scope.searchModel.tags = [];
        $scope.searchModel.suggestions = [];
    }

    $scope.getPlaceholder = function () {
        if ($scope.searchMode == null) {
            return "Choose Search mode - Make + or Asset ID +";
        }
        if ($scope.searchMode == "assetid") {
            // if ($scope.searchModel.suggestions.length == 0)
                return "Enter VIN / HIN / SNo. / PVNo. or Other Asset ID";
            // else
                // return "Select VAULT / Asset Class";
        }
        /*
        if (!$scope.searchModel.tags.some(x => x.SuggestionProperty == "SuperType"))
            return "Select VAULT / Asset Class";
            */
        if ($scope.searchModel.tags.some(x => x.SuggestionType == "IDSearch"))
            return "";
        if ($scope.searchModel.tags.some(x => x.SuggestionProperty == "KeywordTokens"))
            return "Enter Keyword";
        if ($scope.searchModel.tags.some(x => x.SuggestionProperty == "PropertyModel"))
            return "Enter Keyword";
        if ($scope.searchModel.tags.some(x => x.SuggestionProperty == "MakeID"))
            return "Enter Model / Keyword";
        /*
        if (!$scope.searchModel.tags.some(x => x.SuggestionProperty == "MakeID"))
            return "Enter Make / Keyword";
            */
        // return "Type, Make, Keyword/s or any ID";
        return "Search for anything";
    }

    $scope.isSearchButtonDisabled = function () {
        return false; // $scope.searchMode == "smart" && ( /*!$scope.searchModel.tags.some(x => x.SuggestionProperty == "SuperType") || */ !($scope.searchModel.input && $scope.searchModel.input.length > 1)) && !$scope.isAdmin;
    }

    $scope.deleteAllTags = function () {
        if ($scope.searchModel.tags.length == 0)
            return;
        $scope.searchModel.input = "";
        if ($scope.searchMode == "assetid") {
            $scope.searchModel.tags = [];
            return;
        }

        $scope.SuperTypes = [];
        $scope.vaultStates = [];
        $scope.locations = [];

        $scope.searchModel.SuperType = null;
        $scope.searchModel.superType = null;
        $scope.searchModel.tags = [];

        $scope.lastActionWasDelete = true;
        if ($scope.canceller)
            $scope.canceller.resolve();
        if ($scope.searchCanceller)
            $scope.searchCanceller.resolve();
    }

    $scope.deleteTag = function (tag) {
        $scope.searchModel.input = "";
        if ($scope.searchMode == "assetid") {
            $scope.searchModel.tags = [];
            return;
        }

        $scope.SuperTypes = [];
        $scope.vaultStates = [];
        $scope.locations = [];

        if (tag.SuggestionProperty == "SuperType") {
            $scope.searchModel.SuperType = null;
            $scope.searchModel.superType = null;
        }

        $scope.searchModel.tags = $scope.searchModel.tags.filter(x => x != tag);

        $scope.lastActionWasDelete = true;
        if ($scope.canceller)
            $scope.canceller.resolve();
        if ($scope.searchCanceller)
            $scope.searchCanceller.resolve();
        // $scope.runSearch();

        /*
        if (tag.SuggestionProperty == "KeywordTokens") {
            $scope.searchModel.tags = $scope.searchModel.tags.filter(x => x != tag);
            $scope.runSearch();
            return;
        }

        $scope.searchModel.tags = $scope.searchModel.tags.filter(x => x.SuggestionProperty !== "PropertyModel");
        if (tag.SuggestionProperty == "PropertyModel") {
            $scope.runSearch();
            return;
        }

        $scope.searchModel.tags = $scope.searchModel.tags.filter(x => x.SuggestionProperty !== "MakeID");
        if (tag.SuggestionProperty == "MakeID") {
            $scope.runSearch();
            return;
        }

        $scope.searchModel.tags = $scope.searchModel.tags.filter(x => x.SuggestionProperty !== "SearchType");
        if (tag.SuggestionProperty == "SearchType") {
            $scope.runSearch();
            return;
        }


        $scope.searchModel.tags = [];
        $scope.searchModel.suggestions = $scope.vaultSuggestions;
        $scope.runSearch();
        */
    }
    
    var $tagsChanges = $scope.$watchAsProperty('searchModel.tags');
    $tagsChanges.throttle(2000).onValue(function (x) {
        console.log(x);
        if ($scope.lastActionWasDelete)
            $scope.runSearch();
        $scope.lastActionWasDelete = false;
    });

    var lookupInput = $scope.$watchAsProperty('searchModel.input');

    lookupInput.onValue(function (x) {
        if ($scope.superTypeSelecting)
            $scope.superTypeSelecting = false;
        if ($scope.searchModel.tags.some(x => x.SuggestionType == "IDSearch"))
            $scope.searchModel.input = "";
        if ($scope.lastActionWasDelete)
            $scope.lastActionWasDelete = false;
    });

    lookupInput.filter(function (x) { return !x || x.length <= 1; }).throttle(1000).onValue(function (x) {
        if (!$scope.searchModel.suggestions.some(x => x.SuggestionProperty == 'Message'))
            $scope.searchModel.suggestions = [];
        if ($scope.canceller)
            $scope.canceller.resolve();
        if (!x && $scope.searchModel.tags.length == 0 && !$scope.searchModel.suggestions.some(x => x.SuggestionProperty == 'Message'))
            $scope.setSmart("smart");
    });

    lookupInput.filter(function (x) { return x && x.length > 1; }).throttle(1000).onValue(function (x) {
        if (!$scope.searchMode == null)
           return;
        
        if ($scope.canceller)
            $scope.canceller.resolve();
        $scope.canceller = $q.defer();

        if ($scope.searchMode == "assetid")
            return;

        if (!$scope.searchModel.suggestions.some(x => x.SuggestionProperty == 'Message'))
            $scope.searchModel.suggestions = [];

        if (x.length > 1 || ["sa","wa","nt"].includes(x.toLowerCase())) {
            const txt = x;
            if ($scope.searchModel.suggestions.some(x => x.SearchTypeName == "Keyword")) {
                $scope.searchModel.suggestions.find(x => x.SearchTypeName == "Keyword").Name = txt;
            }
            else {
                var sg = {
                    Name: txt,
                    SuggestionType: "Keyword",
                    SuggestionTypeName: "KEYWORD search",
                };

                $scope.searchModel.suggestions.push(sg);
            }
        }
        if (x.length > 2 && $scope.searchModel.tags.length == 0) {
            const txt = x;
            if ($scope.searchModel.suggestions.some(x => x.SearchTypeName == "IDSearch")) {
                $scope.searchModel.suggestions.find(x => x.SearchTypeName == "IDSearch").Name = txt;
                $scope.searchModel.suggestions.find(x => x.SearchTypeName == "IDSearch").SuggestionValue = txt;
            }
            else {
                var sg = {
                    Name: txt,
                    SuggestionType: "IDSearch",
                    SuggestionTypeName: "ASSET ID search (VIN, HIN, S/N or any other ID)",
                    SearchType: "ID_Serial",
                    SuggestionValue: txt
                };

                $scope.searchModel.suggestions.push(sg);
            }
        }


        var regex = /\d/;
        var hasNumeral = regex.test(x);

        if (hasNumeral) {
            function customSort(a, b) {
                if (a.SuggestionType === "IDSearch") {
                    return -1; // 'a' comes before 'b'
                } else if (b.SuggestionType === "IDSearch") {
                    return 1; // 'b' comes before 'a'
                } else {
                    return 0; // No change in order
                }
            }
            $scope.searchModel.suggestions.sort(customSort);
        }

        $http({
            method: 'POST',
            url: '/search/SmartSearch/',
            timeout: $scope.canceller.promise,
            data: { search: x, tags: $scope.searchModel.tags, isGroupVault:$scope.isGroupVault(), accessType:$scope.accessType }
        }).
            then(function (response) {
                if ($scope.superTypeSelecting)
                    $scope.superTypeSelecting = false;
                var specials = $scope.searchModel.suggestions.filter(x => x.SuggestionType == "Keyword" || x.SuggestionType == "IDSearch");
                $scope.searchModel.suggestions = response.data.concat(specials);
                if ($scope.isAdmin) {
                    $scope.searchModel.suggestions.forEach(x => {
                        x.SuggestionTypeName = x.SuggestionTypeName.replace("For Sale", "Registered");
                        x.SearchTypeName = x.SearchTypeName.replace("For Sale", "Registered");
                    })
                }
            }, function (response) {
                console.log("api cancel or failure - " + "/search/SmartSearch/");
            });
    });

    $scope.keypressed = function (e) {
        // console.log(e);
        if (e.which === 13 && !$scope.isSearchButtonDisabled()) {
            console.log("enter");
            // $scope.runSearch();
        }
    };

    $scope.getSuggestionNamePart = function (suggestion, searchIncluded){
        var sgname = suggestion.Name;

        if (suggestion.SuggestionProperty == "SuperType" || suggestion.SuggestionProperty == "Channel")
            return searchIncluded ? sgname : "";

        if (!$scope.searchModel.input || sgname.toLowerCase().indexOf($scope.searchModel.input.toLowerCase()) == -1)
            return !searchIncluded ? sgname : "";

        if (searchIncluded)
            return sgname.substring(0,$scope.searchModel.input.length);

        return sgname.substring($scope.searchModel.input.length);
    }

    $scope.setSuperTypeOff = function () {
        if (!!isGroupVault())
            $scope.searchModel.superType = null;
    }

    $scope.selectSuggestion = function (suggestion) {
        if (suggestion.SuggestionProperty == "Message")
            return;

        if (suggestion.SuggestionProperty == "SuperType") {
            /*
            $scope.searchModel.input = "";
            $scope.chooseSuperType($scope.superTypes.find(x => x.SuperType == suggestion.SuperType));
            return;
            */
           $scope.searchModel.superType = $scope.superTypes.find(x => x.SuperType == suggestion.SuperType);
           $scope.searchModel.SuperType = suggestion.SuperType;
        }
            
        if (suggestion.SuggestionTypeValue == "Smart_Search") {
            $scope.setSmart("smart");
            document.getElementById("search-input").focus();
            return;
        }

        if (suggestion.SuggestionType == "Keyword") {
            // $scope.setSuperTypeOff;
            // $scope.searchModel.SuperType = null;
            $scope.runSearch();
            return;
        }

        /*
        if (!$scope.searchModel.tags.some(x => x.SuggestionProperty == "SearchType") &&
            suggestion.SuggestionProperty != "SearchType" && suggestion.SuggestionProperty ==  "MakeID" &&
            suggestion.SearchType != null) {

            var sg = {
                Name: suggestion.SearchTypeName,
                SuggestionType: "Listing Type",
                SuggestionTypeName: "Listing Type",
                SuggestionProperty: "SearchType",
                SuggestionValue: suggestion.SearchType,
                SuggestionTypeClass: suggestion.SearchTypeClass,
                SearchType: suggestion.SearchType
            };

            $scope.searchModel.tags.push(sg);
        }
        */

        /*
        if (!$scope.searchModel.tags.some(x => x.SuggestionProperty == "Make") &&
            suggestion.SuggestionProperty != "Make" &&
            suggestion.MakeName != null) {

            $scope.searchModel.tags.push({
                Name: suggestion.MakeName,
                SuggestionType: "Make",
                SuggestionTypeName: "Make",
                SuggestionProperty: "MakeID",
                SuggestionValue: suggestion.MakeID,
                SuggestionTypeClass: suggestion.SuggestionClass,
                MakeID: suggestion.MakeID
            });

            suggestion.SuggestionClass = "make"
        }
        */

        // suggestion.SuggestionClass = "make"
        $scope.searchModel.tags.push(suggestion);
        $scope.searchModel.suggestions = [];
        if(!suggestion.AddKeyword)
            $scope.searchModel.input = "";
        // $scope.setSuperTypeOff;
        // $scope.searchModel.SuperType = null;


        // if ($scope.searchModel.tags.some(x => x.SuggestionProperty == "SearchType"))
        if ($scope.searchMode == "smart")
            $scope.runSearch();

        /*
        $timeout(function () {
            $apply();
        }, 500);
        */
    }

    $scope.clearSuggestions = function () {
        $scope.searchModel.suggestions = [];
        $scope.superTypeSelecting = false;
        $scope.searchModel.input = "";
    }

    $scope.getVisibleTags = function () {
        if (!$scope.searchModel.tags)
            return [];
        return $scope.searchModel.tags.filter(x => x.SuggestionProperty !== "SearchType");
    }

    $scope.getInputPadding = function () {
        // console.log($(window).width(), $(".search-form-smart .tags .tag").length);
        if ($(window).width() <= 750)
            return 15;
        var pad = 15;
        $(".search-form-smart .tags .tag").each(function () {
            pad += $(this).width() + 25;
        });
        if ($scope.isAdmin)
            pad += 35;
        return pad + "px";
    }

    $scope.filterButtonClick = function () {
        $scope.showFilter = !$scope.showFilter;

    }

    $scope.showClearAll = function (filterSet) {
        return filterSet.some(x => x.Selected);
    }

    $scope.clearAllFilters = function (filterSet) {
        filterSet.forEach(x => x.Selected = false);
        $scope.runFilter();
    }

    $scope.isFilterDisabled = function () {
        return true;
        /*
        return ($scope.searchModel.tags.filter(x => x.SuggestionProperty != "SuperType").length == 0 && !$scope.isGroupVault() && !$scope.isMyVault()) ||
            !(($scope.vaultStates && $scope.vaultStates.length > 1) || ($scope.vaultTypes && $scope.vaultTypes.length > 1) || ($scope.locations && $scope.locations.length > 1));
            */
    }

    $scope.filterIsActing = function () {
        if (!$scope.vaultTypes)
            return false;
        return $scope.vaultTypes.some(x => !x.Selected) || $scope.vaultStates.some(x => !x.Selected) || $scope.locations.some(x => !x.Selected);
    }

    $scope.selectFilter = function (filter) {
        if ($scope.vaultStates.some(x => x == filter)) {
            filter.Selected = true;
            $scope.vaultStates.filter(x => x !== filter).forEach(x => x.Selected = false);
        }

        if ($scope.vaultTypes.some(x => x == filter)) {
            filter.Selected = true;
            $scope.vaultTypes.filter(x => x !== filter).forEach(x => x.Selected = false);
        }

        if ($scope.locations.some(x => x == filter)) {
            filter.Selected = true;
            $scope.locations.filter(x => x !== filter).forEach(x => x.Selected = false);
        }

        $scope.runFilter();
    }

    $scope.runFilter = function () {
        $scope.runSearch(null, null, true)
    }

    $scope.runSearch = function (forceRedirect, append, isButton) {
        if ($scope.isAdmin && !isButton)
            return;
        var sendModel = {}
        $scope.searchModel.suggestions = [];
        var displayHere = ($scope.searchModel.displayInPage || append) && !forceRedirect && !$scope.isAdmin;
        var popLastIfNoResults = false;

        var searchDataExisting = $("#SearchData");
        if (searchDataExisting.length && displayHere)
            sendModel.TightMode = searchDataExisting.data("tightmode");

        if (!$scope.searchModel.tags.some(x => x.SuggestionType == "IDSearch")) {
        //if ($scope.searchMode == "smart") {
            if (!sendModel.KeywordTokens)
                sendModel.KeywordTokens = [];
            sendModel.HasNewTokens = false;
            $scope.searchModel.tags.forEach((x) => {
                if (x.SuggestionProperty == "KeywordTokens")
                    sendModel.KeywordTokens.push(x.SuggestionValue)
                else
                    sendModel[x.SuggestionProperty] = x.SuggestionValue;
            })
            if ($scope.searchModel.input) {
                sendModel.KeywordTokens.push($scope.searchModel.input);
                sendModel.HasNewTokens = true;
                var tokens = $scope.getKeywordTokens($scope.searchModel.input); 
                tokens = tokens.filter(x => !["and", "the", "is", "in", "at", "of", "on", "for", "with", "to", "by", "an", "be", "this", "that", "it", "a", "or", "as", "but"].includes(x.toLowerCase()));
                for (var i = 0; i < tokens.length; i++) {
                    $scope.searchModel.tags.push({
                        Name: tokens[i],
                        SuggestionType: "KeywordTokens",
                        SuggestionProperty: "KeywordTokens",
                        SuggestionTypeClass: "keywords",
                        SuggestionValue: tokens[i],
                    });
                } 
                popLastIfNoResults = true;
                $scope.searchModel.input = "";
            }
            if ($scope.isHome && append)
                sendModel.SearchType = "Home_List";
            else
                sendModel.SearchType = null;
        }
        else {
            sendModel.SearchType = 15;
            $scope.searchModel.tags.forEach((x) => {
                sendModel[x.SuggestionProperty] = x.SuggestionValue;
            })
            sendModel.Keywords = $scope.searchModel.tags.find(x => x.SuggestionType == "IDSearch").SuggestionValue;
            popLastIfNoResults = true;
            $scope.searchModel.input = "";
        }

        if ($scope.vaultStates.some(x => x.Selected)) {
            sendModel.Channel = $scope.vaultStates.find(x => x.Selected).Value;
        }
        else if ($scope.searchModel.Channel) {
            sendModel.Channel = $scope.searchModel.Channel;
        }

        if ($scope.locations.some(x => x.Selected)) {
            sendModel.Location = $scope.locations.find(x => x.Selected).Value;
        }
        else if ($scope.searchModel.Locations) {
            sendModel.Location = $scope.searchModel.Location;
        }

        if ($scope.vaultTypes.some(x => x.Selected) && displayHere) {
            sendModel.FilterVaultType = $scope.vaultTypes.find(x => x.Selected).Value;
        }

        if ($scope.searchModel.SuperType != null) {
            sendModel.SuperType = $scope.searchModel.SuperType;
        }

        if ($scope.isGroupVault()) {
            sendModel.VaultType = $scope.searchModel.vault.Vault;
        }
        else if ($scope.searchModel.VaultType) {
            sendModel.VaultType = $scope.searchModel.VaultType;
        }

        if ($scope.accessType) {
            sendModel.AccessType = $scope.accessType;
        }

        var param = "?" + $scope.serialize(sendModel);
        param += "&Filter=true";
        var path = $scope.isAdmin || $scope.isMyVault() ? "" : "/search/";
        var pathParam = param;
        if ($scope.isAdmin)
            pathParam += "&isSmart=true";

        if (append)
            $(".load-more").replaceWith("<div style='text-align:center;width:100%;' class='search-loader'><img src='/content/images/design2/ajax-loader.gif'/></div>");
        else {
            $(".search-loader").remove();
            $('.found-list-box').prepend("<div style='text-align:center;width:100%;' class='search-loader'><img src='/content/images/design2/ajax-loader.gif'/></div>")
        }
        if (displayHere) {
            if (append) {
                $scope.pageNo = $scope.pageNo ? $scope.pageNo + 1 : 2;
                param += "&pageNo=" + $scope.pageNo;
            }

            if ($scope.searchCanceller)
                $scope.searchCanceller.resolve();
            $scope.searchCanceller = $q.defer();

            $http({
                method: 'POST',
                url: '/search/results/' + param,
                timeout: $scope.searchCanceller.promise
            }).
                then(function (result) {
                    if (result.data.indexOf("REDIRECT::") == 0) {
                        window.location = result.data.substring(10);
                        return;
                    }
                    if (append) {
                        $('.search-loader').remove();
                        $('.found-list-box').find(".load-more").remove();
                        var newData = $(result.data);
                        newData.find("h2").remove();
                        newData.find("orderby").remove();
                        $('.found-list-box').append(newData);
                        $(".found-list-box .lko").each(bootStrapAds);
                        $scope.toolActions();
                    }
                    else {
                        var searchData = $(result.data).find("#SearchData");
                        if (searchData.data("suggestionmessage")) {
                            $scope.searchModel.suggestions = [{
                                Name : searchData.data("suggestionmessage"),
                                SuggestionProperty : "Message"
                            }];
                            $(".search-loader").remove();
                            if (popLastIfNoResults)
                                $scope.searchModel.tags.pop();
                            return;
                        }
                        $('.found-list-box').html(result.data);
                        /*
                        if ($scope.searchMode == "smart") {
                            var resultTitle = $('.found-list-box').find("h2");
                            if (resultTitle.length) {
                                resultTitle.remove();
                                $(".search-description").html(resultTitle.html())
                            }
                        }
                        else {
                            $('.found-list-box').find("h2").remove();
                        }
                        */
                        $(".found-list-box .lko").each(bootStrapAds);
                        document.title = "Property Vault Search Results";
                        window.history.pushState({ "html": result.data, "pageTitle": document.title }, "", path + pathParam);
                        $scope.toolActions();
                        // window.pvRunPagination();
                    }
                }, function (response) {
                    console.log("api cancel or failure - " + "/search/results/");
                });
        }
        else {
            window.location = path + pathParam;// + "#search";
        }
    }

    $scope.toolActions = function () {
        $(".found-list-box .load-more button").click(function () {
            $scope.runSearch($(this).hasClass("redirect"), true);
            // $scope.apply();
        });
        $(".orderby button.action").click(function () {
            $scope.selectLocation({ state: $(this).data("val") });
        });
    }

    $scope.toolSetup = function () {
        $(window).click(function () {
            //Hide the menus if visible
            if ((!$scope.searchModel.suggestions || !$scope.searchModel.suggestions.length) && !$scope.superTypeSelecting)
                return;
            $scope.clearSuggestions();
            $scope.$apply();
        });

        $('.smart-search-box').click(function (event) {
            event.stopPropagation();
        });
    }

    $scope.serialize = function (obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    $scope.getKeywordTokens = function(keywordTokens) {
        if (!keywordTokens) {
            return [];
        }
        const words = keywordTokens.split(/\s+/);
        const tokens = [];
        let currentToken = '';
        words.forEach(word => {
            var curentTokenPlusWord = (currentToken + ' ' + word).toLowerCase();
            if ((word.length === 1 && currentToken)
                || (channelAliases.some(x => x == curentTokenPlusWord))
                || (stateAliases.some(x => x == curentTokenPlusWord))
                || (superTypeAliases.some(x => (x == curentTokenPlusWord)))
                || (superTypeSuggestions.some(x => x == curentTokenPlusWord))
                || (keywordAliases.some(x => x == curentTokenPlusWord || (x == curentTokenPlusWord + 's') || (x == curentTokenPlusWord + 'es')))
                || (keywordAliasesKeys.some(x => x == curentTokenPlusWord || (x == curentTokenPlusWord + 's') || (x == curentTokenPlusWord + 'es')))
            ) {
                currentToken += ' ' + word;
            } else {
                if (currentToken) {
                    tokens.push(currentToken);
                }
                currentToken = word;
            }
        });
        if (currentToken) {
            tokens.push(currentToken);
        }
        return tokens;
    }

    $scope.init();

}]);
;
jQuery(document).ready(function ($) {
    // browser window scroll (in pixels) after which the "back to top" link is shown
    var offset = 300,
		//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
		offset_opacity = 12000,
		//duration of the top scrolling animation (in ms)
		scroll_top_duration = 700,
		//grab the "back to top" link
		$back_to_top = $('.cd-top');

    //hide or show the "back to top" link
    $(window).scroll(function () {
        ($(this).scrollTop() > offset) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
        if ($(this).scrollTop() > offset_opacity) {
            $back_to_top.addClass('cd-fade-out');
        }
    });

    //smooth scroll to top
    $back_to_top.on('click', function (event) {
        event.preventDefault();
        $('body,html').animate({
            scrollTop: 0,
        }, scroll_top_duration
		);
    });


    $(".print a").click(function () {
        window.print();
        return fakse;
    });

    window.pvRunPagination = function () {
        $(".pagination li").addClass("page-item");
        $(".pagination a, .pagination span").addClass("page-link");
        $(".pagination .active").addClass("current");
    }
    window.pvRunPagination();

    $(".copytag").click(function () {
        copyStringToClipboard($(this).attr("data-original-title"))
    });

    function gotoSearch() {
       if ($("#searchtitle").length == 0) return true;
       $([document.documentElement, document.body]).animate({
           scrollTop: $("#searchtitle").offset().top - 80
        }, 1000);
        return false;
    }

    if (window.location.hash && window.location.hash.substr(1)=="search") {
        gotoSearch();
    }
    // $(".searchlink").click(function () { gotoSearch() });
});

function showMoreOrLess(thisObj, bonusContent) {
    var caption = thisObj.innerHTML;
    //alert(caption);
    if (caption == "...read more") {
        document.getElementById(bonusContent).style.display = "inline";
        thisObj.innerHTML = "...read less";
    } else {
        document.getElementById(bonusContent).style.display = "none";
        thisObj.innerHTML = "...read more";
    }
}

function copyStringToClipboard(str) {
    // Create new element
    var el = document.createElement('textarea');
    // Set value (string to be copied)
    el.value = str;
    // Set non-editable to avoid focus and move outside of view
    el.setAttribute('readonly', '');
    el.style = { position: 'absolute', left: '-9999px' };
    document.body.appendChild(el);
    // Select text inside element
    el.select();
    // Copy text to clipboard
    document.execCommand('copy');
    // Remove temporary element
    document.body.removeChild(el);
    console.log(str + ' copied to clip')
};
$(function () {
    window.bootStrapAds = function () {
        if (this.lkoBooted) return;
        $(this).wrap("<a href='" + $(this).attr("data-lko-outurl") + "' target='_blank'></a>")
        var lko = {
            AdAssetID: $(this).attr("data-lko-asssetid"),
            AdSlot: $(this).attr("data-lko-slot"),
            AdViewPort: $(this).attr("data-lko-device"),
            FileName: $(this).attr("src"),
            OutUrl: $(this).attr("data-lko-outurl"),
        };
        $(this).parent()[0].lko = lko;
        $(this).parent().click(function () {
            var outUrl = this.lko.OutUrl;
            var post = JSON.stringify(this.lko);
            $.ajax(
            {
                type: "POST",
                url: "/Lko/SaveEvent/",
                data: post,
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                },
                error: function (req, status, error) {
                },
                returnObj: null
            });
            return true;
        });

        var cs = window.getComputedStyle($(this)[0]);

        if(cs.display !== 'none')
        {
            var post = JSON.stringify($.extend({}, lko, {Type:1}));
            $.ajax(
            {
                type: "POST",
                url: "/Lko/SaveEvent/",
                data: post,
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                },
                error: function (req, status, error) {
                },
                returnObj: null
            });
        }
        this.lkoBooted = true;
    };

    $(".lko").each(bootStrapAds);
});;
if (window.location.href.indexOf(location.protocol + "//www") == -1 && window.location.href.indexOf(location.protocol + "//sg1") == -1) {
    location.href = 'https://www.' + window.location.href.substring(window.location.protocol.length + 2);
}
else  if (location.protocol != 'https:') {
    location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}

;
