/* Minification failed. Returning unminified contents.
(4724,97-98): run-time error JS1195: Expected expression: .
(4725,13-16): run-time error JS1003: Expected ':': var
(4862,23-24): run-time error JS1195: Expected expression: .
(4862,31-32): run-time error JS1195: Expected expression: .
(4862,39-40): run-time error JS1003: Expected ':': )
(4863,16-23): run-time error JS1009: Expected '}': console
(4863,16-23): run-time error JS1003: Expected ':': console
(4863,23-24): run-time error JS1195: Expected expression: .
(4863,61-62): run-time error JS1006: Expected ')': ;
(4866,12-13): run-time error JS1006: Expected ')': }
(4865,15): run-time error JS1004: Expected ';'
(4866,13-14): run-time error JS1195: Expected expression: )
(1241,15,1247,16): run-time error JS1314: Implicit property name must be identifier: onDelete(values, event) {
                if(event.constructor === PointerEvent || event.constructor === MouseEvent) {
                  App.pages.search.propertyedit_view.removeTextProperty(targetElementId, propertyId, values[0]);
                }
                
                return false;
              }
(1248,15,1255,16): run-time error JS1314: Implicit property name must be identifier: onItemAdd(value, item) {
                let $form = $(targetElementId).closest('form.prop-text-form');
                
                if($form) {
                  $form.data('refLabel', item.dataset.value);
                  $form.submit();
                }
              }
 */
$(document).ready(function () {
    function initAjaxCsrfHandler() {

        var nonCsrfRequestTypes = ['GET', 'HEAD', 'OPTIONS', 'TRACE'];
        
        function isValidAjaxUrl(url) {
            if(url) {
                var origin = window.location.origin
                    ? window.location.origin
                    : window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');

                return !url.startsWith('http') || url.startsWith(origin);
            }
            
            return false;
        }
        
        function ajaxRequestRequiresCSRFToken(requestType) {
            return nonCsrfRequestTypes.indexOf(requestType.toUpperCase()) < 0;
        }

        // Add CSRF token to all internal ajax requests
        $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
            if (ajaxRequestRequiresCSRFToken(options.type) && isValidAjaxUrl(options.url)) {
                var antiForgeryToken = $("input[name=__RequestVerificationToken]").val();

                if (antiForgeryToken) {
                    options.headers = $.extend({__RequestVerificationToken: antiForgeryToken}, options.headers);
                }
            }
        });
    }
    
    initAjaxCsrfHandler();
});
;
if (jQuery)
{
    $.extend({
        getCachedScript: function (url, options) {
            options = $.extend(options || {}, {
                dataType: "script",
                cache: true,
                url: url
            });

            return jQuery.ajax(options);
        },
        innovadex: {
            tracking: {
                tracker: null,
                tracker_list: null,
                init: function (tracker, tracking_codes, url, config, customVars) {
                    if (tracker == null || tracker === false) return;
                    this.tracker = tracker;
                    // handle 1-entry string for backwards compatibility
                    if (typeof tracking_codes === 'string')
                       this.tracker_list = [ tracking_codes ];
                    else
                       this.tracker_list = tracking_codes;
                    
                    if (typeof url != 'undefined' && url != null && url.length > 0)
                    {
                        config.page_location = url;
                        config.page_path = url;
                    }
                    if (!tracker === false)
                    {
                        if (typeof customVars != 'undefined' && customVars != null)
                        {
                            let varConfig = $.innovadex.tracking.createCustomVariableConfig(customVars);
                            if (varConfig != null && varConfig['map'] != null && varConfig['data'] != null) {
                                const customVarMap = varConfig['map'];
                                const customVarData = varConfig['data'];
                                tracker('set', {'custom_map': customVarMap});
                                Object.assign(config, customVarData)
                            }
                        }
                        
                        $.each(tracking_codes, function (i, code) {
                            tracker('config', code, config)
                        });
                    }
                },
                trackPage: function (url) {
                    if (this.tracker == null) return;
                    
                    // This function is for manual additional page-view calls only
                    if (typeof url == 'undefined' || url == null)
                        return;
                    
                    this.tracker('event', 'page_view', {
                        'page_location': url,
                        'page_path': url
                    });
                },
                trackEvent: function (category, action, label, numericalValue) {
                    if (this.tracker == null) return;
                    if (typeof label == 'undefined')
                        label = null;

                    if (typeof numericalValue == 'undefined')
                        numericalValue = null;

                    this.tracker('event', action, {'eventCategory': category, 'label': label});
                },
                addCustomVariable: function (index, name, value, scope) {
                    // This is probably not going to do much of anything with gtag
                    if (this.tracker == null) return;
                    let data = {};
                    data['dimension' + index] = value;
                    this.tracker('set', data);
                },
                createCustomVariableConfig: function(varMap)
                {
                    let map = {};
                    let data = {};
                    for (let itemKey in varMap) {
                        let item = varMap[itemKey];
                        if (item != null && item['index'] != null && item['value'] != null) {
                            map['dimension' + item['index']] = itemKey;
                            data[itemKey] = item['value'];
                        }
                    }
                    return {'map': map, 'data': data};
                }
                
            },
            refreshWindow: function () {
                window.location.reload(true);
            },
            handleErrors:
            {
                enabled: true,

                init: function () {
                    window.onerror = function (msg, url, line) {
                        if ($.innovadex.handleErrors.enabled)
                        {
                            msg = msg + " (likely on page init)";
                            $(document).trigger('client_error', [msg, null, line]);
                        }
                    };

                    window.beforeunload = function() {
                        $.innovadex.handleErrors.enabled = false;
                    };

                    // override jQuery.fn.bind to wrap every provided function in try/catch
                    var jQueryBind = jQuery.fn.bind;
                    jQuery.fn.bind = function (type, data, fn) {
                        if (!fn && data && typeof data == 'function') {
                            fn = data;
                            data = null;
                        }
                        if (fn) {
                            var origFn = fn;
                            var wrappedFn = function () {
                                try {
                                    origFn.apply(this, arguments);
                                }
                                catch (ex) {
                                    var source = null;
                                    var code = null;
                                    var stack = null;
                                    var line = 0;

                                    try {
                                        code = origFn.toString();

                                        if (ex.stack)
                                            stack = ex.stack.toString();

                                        if (ex.line)
                                            line = ex.line.toString();

                                        var $this = $(this);

                                        if ($this.attr('id') != null)
                                            source = $this.attr('id');
                                    }
                                    catch (e) { /* ignore */ }


                                    if ($.innovadex.handleErrors.enabled)
                                    {
                                        $(document).trigger('client_error', [ex.message.toString(), stack, line, source, code]);
                                    }
                                    // re-throw ex iff error should propogate
                                    // throw ex;
                                }
                            };
                            fn = wrappedFn;
                        }
                        return jQueryBind.call(this, type, data, fn);
                    };
                }
            },
            createAndSubmitForm: function (url, data) {
                $form = $(document.createElement("form"))
                    .attr('action', url)
                    .attr('method', 'post');
                $("body").append($form);

                if (typeof data != 'undefined' && data != null) {
                    $.each(data, function (key, value) {
                        $input = $(document.createElement("input"))
                            .attr('type', 'hidden')
                            .attr('name', key)
                            .attr('value', value);
                        $form.append($input);
                    });
                }

                $form.submit();
            },
            addQuerystringParam: function (url, param, value, replaceValueIfParamExists) {
                if (url.charAt(url.length - 1) == "#")
                    url = url.substr(0, url.length - 1);

                if (url.indexOf("?") == -1)
                    url = url + "?" + param + "=" + value;
                else {
                    var paramIndex = url.indexOf(param + "=");
                    if (paramIndex == -1)
                        url = url + "&" + param + "=" + value;
                    else {
                        if (replaceValueIfParamExists) {
                            var valBeginIndex = url.indexOf("=", paramIndex + 1) + 1;
                            var valEndIndex = url.indexOf("&", paramIndex + 1);

                            if (valEndIndex == -1)
                                url = url.substr(0, valBeginIndex) + value;
                            else
                                url = url.substr(0, valBeginIndex) + value + url.substr(valEndIndex);
                        }
                        else {
                            var sepIndex = url.indexOf("&", paramIndex + 1);

                            if (sepIndex == -1)
                                url = url + "|" + value;
                            else
                                url = url.substr(0, sepIndex) + "|" + value + url.substr(sepIndex);
                        }
                    }
                }

                return url;
            },

            removeQuerystringParam: function (url, param) {
                var paramIndex = url.indexOf(param + "=");

                if (paramIndex != -1) {
                    var valEndIndex = url.indexOf("&", paramIndex + 1);

                    if (valEndIndex == -1)
                        url = url.substr(0, paramIndex);
                    else
                        url = url.substr(0, paramIndex) + url.substr(valEndIndex + 1);
                }

                if (url.length > 0) {
                    var lastChar = url.substr(url.length - 1);

                    if (lastChar == '&' || lastChar == '?')
                        url = url.substr(0, url.length - 1);
                }

                return url;
            },
            url_encode: function(string) {
                if (string == null || string.length === 0)
                    return '';
                var encode = encodeURIComponent||escape;
                return encode(string).replace(/ /g, "+").replace("%20", "+");
            },
            redirectToUrl: function (url) {
                window.location = url;
            },
            supportsLocalStorage: function () {
                return ('localStorage' in window) && window['localStorage'] !== null;
            },
            saveLocal: function (key, val) {
                if (val == null || typeof val === "undefined") {
                    $.innovadex.deleteLocal(key);
                    return;
                }

                if (this.supportsLocalStorage())
                    localStorage[key] = val.toString();
            },
            saveLocalRaw: function (key, val) {
                if (this.supportsLocalStorage())
                    localStorage[key] = val;
            },
            retrieveLocal: function (key) {
                if (this.supportsLocalStorage())
                    return localStorage[key];
                else
                    return null;
            },
            deleteLocal: function (key) {
                if (this.supportsLocalStorage())
                    localStorage[key] = null;
            },
            getCookie: function(c_name) {
                if (document.cookie.length>0)
                {
                    c_start=document.cookie.indexOf(c_name + "=");
                    if (c_start!=-1)
                    {
                        c_start=c_start + c_name.length+1;
                        c_end=document.cookie.indexOf(";",c_start);
                        if (c_end == -1) c_end = document.cookie.length;
                        {
                            return unescape(document.cookie.substring(c_start, c_end));
                        }
                    }
                }
                return "";
            },
            setTableBodyText: function ($table, text) {
                var cols = $table.find("th");
                $table.find("tbody").html('<tr><td colspan="' + cols.length + '">' + text + '</td></tr>');
            },
            canPlayType: function (type) {
                var $audio = document.createElement('audio');
                if (typeof $audio.canPlayType == 'undefined' || $audio.canPlayType == null)
                    return false;

                // Put the call to canPlayType in a try..catch because of known issue w/ ie9 and windows server os
                try {
                    return $audio.canPlayType(type);
                }
                catch (ex) {
                    return false;
                }
            },
            defaultAutoCompleteSource: function (url, request, response, control) {
                $.ajax({
                    url: url,
                    data: "term=" + request.term,
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        response(data);
                    },
                    error: function (xhr, status, error) {
                        $(control).removeClass("ui-autocomplete-loading").val("Error retrieving list...");
                    }
                });
            },
            crossSiteAutoCompleteSource: function (url, request, response, control) {
                var success = function (data) { response(data) };
                var error = function () { $(control).removeClass("ui-autocomplete-loading").val("Error retrieving list..."); };

                if ($.browser.msie && parseInt($.browser.version, 10) >= 8 && window.XDomainRequest) {
                    // Use Microsoft XDR
                    var msUrl = this.addQuerystringParam(url, "term", request.term, true);
                    var xdr = new XDomainRequest();
                    xdr.open("get", msUrl);
                    xdr.onload = function () {
                        var data = JSON.parse(xdr.responseText);
                        success(data)
                    };
                    xdr.onerror = error;
                    xdr.send();
                }
                else {
                    $.ajax({
                        url: url,
                        data: "term=" + request.term,
                        type: 'GET',
                        dataType: 'json',
                        success: success,
                        error: error
                    });
                }
            },
            defaultAutoCompleteSearch: function (event, ui) {
                // Function to make autocompletes start search for alpha 3 or more characters and numeric for any number of characters
                var val = $(this).val();

                if (isNaN(val) && val.length < 3)
                    return false;
                else
                    return true;
            },
            isTextOnlyElementWrapping: function ($element) {
                return $element.get()[0].getClientRects().length > 1;
            },
            shortenTextToPreventWrap: function ($element) {
                var cssDisplay = $element.css('display');

                if (cssDisplay != null && cssDisplay != 'inline')
                    $element.css('display', 'inline');

                while ($.innovadex.isTextOnlyElementWrapping($element)) {
                    var text = $element.html();
                    var lastSpace = text.lastIndexOf(' ');

                    if (lastSpace == -1)
                        break;

                    $element.html(text.substring(0, lastSpace) + "...");
                }

                if (cssDisplay != null)
                    $element.css('display', cssDisplay);
            },
            ajaxifyForm: function ($form, onstart, onend) {
                $form.trigger("ajax:begin");
                $.ajax({
                    type: "POST",
                    url: $form.attr("action"),
                    dataType: "json",
                    data: $form.serialize(),
                    beforeSend: function(xhr, settings) {
                        if (onstart)
                            onstart();
                    },
                    success: function (data, status, xhr) {
                        $form.trigger('ajax:success', [data, status, xhr]);
                    },
                    error: function (xhr, status, error) {
                        $form.trigger("ajax:failure", [xhr, status, error]);
                    },
                    complete: function (xhr, status) {
                        $form.trigger("ajax:complete", xhr);

                        if (onend)
                            onend(status);
                    }
                });
            },
            inspect: function (item) {
                if (typeof (item) == 'object') {
                    var string = "{ ";

                    for (prop in item) {
                        string += prop + ' : ' + item[prop] + ", ";
                    }

                    string += " }";

                    return string;
                }
                else
                    return item;
            },
            scrollbarWidth: function (width) {
                var parent, child;

                if (width === undefined) {
                    parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
                    child = parent.children();
                    width = child.innerWidth() - child.height(99).innerWidth();
                    parent.remove();
                }

                return width;
            },
            //returns true if page scrolls, and false if not
            pageScroll: function () {
                var docHeight = $(document).height(),
                  scroll = $(window).height() + $(window).scrollTop();
                if ($('body').height() < docHeight)
                    scroll = docHeight;
                return !(docHeight == scroll);
            },
            //adds a character remaining countdown to an input object
            //in the input field can have 3 addtional properties,
            //data-related [the field in which the countdown should display]
            //data-limit [the length limit for the input]
            //data-message [the error message for exceeding the limit ]
            //OR those values can be passed into the method call
            countdown: function ($obj, r_id, limit, err_msg) {
                $obj.each(function () {
                    var $th = $(this),
                        $sp = $('.char_countdown', $($(this).parents('.form-group').get(0))),
                    related_b = r_id == undefined || r_id == null ? $th.data('related') : r_id,
                    cntdwn_l = limit == undefined || limit == null ? $th.data('limit') : limit,
                    msg = err_msg == undefined || err_msg == null ? $th.data('message') : err_msg,
                    $related = $('#' + related_b.replace(/^#/, '')),
                _docheck = function () {
                    var l = $th.val().length, scrollT = $th.scrollTop();
                    $related.html(cntdwn_l - l);

                    $related.toggleClass('label-default', cntdwn_l - l > 10 ).toggleClass('label-warning', cntdwn_l - l > 0 && cntdwn_l - l < 11 ).toggleClass( 'label-danger', cntdwn_l - l < 1 );

                    if (cntdwn_l - l > 0 && $th.parent().hasClass('has-error')) {
                        $th.parent().removeClass('has-error');
                        $sp.next('[data-type="inserted-error"]').remove();
                    }

                    //console.log($sp);
                    if (cntdwn_l - l < 1) {
                        $th.val($th.val().substring(0, cntdwn_l)).scrollTop(scrollT).parent().addClass('has-error');
                        if ($sp.next('[data-type="inserted-error"]').length == 0) {
                            $sp.after('<span class="help-block pull-left" data-type="inserted-error">' + msg + '</span>');
                        }
                        $related.html('0');
                    }
                };
                    _docheck();

                    $th.bind('keyup', function () { _docheck(); }).bind('paste', function () { _docheck(); });
                });
            },
            get_translation: function(phrase, default_text)
            {
                if (typeof(Translations) != 'undefined' && Translations != null && phrase in Translations)
                    return Translations[phrase];
                else
                    return default_text;
            }
        }
    });

    // Plugins
    $.fn.toggleSliderSwitch = function (isTurnedOn)
    {
        var $this = this;

        $this.css(
            {
                'display': 'inline-block',
                'position': 'relative',
                'border': 'solid 1px #666',
                'border-radius': '0.8em',
                '-webkit-border-radius': '0.8em',
                '-moz-border-radius': '0.8em',
                'font-weight': 'normal',
                'cursor': 'pointer',
                'text-decoration': 'none'
            });

        var cssHeight = $this.css('height');

        if (typeof cssHeight == 'undefined' || cssHeight == null || cssHeight == 0 || cssHeight == '0px')
            $this.css('height', '22px');

        var cssWidth = $this.css('width');

        if (typeof cssWidth == 'undefined' || cssWidth == null || cssWidth == 0 || cssWidth == '0px')
            $this.css('width', '67px');

        if (typeof isTurnedOn == 'undefined' || isTurnedOn == null)
            initialState = false;

        var height = $this.height();

        var $toggle = $(document.createElement('span'))
            .css(
                {
                    'position': 'absolute',
                    'top': '0',
                    'border': 'solid 1px #999',
                    'border-radius': '0.8em',
                    '-webkit-border-radius': '0.8em',
                    '-moz-border-radius': '0.8em',
                    'background-color': '#CCC',
                    'width': (height - 1) + 'px',
                    'height': (height - 1) + 'px'
                });

        var $onText = $(document.createElement('span'))
            .css(
                {
                    'position': 'absolute',
                    'color': '#fff',
                    'display': 'none',
                    'left': '9px',
                    'top': '3px',
                    'font-size': '10pt',
                    'font-weight': 'bold'
                })
            .html('ON');

        var $offText = $(document.createElement('span'))
            .css(
                {
                    'position': 'absolute',
                    'color': '#858585',
                    'display': 'none',
                    'right': '9px',
                    'top': '3px',
                    'font-size': '10pt',
                    'font-weight': 'bold'
                })
            .html('OFF');

        $this.append($toggle);
        $this.append($onText);
        $this.append($offText);

        var offBgColor = "#eee";
        var onBgColor = "#6699cc";

        $this.prop('isOn', isTurnedOn);

        if (isTurnedOn)
        {
            $this.css('background-color', onBgColor);
            $this.addClass('on');
            $toggle.css({ 'left': 'auto', 'right': '0' });
            $onText.show();
        }
        else
        {
            $this.css('background-color', offBgColor);
            $this.addClass('off');
            $offText.show();
        }

        var eventName = ('ontouchstart' in document.documentElement) ? "touchstart" : "mousedown";
        $this.bind(eventName, function (evt)
        {
            evt.preventDefault();

            if ($this.prop('isOn'))
            {
                $this.prop('isOn', false);
                $onText.hide();
                $offText.show();
                $toggle.css({ 'left': '0', 'right': 'auto' });
                $this.css('background-color', offBgColor);

                // Add css class so that styles can be overridden by css
                $this.removeClass('on');
                $this.addClass('off');

                $this.trigger('turnedOff');
            }
            else
            {
                $this.prop('isOn', true);
                $offText.hide();
                $onText.show();
                $toggle.css({ 'left': 'auto', 'right': '0' });
                $this.css('background-color', onBgColor);

                // Add css class so that styles can be overridden by css
                $this.removeClass('off');
                $this.addClass('on');

                $this.trigger('turnedOn');
            }
        });
    };
}

// String Methods
String.prototype.startsWith = function (str)
{
    return (this.match("^" + str) == str);
}
;
function getRefinementListSwapLinks(listId) {
  /*NOTE: the legacy $("[data-list-swap]") is initiated in desktop.js and assigns event handlers to these links*/
  let items = [];
  const elementsForId = document.querySelectorAll('a[data-list-id="' + listId + '"]');

  for (let i = 0; i < elementsForId.length; i++) {
    const el = elementsForId[i];
    const swapData = el.attributes["data-list-swap"];
    if (swapData && swapData.value === "true") {
      items.push(el);
    }
  }
  return items;
}

function saveInitialListVisibilityToConfig(refinementCfg) {
  if (refinementCfg.listElement) {
    refinementCfg.listInitialHidden = refinementCfg.listElement.classList.contains("hide");
  }
  if (refinementCfg.fullListElement) {
    refinementCfg.fullListInitialHidden = refinementCfg.fullListElement.classList.contains("hide");
  }
}

function showRefinementList(listElement, txtBox) {
  listElement.classList.remove("hide");
  listElement.scrollTop = 0;
  txtBox.setAttribute("aria-expanded", "true");
  txtBox.setAttribute("aria-controls", listElement.getAttribute("id"));
  if (document.activeElement != txtBox) {
    txtBox.focus();
  }
}

function hideRefinementList(listElement) {
  listElement.classList.add("hide");
}

function showRefinementListItem(listItem) {
  listItem.style.display = "";
}

function hideRefinementListItem(listItem) {
  listItem.style.display = "none";
}

function showRefinementListSwapElements(refinementCfg) {
  const elements = getRefinementListSwapLinks(refinementCfg.listId);
  for (let i = 0; i < elements.length; i++) {
    showRefinementListItem(elements[i]);
  }
}

function hideRefinementListSwapElements(refinementCfg) {
  const elements = getRefinementListSwapLinks(refinementCfg.listId);
  for (let i = 0; i < elements.length; i++) {
    hideRefinementListItem(elements[i]);
  }
}

function showCancel(refinementCfg) {
  showRefinementListItem(refinementCfg.cancelElement);
}

function hideCancel(refinementCfg) {
  hideRefinementListItem(refinementCfg.cancelElement);
}

function initCancel(refinementCfg) {
  hideCancel(refinementCfg);

  refinementCfg.cancelElement.addEventListener('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    refinementCfg.currentValue = refinementCfg.textElement.value = "";
    handleSearchClose(refinementCfg);
  })
}
function handleSearchOpen(refinementCfg) {
  //saveInitialListVisibilityToConfig(refinementCfg);
  if (refinementCfg.fullListElement) {
    hideRefinementList(refinementCfg.listElement);
    showRefinementList(refinementCfg.fullListElement, refinementCfg.textElement);
  }
  hideRefinementListSwapElements(refinementCfg);
  showCancel(refinementCfg);
}

function handleShowAllElements(nodeList) {
  var nodes = nodeList.getElementsByTagName("li"),
    emptyNode = nodeList.querySelector("[data-empty]");
  for (let i = 0; i < nodes.length; i++) {
    showRefinementListItem(nodes[i]);
  }
  if (!emptyNode.classList.contains("hide")) {
    emptyNode.classList.add("hide");
  }
  nodeList.scrollTop = 0;
}

function handleSearchClose(refinementCfg) {
  if (refinementCfg.listInitialHidden && document.activeElement != refinementCfg.textElement) {
    hideRefinementList(refinementCfg.listElement);
  }
  else {
    showRefinementList(refinementCfg.listElement, refinementCfg.textElement);
  }

  if (refinementCfg.fullListElement) {
    if (refinementCfg.fullListInitialHidden) {
      hideRefinementList(refinementCfg.fullListElement);
    }
    else {
      showRefinementList(refinementCfg.fullListElement, refinementCfg.textElement);
    }
  }

  showRefinementListSwapElements(refinementCfg);
  hideCancel(refinementCfg);

  // Make sure all elements in search list are set back to visible
  const listElements = refinementCfg.fullListElement ? refinementCfg.fullListElement : refinementCfg.listElement;
  handleShowAllElements(listElements);

  if (refinementCfg.listElement.classList.contains("hide") && (!refinementCfg.fullListElement || refinementCfg.fullListElement.classList.contains("hide"))) {
    refinementCfg.textElement.setAttribute("aria-expanded", "false");
  }
}

function getListElementSearchableText(listElement) {
  const labels = listElement.getElementsByTagName("label");
  if (labels.length === 0) return "";

  const text = labels[0].getAttribute("title");
  if (text.length === 0) return "";

  return text.toUpperCase();
}

function filterList(textVal, refinementCfg) {
  const searchTerm = textVal.toUpperCase();
  const listElements = refinementCfg.fullListElement ? refinementCfg.fullListElement.getElementsByTagName("li") : refinementCfg.listElement.getElementsByTagName("li");

  for (let i = 0; i < listElements.length; i++) {
    const listEl = listElements[i];
    const searchableText = getListElementSearchableText(listEl);
    if (!listEl.dataset["empty"]) {
      if (searchableText.indexOf(searchTerm) > -1) {
        showRefinementListItem(listEl);
      }
      else {
        hideRefinementListItem(listEl);
      }
    }
  }
}

function handleRefinementListSearch(textVal, refinementCfg) {
  var filteredList = refinementCfg.fullListElement ? refinementCfg.fullListElement : refinementCfg.listElement;

  if (textVal.length > 0) {
    handleSearchOpen(refinementCfg);
    if (refinementCfg.currentValue !== "") {
      filterList(textVal, refinementCfg);

      var emptyEl = filteredList.querySelector("[data-empty=true]");
      //if matches found, hide no matches message
      //select li without style (display none) and not the empty message = visible matches
        // and if no matches visible (no .hide class)
      if (filteredList.querySelector("li:not([style*=display]):not([data-empty=true])")) {
        if (!emptyEl.classList.contains("hide")) {
          emptyEl.classList.add("hide");
        }
      }
      else {
        if (emptyEl.classList.contains("hide")) {
          emptyEl.classList.remove("hide");
        }
      }
      if (filteredList.classList.contains("hide")) {
        showRefinementList(filteredList, refinementCfg.textElement);
      }
      filteredList.scrollTop = 0;
    }
  }

  if (textVal.length === 0 && refinementCfg.currentValue.length > 0 && !refinementCfg.listInitialHidden) {
    handleSearchClose(refinementCfg);
  }
  else if (textVal.length === 0 && refinementCfg.currentValue.length > 0) {
    //reload the full list
    handleShowAllElements(filteredList);
  }

  refinementCfg.currentValue = textVal;
}

function initRefinementListSearch() {
  /*NOTE: the legacy $("[data-list-swap]") is initiated in desktop.js and controls the "load all options" link in the dropdown*/

  const searches = document.querySelectorAll('input[data-refinement-list-filter]');
  for (let i = 0; i < searches.length; i++) {
    const txtBox = searches[i];
    const listId = txtBox.getAttribute("data-list-id");
    const altPlaceholder = txtBox.dataset["altPlaceholder"];

    let cfg = {
      listId: listId,
      listElement: document.getElementById(listId),
      fullListElement: document.getElementById(listId + "-alt"),
      textElement: txtBox,
      cancelElement: txtBox.parentElement.getElementsByClassName("cancel-filter")[0],
      currentValue: ""
    };

    saveInitialListVisibilityToConfig(cfg);
    initCancel(cfg);

    txtBox.addEventListener('input', function (e) {
      handleRefinementListSearch(e.target.value, cfg);
    });

    if (cfg.listInitialHidden) {
      txtBox.addEventListener("focusin", function (e) {

        if (txtBox.value.length > 0) {
          cfg.currentValue = txtBox.value;
          handleRefinementListSearch(txtBox.value, cfg);
        }
        else {
          if (!cfg.fullListElement || cfg.fullListElement.classList.contains("hide")) {
            showRefinementList(cfg.listElement, txtBox);
          }
        }
      });

      document.addEventListener('click', function (e) {
        var target = e.target,
          list = cfg.listElement, fulllist = cfg.fullListElement;

        //only worry about the active search element
        if (target != list && target != fulllist && !list.contains(target) && (!fulllist || (fulllist && !fulllist.contains(target))) && target != txtBox && (!list.classList.contains("hide") || (fulllist && !fulllist.classList.contains("hide")))) {
          handleSearchClose(cfg);
        }
        if (target == list.querySelector("[data-property-list-expander=true]")) {
          txtBox.focus();
        }
      });
    }
    else {
      if (txtBox.value.length > 0) {
        cfg.currentValue = txtBox.value;
        handleRefinementListSearch(txtBox.value, cfg);
      }
    }
  }
}
;
if (jQuery) {
  var App = {
    pageTrackingCategory: null,
    defaults:
    {
      AutoCompleteDelay: 700,
      promo_code_region_list: [ 'asia' ]
    },
    initTrack: function($context) {
        // Do not change this to use live because on clicks that go to a new page, the track
        // will not fire in Webkit browsers
        var $event_links = $("a[data-action-event]", $context);
        $event_links.unbind('click', App.actions.handleTrackingActionEvent);
        $event_links.click(App.actions.handleTrackingActionEvent);

        var $event_forms = $("form[data-action-event]", $context);
        $event_forms.unbind('submit', App.actions.handleTrackingActionEvent);
        $event_forms.submit(App.actions.handleTrackingActionEvent);

        var $event_buttons = $("button[data-action-event]", $context);
        $event_buttons.unbind('click', App.actions.handleTrackingActionEvent);
        $event_buttons.click(App.actions.handleTrackingActionEvent);

        var $openers = $(".opener[data-action-event]", $context);
        $openers.unbind('click', App.actions.handleTrackingActionEvent);
        $openers.click(App.actions.handleTrackingActionEvent);
    },
    initPage: function (page_name, isBoosted) {
      let init = () => {
        $('form[data-prevent-double-submit="true"]').submit(function () {
          $(this).find("input[type='submit']").attr("disabled", "disabled");
        });

        $(".preventDoubleClick").preventDoubleClick();

        initDropdowns();
        initCollapsibles();
        initDisclosure();
      };
      
      $(document).ready(function () {
        init();
      });

      // document.addEventListener('htmx:afterSwap', function(event) {
      //   console.log('loaded detail');
      //   console.log(event.detail);
      //
      //   console.log(`detail boosted? ${event.detail.boosted}`);
      //
      //   if(event?.detail?.boosted) {
      //     console.log('inside boosted init');
      //     init();
      //   }
      // });
      
      $body = $("body");

        //ios6 post bug fix
        // if we are doing a post and url is set (which it should be) then we add a time parameter to url
        // to ensure that the result is not cached
      $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
          if (options.type.toUpperCase() == 'POST' && options.url.length > 0) {
              $.innovadex.addQuerystringParam(options.url, 'time', (new Date()).getTime().toString(), false);
          }
      });

      App.initTrack($body);

      // following is used to initialize page and run scripts
      if (page_name != null && page_name.length > 0) {
        var page = null;
        try {
          page = eval("App.pages." + page_name);
        }
        catch (err) {
            //ignore
        }
      }

      if (page != null) {
        if (isBoosted || page['isInitialized'] == null) {
          page['isInitialized'] = true;   // Set early so that javascript error doesn't make it to continue to be called

          // Perform initializations specific to this page
          var params = null;
          var $param_element = $("#page_params");

          if ($param_element != null) {
              var param_html = $.trim($param_element.html());

              if (param_html.length > 0) {
                  param_html = '(' + param_html + ')';
                  params = eval(param_html);
              }
          }

          page.init($body, params);
        }
      }
    },
    pages:
    {
      search:
      {
        performsearch_view:
        {
          init: function($context, params)
          {
            $("#full-search-link").click(function(evt) {
              $.innovadex.tracking.trackEvent("Actions", "Keyword Search All Fields");
              return true;
            });

            $("body").delegate(".swap-content-link", "click", function (evt) {
                evt.preventDefault();
                $link = $(this);

                var $swap_to = $link.parent().parent().children('[data-swap-id="' + $link.attr("data-swap-to") + '"]');
                $link.parent().hide();
                $swap_to.removeClass('hide');   // Show does not seem to override the class anymore
                $swap_to.show();
            });

            $("#keyword-search-form", $context).submit(function(evt) {
              evt.preventDefault();

              term = $.trim($("#keyword-search").val());
              if (term == "")
                return false;

              encode = encodeURIComponent||escape;
              term = encode(term);
              term = term.replace(/ /g, "+").replace("%20", "+");

              var newUrl = getSearchBaseUrl(true);
              console.log(newUrl);
              newUrl = $.innovadex.addQuerystringParam(newUrl, 'k', term, false);
              newUrl = $.innovadex.addQuerystringParam(newUrl, "st", "1", true);      // Always should have search search-type

              // Add search order to querystring if its available
              if (typeof searchOrder != 'undefined')
                newUrl = newUrl + "&so=" + searchOrder;

              if (typeof parentSearchLogId != 'undefined')
                newUrl = newUrl + "&sl=" + parentSearchLogId;

              $.innovadex.redirectToUrl(newUrl);
            })
          },
          removeSearchChip: function(linkElement) {
            console.log(linkElement);

            if(linkElement && linkElement.href) {
              let newUrl = new URL(linkElement.href, window.location.origin);

              newUrl.searchParams.set('st', '1');

              const currentSearchParams = new URLSearchParams(window.location.search);
              let parentSearchLogId = currentSearchParams.get('sl');
              let searchOrder = currentSearchParams.get('so');

              // Add search order to querystring if its available
              if (searchOrder != null)
                newUrl.searchParams.set('so', searchOrder);

              if (parentSearchLogId !== null)
                newUrl.searchParams.set('sl', parentSearchLogId);
              
              console.log(newUrl.searchParams);

              $.innovadex.redirectToUrl(newUrl.href);
            }
          }
        },
        propertyedit_view:
        {
          init: function($context, params)
          {
            $("#unit-selector").change(function(evt) {
              
              var $ranges = $("#prop-ranges", $context);

              if ($ranges != null && $ranges.length != 0)
              {
                var url = params['search_url'];

                if (url.indexOf('/search') != -1)
                    url = url.replace('/search', '/PropertyEditRanges');
                else
                {
                  var endPos = url.indexOf('?');
                  if (endPos)
                      url = url + '/PropertyEditRanges';
                  else
                      url = url.substr(0, endPos - 1) + '/PropertyEditRanges' + url.substr(endPos);
                }

                $ranges.html('');
                $.getJSON(url, { pId: params['property_id'], unitId: $("#unit-selector").val() }, function(data, textStatus, xhr) {
                  if (data != null && data.length != 0)
                  {
                    $.each(data, function(idx, $item) {
                      var $li = $(document.createElement("li"));
                      var $link = $(document.createElement("a"))
                        .html($item.Text)
                        .attr('href', $item.Url);
                      $li.append($link);
                      $ranges.append($li);
                    });
                  }
                })
              }
            });

            $(".prop-manual-form", $context).submit(function(evt) {
              evt.preventDefault();

              let propertyDataTypeName = $(".property-data-type-id", $context).val();
              let unitElement = evt.target.querySelector("[data-unit-selector='true']");
              let unit_id = 0;
              
              if(unitElement && unitElement.value.length > 0) {
                unit_id = unitElement.value;
              }

              let minElement = evt.target.querySelector("[data-prop-min='true']");
              
              let maxElement = evt.target.querySelector("[data-prop-max='true']");
              
              let min = minElement ? minElement.value : null;
              let max = maxElement ? maxElement.value : null;

              if ((min == null || min.length === 0) && (max == null || max.length === 0))
                return false;

              let searchUrl = params['search_url'];
              let newUrl = new URL(searchUrl, window.location.origin);
              let propertyId = params['property_id'];

              let pUserParam = newUrl.searchParams.get('pUser');

              let paramVal = `${propertyDataTypeName}:${unit_id}:${min ? min : ''}${max ? ':' + max : ''}`;

              console.log(paramVal);
              
              if(pUserParam) {
                let propertyIndex = pUserParam.indexOf(propertyId);
                if(propertyIndex >= 0) {
                  const regex = new RegExp(`(${propertyId}:[^:]*:[^:]*:[^:|]*(:[^:|]*)?)`, 'g');
                  console.log('replace param');
                  console.log(pUserParam);
                  pUserParam = pUserParam.replace(regex, `${propertyId}:${paramVal}`);
                  console.log(pUserParam)
                }
                else {
                  console.log('append param');
                  pUserParam += `|${propertyId}:${paramVal}`;
                }
              }
              else {
                console.log('assign param');
                pUserParam = `${propertyId}:${paramVal}`;
              }
              
              newUrl.searchParams.set('pUser', pUserParam);

              redirectToSelectedRefinement($(evt.target), newUrl.href);
            });

            $(".prop-text-form", $context).submit(function(evt) {
              evt.preventDefault();

              let selectElement = evt.target.querySelector(".pText").tomselect;
              selectElement.disable();
              
              let searchTerm = $.trim(selectElement.getValue().slice(-1));
              if (searchTerm === "")
                return false;

              let searchUrl = params['search_url'];
              let newUrl = new URL(searchUrl, window.location.origin);
              let pTextPropertyId = params['property_id'];

              let pTextParam = newUrl.searchParams.get('pText');
              
              if(pTextParam) {
                let propertyIndex = pTextParam.indexOf(pTextPropertyId);
                if(propertyIndex >= 0) {
                  const regex = new RegExp(`(${pTextPropertyId}:.*(?=\\|)|${pTextPropertyId}:.*$)`, 'g');
                  let result = regex.test(pTextParam);
                  
                  if(result) {
                    let pTextParamArray = pTextParam.split('');
                    pTextParamArray.splice(regex.lastIndex, 0, `:${searchTerm}`);

                    pTextParam = pTextParamArray.join('');
                  }
                }
                else {
                  pTextParam += `|${pTextPropertyId}:${searchTerm}`;
                }
              }
              else {
                pTextParam = `${pTextPropertyId}:${searchTerm}`;
              }
              
              newUrl.searchParams.set('pText', pTextParam);
              
              redirectToSelectedRefinement($(evt.target), newUrl.href);
            })
          },
          initPropertyEditSelect: function(targetElementId, propertyId, maxItemCount) {
            new TomSelect(targetElementId,{
              plugins: {
                remove_button:{
                  title:'Remove property',
                }
              },
              createOnBlur: false,
              create: false,
              maxOptions: null,
              maxItems: maxItemCount,
              onDelete(values, event) {
                if(event.constructor === PointerEvent || event.constructor === MouseEvent) {
                  App.pages.search.propertyedit_view.removeTextProperty(targetElementId, propertyId, values[0]);
                }
                
                return false;
              },
              onItemAdd(value, item) {
                let $form = $(targetElementId).closest('form.prop-text-form');
                
                if($form) {
                  $form.data('refLabel', item.dataset.value);
                  $form.submit();
                }
              },
              render: {
                option: function(data, escape) { 
                  return `<div data-selected="${data.selected}"><span>${escape(data.name)}</span><span class="pull-right">(${escape(data.count)})</span></div>`;
                },
                item: function(data, escape) {
                  return `<div data-property-chip="true" data-property-id="${data.propertyId}" data-property-value="${escape(data.name)}" data-removal-url="${data.removalUrl}">${escape(data.name)}</div>`;
                }}
            })
          },
          initRefinementTypeahead: function() {
            new TomSelect('#selectProperty',{
                createOnBlur: false,
                create: false,
                maxOptions: null,
                onItemAdd: function(value, item) {
                  let currentSearchParams = new URLSearchParams(window.location.search);
                  let pUser = currentSearchParams.get('pUser');
                  let pText = currentSearchParams.get('pText');
    
                  let requestUrl = new URL(value, window.location.origin);
                  if(pUser) {
                    requestUrl.searchParams.set('pUser', pUser);
                  }
    
                  if(pText) {
                    requestUrl.searchParams.set('pText', pText);
                  }
    
                  htmx.ajax('GET',requestUrl.href, {target:'#working-property', swap:'innerHTML', indicator:'#refinements'});
                  document.getElementById('selectProperty').tomselect.blur();
              },
              render: {
                item: function(data, escape) {
                  return `<div data-property-id="${data.propertyId}">${escape(data.text)}</div>`;
                  },
                option: function(data, escape) {
                  return '<div><span>' + escape(data.name) + (data.count ? '</span><span class=\'pull-right\'>(' + escape(data.count) + ')</span>' : '') + '</div>';}
              },
            })
          },
          removeTextProperty: function(targetElementId, propertyId, value) {
            console.log(`removing ${propertyId} value: ${value}`);

            let selectEl = document.querySelector(targetElementId).tomselect;
            selectEl.disable();

            let element = document.querySelector(`div[data-property-chip=true][data-property-id="${propertyId}"][data-property-value="${value}"]`);
            console.log(element);
            
            if(element && element.dataset.removalUrl) {
              let newUrl = new URL(element.dataset.removalUrl, window.location.origin);

              newUrl.searchParams.set('st', '1');

              // Add search order to querystring if its available
              if (typeof searchOrder != 'undefined')
                newUrl.searchParams.set('so', searchOrder);

              if (typeof parentSearchLogId != 'undefined')
                newUrl.searchParams.set('sl', parentSearchLogId);

              $.innovadex.redirectToUrl(newUrl.href);
            }
          }
        }
      },
      industry:
      {
        index_view:
        {
          init: function ($context, params)
          {
            App.pageTrackingCategory = "Industry Home";
          }
        }
      },
      error:
      {
          e404_view:
        {
            init: function () {
            }
        }
      }
    },
    actions:
    {
      handleTrackingActionEvent: function() {
        var $src = $(this),
            label = null,
            category = "Actions";
        if (!$src.attr("data-action-event")) return;
        let eventName = $src.attr("data-action-event");
        if (eventName == null || eventName.length === 0) return;

        if ($src.attr("data-action-event-category"))
          category = $src.attr("data-action-event-category");

        if ($src.attr("data-action-event-label"))
            label = $src.attr("data-action-event-label");

        $.innovadex.tracking.trackEvent(category, eventName, label);
      }
    },
    controls:
    {
      //NOTE: REVISIT THIS ON TEST
      supports_select_to_autocomplete: function()
      {
        return true;// !((typeof(MobileApp) != 'undefined' && MobileApp) || ($.browser.msie && parseInt($.browser.version, 10) <= 7));
      },
      country_select:
      {
        init: function($select)
        {
          if (!App.controls.supports_select_to_autocomplete())
            return;
        
          // Add spelling suggestions and relevancy boost
          if (typeof(country_selector_data) != 'undefined' && country_selector_data != null)
          {
            $.each(country_selector_data, function(key, value) {
              var $option = $("option[value='" + key + "']", $select);

              if ($option != null && $option.length == 1)
              {
                $.each(value, function(key, value) {
                  $option.attr(key, value);
                });
              }
            });
          }

          /*$select.selectToAutocomplete();
          var $textbox = $select.siblings(".ui-autocomplete-input");

          if ($textbox.length != 0)
            $textbox.attr({'id': 'CountryText', 'name': 'CountryText'});*/
          //create dropdown array list from hidden select box
          var countries = {},
              items   = [];
          $('option', $select).each( function(i,o) {
            var $o = $(o);
            items.push( $o.text() );
            countries[ $o.text() ] = { name: $o.text(), id: $o.attr('value'), spellings: $o.data('alternative-spellings')  };

            countries[ $o.text() ]['relevancy-score'] = 0;
            countries[ $o.text() ]['relevancy-score-booster'] = 1;
            var boost_by = parseFloat( $o.data('relevancy-booster') );
            if ( boost_by ) {
              countries[ $o.text() ]['relevancy-score-booster'] = boost_by;
            } 
          });
          // init typeahead
          $($select.data('related')).typeahead({
              source: items,
              matcher: function (item) {
                var all_spellings = [item],
                    alt_spellings = countries[item].spellings,
                    t             = this,
                    match         = false;

                if( alt_spellings )
                {
                  $(alt_spellings.split(' ')).each(function(i,x){ all_spellings.push(x) } );
                }

                $( all_spellings ).each( function(i, it) {
                  if (it.toLowerCase().indexOf(t.query.trim().toLowerCase()) != -1) {
                    match = true;
                  }
                });
                return match;
              },
              sorter: function (items) {
                var list = [], sorter = [], sorted = [];

                $(items).each(function(i,a){
                  list.push( countries[a] );
                });

                sorter = list.sort(function( a, b ) { return b['relevancy-score-booster'] - a['relevancy-score-booster'] })
                $( sorter ).each(function(i,x){ sorted.push(x.name) } );

                return sorted;
              },
              highlighter: function (item) {
                $('#CountryId').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
                var regex = new RegExp( '(' + this.query + ')', 'gi' );
                return item.replace( regex, "<strong>$1</strong>" );
              },
              updater: function(item)
              {
                $('#CountryId').val(countries[item].id).change();
                return item;
              }
          });
        }
      },
      employer_select:
      {
        element: null,
        id_element: null,
        get_id: function() 
        { 
          var id = this.id_element.val(); 

          if (id.length === 0)
            return 0;
          else
            return parseInt(id);
        },
        set_id: function(id) 
        { 
          var val = '';
          if (id > 0)
            val = id;

          this.id_element.val(val); 
          this.id_element.trigger('id_set', id);
        },
        get_text: function() { this.element.val(); },
        set_text: function(text) { this.element.val(text); },

        init: function ($control, $id_control)
        {
          this.element = $control;
          this.id_element = $id_control;
          employer_select_control = this;

          this.element.change(function(evt) {
            employer_select_control.set_id(-1);
          });

          //TYPEAHEAD is the bootstrap autocomplete
          //console.log( App.defaults.AutoCompleteDelay );
          this.element.typeahead({
            timer: App.defaults.AutoCompleteDelay,
            source: function( query, process ) {
              //the ajax call remains the same, using "query" as term
              //query is available in the entire typeahead scope (ie. all functions)
              $.ajax({
                url: '/employer/search?limit=150',
                data: "term=" + query,
                type: 'GET',
                dataType: 'json',
                //in this case, there is an "addon" element with a search icon on the typedown input
                //switch search icon to animated loading icon
                beforeSend: function() {
                  $('#EmployerName').siblings('.add-on').children('i').removeClass('icon-search').addClass('icon-spinner icon-spin');
                },
                success: function (data) {
                  // create an array of the strings to appear in the
                  // dropdown list from the JSON array of results
                  var names = [];
                  // create a hash to hold the results, using the list string as the key
                  // the hash will need to be accessible to the other methods in the typeahead scope
                  App.controls.employer_select.emps = {};
                  $.each(data, function (i, e) {
                      // put each JSON object into the hash
                      App.controls.employer_select.emps[e.Name] = e;
                      // put each display list string  in array
                      names.push(e.Name);
                  });

                  // return the array using the process method (second
                  // argument of the source function)
                  return process(names);
                },
                complete: function() {
                  $('#EmployerName').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
                }
              });
            },
            //this function makes the matching of the display list items case insensitive
            //in most circumstances, this function will not need to be changed
            matcher: function (item) {
              return (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1);
            },
            //simple alphabetical sort of the display list array
            //in most circumstances, this function will not need to be changed
            sorter: function (items) {
              return items.sort();
            },
            //makes the search string bold
            //in most circumstances, this function will not need to be changed
            highlighter: function (item) {
              //switch animated loading icon back to search icon
              $('#EmployerName').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
              var regex = new RegExp( '(' + this.query + ')', 'gi' );
              return item.replace( regex, "<strong>$1</strong>" );
            },
            //function fires when the user chooses an option from the dropdown list
            //in this case, updates a hidden field using a value from the JSON object stored with a 
            //key matching the selected value
            //return the item (in order to return "true")
            updater: function (item) {
              if( App.controls.employer_select.emps[item] )
              {
                $('#EmployerId').val(App.controls.employer_select.emps[item].EmployerId);
                return item;
              }
            }
          });

          /*this.element.autocomplete({
              delay: App.defaults.AutoCompleteDelay,
              focus: function (event, ui) { return false; },
              source: function (request, response) {
                  $.ajax({
                      url: '/employer/search?limit=150',
                      data: "term=" + request.term,
                      type: 'GET',
                      dataType: 'json',
                      success: function (data) {
                        response(data);
                      },
                      error: function (xhr, status, error) {
                       // Do nothing - don't want to overwrite what user typed with error message 
                      }
                  });
              },
              select: function (event, ui) {
                  employer_select_control.set_id(ui.item.EmployerId);
                  employer_select_control.set_text(ui.item.Name);
                  return false;
              },
              search: function(evt, ui) {
                $(this).data('state', 'opening');
              },
              open: function(evt, ui) {
                if ($(this).data('state') === 'cancel')
                  $(this).autocomplete('close');
                else
                  $(this).data('state', 'open');
              },
              close: function(evt, ui) {
                $(this).data('state', 'closed');
              }
          })
          .data("autocomplete")._renderItem = function (ul, item) {
              return $("<li></li>")
              .data("item.autocomplete", item)
              .append("<a>" + item.Name + "</a>")
              .appendTo(ul);
          };*/

          $("input").focus(function(evt) {
              if ($(this).attr('id') != employer_select_control.element.attr('id') && employer_select_control.is_open())
                  employer_select_control.close_options();
          });
        },
        is_open: function()
        {
            var state = this.element.data('state');
            return state === 'open' || state == 'opening';
        },
        close_options: function()
        {
          if (this.element.data('state') === 'opening')
            this.element.data('state', 'cancel');
          else
            this.element.autocomplete('close');
        }
      },
      state_select:
      {
        element: null,
        free_form_text: null,
        section: null,
        data_list: {},

        init: function($select, $section)
        {
          state_control = this;
          this.element = $select;
          this.section = $section;

          this.create_data_list();
          this.element = $select.detach(); 
          this.free_form_text = this.create_free_form();
          this.show_free_form();  
        },
        get_select: function() { return $("select#StateProvince", this.section); },
        get_select_textbox: function() 
        { 
          var $select = this.get_select();

          if ($select.length == 0)
            return [];
          else
            return $select.siblings(".ui-autocomplete-input");
        },
        get_free_form: function() { return $("input#State", this.section); },
        create_free_form: function()
        {
          var $text = $(document.createElement("input"))
            .attr({ 'id': 'State', 'name': 'StateProvince', 'type': 'text' });

          $text.addClass('input-large');

          var cls = this.element.attr('class');
          if (typeof(cls) != 'undefined' && cls)
            $text.addClass(cls);

          return $text;
        },

        create_data_list: function()
        {
            var state_list = null;

            if (typeof State_Data != 'undefined')
              state_list = State_Data.selector_data;

            $.each($("option[data-country]", this.element), function(idx, item)
            {
                var $option = $(item).detach();
                var name = $option.attr('value');
              
                if (state_list)
                {
                  if (name in state_list)
                  {
                    $.each(state_list[name], function(key, value) {
                      $option.attr(key, value);
                    });
                  }
                }
                var cntry_id = parseInt($option.attr('data-country'));

                if (cntry_id in state_control.data_list)
                    state_control.data_list[cntry_id].push($option);
                else
                    state_control.data_list[cntry_id] = [ $option ];
            });
        },

        populate: function(country_id)
        {
            // try to save any existing value
            var current_val = null;
            var $el = this.get_select();
            var $txt = this.get_free_form();

            if ($el && $el.val() && $el.val().length > 0)
              current_val = $el.val();
            else if ($txt && $txt.val() && $txt.val().length > 0)
              current_val = $txt.val();

            if (country_id in this.data_list)
            {
              var $select = this.init_select();

              $.each(this.data_list[country_id], function(idx, item)
              {
                var $option = $(item);
                $select.append($option);
              }); 

              if (current_val)
                $select.val(current_val);
              this.show_select($select);
            }
            else
              this.show_free_form();
        },
        show_free_form: function()
        {
          var $select = this.get_select();

          if ($select.length == 1)
            this.remove_select($select);
 
          var $free_form = this.get_free_form();

          if ($free_form.length == 0)
            if (this.free_form_text != undefined) {
              this.section.append(this.free_form_text.clone());
            }
        },
        init_select: function()
        {
          var $free_form = this.get_free_form();

          if ($free_form.length == 1)
            $free_form.remove();

          var $select = this.get_select();

          if ($select.length == 1)
            this.remove_select($select);   // Need to create a new one or data won't change

          $select = this.element.clone();
          this.section.append($select);
          return $select;
        },
        remove_select: function($select)
        {
          var $textbox = this.get_select_textbox();
          var select_typeahead = $('#state-selector-typeahead-container');

          if ($textbox != undefined && $textbox.length != 0)
            $textbox.remove();

          if($select != undefined) {
            $select.remove();
          }
          select_typeahead.remove();
        },
        show_select: function($select)
        {
          if (App.controls.supports_select_to_autocomplete())
          {
            // Add spelling suggestions and relevancy boost
            if (typeof(State_Data) != 'undefined' && State_Data != null)
            {
              $.each(State_Data.selector_data, function(key, value) {
                var $option = $('option[text="' + key + '"]', $select);

                if ($option != null && $option.length == 1)
                {
                  $.each(value, function(key, value) {
                    $option.attr(key, value);
                  });
                }
              });
            }

            $('#StateProvince').addClass('hide');

            if($('#StateText') != undefined && !$('#StateText').is(":visible")) {
              $('#state-selector').prepend('<div id="state-selector-typeahead-container" class="input-prepend add-on-block span11"><span class="add-on"><i class="icon-search"></i></span><input type="text" autocomplete="off" name="StateText" id="StateText" /></div>');
            }

            var selectedState = $("#StateProvince option:selected").val();
            if(selectedState) {
            	$('#StateText').val(selectedState);
        	}
            
            /*$select.selectToAutocomplete();
            var $textbox = $select.siblings(".ui-autocomplete-input");

            if ($textbox.length != 0)
              $textbox.attr({'id': 'CountryText', 'name': 'CountryText'});*/
            //create dropdown array list from hidden select box
            var states = {},
                items   = [];
            $('#StateProvince option').each( function(i,o) {
              var $o = $(o);
              items.push( $o.text() );
              states[ $o.text() ] = { name: $o.text(), id: $o.attr('value'), spellings: $o.data('alternative-spellings')  };

              states[ $o.text() ]['relevancy-score'] = 0;
              states[ $o.text() ]['relevancy-score-booster'] = 1;
              var boost_by = parseFloat( $o.data('relevancy-booster') );
              if ( boost_by ) {
                states[ $o.text() ]['relevancy-score-booster'] = boost_by;
              } 
            });
            // init typeahead
            $($select.data('related')).typeahead({
                source: items,
                matcher: function (item) {
                  var all_spellings = [item],
                      alt_spellings = states[item].spellings,
                      t             = this,
                      match         = false;

                  if( alt_spellings )
                  {
                    $(alt_spellings.split(' ')).each(function(i,x){ all_spellings.push(x) } );
                  }

                  $( all_spellings ).each( function(i, it) {
                    if (it.toLowerCase().indexOf(t.query.trim().toLowerCase()) != -1) {
                      match = true;
                    }
                  });
                  return match;
                },
                sorter: function (items) {
                  var list = [], sorter = [], sorted = [];

                  $(items).each(function(i,a){
                    list.push( states[a] );
                  });

                  sorter = list.sort(function( a, b ) { return b['relevancy-score-booster'] - a['relevancy-score-booster'] })
                  $( sorter ).each(function(i,x){ sorted.push(x.name) } );

                  return sorted;
                },
                highlighter: function (item) {
                  $('#EmployerNameText').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
                  var regex = new RegExp( '(' + this.query + ')', 'gi' );
                  return item.replace( regex, "<strong>$1</strong>" );
                },
                updater: function(item)
                {
                  $('#StateProvince').val(states[item].id).change();
                  return item;
                }
            });
            //$select.selectToAutocomplete();
            /*var $textbox = this.get_select_textbox();

            if ($textbox.length != 0)
              $textbox.attr({'id': 'State', 'name': 'State'});
              */
          }
        }
      },
      phone_view: {
        UNITED_STATES: 217,
        initialized: false,
        init: function() {
            var pv = this;
            if (pv.initialized)
                return;

            $(".change-country-code-link").click(function () {
                $("#" + $(this).attr("data-labelid")).hide();
                $("#" + $(this).attr("data-textboxid")).show();
                $(this).hide();
                return (false);
            });    

            pv.initialized = true;
        },
        country_changed: function(countryId) {
            if (countryId == 217) {
                $(".countrycode-fields").hide();
            } else {
                $(".countrycode-fields").show();
            }
        }
      }
    }
  }
}
jQuery.fn.preventDoubleClick = function()
{
  jQuery(this).click(function() {
    $(this).css("pointer-events", "none");
  });
};
;
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}


if (jQuery) {
    /* for instantiating tooltips across the site; currently, the only
     * tooltip is on the login page. If it becomes a more widely used
     * feature, uncomment the line below and **remove instantiation**
     * from the session.new init function*/
    //$('[data-toggle="tooltip"]').tooltip()
    /* Doing the full error logging that injects code into every function causes
       errors in refinements view more and clicking on refinement link causes 
       the refinement box to be dragged and can't drop it
    */
    //$.innovadex.handleErrors.init();
    var errorLoggingEnabled = true;

    window.onerror = function (msg, url, line) {
        msg = msg + " (likely on page init)";
        $(document).trigger('client_error', [msg, null, line]);
    };

    window.beforeunload = function () {
        errorLoggingEnabled = false;
    };

    $(document).on('click', '[data-slide="toggle"]', function (e) {
        e.preventDefault();
        $($(this).data('target')).slideToggle();
    });

    $(document).on('click', '[data-fade="toggle"]', function (e) {
        e.preventDefault();
        $($(this).data('target')).fadeToggle();
    });

    $(document).on('click', '[data-function="smooth-scroll"] a, a[data-function="smooth-scroll"]', function (e) {
        e.preventDefault();
        var $target = $(this).attr("href") == "#" ? $('body') : $($(this).attr("href"));
        //console.log($target);
        //console.log($target.offset().top);
        $('html, body').animate({
            scrollTop: $target.offset().top
        }, 800);
    });

    $(document).bind('client_error', function (evt, message, stack, line, source, code) {
        if (!errorLoggingEnabled) {
            return;
        }

        url = window.location.href;
        var data = "type=js&message=" + escape(message);

        if (typeof stack != 'undefined' && stack != null && stack.length != 0)
            data = data + "&stack=" + escape(stack.replace(/[<>]*/g, ''));

        if (typeof url != 'undefined' && url != null)
            data = data + "&url=" + escape(url)

        if (typeof line != 'undefined' && line != null)
            data = data + "&line=" + escape(line);

        if (typeof source != 'undefined' && source != null)
            data = data + "&source=" + escape(source);

        if (typeof code != 'undefined' && code != null)
            data = data + "&code=" + escape(code.replace(/[<>]*/g, ''));

        // Commenting out because these errors fill exception log and are fairly worthless. Can uncomment
        // if need in the future
        // $.post('/errors', data);
    });

    var DesktopApp = {
        fixedResponsiveTable: function () {
            var $table = $('.fixed-responsive-table');
            //Make a clone of our table
            var $fixedColumn = $table.clone().insertBefore($table).addClass('fixed-column');

            //Remove everything except for first column
            $fixedColumn.find('th:not(:first-child),td:not(:first-child)').remove();

            //Match the height of the rows to that of the original table's
            $fixedColumn.find('tr').each(function (i, elem) {
                $(this).height($table.find('tr:eq(' + i + ')').height());
                $(this).width($table.find('tr:eq(' + i + ')').width());
            });
        },
        Defaults: {
            AutoCompleteDelay: App.defaults.AutoCompleteDelay
        },
        siteId: null,
        regionId: null,
        cybraryId: null,
        searchOrder: null,
        parentSearchLogId: null,
        textSearchBaseUrl: null,
        regionUrlParam: null,
        cybraryUrlParam: null,
        isPinningEnabled: false,
        scrollbarWidth: 0,
        supportsAutoGrow: true,
        tour:
            {
                publictourUrl: "",
                authtourUrl: "",
                addRequest: true,
                altauth: true,
                publictour_steps: [
                    {
                        element: '#industrylist li:has(a[data-cid="11"])',
                        placement: $('.touch').length > 0 ? "right" : "bottom",
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_industry_list_title', "Choose an Industry") + "</h4>" + $.innovadex.get_translation('pub_tour_industry_list_content', 'Choose the industry where you want to search. <span class="hidden-touch">Hover over the industry name to see some of the search facets available.</span>'),
                        onShow: function (tour) {
                            if ($('.touch').length < 1) {
                                $('a[data-cid="11"]').parent('li').trigger('mouseout').trigger('mouseenter');
                            }
                        }
                    },
                    {
                        element: '#k',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_search_box_title', 'Search By Keyword') + "</h4>" + $.innovadex.get_translation('pub_tour_search_box_content', "As you enter your keyword, our auto-complete will help you quickly identify what you're looking for."),
                        path: '',
                        onShow: function (tour) {
                            DesktopApp.tour.setPath(tour, 0, "/?f=true")
                        }
                    },
                    {
                        element: '#bookType li:first-child a',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_refine_search_title', 'Refine Your Search') + "</h4>" + $.innovadex.get_translation('pub_tour_refine_search_content', "Innovadex organizes content in a variety of ways so you can choose the search properties that will best narrow down your results."),
                        path: ""
                    },
                    {
                        element: "#searchresultslist li:first h5>a:first-child, #searchresultstable .bookcol:first > a:first-child",
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_results_title', "Locate Products") + "</h4>" + $.innovadex.get_translation('pub_tour_results_content', "Browse the search results to find the listings that fit your needs."),
                        path: "/Product",
                        onShow: function (tour) {
                            DesktopApp.tour.setPath(tour, 4, "#searchresultslist li:first h5>a:first-child, #searchresultstable .bookcol:first > a:first-child")
                        }
                    },
                    {
                        element: ".main-documents ul.unstyled:first-of-type li > a:first-of-type",
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_detail_docs_title', "View Documents") + "</h4>" + $.innovadex.get_translation('pub_tour_detail_docs_content', "Download MSDSs, TDSs, brochures, formulations and more."),
                        placement: "right"
                    },
                    {
                        element: ".details",
                        placement: "left",
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('pub_tour_detail_actions_title', "Do More") + "</h4>" + $.innovadex.get_translation('pub_tour_detail_actions_content', "Once you log in, you can request a sample, get help from the supplier or save the item to your bookmarks. <p class='text-center extra-margin-top'><a href=\"/users/new\" class=\"btn btn-primary\">Register Today</a></p>")
                    }
                ],
                authtour_steps: [
                    {
                        element: '#k',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_search_box_title', 'Search By Keyword') + "</h4>" + $.innovadex.get_translation('auth_tour_search_box_content', "As you enter your keyword, our auto-complete will help you quickly identify what you're looking for."),
                        path: ''
                    },
                    {
                        element: '#ProdType li:first-child a',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_refine_search_title', 'Search Within Results') + "</h4>" + $.innovadex.get_translation('auth_tour_refine_search_content', "Or, you can start browsing by choosing a category type."),
                        path: ''
                    },
                    {
                        element: '#savesearch',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_save_search_title', 'Save Searches') + "</h4>" + $.innovadex.get_translation('auth_tour_save_search_content', 'Save your most common or most complex searches for easy and quick results.'),
                        path: "/Product"
                    },
                    {
                        element: 'a[data-action-event="Add to Sample Cart"]:first',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_sample_req_title', "Request Samples") + "</h4>" + $.innovadex.get_translation('auth_tour_sample_req_content', "Browse through results, and quickly make Sample Requests when you find the items you want."),
                        path: "/Product"
                    },
                    {
                        element: 'td.btn-cell:has(a[data-action-event=\"Add to Sample Cart\"]) + td.bookcol:first a:first, #searchresultslist h5:first a:first',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_results_title', "Locate Products") + "</h4>" + $.innovadex.get_translation('auth_tour_results_content', "Browse the search results to find the listings that fit your needs."),
                        path: "/Product",
                        onShow: function (tour) {
                            DesktopApp.tour.setPath(tour, 5, 'td.btn-cell:has(a[data-action-event=\"Add to Sample Cart\"]) + td.bookcol:first a:first,  #searchresultslist h5:first a:first')
                        }
                    },
                    {
                        element: ".main-documents ul.unstyled:first-of-type li > a:first-of-type",
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_detail_docs_title', "View Documents") + "</h4>" + $.innovadex.get_translation('auth_tour_detail_docs_content', "Download MSDSs, TDSs, brochures, formulations and more."),
                        placement: "right"
                    },
                    {
                        element: "#sample_cart_link,#detailLinkToSampleRequest:visible a",
                        placement: 'left',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_detail_req_title', "Request Samples") + "</h4>" + $.innovadex.get_translation('auth_tour_detail_req_content', "Request a sample once you've learned more about the product you've found."),
                        onShow: function (tour) {
                            /*if(! tour._options.storage.getItem('authtour_detailRequestAdded') )
                            {
                              var x = window.setTimeout( function(){ 
                                $('#sample_cart_link').trigger('click');
                              }, 5000 );
            
                              DesktopApp.tour.setStorageItem(tour, 'authtour_detailRequestAdded', true);
                            }*/

                            //skip to step 10(9) if no samples in cart; do this by not setting the path to samplerequest
                            if (!DesktopApp.tour.altauth) {
                                DesktopApp.tour.setPath(tour, 7, '#detailLinkToSampleRequest a');
                                DesktopApp.tour.setStorageItem(tour, 'authtour_detail_returnUrl', document.location.pathname);
                            }
                        }
                    },
                    {
                        element: "#sample-create-form",
                        placement: 'top',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_req_submit_title', "Submit Your Request") + "</h4>" + $.innovadex.get_translation('auth_tour_req_submit_content', "Complete your request to receive the samples you need."),
                        onShow: function (tour) {
                            var returnPath = tour._options.storage.getItem('authtour_detail_returnUrl') || 'a[data-class="bookDetail"]:first';
                            //if there are no valid return options, something's
                            //off in the flow of the tour, and it'll be better to
                            //just end things
                            if ("undefined" == typeof returnPath || returnPath == null) {
                                tour.end();
                                return;
                            }
                            DesktopApp.tour.setPath(tour, 6, returnPath);

                            //tour._steps[7]["element"] = "a[href^='" + returnPath.substring(0, returnPath.lastIndexOf('/')) + "']:first";

                            //window.tour = tour;
                        }
                    },
                    {
                        element: 'a[data-class="bookDetail"]:first ~ .sample_create_bookmark',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_save_later_title', "Save the Item for Later") + "</h4>" + $.innovadex.get_translation('auth_tour_save_later_content', "If you're not ready to receive the sample, you can save it for later by adding a bookmark."),
                        onNext: function (tour) {
                            $('#step-8').addClass('in').removeClass('out');
                        },
                        onPrev: function (tour) {
                            $('#step-8').addClass('in').removeClass('out');
                        },
                        onEnd: function (tour) {
                            $('#step-8').addClass('in').removeClass('out');
                        }
                    },
                    {
                        element: ".topmenu",
                        placement: 'left',
                        title: $.innovadex.get_translation('tour_header', "Get To Know Innovadex"),
                        content: "<h4>" + $.innovadex.get_translation('auth_tour_my_menu_title', "More Great Features") + "</h4>" + $.innovadex.get_translation('auth_tour_my_menu_content', "Check out more great features, including bookmarks, saved searches and more!"),
                        onShow: function (tour) {
                            /* note: the corresponding step id is set to visibility: hidden in base.css in order to allow
                             * the dropdown menu to open first. if the number of steps change, the css step id must be modified as well */
                            var i = DesktopApp.tour.altauth ? 7 : 9;
                            $('.topmenu > li > a[data-toggle="dropdown"]').trigger('click');
                            var x = window.setTimeout(function () {
                                if ($('#auth-user-menu').offset().left == 0) {
                                    $('.topmenu > li > a[data-toggle="dropdown"]').trigger('click');
                                }
                                var l = $('#auth-user-menu').offset().left,
                                    w = $('#step-' + i).width(),
                                    t = $('#auth-user-menu').offset().top,
                                    m = l - w;
                                $('#step-' + i + ' .arrow').css({'top': '50%'});
                                $('#step-' + i).removeClass('in').addClass('out').css({'left': m, 'top': t, 'visibility': 'visible'}).removeClass('out').addClass('in');
                            }, 300);
                        }
                    }
                ],
                init: function (page) {

                    DesktopApp.tour.altauth = (!isNaN(parseInt($("span[data-samplecart-total-items]").html())) && parseInt($("span[data-samplecart-total-items]").html()) > 0) || document.location.href.indexOf('samplerequest') != -1 ? false : true;

                    Tour.prototype._scrollIntoView = function (tip) {
                        var t = tip.offset().top,
                            bt = tip.offset().top + tip.height(),
                            b = $("body").height(),
                            s = $("body").scrollTop();

                        if (bt > b || t < s) {
                            $('body').scrollTo(tip)
                        }
                    };

                    if (DesktopApp.tour.altauth) {
                        var steps = DesktopApp.tour.authtour_steps.slice(0, 7);
                        steps.push(DesktopApp.tour.authtour_steps[9]);
                        DesktopApp.tour.authtour_steps = steps;
                    }

                    var authtour, publictour, tours = {"authtour": authtour, "publictour": publictour};
                    for (var n in tours) {
                        $.each(DesktopApp.tour[n + "_steps"], function (i, x) {
                            var z = DesktopApp.tour[n + "Url"], p;
                            if ("" == x.path) {
                                x.path = z;
                            } else if ("undefined" != typeof x.path) {
                                //p = z.lastIndexOf("/") == z.length-1 ? "" : "/";
                                x.path = z + x.path;
                            }
                        });

                        tours[n] = new Tour({
                            debug: false, name: n, container: "#wrapper>.span12",
                            onStart: function (tour) {
                                if (tour._options.storage.getItem("tour_start_page") == null) {
                                    tour._options.storage.setItem("tour_start_page", window.location.href)
                                }
                                $('html').off('click');
                            },
                            onShown: function (tour) {
                                $('html').off('click').on('click', function (ev) {
                                    if ("startauthride" != ev.target.id && "startride" != ev.target.id) {
                                        if ("userdropdownmenu" == ev.target.id && (tour._current == 9 || tour._current == 7)) {
                                            return true;
                                        } else {
                                            DesktopApp.tour.suppressEndRedirect = true;
                                            tour.end();
                                        }
                                    }
                                });
                                $('.authtour.popover, .publictour.popover').click(function (event) {
                                    if ($(event.target).hasClass('btn')) {
                                        $('html').off('click');
                                    } else {
                                        event.stopPropagation();
                                    }
                                });
                            },
                            onEnd: function (tour) {
                                if (!DesktopApp.tour.s) {
                                    $('html').off('click');
                                    $('#startauthride').show();
                                    var returnUrl = tour._options.storage.getItem("tour_start_page");
                                    if (returnUrl != null && returnUrl.indexOf("tour=1") != -1) {
                                        var result = {},
                                            params = (returnUrl.split('?')[1] || '').split('&');
                                        for (var param in params) {
                                            if (params.hasOwnProperty(param)) {
                                                var paramParts = params[param].split('=');
                                                if (paramParts[0] != "tour") {
                                                    result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
                                                }
                                            }
                                        }

                                        returnUrl = returnUrl.split('?')[0] + "?" + $.param(result);
                                    }

                                    tour._options.storage.removeItem("tour_start_page");
                                    DesktopApp.tour.s = false;
                                    var currentLocation = window.location.hostname + window.location.pathname;
                                    if (returnUrl.indexOf(currentLocation) == -1 && !DesktopApp.tour.suppressEndRedirect) {
                                        window.location.href = returnUrl;
                                    }
                                }
                            },
                            template: "<div class='popover tour " + n + (DesktopApp.tour.altauth ? " alternate" : "") + ("en" != languageCode ? " lang" : "") + "'>" +
                                "<div class='arrow'></div>" +
                                "<h3 class='popover-title'></h3>" +
                                "<div class='popover-content'></div>" +
                                "<div class='popover-navigation'>" +
                                "<div class='btn-group'>" +
                                "<button class='btn btn-default btn-inverse' data-role='prev'>« " + $.innovadex.get_translation('tour_nav_prev', 'Prev') + "</button>" +
                                "<button class='btn btn-default btn-inverse' data-role='next'>" + $.innovadex.get_translation('tour_nav_next', 'Next') + " »</button>" +
                                "</div>" +
                                "<button class='btn btn-default btn-inverse' data-role='end'>" + $.innovadex.get_translation('tour_nav_end', 'End Tour') + "</button>" +
                                "</div>" +
                                "</div>"
                        });

                        tours[n].addSteps(DesktopApp.tour[n + "_steps"]);

                        if (!tours[n].ended() && tours[n]._options.storage.getItem(n) != null) {
                            tours[n].start();
                        }
                    }

                    function startRide(tourname, endtourname) {
                        var tour = tours[tourname], endtour = tours[endtourname];
                        endtour.end(); //just in case
                        endtour._options.storage.removeItem(endtourname);

                        tour._current = 0;
                        tour._options.storage.setItem(tourname + "_current_step", "0");
                        tour._options.storage.setItem(tourname, "started");

                        if (tour.ended()) {
                            tour.restart();
                        } else {
                            tour.start(true);
                        }
                    }

                    var n_tour = authenticated ? "authtour" : "publictour",
                        o_tour = authenticated ? "publictour" : "authtour";

                    if (window.location.href.indexOf("tour=1") != -1) {
                        DesktopApp.tour.s = true;
                        startRide(n_tour, o_tour);
                    }

                    $('#startride').click(function (e) {
                        e.preventDefault();
                        DesktopApp.tour.s = true;
                        startRide(n_tour, o_tour);
                    });

                    $('#startauthride').click(function (e) {
                        e.preventDefault();
                        DesktopApp.tour.s = true;
                        startRide("authtour", "publictour");
                    });

                },
                setPath: function (tour, step, el) {
                    var path;
                    try {
                        //console.log('trying to get element');
                        //console.log($(el));
                        path = $(el).attr('href') || el;
                        //console.log(path);
                    } catch (e) {
                        path = el;
                    }
                    tour._steps[step]["path"] = path;
                },
                setStorageItem: function (tour, key, val) {
                    tour._options.storage.setItem(key, val);
                }
            },
        defaults:
            {
                pageNotificationTime: 8000
            },
        initPage: function (page_name) {
            //console.log( page_name );
            $body = $("body");

            // following is used to initialize page and run scripts
            if (page_name != null && page_name.length > 0) {
                var page = null;
                try {
                    page = DesktopApp.pages[page_name.split('.')[0]][page_name.split('.')[1]];
                    //page = eval("DesktopApp.pages." + page_name);
                } catch (err) {
                    //ignore
                }

                // Peform initializations that any page should perform
                $('HTML').addClass('JS');
                DesktopApp.utils.initAudioPlayer();
                DesktopApp.utils.initMyStuffBar($body);
                DesktopApp.utils.initSalesApp($body);
                DesktopApp.utils.initKeywordSuggestions($body);
                DesktopApp.utils.initKeywordAutocomplete($body);

                $("#cybraries").on('change', function (evt) {
                    var selItem = $("#cybraries option:selected").first();
                    var url = selItem.attr("value");
                    $.innovadex.redirectToUrl(url);
                });

                $("form.ajaxify").on('submit', function () {
                    return ajaxifyForm($(this), $(this).attr('onsuccess'));
                });

                $("a[data-change-language]").click(function (evt) {
                    var langId = $(this).attr("data-change-language");
                    var regId = $(this).attr("data-region");
                    selectLanguage(langId, regId);
                    evt.preventDefault();
                });

                $("[data-list-swap]").on("click", function (evt) {
                    evt.preventDefault();

                    var $this = $(this),
                      list_id = $this.attr("data-list-id"),
                      trigger = $this[0].dataset["trigger"],
                      triggerControls;

                    var main_list = $("#" + list_id);
                    var alt_list = $("#" + main_list.attr("data-list-alt"));
                    const show_main_list = main_list.hasClass("hide");

                  if (show_main_list) {
                    alt_list.addClass("hide");
                    main_list.removeClass("hide");
                    triggerControls = list_id;
                  } else {
                    main_list.addClass("hide");
                    alt_list.removeClass("hide");
                    triggerControls = main_list.attr("data-list-alt");
                  }

                  if (trigger) {
                    $(trigger).attr("aria-controls", triggerControls);
                  }

                    const swapLinks = getRefinementListSwapLinks(list_id);
                    for (let i = 0; i < swapLinks.length; i++) {
                        const link = swapLinks[i];
                        if (show_main_list) {
                            link.classList.remove("expand-less");
                            link.classList.add("expand-more");
                        } else {
                            link.classList.remove("expand-more");
                            link.classList.add("expand-less");
                        }
                    }
                });

                $("form[data-property-text-type]").submit(function () {
                    var property = $(this).attr('data-property-text-type');
                    var action = "Text Property Search - " + property;
                    var label = null;
                    var $term = $("#" + property);

                    if ($term.length != 0)
                        label = $term.val();
                    $.innovadex.tracking.trackEvent("Search", action, label);
                });

                $("#idesLanguageModal").on('show.bs.modal', function (e) {
                    var fromLink = e.relatedTarget;
                    var modal = $(this);

                    var url = $(fromLink).attr('href');
                    var engUrl = url.replace('/zh-tw', '/en');
                    var simplifiedUrl = url.replace('/zh-tw', '/zh-cn');

                    $("a[data-language='en']", modal).first().attr('href', engUrl);
                    $("a[data-language='zh-cn']", modal).first().attr('href', simplifiedUrl);
                });

                $("#innovadexLanguageModal").on('show.bs.modal', function (e) {
                    var fromLink = e.relatedTarget;
                    var modal = $(this);

                    var url = $(fromLink).attr('href');
                    var engUrl = url.replace('/ja', '/en');

                    $("a[data-language='en']", modal).first().attr('href', engUrl);
                });

                if (page != null) {
                    if (page['isInitialized'] == null) {
                        page['isInitialized'] = true;   // Set early so that javascript error doesn't make it to continue to be called

                        // Perform initializations specific to this page
                        var params = null;
                        var $param_element = $("#page_params");

                        if ($param_element != null) {
                            var param_html = $.trim($param_element.html());

                            if (param_html.length > 0) {
                                param_html = '(' + param_html + ')';
                                params = eval(param_html);
                            }
                        }

                        // Set any app variables from params
                        if (params != null) {
                            if ("searchOrder" in params)
                                DesktopApp.searchOrder = params.searchOrder;

                            if ("parentSearchLogId" in params)
                                DesktopApp.parentSearchLogId = params.parentSearchLogId;

                            if ("textSearchBaseUrl" in params) {
                                DesktopApp.textSearchBaseUrl = params.textSearchBaseUrl;
                                //DesktopApp.pages.search.setupKeyword();
                            }

                            if ("regionUrlParam" in params)
                                DesktopApp.regionUrlParam = params.regionUrlParam;

                            if ("cybraryUrlParam" in params)
                                DesktopApp.cybraryUrlParam = params.cybraryUrlParam;
                        }
                        page.init($body, params);
                    }
                }
            }
        },
        pages: {
            referral: {
                new_view: {
                    init: function (context, params) {

                        var currentEmailCount = 1;

                        jQuery.validator.addClassRules("referral_email", {
                            required: true,
                            email: true
                        });

                        $("#send_referral_form").validate({
                            onkeyup: false,
                            onclick: false,
                            onfocusout: false,
                            errorPlacement: function (error, element) {
                                //error.appendTo(element.parent('div'));
                            },
                            submitHandler: function (form) {
                                // all email inputs require a unique name for jquery validation to work, remove the unique attributes once valid and submitting
                                $(form).find(":input[name*='[']").each(function () {
                                    this.name = this.name.replace(/\[\d+\]/, '');
                                });

                                form.submit();
                            },
                            invalidHandler: function (event, validator) {
                                $('#referral_errors').removeClass('hide');
                                $("html, body").animate({scrollTop: 0}, "fast");
                            }
                        });

                        var checkEmailRemovalButton = function () {
                            if ($('.referral_email').length > 1) {
                                $(".remove_referral_email_btn").removeAttr("disabled");
                                $(".remove_referral_email_btn").show();
                                $('.email_input_div ').addClass('input-append mobile-add-on-block tablet');
                            } else {
                                $(".remove_referral_email_btn").attr("disabled", "disabled");
                                $(".remove_referral_email_btn").hide();
                                $('.email_input_div ').removeClass('input-append mobile-add-on-block tablet');
                            }
                        };

                        var setRemovalButtonClick = function () {
                            $(this).parent('div').remove();
                            checkEmailRemovalButton();
                        };

                        $(".remove_referral_email_btn").click(setRemovalButtonClick);

                        $('#add_new_referral_email').click(function (evt) {
                            evt.preventDefault();

                            //var currentEmailCount = $('.referral_email').length;
                            currentEmailCount++;

                            var emailInput = $('<div class=email_input_div "input-append mobile-add-on-block tablet" style="display: block;"><input type="text" name="email[' + currentEmailCount + ']" id="email_' + currentEmailCount + '" class="input-xlarge referral_email" placeholder="email"/><button class="btn remove_referral_email_btn" type="button"><i class="icon-trash"></i></button></div>');
                            emailInput.insertBefore(this);

                            $(".remove_referral_email_btn").click(setRemovalButtonClick);
                            checkEmailRemovalButton();

                            setupValidation();
                        });
                    }
                }
            },
            site_master: {
                resetModal: function () {
                    var $modal = $('#modal');
                    $('#myModalLabel', $modal).text('');
                    $modal.removeData('modal');
                    $('.modal-body', $modal).html('<div class="progress progress-striped active pull-left collapse-bottom" style="width: 100%"><div class="bar" style="width: 1%"></div></div><p id="modal-alert" style="display: none;"></p>');
                    $('.modal-footer', $modal).html('');
                    $modal.off('hidden');
                }
            },
            services: {
                materialsingredients_view: {
                    init: function (c, p) {
                        $('[data-toggle="popover"]').popover();

                        $('#imagemodal').on('show.bs.modal', function (e) {
                            var $o = $(e.relatedTarget);
                            $('.popupcontent', this).hide();
                            if ($o.data('update') == 'previewimage') {
                                var src = $o.data('content');
                                $('.imagepreview').attr('src', src).show();
                            } else {
                                $($o.data('update')).show();
                            }
                        });

                        $('button[data-tofeatures]').click(function () {
                            $.scrollTo('#pfeaturelist,#mifeaturelist', 400, {axis: 'y'})
                        });
                        $('#toEarlyInsights').click(function () {
                            $.scrollTo('#eiMarketing', 400, {axis: 'y'})
                        });
                    }
                },
                solidmaterials_view: {
                    init: function (c, p) {
                        //All functionality mirrored by foodchem
                        DesktopApp.initPage("services.materialsingredients_view");
                    }
                }
            },
            search: {
                performsearch_view: {
                    init: function (context, params) {
                        DesktopApp.pages.search.initSalesAppFolderSelection(context);

                        var p = $('[data-toggle="popover"]').popover();
                        $('img.thumbnail').each(function (i, x) {
                            $(x).attr('src', $(x).data('image-src'));
                        });
                        // removed tooltip as it causes problems on mobile devices currently. 10-23-13, Adam
                        // we could add detection to only use on desktop, but doesn't seem critical enough for that.
                        //$('.sample_tooltip').tooltip();
                        $('.tip').tooltip({trigger: 'click', placement: 'right'});
                        $('.tip').click(function (e) {
                            // Prevent href # being run
                            e.preventDefault();
                        })

                        $('.refine-opener').click(function () {
                            DesktopApp.utils.toggleHiddenMobileView($('nav#refinements'));
                        });

                        $("#otherIndustryResults ul li a").on('click', refinementLink_clicked);

                        $('#savesearchpopup').on('hidden', function () {
                            $('#savesearchform .progress').addClass('hide');
                        });

                        $('#savesearchform').submit(function (ev) {
                            ev.preventDefault();

                            var valid = true,
                                name = $('#SaveSearchName').val();

                            if (name.length < 1 || name.length > 50) {
                                var txt = name.length < 1 ? emptySavedSearchMsg : maxLengthSavedSearchMsg;
                                $('#save-search-error').text(txt);
                                $('#save-search-error').show();
                                $('#save-search-control').addClass('error');
                                valid = false;
                                return (false);
                            } else {
                                //clear out any previous errors
                                valid = true;
                                $('#save-search-control').removeClass('error');
                            }

                            if (valid) {
                                var progress;

                                $.ajax({
                                    type: "POST",
                                    url: window.location.href,
                                    data:
                                        {
                                            regionId: $('#regionId').val(),
                                            cybraryId: $('#cybraryId').val(),
                                            name: $('#SaveSearchName').val(),
                                            isAlert: $("#isAlert").is(':checked'),
                                            searchTypeId: $('#searchType').val()
                                        },
                                    beforeSend: function () {
                                        $('#savesearchform .progress').removeClass('hide');
                                        var current_perc = 0;
                                        progress = setInterval(function () {
                                            if (current_perc >= 100) {
                                                current_perc = 0;
                                            } else {
                                                current_perc += 1;
                                                $('#savesearchform .progress .bar').css('width', (current_perc) + '%');
                                            }
                                        }, 50);
                                    },
                                    success: function (response) {
                                        //complete loading animation
                                        $('#savesearchform .progress .bar').css('width', '100%');
                                        clearInterval(progress);
                                        //onhide to hide progress bar on completion set on modal popup

                                        //remove the list from the top submenu
                                        $('.searches-opener').removeData('populated-list');
                                        var penultimate = $('#mysearches .divider'),
                                            ultimate = $('#mysearches .divider + li ');
                                        $('#mysearches').html('<li class="text-center"><img src="//localimages.innovadex.com/Search/loading.gif" alt="loading" style="height:16px;width:16px"></li>').append(penultimate).append(ultimate);

                                        //close the popup
                                        $('#savesearchpopup').modal('hide');

                                        //add success message to the results page
                                        $('#page-notifications').removeClass('hide');
                                        var notify = setTimeout(function () {
                                            $('#page-notifications').slideUp(500);
                                        }, 4000);

                                        /*$('#savedsearch_saving').hide();
                                        if (savedSearchSuccess == null || savedSearchSuccess.length == 0)
                                            savedSearchSuccess = 'Successfully saved your search';
    
                                        showNotification(savedSearchSuccess, 4000);*/
                                    },
                                    error: function (msg, textStatus, errorThrown) {
                                        //show error message in the popup
                                        showErrorMsg(msg + " " + textStatus);
                                    }
                                });

                                try {
                                    $.innovadex.tracking.trackEvent("Actions", "Save Search");
                                } catch (ex) { /* Do Nothing */
                                }

                                return (true);//
                                //$('#savedsearch_saving').show();
                            }
                        });

                        function fauxSubmit() {
                            $('.btn', '#categoryForm').attr('disabled', 'disabled');
                            $('.modal-body', '#categoryForm').prepend('<div class="update"><i class="fa fa-spinner fa-pulse fa-2x"></i></div>');
                        }

                        $('#categoryForm').on('show.bs.modal', function (event) {
                            var $link = $(event.relatedTarget);
                            $('.modal-header h4', '#categoryForm').html($link.text());

                            if ($link[0] == $('#category_info_destroy')[0]) {
                                var newlink = '<a href="' + $link.attr('href') + '" class="btn btn-custom" id="categoryinfo_delete">Delete</a>';
                                $('.modal-body', '#categoryForm').after('<div class="modal-footer">' +
                                    '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
                                    newlink + '</div>');
                                $('.modal-body', '#categoryForm').html('<p class="text-center"><strong>Are you sure you want to remove this category text?<br>This action cannot be undone.</strong></p>');
                            } else {
                                $('.modal-body', '#categoryForm').load($link.attr('href'));
                            }
                        });

                        $(document).on('click', '#categoryinfo_form_cancel', function (ev) {
                            $('#categoryForm').modal('hide');
                        });


                        $(document).on('click', '#categoryinfo_form_submit', function () {
                            fauxSubmit();
                            ajaxifyForm($('#categoryinfo_form'), "refreshWindow();");
                            return (false);
                        });

                        $(document).on('click', "#categoryinfo_delete", function (evt) {
                            evt.preventDefault();
                            fauxSubmit();
                            $.ajax({
                                url: $('#category_info_destroy').attr('href'),
                                type: "post",
                                data: {_method: "delete"},
                                dataType: "json",
                                success: function (msg) {
                                    window.refreshWindow();
                                }
                            });
                        });

                        $("#category-read-more").click(function (evt) {
                            evt.preventDefault();
                            $link = $(this);

                            $("#" + $link.attr('data-readmoreid')).show('fast');
                            $link.hide();
                        });

                        $("#category-read-less").click(function (evt) {
                            evt.preventDefault();
                            $link = $(this);

                            $("#" + $link.attr('data-readmoreid')).hide('fast');
                            $("#category-read-more").show();
                        });

                        /*if( window.localStorage )
                          DesktopApp.tour.init();*/
                    },
                    sample_added: function (result, linkid, confirmationElement) {
                        var $link = $('#' + linkid);

                        if ($link != null && $link.length != 0) {
                            var $parent = $link.parent();
                            $link.tooltip("hide");
                            $link.remove();
                        }

                        var confirmationElementToShow = $('#' + confirmationElement);
                        if (confirmationElementToShow != undefined) {
                            confirmationElementToShow.show();
                        }
                        ;

                        if ($('#mobileSampleCartLink')) {
                            $('#mobileSampleCartLink').removeClass('disabled');
                        }
                    },
                    sample_added_in_tabular_view: function (result, linkid, confirmationElement) {
                        var $link = $('#' + linkid);

                        if ($link != null && $link.length != 0) {
                            var $parent = $link.parent();
                            $link.tooltip("hide");
                            $link.remove();
                        }

                        var confirmationElementToShow = $('#' + confirmationElement);
                        if (confirmationElementToShow != undefined) {
                            confirmationElementToShow.show();

                            if (confirmationElementToShow.is("tr")) {
                                confirmationElementToShow.closest('tr').next('tr').removeClass('result_detail_row_bordered').addClass('result_detail_row');
                            }
                        }
                        ;
                    }
                },
                showdetail_view: {
                    tracked: {},
                    init: function (context, params) {
                        $('#submit_purchase_confirmation_modal').click(function (evt) {
                            var submitButton = $(evt.target);
                            submitButton.attr("disabled", "disabled");

                            $.ajax({
                                method: "GET",
                                url: submitButton.data('purchaseUrl'),
                                dataType: "json"
                            })
                                .done(function (response) {
                                    var form = $('#purchase-form');
                                    var formField = $('#purchase-form > input[name="jwt"]');

                                    formField.val(response.token);
                                    form.submit();
                                })
                                .fail(function () {
                                    console.error('Unable to get token');

                                    submitButton.prop("disabled", true);
                                    submitButton.removeAttr("disabled");
                                })
                                .always(function () {
                                    console.log('inside always');
                                });
                        });

                        $('#regDocs').on('show.bs.modal', function (e) {
                            $(this).addClass($(e.relatedTarget).data('regtype'));
                        });

                        function setIt(reset) {
                            var times = reset ? 1 : $('#multiples').val();
                            $('span[data-type="measure"]', '.nutritional').each(function (i, x) {
                                var $v = $(x).data('value'),
                                    nt = $ % 1 === 0,
                                    $t = nt ? $v * times : ($v * times).toFixed(("" + $v).replace(/^-?\d*\.?|0+$/g, '').length),
                                    s = $(x).data('uom') ? $t + $(x).data('uom') : $t;
                                if ($v > 0) {
                                    $(x).removeClass('reset');
                                    void $(x)[0].offsetWidth;//line to ensure css re-animation
                                    $(x).html(s).addClass('reset');
                                }
                            });
                        }

                        $('#calcs').on('submit', function (e) {
                            e.preventDefault();
                            setIt(false);
                        });

                        $('#calcs').on('reset', function (e) {
                            setIt(true);
                        });

                        $('[data-open="pop"]').on('click', function (e) {
                            e.preventDefault();
                            $('.imagepreview').attr('src', $(this).attr('href'));
                            $('#imagemodal').modal('show');
                        });

                        $('[data-toggle="tooltip"]').tooltip();

                        /*if( $('#regulatory').length > 0 )
                        {
                          var t = $('#regulatory').offset().top;
                          $(window).on('resize', function() {
                            t = $('#regulatory').offset().top;
                         });
                        
                         
                         $(window).on('scroll', function() {
                           var y_scroll_pos = window.pageYOffset;
                               $button      = $('.btn[href="#regulatory"]');
                            
                           if(y_scroll_pos > t) {
                             $(window).off('scroll').off('resize');
                             $.innovadex.tracking.trackEvent($button.data('action-event-category'), $button.data('action-event'), "Scrolled Into View");
                           }
                          });
                        }*/
                        App.initTrack(context);

                        $("a[data-refinement]", context).unbind('click', refinementLink_clicked);
                        $("a[data-refinement]", context).click(refinementLink_clicked);
                        DesktopApp.pages.search.initSalesAppFolderSelection(context);

                        $('a[data-load-more-docs]').click(function (evt) {
                            evt.preventDefault();
                            $(this).closest('ul').find("li:hidden").fadeIn();
                            $(this).hide();
                        });

                        $('a[data-load-more-related-docs]').click(function (evt) {
                            evt.preventDefault();
                            // modified to look for just "li" hidden items to fix bug that was showing all hidden sample request
                            // items as well
                            $(this).closest('ul').find("li:hidden").fadeIn();
                            $(this).hide();
                        });

                        $("#add-to-sales-folder", context).click(function (evt) {
                            evt.preventDefault();
                            var $link = $(this);
                            var bookId = $link.attr("data-bookid");
                            var bookshelfId = $link.attr("data-bookshelfid");
                            DesktopApp.pages.search.addToSalesFolder(context, bookId, bookshelfId);
                        });

                        var $reg_restrict_popup = $("#region-restricted-popup");
                        var $supplier_restrict_popup = $("#supplier-restriction-inquiry");

                        if ($reg_restrict_popup != null && $reg_restrict_popup.length == 1) {
                            $("a[data-region-restricted]").click(DesktopApp.pages.search.showdetail_view.handleRegionRestrictedLink);
                        } else if ($supplier_restrict_popup != null && $supplier_restrict_popup.length == 1) {
                            $("a[data-doclink=true]").click(DesktopApp.pages.search.showdetail_view.handleSupplierRestrictedLink);
                            $("a.doctranslator").click(DesktopApp.pages.search.showdetail_view.handleSupplierRestrictedLink);
                            $("a[data-supplier-restricted]").click(DesktopApp.pages.search.showdetail_view.handleSupplierRestrictedLink);

                            $("#supplier-restriction-inquiry form").submit(function (evt) {
                                evt.preventDefault();
                                ajaxifyForm($(this), "DesktopApp.pages.search.showdetail_view.handleRestrictionInquirySuccess()");
                                $("#inquiry-sending-msg").show();
                                $.innovadex.tracking.trackEvent("Detail", "Restriction Access Inquiry Submitted");
                            });
                        }

                        $("a[data-doclink]").on('click', function (evt) {
                            var $link = $(this);
                            var login = $link.data('login');

                            if (login == null || login.length == 0 || !login) {
                                return;
                            }

                            evt.preventDefault();

                            var loginUrl = DesktopApp.routing.getLoginUrl($link.attr('href'));
                            var did = $link.data('did');

                            if (did != null && did.length != 0) {
                                loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'did', did);
                            }

                            var dtype = $link.data('dtype');

                            if (dtype != null && dtype.length != 0) {
                                loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'dtype', dtype);
                            }

                            var bid = $link.data('bid');

                            if (bid != null && bid.length != 0) {
                                loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'bid', bid);
                            }

                            var bsid = $link.data('bsid');

                            if (bsid != null && bsid.length != 0) {
                                loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'bsid', bsid);
                            }

                            $.innovadex.redirectToUrl(loginUrl);
                        });

                        /*if( window.localStorage )
                          DesktopApp.tour.init();*/
                        $("body").delegate(".swap-content-link", "click", function (evt) {
                            evt.preventDefault();
                            $link = $(this);

                            var $swap_to = $link.parent().parent().children('[data-swap-id="' + $link.attr("data-swap-to") + '"]');
                            $link.parent().hide();
                            $swap_to.removeClass('hide');   // Show does not seem to override the class anymore
                            $swap_to.show();
                        });
                        var similarProductsDiv = $('#similarproducts-detail-section');
                        if (similarProductsDiv.length > 0) {
                            var similarProductsLoadingDiv = $('#loading-similarproducts');
                            similarProductsLoadingDiv.slideDown(function () {

                                var languageId = similarProductsDiv.data('languageid');
                                var cybraryId = similarProductsDiv.data('cybraryid');
                                var regionId = similarProductsDiv.data('regionid');
                                var bookId = similarProductsDiv.data('bookid');

                                var url = "/search/" + bookId + "/" + languageId + "/" + regionId + "/" + cybraryId + "/similarproducts";

                                $.ajax({
                                    type: "GET",
                                    url: url,
                                    success: function (data) {
                                        similarProductsDiv.append(data);
                                        var rowCount = $('#searchresultstable tr').length;
                                        var similarProductsHeader = $('#similarproducts-header');
                                        similarProductsLoadingDiv.slideUp(function () {
                                            if (rowCount > 0) {
                                                similarProductsHeader.slideDown();
                                                similarProductsDiv.slideDown();
                                            }
                                        });
                                    },
                                    error: function (xhr, err, exc) {
                                        similarProductsLoadingDiv.slideUp();
                                    }
                                });
                            });
                        }
                    },
                    loadContactSupplier: function (cs_url) {
                        $.ajax({
                            type: "GET",
                            url: cs_url,
                            success: function (response) {
                                $('#simplemodal-container').html(response);


                                /*if (!$.browser.msie && !$.browser.safari)
                                    $(".button").corner("keep");*/

                                var lockit = false;

                                $("#contactSupplierForm").submit(function () {

                                    var form = $(this);
                                    if (lockit != true) {
                                        lockit = true;
                                        $.ajax({
                                            type: "POST",
                                            url: form.attr('action'),
                                            data: form.serialize() + "&noShow=y",
                                            success: function (response) {
                                                lockit = false;
                                                $('#simplemodal-container').html(response);
                                            }
                                        });
                                    }
                                    return false;
                                });
                            }
                        });
                    },
                    sampleAdded: function (result, linkid, image_path) {
                        // Called via callback on the postSampleCart function to
                        // update the GUI on the details page
                        //div_swap('sampleOff', 'sampleOn');
                        //$("#samplecart_img").attr("src", result.inCartImage);
                        //$("#sample_cart_link").replaceWith("<span>" + result.inCartText + "</span>");
                        //$('#detailSubmitSampleRequest').hide('fast', function() {$('#detailLinkToSampleRequest').show('fast');});
                        $('#sample_cart_link').remove();
                        $('#requestNow').show();

                        var $otherSampleLink = $("a[data-role='request-sample']");

                        if ($otherSampleLink.length > 0) {
                            var inCartText = $otherSampleLink.attr('data-inactivetext') || "Sample in cart";
                            $otherSampleLink.html(inCartText);
                            $otherSampleLink.parent().addClass("inactive");
                        }
                    },
                    handleRegionRestrictedLink: function (evt) {
                        evt.preventDefault();
                        //$("#region-restricted-popup").show();
                        $("#region-restricted-popup").modal({backdrop: true, show: true});
                    },
                    handleSupplierRestrictedLink: function (evt) {
                        evt.preventDefault();
                        $("#inquiry-sending-msg").hide();
                        $("#supplier-restriction-inquiry").modal({backdrop: true, show: true});
                        $.innovadex.tracking.trackEvent("Detail", "View Restriction Access Inquiry");
                    },
                    handleRestrictionInquirySuccess: function () {
                        $("#inquiry-sending-msg").hide();
                        $("#supplier-restriction-footer").hide();
                        $("#inquiry-success-msg").remove();
                        $("#supplier-restriction-inquiry-content").html("<div id='inquiry-success-msg'>" + $("form", '#supplier-restriction-inquiry').data('success-phrase') + "</div>");
                    },
                    sample_added_in_tabular_view: function (result, linkid, confirmationElement) {
                        var $link = $('#' + linkid);

                        if ($link != null && $link.length != 0) {
                            var $parent = $link.parent();
                            $link.tooltip("hide");
                            $link.remove();
                        }

                        var confirmationElementToShow = $('#' + confirmationElement);
                        if (confirmationElementToShow != undefined) {
                            confirmationElementToShow.show();

                            if (confirmationElementToShow.is("tr")) {
                                confirmationElementToShow.closest('tr').next('tr').removeClass('result_detail_row_bordered').addClass('result_detail_row');
                            }
                        }
                        ;
                    }

                },
                initSalesAppFolderSelection: function (context) {
                    var selectedSalesAppFolder = $.innovadex.retrieveLocal('selected-salesapp-folder', context);

                    if (selectedSalesAppFolder != null)
                        $(".sales-folder-list", context).val(selectedSalesAppFolder);

                    $(".sales-folder-list", context).change(function () {
                        $folder_list = $(this);
                        $.innovadex.saveLocal('selected-salesapp-folder', $folder_list.val());

                        // Change any other lists on the page
                        $.each($(".sales-folder-list"), function (idx, item) {
                            if ($(item) != $folder_list)
                                $(item).val($folder_list.val());
                        });
                    });
                },
                addToSalesFolder: function (context, bookId, bookshelfId) {
                    var $folder_list = $(".sales-folder-list", context);
                    var cartId = $folder_list.val();

                    if (cartId == '-1') {
                        DesktopApp.pages.search.handleNoSalesFolderSelected($.innovadex.get_translation('searchresults-salescart-no-folder-selected', 'No folder selected'));
                        return;
                    }

                    // Want to update all folder lists on the page
                    $selected_folder = $(".sales-folder-list option[value='" + $folder_list.find("option:selected").val() + "']");

                    var successMethod = function (data) {
                        var count = parseInt(data);

                        if (count > parseInt($selected_folder.attr("data-count"))) {
                            $selected_folder.attr("data-count", data);
                            $selected_folder.html($selected_folder.attr("data-name") + " (" + data + ")");
                        }
                    };

                    DesktopApp.actions.postSalesAppCart(cartId, bookId, bookshelfId, successMethod);
                },
                handleNoSelectedBooks: function (msg) {
                    showErrorMsg(msg);
                },
                handleNoSalesFolderSelected: function (msg) {
                    showErrorMsg(msg);
                }
            },
            samplerequest:
                {
                    new_view:
                        {
                            init: function ($context, params) {
                                /*if( window.localStorage )
                                  DesktopApp.tour.init();*/

                                $("#sample-create-form", $context)
                                    .submit(function (evt) {
                                        $.innovadex.tracking.trackPage("/samplerequest/submitted");
                                    })
                                    .preventDoubleSubmit();
                            }
                        },
                    index_view:
                        {
                            init: function ($context, params) {
                                $('.receivedSampleDateTextField').keydown(function (key) {
                                    return false;
                                });

                                $('.receivedSampleDateTextField')

                                $('.receivedSampleDateTextField').datetimepicker()
                                    .on('dp.change', function (ev) {
                                        var receivedButton = $(this).closest(".controls").find('.hasReceivedSampleLink');

                                        $(receivedButton).removeAttr("disabled");
                                        $(receivedButton).find("i.fa-check").addClass("enabled");
                                    });
                            }
                        }
                },
            contactsupplier:
                {
                    new_view:
                        {
                            init: function ($context, params) {
                                $("#contactSupplierForm", $context).preventDoubleSubmit();
                                if (DesktopApp.supportsAutoGrow) {
                                    $("[data-function*='autogrow']").autogrow();
                                }
                                $.innovadex.countdown($('[data-function*="countdown"]'));
                            }
                        }
                },
            categoryinfo: {
                new_view: {
                    init: function (context, params) {
                        DesktopApp.pages.categoryinfo.ajaxify_categoryinfo_form();
                    }
                },
                edit_view: {
                    init: function (context, params) {
                        DesktopApp.pages.categoryinfo.ajaxify_categoryinfo_form();
                    }
                },
                ajaxify_categoryinfo_form: function () {
                    $("#categoryinfo_form").submit(function (evt) {
                        evt.preventDefault();
                        $(this).bind("ajax:success", function () {
                            window.parent.refreshWindow();
                        }).bind("ajax:failure", function () {
                            window.parent.showNotification("Error attempting to save category info.");
                            window.parent.closeModal();
                        });

                        //disable save button
                        $("input[type='submit']", $(this)).attr({'disabled': true, 'value': 'Saving...'});
                        ajaxifyForm(this);
                    });
                }
            },
            savedsearch:
                {
                    index_view:
                        {
                            init: function () {
                                $('#renameS,#deleteS').on('show.bs.modal', function (e) {
                                    var $trigger = $(e.relatedTarget),
                                        $form = $("form", this);
                                    $form.attr('action', $trigger.data('action'))
                                        .attr('name', $trigger.data('name'))
                                        .attr('id', $trigger.data('id'))
                                        .data('action-event-label', $trigger.data('ael'));
                                    if ("#renameS" == $trigger.data('target')) {
                                        $('#savedSearchName', '#renameS').val($trigger.data('current-value'));
                                    } else {
                                        $('#targetS').html($trigger.data('search-name'));
                                    }
                                });

                                $('#renameS form', '#deleteS form').submit(function (e) {
                                    $.innovadex.tracking.trackEvent($(this).data('action-event-category'), $(this).data('action-event'), $(this).data("action-event-label"));
                                });


                                $('[data-alert]').click(function (e) {
                                    var savedSearchId = $(this).attr('id'),
                                        isAlert = $(this).data('alert');
                                    $("#userSearchId").val(savedSearchId);
                                    $("#isAlert").val(isAlert);
                                    var form = $("#updateForm")
                                    action = $(form).attr("action").replace("[id]", savedSearchId);
                                    $(form).attr("action", action);
                                    $("#updateForm").submit();
                                    return false;
                                });


                                $('*[data-poload]').click(function () {
                                    var e = $(this),
                                        dir = $('.phone-bar').is(':visible') ? 'bottom' : 'right';
                                    e.popover({
                                        content: '<div class="update"><i class="fa fa-spinner fa-pulse fa-2x"></i></div>',
                                        trigger: 'click',
                                        html: true,
                                        animation: false,
                                        placement: dir,
                                        container: "body"
                                    }).popover('show');
                                    //this should only happen once per click per page load
                                    //get the popup container for THIS LINK
                                    var $pc = $('#' + $(this).attr('aria-describedby'));
                                    $.get(e.data('poload'), function (d) {
                                        e.popover('destroy');
                                        e.off('click').on('click', function (ev) {
                                            if ($('.phone-bar').is(':visible')) {
                                                $(this).scrollTo();
                                            }
                                        });
                                        e.popover({
                                            html: true,
                                            content: d,
                                            trigger: 'click',
                                            animation: false,
                                            placement: dir,
                                            container: 'body'
                                        }).popover('show');
                                    });
                                });
                            }
                        }
                },
            usersalesappmessage: {
                index_view: {
                    init: function (page_element, params) {
                        DesktopApp.utils.showNotification(DesktopApp.defaults.pageNotificationTime, "#page-notifications");
                    }
                },
                new_view: {
                    init: function (page_element, params) {
                        if (DesktopApp.supportsAutoGrow) {
                            $(".autogrow").autoGrow("97%");
                        }
                        $.innovadex.countdown($('.countdown'));
                    }
                },
                edit_view: {
                    init: function (page_element, params) {
                        if (DesktopApp.supportsAutoGrow) {
                            $(".autogrow").autoGrow("97%");
                        }
                        $.innovadex.countdown($('.countdown'));
                    }
                }
            },
            session:
                {
                    create_view:
                        {
                            init: function (page_element, params) {
                                DesktopApp.pages.session.new_view.init();
                            }
                        },
                    new_view:
                        {
                            init: function (page_element, params) {
                                $('[data-toggle="tooltip"]').tooltip();

                                DesktopApp.utils.showNotification(null, "#page-notifications");

                                $("#optInForm", page_element).submit(function () {
                                    $.innovadex.tracking.trackEvent("Login", "Opted Back In");
                                });
                            }
                        },
                    simulate_view: {
                        init: function (context, params) {

                            /*
                            $("#ContractingEntityText").autocomplete({
                                delay: App.defaults.AutoCompleteDelay,
                                source: function (request, response) {
                                    $.innovadex.crossSiteAutoCompleteSource(params.contracting_entity_url, request, response, $("#ContractingEntityText"));
                                },
                                select: function (event, ui) {
                                    $("#ContractingEntityText").val("(" + ui.item.ContractingEntityId + ") " + ui.item.Name);
                                    $("#ContractingEntityId").val(ui.item.ContractingEntityId);
                                    $(document).trigger('ContractingEntityAutoCompleteChanged', [ui.item.ContractingEntityId, ui.item.Name]);
    
                                    return false;
                                }
                            })
                            .data("autocomplete")._renderItem = function (ul, item) {
                                return $("<li></li>")
                                        .data("item.autocomplete", item)
                                        .append("<a>(" + item.ContractingEntityId + ") " + item.Name + "</a>")
                                        .appendTo(ul);
                            };
    
                            $("#ContractingEntityText").bind("autocompletesearch", $.innovadex.defaultAutoCompleteSearch);
                            $("#ContractingEntityText").change(function () {
                                if ($(this).val().length == 0)
                                    $("#ContractingEntityId").val("");
                            });
                            */
                            var contractingEntityInput = $("#ContractingEntityText");
                            var request = null;
                            var requestData = null;
                            contractingEntityInput.typeahead({
                                minLength: 3,
                                items: 200,
                                item: '<li><a><span class="title"></span></a></li>',
                                source: function (query, typeahead) {
                                    if (request)
                                        request.abort();

                                    requestData = null;
                                    request = $.ajax({
                                        url: params.contracting_entity_url,
                                        data: 'term=' + query,
                                        dataType: 'json',
                                        beforeSend: function () {
                                            $('#k').siblings('.add-on').children('i').removeClass('icon-search').addClass('icon-spinner icon-spin');
                                        },
                                        success: function (data, status, xhr) {
                                            request = null;
                                            requestData = data;
                                            var typeaheadData = $.map(data, function (itm, idx) {
                                                return itm.Name;
                                            });
                                            return typeahead(typeaheadData);
                                        }
                                    });

                                    return request;
                                },
                                matcher: function (item) {
                                    return true;
                                },
                                highlighter: function (item) {
                                    $('#k').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
                                    var regex = new RegExp('(' + this.query + ')', 'gi');
                                    return item.replace(regex, "<strong>$1</strong>");
                                },
                                updater: function (item) {
                                    var foundItem = null;
                                    $.each(requestData, function (idx, itm) {
                                        if (itm.Name == item) {
                                            foundItem = itm;
                                        }
                                    });

                                    if (foundItem) {
                                        $("#ContractingEntityId").val(foundItem.ContractingEntityId);
                                        return item;
                                    }

                                    return "";
                                }
                            }).data('typeahead');

                            $("#IsTradeshowExpress").change(function (evt) {
                                DesktopApp.pages.session.simulate_view.configure_mode();
                            });

                            $("input[name='portal_mode']").change(function (evt) {
                                DesktopApp.pages.session.simulate_view.configure_mode();
                            });
                        },
                        configure_mode: function () {
                            if ($("#IsTradeshowExpress").prop('checked') && $("#portal_mode_demo").prop('checked'))
                                $("#show-selector").show();
                            else
                                $("#show-selector").hide();
                        }
                    }
                },
            home:
                {
                    contacts_view:
                        {
                            init: function () {
                                if (DesktopApp.supportsAutoGrow) {
                                    $("[data-function*='autogrow']").autogrow();
                                }
                                $.innovadex.countdown($('[data-function*="countdown"]'));
                            }
                        }
                },
            user:
                {
                    showregistrationhelp_view:
                        {
                            init: function () {
                                DesktopApp.pages.home.showhelp_view.init();
                            }
                        },
                    forgotpassword_view:
                        {
                            init: function () {
                            }
                        },
                    resetpassword_view:
                        {
                            init: function () {
                                DesktopApp.pages.user.validatePassword('#resetPassForm');
                            }
                        },
                    forgotresetpassword_view:
                        {
                            init: function () {
                                DesktopApp.pages.user.validatePassword('#resetPassForm');
                            }
                        },
                    validatePassword: function (passwordForm, stopProp, checkSubmit) {
                        stopProp = typeof stopProp == "undefined" ? true : stopProp,
                            checkSubmit = typeof checkSubmit == "undefined" ? true : checkSubmit;

                        var valid = false,
                            validScale = {
                                "Weak": {max: 25, min: 0, klass: "text-warning"},
                                "Medium": {max: 50, min: 26, klass: "text-info"},
                                "Strong": {max: 75, min: 51, klass: "text-success"},
                                "Very Strong": {max: 100, min: 76, klass: "text-success"}
                            };

                        //when focus on password input, open rules popover
                        //onkeyup
                        $('#Password').on('input propertychange', function (e) {
                            valid = DesktopApp.pages.user.checkIt();
                        }).complexify({}, function (v, complexity) {
                            if (valid) {
                                for (var key in validScale) {
                                    if (complexity >= validScale[key].min && complexity <= validScale[key].max) {
                                        $('strong', '#strength').html(key);
                                        $('#strength').attr('class', validScale[key].klass);
                                        break;
                                    }
                                }
                            } else {
                                $('strong', '#strength').html($('#strength').data('default'));
                                var x = $('#strength').attr('class', 'text-danger');
                            }
                        });

                        if (checkSubmit) {
                            $(passwordForm).on('submit', function (e) {
                                $('#CurrentPassword').parents('.form-group').removeClass('has-error');
                                $('#currentPasswordDangerBlock').hide();
                                $('#PasswordConfirm').parents('.form-group').removeClass('has-error');
                                $('#passwordConfirmDangerBlock').hide();

                                valid = DesktopApp.pages.user.checkIt();

                                if (!valid) {
                                    $('#Password').parents('.form-group').addClass('has-error');
                                }

                                if ($('#CurrentPassword').length) {
                                    if ($('#CurrentPassword').val().length == 0) {
                                        valid = false;
                                        $('#CurrentPassword').parents('.form-group').addClass('has-error');
                                        $('#currentPasswordDangerBlock').show();
                                    }
                                }

                                if ($('#Password').val() != $('#PasswordConfirm').val()) {
                                    valid = false;
                                    $('#PasswordConfirm').parents('.form-group').addClass('has-error');
                                    $('#passwordConfirmDangerBlock').show();
                                }

                                if (!valid && stopProp) {
                                    e.stopImmediatePropagation();
                                }

                                if (stopProp) {
                                    return valid;
                                }
                            });
                        }
                    },
                    checkIt: function () {
                        var valid = true;
                        $('#Password').parents('.form-group').removeClass('has-error');
                        //loop through rules object and test each regex
                        for (var key in DesktopApp.pages.user.rules) {
                            var obj = DesktopApp.pages.user.rules[key],
                                p = DesktopApp.pages.user.test_regex($('#Password').val(), obj["reg"]);
                            obj["pass"] = obj["neg"] ? !p : p;
                            if (!obj["pass"])
                                valid = false;
                        }
                        //update rule indicators
                        for (var key in DesktopApp.pages.user.rules) {
                            //loop through again to get pass indic
                            var obj = DesktopApp.pages.user.rules[key],
                                id = "#" + key;
                            //update relevant icons
                            $("i", id).toggleClass("fa-minus-circle text-danger", !obj["pass"]).toggleClass('fa-check text-success', obj["pass"]);
                        }
                        return valid;
                    },
                    rules: {}, //in order to load scripts in the correct order, the rules are defined inline
                    test_regex: function (pass, pattern) {
                        var re = pattern;
                        return re.test(pass);
                    }
                },
            industry:
                {
                    index_view:
                        {
                            init: function () {
                                /*if( window.localStorage )
                                  DesktopApp.tour.init("industry");*/

                                var knowledgeBaseDiv = $('#knowledge-base-rss-feed');

                                if (knowledgeBaseDiv.length > 0 && knowledgeBaseDiv.data('should-load-ajax') == 1) {
                                    $('#loading-knowledge-base-rss-feed').slideDown(function () {

                                        var languageId = knowledgeBaseDiv.data('languageid');
                                        var cybraryId = knowledgeBaseDiv.data('cybraryid');
                                        var regionId = knowledgeBaseDiv.data('regionid');

                                        var url = "/industries/" + languageId + "/" + regionId + "/" + cybraryId + "/knowledgefeed";

                                        $.ajax({
                                            type: "GET",
                                            url: url,
                                            success: function (data) {
                                                knowledgeBaseDiv.append(data);
                                                $('#loading-knowledge-base-rss-feed').slideUp(function () {
                                                    knowledgeBaseDiv.slideDown();
                                                });
                                            },
                                            error: function (xhr, err, exc) {
                                                $('#loading-knowledge-base-rss-feed').slideUp();
                                            }
                                        });
                                    });
                                }

                                $('.show_mark_sample_received_button').click(function () {
                                    $(this).slideUp(function () {
                                        $(this).nextUntil('.sample_received_form').slideDown();
                                    });
                                });

                                $('.receivedSampleDateTextField').keydown(function (key) {
                                    return false;
                                });

                                if ("undefined" != typeof $.fn.datetimepicker) {
                                    $('.receivedSampleDateTextField').datetimepicker()
                                        .on('dp.change', function (ev) {
                                            var receivedButton = $(this).closest(".controls").find('.hasReceivedSampleLink');

                                            $(receivedButton).removeAttr("disabled");
                                            $(receivedButton).find("i.fa-check").addClass("enabled");
                                        });
                                }

                                $('.hasReceivedSampleLink').click(function () {
                                    var userSampleId = $(this).data('user-sample-id');
                                    var dateReceieved = $('#receivedSampleOneDateTextField-' + userSampleId).val();

                                    if (dateReceieved) {
                                        var url = "/samplerequest/marksampleasreceived/";
                                        var dateDisplay = $('#receivedSampleDateDisplay-' + userSampleId);

                                        var sampleLink = $(this);
                                        $('#markSampleReceivedPending-' + userSampleId).slideDown('fast');
                                        sampleLink.attr("disabled", "disabled");

                                        $.ajax({
                                            type: "POST",
                                            dataType: "json",
                                            url: url,
                                            data: {userSampleId: userSampleId, dateReceived: dateReceieved},
                                            success: function (data) {
                                                if (data.resultCode != null && data.resultCode != undefined && data.resultCode == 0) {
                                                    var sendFollowupLink = $('#followupMailLink-' + userSampleId);

                                                    dateDisplay.text($.innovadex.get_translation('UserSampleHistory_Mark_As_Received', 'Received') + " " + data.dateReceived);

                                                    $('#sampleHistoryReceivedSection-' + userSampleId).hide('fast', function () {
                                                        dateDisplay.show('fast');
                                                    });
                                                    if (sendFollowupLink != null) {
                                                        sendFollowupLink.slideUp('fast');
                                                    }
                                                    ;
                                                } else {
                                                    alert("Error occurred. Please try again");
                                                    $('#markSampleReceivedPending-' + userSampleId).hide('fast', function () {
                                                        sampleLink.show('fast');
                                                    });
                                                }
                                            },
                                            error: function (request, textStatus, errorThrown) {
                                                //showErrorMsg(textStatus + " " + errorThrown);
                                                alert(textStatus + " " + errorThrown);
                                                sampleLink.removeAttr("disabled");
                                                $('#markSampleReceivedPending-' + userSampleId).hide('fast');
                                            }
                                        });
                                    } else {
                                        $('#receivedSampleOneDateTextField-' + userSampleId).addClass('error');
                                    }

                                    return false;
                                });


                                $('.refine-opener').click(function () {
                                    DesktopApp.utils.toggleHiddenMobileView($('nav#refinements'));
                                });
                            }
                        },
                    newsletterlist_view:
                        {
                            init: function () {
                                $('.refine-opener').click(function () {
                                    DesktopApp.utils.toggleHiddenMobileView($('nav#refinements'));
                                });
                            }
                        },
                    newseventlist_view:
                        {
                            init: function () {
                                $('.refine-opener').click(function () {
                                    DesktopApp.utils.toggleHiddenMobileView($('nav#refinements'));
                                });
                            }
                        }
                },
            bookmark:
                {
                    index_view:
                        {
                            init: function () {
                                $('#deleteB').on('show.bs.modal', function (e) {
                                    var $trigger = $(e.relatedTarget),
                                        $form = $("form", this);
                                    $form.attr('action', $trigger.data('action'))
                                        .attr('name', $trigger.data('name'))
                                        .attr('id', $trigger.data('id'))
                                        .data('action-event-label', $trigger.data('ael'));
                                    $('#targetB').html($trigger.data('bookmark-name'));
                                });

                                $('form', '#deleteB').submit(function (e) {
                                    $.innovadex.tracking.trackEvent($(this).data('action-event-category'), $(this).data('action-event'), $(this).data("action-event-label"));
                                });
                            }
                        }
                }
        },
        actions:
            {
                handlePropertyRefinementUpdated: function (element) {
                    if (!$('body').data('is-loading-property')) {

                        var params =
                            {
                                'property_id': $link.attr('data-property-id'),
                                'search_url': getSearchBaseUrl(true)
                            };

                        var url = $.innovadex.addQuerystringParam(element.attr('data-value'), 'minimal', '1', true);

                        console.log(url);
                        // $.ajax({
                        //     type: "GET",
                        //     url: url,
                        //     success: function (data) {
                        //         $link.addClass('currently_viewing_property_link');
                        //
                        //         $link.find('.loading_spinner').hide();
                        //
                        //         $(currentLi).after('<li class="property_search" style="display: none;">' + data + '</li>');
                        //         $('.property_search').slideDown();
                        //
                        //         App.pages.search.propertyedit_view.init(null, params);
                        //         $('body').data('is-loading-property', false);
                        //     },
                        //     error: function (xhr, err, exc) {
                        //         $('body').data('is-loading-property', false);
                        //         $link.find('.loading_spinner').hide();
                        //         alert(err);
                        //     }
                        // });
                    }
                },
                handlePropertyRefinement: function ($link) {
                    if (!$('body').data('is-loading-property')) {
                        var currentLi = $link.closest('li');

                        if ($link.hasClass('currently_viewing_property_link')) {
                            $link.removeClass('currently_viewing_property_link');
                            $('.property_search').slideUp(function () {
                                $('.property_search').remove();
                            });
                            return;
                        }

                        $('.currently_viewing_property_link').removeClass('currently_viewing_property_link');

                        $('body').data('is-loading-property', true);

                        $link.find('.loading_spinner').show();

                        var currentPropertySearch = $('.property_search');
                        if (currentPropertySearch != undefined) {
                            currentPropertySearch.slideUp(function () {
                                currentPropertySearch.remove();
                            });
                        }

                        var params =
                            {
                                'property_id': $link.attr('data-property-id'),
                                'search_url': getSearchBaseUrl(true)
                            };

                        var url = $.innovadex.addQuerystringParam($link.attr('href'), 'minimal', '1', true);

                        $.ajax({
                            type: "GET",
                            url: url,
                            success: function (data) {
                                $link.addClass('currently_viewing_property_link');

                                $link.find('.loading_spinner').hide();

                                $(currentLi).after('<li class="property_search" style="display: none;">' + data + '</li>');
                                $('.property_search').slideDown();

                                App.pages.search.propertyedit_view.init(null, params);
                                $('body').data('is-loading-property', false);
                            },
                            error: function (xhr, err, exc) {
                                $('body').data('is-loading-property', false);
                                $link.find('.loading_spinner').hide();
                                alert(err);
                            }
                        });
                    }
                },
                checkModalStatus: function (xhr) {
                    if (xhr.status >= 201) {
                        closeModal();
                        alert("Error occurred. Please try again");
                        return false;
                    }

                    return true;
                },
                postSalesAppCart: function (cartid, bookid, bookshelfid, successCallback) {
                    if (cartid > 0 && bookid > 0 && bookshelfid > 0) {
                        $.ajax({
                            url: "/salesfolders/" + cartid + "/items",
                            type: "POST",
                            data: ({BookshelfId: bookshelfid, BookId: bookid}),
                            dataType: "text",
                            success: function (data) {
                                if (successCallback != null && typeof successCallback == 'function')
                                    successCallback(data);
                            },
                            error: function (xhr, err, exc) {
                                alert(err);
                            }
                        });
                    }
                },
                loadBookmarks: function (url, containerId) {
                    var container = $('#' + containerId);
                    // verify that it has not already been loaded
                    if (container.children().length > 0)
                        return;

                    ajaxRequest(url, 'GET', null,
                        function (response) {
                            container.append(response);
                            $("a", container).click(App.actions.handleTrackingActionEvent);
                        },
                        function (response) {
                            // handle error
                        }, 'html'
                    );
                }

            },
        utils:
            {
                moveSlide: function (toSlide, fromSlide) {
                    $('.content', '.carouselSteps').data('step', toSlide).removeClass('step-' + fromSlide).addClass('step-' + toSlide);
                    $('li.active', '.carouselSteps').removeClass('active').removeAttr('aria-disabled');
                    $('li' + '[data-slide-to=' + toSlide + ']', '.carouselSteps').addClass('active').attr('aria-disabled', true);
                },
                resetCarousel: function () {
                    if ($('.content-body').length == parseInt($('[data-step]', '.carouselSteps').data('step'))) {
                        DesktopApp.utils.moveSlide(1, $('.content-body').length);
                    }
                },
                initMyStuffBar: function (context) {
                    var $mystuff = $("#mystuff", context);

                    if ($mystuff != null && $mystuff.length != 0) {
                        $("#mysalesappfolderslink", context).click(function (evt) {
                            evt.preventDefault();
                            showPopupAt('mystuff_salesappfolders', 'mysalesappfolders', 'bottomleft');
                        });
                    }
                },
                initAudioPlayer: function () {
                    var $player = $("#player");

                    if ($player != null && $player.length != 0) {
                        if ($.innovadex.canPlayType('audio/wav') || $.innovadex.canPlayType('audio/mpeg')) {
                            // HTML5 audio + mp3 support
                            $('#player').show();
                        } else {
                            swfobject.embedSWF(
                                "/Innovadex.swf",
                                "player_fallback",
                                "20",
                                "20",
                                "10.0.0",
                                "",
                                {},
                                {"bgcolor": "#FFFFFF", wmode: 'transparent'});
                        }
                    }
                },
                showNotification: function (time, selector) {
                    if (typeof selector == 'undefined' || selector == null)
                        selector = "#page-notifications";

                    // in order to accommodate the presence of a header to
                    // the information text, there has to be a div surrounding the main content
                    if ($('div', selector).length < 1) {
                        // if there is a header, wrap the content after it with a div
                        var header = $('h1, h2, h3, h4, h5', selector),
                            wrap = false;
                        if (header.length < 1) {
                            wrap = true;
                        } else {
                            var nodes = $(selector).contents();
                            if (nodes.toArray()[0] == header.get(0)) {
                                nodes.slice(1).wrapAll("<div />");
                            }
                            // if the first node is something other than an h-tag, treat the whole node as plain text anyway
                            else {
                                wrap = true;
                            }
                        }

                        if (wrap) {
                            $(selector).wrapInner('<div />');
                        }
                    }
                    if (time == null) return;
                    $(selector).show(0, function () {
                        window.setTimeout(function () {
                            //$(selector + ' span').hide(100, function () {
                            $(selector).slideUp("slow");
                            //});
                        }, time);
                    });
                },
                initSalesApp: function (context) {
                    var $salestoggle = $("#salesapptoggle");

                    if ($salestoggle != null && $salestoggle.length != 0) {
                        $salestoggle.toggleSliderSwitch(DesktopApp.isPinningEnabled);

                        var action = function () {
                            $.innovadex.redirectToUrl($(this).attr('href'))
                        };
                        $salestoggle.bind('turnedOff', action);
                        $salestoggle.bind('turnedOn', action);
                    }

                    $("#salesapp-bookshelf-selection", context).change(function () {
                        var $select = $(this);
                        var $option = $select.find("option:selected");
                        var formData = {'BookshelfId': $option.attr('data-bookshelfid'), 'RegionId': $option.attr('data-regionid'), 'CybraryId': $option.attr('data-cybraryid')};
                        $.innovadex.createAndSubmitForm('/pin', formData);
                    });
                },
                prepareKeywordTermParameter: function (term) {
                    encode = encodeURIComponent || escape;
                    term = encode(term);
                    return term.replace(/ /g, "+").replace("%20", "+");
                },
                initKeywordAutocomplete: function ($selector) {
                    var $keyword_input = $("#keyword-container #k", $selector);
                    if ($keyword_input.length == 0)
                        return;
                    var suggestiontypes_url = $keyword_input.data("suggesttypes-url"),
                        autocomplete_url = $keyword_input.attr("data-suggest-url");
                    autocomplete_url = $.innovadex.addQuerystringParam(autocomplete_url, "term", "%QUERY", true);

                    function dependentInit() {
                        var engines = DesktopApp.utils.initSuggestionEngines(autocomplete_url);

                        $keyword_input.typeahead(
                            {
                                minLength: 2,
                                highlight: true
                            },
                            engines
                        )
                            .bind('typeahead:selected', function (evt, datum, dataset_name) {
                                $(this).val(datum.Text);
                                $.innovadex.tracking.trackEvent('Keyword Suggestion', datum.SuggestionType, datum.ValueString);
                                $.innovadex.redirectToUrl($.innovadex.addQuerystringParam(datum.ValueString, "st", "1"));
                            })
                            .bind('typeahead:cursorchanged', function (evt, datum, dataset_name) {
                                $(this).val(datum.Text);
                            });
                    }

                    //init whether the suggestiontype url exists or not, but
                    //don't try it if there is no URL
                    if (suggestiontypes_url.length > 0) {
                        $.getCachedScript(suggestiontypes_url)
                            .done(function () {
                                dependentInit();
                            });
                    } else {
                        dependentInit();
                    }
                },
                getSuggestionSets: function () {
                    if (typeof SuggestionTypes == 'undefined' || SuggestionTypes == null) {
                        return [];
                    }

                    return SuggestionTypes;
                },
                initSuggestionEngines: function (url) {
                    var sets = this.getSuggestionSets();

                    var datasets = $.map(sets, function (set) {
                        var engine = new Bloodhound({
                            remote: {
                                url: url,
                                filter: function (pr) {
                                    for (var i = 0; i < pr.length; i++) {
                                        var dataset = pr[i];
                                        if (dataset.SuggestionType === set.Type
                                            || (dataset.SuggestionType === 'Property' && dataset.Name === set.Label)) {
                                            return dataset.Items;
                                        }
                                    }

                                    return [];
                                }
                            },
                            datumTokenizer: function (d) {
                                return Bloodhound.tokenizers.whitespace(d.val);
                            },
                            queryTokenizer: Bloodhound.tokenizers.whitespace
                        });
                        engine.initialize();

                        try {
                            var $spinner = $('#keywordForm .input-group-addon i');
                            engine.remote.ajax.beforeSend = function () {
                                $spinner
                                    .removeClass('fa-search')
                                    .addClass('fa-spinner fa-spin');
                            };
                            engine.remote.ajax.complete = function () {
                                $spinner
                                    .removeClass('fa-spinner fa-spin')
                                    .addClass('fa-search');
                            };

                        } catch (e) {
                            // Spinner broken - oh well
                        }

                        return {
                            name: set.Type,
                            source: engine.ttAdapter(),
                            displayKey: function (datum) {
                                var text = datum.Text;

                                if (datum.Description && datum.Description.length != 0) {
                                    text += '<p>' + datum.Description + '</p>';
                                }
                                return text;
                            },
                            templates: {
                                header: '<div class="nav-header">' + set.Label + '</div>'
                            }
                        };
                    });

                    return datasets;
                },
                // initKeywordSuggestions: For bootstrap 2 typedown. Can remove when aspx pages are all converted to razor
                initKeywordSuggestions: function ($selector) {
                    var utils = this;
                    var keyword_suggest_data = null;
                    var keyword_suggest_request = null;
                    var keyword_term = null;

                    var keyword_input = $("#searchcontainer #k", $selector);

                    if (keyword_input.length == 0)
                        return;

                    var typeahead = keyword_input.typeahead({
                        minLength: 2,
                        items: 200,
                        item: '<li><a><span class="title"></span></a></li>',
                        source: function (query, typeahead) {
                            keyword_term = query;
                            if (keyword_suggest_request)
                                keyword_suggest_request.abort();

                            keyword_suggest_request = $.ajax({
                                url: keyword_input.attr("data-suggest-url"),
                                data: 'term=' + utils.prepareKeywordTermParameter(query),
                                dataType: 'json',
                                beforeSend: function () {
                                    $('#k').siblings('.add-on').children('i').removeClass('icon-search').addClass('icon-spinner icon-spin');
                                },
                                success: function (data, status, xhr) {
                                    keyword_suggest_request = null;
                                    keyword_suggest_data = {};
                                    var items = [];
                                    $(data).map(function (group_index, group) {
                                        $(group.Items).map(function (item_index, item) {
                                            item['GroupName'] = group.Name;
                                            item['GroupIndex'] = item_index;
                                            var identifier = group_index + '_' + item_index;
                                            keyword_suggest_data[identifier] = item;
                                            items.push(identifier);
                                        });
                                    });
                                    return typeahead(items);
                                },
                                complete: function () {
                                    $('#k').siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
                                }
                            });

                            return keyword_suggest_request;
                        },

                        matcher: function (item) {
                            return true;
                        },
                        highlighter: function (item) {
                            var regex = new RegExp('(' + this.query + ')', 'gi');
                            return item.replace(regex, "<strong>$1</strong>");
                        },
                        updater: function (item) {
                            var data_item = keyword_suggest_data[item];
                            $.innovadex.tracking.trackEvent('Keyword Suggestion', data_item.SuggestionType, data_item.ValueString);
                            $.innovadex.redirectToUrl($.innovadex.addQuerystringParam(data_item.ValueString, "st", "1"));
                            return data_item.Text;
                        }
                    }).data('typeahead');

                    //NOTE: TYPEAHEAD FUNCTIONALITY BROKEN AS OF 5/16/2013
                    //-- MTM
                    try {
                        typeahead.render = function (items) {
                            var renderer = this;
                            var $html_items = $([]);

                            if (this.query != keyword_term)
                                return $([]);  // Cancels query by returning an empty array which typeahead will then do a Show on

                            $(items).map(function (i, item) {
                                var data_item = keyword_suggest_data[item];

                                if (data_item.GroupIndex === 0) {
                                    var $section_li = $(document.createElement("li"))
                                        .addClass('nav-header')
                                        .html(data_item.GroupName);
                                    $html_items.push($section_li[0]);
                                }
                                var $li = $(renderer.options.item)
                                    .attr('data-value', item)
                                    .addClass('item');

                                if (data_item.GroupIndex === 0)
                                    $li.addClass('first');

                                $li.find('span').html(renderer.highlighter(data_item.Text));

                                if (data_item.Description && data_item.Description.length != 0) {
                                    var $p = $(document.createElement("p"))
                                        .html(data_item.Description);
                                    $li.find('a').append($p);
                                }
                                $html_items.push($li[0]);
                            });

                            this.$menu.html($html_items);
                            this.$menu.find('.item').first().addClass('active');
                            return this;
                        };
                    } catch (e) {
                        //console.log(e);
                    }
                },

                resetModalHeight: function (selector, shrink) {
                    selector = selector || '.simplemodal-container';
                    var origH = $(selector).height(),
                        h = $(selector).get(0).scrollHeight;
                    if ($(window).height() < h) {
                        h = $(window).height() - 50;
                    }

                    if (shrink && selector == '.simplemodal-container') {
                        h = $('.simplemodal-wrap').height() + 30;
                    }

                    var t = Math.floor(($(window).height() / 2) - (h / 2));
                    //var t = (h - origH)/2;

                    if (Math.abs(h - origH) > 12) {
                        $(selector).animate({height: h + "px", top: t + "px"});
                    }
                },
                toggleHiddenMobileView: function ($element) {
                    if ($element.hasClass('hidden-xs')) {
                        $element.removeClass('hidden-xs');
                    } else {
                        $element.slideToggle(300);
                    }
                }
            },
        routing: {
            getLoginUrl: function (targetUrl) {
                var loginUrl = "/session/new";

                if (typeof version != 'undefined' && version != null) {
                    var loginUrl = $.innovadex.addQuerystringParam(loginUrl, "version", versionStr);
                }

                if (typeof languageCode != 'undefined' && languageCode != null) {
                    loginUrl = addQuerystringParam(loginUrl, "lang", languageCode);
                }

                if (typeof (targetUrl) != 'undefined' && targetUrl.length != 0) {
                    loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'ReturnUrl', encodeURIComponent(targetUrl), true);
                }

                return loginUrl;
            }
        },

        initPrivateLabelColor: function () {
            var bColor, tColor,
                privateLabel = isPrivateLabel();
            if (privateLabel) {
                resetCssColor();
            }

            function isPrivateLabel() {
                if ($('.focus').length < 1) {
                    $('body').append('<span class="focus"></span>');
                }
                var gRGB = ["68", "187", "68"],
                    hex = '#44bb44',
                    fColor = $('.focus').css('backgroundColor'),
                    ftColor = $('.focus').css('color');

                if (fColor.indexOf('(') != -1) {
                    var aRGB = fColor.replace(/[\)\s]+/g, '').substring(fColor.indexOf('(') + 1).split(',');
                    if (aRGB.toString() == gRGB.toString()) {
                        return false;
                    } else {
                        var atRGB = ftColor.replace(/[\)\s]+/g, '').substring(ftColor.indexOf('(') + 1).split(','),
                            carr = $.map(aRGB, function (x) {
                                return +x
                            }),
                            ctarr = $.map(atRGB, function (x) {
                                return +x
                            });
                        bColor = Colors.rgb2hex(carr[0], carr[1], carr[2]);
                        tColor = Colors.rgb2hex(ctarr[0], ctarr[1], ctarr[2]);
                        return true;
                    }
                } else {
                    if (fColor.length == 4) {
                        fColor = fColor.replace(/#([\dA-Fa-f])([\dA-Fa-f])([\dA-Fa-f])/, "#$1$1$2$2$3$3");
                        ftColor = ftColor.replace(/#([\dA-Fa-f])([\dA-Fa-f])([\dA-Fa-f])/, "#$1$1$2$2$3$3");
                    }

                    if (hex == fColor) {
                        return false;
                    } else {
                        bColor = fColor;
                        tColor = ftColor;
                        return true;
                    }
                }
            }

            function resetCssColor() {
                var insetC, secondC, borderC, textS;
                // if the text color is white, then the color is already
                // dark, and it should go darker; else the color is
                // light and should go lighter
                if (tColor == "#ffffff") {

                    secondC = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(bColor).H, Colors.hex2hsv(bColor).S, Colors.hex2hsv(bColor).V - 15).a);
                    insetC = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(bColor).H, Colors.hex2hsv(bColor).S, 90).a);
                    borderC = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(bColor).H, Colors.hex2hsv(bColor).S - 10, Colors.hex2hsv(bColor).V - 5).a);
                    textS = "#000000"
                }
                    //if the text is white, the second color should be
                    //lighter. As the gradient should always go lighter
                //to darker, swap color order.
                else {
                    secondC = bColor;
                    bColor = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(secondC).H, Colors.hex2hsv(secondC).S, Colors.hex2hsv(secondC).V + 15).a);
                    insetC = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(secondC).H, Colors.hex2hsv(secondC).S, 95).a);
                    borderC = Colors.rgb2hex.apply(this, Colors.hsv2rgb(Colors.hex2hsv(secondC).H, Colors.hex2hsv(secondC).S - 10, Colors.hex2hsv(secondC).V + 5).a);
                    textS = "#ffffff"
                }

                var styleString = "<style>\ninput.button, .button.submit {\n" +
                    "-moz-box-shadow:inset 0px 1px 0px 0px " + insetC + ";\n" +
                    "-webkit-box-shadow:inset 0px 1px 0px 0px " + insetC + ";\n" +
                    "box-shadow:inset 0px 1px 0px 0px " + insetC + ";\n" +
                    "background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, " +
                    bColor + "), color-stop(1, " + secondC + ") );\n" +
                    "background:-moz-linear-gradient( center top, " + bColor + " 5%, " + secondC + " 100% );\n" +
                    "filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='" +
                    bColor + "', endColorstr='" + secondC + "');\n" +
                    "background-color:" + bColor + ";\n" +
                    "border:1px solid " + borderC + ";\n" +
                    "color: " + tColor + ";\n" +
                    "text-shadow:1px 1px 0px " + textS + ";\n" +
                    "} input.button:hover, .button.submit:hover {\n" +
                    "background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, " +
                    secondC + "), color-stop(1, " + bColor + ") );\n" +
                    "background:-moz-linear-gradient( center top, " + secondC + " 5%, " + bColor + " 100% );\n" +
                    "filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='" +
                    secondC + "', endColorstr='" + bColor + "');\n" +
                    "background-color:" + secondC + ";\n" +
                    "}\n</style>";

                $('head').append(styleString);
            }
        }
    }

    function addNoReferrerToAncientBrowserLinks() {
        var isAncientBrowser = !('fetch' in window);

        if (isAncientBrowser) {
            var externalLinks = document.querySelectorAll("a[target='_blank'][rel*='noopener']");

            for (var i = 0; i < externalLinks.length; i++) {
                var link = externalLinks[i];

                if (link.rel && link.rel.indexOf('noreferrer') === -1) {
                    link.rel += " noreferrer";
                }
            }
        }
    }

    (function() {
       function initDesktopElements () {
         console.log("initiating desktop elements");

        try {
            var $p = $('<p></p>');
            $p.get(0).innerHTML = '<p>test</p>';
        } catch (e) {
            DesktopApp.supportsAutoGrow = false;
        }

        addNoReferrerToAncientBrowserLinks();

        $('.pager .disabled a, .pagination .disabled a').on('click', function (e) {
            e.preventDefault();
        });

        //checkRegionAndLanguage();
        $('a[data-toggle="slider"]').click(function (ev) {
            ev.preventDefault();
            var target = $(this).attr('href') || $(this).data('target');
            $(target).slideToggle();
        });

        $('.menu-opener').click(function () {
            $.scrollTo('#main-page-menu', 400, {axis: 'y'})
        });

        $('.search-opener').click(function (ev) {
            ev.preventDefault();
            $('#searchcontainer').addClass('hide')
                .removeClass('hidden-xs hidden-phone')
                .slideToggle(300);

            var $keyword = $('#keyword-container');

            if ($keyword.length != 0) {
                if ($keyword.hasClass('hidden-xs')) {
                    $keyword.removeClass('hidden-xs', 300)
                        .hide();
                }

                $keyword.slideToggle(300);
            }
        });

        $(document).on('click', 'a[data-opener="region"]:visible', function (ev) {
            ev.preventDefault();

            if ($('#mobile-region-menu').length < 1) {
                var $omClone = $('#headertop #region-menu').clone();
                $('#outer-wrapper').prepend('<nav id="mobile-region-menu" style="display: none;"></nav>');
                $omClone.removeClass('dropdown-menu').addClass("nav nav-list visible-phone visible-xs-block")
                    .prepend('<li class="header">Region</li>');

                $('ul', $omClone).each(function (i, x) {
                    $(x).addClass('hide nav nav-stacked nav-tabs').removeClass('dropdown-menu');
                });

                $('#mobile-region-menu').append($omClone).slideToggle(300);
            } else {
                $('#mobile-region-menu').slideToggle(300);
            }
        });

        $(document).on('click', 'a[data-opener="language"]:visible', function (ev) {
            ev.preventDefault();
            if ($('#mobile-language-menu').length < 1) {
                var $omClone = $('#headertop #language-menu').clone();
                $('#outer-wrapper').prepend('<nav id="mobile-language-menu" style="display: none;"></nav>');
                $omClone.removeClass('dropdown-menu').addClass("nav nav-list visible-phone visible-xs-block")
                    .prepend('<li class="nav-header">Language:</li>');
                $('ul', $omClone).each(function (i, x) {
                    $(x).addClass('hide nav nav-stacked nav-tabs').removeClass('dropdown-menu');
                });

                $('#mobile-language-menu').append($omClone).slideToggle(300);
            } else {
                $('#mobile-language-menu').slideToggle(300);
            }
        });

        $(document).on('click', '.user-menu-opener:visible', function (ev) {
            ev.preventDefault();
            if ($('#user-menu').length < 1) {
                var $omClone = $('#headertop .topmenu').clone(),
                    $nav = $('#outer-wrapper').prepend('<nav style="display: none;" id="user-menu"></nav>'),
                    $menu = $('<ul></ul>').addClass("nav nav-list visible-xs visible-xs-block collapse-bottom").prepend('<li class="header">' +
                        $omClone.data('title') + '</li>'),
                    topMarg = '';
                //$('#login', $omClone).append( $('.unauthenticated .first a:first-child', $omClone).detach() );

                $omClone.find('a[data-menu-item="true"]').each(function (i, x) {
                    topMarg = " extra-margin-top";
                    var u = $(x).siblings('ul:not(.hidden-phone,.hidden-xs)'), $el;
                    if (u.length > 0) {
                        u.removeAttr('class').removeAttr('style').removeAttr('id').addClass('soft-hide nav nav-stacked nav-pills');
                    }

                    $el = $("<li></li>").append(x).append(u);
                    $menu.append($el);

                    if (u.length > 0) {
                        $(x).click(function (ev) {
                            ev.preventDefault();
                            $(this).next('ul').slideToggle(300, function () {
                                var chev = $(this).siblings('a.pull-right').children();
                                if (chev.hasClass('icon-chevron-down')) {
                                    chev.removeClass('icon-chevron-down').addClass('icon-chevron-right');
                                } else {
                                    chev.removeClass('icon-chevron-right').addClass('icon-chevron-down');
                                }
                            });
                        });
                    }
                });

                //$menu.children('a').each(function(i,x){ $(x).wrap('<li/>');});
                var $lomClone = $('#headertop #language-menu').clone();
                $lomClone.removeClass('dropdown-menu').addClass("nav nav-list visible-phone visible-xs-block" + topMarg)
                    .prepend('<li class="nav-header">' + $lomClone.data('title') + '</li>');
                $('ul', $lomClone).each(function (i, x) {
                    $(x).addClass('hide nav nav-stacked nav-tabs').removeClass('dropdown-menu');
                });

                $('#user-menu').append($menu).append($lomClone);
            }

            $('#user-menu').slideToggle(300);
        });
        /*$('.user-menu-opener:visible').click( function() {
          if( $('#user-menu').length < 1 )
          {
            var $omClone = $('#headertop .topmenu').clone();
            $('#outer-wrapper').prepend('<nav class="hide" id="user-menu"></nav>');
            $omClone.removeClass('topmenu').addClass( "nav nav-list visible-phone" )
              .prepend('<li class="nav-header">User Menu:</li><li id="login"></li>');
            $('#login', $omClone).append( $('.first a:first-child', $omClone).detach() );

            //if the user is logged in, put each option into an li
            if( $('.each-li', $omClone).length > 0 )
            {
              var $omClone = $('#headertop .topmenu').clone();
              $('#outer-wrapper').prepend('<nav class="hide" id="user-menu"></nav>');
              $omClone.removeClass('topmenu').addClass( "nav nav-list visible-phone" )
                .prepend('<li class="nav-header">User Menu:</li><li id="login"></li>');
              $('#login', $omClone).append( $('.first a:first-child', $omClone).detach() );

              //if the user is logged in, put each option into an li
              if( $('.each-li', $omClone).length > 0 )
              {
                $('.each-li',$omClone).reverse().each(function(i,x) {
                  $(x).wrap('<li/>');
                  $('#login', $omClone).after( $(x).parent().detach() );
                });
                //console.log('here');
                //$('.each-li',$omClone).wrap('<li></li>');
              }

              $('#user-menu').append($omClone);
            }
          }

          $('#user-menu').slideToggle(300);
        });*/
        /*
                $("#mainmenulogin").click(function (ev) {
                  if (openLoginModal()) {
                    ev.preventDefault();
                    return false;
                  }
                });
                */
        $('.bookmark-opener,.searches-opener').mouseenter(function (ev) {
            var related = '#' + $(this).data('related'),
                $link = $($(this).get(0));

            if ("undefined" === typeof $link.data('populated-list')) {
                $link.data('populated-list', 'listed');
                var url = $(this).data('url');

                $.get(url, function (data) {
                    $(related + ' li:first-child').remove();
                    $(related).prepend(data);

                    var $event_links = $("a[data-action-event]", related);
                    $event_links.unbind('click', App.actions.handleTrackingActionEvent);
                    $event_links.click(App.actions.handleTrackingActionEvent);

                    var w = $(related).outerWidth();
                    if (w > 160) {
                        $(related).animate({left: -w});
                    }
                }).fail(function () {
                    $link.data('populated-list', undefined);
                });
            }
        });

        $("#keywordForm").on("submit", keywordFormSubmitted);
        $("#keywordsubmit").on("click", keywordFormSubmitted);

        $(".sideboxtextsearch .submit").click(function () {
            var ctrl = $(this).prev();
            while (ctrl != null && !ctrl.is(".textbox"))
                ctrl = ctrl.prev();

            if (ctrl == null)
                return false;

            var param = ctrl.get(0).id;
            var term = ctrl.val();
            performKeywordSearch(param, term);
            return false;
        });

        $(".membersonly").on('click', membersOnlyClicked);
        $(".regionrestricted").on('click', regionRestrictionClicked);

        //roundCorners("");

        $("a.singleclick").one("click", function () {
            $(this).click(function () {
                return false;
            });
        });

        $(".sidebox .label a.arrow").click(function () {
            var refinementId = $(this).parent().parent().parent().get(0).id;
            var labelId = $(this).parent().parent().get(0).id;
            var id = labelId.replace("lbl", "data");
            var bodyId = "#" + id;
            var $body = $(bodyId);
            // get requested state which is opposite of current state
            var collapsed = !($body.css('display') == 'none');

            $body.toggle("slow");
            // add class to know if refinement is collapsed
            if ($body.css('display') == 'none')
                $body.removeClass('refinement-collapsed');
            else
                $body.addClass('refinement-collapsed');

            $(this).html(escape($(this).html()) == "%u25B6" ? "&#x25BC;" : "&#x25B6;");

            updateRefinementState(refinementId, collapsed);

            return false;
        });

        var cancelSideboxFlipper = false;

        function setSideboxFlipper(enabled) {
            cancelSideboxFlipper = !enabled;
        }

        $(".sidebox .label a.flipper").click(function () {
            if (cancelSideboxFlipper)
                return false;

            var refinementId = $(this).parent().parent().parent().get(0).id;
            var labelId = $(this).parent().parent().get(0).id;
            var id = labelId.replace("lbl", "data");
            var bodyId = "#" + id;
            var $body = $(bodyId);
            // get requested state which is opposite of current state
            var collapsed = !($body.css('display') == 'none');

            $body.toggle("slow");
            // add class to know if refinement is collapsed
            if ($body.css('display') == 'none')
                $body.removeClass('refinement-collapsed');
            else
                $body.addClass('refinement-collapsed');
            var parent = $(this).parent();
            var arrow = $(":first", parent);
            $(arrow).html(escape($(arrow).html()) == "%u25B6" ? "&#x25BC;" : "&#x25B6;");

            updateRefinementState(refinementId, collapsed);

            return false;
        });

        $("#sortForm").submit(function () {
            var selectedVal = $("#sort").val();

            if (selectedVal.substr(0, 1) == "/") {
                redirectToUrl(selectedVal);
                return false;
            } else
                return true;
        });

        /*$("#refinementListBoxes").sortable({
            opacity: 0.6,
            update: function (event, ui)
            {
                var sortOrder = '';
                $(this).children().each(function (index)
                {
                    if (sortOrder.length > 0)
                        sortOrder += ",";
                    sortOrder += $(this).attr('id').replace('Refinements', '');
                });
                var cookieName = refinementSortCookieName ? refinementSortCookieName : "refinementsortorder";
                var expiryDate = new Date(2040, 1, 1);
                document.cookie = cookieName + "=" + sortOrder + "; expires=" + expiryDate.toGMTString() + "; path=/";

                setSideboxFlipper(false);
                var reEnable = function () { setSideboxFlipper(true) };
                window.setTimeout(reEnable, 500);
            }
        });*/

        $("a[data-refinement]").click(refinementLink_clicked);

         var checkboxRefinementSelected = false;
         console.log(checkboxRefinementSelected);
        $("input[data-checkbox-refinement]").change(function () {
            if (checkboxRefinementSelected)
                return;

            var $checkbox = $(this);
            redirectToSelectedRefinement($checkbox, $checkbox.attr('data-href'));
            checkboxRefinementSelected = true;
        });

        $("input[data-list-option]").change(function () {
            var $listOption = $(this);
            var listName = $listOption.attr('data-list-name');
            var href = window.location.href;
            var listIdentifier = listName + ":";
            var hrefOpPos = href.indexOf(listIdentifier);
            if (hrefOpPos === -1) return;
            var hrefListPos = href.indexOf("(", hrefOpPos);
            if (hrefListPos === -1) return;
            var newHref = href.substr(0, hrefOpPos) + listIdentifier + $listOption.val() + href.substr(hrefListPos);
            redirectToUrl(newHref);
        })

         $("input[data-list-refinement]").change(function () {
           console.log("clicked");
         });
         $("input[data-list-refinement]").change(function () {
           console.log(checkboxRefinementSelected);
            if (checkboxRefinementSelected) return;

            // Gets the href from the item and substitutes the current value of the listed type (may have changed)
            // and substitutes it in
            var $listItem = $(this);
            var href = $listItem.attr('data-href');
            var listTypeName = $listItem.attr('data-ref-type') + "-listed-type";
            var listType = document.querySelector('input[name="' + listTypeName + '"]:checked')?.value
            var listName = $listItem.attr('data-list-name');
            var listIdentifier = listName + ":";
            var txtSearchId = "txt-" + $listItem.attr('data-ref-type');
            var txtSearch = document.getElementById(txtSearchId);
            var newHref = href;
            var hrefListPos = href.indexOf(listIdentifier);
            if (hrefListPos > 0) {
                var hrefOpPos = hrefListPos + listIdentifier.length;
                var hrefValsPos = href.indexOf("(", hrefOpPos);
                newHref = href.substr(0, hrefOpPos) + listType + href.substr(hrefValsPos);
            }
            if (txtSearch && txtSearch.value.length > 0) {
                newHref += "&" + txtSearchId + "=" + txtSearch.value;
            }
            redirectToSelectedRefinement($listItem, newHref);
            checkboxRefinementSelected = true;
        });

        $("a[data-prop-refinement]").on('click', function (evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();
            DesktopApp.actions.handlePropertyRefinement($(this));
            return false;
        });

        $("[data-property-list-expander]").on("click", function () {
            $('.property_search').remove();
        });

        $(".refinementMore, .refinementExpand").click(function (evt) {
            try {
                // Close any other open refinements
                $(".refinementPopup").hide();

                var parent = $(this).parent();

                while (parent != null && !parent.is(".sidebox")) {
                    parent = parent.parent();
                }

                if (parent == null) {
                    showErrorMsg("");
                    return;
                }

                var id = parent.get(0).id;
                var popup = getRefinementPopup(id);
                var container = getRefinementPopupContentContainer(id);

                container.css({position: "relative", top: 10, left: 0, width: "100%", height: "90%", overflow: "auto"});

                // has popup already been popuplated
                var isPopulated = container.children("ul") != null && container.children("ul").length != 0;

                repositionRefinementPopupToSidebox(parent, popup);
                popup.show();

                var endPosition = getRefinementPopupEndPosition(popup);

                if (!isPopulated) {
                    loadRefinementList($(this), container, popup, parent);
                }
                // animate to correct end location
                animateRefinementPopup(popup, endPosition.top, endPosition.width, endPosition.height, 'slow');

            } catch (err) {
                showErrorMsg("");
            }

            evt.preventDefault();
        });

        $("a[data-doclink]").on('click', function () {
            try {
                var $link = $(this);
                var did = $link.data('did');
                var url = "/docattempt?r=" + $link.data('reg') + "&ind=" + $link.data('cyb') + '&did=' + did;
                var category = "Detail";
                var lnkCategory = $link.attr('data-action-event-category');

                if (lnkCategory != null && lnkCategory.length != 0)
                    category = lnkCategory;

                $.innovadex.tracking.trackPage(url);
                $.innovadex.tracking.trackEvent(category, "View Document", did);
            } catch (ex) { /* Do nothing */
            }
        });

        $(".doctranslator").on('click', function () {
            try {
                var url = "/documents/" + $(this).attr("did") + "/text";
                $.innovadex.tracking.trackPage(url);
            } catch (ex) { /* Do nothing */
            }

            return true;
        });

        String.prototype.startsWith = function (str) {
            return (this.match("^" + str) == str);
        }

        expandCollapseRefinements();

        //NOTE: This shouldn't be used with AJAX forms because there's no way to clear the interval in this function
        $(document).on('submit', 'form.with-progress', function (ev) {

            //to do: determine the width that the progress container
            //should be relative to any buttons in the footer

            $('.progress:hidden', $(this)).show();
            var current_perc = 0,
                intTime = $('.progress', $(this)).data('interval') || 50;


            setInterval(function () {
                if (current_perc >= 100) {
                    current_perc = 0;
                } else {
                    current_perc += 1;
                    $('.progress .bar', $(this)).css('width', (current_perc) + '%');
                }
            }, intTime);
        });

        try {
            initRefinementListSearch();
        } catch (e) {
            console.log("Error initializing refinement list search");
        }
    };
    
     $(document).ready(function() {
         initDesktopElements();

         document.addEventListener('htmx:afterSwap', function(event) {
             if(event?.detail?.boosted) {
               console.log('inside boosted desktop.js init');
               initDesktopElements();
             }
           });
     });
    })();

    $.extend({
        inspect: function (item)
        {
            if (typeof (item) == 'object')
            {
                var string = "{ ";

                for(prop in item)
                {
                    string += prop + ' : ' + item[prop] + ", ";
                }

                string += " }";

                return string;
            }
            else
                return item;
        },

        setupSelectAutoComplete: function ($select, $val_field)
        {
            var classes = $select.attr("class");
            var selected = $select.find("option:selected");

            $select.hide();

            $("<input/>")
                .val(selected.text())
                .insertAfter($select)
                .click(function ()
                {
                    $(this).val('');
                    $(this).focus();
                }).autocomplete({

                    data: $select.children("option").map(function ()
                    {
                        return ({ result: $(this).text(), value: $(this).attr("value"), cc: $(this).attr("cc") });
                    }).get(),

                    minChars: 0,
                    mustMatch: true,
                    max: 500,
                    formatItem: function (item) { return item.result; },

                    result: function (evt, data, formatted)
                    {
                        $val_field.val(data.value);
                        $($select).trigger('autoCompleteResult', data);
                    }

                }).addClass("textbox").addClass(classes).attr('id', 'ac_' + $select.attr('id'));
        }

    });
}

function supports_html5_storage() {
    return ('localStorage' in window) && window['localStorage'] !== null;
}

function store(key, val) {
    if (supports_html5_storage())
        localStorage[key] = val.toString();
}

function retrieve(key) {   
    if (!supports_html5_storage())
        return null;

    return localStorage[key];
}

function updateRefinementState(id, collapsed) {
    if (industryId == null || id == null || id.length == 0)
        return;

    var key = id + "-" + industryId.toString();
    // store using localStorage
    store(key, collapsed);
}

function expandCollapseRefinements() {
    if (!supports_html5_storage()) {
        return;
    }

    if (typeof industryId != 'undefined' && industryId == null)
        return;

    $('#refinementLists').children().each(function (index, value) {
        var id = $(this).attr('id');
        var val = retrieve(id + "-" + industryId.toString());
        if (val != null) {
            if (val == "true" || val == true) {
                var obj = $('#' + id + ' a.flipper');
                if (obj != null)
                    obj.click();
            }
        }
    });
}

/*function roundCorners(selector) {
    // Internet Explorer should not keep the borders because it then does
    // not do the rounding correctly so it ends up with square corners.

    // not going to round ie at all - Adam 2/10/2011
    if ($.browser.msie)
        return;

    var cornerStyle = "";
    if (!$.browser.msie)
        cornerStyle = "keep";
    
    if (selector.length != 0 && selector.substr(selector.length - 1, 1) != " ")
        selector += " ";
            
    $(selector + ".round").corner(cornerStyle);
    $(selector + ".roundtop").corner("top " + cornerStyle);
    $(selector + ".roundbottom").corner("bottom " + cornerStyle);
    $(selector + ".roundleft").corner("left " + cornerStyle);
    $(selector + ".roundright").corner("right " + cornerStyle);
    $(selector + ".roundbottomleft").corner("bl " + cornerStyle);

    if (!$.browser.msie) {
        $(selector + ".button").corner("keep");
    }
}*/

function ajaxifyForm(form, onsuccessMethod)
{
    $.ajax({
        type: "POST",
        url: $(form).attr("action"),
        dataType: "json",
        data: $(form).serialize(),
        success: function(data, status, xhr)
        {
            if (typeof onsuccessMethod != 'undefined' && onsuccessMethod != null)
                eval(onsuccessMethod);

            $(form).trigger('ajax:success', [data, status, xhr]);
        },
        error: function (xhr, status, error) 
        {
            $(form).trigger("ajax:failure", [xhr, status, error]);
            var customMessage = "";

            try {
                if (showErrorDetail)
                    customMessage = error;
            }
            catch (err) {
                customMessage = "";
            }

            showErrorMsg(customMessage);
        },
        complete: function (xhr) {
            $(form).trigger("ajax:complete", xhr);
        }
    });

    return false;
}

function keywordFormSubmitted(evt)
{
    evt.preventDefault();
    var keyword_input = $("#k");
    var keyword = keyword_input.val();

    if (typeof(keyDefaultText) != 'undefined' && keyDefaultText != null && keyDefaultText == keyword)
        return;
    
    var category = "Search";
    var inputCategory = keyword_input.attr('data-action-event-category');
    if (inputCategory != null && inputCategory.length != 0) 
        category = inputCategory;

    $.innovadex.tracking.trackEvent(category, "Keyword Search", keyword);

    performKeywordSearch("k", keyword);
}

function homeKeywordSubmitted()
{
    performHomeKeywordSearch($("#homepagek").val());
    $.innovadex.tracking.trackEvent("Home", "Home Page Keyword Search", $("#homepagek").val());
    return false;
}

jQuery.fn.preventDoubleSubmit = function()
{
    jQuery(this).submit(function() {
        var $form = $(this);

        // Do not want beenSubmitted to be set if form has validation errors
        if ('validator' in $form.data())
        {
            if ($form.valid() === false)
                return false;
        }

        if (this.beenSubmitted)
            return false;
        else
            this.beenSubmitted = true;
    });
};

function getRefinementPopup(sideboxId)
{
    return ($("#" + sideboxId + "Popup"));
}

function getSideboxFromPopupId(popupId)
{
   return ($("#" + popupId.replace("Popup", "")));
}

function getRefinementPopupContentContainer(sideboxId)
{
    return ($("#" + sideboxId + "PopupContent"));
}

function repositionRefinementPopupToSidebox(sidebox, popup)
{
    var sideboxPos = sidebox.position();
    popup.css({ position: "absolute", top: sideboxPos.top, left: sideboxPos.left });
    resizeRefinementPopup(popup, sidebox.width(), sidebox.height());
}

function resizeRefinementPopup(popup, width, height)
{
    popup.css({ width: width, height: height });
}

function closeRefinementPopup(popupId)
{
    var popup = $('#' + popupId);
    var sidebox = getSideboxFromPopupId(popupId);

    animateRefinementPopup(popup, sidebox.position().top,
        sidebox.width(), sidebox.height(), "slow", function() { popup.hide() });
}

function getRefinementPopupEndPosition(popup)
{
    //TODO: add some code to resize instead of using fixed height/width based on screen size
    
    var endTop; 
    var endWidth;
    var endHeight;
    
    var relativeTop = $(window).scrollTop();
    // determine middle of screen
    var middle = $(window).height() / 2 + relativeTop;
    
    var currentTop = (popup.position().top);
    endTop = currentTop;
    endWidth = 400;
    endHeight = 400;
    
    if (currentTop > middle) {
        // expand up
        endTop = (currentTop + popup.height()) - endHeight;        
    } else {
        // expand down 
    }
    
    return ({ top: endTop, width: endWidth, height: endHeight });
}

function animateRefinementPopup(popup, endTop, endWidth, endHeight, speed, callback)
{
    var step = 20;
    var top = popup.position().top;
    var width = popup.width();
    var height = popup.height();

    var topAnimationEnabled = (top != endTop);
    var widthAnimationEnabled = (width != endWidth);
    var heightAnimationEnabled = (height != endHeight);

    // determine the max # of frames needed for animation
    var maxframes = (Math.abs(endTop - top) / step);
    if ((Math.abs(endHeight - height) / step) > maxframes)
        maxframes = (Math.abs(endHeight - height) / step);
    if ((Math.abs(endWidth - width) / step) > maxframes)
        maxframes = (Math.abs(endWidth - width) / step);

    // calculate animation time (jquery has a slow=600ms and fast=200ms so i'll use same values here)
    if (isNaN(speed)) {
        if (speed == "fast")
            speed = 200;
        else
            speed = 600;
    }
    
    var animTime = speed / maxframes;
    
    var timers = [];
    for (var i=0; i < maxframes; i++) {
        timers[i] = window.setTimeout(function() {
            if (topAnimationEnabled) {
                if (top < endTop) {
                    if ((top + step) > endTop)
                        top = endTop;
                    else
                        top += step;
                } else {
                    if ((top - step) < endTop)
                        top = endTop;
                    else
                        top -= step;
                }
            }

            if (widthAnimationEnabled) {
                if (width < endWidth) {
                    if ((width + step) > endWidth)
                        width = endWidth;
                    else
                        width += step;
                } else {
                    if ((width - step) < endWidth)
                        width = endWidth;
                    else
                        width -= step;
                }
            }

            if (heightAnimationEnabled) {
                if (height < endHeight) {
                    if ((height + step) > endHeight)
                        height = endHeight;
                    else
                        height += step;
                } else {
                    if ((height - step) < endHeight)
                        height = endHeight;
                    else
                        height -= step;
                }
            }

            if (top == endTop)
                topAnimationEnabled = false;
            if (width == endWidth)
                widthAnimationEnabled = false;
            if (height == endHeight)
                heightAnimationEnabled = false;

            popup.css({ top: top, width: width, height: height });
        
            if (!topAnimationEnabled && !widthAnimationEnabled && !heightAnimationEnabled) {
                if (callback != null)
                    callback();
            }
            
        }, animTime*(i+1));
    }
}

function registerRefinementPopupExpandEvent(listId)
{
    $("#" + listId + " li .showChildren").click(function()
    {
        try {
            var parent = $(this).parent();

            if (!parent.is("li")) {
                showErrorMsg("");
                return;
            }

            var popup = parent.parent();

            while (popup != null && !popup.is(".refinementPopup")) {
                popup = popup.parent();
            }

            if (popup == null) {
                showErrorMsg("");
                return;
            }

            var popupId = popup.get(0).id;
            var content = $('#' + popupId + 'Content');
            
            var list = parent.children("ul");
            var img = $(this).children(0);
            if ($(img).attr("src") == minusImageUrl) {
                list.hide();
                $(img).attr("src", plusImageUrl);
            }
            else {
                var isPopulated = list.length != 0;

                if (!isPopulated)
                {
                    trackRefinementEvent("Expanded", $(this));
                    loadRefinementList($(this), parent, popup);
                }
                else
                    list.show();

                $(img).attr("src", minusImageUrl);
            }
        }
        catch (err) {
            showErrorMsg("");
        }

        return false;
    });
}

function loadRefinementList(sourceElement, container, baseContainer, parent)
{
    var loadingMsg = $("#refinementsLoadingMsg");
    var textOffset = $(sourceElement).offset();
    loadingMsg.css({ top: textOffset.top - 5, left: textOffset.left });
    loadingMsg.show();
    var href = sourceElement.attr("href");

    var isGreen = false;
    var isProperty = false;
    var showCounts = true;
    if (typeof parent != 'undefined' && parent != null)
    {
        isGreen = parent.hasClass('ecotech');
        isProperty = parent.attr('id').indexOf('property') == 0;

        showCountsAttr = parent.attr('data-show-counts');

        if (showCountsAttr != null && showCountsAttr == 'false')
            showCounts = false;
    }

    $.ajax({
        type: "GET",
        url: href,
        dataType: "json",
        success: function (data) {
            var newListId = sourceElement.get(0).id + "_list";
            var listHtml = "<ul id='" + newListId + "'>";
            var itemClass = "class='refinementlink'";

            if (isProperty)
                itemClass = "";

            $.each(data, function (i, item) {
                var extraAttr = 'data-ref-type="' + sourceElement.get(0).id.split('_')[0] + '" data-ref-label="' + item.Text + '(' + item.ID + ')"';

                if (isProperty)
                    extraAttr = " data-prop-refinement='true' data-property-id='" + item.ID + "'";
                
                var itemHtml = "<a " + itemClass + " href='" + item.Url + "' " + extraAttr + ">" + item.Text
                if (showCounts)
                    itemHtml = itemHtml + " (" + item.Count + ")" 
                itemHtml = itemHtml + "</a>";

                if (isGreen) {
                    var whoisthis = "Who is this?";
                    if (whoisthisphrase != null && whoisthisphrase.length > 0)
                        whoisthis = whoisthisphrase;
                    // TODO: check for url on data, if not available need blank image spacer to make sure all text aligns properly
                    if (item.CategoryUrl != null && item.CategoryUrl.length > 0)
                        itemHtml = "<a href='" + item.CategoryUrl + "' title='" + whoisthis + "' target='_blank'><img style='width:17px;' src='" + greenImageUrl + "' /></a>&nbsp;" + itemHtml;
                    else
                        itemHtml = "<span style='width:24px;'>&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;" + itemHtml;
                } else {
                    if (item.ChildrenUrl != null && item.ChildrenUrl != "")
                        itemHtml = "<a id='" + newListId + "_" + i + "' class='showChildren' href='" + item.ChildrenUrl + "'" + extraAttr + "><img alt='+' src='" + plusImageUrl + "' /></a>&nbsp;" + itemHtml;
                    else
                        itemHtml = "<span class='bullet'>&#8226;</span>" + itemHtml;
                }
                listHtml = listHtml + "<li>" + itemHtml + "</li>";
            });
            container.append(listHtml + "</ul>");

            registerRefinementPopupExpandEvent(newListId);
            $("#" + newListId + " .refinementlink").click(refinementLink_clicked);
            loadingMsg.hide();
        },
        error: function (e, xhr) {
            var customMessage = "";

            try {
                if (showErrorDetail)
                    customMessage = xhr;
            }
            catch (err) {
                customMessage = "";
            }

            loadingMsg.hide();
            baseContainer.hide();
            showErrorMsg(customMessage);
        }
    });
}

function performHomeKeywordSearch(term)
{
  try
  {
    term = $.trim(term);
    if (term == "" || term == keyDefaultText) {
        return;
    }
    
    encode = encodeURIComponent||escape;
    term = encode(term);
    term = term.replace("%20", "+");
    
    var selectPopup = $("#keywordIndustrySelect");
    var list = selectPopup.children("ul");

    if (list.children("li").length == 0) {
        var textOffset = $("#homepagek").offset();
        selectPopup.css({ top: textOffset.top - 75, left: textOffset.left });
    }
    else
        list.html("");

    $.each($("#industrylist a"), function(i, item)
    {
        var href = addQuerystringParam($(this).attr("href") + "/search?k=" + term, "st", "1");
        var $item = $(document.createElement("li"));
        var $anchor = $(document.createElement("a"))
            .html($(this).text())
            .attr(
                {
                    'href': href,
                    'data-action-event': 'Home Keyword Industry Select',
                    'data-action-event-label': $(this).text()
                }
            );
        $item.append($anchor);
        list.append($item);
        $anchor.click(App.actions.handleTrackingActionEvent);
    });
    
    selectPopup.show();
  }
  catch(e)
  {
    alert(e.message);
  }
}

function performKeywordSearch(param, term) {
    // NOTE: As of Equipment launch Qtr 1 2011 a keyword search will ALWAYS start a NEW search.
    var searchWithin = false;
    var newUrl = $("#keywordForm").attr('action');

    if (newUrl == null)
        return;
        
    term = $.trim(term);
    if (term == "") {
        showErrorMsg("Please enter a search term");
        return;
    }
    
    encode = encodeURIComponent||escape;
    term = encode(term);
    term = term.replace(/ /g, "+").replace("%20", "+");

    newUrl = addQuerystringParam(newUrl, param, term, false);
    newUrl = addQuerystringParam(newUrl, "st", "1", true);      // Always should have search search-type

    // Add search order to querystring if its available
    if (typeof searchOrder != 'undefined' && searchWithin)
        newUrl = newUrl + "&so=" + searchOrder;
        
    if (typeof parentSearchLogId != 'undefined' && searchWithin)
        newUrl = newUrl + "&sl=" + parentSearchLogId;
        
    redirectToUrl(newUrl);
}

function getSearchBaseUrl(searchWithin)
{
    var newUrl;

    if (searchWithin)
        newUrl = textSearchBaseUrl;
    else
        newUrl = newTextSearchBaseUrl;

    var reg = $("#searchRegion");

    if (reg == null)
        return null;

    newUrl = newUrl.replace("{region}", reg.val());

    var cyb = $("#searchCybrary");

    if (cyb == null)
        return null;

    newUrl = newUrl.replace("{cybrary}", cyb.val());
    newUrl = newUrl.replaceAll("&amp;", "&");
    

    return newUrl;
}

function refinementLink_clicked(evt)
{
    var $link = $(this);
    redirectToSelectedRefinement($(this), this.href);
    
    evt.preventDefault();
}

function redirectToSelectedRefinement($el, href)
{
    if ($el.attr('data-ref-type'))
        trackRefinementEvent("Selected", $el);

    if (href.startsWith("javascript:")) {
        // allow the javascript method to be called by returning true
        return true;
    }

    var url = addQuerystringParam(href, "st", 1, true);
    url = addSearchQueryParams(url);

    redirectToUrl(url);
}

function addSearchQueryParams(url)
{
    if (typeof searchOrder != 'undefined') {
        url = addQuerystringParam(url, "so", searchOrder, true);
    }

    if (typeof parentSearchLogId != 'undefined') {
            url = addQuerystringParam(url, "sl", parentSearchLogId, true);
    }

    return url;
}

function trackRefinementEvent(action_type, $element)
{
    var action = $element.attr("data-ref-type") + ' - ' + action_type;
    var label = $element.attr('data-ref-label');
    var category = "Search Filter";
    var lnkCategory = $element.attr('data-action-event-category');

    if (lnkCategory != null && lnkCategory.length != 0)
        category = lnkCategory;
    $.innovadex.tracking.trackEvent(category, action, label);
}

function addQuerystringParam(url, param, value, replaceValueIfParamExists)
{
    if (url.charAt(url.length - 1) == "#")
        url = url.substr(0, url.length - 1);
        
    if (url.indexOf("?") == -1)
        url = url + "?" + param + "=" + value;
    else {
        var paramIndex = url.indexOf(param + "=");
        if (paramIndex == -1)
            url = url + "&" + param + "=" + value;
        else {
            if (replaceValueIfParamExists)
            {
                var valBeginIndex = url.indexOf("=", paramIndex + 1) + 1;
                var valEndIndex = url.indexOf("&", paramIndex + 1);
                
                if (valEndIndex == -1)
                    url = url.substr(0, valBeginIndex) + value;
                else
                    url = url.substr(0, valBeginIndex) + value + url.substr(valEndIndex);
            }
            else
            {
                var sepIndex = url.indexOf("&", paramIndex + 1);

                if (sepIndex == -1)
                    url = url + "|" + value;
                else
                    url = url.substr(0, sepIndex) + "|" + value + url.substr(sepIndex);
            }
        }
    }
    
    return url;
}

function removeQuerystringParam(url, param)
{
    var paramIndex = url.indexOf(param + "=");

    if (paramIndex != -1)
    {
        var valEndIndex = url.indexOf("&", paramIndex + 1);

        if (valEndIndex == -1)
            url = url.substr(0, paramIndex);
        else
            url = url.substr(0, paramIndex) + url.substr(valEndIndex);
    }

    return url;
}

function showErrorMsg(customMessage, customHeader, closeFunction) {
    var message;

    if (customMessage != null && customMessage != "")
        message = customMessage;
    else
        message = "Sorry...An error occurred";

    openErrorModal(message, customHeader, closeFunction);
}

function ChangeDomain( prefix ) {
    var d = $("#selectDomain").get(0);
    var s = d.options[d.selectedIndex].value;
    redirectToUrl("http://" + prefix + "." + s);
}

function loadPlayer(fil, id, player, width, height) {

    var flashvars = {
        file: fil,
        id: id,
        autostart: 'true'
    };
    var params = {
        align: 'middle',
        play: 'true',
        wmode: 'transparent',
        allowFullScreen: 'true'
    };
    var attributes = {
        id: id,
        name: "name"
    };

    swfobject.embedSWF(player, "media_region", width, height, "9.0.0", null, flashvars, params, attributes);
}

/*function trackPage(url)
{
    try {
        if (typeof(pageTracker) != 'undefined' && pageTracker != null) {
            if (typeof(setAnalyticsVariables) != 'undefined' && setAnalyticsVariables != null)
                setAnalyticsVariables();
                
         $.innovadex.tracking.trackPage(url);
        }
    } catch(err) {}
} */

function openSpotlightModal(url) {
    var h = $(window).height();
    //var w = $(window).width();
    h = (h < 500) ? 500 : h - 100;
    //w = (w < 900) ? 900 : w - 100;
    openModal(url, h, 900, "#CCC");
}

function openExchangeInfoModal(url) {
    var h = $(window).height();
    //var w = $(window).width();
    h = (h < 500) ? 500 : h - 100;
    //w = (w < 900) ? 900 : w - 100;
    var callback = null;

    callback = function () {
        DesktopApp.pages.exchangeinfo.new_view.init($("#modal_placeholder"))
        var h = $('#simplemodal-container').height();
        h = h - 45;
        $('#plaindetailcontent').height(h);


    };
    openModal(url + "?minimal=1", h, 900, "#CCC", callback);


}

function openDetailModal(url) {
    var h = $(window).height();
    //var w = $(window).width();
    h = (h < 500) ? 500 : h - 100;
    //w = (w < 900) ? 900 : w - 100;
    var callback = null;

    callback = function (responseText, textStatus, xhr)
    {
        if (DesktopApp.actions.checkModalStatus(xhr))
        {
            DesktopApp.pages.search.showdetail_view.init($("#modal_placeholder")) 
            var h = $('#simplemodal-container').height();
            h = h - 45;
            $('#plaindetailcontent').height( h );

            if( $('#restrictedmodal').length == 1 )
            {
              //var t = ($(window).height()/2)-175;
              //$('#simplemodal-container').animate({ height: "350px", top:t});
              $('.simplemodal-wrap','#simplemodal-container').css('height','auto');
              DesktopApp.utils.resetModalHeight('.simplemodal-container',true);
            }
        }
    };
    openModal(url + "?minimal=1", h, 900, "#CCC", callback);
    var actionLabel = $.innovadex.removeQuerystringParam(url, 'sl');
    actionLabel = $.innovadex.removeQuerystringParam(actionLabel, 'crit');
    actionLabel = $.innovadex.removeQuerystringParam(actionLabel, 'st');
    actionLabel = $.innovadex.removeQuerystringParam(actionLabel, 'noShow');
    $.innovadex.tracking.trackEvent("Search", "View Detail", actionLabel);
}

function openErrorModal(message, header_label, closeFunction)
{
  console.log("ERROR:");
  console.log(message);
  var $modal = $( '<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="errorModalLabel"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title" id="errorModalLabel"></h4></div><div class="modal-body"></div> </div></div></div>' );

  header_label = "undefined" == typeof header_label || header_label == null || header_label.length < 1 ? "Error" : header_label;

  $('.modal-header h4', $modal).html(header_label);
  $('.modal-body', $modal).html(message);

  $modal.modal('show');

  if( closeFunction )
  {
    $modal.on('hide.bs.modal', function (e) {
      closeFunction();
    });
  }

  //completely destroy modal instead of reset easiest for interop
  //with other modals
  $modal.on('hidden.bs.modal', function(e) {
   $(this).data('bs.modal', null);
  });
}

function openRestrictedResultModal(element, bookshelfId)
{
    if (bookshelfId != null) {
        // attempt to find checkbox for that bookshelf and select it
        var cbx = $('#bookshelf_' + bookshelfId);
        if (cbx != null)
            cbx.prop('checked', true);
    }
    
    openElementAsModal(element, 200, 600, '#ffffff', true);
}

function openElementAsModal(element, height, width, backgroundColor, isModal)
{
    if (typeof isModal == 'undefined' || isModal == null)
        isModal = false;

    element.modal({
        modal: isModal,
        minHeight: height,
        minWidth: width,
        overlay: 80,
        overlayCss: { backgroundColor: backgroundColor },
        onClose: function(dialog) { closeModal(); }
    });
}

var lastModalProps = null;
/*function openModal(url, height, width, backgroundColor, callbackFunction, useFrame, addCloseButton, allowFrameScrolling) {
    if (typeof (callbackFunction) == 'undefined' || callbackFunction == null)
        callbackFunction = openModalCallback;

    if (typeof (useFrame) == 'undefined' || useFrame == null)
        useFrame = false;

    if (typeof (addCloseButton) == 'undefined' || addCloseButton == null)
        addCloseButton = false;

    if (typeof (allowFrameScrolling) == 'undefined' || allowFrameScrolling == null)
        allowFrameScrolling = true;

    // turn scrolling off under the modal
    if (($.browser.msie) && ($.browser.version == "7.0") || ($.browser.version == "6.0"))
    {
        document.documentElement.style.overflow = "hidden";
    }
    else
    {
        document.body.style.overflow = "hidden";
    }
    DesktopApp.scrollbarWidth = DesktopApp.scrollbarWidth == 0 ? $.innovadex.scrollbarWidth() : DesktopApp.scrollbarWidth;

    if ( $.innovadex.pageScroll() || ( $.browser.msie && new Number( $.browser.version ) < 8 ) )
    {
      $('body').css('marginRight',DesktopApp.scrollbarWidth);
    }

    lastModalProps = new Object();
    lastModalProps.url = url;
    lastModalProps.height = height;
    lastModalProps.width = width;
    lastModalProps.backgroundColor = backgroundColor;
    lastModalProps.callbackFunction = callbackFunction;

    // prevent item from loading from cache (ie8 and below seems to have issues loading item from cache for modal)
    url = addQuerystringParam(url, "dtcache", (new Date()).getTime().toString(), false);

    if (useFrame)
    {
        var html = addCloseButton ? "<div class='floatright' style='padding-right: 5px'><a href='#' onclick='closeModal();return false;'>X</a></div>" : '';
        var scrolling = allowFrameScrolling ? "auto" : "no";
        html += "<iframe class='clear' src='" + url + "' frameborder='0' seamless scrolling='" + scrolling + "'";

        if (width != null)
            html += " width='" + (width - 30) + "px'";

        if (height != null)
            html += " height='" + (height - 30) + "px'";

        html += "></iframe>";
        $("#modal_placeholder").html(html);

        var modal_placeholder = $("#modal_placeholder");
        $("#modal_placeholder").modal({
            minHeight: height,
            minWidth: width,
            overlay: 80,
            overlayCss: { backgroundColor: backgroundColor },
            onClose: function(dialog) { closeModal(); }
        });
    } 
    else
    {
        /* so, we have issue with simplemodal that uses a timeout on the close of the dialog so when you have dialog open and are trying to close that
            then open another one, it will consistently fail. Using setTimeout of 500 before opening a new dialog resolves the issue as it gives enough
            time for the other dialog to full close (which the settimeout on simplemodal was added to overcome opera bug). So it is very imporatnt
            to not remove the settimeout here until we have rewritten this code to work with jquery ui dialog */
        /*var modal_placeholder = $("#modal_placeholder");
        window.setTimeout(function () {
            modal_placeholder.modal({
                minHeight: height,
                minWidth: width,
                maxWidth: width + 50,
                overlay: 80,
                overlayCss: { backgroundColor: backgroundColor },
                onClose: function(dialog) { closeModal(); }
            });

            modal_placeholder.load(url, null, callbackFunction);
        }, 500);

    }

    $.innovadex.tracking.trackPage(url);
}

function isModalOpen() {
  console.trace();
    return $("#" + $.modal.defaults.overlayId).html() != null
}

function closeModal() {
    // turn scrolling back on
    $('body').removeAttr('style');
    if (($.browser.msie) && ($.browser.version == "7.0") || ($.browser.version == "6.0")) {
        document.documentElement.style.overflow = '';
    }
    else {
        document.body.style.overflow = '';
    }

    lastModalProps = null;
    $.modal.close();
}

function restoreModal(modalProps) {
    closeModal();
    openModal(modalProps.url, modalProps.height, modalProps.width, modalProps.backgroundColor, modalProps.callbackFunction);
}

function openModalCallback(responseText, textStatus, XMLHttpRequest) {
    if (DesktopApp.actions.checkModalStatus(XMLHttpRequest))
    {
        $("#modal_placeholder .membersonly").click(membersOnlyClicked);
    }
}

function openLocaleModal() {
    var localeUrl = "/locale?time" + new Date().getTime().toString();
    openModal(localeUrl, 610, 900, "#CCC", function () {
        if (cookieRegionId != null && cookieRegionId.length > 0 &&
        cookieLanguageId != null && cookieLanguageId.length > 0 &&
        cookieRegionCode != null && cookieRegionCode.length > 0) {
            $('#inner-' + cookieRegionCode).css("display", "block");
            $('#selectlang' + cookieRegionId + '-' + cookieLanguageId).css("background-color", "#999");
        }
    });
}*/

function membersOnlyClicked(evt) {
    evt.preventDefault();

    var targetUrl = "";
    var $link = $(this);
    var href = $link.attr("href");
    if (typeof (href) != 'undefined' && href.length != 0) {
        // in IE, the href will be the full url with # at the end when the href is "#"
        if (href == "#" || href == window.location.href + "#")
            targetUrl = window.location.href;
        else
            targetUrl = href;
    }

    var extra_params = null;
    var did = $link.attr('did');

    if (did != null && did.length != 0) {
        extra_params = { 'did': did };

        var dtype = $link.attr('dtype');

        if (dtype != null && dtype.length != 0)
            extra_params['dtype'] = dtype;

        var bid = $link.attr('bid');

        if (bid != null && bid.length != 0)
            extra_params['bid'] = bid;

        var bsid = $link.attr('bsid');

        if (bsid != null && bsid.length != 0)
            extra_params['bsid'] = bsid;
    }

    openLoginModal(targetUrl, extra_params);
}

var loginRedirectUrl;
var loginModalRestoreProps;

function openLoginModal(targetUrl, extra_params) {
    /*if (isModalOpen()) {
        loginModalRestoreProps = lastModalProps;
        closeModal();
    } else
        loginModalRestoreProps = null;
        */
  // is modal available
  var modal = $('#modal');
  if (modal == null || modal.length == 0) return false;

    if (languageCode.length == 0)
        languageCode = 'en';

    var loginUrl = addQuerystringParam("/session/new", "version", versionStr);
    loginUrl = addQuerystringParam(loginUrl, "lang", languageCode);

    if (typeof(targetUrl) != 'undefined' && targetUrl.length != 0) {
        loginUrl = $.innovadex.addQuerystringParam(loginUrl, 'ReturnUrl', encodeURIComponent(targetUrl), true);
        loginRedirectUrl = targetUrl;
    } else
        loginRedirectUrl = "/";

    if (typeof extra_params != 'undefined' && extra_params != null) {
        $.each(extra_params, function(key, value) {
            loginUrl = $.innovadex.addQuerystringParam(loginUrl, key, value, true);
        });
    }

    if( $('.navbar.visible-phone').is(':visible') )
    {
      document.location = loginUrl;
    }
    else
    {
      //closeModal(); // needed for modal to be resized
      var current_perc = 0;
      progress = setInterval(function() {
          if (current_perc >= 100) {
              current_perc = 0;
          } else {
              current_perc++;
              //console.log(current_perc);
              $('.modal .progress .bar').css('width', (current_perc) + '%');
          }
      }, 50);

      var executeOnLoad = function() {
        $("#loginform").submit(function() {
          $.innovadex.tracking.trackPage('/login/submitted');
        });
        $("#email").focus();
      };

        //console.log('login url:' + loginUrl);

      $('#myModalLabel').html('Login');
      modal
          //.css({ width: '750px', 'margin-left': '-375px' })
          .on('loaded', function() {
              clearInterval(progress);
              setTimeout(executeOnLoad, 500); // hack but necessary for everything to be in dom to set focus
          })
          .on('shown', function() {
              $("#email").focus();
          })
          .modal({ remote: '/users/new', backdrop: true });
      //openModal(loginUrl, 415, 750, "#CCC", openLoginCallback);
      $.innovadex.tracking.trackPage(loginUrl);

      return true;
    }
}

function openLoginCallback(responseText, textStatus, XMLHttpRequest) {
    if (textStatus == "error") {
        showErrorMsg(responseText);
        closeModal();
    }
    else {
        initLogin();
    }
}

var loginInProgress = false;

function handleLoginPopupSubmit() {
    var form = $("#loginform");
    $("#loginErrText").html("<img src='" + loadingImgPath + "' />");
    loginInProgress = true;

    $.ajax({
        type: "POST",
        url: $(form).attr("action"),
        dataType: "json",
        data: $(form).serialize(),
        success: function (data) {
            loginInProgress = false;
            if (data == null || typeof (data.resultCode) == 'undefined' || data.resultCode == null) {
                $("#loginErrText").html("");    // Clear loading image
                showErrorMsg("Unexpected error occurred. Please try again.");
                closeModal();
                return;
            }

            if (data.resultCode == 0) {
                if (data.url == null || data.url.length == 0) {
                    if (loginRedirectUrl == null)
                        loginRedirectUrl = "/";
                }
                else
                    loginRedirectUrl = data.url;

                redirectToUrl(loginRedirectUrl);
            }
            else if (data.resultCode == 2)
                redirectToUrl(data.url);
            else
                $("#loginErrText").html(data.errMsg);
        },
        error: function (e, xhr) {
            loginInProgress = false;
            $("#loginErrText").html("");    // Clear loading image

            var customMessage = "";

            try {
                if (showErrorDetail)
                    customMessage = xhr;
            }
            catch (err) {
                customMessage = "Unknown Login Error.";
            }

            showErrorMsg(customMessage);
        }
    });

    return false;
}

function closeLoginModal() {
    if (loginModalRestoreProps == null)
        closeModal();
    else {
        restoreModal(loginModalRestoreProps);
        loginModalRestoreProps = null;
    }
}






function regionRestrictionClicked() {
    var targetUrl = "";
    var href = $(this).attr("href");
    if (typeof (href) != 'undefined' && href.length != 0) {
        // in IE, the href will be the full url with # at the end when the href is "#"
        if (href == "#" || href == window.location.href + "#")
            targetUrl = window.location.href;
        else
            targetUrl = href;
    }

    openRegionRestrictionModal(targetUrl);
    return false;
}

var regionRestrictionRedirectUrl;
var regionRestrictionModalRestoreProps;

function openRegionRestrictionModal(targetUrl) {
    if (isModalOpen())
        regionRestrictionModalRestoreProps = lastModalProps;
    else
        regionRestrictionModalRestoreProps = null;

    if (languageCode.length == 0)
        languageCode = 'en';

    var regionRestrictionUrl = addQuerystringParam("/noregionaccess/" + regionId, "version", versionStr);

    if (typeof (targetUrl) != 'undefined' && targetUrl.length != 0)
        regionRestrictionRedirectUrl = targetUrl;
    else
        regionRestrictioRedirectUrl = "/";

    closeModal(); // needed for modal to be resized
    openModal(regionRestrictionUrl, 330, 750, "#CCC", openRegionRestrictionCallback);
}

function openRegionRestrictionCallback(responseText, textStatus, XMLHttpRequest) {
    if (textStatus == "error") {
        showErrorMsg(responseText);
        closeModal();
    }
}

function closeRegionRestrictionModal() {
    if (regionRestrictionModalRestoreProps == null)
        closeModal();
    else {
        restoreModal(regionRestrictionModalRestoreProps);
        regionRestrictionModalRestoreProps = null;
    }
}

function handleAnchorNewWindow(evt) {
    openUrlInNewWindow($(this).attr('href'));
    return false;
}

function openNewWindow(anchor) {
    openUrlInNewWindow(anchor.href);
}

function openUrlInNewWindow(url) {
    window.open(url, "Innovadex");
}

function postBookmark(bookmarkUrl, bookId, bookShelfId, searchTypeId) {
    if (searchTypeId === 'undefined' || searchTypeId == null)
        searchTypeId = null;

    $.ajax({
        type: "POST",
        url: bookmarkUrl,
        dataType: "json",
        data: {
            bookId: bookId,
            BookshelfId: bookShelfId,
            searchTypeId: searchTypeId
        },
        beforeSend: function() {
          $("#detail-bookmark-link i").removeClass('fa-bookmark-o').addClass('fa-spinner fa-spin');
        },
        success: function (res) {
            clearContainer('mybookmarklist');
            $("#detail-bookmark-link").replaceWith("<a class=\"btn btn-default disabled\"><i class=\"fa fa-fw fa-bookmark\"></i>" + res.bookmarkedText + "</a>");
        },
        error: function (msg, textStatus, errorThrown) {
          $("#detail-bookmark-link i").removeClass('fa-spinner fa-spin').addClass('fa-warning');
          div_swap("bookmarkOn", "bookmarkOff");
          showErrorMsg(textStatus + " " + errorThrown);
        }
    });
}

function postBookmarkFromResults(linkId, bookmarkUrl, bookId, bookShelfId, phraseText, searchTypeId) {
    //alert(linkId + " " + bookmarkUrl + " " + bookId + " " + bookShelfId + " " + phraseText);
    if (searchTypeId === 'undefined' || searchTypeId == null)
        searchTypeId = null;

    $.ajax({
        type: "POST",
        url: bookmarkUrl,
        data: {
            bookId: bookId,
            BookshelfId: bookShelfId,
            searchTypeId: searchTypeId
        },
        beforeSend: function (msg) {
        },
        success: function (msg) {
            if (linkId && $('#' + linkId)) {
                $('#' + linkId).html(phraseText);
                $('#' + linkId).removeAttr('href').attr('onclick', 'return (false);');
            }
            $('#menubookmarks').html(msg);
        },
        error: function (msg, textStatus, errorThrown) {
            showErrorMsg(textStatus + " " + errorThrown);
        }
    });
}

function ajaxRequest(url, type, data, onSuccess, onError, dataType) {
    if (dataType == null)
        dataType = "json";

    $.ajax({
        type: type,
        url: url,
        dataType: dataType,
        data: data,
        success: onSuccess,
        error: onError
    });
}

function handlePurchaseClick(e, hasAccepted) {
    e.preventDefault();
    
    if(hasAccepted) {
        $('#submit_purchase_confirmation_modal').click();
    }
    else {
        $('#purchase_confirmation_modal').modal();
    }
}

function postSampleCart(linkid,
        url,
        bookshelfId,
        bookId,
        searchTypeId,
        sampleAddedPhrase,
        callback,
        loadingLinkToShow,
        elementToHideWhileLoading,
        successElementToShow) {

    var elementToHide = $('#' + elementToHideWhileLoading);
    var loadingLink = $('#' + loadingLinkToShow);

    if (elementToHide != undefined) {
        elementToHide.hide();
    };

    if (loadingLink != undefined) {
        loadingLink.show();
    };

    var data = {
        bookshelfId: bookshelfId,
        bookId: bookId,
        searchTypeId: searchTypeId
    };

    $.post(url, data,
        function (result) {
            if (loadingLink != undefined) {
                loadingLink.hide();
            };

            if (elementToHide != undefined) {
                elementToHide.show();
            };

            if (result == null || result.length == 0)
                showErrorMsg("Unknown error occurred. Please try again.");
            else {
                // update sample cart item count
                if ($('[data-samplecart-total-items]')) {
                    $('[data-samplecart-total-items]').html(result.totalItems.toString());
                }

              if (callback != null && typeof(callback) == 'function')
                callback(result, linkid, successElementToShow);
            }
        }
        , "json"
    );
}

function div_swap( show_div, hide_div ) {
    $('#' + show_div).css("display", "block");
    $('#' + hide_div).css("display", "none");
}

function checkRegionAndLanguage(url) {
    if (typeof localeCookieName != 'undefined') {
        var regionLanguageCookie = getCookie(localeCookieName);
        if (regionLanguageCookie == "") {
            //if (!window.location.toString().match( /(session)/ ) ) {
            // got to get cookie.
            openLocaleModal();
            //}
        }
        else {
            // good to go
        }
    }
} 

function selectLanguage(languageId, regionId) {
    $.ajax({
        type: "POST",
        url: "/locale/Update",
        data: "LanguageId=" + languageId + "&RegionId=" + regionId + "&url=" + $.innovadex.url_encode(window.location),
        beforeSend: function(msg) {
        //alert(msg);
        },
        success: function(msg) {
            if ((performJavascriptLocaleRedirect == true) && (msg != "")) {
                //alert(msg);
                redirectToUrl(msg);
            }
            else if (msg.length != 0) {
                alert(msg);
            }
        },
        error: function(msg, textStatus, errorThrown) {
            showErrorMsg(textStatus + " " + errorThrown);
        }
    });
}

function validateEmail(url, email, onSuccess, onError)
{
    ajaxRequest(url,
        'get',
        { email: email, time: new Date().getTime() },
        onSuccess,
        onError);        
}

/// SUMMARY:
/// Function will make any select box with the class of autocomplete into an
/// autocomplete (using jquery UI AutoComplete) textbox utilizing the data
/// from the selects option tags.  Parameter resultFn should be a function that
/// takes id and value parameter and will be called when an autoselect box has
/// been changed. Will contain the original id of the select and the value that
/// was selected.
/// PRE:
/// Verify that autocomplete js has been included in page
/// POST:
/// All selects with autocomplete classes will be autocomplete textboxes
//function registerAutoComplete(resultFn)
//{
//    $("select.autocomplete").map(function()
//    {
//        var sel = $(this);
//        var classes = sel.attr("class");
//        sel.hide();
//        $("<input/>").insertAfter(sel).click(function()
//        {
//            $(this).focus();
//        }).autocomplete({
//            data: sel.children("option").map(function()
//            {
//                return ({ result: $(this).text(), value: $(this).attr("value") });
//            }).get(),
//            minChars: 0,
//            mustMatch: true,
//            formatItem: function(item) { return item.result; },
//            result: function(evt, data, formatted) { resultFn(sel.attr('id'), data.value); }
//        }).addClass("textbox").addClass(classes).attr('id', 'ac_' + sel.attr('id'));
//    });
//}

function load_detail(detail_url) {
    $.ajax({
        type: "GET",
        url: detail_url,
        success: function(response) {
            $('#simplemodal-container').html(response);
        }
    });
}

/* Show a popup div at a location just right and positioned with the top of the element
// specified by the sourceId parameter. Additional offsets may be provided to position 
// from there.*/
function showPopup(sourceId, popupId, offsetX, offsetY)
{
    if (offsetX == null)
        offsetX = 0;
    else
        offsetX = parseInt(offsetX);

    if (offsetY == null)
        offsetY = 0;
    else
        offsetY = parseInt(offsetY);
        
    var sourceId = '#' + sourceId;
    var popupId = '#' + popupId;
    
    var pos = $(sourceId).offset();
    var width = $(sourceId).width();

    $(popupId).css({ "left": (pos.left + width + offsetX) + "px", "top": pos.top + offsetY + "px" });
    $(popupId).show('slow').bgiframe();
}

function showPopupAt(sourceId, popupId, location)
{
    var offsetX = 0; 
    var offsetY = 0;

    var elementSourceId = '#' + sourceId;
    var elementPopupId = '#' + popupId;
    
    if (location == "bottomleft") {
        offsetY = $(elementSourceId).height();
        offsetX = $(elementSourceId).width() * (-1);
    } 
    
    if (location == "bottomright") {
        offsetX = $(elementPopupId).outerWidth() * (-1) + 15;
        offsetY = $(elementSourceId).height();
    }

    showPopup(sourceId, popupId, offsetX, offsetY);
}

function showPopupCentered(popupId,rootselector) 
{
    var root = rootselector == null || rootselector == undefined || rootselector == "undefined" || rootselector.length < 1 ? window : rootselector;
    popupId = "#" + popupId;
    var x = ($(root).width() / 2) - ($(popupId).width() / 2);
    var y = ($(root).height() / 2) - ($(popupId).height() / 2);
    $(popupId).css({ "left": x + "px", "top": y + "px" });

    $(popupId).show(); // ('slow').bgiframe();
}

function hidePopup(popupId)
{
    var popupId = '#' + popupId;
    $(popupId).hide('slow');
}

function showSaveSearchPopup(isAlert) {
    $("#isAlert").prop("checked", isAlert);
    showPopup('savesearch', 'savesearchpopup', -220, 10);
}

function validateEmailRegex(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return email.match(re);
}

function elementHasEventAttached(element, eventName) {
    var data = element.data('events');   //$.data(element.get(0), 'events');
    
    if (data != null)
        return data[eventName] != null;
    else
        return false;
}

function loadStateProvinceValues(getCountryId, stateControl) 
{
    if (typeof (stateControl) == 'undefined' || stateControl == null)
        stateControl = $("#StateProvince");

    $(stateControl).typeahead({
        source: function (query, typeahead) {
                $.ajax({
                    url: '/stateprovince/list',
                    data: { countryId: getCountryId(), time: new Date().getTime() },
                    dataType: 'json',
                    success: function(data, status, xhr) {
                        var items = [];
                        $(data).map(function(state_index, state) {
                            items.push(state.Name);
                        });
                        return typeahead(items);
                    }
                });
        },
        beforeSend: function() {
          $(stateControl).siblings('.add-on').children('i').removeClass('icon-search').addClass('icon-spinner icon-spin');
        },
        matcher: function (item) {
          if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
            return true;
          }
        },
        sorter: function (items) {
          return items.sort();
        },
        highlighter: function (item) {
          $(stateControl).siblings('.add-on').children('i').removeClass('icon-spinner icon-spin').addClass('icon-search');
          var regex = new RegExp( '(' + this.query + ')', 'gi' );
          return item.replace( regex, "<strong>$1</strong>" );
        }
    });

}

function showNotification(message, time, selector) {
    if (typeof selector == 'undefined' || selector == null)
        selector = "#page-notifications";

    $(selector).show(0, function () {
        $(selector + ' span').html(message).show(0, function () {
            window.setTimeout(function () {
                $(selector + ' span').hide(100, function () {
                    $(selector).hide(25);
                });
            }, time);
        });
    });
}

function saveSearch(regionId, cybraryId, name, searchString, searchTypeId)
{
    // user validation has been moved to page, this is just to prevent any other call from getting through with invalid data
    if (name.length < 1 || name.length > 50)
        return (false);

    var isAlert = $("#isAlert").is(':checked');

    $.ajax({
        type: "POST",
        url: '/savedsearches',
        data: { regionId: regionId, cybraryId: cybraryId, name: name, searchString: searchString, isAlert: isAlert, searchTypeId: searchTypeId },
        success: function (response) {
          //remove the list from the top submenu
          //close the popup
          //add success message to the results page
            /*$('#savedsearch_saving').hide();
            if (savedSearchSuccess == null || savedSearchSuccess.length == 0)
                savedSearchSuccess = 'Successfully saved your search';

            showNotification(savedSearchSuccess, 4000);*/
        },
        error: function (msg, textStatus, errorThrown) {
            //show error message in the popup
            showErrorMsg(msg + " " + textStatus);
        }
    });

    try
    {
        $.innovadex.tracking.trackEvent("Search", "Save Search");
    } catch (ex) { /* Do Nothing */ }

    return (true);
}

function changeSearchResultStyle(newStyleId)
{
    var currentUrl = window.location + "";
    redirectToUrl(addQuerystringParam(currentUrl, "srsid", newStyleId, true));
    return false;
}

function redirectToUrl(url)
{
    window.location = url;
}

function loadSearches(url, containerId)
{
    var container = $('#' + containerId);
    // verify that it has not already been loaded
    if (container.children().length > 0)
        return;

    ajaxRequest(url, 'GET', null,
    function(response)
    {
        container.append(response);
        $("a", container).click(App.actions.handleTrackingActionEvent);
    },
    function(response)
    {
        // handle error
    }, 'html');
}

function clearContainer(containerId)
{
    var container = $('#' + containerId);
    container.html('');
}

function refreshWindow()
{
    window.location.reload(true);
}

/* stopwords defines word arrays to use to make sure that google is not search for these words by themselves (we are not using to remove terms, just see if terms match and if so not search) */
var stopwords = [];
function isStopWord(word) {
    for (var i = 0; i < stopwords.length; i++)
        if (stopwords[i] == word)
            return (true);

    return (false);
}

function iwSearch() {
    if (gcse != null && iwKeywords != null && iwKeywords.length > 0 && !isStopWord(iwKeywords))
        gcse.search(iwKeywords);
}

function iwNextPage() {
    if (gcse != null && gcse.hasSearched())
        gcse.nextPage();
}

/* used when "web results" content type is clicked */
function ShowWebResults(inmodal) {
    // gcse is the custom google search engine that is created on the results page, if it's not available just return
    
    if (iwKeywords == null)
        return;

    // extra check for stopwords to stop before hiding information
    if (isStopWord(iwKeywords))
        return;

    if (inmodal) {
        showModalWebResults(); // search using modal
    } else {
        // hide results
        if (gcse == null)
            return;

        var searchOptionsBar = $('#search-results-options');
        if (searchOptionsBar != null)
            searchOptionsBar.hide();

        var restrictionMessage = $('#restrictedresultmessage');
        if (restrictionMessage != null)
            restrictionMessage.hide();

        if (resultsContainer != null)
            resultsContainer.hide();
        
        if (contentUrl != null)
            contentUrl = null;
        
        var pagingObject = $('div.paging');
        if (pagingObject != null)
            pagingObject.hide();

        iwSearch(); // does inline search
    }

}

function showModalWebResults() {
        var searchVisible = false;
        var resultsLoading = false;

        if (gcseid != null && gcseid.length > 0) {
            var loadingDiv = $('#google-iw-results-loading');
            google_search = new $.googlecustomsearch({
                cseid: gcseid,
                onSearchStarted: function () {
                    if (!searchVisible) {
                        searchVisible = true;
                        var $modal = $('#googlesearchresults_modal');
                        var $results_container = $('#googlesearchresults_container');
                        var $results = $('#google-iw-results');

                        $('#iw-branding').html(google_search.branding);
                        $results_container.scroll(function (evt) {
                            evt.preventDefault();
                            //var scrolloffset = this.height() / 2;
                            var position = $results.outerHeight() - ($results_container.height() * 1.5);
                            if ($results_container.scrollTop() >= position) {
                                if (!resultsLoading) {
                                    resultsLoading = true;
                                    google_search.nextPage();
                                    resultsLoading = false;
                                }
                            }
                        });

                        openElementAsModal($modal, 600, 800, '#ccc');

                    }

                    loadingDiv.show();
                },
                onSearchCompleted: function (searcher) {
                    loadingDiv.hide();
                    var $results = $('#google-iw-results');
                    if (searcher.results && searcher.results.length > 0) {
                        for (var i = 0; i < searcher.results.length; i++) {
                            var result = searcher.results[i];
                            searcher.createResultHtml(result);
                            if (result.html)
                                $results.append($(result.html.cloneNode(true)));
                        }
                    } else {
                        if ($results.html().length >= 13)
                            $results.html('No results were found');
                    }
                }
            });

            google_search.search(iwKeywords);

        } else {
            if (gcse == null)
                return;

            // need to clear existing results that are shown by simply remove all html inside of the results
            if (resultsContainer != null)
                resultsContainer.html('');

            // remove contenturl so that regular results aren't loaded via dynamic scrolling
            if (contentUrl != null)
                contentUrl = null;

            var pagingObject = $("div.paging");
            if (pagingObject != null)
                pagingObject.hide();

            iwSearch();
        }

}

function getCookie(name) {
    if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            start = start + name.length + 1;
            var end = document.cookie.indexOf(";", start);
            if (end == -1)
                end = document.cookie.length;

            return unescape(document.cookie.substring(start, end));
        }
    }

    return "";
}

$("#sampleAddContainer input").on("change", function (evt) {
    if ($("#sampleAddContainer input:checked").length > 0) {
        $("#forward_sample_fields").show();
    } else {
        $("#forward_sample_fields").hide();
    }
});


function lookupUserByEmail(email, user_found_callback, not_found_callback) {
    var url = "/users/validateemail";

    $.ajax({
        type: "GET",
        url: url,
        data: { email: email },
        success: function (data, status, xhr) {
            if (data.foundUserIsActive) {
                user_info = {
                    email: email,
                    id: data.foundUserId
                };
                lookupUserById(user_info.id, user_found_callback, not_found_callback);
                //user_found_callback(user_info);
            } else {
                not_found_callback("No active user found by the specified email address");
            }
        },
        error: function () {
            not_found_callback("No user found by the specified email address");
        }
    });
}

function lookupUserById(userId, user_found_callback, not_found_callback) {
    var url = "/users/" + userId + "/name";

    $.ajax({
        type: "GET",
        url: url,
        success: function (data, status, xhr) {
            userinfo = {
                email: data.split("|")[0],
                name: data.split("|")[1],
                id: userId
            };

            user_found_callback(userinfo);
        },
        error: function () {
            not_found_callback("No users found by the specified ID");
        }
    });
}

function completeRestrictionRequest() {
    $('#restrictedresultpopup').modal('hide');
    $('#restrictedresultnotes').val('');
    div_swap('restriction_submitdiv', 'restriction_submittingdiv');
}
/**
 * Copyright (c) 2007 Ariel Flesler - aflesler ? gmail  com | https://github.com/flesler
 * Licensed under MIT
 * @author Ariel Flesler
 * @version 2.1.2
 */
;(function(f){"use strict";"function"===typeof define&&define.amd?define(["jquery"],f):"undefined"!==typeof module&&module.exports?module.exports=f(require("jquery")):f(jQuery)})(function($){"use strict";function n(a){return!a.nodeName||-1!==$.inArray(a.nodeName.toLowerCase(),["iframe","#document","html","body"])}function h(a){return $.isFunction(a)||$.isPlainObject(a)?a:{top:a,left:a}}var p=$.scrollTo=function(a,d,b){return $(window).scrollTo(a,d,b)};p.defaults={axis:"xy",duration:0,limit:!0};$.fn.scrollTo=function(a,d,b){"object"=== typeof d&&(b=d,d=0);"function"===typeof b&&(b={onAfter:b});"max"===a&&(a=9E9);b=$.extend({},p.defaults,b);d=d||b.duration;var u=b.queue&&1<b.axis.length;u&&(d/=2);b.offset=h(b.offset);b.over=h(b.over);return this.each(function(){function k(a){var k=$.extend({},b,{queue:!0,duration:d,complete:a&&function(){a.call(q,e,b)}});r.animate(f,k)}if(null!==a){var l=n(this),q=l?this.contentWindow||window:this,r=$(q),e=a,f={},t;switch(typeof e){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)){e= h(e);break}e=l?$(e):$(e,q);case "object":if(e.length===0)return;if(e.is||e.style)t=(e=$(e)).offset()}var v=$.isFunction(b.offset)&&b.offset(q,e)||b.offset;$.each(b.axis.split(""),function(a,c){var d="x"===c?"Left":"Top",m=d.toLowerCase(),g="scroll"+d,h=r[g](),n=p.max(q,c);t?(f[g]=t[m]+(l?0:h-r.offset()[m]),b.margin&&(f[g]-=parseInt(e.css("margin"+d),10)||0,f[g]-=parseInt(e.css("border"+d+"Width"),10)||0),f[g]+=v[m]||0,b.over[m]&&(f[g]+=e["x"===c?"width":"height"]()*b.over[m])):(d=e[m],f[g]=d.slice&& "%"===d.slice(-1)?parseFloat(d)/100*n:d);b.limit&&/^\d+$/.test(f[g])&&(f[g]=0>=f[g]?0:Math.min(f[g],n));!a&&1<b.axis.length&&(h===f[g]?f={}:u&&(k(b.onAfterFirst),f={}))});k(b.onAfter)}})};p.max=function(a,d){var b="x"===d?"Width":"Height",h="scroll"+b;if(!n(a))return a[h]-$(a)[b.toLowerCase()]();var b="client"+b,k=a.ownerDocument||a.document,l=k.documentElement,k=k.body;return Math.max(l[h],k[h])-Math.min(l[b],k[b])};$.Tween.propHooks.scrollLeft=$.Tween.propHooks.scrollTop={get:function(a){return $(a.elem)[a.prop]()}, set:function(a){var d=this.get(a);if(a.options.interrupt&&a._last&&a._last!==d)return $(a.elem).stop();var b=Math.round(a.now);d!==b&&($(a.elem)[a.prop](b),a._last=this.get(a))}};return p});

jQuery.fn.reverse = [].reverse;

function showTranslationModal(url) {
    $('#modal').on('show', function() { $('#myModalLabel').text('Edit Phrase')}); 
    $('#modal').on('hidden', function() { DesktopApp.pages.site_master.resetModal(); }); 
    $('#modal').modal({ remote: url, backdrop: true });
}

function initDropdowns() { 
  document.addEventListener('click', (evt) => {
    let el = evt.target;
    if (!el || !el.dataset || !el.dataset.toggle || el.dataset.toggle !== 'ul-dropdown')
      return;
    evt.preventDefault();

    const $this = evt.target,
      $dropdown = document.getElementById($this.getAttribute("aria-controls"));

    const openDropdownEvent = new CustomEvent('ul-dropdown.open', { detail: { source: el }, bubbles: true }),
      closeDropdownEvent = new CustomEvent('ul-dropdown.close', { detail: { source: el }, bubbles: true });

    function _closeDropdown(_target, _this) {
      _target.classList.remove("on");
      _this.setAttribute('aria-expanded', "false");

      document.removeEventListener('click', closeme);
      document.removeEventListener('keydown', _detectKeyFocus);
      _target.dispatchEvent(closeDropdownEvent);
    }

    let closeme = (e) => {
      if (e.target !== $this && (!$dropdown.contains(e.target) || (e.target && e.target.classList && e.target.classList.contains('dropdown-close')))) {
        e.stopPropagation();
        _closeDropdown($dropdown, $this);
      }
    }

    //dropdown-close
    [...$dropdown.querySelectorAll('.dropdown-close')].forEach(d => {
      if (d.getAttribute('listener') !== 'true') {
        d.addEventListener('click', closeme);
        d.setAttribute('listener', true);
      }
    });

    function _detectKeyFocus(_evt) {
      if (_evt.keyCode == 9) {
        if (!$dropdown.contains(document.activeElement)) {
          _closeDropdown($dropdown, $this);
        }
      }
    }

    //close if open
    if ($this.getAttribute('aria-expanded') === 'true') {
      _closeDropdown($dropdown, $this);
    } else {
      //open the dropdown
      $this.setAttribute('aria-expanded', "true");
      $dropdown.classList.add("on");

      document.addEventListener("keyup", _detectKeyFocus);

      document.addEventListener('click', closeme);
      $dropdown.dispatchEvent(openDropdownEvent);
    }
  });
}

function initCollapsibles() {
  //console.log("initiating modals");
  document.querySelectorAll('.ul-collapsible').forEach(el => {
    let trigger = el.querySelector('.ul-collapsible__trigger');
    trigger.addEventListener('click', (evt) => {

      let open = trigger.getAttribute("aria-expanded"),
         state = open ? "false" : "true";

      trigger.setAttribute("aria-expanded", state);

      el.classList.toggle('-open');
      el.classList.toggle('-closed');


      evt.preventDefault();
    });
  });
}


function initDisclosure() {
  //always bind the trigger element as "this" using bind
  var appspace = {
    toggleClass: function (target, klass, ev) {
      let targetEl = document.querySelector(target);
      targetEl.classList.toggle(klass);

      var toggleExpanded = this.getAttribute("aria-expanded"),
        ten = toggleExpanded ? !(toggleExpanded === 'true') : "true";
      this.setAttribute("aria-expanded", ten);
      //set a session variable target-klass=expanded

      let eventType = ten ? "ul-disclosure.open" : "ul-disclosure.close";
      targetEl.dispatchEvent(new CustomEvent(eventType, { detail: { source: this }, bubbles: true }));
    }
  };

  document.addEventListener("click", function (evt) {
    var trigger = evt.target;
    if (!trigger || !trigger.dataset || !trigger.dataset.toggle || trigger.dataset.toggle !== 'ul-menu')
      return true;
    const transEl = document.getElementById(trigger.getAttribute("aria-controls")),
      targetSelector = trigger.dataset && trigger.dataset.target ? trigger.dataset.target : "#" + trigger.getAttribute("aria-controls");
    //for setting the new class
    function _toggle() {
      appspace.toggleClass.bind(trigger, targetSelector, trigger.dataset.class)();
      //always remove the event listener
      transEl.removeEventListener('transitionend', _toggle, { passive: true, capture: false });
    }

    if (trigger.dataset.removeClass) {
      const $target = document.querySelector(targetSelector);
      if ($target.classList.contains(trigger.dataset.removeClass)) {
        const props = window.getComputedStyle(transEl),
          dur = props.transitionDuration;
        appspace.toggleClass.bind(trigger, targetSelector, trigger.dataset.removeClass)();

        //wait for the transition to end before adding the new class
        if (dur > 0) {
          transEl.addEventListener('transitionend', _toggle, { passive: true, capture: false });
          return;
        }
      }
    }
    //console.log("main toggle on");
    _toggle();
  });
}

;
