

/*********************
Including file: lang.js
*********************/
/**
 * lang.js - js functions for working with multilingual strings
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var lang = {
    
};

String.prototype.format = function string_format(d) {
  // there are two modes of operation... unnamed indices are read in order;
  // named indices using %(name)s. The two styles cannot be mixed.
  // Unnamed indices can be passed as either a single argument to this function,
  // multiple arguments to this function, or as a single array argument
   curindex = 0;

  if (arguments.length > 1)
    d = arguments;

  function r(s, key, type) {
    var v;
    if (key == "" || key == null || key == undefined) {
      if (curindex == -1)
        throw Error("Cannot mix named and positional indices in string formatting.");

      if (curindex == 0 && (!(d instanceof Object) || !(0 in d)))
        v = d;
      else if (!(curindex in d))
        throw Error("Insufficient number of items in format, requesting item %i".format(curindex));
      else
        v = d[curindex];

      ++curindex;
    }
    else {
      key = key.slice(1, -1);
      if (curindex > 0)
        throw Error("Cannot mix named and positional indices in string formatting.");
      curindex = -1;

      if (!(key in d))
        throw Error("Key '%s' not present during string substitution.".format(key));
      v = d[key];
    }
    switch (type) {
    case "s":
      return v.toString();
    case "r":
      return v.toSource();
    case "i":
      return parseInt(v);
    case "f":
      return Number(v);
    case "%":
      return "%";
    default:
      throw Error("Unexpected format character '%s'.".format(type));
    }
  }
  return this.replace(/%(\([^)]+\))?(.)/g, r);
};
String.prototype.$f = String.prototype.format;

/*********************
Including file: ajaxLogout.js
*********************/
/**
 * ajaxLogout.js - handle the situation where a users session timed out before an ajax request
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */

(function() {
    
ajaxLogout = {
    
    /**
     * setup
     * 
     * @return  void
     */
    _setup:function(){

        // if we get an unauthorised staus back on the ajax request, redirect if told to do so
        $(document).ajaxComplete(function(o,xhr){
            var loc;
            if (xhr!= undefined && xhr.status==401) {
                var obj=eval('('+xhr.responseText+')');
                if (loc=obj.authError) location.href = APP.baseURL+loc;
            }
        });         
    }
}
})();
$(ajaxLogout._setup);



/*********************
Including file: hoverdropdown.js
*********************/
/**
 * hoverdropdown.js - js functions relating to common hover dropdown
 *
 * @package    core
 * @author     Tik Nipaporn
 * @copyright  (c) 2010 OnAsia
 */
(function() {
    
hoverDropdown = {
    
    /**
     * setup for hover dropdowns
     *
     * @return  void
     */
    _setup:function() {
        hoverDropdown._bindHoverEvents();
        
        // handle a click on hover list item
        $('ul.hoverdd ul li:not([onclick])').click(hoverDropdown._handleLIClick);
        
        hoverDropdown.rebind();
                
        hoverDropdown._resizeToContent();
    },
    
    /**
     * bind hidden input events for all hover dropdowns
     *
     * @return  void
     */
    rebind:function() {
        var inputs = $('ul.hoverdd > li > input[type=hidden]');
        inputs.unbind('click', hoverDropdown._handleClick).unbind('change', hoverDropdown._handleChange).unbind('refresh', hoverDropdown._handleChange);
        inputs.bind('click', hoverDropdown._handleClick).bind('change', hoverDropdown._handleChange).bind('refresh', hoverDropdown._handleChange);
    },
     
    /**
     * handle 'click' on hover dropdown option
     *
     * @return  void
     */
    _handleLIClick:function(event) {
        var thisID = $(this).closest('ul.hoverdd').find('input')[0].id;
        var ul = $(this).closest('ul.hoverdd');
        ul.addClass('shut'); // make sure dropdown closes
        $('#'+thisID).trigger('click', this);
        hoverDropdown.setScrollPosition(ul);
    },
     
    /**
     * handle 'click' on contained hidden input
     *
     * @return  void
     */
     _handleClick:function(event, li) {
        var thisVal = $(li).attr('hval');
        if (this.value != thisVal) {
            $(this).val(thisVal);
            $(this).trigger('change');
        }
     },
    
    /**
     * handle 'change' event for dropdown
     *
     * @return  void
     */
     _handleChange:function() {
        
        $(this).next().children().removeClass('_sel');
        var li = $(this).parent().find('li[hval="'+this.value+'"]');
        $(this).prev().text(li.text());
        li.addClass('_sel');
     },
    
    
    /**
     * hook up events to make sure hover dropdowns re-open
     *
     * @return  void
     */
    _bindHoverEvents:function() {
        $('ul.hoverdd').mouseover(hoverDropdown._reopenFix).mouseout(hoverDropdown._reopenFix);
    },
     _reopenFix:function() { $(this).removeClass('shut'); },
     
    /**
     * resize dropdowns to their content (except when asked not to)
     *
     * @return  void
     */
    _resizeToContent:function() {
        $('ul.hoverdd:not([noresize])').each(function(idx, el) {
            $(el).css('width', $(el).outerWidth() + 5 + 'px')
        });
    },
    
    /**
     * make the selected option visible when the dropdown opens
     * 
     * @param    hover dropdown
     * @return    void
     */
    setScrollPosition:function(ul) {
        var scrollUL = ul.children().find('ul');
        var val = ul.children().find('input[type=hidden]').val();
        if(val == "") return;
        var pos = scrollUL.children('li').index($('li[hval='+val+']'));
        scrollUL.attr({ scrollTop: pos*10 });
    }
};


})();


$(hoverDropdown._setup);

/*********************
Including file: app.js
*********************/
/**
 * app.js - js functions tools for the application
 *
 * @package    core
 * @author     Laurent Hunaut
 * @copyright  (c) 2021 Lightrocket
 */

(function() {
    APP = $.extend({}, APP,{
        htmlTagsRegex : {
            searchRegExPP       : {
                rx : new RegExp('</p><p>', 'g'),
                rp : '<br>',
            },
            searchRegExP        : {
                rx : new RegExp('<p>', 'g'),
                rp : '',
            },
            searchRegExSP       : {
                rx : new RegExp('</p>', 'g'),
                rp : '',
            },
            searchRegExSpace    : {
                rx : new RegExp('&nbsp;', 'g'),
                rp : ' ',
            },
        },
        descriptionConvTextJS: function(desc) {
            let elements = $.parseHTML(desc);
            desc = APP.traverseDOM(elements);
            desc = desc.replace('  ', ' ');

            return desc;
        },
        traverseDOM: function(elements) {
            let text = '';
            $.each(elements, function(key, element) {
                if ($(element).attr('href')) {
                    text += ' ' + $(element).attr('href');
                } else if (element.childNodes.length) {
                    text += ' ' + APP.traverseDOM(element.childNodes);
                } else if ($(element).text().trim() != '') {
                    text += ' ' + $(element).text().trim();
                }
            });
            return text.trim();
        },
        getUrlParameter:function(param) {
            var pageUrl = window.location.search.substring(1),
            urlVariables = pageUrl.split('&');
            var parameterName,
            i;
            for (i = 0; i < urlVariables.length; i++) {
                parameterName = urlVariables[i].split('=');

                if (parameterName[0] === param) {
                    return parameterName[1] === undefined ? true : decodeURIComponent(parameterName[1]);
                }
            }
        },
        decodeEntities:function(encodedString) {
            var textArea = document.createElement('textarea');
            textArea.innerHTML = encodedString;
            return textArea.value;
        },
        copyToClipboard:function(value) {
            var appendToEl = (arguments.length>1) ? arguments[1] : "body";
            var $temp = $("<input>");
            $(appendToEl).append($temp);
            $temp.val(value).select();
            document.execCommand("copy");
            $temp.remove();
        },
        copyToClipboardHTML:function(value) {
            var appendToEl = (arguments.length>1) ? arguments[1] : "body";
            var $temp = $("<textarea>");
            $(appendToEl).append($temp);
            $temp.val(value).select();
            document.execCommand("copy");
            $temp.remove();
        },
        removeArrDup:function(arr){
            var newArray = arr.filter(function(elem, index, self) {
                return index === self.indexOf(elem);
            });
            return newArray;
        },
        getNumHandlers:function(selector){
            nums = {total:0};
            $.each($(selector), function(){

                events = getEventListeners($(this)[0]);
                $.each(Object.keys(events), function(){
                    if(nums[this] == undefined) nums[this] = 0;
                    nums.total += events[this].length;
                    nums[this] += events[this].length;
                });
            });
            return nums;
        },
        registerRTFeditor:function(editor, key){
            if(window.editors === undefined) window.editors = {};
            window.editors[key] = editor;
        },
        destroyRTFeditors:function(){
            if(window.editors !== undefined){
                $.each(Object.keys(window.editors), function(){
                    if(window.editors[this] !== undefined && typeof(window.editors[this].destroy) == "function"){
                        let toDestroy = window.editors[this];
                        delete window.editors[this];
                        toDestroy.destroy();

                    }
                });
            }
            
        },
    });
})();


/*********************
Including file: notify.js
*********************/
/**
 * notify.js - fancy notifications
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */

(function() {
    
notify = {
    
    timeoutID:false,
    waiting:false,
    confirmResult:false,
    
    defaults: {
        background_color    : '#FFFFCC',
        color                    : '#000',
        time                    : 8000,
        onDisplayed            : false
    },
    
    show:function(message) {
        var opts = {};
        $.extend(opts, notify.defaults, (arguments.length>1) ? arguments[1] : {});
        
        // make sure message is a string
        message = ''+message;
        
        // remove existing if there
        if ($('.notifyBar').length) {
            notify.hide(function(){notify.show(message, opts);});
            return;
        }
        
        if (message==='') return;
        
        var msg = $('<div/>').html('<p>'+message.replace(/\n/i, '<br />')+'</p>').css({"color" : opts.color});
        var mouseoverMsg = '';
        if (typeof(lang.common)!='undefined')  mouseoverMsg = lang.common.lbl_dismissNotification;
        var wrapDiv = $('<div/>').addClass('notifyBar').css({"background-color" : opts.background_color}).attr('title', mouseoverMsg);
        wrapDiv.mousemove(notify.hide);
        wrapDiv.append(msg).hide().appendTo('body').slideDown('fast', opts.onDisplayed);
        
        notify.timeoutID = setTimeout(notify.hide, opts.time);

        
    },
    
    hide:function() {
        var callback = arguments.length ? arguments[0] : false;
        if ($('.notifyBar').length){
            clearTimeout(notify.timeoutID);
            $('.notifyBar').slideUp('fast',function(){
                $('.notifyBar').remove();
                if ($.isFunction(callback)) callback();
            });
        }
    },
    
    confirmAction:function(message, title, opts) {
        var o = {onOK:false, onCancel:false, opts:false};
        $.extend(o, opts);
        var okAction = opts.onOK ? opts.onOK : function(){};
        var cancelAction = opts.onCancel ? opts.onCancel : function(){};
        console.log("notify confirm");
        console.log(message);
        if (title) {
            var msgOpts = opts.opts ? opts.opts : {};
            var notifyOpts = {
                time:100000000,
                onDisplayed:function(){
                    var res = confirm(message);
                    notify.hide(function() {res ? okAction() : cancelAction();});
                }
            };
            $.extend(notifyOpts, msgOpts);
            notify.show(title, notifyOpts);
        } else {
            confirm(message) ? okAction() : cancelAction();
        }
    }
        

};




})();

window._alert = window.alert;
window.alert = function() { notify.show.apply(this, arguments); };

window.confirmAction = function() { return(notify.confirmAction.apply(this, arguments)); };



/*********************
Including file: labs_json.js
*********************/
/**
 * labs_json Script by Giraldo Rosales.
 * Version 1.0
 * Visit www.liquidgear.net for documentation and updates.
 *
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/
 
/**
 * HOW TO USE
 * ==========
 * Serialize:
 * var obj = {};
 * obj.name    = "Test JSON";
 * obj.type    = "test";
 * $.json.serialize(obj); //output: {"name":"Test JSON", "type":"test"}
 * 
 * Deserialize:
 * $.json.deserialize({"name":"Test JSON", "type":"test"}); //output: object
 * 
 */

jQuery.json = {
    serialize:function(value, replacer, space) {
        var i;
        gap = '';
        var indent = '';
        
        if (typeof space === 'number') {
            for (i = 0; i < space; i += 1) {
                indent += ' ';
            }
            
        } else if (typeof space === 'string') {
            indent = space;
        }
        
        rep = replacer;
        if (replacer && typeof replacer !== 'function' &&
                (typeof replacer !== 'object' ||
                 typeof replacer.length !== 'number')) {
            throw new Error('JSON.serialize');
        }
        
        return this.str('', {'': value});
    },
    
    deserialize:function(text, reviver) {
        var j;
        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        
        function walk(holder, key) {
            var k, v, value = holder[key];
            
            if (value && typeof value === 'object') {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = walk(value, k);
                        if (v !== undefined) {
                            value[k] = v;
                        } else {
                            delete value[k];
                        }
                    }
                }
            }
            return reviver.call(holder, key, value);
        }
        
        cx.lastIndex = 0;
        
        if (cx.test(text)) {
            text = text.replace(cx, function (a) {
                return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            });
        }
        
        if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
            j = eval('(' + text + ')');
            return typeof reviver === 'function' ? walk({'': j}, '') : j;
        }
        
        throw new SyntaxError('JSON.parse');
    },
    
    f:function(n) {
        return n < 10 ? '0' + n : n;
    },
    
    DateToJSON:function(key) {
        return this.getUTCFullYear() + '-' + this.f(this.getUTCMonth() + 1) + '-' + this.f(this.getUTCDate())      + 'T' + this.f(this.getUTCHours())     + ':' + this.f(this.getUTCMinutes())   + ':' + this.f(this.getUTCSeconds())   + 'Z';
    },
    
    StringToJSON:function(key) {
        return this.valueOf();
    },
    
    quote:function(string) {
        var meta = {'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};
        var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    },
    
    str:function(key, holder) {
        var indent='', gap = '', i, k, v, length, mind = gap, partial, value = holder[key];
        
        if (value && typeof value === 'object') {
            switch((typeof value)) {
                case 'date':
                    this.DateToJSON(key);
                    break;
                default:
                    this.StringToJSON(key);
                    break;
            }
        }
        
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
            case 'string':
                return this.quote(value);
            case 'number':
                return isFinite(value) ? String(value) : 'null';
            case 'boolean':
            case 'null':
                return String(value);
            case 'object':
                if (!value) {
                    return 'null';
                }
                gap += indent;
                partial = [];
                
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length;
                    
                    for (i = 0; i < length; i += 1) {
                        partial[i] = this.str(i, value) || 'null';
                    }
    
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
                    
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = this.str(k, value);
                            if (v) {
                                partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = this.str(k, value);
                            if (v) {
                                partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }
};


/*********************
Including file: jqContext.js
*********************/
/**
 * jqContext.js - jquery extension to allow for easy creation of context specific callbacks
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
 
 // $.context - example use: $.context(this).callback('myCallback') - would return a function that calls 'myCallback' in the context of this
jQuery.extend(
{
    context: function (context)
    {
        var co = 
        {
            callback: function (method)
            {
                if (typeof method == 'string') method = context[method];
                var cb = function () { method.apply(context, arguments); }
                return cb;
            }
        };
        return co;
    }
}); 


/*********************
Including file: jqModal.js
*********************/
/*
 * jqModal - Minimalist Modaling with jQuery
 *
 * Copyright (c) 2007-2015 Brice Burgess @IceburgBrice
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 1.4.1 (2015.09.07 +r26)
 * Requires: jQuery 1.2.3+
 */

(function (factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function ($) {

    /**
     * Initialize elements as "modals". Modals typically are popup dialogs,
     * notices, modal windows, &c.
     *
     * @name jqm
     * @param options user defined options, augments defaults.
     * @type jQuery
     * @cat Plugins/jqModal
     */

    $.fn.jqm=function(options){
        return this.each(function(){
            var jqm = $(this).data('jqm') || $.extend({ID: I++}, $.jqm.params),
              o = $.extend(jqm,options);

            // add/extend options to modal and mark as initialized
            $(this).data('jqm',o).addClass('jqm-init')[0]._jqmID = o.ID;

            // ... Attach events to trigger showing of this modal
            $(this).jqmAddTrigger(o.trigger);
        });
    };

    /**
     * Matching modals will have their jqmShow() method fired by attaching a
     *   onClick event to elements matching `trigger`.
     *
     * @name jqmAddTrigger
     * @param trigger a a string selector, jQuery collection, or DOM element.
     */
    $.fn.jqmAddTrigger=function(trigger){
      if(trigger){
        return this.each(function(){
              if (!addTrigger($(this), 'jqmShow', trigger))
                err("jqmAddTrigger must be called on initialized modals");
          });
      }
    };

    /**
     * Matching modals will have their jqmHide() method fired by attaching an
     *   onClick event to elements matching `trigger`.
     *
     * @name jqmAddClose
     * @param trigger a string selector, jQuery collection, or DOM element.
     */
    $.fn.jqmAddClose=function(trigger){
      if(trigger){
        return this.each(function(){
              if(!addTrigger($(this), 'jqmHide', trigger))
                err ("jqmAddClose must be called on initialized modals");
          });
      }
    };

    /**
     * Open matching modals (if not shown)
     */
    $.fn.jqmShow=function(trigger){
        return this.each(function(){ if(!this._jqmShown) show($(this), trigger); });
    };

    /**
     * Close matching modals
     */
    $.fn.jqmHide=function(trigger){
        return this.each(function(){ if(this._jqmShown) hide($(this), trigger); });
    };

    // utility functions

    var
        err = function(msg){
            if(window.console && window.console.error) window.console.error(msg);

    }, show = function(m, t){

        /**
         * m = modal element (as jQuery object)
         * t = triggering element
         *
         * o = options
         * z = z-index of modal
         * v = overlay element (as jQuery object)
         * h = hash (for jqModal <= r15 compatibility)
         */

      t = t || window.event;

        var o = m.data('jqm'),
            z = (parseInt(m.css('z-index'))) || 3000,
            v = $('<div></div>').addClass(o.overlayClass).css({
              height:'100%',
              width:'100%',
              position:'fixed',
              left:0,
              top:0,
              'z-index':z-1,
              opacity:o.overlay/100
            }),

            // maintain legacy "hash" construct
            h = {w: m, c: o, o: v, t: t};

        m.css('z-index',z);

        if(o.ajax){
            var target = o.target || m,
                url = o.ajax;

            target = (typeof target === 'string') ? $(target,m) : $(target);
            if(url.substr(0,1) === '@') url = $(t).attr(url.substring(1));

            // load remote contents
            target.load(url,function(){
                if(o.onLoad) o.onLoad.call(this,h);
            });

            // show modal
            if(o.ajaxText) target.html(o.ajaxText);
      open(h);
        }
        else { open(h); }

    }, hide = function(m, t){
        /**
         * m = modal element (as jQuery object)
         * t = triggering element
         *
         * o = options
         * h = hash (for jqModal <= r15 compatibility)
         */

      t = t || window.event;
        var o = m.data('jqm'),
            // maintain legacy "hash" construct
            h = {w: m, c: o, o: m.data('jqmv'), t: t};

        close(h);

    }, onShow = function(hash){
        // onShow callback. Responsible for showing a modal and overlay.
        //  return false to stop opening modal.

        // hash object;
        //  w: (jQuery object) The modal element
        //  c: (object) The modal's options object
        //  o: (jQuery object) The overlay element
        //  t: (DOM object) The triggering element

        // if overlay not disabled, prepend to body
        if(hash.c.overlay > 0) hash.o.prependTo('body');

        // make modal visible
        hash.w.show();

        // call focusFunc (attempts to focus on first input in modal)
        $.jqm.focusFunc(hash.w,true);

        return true;

    }, onHide = function(hash){
        // onHide callback. Responsible for hiding a modal and overlay.
        //  return false to stop closing modal.

        // hash object;
        //  w: (jQuery object) The modal element
        //  c: (object) The modal's options object
        //  o: (jQuery object) The overlay element
        //  t: (DOM object) The triggering element

        // hide modal and if overlay, remove overlay.
        if(hash.w.hide() && hash.o) hash.o.remove();

        return true;

    },  addTrigger = function(m, key, trigger){
        // addTrigger: Adds a jqmShow/jqmHide (key) event click on modal (m)
        //  to all elements that match trigger string (trigger)

        var jqm = m.data('jqm');
        if(jqm) return $(trigger).each(function(){
            this[key] = this[key] || [];

            // register this modal with this trigger only once
            if($.inArray(jqm.ID,this[key]) < 0) {
                this[key].push(jqm.ID);

                // register trigger click event for this modal
                //  allows cancellation of show/hide event from
                $(this).click(function(e){
                    if(!e.isDefaultPrevented()) m[key](this);
                    return false;
                });
            }

        });

    }, open = function(h){
        // open: executes the onOpen callback + performs common tasks if successful

        // transform legacy hash into new var shortcuts
        var m = h.w,
            v = h.o,
            o = h.c;

        // execute onShow callback
        if(o.onShow(h) !== false){
            // mark modal as shown
            m[0]._jqmShown = true;

            // if modal:true  dialog
            //   Bind the Keep Focus Function [F] if no other Modals are active
            // else,
            //   trigger closing of dialog when overlay is clicked
            if(o.modal){
              if(!ActiveModals[0]){ F('bind'); }
              ActiveModals.push(m[0]);
            }
            else m.jqmAddClose(v);

            //  Attach events to elements inside the modal matching closingClass
            if(o.closeClass) m.jqmAddClose($('.' + o.closeClass,m));

            // if toTop is true and overlay exists;
            //  remember modal DOM position with <span> placeholder element, and move
            //  the modal to a direct child of the body tag (after overlyay)
            if(o.toTop && v)
              m.before('<span id="jqmP'+o.ID+'"></span>').insertAfter(v);

            // remember overlay (for closing function)
            m.data('jqmv',v);

            // close modal if the esc key is pressed and closeOnEsc is set to true
            m.unbind("keydown",$.jqm.closeOnEscFunc);
            if(o.closeOnEsc) {
                m.attr("tabindex", 0).bind("keydown",$.jqm.closeOnEscFunc).focus();
            }
        }

    }, close = function(h){
        // close: executes the onHide callback + performs common tasks if successful

        // transform legacy hash into new var shortcuts
         var m = h.w,
            v = h.o,
            o = h.c;

        // execute onHide callback
        if(o.onHide(h) !== false){
            // mark modal as !shown
            m[0]._jqmShown = false;

             // If modal, remove from modal stack.
             // If no modals in modal stack, unbind the Keep Focus Function
             if(o.modal){
               ActiveModals.pop();
               if(!ActiveModals[0]) F('unbind');
             }

             // IF toTop was passed and an overlay exists;
             //  Move modal back to its "remembered" position.
             if(o.toTop && v) $('#jqmP'+o.ID).after(m).remove();
        }

    },  F = function(t){
        // F: The Keep Focus Function (for modal: true dialos)
        // Binds or Unbinds (t) the Focus Examination Function (X)

        $(document)[t]("keypress keydown mousedown",X);

    }, X = function(e){
        // X: The Focus Examination Function (for modal: true dialogs)

        var targetModal = $(e.target).data('jqm') ||
                          $(e.target).parents('.jqm-init:first').data('jqm');
        var activeModal = ActiveModals[ActiveModals.length-1];

        // allow bubbling if event target is within active modal dialog
        return (targetModal && targetModal.ID === activeModal._jqmID) ?
                 true : $.jqm.focusFunc(activeModal,e);
    },

    I = 0,   // modal ID increment (for nested modals)
    ActiveModals = [];  // array of active modals

    // $.jqm, overridable defaults
    $.jqm = {
        /**
         *  default options
         *
         * (Integer)   overlay      - [0-100] Translucency percentage (opacity) of the body covering overlay. Set to 0 for NO overlay, and up to 100 for a 100% opaque overlay.
         * (String)    overlayClass - Applied to the body covering overlay. Useful for controlling overlay look (tint, background-image, &c) with CSS.
         * (String)    closeClass   - Children of the modal element matching `closeClass` will fire the onHide event (to close the modal).
         * (Mixed)     trigger      - Matching elements will fire the onShow event (to display the modal). Trigger can be a selector String, a jQuery collection of elements, a DOM element, or a False boolean.
         * (String)    ajax         - URL to load content from via an AJAX request. False to disable ajax. If ajax begins with a "@", the URL is extracted from the attribute of the triggering element (e.g. use '@data-url' for; <a href="#" class="jqModal" data-url="modal.html">...)
         * (Mixed)     target       - Children of the modal element to load the ajax response into. If false, modal content will be overwritten by ajax response. Useful for retaining modal design.
         *                            Target may be a selector string, jQuery collection of elements, or a DOM element -- and MUST exist as a child of the modal element.
         * (String)    ajaxText     - Text shown while waiting for ajax return. Replaces HTML content of `target` element.
         * (Boolean)   modal        - If true, user interactivity will be locked to the modal window until closed.
         * (Boolean)   toTop        - If true, modal will be posistioned as a first child of the BODY element when opened, and its DOM posistion restored when closed. Useful for overcoming z-Index container issues.
         * (Function)  onShow       - User defined callback function fired when modal opened.
         * (Function)  onHide       - User defined callback function fired when modal closed.
         * (Function)  onLoad       - User defined callback function fired when ajax content loads.
         */
        params: {
            overlay: 50,
            overlayClass: 'jqmOverlay',
            closeClass: 'jqmClose',
            closeOnEsc: false,
            trigger: '.jqModal',
            ajax: false,
            target: false,
            ajaxText: '',
            modal: false,
            toTop: false,
            onShow: onShow,
            onHide: onHide,
            onLoad: false
        },

        // focusFunc is fired:
        //   a) when a modal:true dialog is shown,
        //   b) when an event occurs outside an active modal:true dialog
        // It is passed the active modal:true dialog as well as event
        focusFunc: function(activeModal, e) {

          // if the event occurs outside the activeModal, focus on first element
          if(e) $(':input:visible:first',activeModal).focus();

          // lock interactions to the activeModal
          return false;
        },

        // closeOnEscFunc is attached to modals where closeOnEsc param true.
        closeOnEscFunc: function(e){
            if (e.keyCode === 27) {
                $(this).jqmHide();
                return false;
            }
        }
    };

    return $.jqm;

}));


/*********************
Including file: login.js
*********************/
/**
 * Login js - js functions relating to logging in
 *
 * @package    application/js
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var login = {
    ssoLoginOnly: 0,

    /**
     * setup login object
     *
     * @return  void
     */
    _setup:function() {
        if (!$('body').hasClass('noLoginPop')) {
            if (login.ssoLoginOnly) {
                $('a.mainLinkLogin').attr('href', APP.baseURL + 'access/sso');
            } else {
                $('a.mainLinkLogin').attr('data-toggle', 'modal');
                $('a.mainLinkLogin').attr('data-target', '#LoginForm');
                $('a.mainLinkLogin').attr('href', '#');
                $('a.mainLinkLogin').click(function(e){e.preventDefault();});
            }
        }

        $('#password-login').off().on('click', function() {
            $('#FailForm').removeClass('hideMe');
        });
        
        //set auto focus when the page loads for login failed page
        if($('#FailForm').length) {
            if($('#username').val().length > 0) {
                $('#username').select();
            }
            else {
                $('#username').focus();
            }
        }
        if($('#forgotpassword').length) {
            if($('#email').val().length > 0) {
                $('#email').select();
            }
            else {
                $('#email').focus();
            }
        }
        if ($('#LoginFailForm').length){
            $('#LoginForm').remove();
        }
        if ($('.login-form-button').length) {
            $('.login-form-button').click(function() {
                $('.back-arrow').removeClass('hidden');
                $('.loginform').removeClass('hidden');
                $('.login_form_buttons').addClass('hidden');
                $('.social_auth_buttons').addClass('hidden');
            });
        }
        if ($('.back-arrow').length) {
            $('.back-arrow').click(function() {
                $(this).siblings('h2').html(lang.common.lbl_MainLinkLogIn);
                $(this).addClass('hidden');
                $('.loginform').addClass('hidden');
                $('.alert-danger').addClass('hidden');
                $('.login_form_buttons').removeClass('hidden');
                $('.social_auth_buttons').removeClass('hidden');
            });
        }
    },
};

// set up on DOM ready
$(login._setup);



/*********************
Including file: headerSearch.js
*********************/
/**
 * headerSearch js - js functions relating to Header Search
 *
 * @package    search
 * @author     Pachara Chutisawaeng
 * @copyright  (c) 2021 LightRocket
 */
 var headerSearch = {
    rcp_email:'',
    _setup:function() {
        $('#search #header_search').focus(function() {
            if(this.value == $(this).attr('tag')) {
                this.value = '';
            } else {
                this.select();
            }
        });
        $('#block_search').find('br').remove();
        $(document).on('click', '.wpro_help_link', function(e){
            e.preventDefault();
            if($("#footerLinks .wpro_help_link").length){
                dialog.alert({
                    title:"Help",
                    message:lang.common.msg_help_box,
                    boxId:"wpro-help-box-id",
                    sizeClass:"modal-m",
                })
            }
            else{
                window.open($("#headerLinks .wpro_quick_guide").attr("href"), '_blank');
            }
        });
        // $('a.assetEmail').click(function(e){ e.preventDefault(); });
        // $('.assetOpts li .assetEmail').live('click', function(event){
        //     event.preventDefault();
        //     //check context is search result or preview modal
        //     let asset_id = ($(this).closest(".resultCell").length)?$(this).closest(".resultCell").attr("data-assetid"):$('#assetid').val();
        //     sharePreview.begin({
        //         boxId:"wproSharePreview-box",
        //         fullname: user.fullname,
        //         asset_id: asset_id,
        //     });
        //     $('#share-asset-box #toEmail').val(headerSearch.rcp_email);
        // });
    	// if ($('#resActShareGroup').length) $('#resActShareGroup').click(function(e){
        //     e.preventDefault();
        //     shareGroup.begin({
        //         boxId:"wproShareGroup-box",
        //         group_id: $("#group_id").val(),
        //         fullname: user.fullname,
        //         share_url: window.location.href,
        //     });
        //     $('#share-group-box #toEmail').val(headerSearch.rcp_email);
        // });
        // $('#main_search_btn').attr("value",lang.common.lbl_Search);
        // var lang_html = '';
        // $('#lang_list li').each(function(){
        //     var link = $(this).find('a');
        //     var lang = $(this).data('lang');
        //     lang_html += '<span class="'+$(this).attr('class')+'"><a href="'+$(link).attr('href')+'" title="'+$(link).attr('title')+'">'+lang+'</a></span>';
        // });
        // $('#lang_panel').html(lang_html);
        
        //headerSearch.initAutoComplete();
    },
    
    initAutoComplete:function(){
        $( "#header_search" ).autocomplete({
            delay: 500,
            source: function(request, response) {
                $.ajax({
                    url:  APP.baseURL + "search/autosuggest",
                    dataType: "json",
                    data: {
                        keyword: $("#header_search").val()
                    },
                    success: function(data) {
                        response(data.suggestions);
                        $.each($("ul.ui-autocomplete li div"), function(){
                            $(this).html($(this).html().toLowerCase().replace(request.term.toLowerCase(),'<span class="highlight-word">'+request.term.toLowerCase()+'</span>'));
                        });
                    }
                });
            },
            minLength: 3,
        }).autocomplete( "widget" ).addClass( "header_search_autocomplete" );
    },
};

// set up on DOM ready
$(headerSearch._setup);

/*********************
Including file: linkRel.js
*********************/
/**
 * linkRel.js - js functions relating to link pages
 *
 * @author     Tik Nipaporn
 * @copyright  (c) 2009 OnAsia
 */

var linkRel = {
    openPopup:function() {
        var features = "height=700,width=1000,scrollTo,resizable=1,scrollbars=1,location=0";
        newwindow = window.open(this.href, 'Popup_'+this.id, features);
        if (window.focus) newwindow.focus();
        return false;
    },
    _setup:function() {
        $('a#poweredBy').attr('target', '_blank');
        $('a[rel=external]').attr('target', '_blank');
        $('a[rel=popup]').unbind('click', linkRel.openPopup);
        $('a[rel=popup]').click(linkRel.openPopup);
    }
};

// set up on dom ready
$(linkRel._setup);

// dumbass IE fix
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    };
}



/*********************
Including file: jqueryCookie.js
*********************/
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*********************
Including file: jquery.blockUI.js
*********************/
/*!
 * jQuery blockUI plugin
 * Version 2.70.0-2014.11.23
 * Requires jQuery v1.7 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2013 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";

    function setup($) {
        $.fn._fadeIn = $.fn.fadeIn;

        var noOp = $.noop || function() {};

        // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
        // confusing userAgent strings on Vista)
        var msie = /MSIE/.test(navigator.userAgent);
        var ie6  = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
        var mode = document.documentMode || 0;
        var setExpr = $.isFunction( document.createElement('div').style.setExpression );

        // global $ methods for blocking/unblocking the entire page
        $.blockUI   = function(opts) { install(window, opts); };
        $.unblockUI = function(opts) { remove(window, opts); };

        // convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
        $.growlUI = function(title, message, timeout, onClose) {
            var $m = $('<div class="growlUI"></div>');
            if (title) $m.append('<h1>'+title+'</h1>');
            if (message) $m.append('<h2>'+message+'</h2>');
            if (timeout === undefined) timeout = 3000;

            // Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications
            var callBlock = function(opts) {
                opts = opts || {};

                $.blockUI({
                    message: $m,
                    fadeIn : typeof opts.fadeIn  !== 'undefined' ? opts.fadeIn  : 700,
                    fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
                    timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
                    centerY: false,
                    showOverlay: false,
                    onUnblock: onClose,
                    css: $.blockUI.defaults.growlCSS
                });
            };

            callBlock();
            var nonmousedOpacity = $m.css('opacity');
            $m.mouseover(function() {
                callBlock({
                    fadeIn: 0,
                    timeout: 30000
                });

                var displayBlock = $('.blockMsg');
                displayBlock.stop(); // cancel fadeout if it has started
                displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency
            }).mouseout(function() {
                $('.blockMsg').fadeOut(1000);
            });
            // End konapun additions
        };

        // plugin method for blocking element content
        $.fn.block = function(opts) {
            if ( this[0] === window ) {
                $.blockUI( opts );
                return this;
            }
            var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
            this.each(function() {
                var $el = $(this);
                if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
                    return;
                $el.unblock({ fadeOut: 0 });
            });

            return this.each(function() {
                if ($.css(this,'position') == 'static') {
                    this.style.position = 'relative';
                    $(this).data('blockUI.static', true);
                }
                this.style.zoom = 1; // force 'hasLayout' in ie
                install(this, opts);
            });
        };

        // plugin method for unblocking element content
        $.fn.unblock = function(opts) {
            if ( this[0] === window ) {
                $.unblockUI( opts );
                return this;
            }
            return this.each(function() {
                remove(this, opts);
            });
        };

        $.blockUI.version = 2.70; // 2nd generation blocking at no extra cost!

        // override these in your code to change the default behavior and style
        $.blockUI.defaults = {
            // message displayed when blocking (use null for no message)
            message:  '<h1>Please wait...</h1>',

            title: null,        // title string; only used when theme == true
            draggable: true,    // only used when theme == true (requires jquery-ui.js to be loaded)

            theme: false, // set to true to use with jQuery UI themes

            // styles for the message when blocking; if you wish to disable
            // these and use an external stylesheet then do this in your code:
            // $.blockUI.defaults.css = {};
            css: {
                padding:    0,
                margin:        0,
                width:        '30%',
                top:        '40%',
                left:        '35%',
                textAlign:    'center',
                color:        '#000',
                border:        '3px solid #aaa',
                backgroundColor:'#fff',
                cursor:        'wait'
            },

            // minimal style set used when themes are used
            themedCSS: {
                width:    '30%',
                top:    '40%',
                left:    '35%'
            },

            // styles for the overlay
            overlayCSS:  {
                backgroundColor:    '#000',
                opacity:            0.6,
                cursor:                'wait'
            },

            // style to replace wait cursor before unblocking to correct issue
            // of lingering wait cursor
            cursorReset: 'default',

            // styles applied when using $.growlUI
            growlCSS: {
                width:        '350px',
                top:        '10px',
                left:        '',
                right:        '10px',
                border:        'none',
                padding:    '5px',
                opacity:    0.6,
                cursor:        'default',
                color:        '#fff',
                backgroundColor: '#000',
                '-webkit-border-radius':'10px',
                '-moz-border-radius':    '10px',
                'border-radius':        '10px'
            },

            // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
            // (hat tip to Jorge H. N. de Vasconcelos)
            /*jshint scripturl:true */
            iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

            // force usage of iframe in non-IE browsers (handy for blocking applets)
            forceIframe: false,

            // z-index for the blocking overlay
            baseZ: 1000,

            // set these to true to have the message automatically centered
            centerX: true, // <-- only effects element blocking (page block controlled via css above)
            centerY: true,

            // allow body element to be stetched in ie6; this makes blocking look better
            // on "short" pages.  disable if you wish to prevent changes to the body height
            allowBodyStretch: true,

            // enable if you want key and mouse events to be disabled for content that is blocked
            bindEvents: true,

            // be default blockUI will supress tab navigation from leaving blocking content
            // (if bindEvents is true)
            constrainTabKey: true,

            // fadeIn time in millis; set to 0 to disable fadeIn on block
            fadeIn:  200,

            // fadeOut time in millis; set to 0 to disable fadeOut on unblock
            fadeOut:  400,

            // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
            timeout: 0,

            // disable if you don't want to show the overlay
            showOverlay: true,

            // if true, focus will be placed in the first available input field when
            // page blocking
            focusInput: true,

            // elements that can receive focus
            focusableElements: ':input:enabled:visible',

            // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
            // no longer needed in 2012
            // applyPlatformOpacityRules: true,

            // callback method invoked when fadeIn has completed and blocking message is visible
            onBlock: null,

            // callback method invoked when unblocking has completed; the callback is
            // passed the element that has been unblocked (which is the window object for page
            // blocks) and the options that were passed to the unblock call:
            //    onUnblock(element, options)
            onUnblock: null,

            // callback method invoked when the overlay area is clicked.
            // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
            onOverlayClick: null,

            // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
            quirksmodeOffsetHack: 4,

            // class name of the message block
            blockMsgClass: 'blockMsg',

            // if it is already blocked, then ignore it (don't unblock and reblock)
            ignoreIfBlocked: false
        };

        // private data and functions follow...

        var pageBlock = null;
        var pageBlockEls = [];

        function install(el, opts) {
            var css, themedCSS;
            var full = (el == window);
            var msg = (opts && opts.message !== undefined ? opts.message : undefined);
            opts = $.extend({}, $.blockUI.defaults, opts || {});

            if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
                return;

            opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
            css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
            if (opts.onOverlayClick)
                opts.overlayCSS.cursor = 'pointer';

            themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
            msg = msg === undefined ? opts.message : msg;

            // remove the current block (if there is one)
            if (full && pageBlock)
                remove(window, {fadeOut:0});

            // if an existing element is being used as the blocking content then we capture
            // its current place in the DOM (and current display style) so we can restore
            // it when we unblock
            if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
                var node = msg.jquery ? msg[0] : msg;
                var data = {};
                $(el).data('blockUI.history', data);
                data.el = node;
                data.parent = node.parentNode;
                data.display = node.style.display;
                data.position = node.style.position;
                if (data.parent)
                    data.parent.removeChild(node);
            }

            $(el).data('blockUI.onUnblock', opts.onUnblock);
            var z = opts.baseZ;

            // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
            // layer1 is the iframe layer which is used to supress bleed through of underlying content
            // layer2 is the overlay layer which has opacity and a wait cursor (by default)
            // layer3 is the message content that is displayed while blocking
            var lyr1, lyr2, lyr3, s;
            if (msie || opts.forceIframe)
                lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
            else
                lyr1 = $('<div class="blockUI" style="display:none"></div>');

            if (opts.theme)
                lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
            else
                lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');

            if (opts.theme && full) {
                s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
                if ( opts.title ) {
                    s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
                }
                s += '<div class="ui-widget-content ui-dialog-content"></div>';
                s += '</div>';
            }
            else if (opts.theme) {
                s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
                if ( opts.title ) {
                    s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
                }
                s += '<div class="ui-widget-content ui-dialog-content"></div>';
                s += '</div>';
            }
            else if (full) {
                s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
            }
            else {
                s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
            }
            lyr3 = $(s);

            // if we have a message, style it
            if (msg) {
                if (opts.theme) {
                    lyr3.css(themedCSS);
                    lyr3.addClass('ui-widget-content');
                }
                else
                    lyr3.css(css);
            }

            // style the overlay
            if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
                lyr2.css(opts.overlayCSS);
            lyr2.css('position', full ? 'fixed' : 'absolute');

            // make iframe layer transparent in IE
            if (msie || opts.forceIframe)
                lyr1.css('opacity',0.0);

            //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
            var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
            $.each(layers, function() {
                this.appendTo($par);
            });

            if (opts.theme && opts.draggable && $.fn.draggable) {
                lyr3.draggable({
                    handle: '.ui-dialog-titlebar',
                    cancel: 'li'
                });
            }

            // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
            var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
            if (ie6 || expr) {
                // give body 100% height
                if (full && opts.allowBodyStretch && $.support.boxModel)
                    $('html,body').css('height','100%');

                // fix ie6 issue when blocked element has a border width
                if ((ie6 || !$.support.boxModel) && !full) {
                    var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
                    var fixT = t ? '(0 - '+t+')' : 0;
                    var fixL = l ? '(0 - '+l+')' : 0;
                }

                // simulate fixed position
                $.each(layers, function(i,o) {
                    var s = o[0].style;
                    s.position = 'absolute';
                    if (i < 2) {
                        if (full)
                            s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
                        else
                            s.setExpression('height','this.parentNode.offsetHeight + "px"');
                        if (full)
                            s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
                        else
                            s.setExpression('width','this.parentNode.offsetWidth + "px"');
                        if (fixL) s.setExpression('left', fixL);
                        if (fixT) s.setExpression('top', fixT);
                    }
                    else if (opts.centerY) {
                        if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                        s.marginTop = 0;
                    }
                    else if (!opts.centerY && full) {
                        var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
                        var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
                        s.setExpression('top',expression);
                    }
                });
            }

            // show the message
            if (msg) {
                if (opts.theme)
                    lyr3.find('.ui-widget-content').append(msg);
                else
                    lyr3.append(msg);
                if (msg.jquery || msg.nodeType)
                    $(msg).show();
            }

            if ((msie || opts.forceIframe) && opts.showOverlay)
                lyr1.show(); // opacity is zero
            if (opts.fadeIn) {
                var cb = opts.onBlock ? opts.onBlock : noOp;
                var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
                var cb2 = msg ? cb : noOp;
                if (opts.showOverlay)
                    lyr2._fadeIn(opts.fadeIn, cb1);
                if (msg)
                    lyr3._fadeIn(opts.fadeIn, cb2);
            }
            else {
                if (opts.showOverlay)
                    lyr2.show();
                if (msg)
                    lyr3.show();
                if (opts.onBlock)
                    opts.onBlock.bind(lyr3)();
            }

            // bind key and mouse events
            bind(1, el, opts);

            if (full) {
                pageBlock = lyr3[0];
                pageBlockEls = $(opts.focusableElements,pageBlock);
                if (opts.focusInput)
                    setTimeout(focus, 20);
            }
            else
                center(lyr3[0], opts.centerX, opts.centerY);

            if (opts.timeout) {
                // auto-unblock
                var to = setTimeout(function() {
                    if (full)
                        $.unblockUI(opts);
                    else
                        $(el).unblock(opts);
                }, opts.timeout);
                $(el).data('blockUI.timeout', to);
            }
        }

        // remove the block
        function remove(el, opts) {
            var count;
            var full = (el == window);
            var $el = $(el);
            var data = $el.data('blockUI.history');
            var to = $el.data('blockUI.timeout');
            if (to) {
                clearTimeout(to);
                $el.removeData('blockUI.timeout');
            }
            opts = $.extend({}, $.blockUI.defaults, opts || {});
            bind(0, el, opts); // unbind events

            if (opts.onUnblock === null) {
                opts.onUnblock = $el.data('blockUI.onUnblock');
                $el.removeData('blockUI.onUnblock');
            }

            var els;
            if (full) // crazy selector to handle odd field errors in ie6/7
                els = $('body').children().filter('.blockUI').add('body > .blockUI');
            else
                els = $el.find('>.blockUI');

            // fix cursor issue
            if ( opts.cursorReset ) {
                if ( els.length > 1 )
                    els[1].style.cursor = opts.cursorReset;
                if ( els.length > 2 )
                    els[2].style.cursor = opts.cursorReset;
            }

            if (full)
                pageBlock = pageBlockEls = null;

            if (opts.fadeOut) {
                count = els.length;
                els.stop().fadeOut(opts.fadeOut, function() {
                    if ( --count === 0)
                        reset(els,data,opts,el);
                });
            }
            else
                reset(els, data, opts, el);
        }

        // move blocking element back into the DOM where it started
        function reset(els,data,opts,el) {
            var $el = $(el);
            if ( $el.data('blockUI.isBlocked') )
                return;

            els.each(function(i,o) {
                // remove via DOM calls so we don't lose event handlers
                if (this.parentNode)
                    this.parentNode.removeChild(this);
            });

            if (data && data.el) {
                data.el.style.display = data.display;
                data.el.style.position = data.position;
                data.el.style.cursor = 'default'; // #59
                if (data.parent)
                    data.parent.appendChild(data.el);
                $el.removeData('blockUI.history');
            }

            if ($el.data('blockUI.static')) {
                $el.css('position', 'static'); // #22
            }

            if (typeof opts.onUnblock == 'function')
                opts.onUnblock(el,opts);

            // fix issue in Safari 6 where block artifacts remain until reflow
            var body = $(document.body), w = body.width(), cssW = body[0].style.width;
            body.width(w-1).width(w);
            body[0].style.width = cssW;
        }

        // bind/unbind the handler
        function bind(b, el, opts) {
            var full = el == window, $el = $(el);

            // don't bother unbinding if there is nothing to unbind
            if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
                return;

            $el.data('blockUI.isBlocked', b);

            // don't bind events when overlay is not in use or if bindEvents is false
            if (!full || !opts.bindEvents || (b && !opts.showOverlay))
                return;

            // bind anchors and inputs for mouse and key events
            var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
            if (b)
                $(document).bind(events, opts, handler);
            else
                $(document).unbind(events, handler);

        // former impl...
        //        var $e = $('a,:input');
        //        b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
        }

        // event handler to suppress keyboard/mouse events when blocking
        function handler(e) {
            // allow tab navigation (conditionally)
            if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
                if (pageBlock && e.data.constrainTabKey) {
                    var els = pageBlockEls;
                    var fwd = !e.shiftKey && e.target === els[els.length-1];
                    var back = e.shiftKey && e.target === els[0];
                    if (fwd || back) {
                        setTimeout(function(){focus(back);},10);
                        return false;
                    }
                }
            }
            var opts = e.data;
            var target = $(e.target);
            if (target.hasClass('blockOverlay') && opts.onOverlayClick)
                opts.onOverlayClick(e);

            // allow events within the message content
            if (target.parents('div.' + opts.blockMsgClass).length > 0)
                return true;

            // allow events for content that is not being blocked
            return target.parents().children().filter('div.blockUI').length === 0;
        }

        function focus(back) {
            if (!pageBlockEls)
                return;
            var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
            if (e)
                e.focus();
        }

        function center(el, x, y) {
            var p = el.parentNode, s = el.style;
            var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
            var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
            if (x) s.left = l > 0 ? (l+'px') : '0';
            if (y) s.top  = t > 0 ? (t+'px') : '0';
        }

        function sz(el, p) {
            return parseInt($.css(el,p),10)||0;
        }

    }


    /*global define:true */
    if (typeof define === 'function' && define.amd && define.amd.jQuery) {
        define(['jquery'], setup);
    } else {
        setup(jQuery);
    }

})();


/*********************
Including file: userPrefs.js
*********************/
/**
 * userPrefs js - js functions for getting and setting user preferences
 *
 * @package    user
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var userPrefs = {
    
    cookiePrefix:'userPrefs',
    
    /**
     * get a user pref
     *
     * @param  string        user pref name to retrieve
     * @return  mixed        value of user pref
     */
    get:function(name) {
        return $.cookie(userPrefs._cookieName(name));
    },
    
    /**
     * set a user pref
     *
     * @param  string        user pref name to retrieve
     * @param  mixed        value of user pref
     * @return  void
     */
    set:function(name, value) {
        $.cookie(userPrefs._cookieName(name), value, {path:'/'});
    },
    
    /**
     * get cookie name used to store pref
     *
     * @param  string        user pref name
     * @return  string        name of cookie
     */
    _cookieName:function(name) {
        return userPrefs.cookiePrefix + '[' + name + ']';    
    },
    
    /**
     * setup for userPrefs object
     *
     * @return  void
     */
    _setup:function() {
        if (APP.userPrefCookiePrefix) userPrefs.cookiePrefix = APP.userPrefCookiePrefix;
    }
    
};

// set up on DOM ready
$(userPrefs._setup);

/*********************
Including file: fullscreen.js
*********************/
/**
 * fullscreen.js - popup messages for fullscreen pages
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */

(function() {
    
fullscreen = {
    
    keyName:false, // will store 'name' of fullscreen key
    keyCode:false, // will store code of 'fullscreen key'
    ctrlKey:false, 
    altKey:false, 
    metaKey:false, 
    shiftKey:false, 
    _tempW:0,
    _tempH:0,
    notifications:false,
    isFull:false,
    leaveMessage:false,
    
    /**
     * setup
     * 
     * @return  void
     */
    _setup:function(){
        var isWin = (navigator.platform.indexOf('win') != -1) || (navigator.platform.indexOf('Win') != -1);
        var isMac = (navigator.platform.indexOf('mac') != -1) || (navigator.platform.indexOf('Mac') != -1);
        var isChrome = (navigator.userAgent.indexOf('chrome') != -1) || (navigator.userAgent.indexOf('Chrome') != -1);
        var isFirefox = (navigator.userAgent.indexOf('firefox') != -1) || (navigator.userAgent.indexOf('Firefox') != -1);
        var ffVer = isFirefox ? navigator.userAgent.match(/firefox\/([0-9\.]*)/i)[1] : '0';
        var isSafari = !isChrome && ((navigator.userAgent.indexOf('safari') != -1) || (navigator.userAgent.indexOf('Safari') != -1));
        var ver = $.browser.version;
        // set up keys
        if ((isWin && !isSafari)||(isWin && isChrome && (ver>'2'))) {
            fullscreen.keyName = 'F11';
            fullscreen.keyCode = 122;
            fullscreen.ctrlKey = false;
            fullscreen.altKey = false;
            fullscreen.shiftKey = false;
            fullscreen.metaKey = false;
            fullscreen.leaveMessage = !isChrome;
        } else if (isMac && isFirefox && (ffVer>='3.6')) {
            fullscreen.keyName = '⇧⌘F';
            fullscreen.keyCode = 70;
            fullscreen.ctrlKey = false;
            fullscreen.altKey = false;
            fullscreen.shiftKey = true;
            fullscreen.metaKey = true;
            fullscreen.leaveMessage = true;
        }
        $('html').keydown(fullscreen._checkKeys);
    },
    
    /**
     * check the keys pressed to see if it is our 'fullscreen' key
     * 
     * @param  object            -    event object
     * @return  void
     */
    _checkKeys:function(e){
        var e_ctrlKey = e.ctrlKey ? true : false;
        var e_altKey = e.altKey ? true : false;
        var e_shiftKey = e.shiftKey ? true : false;
        var e_metaKey = e.metaKey ? true : false;
        if ((e.which==fullscreen.keyCode) && (e_ctrlKey==fullscreen.ctrlKey) && (e_altKey==fullscreen.altKey) && (e_shiftKey==fullscreen.shiftKey) && (e_metaKey==fullscreen.metaKey)) {
            fullscreen._tempW = $(window).width();
            fullscreen._tempH = $(window).height();
            setTimeout(fullscreen._checkFull, 500);
        }
    },

    /**
     * check the page has gone in/out of full mode
     * 
     * @return  void
     */
    _checkFull:function(){
        var newW = $(window).width();
        var newH = $(window).height();
        if (fullscreen.isFull) {
            if ((newW<fullscreen._tempW)||(newH<fullscreen._tempH)) {
                fullscreen.isFull = false;
                alert('');
            }
        } else {
            if ((newW>fullscreen._tempW)||(newH>fullscreen._tempH)) {
                fullscreen.isFull = true;
                if (fullscreen.notifications) alert(fullscreen.leaveMessage ? lang.common.msg_leaveFullScreen.format(fullscreen.keyName) : '');
            }
        }
    },
    
    /**
     * turn on/off notifications
     * 
     * @param  [bool]        -    optional state on/off - default is true
     * @return  void
     */
    notify:function(){
        var state = arguments.length ? arguments[0] : true;
        if ((fullscreen.notifications = state) && fullscreen.keyCode) alert(lang.common.msg_goFullScreen.format(fullscreen.keyName));
    }
    
}

})();


$(fullscreen._setup);



/*********************
Including file: dialog.js
*********************/
/**
 * dialog.js - js functions allowing to display dialog boxes
 *
 * @package    core
 * @author     Romain Bouillard
 * @copyright  (c) 2016 OnAsia
 */

(function() {

dialog = {
    default_options:{
        boxId           : "dialog-box",
        sizeClass       : "modal-sm",
        tallModal       : false,
        title           : "",
        showHeader      : true,
        resizable       : false,
        height          : 140,
        modal           : true,
        buttonsClass    : "nice_btn grey",
        hideCallback    : false,
        shownCallback   : false,
        backdrop        : true,
        onHiddenCallback: false,
    },
    options:{},
    template: _.template(
        '<div id="<%-boxId%>" class="modal fade"  tabindex="-1" role="dialog" <%-backdrop?"":\'data-backdrop=false\'%>>' +
        '   <div class="modal-dialog <%-tallModal?"tall-modal":""%> <%-sizeClass%>" role="document">' +
        '       <div class="modal-content">' +
        '           <div class="<%-showHeader?"":"hideMe"%> modal-header">' +
        '               <button type="button" class="close" data-dismiss="modal" aria-label="Close"><img src="'+APP.baseURL+'/media/icon?src=close-757575.svg"></button>' +
        '               <h4 class="modal-title"><%-title%></h4>' +
        '           </div>' +
        '           <div class="modal-body">' +
        '               <%=content%>' +
        '           </div>' +
        '           <div class="modal-footer">' +
        '               <%=buttons%>' +
        '           </div>' +
        '       </div>' +
        '   </div>' +
        '</div>'),
    button_template : _.template('<button id="<%-buttonId%>" type="button" class="btn <%-classes%> btn-sm" <%=attributes%>><%-label%></button>'),
    message_template: _.template('<p><%=message%></p>'),
    prompt_template: _.template('<p><%=message%></p><input class="form-control input-sm" placeholder="<%=placeHolder%>" type="text"<%=(inputLength)?" maxlength="+inputLength:""%> value="<%-initInput%>">'),
    buttons_html:"",
    shown:false,
    hiding:false,
    setup:function(){},
    addBox:function(){
        this.remove();
        if(!this.hiding){
            $("body").append(this.template({
                boxId       : this.options.boxId,
                sizeClass   : this.options.sizeClass,
                tallModal   : this.options.tallModal,
                showHeader  : this.options.showHeader,
                title       : this.options.title,
                content     : this.options.content,
                buttons     : this.buttons_html,
                backdrop    : this.options.backdrop,
            }));
        }   
    },
    reset:function(){
        this.options = {};
        this.buttons_html = "";
    },
    show:function(){
        if(!this.hiding && this.shown) this.hide(this.show);
        if(!this.hiding){
            var that = this;
            $("#"+this.options.boxId).removeClass("hideMe");
            $("#"+this.options.boxId).modal({backdrop:that.options.backdrop});
            $("#"+that.options.boxId).off("hide.bs.modal").on("hide.bs.modal", function(){
                that.hiding = true;
                if(that.options.hideCallback){
                    that.options.hideCallback();
                    that.options.hideCallback = false;
                }
            });
            this.setHidingEvent();
            this.shown = true;
        }
        $("#"+that.options.boxId).off("shown.bs.modal").on('shown.bs.modal', function () {
            $("#"+that.options.boxId+" .modal-footer button:last-child").focus();
            that.callbackOnShown();
        });
    },
    hide:function(){
        if(!this.shown) return;
        if(this.options.hideCallback){
            this.options.hideCallback();
            this.options.hideCallback = false;
        }
        $("#"+this.options.boxId).modal("hide");
    },
    temporarilyHide:function(){
        let state = (arguments.length > 0)?arguments[0]: true;
        $("#"+this.options.boxId)[state?"addClass":"removeClass"]("hideMe");
    },
    setHidingEvent:function(){
        var that = this;
        $("#"+that.options.boxId).off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
            that.hiding = false;
            that.shown = false;
            $(".modal").each(function(){
                if($(this).css("display") == "block") $("body").addClass("modal-open"); 
            });
            if(that.options.onHiddenCallback){
                that.options.onHiddenCallback();
            }
            that.remove();
        });
    },
    remove:function(){
        if($("#"+this.options.boxId).length !== 0){
            $("#"+this.options.boxId + "+.modal-backdrop").remove();
            $("#"+this.options.boxId).remove();
        }
    },
    /**
     * Display a simple dialog box with a single button to close it.
     * @param options object containing option for the dialog: message, title, buttons object etc.
     * @return void
     */
    alert:function(options){
        if(this.hiding){
            setTimeout(function(){this.alert(options)},500);
            return;
        }
        this.reset();
        $.extend(this.options,this.default_options,
            {
                buttons:{
                    ok:{
                        label:lang.common.lbl_OK,
                        events:{
                        },
                        attributes:{
                            "data-dismiss":"modal",
                        },
                    },
                }
            }, options
        );
        this.options.content = this.message_template({message:this.options.message});
        
        this.makeButtonsDismiss();
        this.setButtonsHtml();
        this.addBox();
        var that = this;
        this.show();
        this.setButtonsEvents();
    },
    
    confirm:function(options){
        if(this.hiding){
            var that = this
            setTimeout(function(){that.confirm(options)}, 500);
            return;
        }
        this.reset();
        $.extend(this.options,this.default_options,
            {
                buttons:{
                    yes:{
                        label:lang.common.lbl_Yes,
                        events:{
                            click:function(){}
                        },
                    },
                    no:{
                        label:lang.common.lbl_No,
                        events:{
                            click:function(){}
                        },
                    },
                },
            }, options
        );
        this.options.content = this.message_template({message:this.options.message});
        
        //set event attached to click on yes
        if(this.options.actionOnYes !== undefined)
            this.options.buttons.yes.events.click = this.options.actionOnYes;
        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        if(this.options.actionOnNo !== undefined){
            this.options.actionOnCancel = this.options.actionOnNo;
            this.options.buttons.no.events.click = this.options.actionOnNo;
        }
        this.makeButtonsDismiss();
        this.setButtonsHtml();
        this.addBox();
        var that = this;
        this.show();
        this.setButtonsEvents();
        this.setButtonCancel();
    },
    prompt:function(options){
        if(this.hiding){
            setTimeout(function(){this.prompt(options)}, 500);
            return;
        }
        this.reset();
        $.extend(this.options,this.default_options, 
            {
                buttons:{
                    ok:{
                        label:lang.common.lbl_OK,
                        events:{
                            click:function(){}
                        },
                    },
                    cancel:{
                        label:lang.common.lbl_Cancel,
                    },
                },
            },options
        );
        this.options.content = this.prompt_template({
            message:this.options.message,
            placeHolder:this.options.placeHolder,
            initInput:this.options.initInput?this.options.initInput:"",
            inputLength:this.options.inputLength?this.options.inputLength:0,
        });
        //set event attached to click on yes
        if(this.options.actionOnOk !== undefined)
            this.options.buttons.ok.events.click = this.options.actionOnOk;
        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        if(this.options.actionOnCancel !== undefined)
            this.options.buttons.cancel.events.click = this.options.actionOnCancel;
        this.makeButtonsDismiss();
        this.setButtonsHtml();
        this.addBox();
        this.show();
        var that = this;
        $("#"+that.options.boxId).off("shown.bs.modal").on('shown.bs.modal', function () {
            $("#"+that.options.boxId+" input").focus();
            $("#"+that.options.boxId+" input").caret({start:0,end:$("#"+that.options.boxId+" input").val().length});
            $("#"+that.options.boxId+" input").on("keypress", function(event){
                var keycode = (event.keyCode ? event.keyCode : event.which);
                if(keycode == '13'){
                    $("#"+that.options.boxId+"-btn-ok").trigger("click");
                }
            });
        });
        this.setButtonsEvents();
    },
    customModal:function(options){
        if(this.hiding){
            setTimeout(function(){this.customModal(options)},500);
            return;
        }
        this.reset();
        $.extend(this.options,this.default_options, options);
        if(this.options.message !== undefined && this.options.message) this.options.content = this.message_template({message:this.options.message});
        
        this.makeButtonsDismiss();
        this.setButtonsHtml();
        this.addBox();
        var that = this;
        $("#"+that.options.boxId).off("show.bs.modal").on('show.bs.modal', function () {
            that.callbackBeforeShow();
        });
        this.show();
        this.setButtonsEvents();
    },
    
    makeButtonsDismiss:function(){
        $.each(this.options.buttons, function(name, button){
            if(button.preventDismiss == undefined || !button.preventDismiss) button.attributes = (button.attributes == undefined)?{"data-dismiss":"modal"}:$.extend(button.attributes,{"data-dismiss":"modal"});
        });
    },
    setButtonsHtml:function(){
        btn_html = "";
        var that = this;
        $.each(this.options.buttons, function(name, button){
            attr_str = "";
            $.each(button.attributes, function(key, value){
                attr_str += " "+key+'="'+value+'"';
            });
            btn_html += that.button_template({
                label:button.label,
                attributes:attr_str,
                buttonId:that.options.boxId+"-btn-"+name,
                classes:button.classes?button.classes:"btn-default",
            });
        });
        this.buttons_html = btn_html;
    },
    setButtonCancel:function(){
        if(this.options.actionOnCancel !== undefined){
            $("#"+this.options.boxId+" .modal-header button.close").on("click", this.options.actionOnCancel);
        }
    },
    setButtonsEvents:function(){
        var that = this;
        $.each(that.options.buttons, function(name, button){
            $.each(button.events, function(event, callback){
                $("#"+that.options.boxId).on(event, "#"+that.options.boxId+"-btn-"+name, callback);
            });
        });
    },
    callbackOnShown:function(){
        if(this.options.shownCallback)this.options.shownCallback();
    },
    callbackBeforeShow : function(){
        if(this.options.beforeShowCallback)this.options.beforeShowCallback();
    }
}})(); 

//dialog.setup()


/*********************
Including file: jquery.caret.js
*********************/
/*
 *
 * Copyright (c) 2010 C. F., Wong (<a href="http://cloudgen.w0ng.hk">Cloudgen Examplet Store</a>)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
﻿(function($,len,createRange,duplicate){
    $.fn.caret=function(options,opt2){
        var start,end,t=this[0],browser=$.browser.msie;
        if(typeof options==="object" && typeof options.start==="number" && typeof options.end==="number") {
            start=options.start;
            end=options.end;
        } else if(typeof options==="number" && typeof opt2==="number"){
            start=options;
            end=opt2;
        } else if(typeof options==="string"){
            if((start=t.value.indexOf(options))>-1) end=start+options[len];
            else start=null;
        } else if(Object.prototype.toString.call(options)==="[object RegExp]"){
            var re=options.exec(t.value);
            if(re != null) {
                start=re.index;
                end=start+re[0][len];
            }
        }
        if(typeof start!="undefined"){
            if(browser){
                var selRange = this[0].createTextRange();
                selRange.collapse(true);
                selRange.moveStart('character', start);
                selRange.moveEnd('character', end-start);
                selRange.select();
            } else {
                this[0].selectionStart=start;
                this[0].selectionEnd=end;
            }
            this[0].focus();
            return this
        } else {
           if(browser){
                var selection=document.selection;
                if (this[0].tagName.toLowerCase() != "textarea") {
                    var val = this.val(),
                    range = selection[createRange]()[duplicate]();
                    range.moveEnd("character", val[len]);
                    var s = (range.text == "" ? val[len]:val.lastIndexOf(range.text));
                    range = selection[createRange]()[duplicate]();
                    range.moveStart("character", -val[len]);
                    var e = range.text[len];
                } else {
                    var range = selection[createRange](),
                    stored_range = range[duplicate]();
                    stored_range.moveToElementText(this[0]);
                    stored_range.setEndPoint('EndToEnd', range);
                    var s = stored_range.text[len] - range.text[len],
                    e = s + range.text[len]
                }
            } else {
                var s=t.selectionStart,
                    e=t.selectionEnd;
            }
            var te=t.value.substring(s,e);
            return {start:s,end:e,text:te,replace:function(st){
                return t.value.substring(0,s)+st+t.value.substring(e,t.value[len])
            }}
        }
    }
})(jQuery,"length","createRange","duplicate");

/*********************
Including file: messages.js
*********************/
/**
 * messages.js - js functions relating to messaging system
 *
 * @package    messages
 * @author     Tik Nipaporn
 * @copyright  (c) 2012 Lightrocket
 */

var messages = {

    _queue:[], // message queue to display
    _queueCallback:false, // store callback function
    _currentMsgID:false, // current message id

    
    /**
     * extract message and store in a queue
     *
     * @param  mixed UL element or UL id
     * @return void
     */
    processMessageList:function(ul){
        var li = (typeof(ul)=='string')?$('#'+ul+' li'):ul.children();
        messages._queue = []; messages._queueCallback = false;
        li.each(function(){ messages._queue.push({id:$(this).attr('mval'),type:$(this).attr('mtype'),content:$(this).html()}); });
        messages._processQueue(function(msg){ messages._dismissOnScreen(msg.id); messages._processQueue(); });
    },
    
    /**
     * manage and display messages in the queue
     */
    _processQueue:function(){
        if (!messages._queue.length) { messages.hide(); return; }
        if (arguments.length) { messages._queueCallback = arguments[0]; }
        var msg = messages._queue.shift();
        messages.show(msg, messages._queueCallback);
    },
    
    /**
     * display given message
     *
     * @param  object Message
     * @return void
     */
    show:function(msg){
        var callback = (arguments.length==2) ? arguments[1] : false;
        $('#system_message span').attr('class','').addClass('type'+msg.type);
        $('#system_message div').html(msg.content);
        (callback) ? $('#dismiss').unbind().click(function(){callback(msg);}) : $('#dismiss').unbind().click(messages.hide);
        $('#system_message').jqmShow();
        // store current id if we have one, also make sure msg is dissmissed if links clicked within message html
        if (typeof(msg.id)!='undefined') {
            messages._currentMsgID = msg.id;
            ////// ** Removed as we are now marking messages as dismissed on the server as soon as they are shown
            ////// $('#system_message div a[href]').unbind().click(function(e) {
            //////     e.preventDefault();
            //////     var nextURL = $(this).attr('href');
            //////     messages._dismissCurrent(function() {
            //////         messages.hide();
            //////         location.href = nextURL;
            //////     });
            ////// });
            messages._dismissOnServer(msg.id);
        }
    },
    
    /**
     * hide any message being displayed
     */
    hide:function(){
        $('#system_message').jqmHide();
        messages._currentMsgID = false;
    },
    
    
    /**
     * dismiss the message on the server
     */
    _dismissOnServer:function(msg_id){
        ////// var callback = (arguments.length>1) ? arguments[1] : false;
        var callback = false;
        $.post(APP.baseURL+'messages/dismiss', {msg_id:msg_id}, callback);
    },
    
    /**
     * dismiss the message on the screen
     */
    _dismissOnScreen:function(msg_id){
        var callback = (arguments.length>1) ? arguments[1] : false;
        ////// $.post(APP.baseURL+'messages/dismiss', {msg_id:msg_id}, callback);
        if (callback) callback();
    },
    
    /**
     * dismiss current message (if we have an id stored)
     */
    _dismissCurrent:function(){
        var callback = arguments.length ? arguments[0] : false;
        if (messages._currentMsgID) messages._dismiss(messages._currentMsgID, callback);
    },
    
    /**
     * setup for system messages
     *
     * @return  void
     */
    _setup:function(){
        $('#system_message').jqm({modal:true, trigger:false});
        if ($('#system_message ul#system_msg li').length) { messages.processMessageList($('#system_msg')); }
    }
};

$(messages._setup);

/*********************
Including file: initial.min.js
*********************/
!function(a){a.fn.initial=function(b){var c=["#1abc9c","#16a085","#f1c40f","#f39c12","#2ecc71","#27ae60","#e67e22","#d35400","#3498db","#2980b9","#e74c3c","#c0392b","#9b59b6","#8e44ad","#bdc3c7","#34495e","#2c3e50","#95a5a6","#7f8c8d","#ec87bf","#d870ad","#f69785","#9ba37e","#b49255","#b49255","#a94136"];return this.each(function(){var d=a(this),e=a.extend({name:"Name",seed:0,charCount:1,textColor:"#ffffff",height:100,width:100,fontSize:60,fontWeight:400,fontFamily:"HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif",radius:0},b);e=a.extend(e,d.data());var f=e.name.substr(0,e.charCount).toUpperCase(),g=a('<text text-anchor="middle"></text>').attr({y:"50%",x:"50%",dy:"0.35em","pointer-events":"auto",fill:e.textColor,"font-family":e.fontFamily}).html(f).css({"font-weight":e.fontWeight,"font-size":e.fontSize+"px"}),h=Math.floor((f.charCodeAt(0)+e.seed)%c.length),i=a("<svg></svg>").attr({xmlns:"http://www.w3.org/2000/svg","pointer-events":"none",width:e.width,height:e.height}).css({"background-color":c[h],width:e.width+"px",height:e.height+"px","border-radius":e.radius+"px","-moz-border-radius":e.radius+"px"});i.append(g);var j=window.btoa(unescape(encodeURIComponent(a("<div>").append(i.clone()).html())));d.attr("src","data:image/svg+xml;base64,"+j)})}}(jQuery);

/*********************
Including file: hashchange.js
*********************/
/*
 * jQuery hashchange event, v1.4, 2013-11-29
 * https://github.com/georgekosmidis/jquery-hashchange
 */
(function(e,t,n){"$:nomunge";function f(e){e=e||location.href;return"#"+e.replace(/^[^#]*#?(.*)$/,"$1")}var r="hashchange",i=document,s,o=e.event.special,u=i.documentMode,a="on"+r in t&&(u===n||u>7);e.fn[r]=function(e){return e?this.bind(r,e):this.trigger(r)};e.fn[r].delay=50;o[r]=e.extend(o[r],{setup:function(){if(a){return false}e(s.start)},teardown:function(){if(a){return false}e(s.stop)}});s=function(){function p(){var n=f(),i=h(u);if(n!==u){c(u=n,i);e(t).trigger(r)}else if(i!==u){location.href=location.href.replace(/#.*/,"")+i}o=setTimeout(p,e.fn[r].delay)}var s={},o,u=f(),l=function(e){return e},c=l,h=l;s.start=function(){o||p()};s.stop=function(){o&&clearTimeout(o);o=n};var d=function(){var e,t=3,n=document.createElement("div"),r=n.getElementsByTagName("i");while(n.innerHTML="<!--[if gt IE "+ ++t+"]><i></i><![endif]-->",r[0]);return t>4?t:e}();d&&!a&&function(){var t,n;s.start=function(){if(!t){n=e.fn[r].src;n=n&&n+f();t=e('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){n||c(f());p()}).attr("src",n||"javascript:0").insertAfter("body")[0].contentWindow;i.onpropertychange=function(){try{if(event.propertyName==="title"){t.document.title=i.title}}catch(e){}}}};s.stop=l;h=function(){return f(t.location.href)};c=function(n,s){var o=t.document,u=e.fn[r].domain;if(n!==s){o.title=i.title;o.open();u&&o.write('<script>document.domain="'+u+'"</script>');o.close();t.location.hash=n}}}();return s}()})(jQuery,this);


/*********************
Including file: popupform.js
*********************/
/**
 * popupform.js - generic Backbone view for creating popup form functionality
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2013 OnAsia
 */

var _View = Backbone.View.extend({
    // proxifier for functions
    _p:function(fn, context) {
        var args = Array.prototype.slice.call(arguments, 2);
      var prxy = function () {
            return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
        };
        return prxy;
   }
});



var PopupFormView = Backbone.View.extend({

    // width and height (px) of the popup
    width        :            250,
    height    :            150,

    // Close when ESC pressed?
    closeOnESC    :        true,

    // details used to retrieve the form
    formURL        :            '',
    formParams    :            {},
    _gotForm        :            false,

    // id for the div that will be created to contain the form
    containerDivID        :        'popup',
    _visible                :        false,

    // show the form
    show:function() {
        if (!this._gotForm) {
            this._loadForm();
            this._setupForm();
        }
        this._setFormCSS();
        this._dimBackground();
        if (this.closeOnESC) this._setESCHandler();
        this.$el.show();
        this._visible = true;
    },

    // hide the form
    hide:function() {
        if (this.closeOnESC) this._setESCHandler(false);
        this.$el.hide();
        $this._dimBackground(false);
        $this._visible = false;
    }


});


/*********************
Including file: nice_buttons.js
*********************/
/**
 * nice_buttons.js - js functions relating to customize html element
 *
 * @author     Tik Nipaporn
 * @copyright  (c) 2014 OnAsia
 */
 
var nice_buttons = {

    toggleCheckbox:false,

    /**
     * setup 
     *
     * @return  void
     */
    _setup:function() {
        // $(document).delegate('.custom-checkbox>input[type="checkbox"]', 'click', function(){
        //     var input = $(this), wrapper = input.parent();
        //     (input.attr('checked')) ? wrapper.addClass('checked') : wrapper.removeClass('checked');
        //     if (nice_buttons.toggleCheckbox!==false) nice_buttons.toggleCheckbox($(this));
        // });
        // $(document).delegate('.custom-checkbox.radio>input[type="radio"]', 'click', function(){
        //     var radioBtns = $('input[name="'+$(this).attr('name')+'"]');
        //     $.each(radioBtns, function(){
        //         (this.checked) ? $(this).parent('.radio').addClass('checked') : $(this).parent('.radio').removeClass('checked');
        //     });
        // });
        // $(document).delegate('.custom-switch.common', 'click', function(){
        //     if ($(this).hasClass('disabled')) return;
        //     $('input[name="'+this.id+'"][type="hidden"]').val($(this).hasClass('on')?0:1).trigger('change');
        //     nice_buttons.setCommonSwitch($(this));
        // });
    },
    
    setCommonSwitch:function() {
        var input;
        var fields = (arguments.length) ? arguments[0] : $('.custom-switch.common');
        $.each(fields, function(){
            input = $(this).find('input[name="'+this.id+'"][type="hidden"]');
            if (input.length) {
                input = input.val();
                $('.custom-switch.common span[id^="'+this.id+'_"]').hide();
                if (input=='1') {
                    $(this).removeClass('off').addClass('on');
                    $('#'+this.id+'_1').show();
                } else {
                    $(this).removeClass('on').addClass('off');
                    $('#'+this.id+'_0').show();
                }
            }
        });
    }
    
};

// set up on dom ready
$(nice_buttons._setup);

/*********************
Including file: mobile_menu.js
*********************/
$(document).ready(function(){
    $("ul#headerLinks>li>a.hasSubMenu").click(function(e){
        e.preventDefault();
        $(this).parent('li').children('ul').toggleClass('showSubMenu');
    });
    $("#header").on("click", ".hamburgerButton", toggleMobileMenu);
    $("#header").on("click", ".mobile-menu-overlay", toggleMobileMenu);
});
toggleMobileMenu = function(){
    $(this).toggleClass('active');
    $("#header").toggleClass('openHeader');
    $("body").toggleClass('mobile-menu-opened');
};

/*********************
Including file: highlightCurrentMenu.js
*********************/
/**
 * highlightCurrentMenu.js - js functions relating to Navigation Menu - Highlight the active menu
 *
 * @package    skin (_base)
 * @author     Laurent hunaut
 * @copyright  (c) 2016 Lightrocket
 */
var highlightCurrentMenu = {
    _setup:function() {
        if ($('body').attr("class") !== undefined) {
            var classes = $('body').attr("class").split(" ");
            $.each(classes, function(){
                bodyClass = this.toString();
                if($('#headerLinks li a[data-page-name="'+bodyClass+'"]').length > 0) $('#headerLinks li a[data-page-name="'+bodyClass+'"]').addClass('selected_menu');
            });
        }
    },

};


/*********************
Including file: moment.min.js
*********************/
//! moment.js
//! version : 2.9.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function(a){function b(a,b,c){switch(arguments.length){case 2:return null!=a?a:b;case 3:return null!=a?a:null!=b?b:c;default:throw new Error("Implement me")}}function c(a,b){return Bb.call(a,b)}function d(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function e(a){vb.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+a)}function f(a,b){var c=!0;return o(function(){return c&&(e(a),c=!1),b.apply(this,arguments)},b)}function g(a,b){sc[a]||(e(b),sc[a]=!0)}function h(a,b){return function(c){return r(a.call(this,c),b)}}function i(a,b){return function(c){return this.localeData().ordinal(a.call(this,c),b)}}function j(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function k(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function l(){}function m(a,b){b!==!1&&H(a),p(this,a),this._d=new Date(+a._d),uc===!1&&(uc=!0,vb.updateOffset(this),uc=!1)}function n(a){var b=A(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=vb.localeData(),this._bubble()}function o(a,b){for(var d in b)c(b,d)&&(a[d]=b[d]);return c(b,"toString")&&(a.toString=b.toString),c(b,"valueOf")&&(a.valueOf=b.valueOf),a}function p(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=b._pf),"undefined"!=typeof b._locale&&(a._locale=b._locale),Kb.length>0)for(c in Kb)d=Kb[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function q(a){return 0>a?Math.ceil(a):Math.floor(a)}function r(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function s(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function t(a,b){var c;return b=M(b,a),a.isBefore(b)?c=s(a,b):(c=s(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function u(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(g(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=vb.duration(c,d),v(this,e,a),this}}function v(a,b,c,d){var e=b._milliseconds,f=b._days,g=b._months;d=null==d?!0:d,e&&a._d.setTime(+a._d+e*c),f&&pb(a,"Date",ob(a,"Date")+f*c),g&&nb(a,ob(a,"Month")+g*c),d&&vb.updateOffset(a,f||g)}function w(a){return"[object Array]"===Object.prototype.toString.call(a)}function x(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function y(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&C(a[d])!==C(b[d]))&&g++;return g+f}function z(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=lc[a]||mc[b]||b}return a}function A(a){var b,d,e={};for(d in a)c(a,d)&&(b=z(d),b&&(e[b]=a[d]));return e}function B(b){var c,d;if(0===b.indexOf("week"))c=7,d="day";else{if(0!==b.indexOf("month"))return;c=12,d="month"}vb[b]=function(e,f){var g,h,i=vb._locale[b],j=[];if("number"==typeof e&&(f=e,e=a),h=function(a){var b=vb().utc().set(d,a);return i.call(vb._locale,b,e||"")},null!=f)return h(f);for(g=0;c>g;g++)j.push(h(g));return j}}function C(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function D(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function E(a,b,c){return jb(vb([a,11,31+b-c]),b,c).week}function F(a){return G(a)?366:365}function G(a){return a%4===0&&a%100!==0||a%400===0}function H(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[Db]<0||a._a[Db]>11?Db:a._a[Eb]<1||a._a[Eb]>D(a._a[Cb],a._a[Db])?Eb:a._a[Fb]<0||a._a[Fb]>24||24===a._a[Fb]&&(0!==a._a[Gb]||0!==a._a[Hb]||0!==a._a[Ib])?Fb:a._a[Gb]<0||a._a[Gb]>59?Gb:a._a[Hb]<0||a._a[Hb]>59?Hb:a._a[Ib]<0||a._a[Ib]>999?Ib:-1,a._pf._overflowDayOfYear&&(Cb>b||b>Eb)&&(b=Eb),a._pf.overflow=b)}function I(b){return null==b._isValid&&(b._isValid=!isNaN(b._d.getTime())&&b._pf.overflow<0&&!b._pf.empty&&!b._pf.invalidMonth&&!b._pf.nullInput&&!b._pf.invalidFormat&&!b._pf.userInvalidated,b._strict&&(b._isValid=b._isValid&&0===b._pf.charsLeftOver&&0===b._pf.unusedTokens.length&&b._pf.bigHour===a)),b._isValid}function J(a){return a?a.toLowerCase().replace("_","-"):a}function K(a){for(var b,c,d,e,f=0;f<a.length;){for(e=J(a[f]).split("-"),b=e.length,c=J(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=L(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&y(e,c,!0)>=b-1)break;b--}f++}return null}function L(a){var b=null;if(!Jb[a]&&Lb)try{b=vb.locale(),require("./locale/"+a),vb.locale(b)}catch(c){}return Jb[a]}function M(a,b){var c,d;return b._isUTC?(c=b.clone(),d=(vb.isMoment(a)||x(a)?+a:+vb(a))-+c,c._d.setTime(+c._d+d),vb.updateOffset(c,!1),c):vb(a).local()}function N(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function O(a){var b,c,d=a.match(Pb);for(b=0,c=d.length;c>b;b++)d[b]=rc[d[b]]?rc[d[b]]:N(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function P(a,b){return a.isValid()?(b=Q(b,a.localeData()),nc[b]||(nc[b]=O(b)),nc[b](a)):a.localeData().invalidDate()}function Q(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Qb.lastIndex=0;d>=0&&Qb.test(a);)a=a.replace(Qb,c),Qb.lastIndex=0,d-=1;return a}function R(a,b){var c,d=b._strict;switch(a){case"Q":return _b;case"DDDD":return bc;case"YYYY":case"GGGG":case"gggg":return d?cc:Tb;case"Y":case"G":case"g":return ec;case"YYYYYY":case"YYYYY":case"GGGGG":case"ggggg":return d?dc:Ub;case"S":if(d)return _b;case"SS":if(d)return ac;case"SSS":if(d)return bc;case"DDD":return Sb;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return Wb;case"a":case"A":return b._locale._meridiemParse;case"x":return Zb;case"X":return $b;case"Z":case"ZZ":return Xb;case"T":return Yb;case"SSSS":return Vb;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"ww":case"WW":return d?ac:Rb;case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"W":case"e":case"E":return Rb;case"Do":return d?b._locale._ordinalParse:b._locale._ordinalParseLenient;default:return c=new RegExp($(Z(a.replace("\\","")),"i"))}}function S(a){a=a||"";var b=a.match(Xb)||[],c=b[b.length-1]||[],d=(c+"").match(jc)||["-",0,0],e=+(60*d[1])+C(d[2]);return"+"===d[0]?e:-e}function T(a,b,c){var d,e=c._a;switch(a){case"Q":null!=b&&(e[Db]=3*(C(b)-1));break;case"M":case"MM":null!=b&&(e[Db]=C(b)-1);break;case"MMM":case"MMMM":d=c._locale.monthsParse(b,a,c._strict),null!=d?e[Db]=d:c._pf.invalidMonth=b;break;case"D":case"DD":null!=b&&(e[Eb]=C(b));break;case"Do":null!=b&&(e[Eb]=C(parseInt(b.match(/\d{1,2}/)[0],10)));break;case"DDD":case"DDDD":null!=b&&(c._dayOfYear=C(b));break;case"YY":e[Cb]=vb.parseTwoDigitYear(b);break;case"YYYY":case"YYYYY":case"YYYYYY":e[Cb]=C(b);break;case"a":case"A":c._meridiem=b;break;case"h":case"hh":c._pf.bigHour=!0;case"H":case"HH":e[Fb]=C(b);break;case"m":case"mm":e[Gb]=C(b);break;case"s":case"ss":e[Hb]=C(b);break;case"S":case"SS":case"SSS":case"SSSS":e[Ib]=C(1e3*("0."+b));break;case"x":c._d=new Date(C(b));break;case"X":c._d=new Date(1e3*parseFloat(b));break;case"Z":case"ZZ":c._useUTC=!0,c._tzm=S(b);break;case"dd":case"ddd":case"dddd":d=c._locale.weekdaysParse(b),null!=d?(c._w=c._w||{},c._w.d=d):c._pf.invalidWeekday=b;break;case"w":case"ww":case"W":case"WW":case"d":case"e":case"E":a=a.substr(0,1);case"gggg":case"GGGG":case"GGGGG":a=a.substr(0,2),b&&(c._w=c._w||{},c._w[a]=C(b));break;case"gg":case"GG":c._w=c._w||{},c._w[a]=vb.parseTwoDigitYear(b)}}function U(a){var c,d,e,f,g,h,i;c=a._w,null!=c.GG||null!=c.W||null!=c.E?(g=1,h=4,d=b(c.GG,a._a[Cb],jb(vb(),1,4).year),e=b(c.W,1),f=b(c.E,1)):(g=a._locale._week.dow,h=a._locale._week.doy,d=b(c.gg,a._a[Cb],jb(vb(),g,h).year),e=b(c.w,1),null!=c.d?(f=c.d,g>f&&++e):f=null!=c.e?c.e+g:g),i=kb(d,e,f,h,g),a._a[Cb]=i.year,a._dayOfYear=i.dayOfYear}function V(a){var c,d,e,f,g=[];if(!a._d){for(e=X(a),a._w&&null==a._a[Eb]&&null==a._a[Db]&&U(a),a._dayOfYear&&(f=b(a._a[Cb],e[Cb]),a._dayOfYear>F(f)&&(a._pf._overflowDayOfYear=!0),d=fb(f,0,a._dayOfYear),a._a[Db]=d.getUTCMonth(),a._a[Eb]=d.getUTCDate()),c=0;3>c&&null==a._a[c];++c)a._a[c]=g[c]=e[c];for(;7>c;c++)a._a[c]=g[c]=null==a._a[c]?2===c?1:0:a._a[c];24===a._a[Fb]&&0===a._a[Gb]&&0===a._a[Hb]&&0===a._a[Ib]&&(a._nextDay=!0,a._a[Fb]=0),a._d=(a._useUTC?fb:eb).apply(null,g),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[Fb]=24)}}function W(a){var b;a._d||(b=A(a._i),a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],V(a))}function X(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function Y(b){if(b._f===vb.ISO_8601)return void ab(b);b._a=[],b._pf.empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=Q(b._f,b._locale).match(Pb)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(R(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&b._pf.unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length),rc[f]?(d?b._pf.empty=!1:b._pf.unusedTokens.push(f),T(f,d,b)):b._strict&&!d&&b._pf.unusedTokens.push(f);b._pf.charsLeftOver=i-j,h.length>0&&b._pf.unusedInput.push(h),b._pf.bigHour===!0&&b._a[Fb]<=12&&(b._pf.bigHour=a),b._a[Fb]=k(b._locale,b._a[Fb],b._meridiem),V(b),H(b)}function Z(a){return a.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e})}function $(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function _(a){var b,c,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;f<a._f.length;f++)g=0,b=p({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._pf=d(),b._f=a._f[f],Y(b),I(b)&&(g+=b._pf.charsLeftOver,g+=10*b._pf.unusedTokens.length,b._pf.score=g,(null==e||e>g)&&(e=g,c=b));o(a,c||b)}function ab(a){var b,c,d=a._i,e=fc.exec(d);if(e){for(a._pf.iso=!0,b=0,c=hc.length;c>b;b++)if(hc[b][1].exec(d)){a._f=hc[b][0]+(e[6]||" ");break}for(b=0,c=ic.length;c>b;b++)if(ic[b][1].exec(d)){a._f+=ic[b][0];break}d.match(Xb)&&(a._f+="Z"),Y(a)}else a._isValid=!1}function bb(a){ab(a),a._isValid===!1&&(delete a._isValid,vb.createFromInputFallback(a))}function cb(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function db(b){var c,d=b._i;d===a?b._d=new Date:x(d)?b._d=new Date(+d):null!==(c=Mb.exec(d))?b._d=new Date(+c[1]):"string"==typeof d?bb(b):w(d)?(b._a=cb(d.slice(0),function(a){return parseInt(a,10)}),V(b)):"object"==typeof d?W(b):"number"==typeof d?b._d=new Date(d):vb.createFromInputFallback(b)}function eb(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function fb(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function gb(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function hb(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function ib(a,b,c){var d=vb.duration(a).abs(),e=Ab(d.as("s")),f=Ab(d.as("m")),g=Ab(d.as("h")),h=Ab(d.as("d")),i=Ab(d.as("M")),j=Ab(d.as("y")),k=e<oc.s&&["s",e]||1===f&&["m"]||f<oc.m&&["mm",f]||1===g&&["h"]||g<oc.h&&["hh",g]||1===h&&["d"]||h<oc.d&&["dd",h]||1===i&&["M"]||i<oc.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,hb.apply({},k)}function jb(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=vb(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function kb(a,b,c,d,e){var f,g,h=fb(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:F(a-1)+g}}function lb(b){var c,d=b._i,e=b._f;return b._locale=b._locale||vb.localeData(b._l),null===d||e===a&&""===d?vb.invalid({nullInput:!0}):("string"==typeof d&&(b._i=d=b._locale.preparse(d)),vb.isMoment(d)?new m(d,!0):(e?w(e)?_(b):Y(b):db(b),c=new m(b),c._nextDay&&(c.add(1,"d"),c._nextDay=a),c))}function mb(a,b){var c,d;if(1===b.length&&w(b[0])&&(b=b[0]),!b.length)return vb();for(c=b[0],d=1;d<b.length;++d)b[d][a](c)&&(c=b[d]);return c}function nb(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),D(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function ob(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function pb(a,b,c){return"Month"===b?nb(a,c):a._d["set"+(a._isUTC?"UTC":"")+b](c)}function qb(a,b){return function(c){return null!=c?(pb(this,a,c),vb.updateOffset(this,b),this):ob(this,a)}}function rb(a){return 400*a/146097}function sb(a){return 146097*a/400}function tb(a){vb.duration.fn[a]=function(){return this._data[a]}}function ub(a){"undefined"==typeof ender&&(wb=zb.moment,zb.moment=a?f("Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release.",vb):vb)}for(var vb,wb,xb,yb="2.9.0",zb="undefined"==typeof global||"undefined"!=typeof window&&window!==global.window?this:global,Ab=Math.round,Bb=Object.prototype.hasOwnProperty,Cb=0,Db=1,Eb=2,Fb=3,Gb=4,Hb=5,Ib=6,Jb={},Kb=[],Lb="undefined"!=typeof module&&module&&module.exports,Mb=/^\/?Date\((\-?\d+)/i,Nb=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,Ob=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,Pb=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Qb=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Rb=/\d\d?/,Sb=/\d{1,3}/,Tb=/\d{1,4}/,Ub=/[+\-]?\d{1,6}/,Vb=/\d+/,Wb=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Xb=/Z|[\+\-]\d\d:?\d\d/gi,Yb=/T/i,Zb=/[\+\-]?\d+/,$b=/[\+\-]?\d+(\.\d{1,3})?/,_b=/\d/,ac=/\d\d/,bc=/\d{3}/,cc=/\d{4}/,dc=/[+-]?\d{6}/,ec=/[+-]?\d+/,fc=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gc="YYYY-MM-DDTHH:mm:ssZ",hc=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],ic=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],jc=/([\+\-]|\d\d)/gi,kc=("Date|Hours|Minutes|Seconds|Milliseconds".split("|"),{Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6}),lc={ms:"millisecond",s:"second",m:"minute",h:"hour",d:"day",D:"date",w:"week",W:"isoWeek",M:"month",Q:"quarter",y:"year",DDD:"dayOfYear",e:"weekday",E:"isoWeekday",gg:"weekYear",GG:"isoWeekYear"},mc={dayofyear:"dayOfYear",isoweekday:"isoWeekday",isoweek:"isoWeek",weekyear:"weekYear",isoweekyear:"isoWeekYear"},nc={},oc={s:45,m:45,h:22,d:26,M:11},pc="DDD w W M D d".split(" "),qc="M D H h m s w W".split(" "),rc={M:function(){return this.month()+1},MMM:function(a){return this.localeData().monthsShort(this,a)},MMMM:function(a){return this.localeData().months(this,a)},D:function(){return this.date()},DDD:function(){return this.dayOfYear()},d:function(){return this.day()},dd:function(a){return this.localeData().weekdaysMin(this,a)},ddd:function(a){return this.localeData().weekdaysShort(this,a)},dddd:function(a){return this.localeData().weekdays(this,a)},w:function(){return this.week()},W:function(){return this.isoWeek()},YY:function(){return r(this.year()%100,2)},YYYY:function(){return r(this.year(),4)},YYYYY:function(){return r(this.year(),5)},YYYYYY:function(){var a=this.year(),b=a>=0?"+":"-";return b+r(Math.abs(a),6)},gg:function(){return r(this.weekYear()%100,2)},gggg:function(){return r(this.weekYear(),4)},ggggg:function(){return r(this.weekYear(),5)},GG:function(){return r(this.isoWeekYear()%100,2)},GGGG:function(){return r(this.isoWeekYear(),4)},GGGGG:function(){return r(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.localeData().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.localeData().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return C(this.milliseconds()/100)},SS:function(){return r(C(this.milliseconds()/10),2)},SSS:function(){return r(this.milliseconds(),3)},SSSS:function(){return r(this.milliseconds(),3)},Z:function(){var a=this.utcOffset(),b="+";return 0>a&&(a=-a,b="-"),b+r(C(a/60),2)+":"+r(C(a)%60,2)},ZZ:function(){var a=this.utcOffset(),b="+";return 0>a&&(a=-a,b="-"),b+r(C(a/60),2)+r(C(a)%60,2)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},x:function(){return this.valueOf()},X:function(){return this.unix()},Q:function(){return this.quarter()}},sc={},tc=["months","monthsShort","weekdays","weekdaysShort","weekdaysMin"],uc=!1;pc.length;)xb=pc.pop(),rc[xb+"o"]=i(rc[xb],xb);for(;qc.length;)xb=qc.pop(),rc[xb+xb]=h(rc[xb],2);rc.DDDD=h(rc.DDD,3),o(l.prototype,{set:function(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(a){return this._months[a.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(a){return this._monthsShort[a.month()]},monthsParse:function(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=vb.utc([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(a){return this._weekdays[a.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(a){return this._weekdaysShort[a.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(a){return this._weekdaysMin[a.day()]},weekdaysParse:function(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=vb([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b},_longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},longDateFormat:function(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b},isPM:function(a){return"p"===(a+"").toLowerCase().charAt(0)},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.apply(b,[c]):d},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)},pastFuture:function(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)},ordinal:function(a){return this._ordinal.replace("%d",a)},_ordinal:"%d",_ordinalParse:/\d{1,2}/,preparse:function(a){return a},postformat:function(a){return a},week:function(a){return jb(a,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6},firstDayOfWeek:function(){return this._week.dow},firstDayOfYear:function(){return this._week.doy},_invalidDate:"Invalid date",invalidDate:function(){return this._invalidDate}}),vb=function(b,c,e,f){var g;return"boolean"==typeof e&&(f=e,e=a),g={},g._isAMomentObject=!0,g._i=b,g._f=c,g._l=e,g._strict=f,g._isUTC=!1,g._pf=d(),lb(g)},vb.suppressDeprecationWarnings=!1,vb.createFromInputFallback=f("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),vb.min=function(){var a=[].slice.call(arguments,0);return mb("isBefore",a)},vb.max=function(){var a=[].slice.call(arguments,0);return mb("isAfter",a)},vb.utc=function(b,c,e,f){var g;return"boolean"==typeof e&&(f=e,e=a),g={},g._isAMomentObject=!0,g._useUTC=!0,g._isUTC=!0,g._l=e,g._i=b,g._f=c,g._strict=f,g._pf=d(),lb(g).utc()},vb.unix=function(a){return vb(1e3*a)},vb.duration=function(a,b){var d,e,f,g,h=a,i=null;return vb.isDuration(a)?h={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(h={},b?h[b]=a:h.milliseconds=a):(i=Nb.exec(a))?(d="-"===i[1]?-1:1,h={y:0,d:C(i[Eb])*d,h:C(i[Fb])*d,m:C(i[Gb])*d,s:C(i[Hb])*d,ms:C(i[Ib])*d}):(i=Ob.exec(a))?(d="-"===i[1]?-1:1,f=function(a){var b=a&&parseFloat(a.replace(",","."));return(isNaN(b)?0:b)*d},h={y:f(i[2]),M:f(i[3]),d:f(i[4]),h:f(i[5]),m:f(i[6]),s:f(i[7]),w:f(i[8])}):null==h?h={}:"object"==typeof h&&("from"in h||"to"in h)&&(g=t(vb(h.from),vb(h.to)),h={},h.ms=g.milliseconds,h.M=g.months),e=new n(h),vb.isDuration(a)&&c(a,"_locale")&&(e._locale=a._locale),e},vb.version=yb,vb.defaultFormat=gc,vb.ISO_8601=function(){},vb.momentProperties=Kb,vb.updateOffset=function(){},vb.relativeTimeThreshold=function(b,c){return oc[b]===a?!1:c===a?oc[b]:(oc[b]=c,!0)},vb.lang=f("moment.lang is deprecated. Use moment.locale instead.",function(a,b){return vb.locale(a,b)}),vb.locale=function(a,b){var c;return a&&(c="undefined"!=typeof b?vb.defineLocale(a,b):vb.localeData(a),c&&(vb.duration._locale=vb._locale=c)),vb._locale._abbr},vb.defineLocale=function(a,b){return null!==b?(b.abbr=a,Jb[a]||(Jb[a]=new l),Jb[a].set(b),vb.locale(a),Jb[a]):(delete Jb[a],null)},vb.langData=f("moment.langData is deprecated. Use moment.localeData instead.",function(a){return vb.localeData(a)}),vb.localeData=function(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return vb._locale;if(!w(a)){if(b=L(a))return b;a=[a]}return K(a)},vb.isMoment=function(a){return a instanceof m||null!=a&&c(a,"_isAMomentObject")},vb.isDuration=function(a){return a instanceof n};for(xb=tc.length-1;xb>=0;--xb)B(tc[xb]);vb.normalizeUnits=function(a){return z(a)},vb.invalid=function(a){var b=vb.utc(0/0);return null!=a?o(b._pf,a):b._pf.userInvalidated=!0,b},vb.parseZone=function(){return vb.apply(null,arguments).parseZone()},vb.parseTwoDigitYear=function(a){return C(a)+(C(a)>68?1900:2e3)},vb.isDate=x,o(vb.fn=m.prototype,{clone:function(){return vb(this)},valueOf:function(){return+this._d-6e4*(this._offset||0)},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var a=vb(this).utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():P(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):P(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},toArray:function(){var a=this;return[a.year(),a.month(),a.date(),a.hours(),a.minutes(),a.seconds(),a.milliseconds()]},isValid:function(){return I(this)},isDSTShifted:function(){return this._a?this.isValid()&&y(this._a,(this._isUTC?vb.utc(this._a):vb(this._a)).toArray())>0:!1},parsingFlags:function(){return o({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(a){return this.utcOffset(0,a)},local:function(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(this._dateUtcOffset(),"m")),this},format:function(a){var b=P(this,a||vb.defaultFormat);return this.localeData().postformat(b)},add:u(1,"add"),subtract:u(-1,"subtract"),diff:function(a,b,c){var d,e,f=M(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=z(b),"year"===b||"month"===b||"quarter"===b?(e=j(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:q(e)},from:function(a,b){return vb.duration({to:this,from:a}).locale(this.locale()).humanize(!b)},fromNow:function(a){return this.from(vb(),a)},calendar:function(a){var b=a||vb(),c=M(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,vb(b)))},isLeapYear:function(){return G(this.year())},isDST:function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},day:function(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=gb(a,this.localeData()),this.add(a-b,"d")):b},month:qb("Month",!0),startOf:function(a){switch(a=z(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a?this.weekday(0):"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this},endOf:function(b){return b=z(b),b===a||"millisecond"===b?this:this.startOf(b).add(1,"isoWeek"===b?"week":b).subtract(1,"ms")},isAfter:function(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+this>+a):(c=vb.isMoment(a)?+a:+vb(a),c<+this.clone().startOf(b))},isBefore:function(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+a>+this):(c=vb.isMoment(a)?+a:+vb(a),+this.clone().endOf(b)<c)},isBetween:function(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)},isSame:function(a,b){var c;return b=z(b||"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+this===+a):(c=+vb(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))},min:f("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(a){return a=vb.apply(null,arguments),this>a?this:a}),max:f("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(a){return a=vb.apply(null,arguments),a>this?this:a}),zone:f("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",function(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}),utcOffset:function(a,b){var c,d=this._offset||0;return null!=a?("string"==typeof a&&(a=S(a)),Math.abs(a)<16&&(a=60*a),!this._isUTC&&b&&(c=this._dateUtcOffset()),this._offset=a,this._isUTC=!0,null!=c&&this.add(c,"m"),d!==a&&(!b||this._changeInProgress?v(this,vb.duration(a-d,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,vb.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?d:this._dateUtcOffset()},isLocal:function(){return!this._isUTC},isUtcOffset:function(){return this._isUTC},isUtc:function(){return this._isUTC&&0===this._offset},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(S(this._i)),this},hasAlignedHourOffset:function(a){return a=a?vb(a).utcOffset():0,(this.utcOffset()-a)%60===0},daysInMonth:function(){return D(this.year(),this.month())},dayOfYear:function(a){var b=Ab((vb(this).startOf("day")-vb(this).startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")},quarter:function(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)},weekYear:function(a){var b=jb(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")},isoWeekYear:function(a){var b=jb(this,1,4).year;return null==a?b:this.add(a-b,"y")},week:function(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")},isoWeek:function(a){var b=jb(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")},weekday:function(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")},isoWeekday:function(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)},isoWeeksInYear:function(){return E(this.year(),1,4)},weeksInYear:function(){var a=this.localeData()._week;return E(this.year(),a.dow,a.doy)},get:function(a){return a=z(a),this[a]()},set:function(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else a=z(a),"function"==typeof this[a]&&this[a](b);return this},locale:function(b){var c;return b===a?this._locale._abbr:(c=vb.localeData(b),null!=c&&(this._locale=c),this)},lang:f("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(b){return b===a?this.localeData():this.locale(b)}),localeData:function(){return this._locale},_dateUtcOffset:function(){return 15*-Math.round(this._d.getTimezoneOffset()/15)}}),vb.fn.millisecond=vb.fn.milliseconds=qb("Milliseconds",!1),vb.fn.second=vb.fn.seconds=qb("Seconds",!1),vb.fn.minute=vb.fn.minutes=qb("Minutes",!1),vb.fn.hour=vb.fn.hours=qb("Hours",!0),vb.fn.date=qb("Date",!0),vb.fn.dates=f("dates accessor is deprecated. Use date instead.",qb("Date",!0)),vb.fn.year=qb("FullYear",!0),vb.fn.years=f("years accessor is deprecated. Use year instead.",qb("FullYear",!0)),vb.fn.days=vb.fn.day,vb.fn.months=vb.fn.month,vb.fn.weeks=vb.fn.week,vb.fn.isoWeeks=vb.fn.isoWeek,vb.fn.quarters=vb.fn.quarter,vb.fn.toJSON=vb.fn.toISOString,vb.fn.isUTC=vb.fn.isUtc,o(vb.duration.fn=n.prototype,{_bubble:function(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;g.milliseconds=d%1e3,a=q(d/1e3),g.seconds=a%60,b=q(a/60),g.minutes=b%60,c=q(b/60),g.hours=c%24,e+=q(c/24),h=q(rb(e)),e-=q(sb(h)),f+=q(e/30),e%=30,h+=q(f/12),f%=12,g.days=e,g.months=f,g.years=h},abs:function(){return this._milliseconds=Math.abs(this._milliseconds),this._days=Math.abs(this._days),this._months=Math.abs(this._months),this._data.milliseconds=Math.abs(this._data.milliseconds),this._data.seconds=Math.abs(this._data.seconds),this._data.minutes=Math.abs(this._data.minutes),this._data.hours=Math.abs(this._data.hours),this._data.months=Math.abs(this._data.months),this._data.years=Math.abs(this._data.years),this},weeks:function(){return q(this.days()/7)},valueOf:function(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*C(this._months/12)
},humanize:function(a){var b=ib(this,!a,this.localeData());return a&&(b=this.localeData().pastFuture(+this,b)),this.localeData().postformat(b)},add:function(a,b){var c=vb.duration(a,b);return this._milliseconds+=c._milliseconds,this._days+=c._days,this._months+=c._months,this._bubble(),this},subtract:function(a,b){var c=vb.duration(a,b);return this._milliseconds-=c._milliseconds,this._days-=c._days,this._months-=c._months,this._bubble(),this},get:function(a){return a=z(a),this[a.toLowerCase()+"s"]()},as:function(a){var b,c;if(a=z(a),"month"===a||"year"===a)return b=this._days+this._milliseconds/864e5,c=this._months+12*rb(b),"month"===a?c:c/12;switch(b=this._days+Math.round(sb(this._months/12)),a){case"week":return b/7+this._milliseconds/6048e5;case"day":return b+this._milliseconds/864e5;case"hour":return 24*b+this._milliseconds/36e5;case"minute":return 24*b*60+this._milliseconds/6e4;case"second":return 24*b*60*60+this._milliseconds/1e3;case"millisecond":return Math.floor(24*b*60*60*1e3)+this._milliseconds;default:throw new Error("Unknown unit "+a)}},lang:vb.fn.lang,locale:vb.fn.locale,toIsoString:f("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",function(){return this.toISOString()}),toISOString:function(){var a=Math.abs(this.years()),b=Math.abs(this.months()),c=Math.abs(this.days()),d=Math.abs(this.hours()),e=Math.abs(this.minutes()),f=Math.abs(this.seconds()+this.milliseconds()/1e3);return this.asSeconds()?(this.asSeconds()<0?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"},localeData:function(){return this._locale},toJSON:function(){return this.toISOString()}}),vb.duration.fn.toString=vb.duration.fn.toISOString;for(xb in kc)c(kc,xb)&&tb(xb.toLowerCase());vb.duration.fn.asMilliseconds=function(){return this.as("ms")},vb.duration.fn.asSeconds=function(){return this.as("s")},vb.duration.fn.asMinutes=function(){return this.as("m")},vb.duration.fn.asHours=function(){return this.as("h")},vb.duration.fn.asDays=function(){return this.as("d")},vb.duration.fn.asWeeks=function(){return this.as("weeks")},vb.duration.fn.asMonths=function(){return this.as("M")},vb.duration.fn.asYears=function(){return this.as("y")},vb.locale("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===C(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),Lb?module.exports=vb:"function"==typeof define&&define.amd?(define(function(a,b,c){return c.config&&c.config()&&c.config().noGlobal===!0&&(zb.moment=wb),vb}),ub(!0)):ub()}).call(this);

/*********************
Including file: flags.js
*********************/
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


(function() {
    
flags = {
    /**
     * makeFlagList - convert the coded flags in the asset to a readable list
     *
     * @param    string - coded list
     * @return  string - readable list
     */
    makeFlagList: function(coded) {
        let flagList = coded.replace(new RegExp('__', 'g'), ',').replace(new RegExp('_', 'g'), '').split(',');
        let read = [], i=0;
        for (i=0; i<flagList.length; i++)  if (flags.specialFlags.indexOf(flagList[i]/1)==-1) read.push(flags.flagNames[(flagList[i]/1)]); 
        return read.join(', ');
    },
    makeFlagIconList: function(coded, template) {
        let flagList = coded.replace(new RegExp('__', 'g'), ',').replace(new RegExp('_', 'g'), '').split(',');
        let list = [], i=0;
        for (i=0; i<flagList.length; i++){
            if (flags.specialFlags.indexOf(flagList[i]/1)==-1) list.push(template({id: flagList[i]}));
        }
        return list.join('');
    },
}
})();


/*********************
Including file: results.js
*********************/
/**
 * results.js - js functions relating to results page functionality
 *
 * @package    search
 * @author     Jon Randy & Laurent
 * @copyright  (c) 2016 Lightrocket
 */
(function() {

results = {
    deferredCount: false,
    pageReady: false,
    _closest:'li.resultCell',
    _assetList: [],
    assetWidth: 300,
    assetMargin: 5,
    marginLeft: 25,
    initTop: 141,
    columnsNb: 0,
    currentPage: 0,
    searchName: false,
    assetsLoading:false,
    itemsPerPage: 50,
    searchUri:"",
    searchParams:"",
    hasMoreResults:true,
    deferredCountDone:false,
    addAnimScale:true,
    useRestful:false,
    flagTemplate:false,
    assetTemplate: false,
    groupHeaderTemplate: false,
    allAssets: {},
    countAssets: 0,
    dateCreatedHideTime: 0,
    allowHTMLInDescription: 0,
    allowHTMLInGroupDesc: 0,
    afterLoadAssetsCallback: false,
    handleSlideshowAllClick:function() {
        var resCount = $('#result_count').attr('title');
        if (resCount == '...') {
                alert(lang.search_results.msg_SlideshowNotYet);
                return false;
        } else {
                var title = $('#result_count b').html();
                title = (title===null) ? lang.search_results.lbl_SearchResults : title;
            (resCount/1) ? slideshow.launch('currentMainSearch', title) : alert(lang.search_results.msg_NoResultsForShow);
        }
    }, // may be overwritten from outside
    handleShareGroupClick:function(){alert(lang.common.msg_NotImplemented);}, // will be overwritten from outside
    handleManageGroupClick:function(){alert(lang.common.msg_NotImplemented);}, // will be overwritten from outside
    relaunch:function() {
        $("ul#searchResults").html("");
        $("#waitForMore").css("display", "block");
        $("#maincontent").css("height", "auto");
        results.hasMoreResults = true;
        results.assetsLoading = false;
        results.currentPage = 0;
        results.countAssets = 0;
        results.allAssets = [];
        results.columnCurrentHeights = undefined;
        results.searchName = false;
        results.loadAssets();
    },
    /**
     * general setup
     *
     * @return  void
     */
    _setup:function() {
        $("#sort_by").parent().customDropDown();
        results.loadAssets();
        //ADDED FOR PREVIEW POPUP
        var previewDivHtml = '<div id="previewPopupWindow"></div>';
        $('body').append(previewDivHtml);
        $("ul#searchResults").css("visibility", "hidden");
        
        // setup 'launch preview' links to make sure they close any hover preview before opening
        $('#searchResults').on("click", 'img[id^="assetthumb_"]+img.blankDL', function(){
            if (typeof(hoverPreview)!='undefined') if (hoverPreview.active) hoverPreview.hide();
        });
        // setup links : 'add to lightbox' + 'Contact Contributor' + 'view more from this group' + 'download'
        results.handleClicks();
        // focus select on advanced search textboxes if advanced search is there
        if ($('#adv_search').length) {
            $('#adv_search input[type=text]').focus(function(){
                this.select();
            });
            results.initKeywordAutocompleteAdvSearch();
        };
        // set ESC to close email popup
        document.onkeyup = function(e){
            if (e === null) { // ie
                keycode = event.keyCode;
            } else {
                keycode = e.which;
            }
            if(keycode == 27) { $('#email_asset_form').addClass('hideMe'); }
        };
        
        // setup slideshow, download result and share links if they are present
        var tmp;
        tmp = $('#select_dlAll, #select_dlNone');
        if (tmp.length) tmp.click(results.handleAllSelection);
        tmp = $('#resActDL');
        if (tmp.length) tmp.click(function(e){e.preventDefault(); results.handleDownloadAllClick();});
        tmp = $('#resActSlide');
        if (tmp.length) tmp.click(function(e){e.preventDefault(); results.handleSlideshowAllClick();});
        $('#resActShareGroup').click(function(e){e.preventDefault();});
        tmp = $('#resActManageGroupFiles');
        if (tmp.length) tmp.click(function(e){e.preventDefault(); results.handleManageGroupClick();});
        tmp = $('#resActADDLB');
        if (tmp.length) tmp.click(function(e){e.preventDefault(); results.handleAddAllToLightBox();});

        // setup contact contrib about all link if present
        var tmp;
        tmp = $('#resActCContact');
        if (tmp.length) tmp.click(function(e) {
            e.preventDefault();
            var link        = $(this);
            var contribID   = link.attr('data-contribid')/1;
                    var groupID     = link.attr('data-groupid')/1;
                    var langstr     = link.attr('data-langstr');
                    var assetID     = '';
            results.contactContributorAll(contribID, langstr, groupID, assetID);
        });
        
        // event handlers on assets TODO:move them?
        // make clicks on flag indicator do nothing
        $('img.assetAct.Flag').parent().click(function(e){e.preventDefault();});
        results.setupPreviewClick();
        $('a.assetShareFile').click(function(e){ e.preventDefault(); });
        results.addShareByEmail();
        results.addCopyLink();
        $('#resultActions .share .social_icons').append('<a title="'+lang.search_results.lbl_ShareViaEmail+'" href="#" class="email no-action"></a>');
        $('#resultActions .share .social_icons .email').click(function(e){e.preventDefault(); results.handleShareGroupClick();});
        $('#searchResults').on('click', 'a.no-action', function(e){
            e.preventDefault();
        });

        // Go to top button
        window.onscroll = function() {results.setScrollBtn($('#goToTopBtn'))};
        $('#goToTopBtn').on('click', function(e){
            $("html, body").animate({ scrollTop: 0 }, 300);
        });

        // TODO:move shiftAll?
        results.shiftAll($("#container").hasClass("opened")?true:false);
        //TODO:move opacity trick?
        $("ul#searchResults").css("visibility", "visible");
        $("ul#searchResults").css("opacity", "0");
        $("ul#searchResults").fadeTo(1000, 1, function(){$("ul#searchResults").css("visibility", "visible");});
        $( window ).resize(function() {results.handleResize();});
        $(window).scroll(function() {
            if( $(window).scrollTop() + $(window).height() > $(document).height() - 600 ) {
                results.loadAssets();
            }
        });
        results.pageReady = true;
        results.showHideResultCount();
        results.setNoShift();
        
        $(hoverPreview._setup({
            container:"#searchResults",
            // userPrefsActiveVar:"hoverPreview_active",
        }));
        results.flagTemplate        = _.template($("#flag-icon-template").html());
        results.assetTemplate       = _.template($("#asset-cell-template").html());
        results.groupHeaderTemplate = _.template($("#group-title-template").html());
        results.socialmediaTemplate = _.template($("#socialmedia-template").html());
        results.shareDlIconTemplate = $("#share-dl-icon-template").length?_.template($("#share-dl-icon-template").html()):false;

        $(".hlp-tooltip").tooltip({html:true,placement:"right",container:"#pageContent"});
    },
    setScrollBtn:function(topButton){
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            topButton.show();
        } else {
            topButton.hide();
        }
    },
    loadAssets:function(){
        if (results.searchUri == "") {
            results.handleDeferredCount(0);
            return;
        }
        if (!results.assetsLoading && results.hasMoreResults) {
            $("#waitForMore").css("display", "block");
            results.assetsLoading = true;
            url = APP.baseURL+results.searchUri;

            results.currentPage ++;
            results.searchParams.page = results.currentPage;

            // since this code is used by other modules, we'll be passing the querystring as a whole for now
            results.searchParams.querystring = new URLSearchParams(window.location.search).toString();

            $.get(url, results.searchParams, function(data){
                if (data.sortBy) {
                    customBootstrapDropdown.selectItem($("#sort_by").parent(),data.sortBy);
                }
                if (data.expired != undefined && data.expired ) {
                    results.stopLoading();
                    $("#maincontent .no-results").append("<h2>" + data.message + "</h2>");
                    $('#goToTopBtn').remove();
                    $('body').css("overflow", 'hidden');
                    results.hasMoreResults = false;
                    results.handleDeferredCount(0);
                } else if (data && data.length !== 0) {
                    if (results.currentPage === 1) {
                        if (data.galleryTitle !== undefined) {
                            results.galleryDetails = {
                                id:         data.galleryId,
                                title:      data.galleryTitle,
                                credit:     data.galleryCredit?data.galleryCredit:false,
                                description :data.galleryDescription?((results.allowHTMLInGroupDesc) ? data.galleryDescription : APP.descriptionConvTextJS(data.galleryDescription)):false,
                            }
                            results.setGroupTitle(results.galleryDetails.id, results.galleryDetails.title, results.galleryDetails.credit, results.galleryDetails.description);
                        }
                        if (data.viewMoreHtmlMsg !== undefined && data.viewMoreHtmlMsg) {
                            $("#groupHeading").html(lang.search_results.msg_ViewMoreShareLbx.format(" <a href=\""+APP.baseURL+"login\">"+lang.common.lbl_MainLinkLogIn+"</a>"));
                            $("#groupHeading").addClass("lightbox-viewmore-msg text-danger");
                        }
                        if (data.assets.length === 0) {
                            results.handleDeferredCount(0);
                            results.stopLoading();
                            results.showNoResults();
                            return;
                        } else if (data.deferredCountURL) {
                            results.launchDeferredCountWait(data.deferredCountURL);
                        } else if (data.totalItems !== undefined && data.totalItems !== -999) {
                            results.handleDeferredCount(data.totalItems);
                        }
                        if (data.assets.length < results.itemsPerPage) {
                            results.hasMoreResults = false;
                            //results.stopLoading();
                        }
                        results.searchName = data.searchName;
                    }
                    $.each(data.assets, function(){
                        results.countAssets++;
                        results.allAssets[this.id] = this;
                        searchResult[this.id] = JSAsset.newAsset(this);
                        hoverPreview.assetDetails[this.id] = this;
                    });
                    newAssets = results.renderAssets(data);

                    $("#maincontent").append("<div id=\"moreAssets\">"+newAssets+"</div>");
                    if($("#moreAssets li").length === 0){
                        results.stopLoading();
                    } else {
                        results.addShareByEmail();
                        results.addCopyLink();
                        results.setAssetLayout("div#moreAssets li.resultCell");
                        $("#moreAssets").remove();
                        results.assetsLoading = false;
                    }
                    if (results.searchParams.directaccess != undefined && results.searchParams.directaccess) {
                        results.hasMoreResults = false;
                        results.handleDeferredCount(data.totalItems);
                        results.stopLoading();
                    }
                } else {
                    results.hasMoreResults = false;
                    results.handleDeferredCount(0);
                    results.stopLoading();
                    results.showNoResults();
                }
                if(results.afterLoadAssetsCallback) results.afterLoadAssetsCallback();
            }, "json");
        }
    },
    setupPreviewClick:function(){
        // preview links
        $('#searchResults').off('click', 'img[id^="assetthumb_"]+img.blankDL');
        $('#searchResults').on("click", 'img[id^="assetthumb_"]+img.blankDL', function(){
            var id = $(this).prev().attr('id').replace('assetthumb_', '');
            results.viewPreview(id/1);
        });

    },
    addShareByEmail:function(){
        //share by email icon
        $('.assetOpts .share .social_icons').each(function(){
            if ($(this).children('.email').length == 0) {
                $(this).append('<a title="'+lang.search_results.lbl_ShareViaEmail+'" href="#" class="email no-action"></a>');
            }
        });
    },
    addCopyLink:function(){
        // //copy link icon
        $('.assetOpts .share .social_icons').each(function(){
            if ($(this).children('.copylink').length == 0) {
                var id = $(this).closest('.resultCell ').data('assetid');
                $(this).append('<a title="' + lang.common.lbl_copyLink + '" href="#" data-link="'+id+'" class="copylink no-action"></a>');
            }
        });
    },
    stopLoading:function(){
        results.hasMoreResults = false;
        $("#waitForMore").css("display", "none");
        results.addEndPage();
    },
    showNoResults:function(){
        marginTop = ($("#groupHeading").height()?($("#groupHeading").offset().top + $("#groupHeading").height()):($("#resultnav").offset().top -results.scrollTop + $("#resultnav").height())) - $("#page").offset().top;
        $("#maincontent .no-results").html("<h2>"+lang.search_results.msg_NoSearchResults+"</h2>");
        $('#goToTopBtn').remove();
        $('body').css("overflow", 'hidden');
        results.setMargin();
    },
    /**
     * Contact a contributor about an asset
     *
     * @param    id of asset to view
     */
    contactContributorAll:function(contribID, contribLang, groupID, assetEmpty) {
        var link = location.href;
        ContribMessenger.launch(contribID, {
            relatesTo       : lang.contributors[contribLang],
            relatesToLink   : link,
            groupID         : groupID,
            assetID         : assetEmpty
        });
    },
    handleClicks:function() {
        // 'Contact Contributor'
        $('#searchResults').off('click', 'a.assetContactContrib');
        $('#searchResults').on('click', 'a.assetContactContrib', function(e) {
            e.preventDefault();
            var link        = $(this);
            var li          = $(this).closest('li.resultCell');
            var contribID   = link.attr('data-contribid')/1;
            var assetID     = li.attr('data-assetid')/1;
            var groupID     = '';
            results.contactAssetContributor(contribID, assetID, groupID);
        });
        // 'add to lightbox'
        $('#searchResults').off('click', 'a.assetAddLbx');
        $('#searchResults').on('click', 'a.assetAddLbx', function(event){
            lightbox.addAssetFromSearch(results._getResultAssetID(this));
            event.preventDefault();
        });
        // 'view more from this group'
        $('#searchResults').off('click', 'a.assetGrp');
        $('#searchResults').on('click', 'a.assetGrp', function(event){
            if ($(this).attr('href') != '#') {
                    window.location = $(this).attr('href');
            }
            event.preventDefault();
        });
        // 'download'
        $('#searchResults').off('click', 'a.resultDL');
        $('#searchResults').on('click', 'a.resultDL', function(event){
            download.begin(results._getResultAssetID(this));
            event.preventDefault();
        });
        $('#searchResults').off('click', '.assetOpts .share .social_icons .email');
        $('#searchResults').on('click', '.assetOpts .share .social_icons .email', function(event){
            event.preventDefault();
            sharePreview.begin({
                fullname: user.fullname,
                asset_id: $(this).closest(".resultCell").attr("data-assetid"),
            });
        });
        $('#searchResults').off('click', '.assetOpts .share .social_icons .copylink');
        $('#searchResults').on('click', '.assetOpts .share .social_icons .copylink', function(event){
            event.preventDefault();
            $('<input id="ThenRemoveIt">').val( APP.baseURL + 'preview/' + $(this).data('link') ).appendTo('body').select()
            document.execCommand('copy');
            $('input#ThenRemoveIt').remove();
            alert(lang.common.msg_copiedToClipboard);
        });
        $('#searchResults').off('mouseover', '.assetOpts .info');
        $('#searchResults').on('mouseover', '.assetOpts .info', function(event){
            li = $(this);
            li_offset = li.offset();
            if($(this).find(".fileDesc").length)
                max_width = parseInt($(this).find(".fileDesc").css("max-width").replace("px", ""));
            else
                max_width = parseInt($(this).find(".fileName").css("max-width").replace("px", ""));
            realTextWidth = (textWidth > max_width)?max_width:textWidth;
            if((li_offset.left + results.assetWidth + realTextWidth - parseInt($("#maincontent").css("margin-left").replace("css", "")) - 100) > $("#maincontent").width())
                $(this).find(".hoverFileInfo").css("right", 0);
            else
                $(this).find(".hoverFileInfo").css("right", "auto");
        });

        $('#searchResults').off('click', '.share_dlselection');
        $('#searchResults').on('click', '.share_dlselection', results.assetToggle);
        $('#searchResults').on('click', '.copy-all-data', results._copyHoverMetadata);
        $('#searchResults').on('click', '.fa-clipboard', function() {
            var elSpan = $(this).siblings('.clipboard-text');
            if(elSpan.length == 0) return false;
            elSpan.css({'background': '#3390ff', 'color': '#fff'});
            APP.copyToClipboardHTML(elSpan.html().replace(/^\s+|\s+$/gm,''));
            setTimeout(function() {
                elSpan.removeAttr('style');
            }, 3000);
        });

    },
    initKeywordAutocompleteAdvSearch:function(){
        $.each($(".adv_search .auto-suggest"),function(){
            let params = {};
            let field = this;
            let acType = $(this).data("ac-type")
            if(acType == "field"){
                params.field = $(this).data("ac-field");
            }
            if($(this).data("kw-type")){
                params.types = $(this).data("kw-type");
            }
            $(this).autocomplete({
                delay: 500,
                source: function(request, response) {
                    $.ajax({
                        url:  APP.baseURL + "search/"+acType+"autosuggest",
                        dataType: "json",
                        data: $.extend({},params,{search_txt: $(field).val()}),
                        success: function(data) {
                            response(data.suggestions);
                            $.each($("ul.ui-autocomplete li div"), function(){
                                $(this).html($(this).html().toLowerCase().replace(request.term.toLowerCase(),'<span class="highlight-word">'+request.term.toLowerCase()+'</span>'));
                            });
                        }
                    });
                },
                minLength: 3,
            }).autocomplete( "widget" ).addClass( "adv_search_autocomplete" );
        });
    },
    /**
     * Contact a contributor about an asset
     *
     * @param    id of asset to view
     */
    contactAssetContributor:function(contribID, assetID, groupEmpty) {
        var link = APP.baseURL+'preview/'+assetID;
        ContribMessenger.launch(contribID, {
            relatesTo       :   lang.contributors.sendMessageAboutAsset,
            relatesToLink   :   link,
                        assetID         :   assetID,
                        groupID         :   groupEmpty
        });
    },
    /**
     * view previews of assets in group
     *
     * @param    id of asset to view
     */
    viewPreview:function(id) {
        var prevParam = {
            id:id,
            url_thumb:$("#result_"+id+" img:first-child").attr("src"),
            fileType:results.allAssets[id]["asset_file_type"].split("_")[0],
        };
        if($('#searchResults > li.resultCell').length > 1 && results.deferredCountDone){
            //find current position of the asset results
            var assetPosition = ($('#searchResults > li').index($('#result_'+id))/1)+1;
            preview.launch(prevParam, results.searchName, false, assetPosition);
        }else{
            preview.launch(prevParam, results.searchName);
        }
    },
    /**
     * get id of asset from any element within the result list item
     *
     * @param  element/string
     * @return  integer id
     */
    _getResultAssetID:function(element) {
        return $(element).closest(results._closest)[0].id.replace('result_','')/1;
     },
    /**
     * do remaining set up on the page related to the results count (when it comes via a deferred count)
     *
     * @param        int    result count value
     * @return    void
     */
    handleDeferredCount:function(data) {
        if(data.toString().indexOf('[') == -1)
            count = parseInt(data);
        else
        {
            allresults = JSON.parse(data);
            count = allresults.length;
        }
        // show the count
        var rc = $('#result_count');
        var single = rc.attr('data-single');
        var plural = rc.attr('data-plural');
        var stitle = rc.attr('data-stitle');
        var resultStr = '' + results._addCommas(count) + ' ' + ((count==1)?single:plural);
        rc.html(stitle.format(resultStr));
        rc.attr('title', count);
        // pagination
        //$('#result_pagination').html(window.pagHTML.replace(new RegExp(window.__pagHTML,'g'), APP.baseURL));
        // show big next arrow if necessary
        var rpp = results.itemsPerPage;
        var pageCount = 1 + Math.floor((count-1)/rpp);
        results.deferredCountDone = true;
    },
    _addCommas:function(value) {
        value += '';
        x = value.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },
    setAssetLayout:function(){
        view = "flow";
        results._assetList = [];
        results.scrollTop = $(window).scrollTop();
        
        //if a selector is passed as argument, we extract the 'li's and add them to the main list of assets
        // this is called when we load more assets
        if(arguments.length > 0)
        {
            if(results.currentPage === 1) results.setMargin();
            $("li.pageNum_"+results.currentPage).css("visibility", "hidden");
            $.each($(arguments[0]), function(){
                $("#searchResults").append(this);
                results._assetList[results._assetList.length] = this;
            });
            columnCurrentHeights = results.columnCurrentHeights;
            if(columnCurrentHeights === undefined){
                columnCurrentHeights = [];
                let tooltipHeight = $(".result-tooltip").height()?$(".result-tooltip").height()+10:0;
                let initTop = tooltipHeight;
                    for(col = 0; col < results.columnsNb; col++){
                    columnCurrentHeights[columnCurrentHeights.length] = initTop;
                }
            }
        }
        else //otherwise we just set the layout for the asset already in the list
        {
            if($("#searchResults li.resultCell").length == 0) return false;
            $.each($("#searchResults li.resultCell"), function(asset){
                results._assetList[results._assetList.length] = this;
            });
            results.setMargin();
            columnCurrentHeights = [];
            let tooltipHeight = $(".result-tooltip").height()?$(".result-tooltip").height()+10:0;
            let initTop = tooltipHeight;
            for(col = 0; col < results.columnsNb; col++){
                columnCurrentHeights[columnCurrentHeights.length] = initTop;
                $("#searchResults li.column_"+col).removeClass("column_"+col);
            }
        }

        mcw = $("#maincontent").width();
        totalHeight = 0;
        for(currentAsset = 0; currentAsset < results._assetList.length; currentAsset++)
        {    
            if(currentAsset <= results.columnsNb && mcw !== $("#maincontent").width())
            {
                mcw = $("#maincontent").width();
                results.setMargin();
            }
            li_id = results._assetList[currentAsset].id;
            asset_id = li_id.replace("result_", "");
            smallestCol = 0;
            for(col = 1; col < results.columnsNb; col++) if(columnCurrentHeights[col] < columnCurrentHeights[smallestCol]) smallestCol = col;
            assetTop = parseInt(columnCurrentHeights[smallestCol]) + parseInt(results.assetMargin);
            left = results.marginLeft+parseInt((smallestCol)*results.assetWidth +(smallestCol*results.assetMargin));
            $("#searchResults li#"+li_id).addClass("column_"+smallestCol);
            $("#searchResults li#"+li_id).css("top", assetTop+"px");
            $("#searchResults li#"+li_id).css("left", left+"px");
            
            // assetHeight = ((results.allAssets[asset_id].thumbHeight === undefined || !results.allAssets[asset_id].width)?results.assetWidth:(results.allAssets[asset_id].height*results.assetWidth/results.allAssets[asset_id].width));
            assetHeight = results.allAssets[asset_id].thumbHeight;

            columnCurrentHeights[smallestCol] = parseInt(columnCurrentHeights[smallestCol]) + assetHeight +parseInt(results.assetMargin);
            if(columnCurrentHeights[smallestCol] > totalHeight){
                totalHeight = columnCurrentHeights[smallestCol];
            }
            //File info text
            textWidth = results.textWidth($("#searchResults li#"+li_id + " .fileDesc").html());
            $("#searchResults li#"+li_id + " .fileDesc").css("width", textWidth+"px");
        }
        if (totalHeight === 0) totalHeight =  $("#maincontent div:first-child").height();
        $("#maincontent").css("height", totalHeight+100+"px");
        results.columnCurrentHeights = columnCurrentHeights;
        biggestCol = 0;
        for(col = 1; col < results.columnsNb; col++) if(columnCurrentHeights[col] > columnCurrentHeights[biggestCol]) biggestCol = col;
        if(results.addAnimScale) $("li.pageNum_"+results.currentPage+" img.hovpvw").addClass("animScale");
        $("li.pageNum_"+results.currentPage).css("visibility", "visible");
        if(!results.hasMoreResults){
            results.stopLoading();
        }
        if(results.scrollTop) $(window).scrollTop(results.scrollTop);
    },
    setNbColumns:function(){
        sideBarLabels = $("body.Search .sidebarTab").length?parseInt($("body.Search .sidebarTab").css("width").replace("px", "")):0;
        results.columnsNb = parseInt(($("#maincontent").width() - sideBarLabels*2) / (results.assetWidth + results.assetMargin));
        if(results.columnsNb == 0) results.columnsNb = 1;
    },
    setMargin:function(){
        let marginTop = ($("#groupHeading").height()?($("#groupHeading").offset().top + $("#groupHeading").height()):($("#resultnav").offset().top - $(window).scrollTop() + $("#resultnav").height())) - $("#page").offset().top;
        $("#maincontent").css("margin-top", marginTop + "px");
        results.setNbColumns();
        totalWidth = results.columnsNb * results.assetWidth + (results.columnsNb -1 ) * results.assetMargin;
        //adjust marginLeft in order to center the results;
        results.marginLeft = ($("#maincontent").width() - totalWidth)/2;
    },
    textWidth:function(text){
        if(text === undefined) return 0;
        else if(text.length > 60) return 500;
        else if(text.length > 30) return 300;
        else return 200;
    },
    addEndPage:function(){
        $(".completeColumn").remove();
        if($("li.resultCell").length >= results.columnsNb && results.columnsNb !== 0)
        {
            columnCurrentHeights = results.columnCurrentHeights;
            biggestCol = 0;
            for(col = 1; col < results.columnsNb; col++) if(columnCurrentHeights[col] > columnCurrentHeights[biggestCol]) biggestCol = col;
            bottom = columnCurrentHeights[biggestCol] + 100;
            for(col = 0; col < results.columnsNb; col++){
                squareHeight = bottom - columnCurrentHeights[col];
                left = results.marginLeft+parseInt((col)*results.assetWidth +(col*results.assetMargin));
            // left -= (col != 0)?(results.assetMargin/2):0;
                width = results.assetWidth; //+parseInt(results.assetMargin)/2;
            //width += (col == 0 || col == results.columnsNb-1)?0:parseInt(results.assetMargin)/2;
                html = "<div class=\"completeColumn column_"+col+"\" style=\"top:"+(columnCurrentHeights[col] + parseInt(results.assetMargin))+"px;left:"+left+"px;width:"+width+"px;height:"+squareHeight+"px\"></div>";
                $("#maincontent").append(html);
            }
            html = "<div class=\"completeColumn\" style=\"top:"+(bottom+results.assetMargin)+"px;height:"+results.assetMargin+"px;width: 1px;\"></div>";
            $("#maincontent").append(html);
        }
    },
    handleResize:function(){
        results.setNoShift();
        columnsNb = results.columnsNb;
        results.setMargin();
        if(results.columnsNb != columnsNb)
            results.setAssetLayout();
        else{
            $(".column_0").css("left", results.marginLeft+"px");
            for(col = 1; col < results.columnsNb; col++){
                left = results.marginLeft+parseInt((col)*results.assetWidth +(col*results.assetMargin));
                $(".column_"+col).css("left", left+"px");
            }
        }
        results.showHideResultCount();
        //show hide result count
    },
    showHideResultCount:function(){
        $("#result_count").css("visibility", ($("#result_count").offset().top > $("#resultnav").offset().top + $("#resultnav").height())?"hidden":"visible");
    },
    shiftAll:function(opened){
        if(opened && !$("#container").hasClass("noShift"))
        {
            //$("div#banner").addClass("sideOpened");
            $("#Panel_Container").off("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd");
            $("#Panel_Container").on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(e){
                $(".sidebarTab").css("display", "block");
                results.setAssetLayout();
            });
        }
        else{
            $("div#banner").removeClass("sideOpened");
            results.setAssetLayout();
        }
    },
    setNoShift:function(){
        if($(window).width() <= 640){
            $("div#banner").removeClass("sideOpened");
            $('#container').addClass('noShift');
        }
        else{
            if($("#container").hasClass("opened")) $("div#banner").addClass("sideOpened");
            $('#container').removeClass('noShift');
        }
    },
    renderAssets:function(data){
        var assets = [];
        var assetsData = data.assets;
        delete data.assets;
        $.each(assetsData, function(id, asset){
            data.asset = asset;
            assets.push(results.renderAsset(data));
        });
        return assets;
    },
    renderAsset:function(data){
        var locArr = [data.asset.location, data.asset.city, data.asset.state, data.asset.country];
        var locs = [];
        $.each(locArr, function(id, loc){if(loc !== "") locs.push(loc);});
        locbit = locs.join(", ");
        var dateLabel = (data.asset.date_label) ? data.asset.date_label : data.asset.date_created;
        date = preview.formatDate(dateLabel, results.dateCreatedHideTime);
        datebit = ((locbit !== '') ? ' - ' : '') + date;
        captionbit = locbit + datebit;
        captionbit += captionbit.trim().length ? ": " : "";
        data.captionbit = captionbit;

        data.socialmedia = results.socialmediaTemplate({
            url     : encodeURIComponent(APP.baseURL + "preview/" + data.asset.id),
            img_url : encodeURIComponent(data.asset.previewURL),
            desc    : encodeURIComponent(data.captionbit),
            flagged : data.asset.flagString,
        });
        data.shareDlIconTemplate = results.shareDlIconTemplate ? results.shareDlIconTemplate({asset_id: data.asset.id}) : "";
        data.asset.description = results.formatDesc(data.asset.description,data.asset.description2,captionbit)
        data.asset.alt = APP.descriptionConvTextJS(data.asset.description);
        data.asset.flagIcons = flags.makeFlagIconList(data.asset.flags, results.flagTemplate);
        return results.assetTemplate(data);
    },
    formatDesc:function(description, description2, captionbit){
        let separator = (description && description2) ? ((results.allowHTMLInDescription) ? '<br/>' : ' ') : '';
        if(description.substr(-8) == "<p>\xa0</p>") 
            description = description.substr(0,description.length-8);
        if(description2.substr(-8) == "<p>\xa0</p>") 
            description2 = description2.substr(0,description2.length-8);
        description = (description + separator + description2).trim();
        if(description.substr(0,3) == "<p>") 
            description = "<p>"+captionbit + description.substr(3);
        else description = captionbit + description;
        return description;
    },
    setGroupTitle:function(id,title,credit,description){
        groupHeader = results.groupHeaderTemplate({
            group_id:id,
            galleryTitle:title,
            galleryCredit:credit,
            galleryDescription:description
        });
        $("#groupHeading").html(groupHeader);
    },
    launchDeferredCountWait:function(url){
        $.get(url, {}, function(data){
            results.handleDeferredCount(data);
        });
    },
    assetSelect:function(asset_id) {
        var thumb = $("li#result_"+asset_id);
        thumb.addClass('selected').find(".share_dlselection").attr('title', lang.lightbox.alt_SelectedIndicator);
        results.refreshFileCount();
    },
    assetToggle:function(e) {
        var thumb = $(this).closest("li.resultCell");
        if (thumb.hasClass('selected')) {
            thumb.removeClass('selected').find(".share_dlselection").attr('title', lang.lightbox.alt_NotselectedIndicator);
        } else {
            thumb.addClass('selected').find(".share_dlselection").attr('title', lang.lightbox.alt_SelectedIndicator);
        }
        results.refreshFileCount();
    },
    refreshFileCount:function() {
        var selections = $('#searchResults li.resultCell.selected').length;
        var totalItems = $('#result_count').attr('title');
        if (selections) {
            selections = selections+'/'+totalItems+' '+lang.common.lbl_Selected;
            $('#resActDL').removeAttr('disabled');
            $('#resActADDLB').removeAttr('disabled');
        } else {
            selections = totalItems+' '+((selections!=1)?lang.common.plural_Asset:lang.common.noun_Asset);
            $('#resActDL').attr('disabled','disabled');
            $('#resActADDLB').attr('disabled','disabled');
        }
        $('#result_count').html(selections);
    },
    handleAllSelection:function(e) {
        e.preventDefault();
        if (this.id=='select_dlAll') {
            $('#searchResults li.resultCell').addClass('selected').find(".share_dlselection").attr('title', lang.lightbox.alt_SelectedIndicator);
        } else {
            $('#searchResults li.resultCell').removeClass('selected').find(".share_dlselection").attr('title', lang.lightbox.alt_NotselectedIndicator);
        }
        results.refreshFileCount();
    },
    handleDownloadAllClick:function(){
        // if (results.downloadAll) download.beginFromResult(results.searchName); // if select all paginated results
        var ids = [];
        $('#searchResults li.resultCell.selected').each(function() {
            let assetID = $(this).data('assetid');
            ids.push(assetID);
        });
        if (ids.length) {
            download.begin(ids);
        } else {
            alert(lang.search_results.lbl_NoAssetsSelected);
        }
    },
    handleAddAllToLightBox:function(){
        var ids = [];
        $('#searchResults li.resultCell.selected').each(function() {
            let assetID = $(this).data('assetid');
            ids.push(assetID);
        });
        if (ids.length) {
            ids.forEach(element => {
                lightbox.addAssetFromSearch(element);
            });
        } else {
            alert(lang.search_results.lbl_NoAssetsSelected);
        }
    },
    _copyHoverMetadata:function(){
        let id = $(this).closest(".resultCell").data("assetid");
        navigator.clipboard.writeText(results.getMetadataHoverText(id));
        alert(lang.common.msg_copiedToClipboard);
    },
    getMetadataHoverText:function(id){
        let text = "";
        if($("#result_"+id+" .fileHeadline").length > 0) text += $("#result_"+id+" .fileHeadline").text()+"\n";
        if($("#result_"+id+" .fileDesc p").length > 0){
            $.each($("#result_"+id+" .fileDesc p"), function(){
                if($.inArray($(this).text().trim(),['','\xa0']) == -1) text += $(this).text()+"\n";
            });
        }else if($("#result_"+id+" .fileDesc").length > 0){
            text += $("#result_"+id+" .fileDesc").text()+"\n";
        }
        if($("#result_"+id+" .fileCredit").length > 0) text += $("#result_"+id+" .fileCredit").text()+"\n";
        if($("#result_"+id+" .reference").length > 0) text +=  $("#result_"+id+" .reference").text()+"\n";
        return text;
    },
};
})();

$(results._setup);


/*********************
Including file: download.js
*********************/
/**
 * download.js - js functions relating to instant downloads of assets
 *
 * @package    downloads
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */
(function() {
    
download = $.extend({},dialog,{
    
    cancelled:false,
    request:false,
    user_email:'',
    _getFileSize:false,
    dl_size : 0,
    totalSize : 0,
    sizeLimit: false,
    mustSetUsage : 0,
    canMergePPTX: false,
    mergeSelected: false,
    merge: 0,
    isContrib : false,
    allIds: false,
    email: false,
    saved_email: false,
    usageData: {},
    usageList: {},
    resizeOverOriginal: false,
    assetOriginalHtmlContent: [],
    /**
     * setup
     *
     * @return  void
     */
    _setup:function() {
    },
    initializeOptions:function(){
        $.extend(download.options,download.default_options,         
            {
                boxId : "download-box",
                buttons:{
                    checkRequisite:{ //setUsage
                        label:lang.common.lbl_Download,
                        preventDismiss:true,
                        events:{
                            click:download.validateRequisite,//validateRequisite
                            classes:""
                        },
                    },
                    formOptions:{//download
                        label:lang.common.lbl_Download,
                        preventDismiss:true,
                        events:{
                            click:download.showRequisite,
                            classes:""
                        },
                    },
                    sendEmail:{
                        label:lang.downloads.btn_largeDownload1,
                        events:{
                            click:download._prepareDelayed
                        },
                        classes:"btn-default"
                    },
                    canWait:{
                        label:lang.downloads.btn_largeDownload2,
                        preventDismiss:true,
                        events:{
                            click:download._prepare
                        },
                        classes:"btn-default"
                    },
                    cancel:{
                        label:lang.common.lbl_Cancel,
                        events:{
                            click:function(){}
                        },
                    },
                },
                // shownCallback: download.shownCallback
            }
        );
        download.allIds = false;        
    },
    
    /**
     * start a download process for passed asset id(s)
     *
     * @param    mixed        array of asset ids to download or single id (string/int)
     * @param    [bool]        optional switch for contributor download (default is false)
     * @return    void
     */
    begin:function(ids) {
        download.totalSize = 0;
        if(download.hiding){
            setTimeout(function(){download.begin(ids)}, 500);
            return;
        }
        download.reset();
        download.merge = 0;
        download.initializeOptions();
        download.options.content = download.message_template({message:download.options.message});
        download.isContrib = (arguments.length>1) ? arguments[1] : false;
        download.dl_email = "";
        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        download.makeButtonsDismiss();
        download.setButtonsHtml();

        alert(lang.downloads.msg_initialising, {time:3600000});
        if (!$.isArray(ids)) ids = [ids];
        this._loadForm(ids);
    },
     
    /**
     * start a download process for named search result
     *
     * @param    string        name of search
     * @param    [bool]        optional switch for contributor download (default is false)
     * @return    void
     */
    beginFromResult:function(resname) {
        if(download.hiding){
            setTimeout(function(){download.beginFromResult(resname)}, 500);
            return;
        }
        download.reset();
        download.initializeOptions();
        download.options.content = download.message_template({message:download.options.message});
        download.isContrib = (arguments.length>1) ? arguments[1] : false;

        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        download.makeButtonsDismiss();
        download.setButtonsHtml();

        alert(lang.downloads.msg_initialising, {time:3600000});
        let form = $('#download-box .dlForm');
        if (form) form.remove();
        this._loadFormForResult(resname);
    },
     
    /**
     * Load the download form for the passed assets
     *
     * @param    array        asset ids to download
     * @param    bool        contrib download?
     * @return    void
     */
    _loadForm:function(ids) {
        let params = download.isContrib ? {id:ids.join(','), c:APP._userKey} : {id:ids.join(',')};
        let URL = APP.baseURL + 'download/formhtml';
        $.post(URL, params, download._receiveForm, 'json');
    },
    
    /**
     * Load the download form for the passed result name
     *
     * @param    string        name of search result
     * @param    bool        contrib download?
     * @return    void
     */
    _loadFormForResult:function(res) {
        let params = download.isContrib ? {sname:res, c:APP._userKey} : {sname:res};
        let URL = APP.baseURL + 'download/resultformhtml';
        $.post(URL, params, download._receiveForm, 'json');
    },
    
    /**
     * Process and prepare the form
     *
     * @param    object        form data object from server
     * @return    void
     */
    _receiveForm:function(data) {
        // check to see if we could download any
        download.allIds = data.allIds;
        if (data.none || data.errorState) {
            if(data.requestForm){
                alert('');
                download.showRequestForm(data.requestForm);
            }
            else{
                alert(lang.downloads.msg_noAccess);
            }
            return;
        }
        alert(data.noAccess ? lang.downloads.msg_limitedAccess.format(data.noAccess) : '');
        download.options.title = data.title;
        download.options.content = data.html;
        download.user_email = data.email;

        download._showForm(data.noAccess);
        if(download.isContrib) download.mustSetUsage = 0; //don't force setting usage if it is a backend download
        download.totalSize = $("#totalFileSize span").html();
        download._setupHandlers();
        download._handleResizeChange(0);

        /**
         * Can the assets be merged ?
         */
        download.canMergePPTX = data.can_merge_pptx;
    },
    
    /**
     * setup handlers for the form
     *
     * @return    void
     */
    _setupHandlers:function() {
        $('#download-box .dlForm .btnRemoveDL').click(download._removeItem);

        $('.FTPsized').hide();
        $("#enable-resize").change(function() {
            if($(this).prop("checked")) $('#sizeSelect').trigger("change");
            else download.updateAssetSizes("");
        });
        $('#sizeSelect').change(function() {
            $("#enable-resize").prop("checked",true);
            download.updateAssetSizes($(this).val());
        });
    },
    updateAssetSizes:function(size){
        download._handleResizeChange(size);
        $('#jpgFormat').removeAttr('disabled');
        if (size != '') {
            $('#jpgFormat').attr('disabled', "disabled");
        }

    },
    /**
     * remove non digit from input field
     *
     * @param  object DOM input field
     * @return string Valid digit input
     */
    _validateInteger:function(field) {
        let val = field.val()
        val = val.replace(/[^0-9]/g,'');
        field.val(val);
        return val;
    },

    /**
     * handle when resize value has been changed
     */
    _handleResizeChange:function(size) {
        if (size==0 || size=='' && download.sizeLimit) size = download.sizeLimit;
        if (size==0 || size=='') {
            $('.FTPsized').hide();
        } else {
            download._changeFileSize(size);
            $('.FTPsized').show();
        }
    },

    /**
     * change resized file size to any affected items in the files list
     *
     * @param    integer        File size
     * @return    void
     */
    _changeFileSize:function(size) {
        // update size of each file in the list
        let w = h = id = 0;
        download.resizeOverOriginal = false;
        $('.dlForm ul li').each(function(){
            id = this.id.replace('dlasset_', '');
            w = $('#assetW_'+id).text()/1;
            h = $('#assetH_'+id).text()/1;
            if(size>=w && size>=h){
                download.resizeOverOriginal = true;
                span = $('#dlasset_'+id+' .FTPsized');
                if(download.assetOriginalHtmlContent[id] === undefined) download.assetOriginalHtmlContent[id] = span.html();
                span.text("("+lang.share.not_resized+")");
                span.addClass("not_resized");
            }
            else
            {
                span = $('#dlasset_'+id+' .FTPsized');
                span.removeClass("not_resized");
                if (w>=h) {
                    h = Math.round(h*size/w);
                    w = size;
                } else {
                    w = Math.round(w*size/h);
                    h = size;
                }
                if(download.assetOriginalHtmlContent[id] != undefined){
                    span.html(download.assetOriginalHtmlContent[id]);
                }
                $('#resizedW_'+id).text(w);
                $('#resizedH_'+id).text(h);
            }
        });
    },
    
    /**
     * remove clicked item
     *
     * @param    event object
     * @return    void
     */
    _removeItem:function(e) {
        e.preventDefault();
        $(this).closest('li').remove();
        let newCount = $('#download-box .dlForm ul li').length;
        if (!newCount) {
            download._destroyForm();
        } else {
            download.options.title = (newCount==1) ? lang.downloads.formTitleSingle : (lang.downloads.formTitleMultiple.format(newCount));
            $('#'+download.options.boxId+" .modal-header h4").html(download.options.title);
            // cancel a previous request if one running
            if (download._getFileSize) download._getFileSize.abort();
            if (newCount>1) {
                let params = download._getCommonParams();
                download._getFileSize = $.post(APP.baseURL + 'download/getfilesize', params, function(res){
                    let span = '#download-box .dlForm div#totalFileSize>span';
                    download.totalSize = res.filesize;
                    $(span).html(res.filesize);
                    if (res.warning=='') { $(span).removeClass('exceedLimit').attr('title', ''); }
                }, 'json');
            } else {
                $('#download-box .dlForm div#totalFileSize').html('');
            }
        }
    },

    /**
     * cancel download
     *
     * @return    void
     */
    _cancel:function() {
        download.cancelled = true;
        if (download.request) download.request.abort();
        if (download._getFileSize) download._getFileSize.abort();
        alert('');  // remove any message present
        download._destroyForm(true);
    },
        
    /**
     * Display the form
     *
     * @return    void
     */
    _showForm:function() {
        // hide hoverpreview first if it is active
        if (typeof(hoverPreview)!='undefined') {
            if (hoverPreview.active) hoverPreview.hide();
        }
        download.addBox();
        download.show();
        $("#"+download.options.boxId).attr("data-mode", "form");     
        download.setButtonsEvents();
    },
    
    /**
     * Destroy the form
     *
     * @return    void
     */
    _destroyForm:function() {
        this.hide();
    },
    
    validateEmail:function(){
        if($("#dl-requisite #user-email").length != 0){
            let email = $("#dl-requisite #user-email input").val();
            if(!download.validEmail(email))
                return false;
            else 
                download.dl_email = email;
                download.saved_email = email;
        }
        return true;
    },
    
    /**
     * Do the submit
     *
     * @return    void
     */
    submit:function() {
        download.setModalBoxMode('submit'); 
        if (download._getFileSize) download._getFileSize.abort();
        let params = download._getCommonParams();
        download._getFileSize = $.post(APP.baseURL + 'download/getfilesize', params, function(res){
            if (res.warning=='') {
                if(res.large == true)
                {
                    $("#"+download.options.boxId).addClass("large-dl-check");
                }
                else{
                    download._prepare();
                }
            } else {
                alert(res.warning);
                $('#download-box .dlForm div#totalFileSize>span').html(res.filesize);
            }
        }, 'json');
    },

    showRequestForm:function(content){
        let contentTemplate = _.template(content);
        dialog.customModal({
            boxId: "dl-request-form",
            title:lang.downloads.lbl_requestTitle,
            content:contentTemplate(),
            buttons:{
                ok:{
                    label:lang.common.lbl_OK,
                    events:{
                        click:download.checkRequestForm
                    },
                    preventDismiss: true,
                },
                cancel:{
                    label:lang.common.lbl_Cancel,
                },
            }
        });
        $("#work-area").parent().customDropDown();
        $("#requested-size").parent().customDropDown();
    },
    checkRequestForm:function(){
        let workArea = $("#work-area").val();
        let valid = true;
        let mustInputEmail = ($(".input-email").length>0);
        $("#request-form").removeClass("required-fields");
        $("#request-form .mandatory-field").removeClass("required-field");
        if(mustInputEmail && $(".input-name input").val() == ""){
            $("#request-form").addClass("required-fields");
            $("#request-form .input-name").addClass("required-field");
            valid = false;
        }
        let userName = mustInputEmail?$(".input-name input").val():false;
        let userEmail = mustInputEmail?$(".input-email input").val():false;
        if(mustInputEmail && userEmail == ""){
            $("#request-form").addClass("required-fields");
            $("#request-form .input-email").addClass("required-field");
            valid = false;
        }
        else if(mustInputEmail && !download.validEmail(userEmail)){
            alert(lang.contributors.sendMessageValidation.fromEmail.email);
            $("#request-form .input-email").addClass("required-field");
            valid = false;
        }
        if(workArea == 0){
            $("#request-form").addClass("required-fields");
            $("#request-form .work-area").addClass("required-field");
            valid = false;
        }
        let propUsage = $("#request-form .proposed-usage textarea").val();
        if(propUsage == ""){
            $("#request-form").addClass("required-fields");
            $("#request-form .proposed-usage").addClass("required-field");
            valid = false;
        }
        let requestedSize = $("#requested-size").val();
        if(valid){
            download.sendRequestForm(workArea, propUsage, requestedSize, userEmail, userName);
        }
    },
    sendRequestForm:function(workArea, propUsage, requestedSize, userEmail, userName){
        let url = APP.baseURL + "download/request";
        params = {workArea:workArea,propUsage:propUsage,requestedSize:requestedSize,ids:download.allIds};
        if(userEmail){
            params.userEmail=userEmail;
            params.userName=userName;
        }
        $.post(url, params, function(){
            dialog.hide();
            alert(lang.downloads.lbl_requestSent);
        });        
    },

    /**
     * This function display the correct box mode
     */
    setModalBoxMode : function(mode, box_id){
        $("#"+this.options.boxId).attr("data-mode", mode);
    },

    getBoxId(args) {
        return (args.length > 0) ? args[0] : this.options.boxId;
    },
    
    /**
     * Show the requisite step
     */
    showRequisite:function(){
        if(download.isContrib) download.submit();
        else{
            download.setModalBoxMode('requisite'); 
            $("#usage-state").parent().customDropDown();
            $("#usage-type").parent().customDropDown();
            $("#usage-main").parent().customDropDown();
            $("#usage-second").parent().customDropDown();
            $("#usage-type").change(download.updateDDMain);
            $("#usage-main").closest(".dropdown").addClass("disabled");
            $("#usage-main").change(download.updateDDSecond);
            $("#usage-second").closest(".dropdown").addClass("disabled");
            $("#dl-requisite").on("click", ".custom-bootstrap-dropdown.disabled button", function(){return false;});

            if (download.usageData.usage_type != undefined) {
                download.setInitialUsage = true;
                customBootstrapDropdown.selectItem($("#usage-type"), download.usageData.usage_type);
                $("#usage-type").trigger("change");
                download.setInitialUsage = false;
            }
            let usageOther = (download.usageData.usage_other != undefined) ? download.usageData.usage_other : '';
            $("#usage-other").val(usageOther);

            if($("#dl-requisite #user-email").length != 0 && download.saved_email){
                $("#dl-requisite #user-email input").val(download.saved_email);
            }
        }
    },
    updateDDMain:function(e){
        $("#usage-main").closest(".dropdown")[parseInt($(this).val())?'removeClass':'addClass']("disabled");
        let values = {0: ""};
        if(parseInt($(this).val())){
            $.each(download.usageList['order'][$(this).val()], function(){
                values["id_"+this.id.toString()] = this.name;
            });
        }
        let usageMain = (download.setInitialUsage && download.usageData.usage_main != undefined) ? download.usageData.usage_main : 0;
        download.setDDContent($("#usage-main"), values, usageMain);
    },
    updateDDSecond:function(e){
        let type = $('#download-box #usage-type').val();
        $("#usage-second").closest(".dropdown")[parseInt(type)?'removeClass':'addClass']("disabled");
        let values = {0: ""};
        if(parseInt(type)){
            $.each(download.usageList['order'][type], function(){
                values["id_"+this.id.toString()] = this.name;
            });
        }
        let usageSecond = (download.setInitialUsage && download.usageData.usage_second != undefined) ? download.usageData.usage_second : 0;
        download.setDDContent($("#usage-second"), values, usageSecond);
    },
    setDDContent:function(elt, values, selected){
        customBootstrapDropdown.removeAllItems(elt);
        $.each(values, function(k,v){
            customBootstrapDropdown.addItem(elt,k.replace("id_",""),v);
        });
        customBootstrapDropdown.selectItem(elt,selected);
        elt.trigger("change");
    },
    validateRequisite:function(){
        let errors = [];
        $("#dl-requisite .error-msg").addClass("hideMe");
        $("#dl-requisite .input-error").removeClass("input-error");
        if (!download.validateEmail()) {
            $("#user-email input").parent().addClass("input-error");
            errors.push(lang.downloads.msg_emailFormatError);
        }
        if($("#usage-type").val() == 0){
            $("#usage-type").parent().addClass("input-error");
            $("#usage-main").parent().addClass("input-error");
            errors.push(lang.download_followup.err_input_usage);
        }
        else if($("#usage-main").val() == 0 ){
            $("#usage-main").parent().addClass("input-error");
            errors.push(lang.download_followup.err_input_usage);
        }

        let tcsError = false;
        $.each($('.chk-download-agreement'), function(){
            if (!$(this).prop("checked")) {
                $(this).addClass("input-error");
                if(!tcsError){
                    tcsError= true;
                    errors.push(lang.downloads.msg_TCsError);
                }
            }
        });
        if(errors.length > 0){
            $("#dl-requisite .error-msg").removeClass("hideMe");
            $("#dl-requisite .error-msg").html("<ul><li>"+errors.join("</li><li>")+"</li></ul>");
        }
        else{
            download.submit();
        }

    },
    getUsageData:function(){
        return {
            usage_state: 1,
            usage_type: $("#usage-type").val(),
            usage_main: $("#usage-main").val(),
            usage_second: $("#usage-second").val(),
            usage_other: $("#usage-other").val(),
        };
    },
    /**
     * Start downloading
     *
     * @params  object to be sent via ajax
     * @return  void
     */
    _prepare:function() {
        $("#"+download.options.boxId).removeClass("large-dl-check");
        params = download._getCommonParams();
        download.showPrepare();
        $('#'+download.options.boxId+'-btn-sendEmail').unbind();
        ajax_id = download._getToken();
        $('#'+download.options.boxId+'-btn-sendEmail').click( function(e){download._abortDirectDownload(ajax_id);});
        download.dl_size = $("#enable-resize").prop("checked")?$('#sizeSelect').val():0;
        let jpg = 0;
        if ($('#sizeSelect').length) sz = $('#sizeSelect').val();
        if ($('#jpgFormat').length) jpg = $('#jpgFormat').is(':checked') ? 1 : 0;
        (typeof(params.c)!='undefined' && params.c!==false) ? $.extend(params, {size:download.dl_size}) : $.extend(params, {size:download.dl_size, attachPDF:$("#attach-metadata-pdf").prop("checked")?1:0, origmeta:$('#chkOrigMeta').is(':checked')?1:0, saveAsJPGFormat:jpg});
        $.extend(params, {ajax_id:ajax_id});
        if(download.mustSetUsage) params.usage = download.getUsageData();
        let URL = APP.baseURL + 'download/prepare';
        download.cancelled = false;
        alert(lang.downloads.msg_startShortly, {time:3600000, persistent:true});
        params['merge_pptx'] = $('#merge_slide').length?($('#merge_slide').prop("checked")?1:0):0;
        params['embedText'] = $('#embed-text').length?($('#embed-text').prop("checked")?1:0):0;
        params['useProvenanceWatermark'] = $('#provenance_watermark').length?($('#provenance_watermark').prop("checked")?1:0):0;
        
        download.request = $.ajax({
            type: "POST",
            url:URL,
            data: params,
            success: download._downloadReady,
            timeout: 0
        });
    },
                
    _prepareDelayed:function(){
        let params = download._getCommonParams();
        alert(lang.downloads.lbl_willSendEmail.format(download.user_email));
        // let sz = $('[name=size]').serializeArray()[0].value;
        (typeof(params.c)!='undefined' && params.c!==false) ? $.extend(params, {size:download.dl_size, async:true}) : $.extend(params, {size:download.dl_size, async:true, origmeta:0});
        if(download.mustSetUsage) params.usage = download.getUsageData();
        $.ajax({
            url:APP.baseURL + 'download/prepare',
            type:'POST',
            data:params,
            cache:false,
            dataType:'json',
            async:true
        });
        download._destroyForm();      
    },
    showPrepare:function(){
        // download.setModalBoxMode("submit");
        $('#'+download.options.boxId+" .modal-header h4").html(download.options.title+" ("+download.totalSize+")");

    },
 
    _abortDirectDownload:function(ajax_id) {
        //let params = download._getCommonParams();
        if(download.request && download.request !== undefined) download.request.abort();
        alert(lang.downloads.lbl_willSendEmail.format(download.user_email));
        let params = {ajax_id:ajax_id};
        $.ajax({
            url:APP.baseURL + 'download/abortdirectdl',
            type:'GET',
            data:params,
            cache:false,
            dataType:'json',
            async:true
        });
        download._destroyForm();
    },
            
    _getToken:function() {
        return Math.random().toString(36).substr(2)+new Date().getTime().toString(36); // to make it longer
    },

    /**
     * Get common parameters for getting file size, prepare download
     *
     * @return  object to be sent via ajax
     */
    _getCommonParams:function() {
        let ids = [], code = $('#c').length ? $('#c').val() : false;
        $('#download-box .dlForm ul li').each(function(){ids.push($(this).attr('id').replace('dlasset_',''));});
        let params = (code) ? {id:ids.join(','), c:code, attachPDF:$('body').find("#attach-metadata-pdf").prop("checked")?1:0, origmeta:$('#chkOrigMeta').is(':checked')?1:0, size:$("#enable-resize").prop("checked")?$('#sizeSelect').val():false, saveAsJPGFormat:$('#jpgFormat').is(':checked')?1:0} : {id:ids.join(',')};
        if(download.dl_email) params.dl_email = download.dl_email;
        return params;
    },
    
    /**
     * respond to download being ready
     *
     * @param    int        id of download that is ready
     * @return    void
     */
    _downloadReady:function(id) {
        id = parseInt(id);
        if (!download.cancelled) {
            download._destroyForm();
            download.request = false;
            alert(''); // clear any message
            if (id) {
                let url = APP.baseURL + 'download/get/' + id; // go to the force download URL for the download
                download.startDownload(url);
                // download.startDownload(url, data.filename);
            } else {
                alert(lang.downloads.msg_ProblemWithDownload);
            }
        }
    },
    startDownload:function(url, filename){
        let element = document.createElement('a');
        element.setAttribute('href',url);
        // element.setAttribute('download', filename);
        element.click();
    },
    validEmail:function(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 re.test(email);
    }

});
})();
$(download._setup);


/*********************
Including file: hoverPreview.js
*********************/
/**
 * hoverPreview.js - js functions relating to the mouseover 'hover' preview of assets
 *
 * @package    search
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var hoverPreview = {
    
    active:false,            // switch hover preview on/off
    assetDetails:{},        // to store details of assets on the page - will be filled by dynamically generated JS within the page
    assetColumnList:["id","hvPreviewURL","status","location","city","state","country","date_created","previewCaption","credit","hvPrevDimensions","previewExt"],
    elem:false,                // convenience var to store the hoverPreview div
    activePreviewID:false,    // stores id of the asset which the hoverPreview is currently showing details of
    timerID:false,            // stores timeour reference
    initialDelay:250,        // initial delay (ms) before preview appears
    visible:false,
    settings:{noCaption:false, headerHeight:0, thumbimgPrefix:''},
    can_show:true,
    containers:{},
    mobileMode: false,
        
    /**
     * initiate - start the hover preview
     *
     * @param  mixed - id of asset, or event object
     * @return  boolean - true if hover started, false otherwise
     */
    initiate:function(id, container) {
        var target = $(id.target).closest(".hovpvw");
        if (!hoverPreview._isActive(container)) return false;
        id = (target) ? hoverPreview._getAssetIDFromClass(id.currentTarget.className) : id; // deal with being passed an event or an id
        if(hoverPreview.assetDetails[id] == undefined || !hoverPreview.assetDetails[id].hvPreviewURL) return false;

        if(hoverPreview.assetDetails[id].status == 2){
            hoverPreview.can_show = false;
            return;
        }
        else hoverPreview.can_show = true;
        // fill in content
        if (id != hoverPreview.activePreviewID) {
            hoverPreview._setThumbImgPrefix(target);
            hoverPreview._setupContent(id);
        }
        
        // set the position and size of the preview container
        hoverPreview._setSizeAndPosition(id, target);
        
        ////// // show preview
        ////// hoverPreview.elem.fadeIn('fast');
        
        // if previous timer running, clear it
        if (hoverPreview.timerID) clearTimeout(hoverPreview.timerID);
        
        // set timer to display the preview
        hoverPreview.timerID = setTimeout(hoverPreview.show, hoverPreview.initialDelay);
        
        return true;
    },

    /**
     * hover preview is on or off
     */
    _isActive:function(container) {
        return hoverPreview.containers[container].active;
    },

    /**
     * set prefix for id of thumbnail to preview e.g. for $('groupassetthumb_2287'), will pass string 'group' as thumbimgPrefix
     * 
     * @return    void
     */
    _setThumbImgPrefix:function() { hoverPreview.settingsthumbimgPrefix = ''; },
    
    /**
     * show - show the hover preview
     *
     * @return  void
     */
    show:function() {
        if(!hoverPreview.can_show) return;
        if(hoverPreview.mobileMode){
            hoverPreview.hide();
            return;
        }
        // show preview
        hoverPreview.elem.fadeIn('fast', function(){
            hoverPreview.visible = true;

            // start the video when we show it (solves IE problem)
//            vid = hoverPreview.elem.find('object');
//                        if (vid!= undefined) {
//                vid.play();
//            }
            vid = hoverPreview.elem.find('object');
            if (vid.length) {
                if (vid[0].startPlayer) vid[0].startPlayer();
                try {
                    aud = new niftyplayer('audioPlayer');
                    aud.play();
                } catch(e) {}
            }
        });
        vid = document.getElementsByTagName('video')[0];
        if (vid!= undefined) {
            // vid.play();
        }
        aud = document.getElementsByTagName('audio')[0];
        if (aud!= undefined) {
            aud.play();
        }
        hoverPreview.timerID = false;
    },
    
    /**
     * hide - hide the hover preview
     *
     * @return  void
     */
    hide:function() {
        if(!hoverPreview.elem) return false;
        clearTimeout(hoverPreview.timerID);
        hoverPreview.timerID = false;
        // stop the video before we hide it (stops it playing in background on IE)
        vid = hoverPreview.elem.find('object');
        if (vid.length) {
            if (vid[0].startPlayer) vid[0].startPlayer(false);
            try {
                aud = new niftyplayer('audioPlayer');
                aud.stop();
            } catch(e) {
                
            }
        }
        vid = document.getElementsByTagName('video')[0];
        if (vid!= undefined) {
            vid.pause();
        }
        aud = document.getElementsByTagName('audio')[0];
        if (aud!= undefined) {
            aud.pause();
        }
        hoverPreview.elem.hide();
        hoverPreview.visible = false;
    },
    
    /**
     * turns the hoverPreview on and off
     *
     * @return  bool        active state
     * @return  void
     */
    setActive:function(state,container) {
        hoverPreview.active = state ? true : false;
        if (!state) hoverPreview.hide(container);
        hoverPreview._saveState();
    },
    
    /**
     * save active state of hoverPreview in a user pref
     *
     * @return  void
     */
    _saveState:function(){
        userPrefs.set('hoverPreview_active', hoverPreview.active?1:0);
    },
    
    /**
     * set up content for the hover preview
     *
     * @param  integer        id of asset
     * @return  void
     */
    _setupContent:function(id) {
        var dets = hoverPreview.assetDetails[id];
        var result;
        result = assetPreview.getHTML(id, dets, hoverPreview.settings.noCaption, true, true, hoverPreview.settings.thumbimgPrefix);
        var isObj = typeof(result.html) != 'undefined';
        hoverPreview.elem.html(isObj?result.html:result);
        if (isObj) result.callback();
        hoverPreview.activePreviewID = id;
    },

    /**
     * set size and position of preview
     *
     * @param  integer        id of asset
     * @return  void
     */
    _setSizeAndPosition:function(id) {
        // size is determined by content so no need to set it
        // pos
        var target = (arguments.length>1) ? arguments[1] : false;
        var headerHeight = hoverPreview.settings.headerHeight;
        var hw = hoverPreview.elem.width();
        var hh = hoverPreview.elem.height();
        var thumb = hoverPreview._getHoverThumb(id, target);
        var offs = thumb.offset();
        var d = $(document);
        var x = offs.left - d.scrollLeft();
        var y = offs.top - d.scrollTop();
        var x1 = x + thumb.width() + 5;
        var x2 = x - hw - 25;
        var rx = ((x1 + hw + 20) > $(window).width()) ? x2 : x1;
        var ry = y + (thumb.height()/2) - (hh/2 + 10);
        var overy=ry + hh + 20;
        var wh=$(window).height();
        if (overy > wh) ry = ry - (overy-wh);
        ry = (ry<headerHeight) ? headerHeight : ry;

        hoverPreview.elem.css('top', ry+'px').css('left', rx+'px');
    },

    /**
     * get current thumbnail to preview
     * 
     * @param  integer        id of asset
     * @return object        DOM
     */
    _getHoverThumb:function(id) {
        target = (arguments.length>1)?arguments[1]:false;
        var thumb = $(target).hasClass("hovThumb")?target:$(target).find(".hovThumb");
        return $(thumb).length?$(thumb):$('#result_'+id+' .imgs img');
    },
    
    /**
     * get the id of the asset we are to preview from inside a class name
     *
     * @param  string        class string
     * @return  id/false
     */
    _getAssetIDFromClass:function(c) {
        var re = new RegExp('pvwid_([0-9]+)', 'i');
        var m = re.exec(c);
        return (m === null) ? false : m[1];
    },
    
    /**
     * wire up relevant elements to show previews
     *
     * @return  void
     */
    _setupHoverEventHandlers:function(container) {
        $(container).off( "mouseenter mouseleave" , ".hovpvw");
        $(container).on("mouseenter",".hovpvw", function(e){hoverPreview.initiate(e,container);}).on("mouseleave", ".hovpvw", hoverPreview.hide);
        // hide hover preview on some elements
        $('#header,#resultnav,#sidebar').mousemove(function() { if ( hoverPreview.active && hoverPreview.visible) hoverPreview.hide();});
        $(".stopHoverPreview").mousemove(function() { if ( hoverPreview.active && hoverPreview.visible) hoverPreview.hide();});
    },
    
    /**
     * general setup for hover previews
     *
     * @return  void
     */
    _setup:function(options) {
        
        if(options.container === undefined || $(options.container).length === 0){
            console.log("To enable hover preview, please call hoverPreview.setup({container:[selector]}) with a valid selector");
            return false;
        }
        var hpa = (options.userPrefsActiveVar === undefined)?true:userPrefs.get(options.userPrefsActiveVar);
        hpa = (hpa===null) ? true : ((hpa/1) ? true : false);
        hoverPreview.containers[options.container] = {
            active: hpa,
        };
        hoverPreview.elem = $('#hoverPreview'); // convenience var
        if (hoverPreview.settings.headerHeight==0) hoverPreview.settings.headerHeight = $('#header').height() + $('#Panel_Container').height() + 10;
        hoverPreview._setupHoverEventHandlers(options.container);
        $('#largepreview').click(function(){hoverPreview.setActive(this.checked);});
    }
};

// set up on DOM ready
//$(hoverPreview._setup);




/*********************
Including file: side_bar.js
*********************/
/**
 * side_bar.js - js functions relating to the search results page sidebar
 *
 * @package    search
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */
var searchSideBar = {

    _cookieName : 'sidebarTab',

     /**
     * setup search side bar
     *
     * @return  void
     */
    _setup:function() {
        $('#sidebar .sidebarTab').click(function(e){searchSideBar._handleTabClick($(e.target).parent().attr("id").replace("tab_",""))});
        searchSideBar.setHiddenSortBys($("#sort_by").val());
        $("#sort_by").change(function() {
            searchSideBar.setHiddenSortBys($(this).val());
            searchSideBar.setParamInURL('sort_by', $(this).val());
            results.searchParams.sort_by = $(this).val();
            results.relaunch();
        });
        $('a[href$="adv_search"]').on('click', function(event){event.preventDefault();searchSideBar._openSideBar('advance_search')});
        $('a[href$="mylightbox"]').on('click', function(event){event.preventDefault();searchSideBar._openSideBar('lightbox')});

        // date range in advance search
        $('#dateFrom, #dateTo').bind('change keyup', function(){ $('#chk_dateRange').attr('checked', true); });
        $('#chk_dateRange').click(function(){ if (!this.checked) { $('#adv_search #dateFrom, #adv_search #dateTo').val(''); } });

        // color activation in advance search
        $('#colour-pix, #greyscale-pix').bind('change keyup', function(){ $('#chk_color').attr('checked', true); });
        $('#chk_color').click(function(){ if (!$(this).prop("checked")) { 
            $('#colour-pix, #greyscale-pix').prop('checked', false);
            $('.selected-color').val('');
            $('.color-palette li.selected').removeClass('selected');
         } });
        
        // Force open sidebar
        var urlParams = searchSideBar.parseURLParams();
        if(urlParams.open_panel != undefined && urlParams.open_panel == 1) {
            $('a[href$="adv_search"]').trigger('click');
        }

        $("#adv_search .color-palette ul>li").click(searchSideBar.selectColor);

        $('.advSearchSubmit input[type="reset"]').on('click', function(ev) {
            if($('#chk_color').prop("checked")) $('#chk_color').trigger("click");
            ev.preventDefault();
            let $form = $(this).parents("form");
            $form.find("input[type=text], textarea").val("");
            $form.find("select").prop("selectedIndex", 0);
            $form.find("#country").multiselect('deselectAll', false);
            $form.find("input[type=checkbox]", "radio")
                .prop('checked', false)
                .prop('selected', false);
        });

        $('#country').multiselect({
            nonSelectedText: lang.adv_search.lbl_Any,
            buttonClass: "form-control",
            enableFiltering: true,
            enableCaseInsensitiveFiltering: true,
        });
    },
    setHiddenSortBys:function(val){
        $(".sort_value").val(val);
    },
     /**
     * handle clicks on link to open side bar
     *
     * @param  string         id of panel related to the header click
     * @param  [false]         add a second param of false to force a change to named tab without doing any closing of sidebar
     * @return  void
     */
    _openSideBar:function(tab) {
        console.log({tab});
        var c = searchSideBar._cookieName;
        var current = $.cookie(c);
        var currentEl = current ? $('#'+current) : false;
        var clickedEl = $('#'+tab);
        var sidebar = $('#container');
        // clicked on something other than current?

        if (current)
        {
            currentEl.removeClass('actived');
            $("#tab_"+currentEl.attr("id")).removeClass('actived');
        }
        clickedEl.addClass('actived');
        $("#tab_"+clickedEl.attr("id")).addClass('actived');
        current = tab;
        // clicked on current

        $.cookie(searchSideBar._cookieName, current, { path: '/', expires: 10 });
        !current ? sidebar.removeClass('opened') : sidebar.addClass('opened');
        results.shiftAll(!current?false:true);
    },

        /**
        * handle clicks on tab headers
        *
        * @param  string         id of panel related to the header click
        * @param  [false]         add a second param of false to force a change to named tab without doing any closing of sidebar
        * @return  void
        */
    _handleTabClick:function(clicked) {
        console.log({clicked});
        var c = searchSideBar._cookieName;
        var current = $.cookie(c);
        var currentEl = current ? $('#' + current) : false;
        var clickedEl = $('#' + clicked);
        var sidebar = $('#container');
        opened = false;
        openclose = false;
        // clicked on something other than current?
        if (current!=clicked) {
            if (current)
            {
                currentEl.removeClass('actived');
                $("#tab_" + currentEl.attr("id")).removeClass('actived');
            }
            else openclose = true;
            clickedEl.addClass('actived');
            $("#tab_" + clickedEl.attr("id")).addClass('actived');
            current = clicked;
            opened = true;
        // clicked on current
        } else {
            if (arguments.length==1) {
                currentEl.removeClass('actived');
                $("#tab_" + currentEl.attr("id")).removeClass('actived');
                current = '';
            }
            else{
                //nothing was clicked, we just wanted to make sure the tab was opened
                return;
            }
            openclose = true;
        }
        $("#container").removeClass("lightbox-expanded");
        $.cookie(searchSideBar._cookieName, current, { path: '/', expires: 10 });
        !current ? sidebar.removeClass('opened') : sidebar.addClass('opened');
        results.shiftAll(opened);
    },
    setParamInURL:function(key,value){
        let params = searchSideBar.parseURLParams();
        params[key] = value;
        let newURL = document.location.href.split("?")[0] + "?" + searchSideBar.makeURLParams(params);
        window.history.pushState({ path: newURL }, '', newURL);
    },
    makeURLParams:function(params){
        let params_str = [];
        $.each(params, function(k,v){
            params_str.push(k+"="+v);
        });
        return params_str.join("&");
    },
    parseURLParams:function(){
        let parts = document.location.search.substring(1).split("&");
        let params = {};
        $.each(parts, function(){
            param = this.split("=");
            params[param[0]] = (param[1] != undefined)?param[1]:"";
        });
        return params;
    },
    selectColor:function(){
        let selElt = $("#adv_search .color-palette ul>li.selected");
        let selected = selElt.length?selElt.data("color"):false;
        $("#adv_search .color-palette ul>li.selected").removeClass("selected");
        $("#adv_search .selected-color").val("");
        if($(this).data("color") != selected){
            $('#adv_search .color-palette ul>li[data-color="'+$(this).data("color")+'"]').addClass("selected");
            $("#adv_search .selected-color").val($(this).data("color"));
        }
    },
};

// set up on dom ready
$(searchSideBar._setup);


/*********************
Including file: resultThumbZoom.js
*********************/
/**
 * resultThumbZoom js - does the fancy thumbnail zooming on results page
 *
 * @package    search
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var resultThumbZoom = {
    
    cookieSetTimer:null,
    
    /**
     * zoom - set the 'zoom' level of all asset thumbs
     *
     * @param  integer        zoom level
     * @return  void
     */
    zoom:function(i) {
        if (hoverPreview) hoverPreview.hide();
        $('div.imgs').css('font-size', i.value+'px');
        if(resultThumbZoom.cookieSetTimer != null )    clearTimeout(resultThumbZoom.cookieSetTimer);
        resultThumbZoom.cookieSetTimer = setTimeout(function(){ userPrefs.set('result_zoomlevel', i.value); }, 500);
    }
        
};


/*********************
Including file: assetPreview.js
*********************/
/**
 * assetPreview.js - js functions for generating preview html for assets (used in hoverpreviews and asset selector)
 *
 * @package    search
 * @author     Jon Randy
 * @copyright  (c) 2009 OnAsia
 */
var assetPreview = {
    
    /**
     * generate html for the preview
     *
     * @param  integer        id of asset we are generating preview for
     * @param  object        object with details of asset (probably an asset object)
     * @param  [bool]        audio/video only - display a caption for the asset? default is false
     * @param  [bool]        audio/video only - autoplay the preview? default is false
     * @param  [string]        id of thumbnail to preview
     * @return  void
     */
    getHTML:function(id, dets) {
        var html = "";
        noCaption = (arguments.length > 2) ? arguments[2] : false; // for audio and video
        autoplay = (arguments.length > 3) ? arguments[3] : false; // for audio and video
        isPreview = (arguments.length > 4) ? arguments[4] : false; // for audio and video
        thumbimgPrefix = (arguments.length > 5) ? arguments[5] : '';
        // do we have a preview?
        if (!dets || !dets['hvPreviewURL']) {
            html = assetPreview._thumbPreviewHTML(id, dets, noCaption, thumbimgPrefix);
        } else {
            switch (dets['previewExt']) {
                case 'jpg':
                case 'png':
                case 'gif':
                    html = assetPreview._imagePreviewHTML(id, dets, noCaption, thumbimgPrefix);
                    break;
                case 'flv':
                case 'mp4':
                    html = assetPreview._videoPreviewHTML(id, dets, noCaption, autoplay, isPreview);
                    break;
                case 'mp3':
                    html = assetPreview._audioPreviewHTML(id, dets, noCaption, autoplay);
                    break;
            }
        }
        return html;
    },
    
    /**
     * generate html for the caption area
     *
     * @param  object        object with details of asset (probably an asset object)
     * @param  bool            display a caption for the asset?
     * @return  string        htmla
     */
    _captionHTML:function(dets, noCaption) {
        var init = (arguments.length==3) ? arguments[2] : '';
        if (noCaption) return '';
        var html = '';
        // filename
        html += '<span>'+dets.original_filename+'</span>';
        // location and date + caption
        if (dets.location || dets.city || dets.state || dets.country || dets.date_created || dets.previewCaption) {
            var locArr = [dets.location, dets.city, dets.state, dets.country];
            var locbit = $.grep( locArr, function(el, i) { return ((el!=='') && (i == $.inArray(el, locArr))); }).join(', ');
            var datebit = ((locbit!=='')?' - ':'')+dets.date_created.replace(/( |^)[0-9]{2}:[0-9]{2}:[0-9]{2}/g, '');
            var captionbit = locbit+datebit;
            if (dets.previewCaption!=='') captionbit += ((captionbit!=='')?' - ':'')+dets.previewCaption;
            html += '<hr /><div class="cpt">'+captionbit+'</div>';
        }
        // credit
        if (dets.credit!=='') {
            html += '<span class="lblCredit"><label>'+lang.assetdata.lbl_Credit+':</label> '+dets.credit+'</span>';
        }
        return init+html;
    },

    /**
     * generate html for a thumbnail preview
     *
     * @param  integer        id of asset we are generating preview for
     * @param  object        object with details of asset (probably an asset object)
     * @param  bool            display a caption for the asset?
     * @param  string        id of thumbnail to preview e.g. for $('groupassetthumb_2287'), will pass string 'group' as thumbimgPrefix
     * @return  string        html
     */
    _thumbPreviewHTML:function(id, dets, noCaption, thumbimgPrefix) {
        if (!dets) return lang.assetdata.msg_NoPreviewAvail;
        var thumbimg = $('#'+thumbimgPrefix+'assetthumb_'+id);
        var dims = {width:thumbimg.attr('width'), height:thumbimg.attr('height')};
        var width = dims.width;
        var height = dims.height;
        var html= '<div style="width:'+width+'px;">';
        html += '<img width="'+width+'" height="'+height+'" src="'+thumbimg.attr('src')+'" />';
        html += '<img class="noSpinner" style="margin-left:-' + width + 'px" width="'+width+'" height="'+height+'" src="media/image?src=blank_image.gif" />';
        ////// if ((dets.previewCaption!=='') && !noCaption) html += '<br /><span>'+dets.previewCaption+'</span>';
        html += assetPreview._captionHTML(dets, noCaption, '<br />');
        html += '</div>';
        return html;
    },
    
    /**
     * generate html for an image preview
     *
     * @param  integer        id of asset we are generating preview for
     * @param  object        object with details of asset (probably an asset object)
     * @param  bool            display a caption for the asset?
     * @return  string        html
     */
    _imagePreviewHTML:function(id, dets, noCaption, thumbimgPrefix) {
        if (!dets) return lang.assetdata.msg_NoPreviewAvail;
        //var thumbimg = $('#result_'+id+' .imgs img').get(0);
        var thumbimg = $('#'+thumbimgPrefix+'assetthumb_'+id);
        var dims = dets.hvPrevDimensions;
        var width = dims ? dims.width : 300;
        var height = dims ? dims.height : 100;
        var html= '<div style="width:'+width+'px;">';
        if (thumbimg.length) {
            html += '<img width="'+width+'" height="'+height+'" src="'+thumbimg.attr('src')+'" />';
            html += '<img style="margin-left:-' + width + 'px" width="'+width+'" height="'+height+'" src="'+dets.hvPreviewURL+'" />';
        } else {
            html += '<img width="'+width+'" height="'+height+'" src="'+dets.hvPreviewURL+'" />';
        }
        html += assetPreview._captionHTML(dets, noCaption, '<br />');
        ////// if ((dets.previewCaption!=='') && !noCaption) html += '<br /><span>'+dets.previewCaption+'</span>';
        html += '</div>';
        return html;
    },
    
    /**
     * generate html + callback func for a video preview
     *
     * @param  integer        id of asset we are generating preview for
     * @param  object        object with details of asset (probably an asset object)
     * @param  bool            display a caption for the asset?
     * @param  bool            autoplay preview?
     * @return  object        object containing html and callback function
     */
    _videoPreviewHTML:function(id, dets, noCaption, autoplay, isPreview) {
        if (!dets) return {html:lang.assetdata.msg_NoPreviewAvail, callback:function(){}};
        
        var dims = dets.hvPrevDimensions;
        var width = dims ? dims.width : 300;
        var height = dims ? dims.height : 100;

        var html = '<div style="width:'+width+'px;"><div class="vwait" id="vidpreview_' + id + '" style="width:'+width+'px; height:'+(height + 2)+'px;"><video id="html5video" style="width:'+width+'px; height:'+height+'px" '+(autoplay?'autoplay':'')+' >';
        html += '<source src="'+dets.hvPreviewURL+'" type="video/mp4">';
        html += 'Your browser does not support HTML5 video.</video></div>';
        html += assetPreview._captionHTML(dets, noCaption);
        html += '</div>';

        var cb = function() {
        };
        
        return {'html':html, callback:cb};
    },
    
    
    /**
     * generate html + callback func for an audio preview
     *
     * @param  integer        id of asset we are generating preview for
     * @param  object        object with details of asset (probably an asset object)
     * @param  bool            display a caption for the asset?
     * @param  bool            autoplay preview?
     * @return  object        object containing html and callback function
     */
    _audioPreviewHTML:function(id, dets, noCaption, autoplay) {
            if (!dets) return {html:lang.assetdata.msg_NoPreviewAvail, callback:function(){}};

            var dims = dets.hvPrevDimensions;
            var width = 168;
            var height = 42;

            var html = '<div style="width:'+width+'px;"><div class="vwait" id="audiopreview_' + id + '" style="width:'+width+'px; height:'+(height + 2)+'px;"><audio id="html5audio" controls controlsList="nodownload" style="width:'+width+'px; height:'+height+'px" '+(autoplay?'autoplay':'')+' >';
            html += '<source src="'+dets.hvPreviewURL+'" type="audio/mp3">';
            ////// if ((dets.previewCaption!=='') && !noCaption) html += '<span>'+dets.previewCaption+'</span>';
            html += 'Your browser does not support HTML5 video.</video></div>';
            html += assetPreview._captionHTML(dets, noCaption);
            html += '</div>';

            var cb = function() {};

            return {'html':html, callback:cb};
    }
    

};





/*********************
Including file: datepicker.js
*********************/
/*
        DatePicker v4.4 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency-decoder in any derivative work - thanks.
        
        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/
var datePickerController;

(function() {

// Detect the browser language
datePicker.languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
datePicker.languageinfo = datePicker.languageinfo ? datePicker.languageinfo.toLowerCase().replace(/-[a-z]+$/, "") : 'en';

// Load the appropriate language file
var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script');
// var loc = scriptFiles[scriptFiles.length - 1].src.substr(0, scriptFiles[scriptFiles.length - 1].src.lastIndexOf("/")) + "/lang/" + datePicker.languageinfo + ".js";
var loc = APP.baseURL + 'media?js=datepicker/lang/' + datePicker.languageinfo + '.js';

var script  = document.createElement('script');
script.type = "text/javascript";
script.src  = loc;
script.setAttribute("charset", "utf-8");
/*@cc_on
/*@if(@_win32)
        var bases = document.getElementsByTagName('base');
        if (bases.length && bases[0].childNodes.length) {
                bases[0].appendChild(script);
        } else {
                document.getElementsByTagName('head')[0].appendChild(script);
        };
@else @*/
document.getElementsByTagName('head')[0].appendChild(script);
/*@end
@*/
script  = null;

// Defaults should the locale file not load
datePicker.months       = ["January","February","March","April","May","June","July","August","September","October","November","December"];
datePicker.fullDay      = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
datePicker.titles       = ["Previous month","Next month","Previous year","Next year", "Today", "Show Calendar"];

datePicker.getDaysPerMonth = function(nMonth, nYear) {
        nMonth = (nMonth + 12) % 12;
        return (((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) ? 29: [31,28,31,30,31,30,31,31,30,31,30,31][nMonth];
};

function datePicker(options) {

        this.defaults          = {};
        for(opt in options) { this[opt] = this.defaults[opt] = options[opt]; };
        
        this.date              = new Date();
        this.yearinc           = 1;
        this.timer             = null;
        this.pause             = 1000;
        this.timerSet          = false;
        this.fadeTimer         = null;
        this.interval          = new Date();
        this.firstDayOfWeek    = this.defaults.firstDayOfWeek = this.dayInc = this.monthInc = this.yearInc = this.opacity = this.opacityTo = 0;
        this.dateSet           = null;
        this.visible           = false;
        this.disabledDates     = [];
        this.enabledDates      = [];
        this.nbsp              = String.fromCharCode( 160 );
        var o = this;

        o.events = {
                onblur:function(e) {
                        o.removeKeyboardEvents();
                },
                onfocus:function(e) {
                        o.addKeyboardEvents();
                },
                onkeydown: function (e) {
                        o.stopTimer();
                        if(!o.visible) return false;

                        if(e == null) e = document.parentWindow.event;
                        var kc = e.keyCode ? e.keyCode : e.charCode;

                        if( kc == 13 ) {
                                // close (return)
                                var td = document.getElementById(o.id + "-date-picker-hover");
                                if(!td || td.className.search(/out-of-range|day-disabled/) != -1) return o.killEvent(e);
                                o.returnFormattedDate();
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 27) {
                                // close (esc)
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 32 || kc == 0) {
                                // today (space)
                                o.date =  new Date();
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        // Internet Explorer fires the keydown event faster than the JavaScript engine can
                        // update the interface. The following attempts to fix this.
                        /*@cc_on
                        @if(@_win32)
                                if(new Date().getTime() - o.interval.getTime() < 100) return o.killEvent(e);
                                o.interval = new Date();
                        @end
                        @*/

                        if ((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) {
                                if (kc > 96) kc -= (96-48);
                                kc -= 49;
                                o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7;
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        if ( kc < 37 || kc > 40 ) return true;

                        var d = new Date( o.date ).valueOf();

                        if ( kc == 37 ) {
                                // ctrl + left = previous month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() - 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 1 );
                                };
                        } else if ( kc == 39 ) {
                                // ctrl + right = next month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() + 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 1 );
                                };
                        } else if ( kc == 38 ) {
                                // ctrl + up = next year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() + 1)) );
                                        d.setFullYear( d.getFullYear() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 7 );
                                };
                        } else if ( kc == 40 ) {
                                // ctrl + down = prev year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() - 1)) );
                                        d.setFullYear( d.getFullYear() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 7 );
                                };
                        };

                        var tmpDate = new Date(d);

                        if(o.outOfRange(tmpDate)) return o.killEvent(e);
                        
                        var cacheDate = new Date(o.date);
                        o.date = tmpDate;

                        if(cacheDate.getFullYear() != o.date.getFullYear() || cacheDate.getMonth() != o.date.getMonth()) o.updateTable();
                        else {
                                o.disableTodayButton();
                                var tds = o.table.getElementsByTagName('td');
                                var txt;
                                var start = o.date.getDate() - 6;
                                if(start < 0) start = 0;

                                for(var i = start, td; td = tds[i]; i++) {
                                        txt = Number(td.firstChild.nodeValue);
                                        if(isNaN(txt) || txt != o.date.getDate()) continue;
                                        o.removeHighlight();
                                        td.id = o.id + "-date-picker-hover";
                                        td.className = td.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                                };
                        };
                        return o.killEvent(e);
                },
                gotoToday: function(e) {
                        o.date = new Date();
                        o.updateTable();
                        return o.killEvent(e);
                },
                onmousedown: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        var found = false;
                        while(el.parentNode) {
                                if(el.id && (el.id == "fd-"+o.id || el.id == "fd-but-"+o.id)) {
                                        found = true;
                                        break;
                                };
                                try {
                                        el = el.parentNode;
                                } catch(err) {
                                        break;
                                };
                        };
                        if(found) return true;
                        o.stopTimer();
                        datePickerController.hideAll();
                },
                onmouseover: function(e) {
                        o.stopTimer();
                        var txt = this.firstChild.nodeValue;
                        if(this.className == "out-of-range" || txt.search(/^[\d]+$/) == -1) return;
                        
                        o.removeHighlight();
                        
                        this.id = o.id+"-date-picker-hover";
                        this.className = this.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                        
                        o.date.setDate(this.firstChild.nodeValue);
                        o.disableTodayButton();
                },
                onclick: function(e) {
                        if(o.opacity != o.opacityTo || this.className.search(/out-of-range|day-disabled/) != -1) return false;
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;
                        while ( el.nodeType != 1 ) el = el.parentNode;
                        var d = new Date( o.date );
                        var txt = el.firstChild.data;
                        if(txt.search(/^[\d]+$/) == -1) return;
                        var n = Number( txt );
                        if(isNaN(n)) { return true; };
                        d.setDate( n );
                        o.date = d;
                        o.returnFormattedDate();
                        if(!o.staticPos) o.hide();
                        o.stopTimer();
                        return o.killEvent(e);
                },
                incDec: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        if(el && el.className && el.className.search('fd-disabled') != -1) { return false; }
                        datePickerController.addEvent(document, "mouseup", o.events.clearTimer);
                        o.timerInc      = 800;
                        o.dayInc        = arguments[1];
                        o.yearInc       = arguments[2];
                        o.monthInc      = arguments[3];
                        o.timerSet      = true;

                        o.updateTable();
                        return true;
                },
                clearTimer: function(e) {
                        o.stopTimer();
                        o.timerInc      = 1000;
                        o.yearInc       = 0;
                        o.monthInc      = 0;
                        o.dayInc        = 0;
                        datePickerController.removeEvent(document, "mouseup", o.events.clearTimer);
                }
        };
        o.stopTimer = function() {
                o.timerSet = false;
                window.clearTimeout(o.timer);
        };
        o.removeHighlight = function() {
                if(document.getElementById(o.id+"-date-picker-hover")) {
                        document.getElementById(o.id+"-date-picker-hover").className = document.getElementById(o.id+"-date-picker-hover").className.replace("date-picker-hover", "");
                        document.getElementById(o.id+"-date-picker-hover").id = "";
                };
        };
        o.reset = function() {
                for(def in o.defaults) { o[def] = o.defaults[def]; };
        };
        o.setOpacity = function(op) {
                o.div.style.opacity = op/100;
                o.div.style.filter = 'alpha(opacity=' + op + ')';
                o.opacity = op;
        };
        o.fade = function() {
                window.clearTimeout(o.fadeTimer);
                o.fadeTimer = null;
                delete(o.fadeTimer);
                
                var diff = Math.round(o.opacity + ((o.opacityTo - o.opacity) / 4));

                o.setOpacity(diff);

                if(Math.abs(o.opacityTo - diff) > 3 && !o.noTransparency) {
                        o.fadeTimer = window.setTimeout(o.fade, 50);
                } else {
                        o.setOpacity(o.opacityTo);
                        if(o.opacityTo == 0) {
                                o.div.style.display = "none";
                                o.visible = false;
                        } else {
                                o.visible = true;
                        };
                };
        };
        o.killEvent = function(e) {
                e = e || document.parentWindow.event;
                
                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on
                @if(@_win32)
                e.cancelBubble = true;
                e.returnValue = false;
                @end
                @*/
                return false;
        };
        o.getElem = function() {
                return document.getElementById(o.id.replace(/^fd-/, '')) || false;
        };
        o.setRangeLow = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.low = o.defaults.low = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setRangeHigh = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.high = o.defaults.high = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDays = function(dayArray) {
                o.disableDays = o.defaults.disableDays = dayArray;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01])$/) != -1) fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = fin;
                        o.enabledDates = [];
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.setEnabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01]|\*\*)$/) != -1 && dateArray[i] != "********") fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = [];
                        o.enabledDates = fin;
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.getDisabledDates = function(y, m) {
                if(o.enabledDates.length) return o.getEnabledDates(y, m);
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                for(var i = o.disabledDates.length; i-- ;) {
                        var tmp = o.disabledDates[i].replace("****", y).replace("**", m);
                        if(tmp < Number(String(y)+m+"01") || tmp > Number(y+String(m)+d)) continue;
                        obj[tmp] = 1;
                };
                return obj;
        };
        o.getEnabledDates = function(y, m) {
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                var day,tmp,de,me,ye,disabled;
                for(var dd = 1; dd <= d; dd++) {
                        day = dd < 10 ? "0" + String(dd) : dd;
                        disabled = true;
                        for(var i = o.enabledDates.length; i-- ;) {
                                tmp = o.enabledDates[i];
                                ye  = String(o.enabledDates[i]).substr(0,4);
                                me  = String(o.enabledDates[i]).substr(4,2);
                                de  = String(o.enabledDates[i]).substr(6,2);

                                if(ye == y && me == m && de == day) {
                                        disabled = false;
                                        break;
                                }
                                
                                if(ye == "****" || me == "**" || de == "**") {
                                        if(ye == "****") tmp = tmp.replace(/^\*\*\*\*/, y);
                                        if(me == "**")   tmp = tmp = tmp.substr(0,4) + String(m) + tmp.substr(6,2);
                                        if(de == "**")   tmp = tmp.replace(/\*\*/, day);

                                        if(tmp == String(y + String(m) + day)) {
                                                disabled = false;
                                                break;
                                        };
                                };
                        };
                        if(disabled) obj[String(y + String(m) + day)] = 1;
                };
                return obj;
        };
        o.setFirstDayOfWeek = function(e) {
                if ( e == null ) e = document.parentWindow.event;
                var elem = e.target != null ? e.target : e.srcElement;
                if(elem.tagName.toLowerCase() != "th") {
                        while(elem.tagName.toLowerCase() != "th") elem = elem.parentNode;
                };
                var cnt = 0;
                while(elem.previousSibling) {
                        elem = elem.previousSibling;
                        if(elem.tagName.toLowerCase() == "th") cnt++;
                };
                o.firstDayOfWeek = (o.firstDayOfWeek + cnt) % 7;
                o.updateTableHeaders();
                return o.killEvent(e);
        };
        o.truePosition = function(element) {
                var pos = o.cumulativeOffset(element);
                if(window.opera) { return pos; }
                var iebody      = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
                var dsocleft    = document.all ? iebody.scrollLeft : window.pageXOffset;
                var dsoctop     = document.all ? iebody.scrollTop  : window.pageYOffset;
                var posReal     = o.realOffset(element);
                return [pos[0] - posReal[0] + dsocleft, pos[1] - posReal[1] + dsoctop];
        };
        o.realOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.scrollTop  || 0;
                        l += element.scrollLeft || 0;
                        element = element.parentNode;
                } while (element);
                return [l, t];
        };
        o.cumulativeOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.offsetTop  || 0;
                        l += element.offsetLeft || 0;
                        element = element.offsetParent;
                } while (element);
                return [l, t];
        };
        o.resize = function() {
                if(!o.created || !o.getElem()) return;
                
                o.div.style.visibility = "hidden";
                if(!o.staticPos) { o.div.style.left = o.div.style.top = "0px"; }
                o.div.style.display = "block";
                
                var osh = o.div.offsetHeight;
                var osw = o.div.offsetWidth;
                
                o.div.style.visibility = "visible";
                o.div.style.display = "none";
                
                if(!o.staticPos) {
                        var elem          = document.getElementById('fd-but-' + o.id);
                        var pos           = o.truePosition(elem);
                        var trueBody      = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
                        var scrollTop     = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollTop;
                        var scrollLeft    = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollLeft;

                        if(parseInt(trueBody.clientWidth+scrollLeft) < parseInt(osw+pos[0])) {
                                o.div.style.left = Math.abs(parseInt((trueBody.clientWidth+scrollLeft) - osw)) + "px";
                        } else {
                                o.div.style.left  = pos[0] + "px";
                        };

                        if(parseInt(trueBody.clientHeight+scrollTop) < parseInt(osh+pos[1]+elem.offsetHeight+2)) {
                                o.div.style.top   = Math.abs(parseInt(pos[1] - (osh + 2))) + "px";
                        } else {
                                o.div.style.top   = Math.abs(parseInt(pos[1] + elem.offsetHeight + 2)) + "px";
                        };
                };
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(o.staticPos) return;
                o.iePopUp.style.top    = o.div.style.top;
                o.iePopUp.style.left   = o.div.style.left;
                o.iePopUp.style.width  = osw + "px";
                o.iePopUp.style.height = (osh - 2) + "px";
                @end
                @*/
        };
        o.equaliseDates = function() {
                var clearDayFound = false;
                var tmpDate;
                for(var i = o.low; i <= o.high; i++) {
                        tmpDate = String(i);
                        if(!o.disableDays[new Date(tmpDate.substr(0,4), tmpDate.substr(6,2), tmpDate.substr(4,2)).getDay() - 1]) {
                                clearDayFound = true;
                                break;
                        };
                };
                if(!clearDayFound) o.disableDays = o.defaults.disableDays = [0,0,0,0,0,0,0];
        };
        o.outOfRange = function(tmpDate) {
                if(!o.low && !o.high) return false;

                var level = false;
                if(!tmpDate) {
                        level = true;
                        tmpDate = o.date;
                };
                
                var d  = (tmpDate.getDate() < 10) ? "0" + tmpDate.getDate() : tmpDate.getDate();
                var m  = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1;
                var y  = tmpDate.getFullYear();
                var dt = String(y)+String(m)+String(d);

                if(o.low && parseInt(dt) < parseInt(o.low)) {
                        if(!level) return true;
                        o.date = new Date(o.low.substr(0,4), o.low.substr(4,2)-1, o.low.substr(6,2), 5, 0, 0);
                        return false;
                };
                if(o.high && parseInt(dt) > parseInt(o.high)) {
                        if(!level) return true;
                        o.date = new Date( o.high.substr(0,4), o.high.substr(4,2)-1, o.high.substr(6,2), 5, 0, 0);
                };
                return false;
        };
        o.createButton = function() {
                if(o.staticPos) { return; };
                
                var but;
                
                if(!document.getElementById("fd-but-" + o.id)) {
                        var inp = o.getElem();
                        
                        but = document.createElement('a');
                        but.href = "#";

                        var span = document.createElement('span');
                        span.appendChild(document.createTextNode(String.fromCharCode( 160 )));

                        but.className = "date-picker-control";
                        but.title = (typeof(fdLocale) == "object" && options.locale && fdLocale.titles.length > 5) ? fdLocale.titles[5] : "";

                        but.id = "fd-but-" + o.id;
                        but.appendChild(span);

                        if(inp.nextSibling) {
                                inp.parentNode.insertBefore(but, inp.nextSibling);
                        } else {
                                inp.parentNode.appendChild(but);
                        };
                } else {
                        but = document.getElementById("fd-but-" + o.id);
                };

                but.onclick = but.onpress = function(e) {
                        e = e || window.event;
                        var inpId = this.id.replace('fd-but-','');
                        try { var dp = datePickerController.getDatePicker(inpId); } catch(err) { return false; };

                        if(e.type == "press") {
                                var kc = e.keyCode != null ? e.keyCode : e.charCode;
                                if(kc != 13) { return true; };
                                if(dp.visible) {
                                        hideAll();
                                        return false;
                                };
                        };

                        if(!dp.visible) {
                                datePickerController.hideAll(inpId);
                                dp.show();
                        } else {
                                datePickerController.hideAll();
                        };
                        return false;
                };
                but = null;
        },
        o.create = function() {
                
                function createTH(details) {
                        var th = document.createElement('th');
                        if(details.thClassName) th.className = details.thClassName;
                        if(details.colspan) {
                                /*@cc_on
                                /*@if (@_win32)
                                th.setAttribute('colSpan',details.colspan);
                                @else @*/
                                th.setAttribute('colspan',details.colspan);
                                /*@end
                                @*/
                        };
                        /*@cc_on
                        /*@if (@_win32)
                        th.unselectable = "on";
                        /*@end@*/
                        return th;
                };
                
                function createThAndButton(tr, obj) {
                        for(var i = 0, details; details = obj[i]; i++) {
                                var th = createTH(details);
                                tr.appendChild(th);
                                var but = document.createElement('span');
                                but.className = details.className;
                                but.id = o.id + details.id;
                                but.appendChild(document.createTextNode(details.text));
                                but.title = details.title || "";
                                if(details.onmousedown) but.onmousedown = details.onmousedown;
                                if(details.onclick)     but.onclick     = details.onclick;
                                if(details.onmouseout)  but.onmouseout  = details.onmouseout;
                                th.appendChild(but);
                        };
                };
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(!document.getElementById("iePopUpHack")) {
                                o.iePopUp = document.createElement('iframe');
                                o.iePopUp.src = "javascript:'<html></html>';";
                                o.iePopUp.setAttribute('className','iehack');
                                o.iePopUp.scrolling="no";
                                o.iePopUp.frameBorder="0";
                                o.iePopUp.name = o.iePopUp.id = "iePopUpHack";
                                document.body.appendChild(o.iePopUp);
                        } else {
                                o.iePopUp = document.getElementById("iePopUpHack");
                        };
                @end
                @*/
                
                if(typeof(fdLocale) == "object" && o.locale) {
                        datePicker.titles  = fdLocale.titles;
                        datePicker.months  = fdLocale.months;
                        datePicker.fullDay = fdLocale.fullDay;
                        // Optional parameters
                        if(fdLocale.dayAbbr) datePicker.dayAbbr = fdLocale.dayAbbr;
                        if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek;
                };
                
                o.div = document.createElement('div');
                o.div.style.zIndex = 9999;
                o.div.id = "fd-"+o.id;
                o.div.className = "datePicker";
                
                if(!o.staticPos) {
                        document.getElementsByTagName('body')[0].appendChild(o.div);
                } else {
                        elem = o.getElem();
                        if(!elem) {
                                o.div = null;
                                return;
                        };
                        o.div.className += " staticDP";
                        o.div.setAttribute("tabIndex", "0");
                        o.div.onfocus = o.events.onfocus;
                        o.div.onblur  = o.events.onblur;
                        elem.parentNode.insertBefore(o.div, elem.nextSibling);
                        if(o.hideInput && elem.type && elem.type == "text") elem.setAttribute("type", "hidden");
                };
                
                //var nbsp = String.fromCharCode( 160 );
                var tr, row, col, tableHead, tableBody;

                o.table = document.createElement('table');
                o.div.appendChild( o.table );
                
                tableHead = document.createElement('thead');
                o.table.appendChild( tableHead );
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                // Title Bar
                o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
                tr.appendChild( o.titleBar );
                tr = null;
                
                var span = document.createElement('span');
                span.className = "month-display";
                o.titleBar.appendChild(span);

                span = document.createElement('span');
                span.className = "year-display";
                o.titleBar.appendChild(span);

                span = null;
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                createThAndButton(tr, [{className:"prev-but", id:"-prev-year-but", text:"\u00AB", title:datePicker.titles[2], onmousedown:function(e) { o.events.incDec(e,0,-1,0); }, onmouseout:o.events.clearTimer },{className:"prev-but", id:"-prev-month-but", text:"\u2039", title:datePicker.titles[0], onmousedown:function(e) { o.events.incDec(e,0,0,-1); }, onmouseout:o.events.clearTimer },{colspan:3, className:"today-but", id:"-today-but", text:datePicker.titles.length > 4 ? datePicker.titles[4] : "Today", onclick:o.events.gotoToday},{className:"next-but", id:"-next-month-but", text:"\u203A", title:datePicker.titles[1], onmousedown:function(e) { o.events.incDec(e,0,0,1); }, onmouseout:o.events.clearTimer },{className:"next-but", id:"-next-year-but", text:"\u00BB", title:datePicker.titles[3], onmousedown:function(e) { o.events.incDec(e,0,1,0); }, onmouseout:o.events.clearTimer }]);

                tableBody = document.createElement('tbody');
                o.table.appendChild( tableBody );

                for(var rows = 0; rows < 7; rows++) {
                        row = document.createElement('tr');

                        if(rows != 0) tableBody.appendChild(row);
                        else          tableHead.appendChild(row);
                        
                        for(var cols = 0; cols < 7; cols++) {
                                col = (rows == 0) ? document.createElement('th') : document.createElement('td');

                                row.appendChild(col);
                                if(rows != 0) {
                                        col.appendChild(document.createTextNode(o.nbsp));
                                        col.onmouseover = o.events.onmouseover;
                                        col.onclick = o.events.onclick;
                                } else {
                                        col.className = "date-picker-day-header";
                                        col.scope = "col";
                                };
                                col = null;
                        };
                        row = null;
                };

                // Table headers
                var but;
                var ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                for ( var y = 0; y < 7; y++ ) {
                        if(y > 0) {
                                but = document.createElement("span");
                                but.className = "fd-day-header";
                                but.onclick = ths[y].onclick = o.setFirstDayOfWeek;
                                but.appendChild(document.createTextNode(o.nbsp));
                                ths[y].appendChild(but);
                                but = null;
                        } else {
                                ths[y].appendChild(document.createTextNode(o.nbsp));
                        };
                };
                
                o.ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                o.trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                
                o.updateTableHeaders();
                
                tableBody = tableHead = tr = createThAndButton = createTH = null;

                if(o.low && o.high && (o.high - o.low < 7)) { o.equaliseDates(); };
                
                o.created = true;
                
                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.addEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');
                                datePickerController.addEvent(mmN, "change", o.changeHandler);
                                datePickerController.addEvent(ddN, "change", o.changeHandler);
                        };
                        
                        o.show();
                } else {
                        o.createButton();
                        o.resize();
                        o.fade();
                };
        };
        o.changeHandler = function() {
                o.setDateFromInput();
                o.updateTable();
        };
        o.setDateFromInput = function() {
                function m2c(val) {
                        return String(val).length < 2 ? "00".substring(0, 2 - String(val).length) + String(val) : val;
                };

                o.dateSet = null;
                
                var elem = o.getElem();
                if(!elem) return;

                if(!o.splitDate) {
                        var date = datePickerController.dateFormat(elem.value, o.format.search(/m-d-y/i) != -1);
                } else {
                        var mmN = document.getElementById(o.id+'-mm');
                        var ddN = document.getElementById(o.id+'-dd');
                        var tm = parseInt(mmN.tagName.toLowerCase() == "input"  ? mmN.value  : mmN.options[mmN.selectedIndex].value, 10);
                        var td = parseInt(ddN.tagName.toLowerCase() == "input"  ? ddN.value  : ddN.options[ddN.selectedIndex].value, 10);
                        var ty = parseInt(elem.tagName.toLowerCase() == "input" ? elem.value : elem.options[elem.selectedIndex || 0].value, 10);
                        var date = datePickerController.dateFormat(tm + "/" + td + "/" + ty, true);
                };

                var badDate = false;
                if(!date) {
                        badDate = true;
                        date = String(new Date().getFullYear()) + m2c(new Date().getMonth()+1) + m2c(new Date().getDate());
                };

                var d,m,y;
                y = Number(date.substr(0, 4));
                m = Number(date.substr(4, 2)) - 1;
                d = Number(date.substr(6, 2));

                var dpm = datePicker.getDaysPerMonth(m, y);
                if(d > dpm) d = dpm;

                if(new Date(y, m, d) == 'Invalid Date' || new Date(y, m, d) == 'NaN') {
                        badDate = true;
                        o.date = new Date();
                        o.date.setHours(5);
                        return;
                };

                o.date = new Date(y, m, d);
                o.date.setHours(5);

                if(!badDate) o.dateSet = new Date(o.date);
                m2c = null;
        };
        o.setSelectIndex = function(elem, indx) {
                var len = elem.options.length;
                indx = Number(indx);
                for(var opt = 0; opt < len; opt++) {
                        if(elem.options[opt].value == indx) {
                                elem.selectedIndex = opt;
                                return;
                        };
                };
        },
        o.returnFormattedDate = function() {

                var elem = o.getElem();
                if(!elem) return;
                
                var d                   = (o.date.getDate() < 10) ? "0" + o.date.getDate() : o.date.getDate();
                var m                   = ((o.date.getMonth() + 1) < 10) ? "0" + (o.date.getMonth() + 1) : o.date.getMonth() + 1;
                var yyyy                = o.date.getFullYear();
                var disabledDates       = o.getDisabledDates(yyyy, m);
                var weekDay             = ( o.date.getDay() + 6 ) % 7;

                if(!(o.disableDays[weekDay] || String(yyyy)+m+d in disabledDates)) {

                        if(o.splitDate) {
                                var ddE = document.getElementById(o.id+"-dd");
                                var mmE = document.getElementById(o.id+"-mm");

                                if(ddE.tagName.toLowerCase() == "input") { ddE.value = d; }
                                else { o.setSelectIndex(ddE, d); /*ddE.selectedIndex = d - 1;*/ };
                                
                                if(mmE.tagName.toLowerCase() == "input") { mmE.value = m; }
                                else { o.setSelectIndex(mmE, m); /*mmE.selectedIndex = m - 1;*/ };
                                
                                if(elem.tagName.toLowerCase() == "input") elem.value = yyyy;
                                else {
                                        o.setSelectIndex(elem, yyyy); /*
                                        for(var opt = 0; opt < elem.options.length; opt++) {
                                                if(elem.options[opt].value == yyyy) {
                                                        elem.selectedIndex = opt;
                                                        break;
                                                };
                                        };
                                        */
                                };
                        } else {
                                elem.value = o.format.replace('y',yyyy).replace('m',m).replace('d',d).replace(/-/g,o.divider);
                        };
                        if(!elem.type || elem.type && elem.type != "hidden"){ elem.focus(); }
                        if(o.staticPos) {
                                o.dateSet = new Date( o.date );
                                o.updateTable();
                        };
                        
                        // Programmatically fire the onchange event
                        if(document.createEvent) {
                                var onchangeEvent = document.createEvent('HTMLEvents');
                                onchangeEvent.initEvent('change', true, false);
                                elem.dispatchEvent(onchangeEvent);
                        } else if(document.createEventObject) {
                                elem.fireEvent('onchange');
                        };
                };
        };
        o.disableTodayButton = function() {
                var today = new Date();
                document.getElementById(o.id + "-today-but").className = document.getElementById(o.id + "-today-but").className.replace("fd-disabled", "");
                if(o.outOfRange(today) || (o.date.getDate() == today.getDate() && o.date.getMonth() == today.getMonth() && o.date.getFullYear() == today.getFullYear())) {
                        document.getElementById(o.id + "-today-but").className += " fd-disabled";
                        document.getElementById(o.id + "-today-but").onclick = null;
                } else {
                        document.getElementById(o.id + "-today-but").onclick = o.events.gotoToday;
                };
        };
        o.updateTableHeaders = function() {
                var d, but;
                var ths = o.ths;
                for ( var y = 0; y < 7; y++ ) {
                        d = (o.firstDayOfWeek + y) % 7;
                        ths[y].title = datePicker.fullDay[d];

                        if(y > 0) {
                                but = ths[y].getElementsByTagName("span")[0];
                                but.removeChild(but.firstChild);
                                but.appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                                but.title = datePicker.fullDay[d];
                                but = null;
                        } else {
                                ths[y].removeChild(ths[y].firstChild);
                                ths[y].appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                        };
                };
                o.updateTable();
        };

        o.updateTable = function(noCallback) {

                if(o.timerSet) {
                        var d = new Date(o.date);
                        d.setDate( Math.min(d.getDate()+o.dayInc, datePicker.getDaysPerMonth(d.getMonth()+o.monthInc,d.getFullYear()+o.yearInc)) );
                        d.setMonth( d.getMonth() + o.monthInc );
                        d.setFullYear( d.getFullYear() + o.yearInc );
                        o.date = d;
                };
                
                if(!noCallback && "onupdate" in datePickerController && typeof(datePickerController.onupdate) == "function") datePickerController.onupdate(o);

                o.outOfRange();
                o.disableTodayButton();
                
                // Set the tmpDate to the second day of this month (to avoid daylight savings time madness on Windows)
                var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 2 );
                tmpDate.setHours(5);

                var tdm = tmpDate.getMonth();
                var tdy = tmpDate.getFullYear();

                // Do the disableDates for this year and month
                var disabledDates = o.getDisabledDates(o.date.getFullYear(), o.date.getMonth() + 1);

                var today = new Date();

                // Previous buttons out of range
                var b = document.getElementById(o.id + "-prev-year-but");
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy - 1), Number(tdm), datePicker.getDaysPerMonth(Number(tdm), tdy-1)))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == -1) o.stopTimer();
                };

                b = document.getElementById(o.id + "-prev-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, (Number(tdm) - 1), datePicker.getDaysPerMonth(Number(tdm)-1, tdy)))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == -1)  o.stopTimer();
                };

                // Next buttons out of range
                b= document.getElementById(o.id + "-next-year-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy + 1), Number(tdm), 1))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == 1)  o.stopTimer();
                };

                b = document.getElementById(o.id + "-next-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, Number(tdm) + 1, 1))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == 1)  o.stopTimer();
                };

                b = null;
                
                var cd = o.date.getDate();
                var cm = o.date.getMonth();
                var cy = o.date.getFullYear();
                
                // Title Bar
                var span = o.titleBar.getElementsByTagName("span");
                while(span[0].firstChild) span[0].removeChild(span[0].firstChild);
                while(span[1].firstChild) span[1].removeChild(span[1].firstChild);
                span[0].appendChild(document.createTextNode(datePicker.months[cm] + o.nbsp));
                span[1].appendChild(document.createTextNode(cy));

                tmpDate.setDate( 1 );
                        
                var dt, cName, td, tds, i;
                var weekDay = ( tmpDate.getDay() + 6 ) % 7;
                var firstColIndex = (( (weekDay - o.firstDayOfWeek) + 7 ) % 7) - 1;
                var dpm = datePicker.getDaysPerMonth(cm, cy);

                var todayD = today.getDate();
                var todayM = today.getMonth();
                var todayY = today.getFullYear();
                
                var c = "class";
                /*@cc_on
                @if(@_win32)
                c = "className";
                @end
                @*/

                var stub = String(tdy) + (String(tdm+1).length < 2 ? "0" + (tdm+1) : tdm+1);
                
                for(var row = 0; row < 6; row++) {

                        tds = o.trs[row].getElementsByTagName('td');

                        for(var col = 0; col < 7; col++) {
                        
                                td = tds[col];
                                td.removeChild(td.firstChild);

                                td.setAttribute("id", "");
                                td.setAttribute("title", "");

                                i = (row * 7) + col;
                        
                                if(i > firstColIndex && i <= (firstColIndex + dpm)) {
                                        dt = i - firstColIndex;

                                        tmpDate.setDate(dt);
                                        td.appendChild(document.createTextNode(dt));
                                        
                                        if(o.outOfRange(tmpDate)) {
                                                td.setAttribute(c, "out-of-range");
                                        } else {

                                                cName = [];
                                                weekDay = ( tmpDate.getDay() + 6 ) % 7;

                                                if(dt == todayD && tdm == todayM && tdy == todayY) {
                                                        cName.push("date-picker-today");
                                                };

                                                if(o.dateSet != null && o.dateSet.getDate() == dt && o.dateSet.getMonth() == tdm && o.dateSet.getFullYear() == tdy) {
                                                        cName.push("date-picker-selected-date");
                                                };
                                                
                                                if(o.disableDays[weekDay] || stub + String(dt < 10 ? "0" + dt : dt) in disabledDates) {
                                                        cName.push("day-disabled");
                                                } else if(o.highlightDays[weekDay]) {
                                                        cName.push("date-picker-highlight");
                                                };
                                                
                                                if(cd == dt) {
                                                        td.setAttribute("id", o.id + "-date-picker-hover");
                                                        cName.push("date-picker-hover");
                                                };
                                                
                                                cName.push("dm-" + dt + '-' + (tdm + 1) + " " + " dmy-" + dt + '-' + (tdm + 1) + '-' + tdy);
                                                td.setAttribute(c, cName.join(' '));
                                                td.setAttribute("title", datePicker.months[cm] + o.nbsp + dt + "," + o.nbsp + cy);
                                        };
                                } else {
                                        td.appendChild(document.createTextNode(o.nbsp));
                                        td.setAttribute(c, "date-picker-unused");
                                };
                        };
                };

                if(o.timerSet) {
                        o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8));
                        o.timer = window.setTimeout(o.updateTable, o.timerInc);
                };
        };
        o.addKeyboardEvents = function() {
                datePickerController.addEvent(document, "keypress", o.events.onkeydown);
                /*@cc_on
                @if(@_win32)
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                @end
                @*/
                if(window.devicePixelRatio) {
                        datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                        datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                };
        };
        o.removeKeyboardEvents =function() {
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.removeEvent(document, "keydown",  o.events.onkeydown);
        };
        o.show = function() {
                var elem = o.getElem();
                if(!elem || o.visible || elem.disabled) return;

                o.reset();
                o.setDateFromInput();
                o.updateTable();
                
                if(!o.staticPos) o.resize();
                
                datePickerController.addEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);

                if(!o.staticPos) { o.addKeyboardEvents(); };
                
                o.opacityTo = o.noTransparency ? 99 : 90;
                o.div.style.display = "block";
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(!o.staticPos) o.iePopUp.style.display = "block";
                @end
                @*/

                o.fade();
                o.visible = true;
        };
        o.hide = function() {
                if(!o.visible) return;
                o.stopTimer();
                if(o.staticPos) return;
                
                datePickerController.removeEvent(document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",  o.events.clearTimer);
                o.removeKeyboardEvents();
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp.style.display = "none";
                @end
                @*/
                
                o.opacityTo = 0;
                o.fade();
                o.visible = false;
                var elem = o.getElem();
                if(!elem.type || elem.type && elem.type != "hidden") { elem.focus(); };
        };
        o.destroy = function() {
                // Cleanup for Internet Explorer
                datePickerController.removeEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",   o.events.clearTimer);
                o.removeKeyboardEvents();

                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.removeEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');

                                datePickerController.removeEvent(mmN, "change", o.changeHandler);
                                datePickerController.removeEvent(ddN, "change", o.changeHandler);
                        };
                        o.div.onfocus = o.div.onblur = null;
                };
                
                var ths = o.table.getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        th.onmouseover = th.onmouseout = th.onmousedown = th.onclick = null;
                };
                
                var tds = o.table.getElementsByTagName("td");
                for(var i = 0, td; td = tds[i]; i++) {
                        td.onmouseover = td.onclick = null;
                };

                var butts = o.table.getElementsByTagName("span");
                for(var i = 0, butt; butt = butts[i]; i++) {
                        butt.onmousedown = butt.onclick = butt.onkeypress = null;
                };
                
                o.ths = o.trs = null;
                
                clearTimeout(o.fadeTimer);
                clearTimeout(o.timer);
                o.fadeTimer = o.timer = null;
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp = null;
                @end
                @*/
                
                if(!o.staticPos && document.getElementById(o.id.replace(/^fd-/, 'fd-but-'))) {
                        var butt = document.getElementById(o.id.replace(/^fd-/, 'fd-but-'));
                        butt.onclick = butt.onpress = null;
                };
                
                if(o.div && o.div.parentNode) {
                        o.div.parentNode.removeChild(o.div);
                };
                
                o.titleBar = o.table = o.div = null;
                o = null;
        };
        o.create();
};

datePickerController = function() {
        var datePickers = {};
        var uniqueId    = 0;
        
        var addEvent = function(obj, type, fn) {
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        };
        var removeEvent = function(obj, type, fn) {
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        };
        var hideAll = function(exception) {
                var dp;
                for(dp in datePickers) {
                        if(!datePickers[dp].created || datePickers[dp].staticPos) continue;
                        if(exception && exception == datePickers[dp].id) { continue; };
                        if(document.getElementById(datePickers[dp].id))  { datePickers[dp].hide(); };
                };
        };
        var cleanUp = function() {
                var dp;
                for(dp in datePickers) {
                        if(!document.getElementById(datePickers[dp].id)) {
                                if(!datePickers[dp].created) continue;
                                datePickers[dp].destroy();
                                datePickers[dp] = null;
                                delete datePickers[dp];
                        };
                };
        };
        var destroy = function() {
                for(dp in datePickers) {
                        if(!datePickers[dp].created) continue;
                        datePickers[dp].destroy();
                        datePickers[dp] = null;
                        delete datePickers[dp];
                };
                datePickers = null;
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(document.getElementById("iePopUpHack")) {
                                document.body.removeChild(document.getElementById("iePopUpHack"));
                        };
                @end
                @*/
                datePicker.script = null;
                removeEvent(window, 'load', datePickerController.create);
                removeEvent(window, 'unload', datePickerController.destroy);
        };
        var dateFormat = function(dateIn, favourMDY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/,    d:5, m:3, y:1 }   // ymd
                        ];

                var start;
                var cnt = 0;
                while(cnt < 3) {
                        start = (cnt + (favourMDY ? 4 : 3)) % 3;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + m;
                                if(d.length == 1) d = "0" + d;
                                if(y.length != 4) y = (parseInt(y) < 50) ? '20' + y : '19' + y;
                                return String(y)+m+d;
                        };
                        cnt++;
                };
                return 0;
        };
        var joinNodeLists = function() {
                if(!arguments.length) { return []; }
                var nodeList = [];
                for (var i = 0; i < arguments.length; i++) {
                        for (var j = 0, item; item = arguments[i][j]; j++) {
                                nodeList[nodeList.length] = item;
                        };
                };
                return nodeList;
        };
        var addDatePicker = function(inpId, options) {
                /*if(!(inpId in datePickers)) {
                        datePickers[inpId] = new datePicker(options);
                };*/
                if (inpId in datePickers) { // For IE7
                    datePickers[inpId] = null;
                    delete datePickers[inpId];
                }
                datePickers[inpId] = new datePicker(options);
        };
        var getDatePicker = function(inpId) {
                if(!(inpId in datePickers)) { throw "No datePicker has been created for the form element with an id of '" + inpId.toString() + "'"; };
                return datePickers[inpId];
        };
        var grepRangeLimits = function(sel) {
                var range = [];
                for(var i = 0; i < sel.options.length; i++) {
                        if(sel.options[i].value.search(/^\d\d\d\d$/) == -1) { continue; };
                        if(!range[0] || Number(sel.options[i].value) < range[0]) { range[0] = Number(sel.options[i].value); };
                        if(!range[1] || Number(sel.options[i].value) > range[1]) { range[1] = Number(sel.options[i].value); };
                };
                return range;
        };
        var create = function(inp) {
                if(!(typeof document.createElement != "undefined" && typeof document.documentElement != "undefined" && typeof document.documentElement.offsetWidth == "number")) return;

                var inputs  = (inp && inp.tagName) ? [inp] : joinNodeLists(document.getElementsByTagName('input'), document.getElementsByTagName('select'));
                var regExp1 = /disable-days-([1-7]){1,6}/g;             // the days to disable
                var regExp2 = /no-transparency/g;                       // do not use transparency effects
                var regExp3 = /highlight-days-([1-7]){1,7}/g;           // the days to highlight in red
                var regExp4 = /range-low-(\d\d\d\d-\d\d-\d\d)/g;        // the lowest selectable date
                var regExp5 = /range-high-(\d\d\d\d-\d\d-\d\d)/g;       // the highest selectable date
                var regExp6 = /format-(d-m-y|m-d-y|y-m-d)/g;            // the input/output date format
                var regExp7 = /divider-(dot|slash|space|dash)/g;        // the character used to divide the date
                var regExp8 = /no-locale/g;                             // do not attempt to detect the browser language
                var regExp9 = /no-fade/g;                               // always show the datepicker
                var regExp10 = /hide-input/g;                           // hide the input
                
                for(var i=0, inp; inp = inputs[i]; i++) {
                        if(inp.className && (inp.className.search(regExp6) != -1 || inp.className.search(/split-date/) != -1) && ((inp.tagName.toLowerCase() == "input" && (inp.type == "text" || inp.type == "hidden")) || inp.tagName.toLowerCase() == "select")) {

                                if(inp.id && document.getElementById('fd-'+inp.id)) { continue; };
                                
                                if(!inp.id) { inp.id = "fdDatePicker-" + uniqueId++; };
                                
                                var options = {
                                        id:inp.id,
                                        low:"",
                                        high:"",
                                        divider:"/",
                                        format:"d-m-y",
                                        highlightDays:[0,0,0,0,0,1,1],
                                        disableDays:[0,0,0,0,0,0,0],
                                        locale:inp.className.search(regExp8) == -1,
                                        splitDate:0,
                                        noTransparency:inp.className.search(regExp2) != -1,
                                        staticPos:inp.className.search(regExp9) != -1,
                                        hideInput:inp.className.search(regExp10) != -1
                                };

                                if(!options.staticPos) {
                                        options.hideInput = false;
                                } else {
                                        options.noTransparency = true;
                                };
                                
                                // Split the date into three parts ?
                                if(inp.className.search(/split-date/) != -1) {
                                        if(document.getElementById(inp.id+'-dd') && document.getElementById(inp.id+'-mm') && document.getElementById(inp.id+'-dd').tagName.search(/input|select/i) != -1 && document.getElementById(inp.id+'-mm').tagName.search(/input|select/i) != -1) {
                                                options.splitDate = 1;
                                        };
                                };
                                
                                // Date format(variations of d-m-y)
                                if(inp.className.search(regExp6) != -1) {
                                        options.format = inp.className.match(regExp6)[0].replace('format-','');
                                };
                                
                                // What divider to use, a "/", "-", "." or " "
                                if(inp.className.search(regExp7) != -1) {
                                        var dividers = { dot:".", space:" ", dash:"-", slash:"/" };
                                        options.divider = (inp.className.search(regExp7) != -1 && inp.className.match(regExp7)[0].replace('divider-','') in dividers) ? dividers[inp.className.match(regExp7)[0].replace('divider-','')] : "/";
                                };

                                // The days to highlight
                                if(inp.className.search(regExp3) != -1) {
                                        var tmp = inp.className.match(regExp3)[0].replace(/highlight-days-/, '');
                                        options.highlightDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.highlightDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The days to disable
                                if(inp.className.search(regExp1) != -1) {
                                        var tmp = inp.className.match(regExp1)[0].replace(/disable-days-/, '');
                                        options.disableDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.disableDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The lower limit
                                if(inp.className.search(/range-low-today/i) != -1) {
                                        options.low = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp4) != -1) {
                                        options.low = datePickerController.dateFormat(inp.className.match(regExp4)[0].replace(/range-low-/, ''), false);
                                        if(!options.low) {
                                                options.low = '';
                                        };
                                };

                                // The higher limit
                                if(inp.className.search(/range-high-today/i) != -1 && inp.className.search(/range-low-today/i) == -1) {
                                        options.high = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp5) != -1) {
                                        options.high = datePickerController.dateFormat(inp.className.match(regExp5)[0].replace(/range-high-/, ''), false);
                                        if(!options.high) {
                                                options.high = '';
                                        };
                                };

                                // Always round lower & higher limits if a selectList involved
                                if(inp.tagName.search(/select/i) != -1) {
                                        var range = grepRangeLimits(inp);
                                        options.low  = options.low  ? range[0] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[0] + "/01/01");
                                        options.high = options.high ? range[1] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[1] + "/12/31");
                                };

                                addDatePicker(inp.id, options);
                        };
                };
        }
        
        return {
                addEvent:addEvent,
                removeEvent:removeEvent,
                create:create,
                destroy:destroy,
                cleanUp:cleanUp,
                addDatePicker:addDatePicker,
                getDatePicker:getDatePicker,
                dateFormat:dateFormat,
                datePickers:datePickers,
                hideAll:hideAll
        };
}();

})();

$(datePickerController.create);
//////datePickerController.addEvent(window, 'load', datePickerController.create);
datePickerController.addEvent(window, 'unload', datePickerController.destroy);


/*********************
Including file: lightbox.js
*********************/
/**
 * lightbox.js - js functions relating to lightbox functionality
 *
 * @package    lightbox
 * @author     Jon Randy
 * @copyright  (c) 2010 Lightrocket
 */

(function() {

lightbox = {

    selectedAssets:[], // array of selected asset ids
    isApplySelection:false, // will set to True when the user has started using any selection features
    assetList:false, // assets of selected lightbox
    defaultLbx:0,
    printResetTimer:false,
    assetFlags:false, // asset ids list of each flag
    allFlags:false, // all flags available in the system
    selectedFlag:0, // flag that is being displayed
    logoAlt : '',
    logoImg : '',

    /**
     * print contact sheet
     *
     * @return  void
     */
    printContactSheet:function(){        
        if (lightbox.printResetTimer) clearTimeout(lightbox.printResetTimer);
        $('link[media=print]').attr('disabled', true);
        $('[title=contactsheet]').attr('disabled', false);
        var ct = $('#lightbox_body').html();
        var printData = lightbox._contactSheetHTML(ct);
        var title = '<title>' + 'Lightbox - ContactSheet' + '</title>';
        window.frames["print_frame"].document.head.innerHTML = title;
        window.frames["print_frame"].document.body.innerHTML = printData;
        window.frames["print_frame"].window.focus();
        if (preview.checkBrowserIE()) window.frames["print_frame"].document.execCommand('print', false, null);
        else window.frames["print_frame"].window.print();
        lightbox.printResetTimer = setTimeout(lightbox._printContactSheet, 2*60*1000);
    },
    
    _printContactSheet:function() {
        $('link[media=print]').attr('disabled', false);
        $('[title=contactsheet]').attr('disabled', true);
        lightbox.printResetTimer = false;
    },

    _contactSheetHTML:function(html){
        var style  = '<style type="text/css" media="print,screen">';
            style += '#printLogo{width:100%;text-align:center; margin-bottom:25px;}';
            style += '#printLogo img {max-width:200px;}';
            style += 'ul#asset {list-style: none;}';
            style += 'li.asset-item{ margin-right:20px; margin-bottom:20px; display: inline-block; width:200px!important;}';
            style += 'img[id^="lightboxAsset_"]{width:100%!important; height:auto!important;}';
            style += 'img[id^="lightboxAsset_"]+img{display:none;}';
            style += '.lbxAsset_filename{width:100%!important; white-space: nowrap; overflow:hidden; text-overflow: ellipsis;}';
            style += 'ul#asset > li > div > div > span > span {margin:0!important;}';
            style += '.btnRemove, .btnNoDownload , input[id^="selection_"] ,input[id^="selection_"] + label {display:none;}';
            style += '</style>';
        var start = '<div id="contactSheet">';
        var end = '</div>';
        var logo = '<div id="printLogo"><img src="' + lightbox.logoImg + '"></div>';
        var printHTML = start + logo + html + end;
        return style + printHTML;
    },
    
    /**
     * create a new lightbox
     *
     * @param  string        proposed name for new lightbox
     * @return  void
     */
    createNewLbx:function(newName){
        var url = APP.baseURL + 'lightbox/newlightbox';
        var params = {name:newName};
        $.post(url, params,    function(lightbox_id) {
            if (lightbox_id !== '') {
                // Add the new lightbox to the end of lightbox dropdown
                $("#lightbox_id").append("<option value='"+lightbox_id+"' hval='"+newName+"'>"+newName+"</option>");
                $("#moveto_lightbox_id > option").removeAttr('disabled');
                $("#moveto_lightbox_id").append("<option value='"+lightbox_id+"' disabled=\"disabled\">"+newName+"</option>");
                $("#lightbox_id").val(lightbox_id);
                lightbox.isApplySelection = false;
                lightbox._loadAssets();
//                lightbox._showHideSelectionButtons();
                $('#lightbox_body').html('');                
            }
            else {
                alert(lang.lightbox.msg_ErrLbxNameExists.format(newName));
            }
        } );
    },

    /**
     * Make the assets in lightbox sortable
     */
    _activateSortable() {
        if(lightbox.allowReorder) {
            $("#lightbox_body > ul#asset").sortable({
                stop: function( event, ui) {   
                    // Get asset positions    
                    let assets = [];
                    $("#lightbox_body > ul#asset > li").each(function(index, value){
                        let assetId = parseInt($(value).prop('id').replace('asset_li_', ''));
                        assets.push(assetId);
                    });
                    let lightboxId = parseInt($('#lightbox_id').val());
    
                    let assetData =  {lightbox_id: lightboxId, assets: assets};
                    let url = APP.baseURL + 'lightbox/updateorders';
    
                    $.post(url, assetData, function(data, status, xhr){
                        lightbox._updateSelectedAssets();
                    });
                }
            });
        }        
    },

    /**
     * rename lightbox
     *
     * @param  string        proposed new name for current lightbox
     * @return  void
     */
    renameLbx:function(newName){
        var assetCountText;
        var url = APP.baseURL + 'lightbox/rename';
        var params = {id:$('#lightbox_id').val(),name:newName};
        $.post(url, params,    function(result) {
            if (result == '1') {
                var assetCount = lightbox.assetList.count;
                var displayLbxName = lightbox._getDisplayLbxName(assetCount, newName);
                $('#lightbox_id :selected').text(displayLbxName).attr('hval', newName);
                $('#moveto_lightbox_id :disabled').text(newName);
                if (assetCount != 1) {
                    assetCountText = lang.common.plural_Asset;
                }
                else {
                    assetCountText = lang.common.noun_Asset;
                }
                $('#contactSheet_lbxTitle').text(newName); // change Lightbox name for contact sheet
            }
            else {
                alert(lang.lightbox.msg_ErrLbxNameExists.format(newName));
            }
        } );
    },

    /**
     * update array of selected assets
     *
     * @return  void
     */
    _updateSelectedAssets:function(){
        lightbox.selectedAssets = [];
        $("label[id^='lbl_selection_']").each(function() {
            $checkbox_asset = $(this).attr('for');
            if ($(this).hasClass('checked')) {
                lightbox.selectedAssets.push($('#'+$checkbox_asset).val());
            }
        });
    },

    /**
     * Show/Hide asset selection buttons
     *
     * @return  void
     */
    _showHideSelectionButtons:function(){
//        if (!lightbox.isApplySelection || $('#moveAssetsLbx').hasClass('active')) {
        if ($('#moveAssetsLbx').hasClass('active')) {
            $('#selectLightboxOpt').addClass('hideMe');
        }
        else {
            $('#selectLightboxOpt').removeClass('hideMe');
        }
    },

    /**
     * Add asset(from search result) into current active lightbox
     *
     * @return  void
     */
    addAssetFromSearch:function(asset_id) {
        if ($('#lightbox_id :selected').text() !== '') {
            lightbox.addAssetLbx(asset_id);            
        }
        else {
            alert(lang.lightbox.lbl_MustLoginToUseLbx);
        }
    },

    /**
     * Add asset(s) into current active lightbox
     *
     * @param  mixed    single asset id to add or array of asset ids
     * @return  void
     */
    addAssetLbx:function(new_asset_ids){
        lightbox._hideShareLbx();
        if (!$.isArray(new_asset_ids)) { new_asset_ids = [new_asset_ids]; }

        // switch to lightbox tab
        searchSideBar._handleTabClick('lightbox', false);

        var numOld = lightbox.assetList.count;
        var scrollPos = $('#lightbox_body').scrollTop();

        var url = APP.baseURL + 'lightbox/addassets';
        var pos = null, params, numNew;
        if (pos !== null) {
            params = {lightbox_id:$('#lightbox_id').val(),asset_ids:new_asset_ids,pos:pos};
            numNew = lightbox.assetList.addAssets(new_asset_ids,searchResult,pos);
        }
        else {
            params = {lightbox_id:$('#lightbox_id').val(),asset_ids:new_asset_ids};
            numNew = lightbox.assetList.addAssets(new_asset_ids,searchResult);
        }
        $.post(url, params, function(flags){
            if (numNew > numOld) {
                lightbox.assetList.count = numNew;
                lightbox._updateNumAssetsFlags(flags);
                lightbox._updateAssetCount();
                lightbox._handleClick();
                lightbox._activateSortable();
            }
        }, "json");

        // refresh all the html of the assets list
        $('#lightbox_body').html(lightbox.assetList.getHTML());
        linkRel._setup();
        if (pos === null) {
            scrollPos = $('#lightbox_body').attr('scrollHeight');
        }

        // update asset count text
        var this_value;
        $('#lightbox_body input:checkbox').each(function() {
            this_value = $(this).val();
            if ($.inArray(this_value, lightbox.selectedAssets) == -1) {
                if ($.inArray(parseInt(this_value, 10), new_asset_ids) !== -1) { // newly added asset
                    $('#lbl_selection_'+this_value).removeClass('unchecked');
                    $('#lbl_selection_'+this_value).addClass('checked');
                    $('#lbl_selection_'+this_value).attr('title', lang.lightbox.alt_SelectedIndicator);
                    lightbox.selectedAssets.push(this_value);
                }
                else {
                    $('#lbl_selection_'+this_value).removeClass('checked');
                    $('#lbl_selection_'+this_value).addClass('unchecked');
                    $('#lbl_selection_'+this_value).attr('title', lang.lightbox.alt_NotselectedIndicator);
                }
            }
        });

        $('#lightbox_body').attr({ scrollTop: scrollPos });
    },

    /**
     * update the amount of assets in flag filters
     *
     * @param   array of assets with flag id as indexes
     * @return  void
     */
    _updateNumAssetsFlags:function(flags){
        var flagCount = false;
        $.each(flags, function(flag_id, assets){
            flagCount = $('label#flagCount_'+flag_id).text();
            flagCount = (flagCount !== '') ? parseInt(flagCount, 10) + assets.length : assets.length;
            $('label#flagCount_'+flag_id).text(flagCount);
            if (flagCount > 0) $('#li_flag_'+flag_id).css('display', '');
            if (flag_id == lightbox.selectedFlag) {
                (flagCount > 0) ? $('span#selected_flagCount').text(flagCount) : $('span#selected_flag').text('');
            }
            // update assets in each flag
            $.each(lightbox.assetFlags, function(this_flag_id, this_assets){
                if (flag_id == this_flag_id) {
                    $.each(assets, function(k,v){
                        if ($.inArray(v, this_assets)<0) this_assets.push(v);//$.merge(this_assets, assets);
                    });
                    return false;
                }
            });
        });
        if (flagCount === false) { $('span#selected_flag').text(''); } // no flags in the system
        lightbox._clearSelectedFlag();
        lightbox._setVisibleFlags();
        lightbox._resizeFlagFilter();
    },

    /**
     * disable current selected lightbox in 'Move selection to' dropdown
     *
     * @return  void
     */
    _disableSelectedLightbox:function(){
        var lightboxes_list = $('option', $('#moveto_lightbox_id'));
        lightboxes_list.each(function() {
            $(this).removeAttr('disabled');
        });
        $("#moveto_lightbox_id option[value='"+$('#lightbox_id :selected').val()+"']").attr('disabled','disabled');
    },

    /**
     * update assets count text (eg. 3 of 25 assets selected)
     *
     * @return  void
     */
    _updateAssetCount:function(){
        if(lightbox.assetList.deferredAllResId){
            var url = APP.baseURL + 'backgroundresult/waitfor/'+lightbox.assetList.deferredAllResId;
            var result = $.ajax({
                type: "GET",
                url: url,
                data: {'return_type':"JSON",'js':'{results}'},
                async: true,
                success:lightbox.handleDeferredCount,
                dataType: 'json'
            });
        }
        else{
            $('span#lbxLoading').hide();
            var assetCount = lightbox.assetList.count, assetCountText;
            if (assetCount != 1) {
                assetCountText = lang.common.plural_Asset;
            }
            else {
                assetCountText = lang.common.noun_Asset;
            }
            // set Lightbox title
            $('#contactSheet_lbxTitle').text($('#lightbox_id :selected').attr('hval'));
            if (lightbox.selectedFlag != 0) {
                $('#contactSheet_numAssets').text($('a#flag_'+lightbox.selectedFlag).text());
            }
            else {
                $('#contactSheet_numAssets').text(assetCount+' '+assetCountText);
            }
            if (lightbox.isApplySelection) {
                assetCountText = lang.lightbox.lbl_AssetCounts.format([lightbox.selectedAssets.length,assetCount,assetCountText]);
            }
            else {
                assetCountText = assetCount+' '+assetCountText;
            }
            $('#num_assets').text(assetCountText);
            var displayLbxName = $('#lightbox_id :selected').attr('hval');
            displayLbxName = lightbox._getDisplayLbxName(assetCount, displayLbxName);
            $('#lightbox_id :selected').text(displayLbxName);
            lightbox._resizeFlagFilter();
        }
    },

    handleDeferredCount:function(data){
        var c = data.length;
        lightbox.assetList.count = c;
        lightbox.assetList.deferredAllResId = false;
        lightbox._updateAssetCount();
    },

    /**
     * retrieve and display assets of current lightbox
     *
     * @return  void
     */
    _loadAssets:function(){
        lightbox._hideShareLbx();
        lightbox.defaultLbx = 1;
        var lightbox_id = $('#lightbox_id').val();
        if (lightbox_id !== undefined) {
            var url = APP.baseURL + 'lightbox/loadassets';
            var params = {lightbox_id:lightbox_id};
            if (userPrefs.get('currentLightbox') !== null) {

                $('div#lightbox .panelContent').block({ message: null,  overlayCSS: { backgroundColor: '#eee', left: '-6px' } });
                $('span#flag_filter1').css('margin-left', '10px');
                $('span#lbxLoading').show();
            }
            $.post(url, params,    function(data){lightbox._displayAssets(data);}, "json");
            $('#shareLbx_id').val(lightbox_id);
            userPrefs.set('currentLightbox', lightbox_id);

        }
    },

    /**
     * display assets of loading lightbox
     *
     * @param   object  contains assets details, total amount of assets, asset flags, asset order, etc.
     * @return  void
     */
    _displayAssets:function(data) {
        var lightboxAssets = [];
        $.each(data.content.assets, function(id, dets) {
            lightboxAssets[id] = JSAsset.newAsset(dets);
        });
        lightbox.assetList.assets = lightboxAssets;
        lightbox.assetList.order = data.content.order;
        lightbox.assetList.count = data.content.count;
        lightbox.assetList.deferredAllResId = data.content.deferredAllResId;
        lightbox.defaultLbx = data.defaultLbx;
        lightbox.assetFlags = data.assets_flags;
        lightbox.allFlags = data.allFlags.split(',');

        $("#lbx_shareURL").data("val", data.shareURL);

        lightbox._checkDefaultLbx();

        $('#lightbox_body').html(lightbox.assetList.getHTML());
        linkRel._setup();

        var scrollPos = userPrefs.get('lightboxScrollPos');
        $('#lightbox_body').attr({ scrollTop: scrollPos });

        lightbox._updateSelectedAssets();
        // show/hide flag filters
        $('li[id^="li_flag_"]').css('display', 'none');
        var visibleFlags = [];
        $.each(lightbox.assetFlags, function(flag, assets) {
            $('label#flagCount_'+flag).text(assets.length);
            if (assets.length > 0) {
                $('#li_flag_'+flag).css('display', '');
                visibleFlags.push(parseInt(flag, 10));
            }
        });
        // reset asset count of flags which lightbox assets don't belong to
        $.each(lightbox.allFlags, function(index, flag_id) {
            if ($.inArray(parseInt(flag_id, 10), visibleFlags) == -1) {
                $('label#flagCount_'+flag_id).text('0');
            }
        });

        if (userPrefs.get('currentLightbox') !== null) {
            $('span#flag_filter1').css('margin-left', '22px');
            $('div#lightbox .panelContent').unblock();
            $('div#lightbox .panelContent').css('position','');
        }
        $('#selectLightboxOpt, #assets_count').removeClass('hideMe');
        lightbox._clearSelectedFlag();
        lightbox._showHideFlagFilter(visibleFlags);
        lightbox._updateAssetCount();
        lightbox._handleClick();
        lightbox._activateSortable();
    },

    _handleClick:function(){
        $("label[id^='lbl_selection_']").off('click');
        $("label[id^='lbl_selection_']").on('click', function(){ lightbox._doSelection(this); });
        $('.btnRemove').off('click');
        $('.btnRemove').on('click', function(e) {
                var this_id = $(this).attr('id').split('_');
                lightbox._removeAsset(this_id[1]);
                e.preventDefault();
        });
        lightbox._handleAssetPreviewPopupClick();
    },

    /**
     * _checkDefaultLbx - enable/disable rename and delete lightbox button
     */
    _checkDefaultLbx:function() {
        if (lightbox.defaultLbx == 1) {
            $('#renameLbx,#deleteLbx').css('display', 'none');
            $('#renameLbx_disabled,#deleteLbx_disabled').css('display', 'block');
        }
        else {
            $('#renameLbx_disabled,#deleteLbx_disabled').css('display', 'none');
            $('#renameLbx,#deleteLbx').css('display', 'block');
        }
    },

    /**
     * _assetTemplateRender - renders the template for an asset
     *
     * @param  object        asset object
     * @return  void
     */
    _assetTemplateRender:function(asset) {
        var template = lightbox._assetTemplate;
        var tAsset = asset;
        if (tAsset.publish_state != 2) {
            tAsset.thumbWidth = tAsset.thumbWidth ? tAsset.thumbWidth : 0;
            tAsset.thumbHeight = tAsset.thumbHeight ? tAsset.thumbHeight : 0;
            tAsset.viewPreview = lang.common.alt_ClickToPreviewLargeSize;
            tAsset.spanClass = 'pointer';
            tAsset.recalledFile = 'display:none';
        }
        else { // Recalled
            tAsset.thumbWidth  = 180;
            tAsset.thumbHeight = 100;
            tAsset.spanClass = '';
            tAsset.viewPreview = '';
        }
        $.extend(tAsset, {
            // Thumb sizing
            thumbStyle : (Math.max(tAsset.thumbWidth, tAsset.thumbHeight) > 64) ? ('width:'+(tAsset.thumbWidth/20)+'em; height:'+(tAsset.thumbHeight/20)+'em') : '',
            contactSheet_style : 'margin-top:-'+(tAsset.thumbHeight/2)+'px;'
        });
        if (tAsset.publish_state == 2) {
            tAsset.recalledFile = tAsset.thumbStyle;
            tAsset.thumbStyle = tAsset.hidePreview + tAsset.thumbStyle;
        }
        tAsset.lightboxID = $('#lightbox_id').val();
        if (tAsset.isDownloadable || tAsset.publish_state == 2) {
            tAsset.hideNoDownload = 'display:none';
        }
        else {
            tAsset.hideNoDownload = 'display:inline';
        }
        // stuff the asset values into the template
        $.each(tAsset, function(i, val) {
            template = template.replace(new RegExp('<\!' + i + '\!>', 'g'), val);
        });

        return template;
    },

    /**
     * _submitShareLbxForm - send lightbox to a defined user
     *
     * @return  void
     */
    _submitShareLbxForm:function() {
        $('#lbx_btn_send_email').attr('disabled', 'disabled');
        $('#lbx_btn_send_email').attr('style', 'background-color: #ECE9D8; color: #A9A9A9;');
        $('#noPermissionAssets').addClass('hideMe');
        var form = $('#lbx_frm_send_email');
        var url = APP.baseURL + 'lightbox/share';
        form.find('input.numLbxAssets').val(lightbox.assetList.count);
        var params = $('form#lbx_frm_send_email').serialize();
        $.post(url, params, function(sent) {
            lightbox._handleShareLbxResult(sent);
        }, "json");
        form.find('.shareLbx_confirmSend').val('0');
    },

    /**
     * show success or error message from sharing lightbox
     *
     * @param   object  contains the result (0, 1, or 2) and/or error message
     * @return  void
     */
    _handleShareLbxResult:function(sent) {
        var displayError = !($('#lbx_send_email_error_msg').text() === '');
        $('#lbx_send_email_error_msg, #noPermissionAssets').text('');
        if (sent.result == '1') {
            var success_msg = lang.assetdata.SuccessSendEmailAsset.format($('#lbx_email_to').val());
            lightbox._hideShareLbx();
            $('#lbx_email_to').val('');
            $('#lbx_email_message').val('');
            alert(sent.result_txt);
        }
        else if (sent.result == '0') {
            alert(lang.assetdata.ErrorSendEmailAsset);
        }
        else if (sent.result == '2') {
            $('#noPermissionAssets').html(sent.result_txt);
            $('#noPermissionAssets').removeClass('hideMe');
            $('#shareLbx_form div.popup div.popup_form').addClass('confirmSend');
            // click on 'Yes' button to confirm sharing this lightbox
            $('#btn_shareLbx_yes').off("click").on('click', function(){
                var form = $('#lbx_frm_send_email');
                form.find('.shareLbx_confirmSend').val('1');
                lightbox._submitShareLbxForm();
            });
            $('#lbx_close_email_form, #lbx_btn_cancel_email, #btn_shareLbx_no').off("click").on('click', function(e){
                    lightbox._hideShareLbx();
                    e.preventDefault();
            });
        }
        else { // validation error
            $('#lbx_send_email_error_msg').html(sent.result_txt);
            if (displayError) { alert(lang.lightbox.msg_NoFilesLbxCanBeSent); }
            $('#lbx_email_to').focus();
        }
        $('#lbx_btn_send_email').removeAttr('disabled');
        $('#lbx_btn_send_email').removeAttr('style');
    },

    /**
     * _showHideFlagFilter - show/hide flag filters
     *
     * @param   array of flag id to be shown
     * @return  void
     */
    _showHideFlagFilter:function(visibleFlags) {
        if ($('span#selected_flagCount').text().length == 0 || $('span#selected_flagCount').text() == '0') {
            // display all
            lightbox._clearSelectedFlag();
            $('li[id^="asset_li_"]').css('display', '');
        }
        if (visibleFlags.length <= 1) { // only 1 flag => hide all flag filters
            $('div#assets_count').removeClass('lozengeSpan');
            $('div#assets_count').removeClass('assets_count');
            if (visibleFlags.length == 1) { // append flag name to the asset count
                var selected_flag = $('a#flag_'+visibleFlags[0]).text();
                selected_flag = $.trim(selected_flag);
                selected_flag = (selected_flag != '') ? ' - '+selected_flag.substring(0,selected_flag.indexOf('(')) : '';
                $('span#selected_flag').text(selected_flag);
                $('li[id^="asset_li_"]').css('display', '');
            }
        }
        else {
            $('div#assets_count').addClass('lozengeSpan');
            $('div#assets_count').addClass('assets_count');
        }
        if (lightbox.selectedFlag != 0) {
            $('#contactSheet_numAssets').text($('a#flag_'+lightbox.selectedFlag).text());
        }
    },

    /**
     * _clearSelectedFlag - unset current filtered and set indicator on the list to 'All'
     *
     * @return  void
     */
    _clearSelectedFlag:function() {
        $('span#selected_flag').text('');
        $('.flag_filter').removeClass('set_selector');
        $('#flag_filter1').addClass('set_selector'); // 'All'
        var assetCount = lightbox.assetList.count;
        $('span#contactSheet_numAssets').text(assetCount+' '+(assetCount != 1?lang.common.plural_Asset:lang.common.noun_Asset));
        lightbox.selectedFlag = 0;
    },

    /**
     * hide share lightbox form
     *
     * @return  void
     */
    _hideShareLbx:function() { $('#shareLbx_form').addClass('hideMe'); },


    /**
     * handle when add new lightbox button has been clicked
     *
     * @return  void
     */
    _handleAddNewLbx:function(){
        var newName = prompt(lang.lightbox.lbl_EnterLbxNameInstructions, lang.lightbox.lbl_NewLbxName);
        newName = (newName == null) ? newName : $.trim(newName);
        if (newName!='' && newName!=null) {
            lightbox._resetStateMovingAsset();
            lightbox.createNewLbx(newName);
        } else if (newName=='') {
            alert(lang.lightbox.msg_BlankLbxNameWarn);
        }
    },

    /**
     * handle when rename lightbox button has been clicked
     *
     * @return  void
     */
    _handleRename:function(){
        if (lightbox.defaultLbx == 0) {
            var newName = prompt(lang.lightbox.lbl_EnterLbxNameInstructions, $('#lightbox_id :selected').attr('hval'));
            newName = (newName == null) ? newName : $.trim(newName);
            if (newName!='' && newName!=null) {
                lightbox.renameLbx(newName);
            } else if (newName=='') {
                alert(lang.lightbox.msg_BlankLbxNameWarn);
            }
        }
    },

    /**
     * handle when delete lightbox button has been clicked
     *
     * @return  void
     */
    _handleDelete:function(){
        if (lightbox.defaultLbx == 0) {
            if (confirm(lang.lightbox.msg_ConfirmLbxDelete)) {
                var url = APP.baseURL + 'lightbox/delete';
                var params = {id:$('#lightbox_id').val()};
                $.post(url, params,    function(result) {
                    if (result == '1') {
                        var loadedLbxID = $('#lightbox_id :selected').prev().val();
                        $('#lightbox_id :selected').remove();
                        $('#moveto_lightbox_id :disabled').remove();
                        $('#lightbox_id').val(loadedLbxID);
                        $('#moveto_lightbox_id option[value="'+loadedLbxID+'"]').attr('disabled','disabled');
                        lightbox.isApplySelection = false;
                        lightbox._loadAssets();
                        lightbox._resetStateMovingAsset();
                    }
                    else {
                        alert(lang.lightbox.msg_ErrDeleteLbx);
                    }
                } );
            }
        }
    },

    /**
     * handle when 'Select all' button has been clicked
     *
     * @return  void
     */
    _handleSelectAll:function() {
        $('#lightbox_body input:checkbox').each(function() {
            if (!$('#lbl_'+$(this).attr('id')).hasClass('checked')) {
                lightbox.selectedAssets.push($(this).val());
                $('#lbl_'+$(this).attr('id')).removeClass('unchecked');
                $('#lbl_'+$(this).attr('id')).addClass('checked');
            }
        });
        lightbox._updateAssetCount();
    },

    /**
     * handle when 'Select none' button has been clicked
     *
     * @return  void
     */
    _handleSelectNone:function() {
        $('#lightbox_body input:checkbox').each(function() {
            if ($('#lbl_'+$(this).attr('id')).hasClass('checked')) {
                $selected_asset_id = $(this).val();
                lightbox.selectedAssets = jQuery.grep(lightbox.selectedAssets, function($this_asset_id){
                    return $this_asset_id != $selected_asset_id;
                });
                $('#lbl_'+$(this).attr('id')).removeClass('checked');
                $('#lbl_'+$(this).attr('id')).addClass('unchecked');
            }
        });
        lightbox._updateAssetCount();
    },

    /**
     * handle when 'Invert selection' button has been clicked
     *
     * @return  void
     */
    _handleSelectInvert:function() {
        $('#lightbox_body input:checkbox').each(function() {
            if ($('#lbl_'+$(this).attr('id')).hasClass('checked')) {
                $selected_asset_id = $(this).val();
                lightbox.selectedAssets = jQuery.grep(lightbox.selectedAssets, function($this_asset_id){
                    return $this_asset_id != $selected_asset_id;
                });
                $('#lbl_'+$(this).attr('id')).removeClass('checked');
                $('#lbl_'+$(this).attr('id')).addClass('unchecked');
            }
            else {
                lightbox.selectedAssets.push($(this).val());
                $('#lbl_'+$(this).attr('id')).removeClass('unchecked');
                $('#lbl_'+$(this).attr('id')).addClass('checked');
            }
        });
        lightbox._updateAssetCount();
    },

    /**
     * mark asset as selected/deselected
     *
     * @param   element Label element of asset that presents checked/unchecked icon
     * @return  void
     */
    _doSelection:function(lbl) {
        $checkbox_asset = $(lbl).attr('for');
        if ($(lbl).hasClass('checked')) { // will change to uncheck
            lightbox.selectedAssets = jQuery.grep(lightbox.selectedAssets, function($this_asset_id){
                return $this_asset_id != $('#'+$checkbox_asset).val();
            });
            $(lbl).removeClass('checked');
            $(lbl).addClass('unchecked');
            $(lbl).attr('title', lang.lightbox.alt_NotselectedIndicator);
        }
        else {
            lightbox.selectedAssets.push($('#'+$checkbox_asset).val());
            $(lbl).removeClass('unchecked');
            $(lbl).addClass('checked');
            $(lbl).attr('title', lang.lightbox.alt_SelectedIndicator);
        }
        lightbox.isApplySelection = true;
//        lightbox._showHideSelectionButtons();
        lightbox._updateAssetCount();
    },

    /**
     * handle when 'Move files' button has been clicked
     *
     * @return  void
     */
    _handleMoveAssets:function() {
        if (lightbox.selectedAssets.length > 0) {
            if ($('#moveAssetOpt').hasClass('hideMe')) {
                $('#moveAssetOpt').removeClass('hideMe');
                $('#moveAssetsLbx').addClass('active');
                $('#selectLightboxOpt').addClass('hideMe');
            }
            else {
                $('#selectLightboxOpt').removeClass('hideMe');
                $('#moveAssetsLbx').removeClass('active');
                $('#moveAssetOpt').addClass('hideMe');
            }
        }
        else {
            alert(lang.lightbox.msg_PlsSelectAssets);
        }
        lightbox._showHideSelectionButtons();
    },

    /**
     * hide dropdown moving asset
     *
     * @return  void
     */
    _resetStateMovingAsset:function() {
        $('#selectLightboxOpt').removeClass('hideMe');
        $('#moveAssetsLbx').removeClass('active');
        $('#moveAssetOpt').addClass('hideMe');
    },


    /**
     * move selected assets to selected lightbox
     *
     * @return  void
     */
    _moveAssetsToLbx:function() {
        lightbox._hideShareLbx();
        lightbox.assetList.count = lightbox.assetList.count - lightbox.selectedAssets.length;
        // remove assets from the display list
        var selectedAssets = [];
        $.each(lightbox.selectedAssets, function(i, val) {
            selectedAssets[i] = parseInt(val);
            $('#asset_li_'+val).remove();
        });

        var url = APP.baseURL + 'lightbox/moveassets';
        var new_lightbox_id = $('#moveto_lightbox_id').val();
        var params = {lightbox_id:$('#lightbox_id').val(),new_lightbox_id:new_lightbox_id,asset_ids:selectedAssets.join(',')};
        $.post(url, params, function(res){
            // show/hide flag filters
            var flagCount = 0;
            $.each(res.flags, function(flag_id, count){
                flagCount = parseInt($('label#flagCount_'+flag_id).text()) - count;
                lightbox._updateFlagCount(flag_id, flagCount);
                $.each(selectedAssets, function(i,asset_id){ lightbox._removeAssetFlags(asset_id, flag_id); });
            });
            lightbox._setVisibleFlags();

            // update the amount of assets of lightbox which asset has been moved to
            var newLbx = '#lightbox_id option[value="'+new_lightbox_id+'"]';
            var new_lightbox_text = $(newLbx).attr('hval');
            new_lightbox_text = lightbox._getDisplayLbxName(res.count, new_lightbox_text);
            $(newLbx).text(new_lightbox_text);
            lightbox._resizeFlagFilter();
        }, "json");

        lightbox.assetList.removeAssets(selectedAssets);
        lightbox._updateSelectedAssets();
        if (lightbox.selectedAssets.length == 0) { // no assets selected
            $('#moveAssetOpt').addClass('hideMe');
            $('#moveAssetsLbx').removeClass('active');
//            $('#selectLightboxOpt').removeClass('hideMe');
        }
        lightbox._updateAssetCount();
        $('#moveto_lightbox_id').val(0); // reset 'Move to lightbox' dropdown
        $('#selectLightboxOpt').removeClass('hideMe');
    },

    /**
     * remove asset from current lightbox
     *
     * @param   integer Asset ID to be removed
     * @return  void
     */
    _removeAsset:function(asset_id) {
        lightbox._hideShareLbx();
        lightbox.assetList.count = lightbox.assetList.count - 1;

        var url = APP.baseURL + 'lightbox/removeasset';
        var params = {lightbox_id:$('#lightbox_id').val(),asset_id:asset_id};
        $.post(url, params, function(flags){
            if (flags.length) {
                // show/hide flag filters
                var flagCount = 0;
                $.each(flags, function(index, flag_id){
                    flagCount = parseInt($('label#flagCount_'+flag_id).text())
                    if (flagCount > 0) { flagCount = flagCount - 1; }
                    lightbox._updateFlagCount(flag_id, flagCount);
                    lightbox._removeAssetFlags(asset_id, flag_id);
                });
                lightbox._setVisibleFlags();
            }
            else {
                $('span#selected_flag').text('');
            }
            lightbox._resizeFlagFilter();
        }, "json");

        lightbox.assetList.removeAssets(parseInt(asset_id));
        // remove asset from the display list
        $('#asset_li_'+asset_id).remove();
        lightbox._updateSelectedAssets();
        lightbox._updateAssetCount();
    },

    /**
     * remove asset id from asset flags array
     *
     * @param    int        asset id
     * @param    int        flag id
     * @return    void
     */
    _removeAssetFlags:function(asset_id, flag_id) {
        if (lightbox.assetFlags[flag_id].length) {
            lightbox.assetFlags[flag_id] = $.grep(lightbox.assetFlags[flag_id], function($this_asset_id){
                return $this_asset_id != asset_id;
            });
        }
    },

    /**
     * update total files displayed in each flag filter
     *
     * @param    int        flag id
     * @param    int        total files
     * @return    void
     */
    _updateFlagCount:function(flag_id, flagCount) {
        $('label#flagCount_'+flag_id).text(flagCount);
        if (flag_id == lightbox.selectedFlag) {
            (flagCount > 0) ? $('span#selected_flagCount').text(flagCount) : $('span#selected_flag').text('');
        }
        $('#li_flag_'+flag_id).css('display', (flagCount>0?'':'none'));
    },

    /**
     * show/hide flag filters
     */
    _setVisibleFlags:function() {
        var visible, publicFlag_id;
        var visibleFlags = [];
        var flagCount = 0;
        $.each(lightbox.assetFlags, function(this_flag_id, this_assets){
            visible = $('#li_flag_'+this_flag_id).css('display');
            if (visible != undefined) {
                flagCount = flagCount + parseInt($('label#flagCount_'+this_flag_id).text());
                if (visible != 'none') visibleFlags.push(parseInt(this_flag_id));
            } else {
                publicFlag_id = parseInt(this_flag_id);
            }
        });
        if (flagCount!=lightbox.assetList.count) visibleFlags.push(publicFlag_id); // add public flag to display as dropdown
        lightbox._showHideFlagFilter(visibleFlags);
    },

    /**
     * change to display assets in another lightbox
     *
     * @return  void
     */
    _changeLbx:function() {
        userPrefs.set('currentLightbox', $('#lightbox_id').val());
        $('#shareLbx_id').val($('#lightbox_id').val());

        // clear selection state from current lightbox
        lightbox.isApplySelection = false;
        $('#moveAssetOpt').addClass('hideMe');
        $('#moveAssetsLbx').removeClass('active');
//        $('#selectLightboxOpt').addClass('hideMe');

        lightbox._loadAssets();
        lightbox._disableSelectedLightbox();
    },

    /**
     * handle when share lightbox button has been clicked
     * 
     * @return  void
     */
    _handleShareLbx:function(e) {
        e.preventDefault();
        if (lightbox.assetList.count > 0) {
            lightbox.share(user.fullname, $('#lightbox_id').val(), lightbox.assetList.count)
        }
        else {
            alert(lang.lightbox.msg_LightboxEmpty);
        }
    },
    share:function(userName, lightbox_id, count){
        var html = "";
        var content = "";
        $.each(lightbox.assetFlags, function(k, v){
            if( k !== 0 && v.length){
                content += '<li>' + $.trim($('a#flag_' + k).text()) + '</li>';
            }
        });
        if (content != "") html = "<h3>" + lang.lightbox.lbl_lbxContainsUsage + "</h3><ul class=\"alert alert-warning\">" + content + '</ul>';
        shareLightbox.begin({
            fullname        : userName,
            shareLbx_id     : lightbox_id,
            num_lbx_assets  : count,
            confirm_send    : 0,
            extraContent    : html
        });
    },
    
    /**
     * display assets from the selected flag
     *
     * @param   element Li element of flag for filtering asset
     * @return  void
     */
    _filterAssets:function(li) {
        if (!$(li).hasClass('set_selector')) { // check if it's not the current flag filter
            $('.flag_filter').removeClass('set_selector');
            if ($(li).attr('id') == 'flag_filter1') {
                $('li[id^="asset_li_"]').css('display', '');
                lightbox._clearSelectedFlag();
            }
            else {
                $('li[id^="asset_li_"]').css('display', 'none');
                var this_id = [];
                var filtered_flagID = $(li).attr('id').split('_');
                // display only assets with the selected flag
                $.each(lightbox.assetFlags, function(flag_id, assets){
                    if (flag_id == filtered_flagID[2]) {
                        var selected_flag = $('a#flag_'+flag_id).text();
                        $('span#selected_flag').html(' - ' + selected_flag.replace(')','</span>)').replace('(','(<span id="selected_flagCount">'));
                        $('span#contactSheet_numAssets').text(selected_flag);
                        $('li[id^="asset_li_"]').each(function(){
                            this_id = this.id.split('_');
                            if ($.inArray(parseInt(this_id[2]), assets) != -1) { $(this).css('display', ''); }
                        });
                        lightbox.selectedFlag = flag_id;
                        return false;
                    }
                });
            }
            $(li).addClass('set_selector');
        }
        lightbox._resizeFlagFilter();
        $('ul#flags_list').addClass('hideMe');
    },

    /**
     * resize flag filter dropdown to its content
     *
     * @return  void
     */
    _resizeFlagFilter:function() {
        if (!$('div#assets_count').hasClass('noFlags')) {
            if ( !$('div#assets_count').hasClass('assets_count') ) {
                $('ul#flags_list').addClass('hideMe');
            }
        }
    },

    /**
     * get counts for the number of files to display with lightbox name in the dropdown selector
     *
     * @param   integer the number of files
     * @param   string  lightbox name
     * @return  string  lightbox name together with the number of files
     */
    _getDisplayLbxName:function(fileCount, lbxName) {
        if (fileCount>0) { lbxName = lbxName+' ('+fileCount+')'; }
        return lbxName;
    },

    _handleAssetPreviewPopupClick:function(){
        $('#lightbox_body img[id^="lightboxAsset_"]+img.blankDL').click( function(){
            var id = $(this).prev().attr('id').replace('lightboxAsset_', '');
            if ($('#asset_li_'+id+' #recall_'+id).is(':visible')) return;
            var prevParam = {
                id:id,
                url_thumb:$("#lightboxAsset_"+id).attr("src"),
            };
            if ($('#lightbox_body > #asset > li[id^="asset_li"]').length > 1) {
                var assetPosition = ($('#lightbox_body > #asset > li').index($(this).closest('li')))+1;
                preview.launch_(prevParam, 'lightboxAssets_'+$('#lightbox_id').val(), false, assetPosition);
            } else {
                preview.launch_(prevParam, 'lightboxAssets_'+$('#lightbox_id').val());
            }
        });
    },

    /**
     * setup for lightbox
     *
     * @return  void
     */
    _setup:function() {


        $('[title=contactsheet]').attr('disabled', true);
        userPrefs.set('currentLightbox', $('#lightbox_id :selected').val());

        $('select#lightbox_id').css({
            'height': '24px!important',
            'line-height': '1.5!important'
        });

        // set up the asset list
        lightbox.assetList = JSAsset.newListView('asset', {
            assetTemplate: lightbox._assetTemplateRender,
            allowReordering:true,
            draggable:true
        });

        //Expand panel
        $(".expand-panel").click(function(){$("#container").toggleClass("lightbox-expanded");setTimeout(results.handleResize, 500);});

        // Lightbox Management
        $('#addLbx').click(lightbox._handleAddNewLbx);
        $('#renameLbx').click(lightbox._handleRename);
        $('#deleteLbx').click(lightbox._handleDelete);

        // Select Assets
        $('#selectAll').click(function(e){ lightbox._handleSelectAll();e.preventDefault(); });
        $('#selectNone').click(function(e){ lightbox._handleSelectNone();e.preventDefault(); });
        $('#selectInvert').click(function(e){ lightbox._handleSelectInvert();e.preventDefault(); });

        // Move Assets
        $('#moveAssetsLbx').click(function(e){ lightbox._handleMoveAssets();e.preventDefault(); });
        $('#moveto_lightbox_id').change(function() {
            // check if it's not the current lightbox
            if ($(this).val() !== '0') { lightbox._moveAssetsToLbx(); }
        });

        // Remove asset from current lightboc + select /deselect asset
        lightbox._handleClick();
        // Change to another lightbox
        $('#lightbox_id').change(lightbox._changeLbx);

        // Share/Email all assets in Lightbox
        $('#shareLbx').click(lightbox._handleShareLbx);
        
        // select any flags in lightbox 'set' selector dropdown
        $('.flag_filter').click(function(e){ lightbox._filterAssets(this); });
        $('#lightbox').on('mouseover', ".assets_count", function(){ $('ul#flags_list').removeClass('hideMe'); })
        $('#lightbox').on('mouseout', ".assets_count", function(){ $('ul#flags_list').addClass('hideMe'); });

        // Download selected assets
        $('#downloadLbx').click(function(e){
            if (lightbox.assetList.count > 0) {
                if (lightbox.selectedAssets.length > 0) {
                    download.begin(lightbox.selectedAssets);
                }
                else {
                    alert(lang.lightbox.msg_PlsSelectAssets);
                }
            }
            else {
                alert(lang.lightbox.msg_LightboxEmpty);
            }
            e.preventDefault();
        });
        $('#lbx_shareURL').off('click').on('click', function(e){
            e.preventDefault();
            // console.log( $("#lbx_shareURL").data('val') );
            APP.copyToClipboard( $("#lbx_shareURL").data('val'), "#lightbox" );
            var msg = lang.common.lbl_copied + '!';
            var flagged = [];    
            $.each(lightbox.assetFlags, function(k, v){
                if( k !== 0 && v.length){
                    flagged.push( $.trim( $('a#flag_' + k).text( )) );
                }
            });
            if (flagged.length){
                msg += " " + lang.lightbox.wargning_flagged.format(flagged.join(', '));
            }
            alert(msg);
        });
        $('#lbx_openInArchive').off('click').on('click', function(e){
            e.preventDefault();
            var url = $("#lbx_openInArchive").data('val') + lightbox.assetList.order.join(',');
            if (lightbox.assetList.count) window.open(url);
            else alert('Lightbox is empty');
        });
        // Print a contact sheet
        $('#printContactSheetLbx').click(function(e) {
            if (lightbox.assetList.count > 0) {
                e.preventDefault();
                $('body').append('<iframe id="print_frame" name="print_frame" width="10" height="10" frameborder="0" src="about:blank"></iframe>');
                lightbox.printContactSheet();
                $('#print_frame').remove();
            }
            else {
                alert(lang.lightbox.msg_LightboxEmpty);
            }
            e.preventDefault();
        });

        // View a slideshow of selected assets
        $('#slideShowLbx').click(function(e) {
            if (lightbox.assetList.count > 0) {
                if (!lightbox.selectedAssets.length) {
                    alert(lang.lightbox.msg_PlsSelectAssets);
                } else {
                    slideshow.allowShare = false;
                    slideshow.launch('lightboxAssets_'+$('#lightbox_id').val(), lang.lightbox.lbl_SlideshowTitle.format($('#lightbox_id :selected').text()), lightbox.selectedAssets);
                }
            }
            else {
                alert(lang.lightbox.msg_LightboxEmpty);
            }
            e.preventDefault();
        });

        //store scroll bar position of lightbox body before leaving the page
        window.onbeforeunload = function () {
            userPrefs.set('lightboxScrollPos', $('#lightbox_body').scrollTop());
        };

        // scroll bar designed with nicescroll.js
        $('#lightbox_body').niceScroll({cursorcolor:"#acacac",autohidemode:false,bouncescroll:true});
    }
};


})();


$(lightbox._setup);
$(lightbox._loadAssets);
$(lightbox._disableSelectedLightbox);


/*********************
Including file: JSAsset.js
*********************/
/**
 * JSAsset.js - js functionality for working with assets on the client side
 *
 * @package    asset
 * @author     Jon Randy
 * @copyright  (c) 2009 Lightrocket
 */

JSAsset = function () {

    /**
     * Private stuff
     */ 

    // Asset Class    
    
        /**
         * constructor
         *
         * @param    dets - asset details
         * @return    asset
         */
        var _asset = function (dets) {
            $.extend(this, dets);
            return this;
        }
        
        /**
         * html method (also used as the toString method for a nice way to 'print' and asset)
         *
         * @param    [mixed] - template to use to draw asset
         * @return  string - html for the asset
         */
        _asset.prototype.toString = _asset.prototype.html = function () {
            var template = (arguments.length>0) ? arguments[0] : JSAsset.defaultTemplate;
            // check if the template is a function and act accordingly
            if (!$.isFunction(template)) {
                $.each(this, function(i, val) {
                    template = template.replace(new RegExp('<\!' + i + '\!>', 'g'), val);
                });
                return template;
            } else {
                return template(this);
            }
        }
        
    // end Asset Class
    
    
    // Search Class
    
        /**
         * constructor
         *
         * @param    string - name of the search (will be used as the session var name on server)
         * @param    [object] - options for the search object we are creating (will be combined with the defaults)
         * @return  search object
         */
        var _search = function(searchName) {
            var opts = (arguments.length > 1) ? arguments[1] : {};
            this.searchName = searchName;
            $.extend(this, JSAsset.searchDefaults, opts);
            this.params = this.params ? this.params : JSAsset.searchParamDefaults;
            this.initialised = false;
            this.loading = false;
            this.loaded = false;
            this.count = 0;
            this.assets = {};
            this.resultsOrder = [];
            this.callback = false;
            return this;
        }

        /**
         * _init - will store search in the session and return results
         *
         * @param    int - start offset for results
         * @param    int - number of results to return
         * @return  void
         */
        _search.prototype._initialise = function (start, amount) {
            var url = APP.baseURL + 'search/do_json';
            var params = {searchName:this.searchName, offset:start, length:amount};
            var postParams = this._paramsForPost();
            $.extend(params, postParams);
            this.loading = true;
            $.post(url, params, $.context(this).callback('_processResponse'), "json");
        }

        /**
         * _retrieve - will retrieve results from the named search (stored in the session)
         *
         * @param    int - start offset for results
         * @param    int - number of results to return
         * @return  void
         */
        _search.prototype._retrieve  = function (start, amount) {
            var url = APP.baseURL + 'search/results_json';
            var params = {searchName:this.searchName, offset:start, length:amount};
            this.loading = true;
            $.post(url, params, $.context(this).callback('_processResponse'), "json");
        }

        /**
         * _paramsForPost - converts params to format required in the POST
         *
         * @return  object
         */
        _search.prototype._paramsForPost  = function () {
            var ret = {orderBy:this.orderBy, orderDir:this.orderDir};
            $.each(this.params, function(key, val) {
                ret['s['+key+']'] = val;
            });
            return ret;
        }

        /**
         * _processResponse - process the response from the search request
         *
         * @param    object - the object created from the JSON data returned by the server
         * @param    string - text status of the server response
         * @return  void
         */
        _search.prototype._processResponse  = function (data, status) {
            this.count = data.count;
            if (data.init) this.initialised = true;
            var receivedAssets = {};
            $.each(data.assets, function(id, dets) {
                receivedAssets[id] = JSAsset.newAsset(dets);
            });
            this.assets = receivedAssets;
            this.resultsOrder = data.order;
            this.deferredCountId = data.deferredCountId;
            this.searchName = data.searchName;
            this.loading = false;
            this.loaded = true;
            if (this.callback) {
                this.callback(this);
                this.callback = false;
            }
        }

        /**
         * getResults - get some or all results from a search
         *
         * usage can be either:    getResults(start, amount) - will get specified results, no callback 
         *                        getResults(callback) - get all results, use callback
         *                        getResults(callback, start, amount) - get specified results, use callback
         *
         * @return  void
         */
        _search.prototype.getResults  = function () {
            this.callback = false;
            var l = arguments.length;
            var start = 0;  var amount = 0;
            if (l==2 || l==3) {
                start = arguments[l-2];
                amount = arguments[l-1];
            }
            if (l==1 || l==3) {
                this.callback = arguments[0];
            }
            if (this.initialised) {
                this._retrieve(start, amount);
            } else {
                this._initialise(start, amount);
            }
        }

    // end Search Class
    
    // List View Class
    
        /**
         * constructor
         *
         * @param    string - id that will be used for the UL
         * @param    [object] - options for the listview object we are creating (will be combined with the defaults)
         * @return  listview object
         */
        var _listView = function(id) {
            var opts = (arguments.length > 1) ? arguments[1] : {};
            this.order = [];
            this.assets = {};
            this.id = id;
            this.shiftClickBase = 0;
            this.mousedownOn = 0;
            this.cancelReorder = false;
            $.extend(true, this, JSAsset.listViewDefaults, opts);
            return this;
        }
        
        /**
         * setShiftBase - sets the 'shift base' for shift selection
         *
         * @return  void
         */
        _listView.prototype.setShiftBase  = function (base) {
            this.shiftClickBase = base ? this._getLIIndexFromID(base) : 0;
            //////alert('Shift base: '+base+' ('+this.shiftClickBase+')');
        }
        
        /**
         * _getLIIndexFromID - get numerical index of LI within the list for LI with given asset id
         *
         * @return  string
         */
        _listView.prototype._getLIIndexFromID  = function (id) {
            var idx = $('#'+this.id + '>li').index($('#'+this._itemContainerID(id)));
            return idx;
        }
        
        /**
         * listHTML - returns full html for entire list
         *
         * @return  string
         */
        _listView.prototype.getHTML  = function () {
            var html = '<ul id="' + this.id + '"' + (this.listClass?(' class="' + this.listClass + '"'):'') + '>';
            var that = this;
            // if order array is empty, fill it with asset ids as they come from the assets object
            if (this.order == []) $.each(this.assets, function(id,asset){that.order.push(id)} );
            $.each(this.order, function(){
                html += that.itemHTML(this, ($.inArray(this/1, that.selectedItems)!=-1));
            });
            html += '</ul>';
            return html;
        }

        /**
         * itemHTML - returns full html for a list item (for asset with supplied id)
         *
         * @param    int - id of the asset
         * @param    mixed - value used to specify if item is selected
         * @return  string
         */
        _listView.prototype.itemHTML  = function (id, sel) {
            var asset, classbit, html, template;
            var allSelected = this.selectedItems.join(',').split(',');
            if (asset = this.assets[id]) {
                classes = ["asset-item"];
                sel ? classes.push("selected"): false;
                classbit = ' class="'+classes.join(" ")+'"';
                html = '<li id="' + this._itemContainerID(id) + '"' + classbit + '>';
                template = this.assetTemplate ? this.assetTemplate : JSAsset.defaultTemplate;
                html += asset.html(template);
                html += '</li>';
            } else {
                html = '';
            }
            return html;
        }

        /**
         * itemContainer - returns jquery object for li container for asset with supplied id
         *
         * @param    int - id of the asset
         * @return  string
         */
        _listView.prototype.itemContainer  = function (id) {
            return $('#' + this._itemContainerID(id));
        }

        /**
         * itemIDs - returns an array of all current asset ids
         *
         * @return  array
         */
        _listView.prototype.itemIDs  = function () {
            var all = [];
            $.each(this.assets, function(id){all.push(id)});
            return all;
        }
        
        /**
         * removeAssets - removes assets with selected id(s) - both from assets object and order array
         *
         * @param    array/int - array of ids or id of the asset to remove
         * @return  void
         */
        _listView.prototype.removeAssets  = function (assetIDs) {
            var that = this;
            if (!$.isArray(assetIDs)) assetIDs = [assetIDs];
            this.deselectItem(assetIDs);
            $.each(assetIDs, function(k,v)    { delete that.assets[v] });
            var temp = []; 
            $.each(this.order, function(k,v) {
                if ($.inArray(v, assetIDs)<0) temp.push(v);
            });
            this.order = temp;
            this.setShiftBase(0);
        }
        
        /**
         * addAssets - adds assets 
         *
         * @param  array - array of asset ids defining the order of assets to be added
         * @param  object - object containg all asset objects for those assets to be added
         * @param  [optional] integer - position to add the assets - will default to end of list
         * @return  integer - the amount of assets after adding
         */
        _listView.prototype.addAssets  = function (assetOrder, assetData) {
            var that = this;
            var pos = (arguments.length>2) ? arguments[2] : 'end';
            if (((pos/1)>(that.order.length-1))||(pos===false)) pos = 'end';
            // put the relavent asset objects into our assets
            $.each(assetOrder, function(k, assetID) {
                that.assets[assetID] = assetData[assetID];
            });

            // strip out the assets from the existing order if they are there
            $.each(that.order, function(k,v) {//alert(v);alert($.inArray(v, o))
                if ($.inArray(v, assetOrder)>-1) {that.order[k] = -999;}
            });
            // combine order arrays as appropriate
            var f;
            switch(pos)    {
                case 0: // add at start
                    f = assetOrder.concat(that.order);
                    break;
                case 'end': // add at end
                    f = that.order.concat(assetOrder);
                    break;
                default:
                    f = that.order.slice(0,pos).concat(assetOrder).concat(that.order.slice(pos)); 
                    break;
            }
            
            var finalArr = [];
            $.each(f, function(k,v) { if (v!=-999) finalArr.push(v) });
            that.order = finalArr;
            this.setShiftBase(0);
            return that.order.length;
        }
        
        /**
         * setItemValue - set new value(s) to selected asset objects
         * 
         * @param  string - asset field
         * @param  mixed - new asset value
         * @param  [id] - asset id to set a new value (otherwise all selected assets will be set)
         * @return void
         */
        _listView.prototype.setItemValue = function(field, value) {
            var items = (arguments.length > 2) ? arguments[2] : this.selectedItems;
            if (!$.isArray(items)) items = [items];
            $.each(this.assets, function(id,dets){
                if ($.inArray(id/1, items)!=-1) {
                    dets[field] = value;
                }
            });
        }

        /**
         * _fireEvent - fires an event for this listView
         *
         * @param    string - name of the event
         * @param    [object] - additional data to send with event
         * @return  void
         */
        _listView.prototype._fireEvent  = function (eventName) {
            var listElement, data;
            var extraData = (arguments.length > 1) ? arguments[1] : {};
            if (listElement = $('#' + this.id)) {
                data = $.extend(extraData, {listView:this});
                listElement.trigger(eventName, data);
            }
        }

        /**
         * _selectItem - changes selected status of given item(s) to true (or false - optional param)
         *
         * @param    array/int - ids/id of item to select/deselect
         * @param    [mixed] - will be used to decide status we are setting items to 
         * @param    [mixed] - will be used to determine if this is part of a multi click select (used?)
         * @return  void
         */
        _listView.prototype._selectItem  = function (id) {
            var sel = (arguments.length > 1) ? arguments[1] : true;
            var multiClick = (arguments.length > 2) ? arguments[2] : false;
            if (!$.isArray(id)) id = [id];
            id = $.map(id, function(a){return a/1;});
            var that = this;
            var current;
            var toAdd;
            // select
            if (sel) {
                current = this.selectedItems;
                toAdd = $.grep(id, function(n){return !($.inArray(n, current) >= 0)});
                this.selectedItems = $.merge(current, toAdd);
                $.each(toAdd, function(){ if (i=that.itemContainer(this)) i.addClass('selected')});
            // deselect    
            } else {
                this.selectedItems = $.grep(this.selectedItems, function(n){return !($.inArray(n/1, id) >= 0)});
                $.each(id, function(){if (i=that.itemContainer(this)) i.removeClass('selected')});
            }
        }
        
        /**
         * _selectDryRun - does a dry run of a select (works like _selectItem above)
         *
         * Does the selection on a copy of the selected asset array so we can check the result of a selection before doing it for real
         *
         * @return  array - array of selected assets after the selection operation
         */
        _listView.prototype._selectDryRun  = function (assets, id) {
            rassets = assets.slice(); // make sure we have a copy of the original selected items array
            var sel = (arguments.length > 2) ? arguments[2] : true;
            var multiClick = (arguments.length > 3) ? arguments[3] : false;
            if (!$.isArray(id)) id = [id];
            id = $.map(id, function(a){return a/1;});
            var that = this;
            var current;
            var toAdd;
            // select
            if (sel) {
                current = rassets;
                toAdd = $.grep(id, function(n){return !($.inArray(n, current) >= 0)});
                rassets = $.merge(current, toAdd);
            // deselect    
            } else {
                rassets = $.grep(rassets, function(n){return !($.inArray(n/1, id) >= 0)});
            }
            return rassets;
        }
        
        /**
         * selectItem - the REAL selectItem method - will fire all associated events
         *
         * @param    array/int - ids/id of item to select
         * @return  void
         */
        _listView.prototype.selectItem  = function (id) {
            this.cancelSelect = false;
            var proposed = this._selectDryRun(this.selectedItems, id);
            this._fireEvent('beforeSelectedChange', {newSelection:proposed});
            if (!this.cancelSelect) {
                this._selectItem(id);
                this._fireEvent('afterSelectedChange');
            }
        }

        /**
         * deselectItem - will deselect item/items and fire all associated events
         *
         * @param    array/int - ids/id of item to deselect
         * @return  void
         */
        _listView.prototype.deselectItem  = function (id) {
            this.cancelSelect = false;
            var proposed = this._selectDryRun(this.selectedItems, id, false);
            this._fireEvent('beforeSelectedChange', {newSelection:proposed});
            if (!this.cancelSelect) {
                this._selectItem(id, false);
                this._fireEvent('afterSelectedChange');
            }
        }

        /**
         * selectAll - select all items and fire associaed events
         *
         * @return  void
         */
        _listView.prototype.selectAll  = function () {
            this.cancelSelect = false;
            var allOnPage = this.itemIDs();
            var proposed = this._selectDryRun(this.selectedItems, allOnPage, true);
            //var proposed = false;
            this._fireEvent('beforeSelectedChange', {newSelection:proposed});
            if (!this.cancelSelect) {
                this._selectItem(allOnPage);
                this._fireEvent('afterSelectedChange');
            }
        }

        /**
         * deselectAll - deselect all items and fire associaed events
         *
         * @return  void
         */
        _listView.prototype.deselectAll  = function () {
            this.cancelSelect = false;
            var allOnPage = this.itemIDs();
            var proposed = this._selectDryRun(this.selectedItems, allOnPage, false);
            this._fireEvent('beforeSelectedChange', {newSelection:proposed});
            if (!this.cancelSelect) {
                this._selectItem(allOnPage, false);
                this._fireEvent('afterSelectedChange');
            }
        }

        /**
         * toggleItem - toggles the selected state of the passed item/items
         *
         * @param    array/int - ids/id of item to deselect
         * @return  void
         */
        _listView.prototype.toggleItem  = function (id) {
            if (!$.isArray(id)) id = [id];
            var currentlySelected = []; var currentlyUnselected = [];
            var that = this;
            $.each(id, function() { that.isSelected(this/1) ? currentlySelected.push(this/1) : currentlyUnselected.push(this/1) });
            var proposed = this._selectDryRun(this.selectedItems, currentlySelected, false);
            proposed = this._selectDryRun(proposed, currentlyUnselected);
            
            this.cancelSelect = false;
            this._fireEvent('beforeSelectedChange', {newSelection:proposed});
            if (!this.cancelSelect) {
                if (currentlySelected.length) { this._selectItem(currentlySelected, false) };
                if (currentlyUnselected.length) { this._selectItem(currentlyUnselected) };
                this._fireEvent('afterSelectedChange');
            }
        }
        
        /**
         * toggleAll - toggle the selected state of all items
         *
         * @return  void
         */
        _listView.prototype.toggleAll  = function () {
            this.toggleItem(this.itemIDs()); // will fire events itself
        }

        /**
         * handleAssetClick - handles asset selection
         *
         * @param    object - the event object from the click
         * @param    int - id of the item being clicked on
         * @return  void
         */
        _listView.prototype.handleAssetClickOld  = function (event, id) {
            id = id/1;
            var isCtrlClick = event.ctrlKey;
            // multi mode
            if (this.multiSelect && isCtrlClick) {
                this.toggleItem(id); // will fire events itself
            }
            // single mode (or multi mode without ctrl pressed)
            else {
                var toDesel = $.grep(this.selectedItems, function(i){return (i!=id)});
                if (toDesel.length) {
                    this.cancelSelect = false;
                    var proposed = this._selectDryRun(this.selectedItems, toDesel, false);
                    proposed = this._selectDryRun(proposed, id);
                    this._fireEvent('beforeSelectedChange', {newSelection:proposed});
                    if (!this.cancelSelect) {
                        this._selectItem(toDesel, false);
                        this._selectItem(id);
                        this._fireEvent('afterSelectedChange');
                    }
                } else {
                    this.toggleItem(id); // will fire events itself
                }
            }
        }
                
        /**
         * handleAssetClick - handles asset selection
         *
         * @param    object - the event object from the click
         * @return  void
         */
        _listView.prototype.handleAssetClick  = function (event) {
            var id = (arguments.length>1) ? arguments[1] : this._assetIDFromElement(event.target);
            var isCtrlClick = (event.ctrlKey || event.metaKey);
            var isShiftClick = event.shiftKey;
            var isClickOnAlreadySelected = $.inArray(id, this.selectedItems)>-1;
            
            // bail on shift click of any kind
            if (isShiftClick) return;
            
            if (isCtrlClick || (!isCtrlClick && isClickOnAlreadySelected)) {
                // multi mode
                if (this.multiSelect && isCtrlClick) {
                    this.toggleItem(id); // will fire events itself
                }
                // single mode 
                else {
                    var toDesel = $.grep(this.selectedItems, function(i){return (i!=id)});
                    if (toDesel.length) {
                        this.cancelSelect = false;
                        var proposed = this._selectDryRun(this.selectedItems, toDesel, false);
                        proposed = this._selectDryRun(proposed, id);
                        this._fireEvent('beforeSelectedChange', {newSelection:proposed});
                        if (!this.cancelSelect) {
                            this._selectItem(toDesel, false);
                            this._selectItem(id);
                            this._fireEvent('afterSelectedChange');
                        }
                        this.pendingSelectID = false;
                    } else {
                        //isCtrlClick ? this.toggleItem(id) : this.selectItem(id); // will fire events itself
                        isCtrlClick ? this.toggleItem(id) : 0; // will fire events itself
                        this.pendingSelectID = false;
                    }
                }
            }
        }
        
        /**
         * handleAssetMouseDown - handles mouse down on asset
         *
         * @param    object - the event object from the click
         * @return  void
         */
        _listView.prototype.handleAssetMouseDown  = function (event) {
            var id = (arguments.length>1) ? arguments[1] : this._assetIDFromElement(event.target);
            this.mousedownOn = id;
            
            id = id/1;
                var isCtrlClick = (event.ctrlKey || event.metaKey);
            var isShiftClick = event.shiftKey;
            
            this.pendingSelectID = id;
            
            // set shift base if multi mode and no shift pressed
            if (!isShiftClick && this.multiSelect) {
                this.setShiftBase(id);
            }
            
            // bail if ctrl click
            if(isCtrlClick && !isShiftClick) return;
            
            // multi mode
            if (isShiftClick && this.multiSelect) {
                // build an array of ids in the shift 'region'
                var low = this.shiftClickBase;
                var high = this._getLIIndexFromID(id);
                if (high<low) high = (low += high -= low) - high;
                var i, ids=[], lis=$('#'+this.id + '>li');
                for (i=low; i<=high; i++) ids.push(this._assetIDFromElement(lis[i]));
                // do selection
                this._selectGroup(ids, !isCtrlClick);
                this.pendingSelectID = false;
            }
            // single mode (or multi mode without ctrl pressed)
            else {
                // if mousedown is on one already selected, then the selection change needs to happen on the click
                if ($.inArray(id, this.selectedItems)>-1) return;
                var toDesel = $.grep(this.selectedItems, function(i){return (i!=id)});
                if (toDesel.length) {
                    this.cancelSelect = false;
                    var proposed = this._selectDryRun(this.selectedItems, toDesel, false);
                    proposed = this._selectDryRun(proposed, id);
                    this._fireEvent('beforeSelectedChange', {newSelection:proposed});
                    if (!this.cancelSelect) {
                        this._selectItem(toDesel, false);
                        this._selectItem(id);
                        this._fireEvent('afterSelectedChange');
                    }
                    this.pendingSelectID = false;
                } else {
                    this.selectItem(id); // will fire events itself
                    this.pendingSelectID = false;
                }
            }
            
        }
        
        /**
         * _selectGroup - handles selecting of a group
         *
         * @param    ids - array of assets in group to select
         * @param    [bool] - optional boolean to clear existing selection first (defaults to false)
         * @return  void
         */
        _listView.prototype._selectGroup  = function (ids) {
            var clearFirst = (arguments.length>1) ? arguments[1] : false;
            if (!clearFirst) {
                this.selectItem(ids);
            } else {
                var toUnselect = [];
                var that = this;
                $.each(this.selectedItems, function() {
                    var thisID = this/1;
                    if ($.inArray(thisID, ids)==-1) toUnselect.push(thisID);
                });
                var proposed = this._selectDryRun(this.selectedItems, ids);
                if (toUnselect.length) proposed = this._selectDryRun(proposed, toUnselect, false);
                this.cancelSelect = false;
                this._fireEvent('beforeSelectedChange', {newSelection:proposed});
                if (!this.cancelSelect) {
                    this._selectItem(ids);
                    if (toUnselect.length) { this._selectItem(toUnselect, false) };
                    this._fireEvent('afterSelectedChange');
                }
            }
        }
        
        /**
         * handleAssetMouseUp - handles mouse up on asset
         *
         * @param    object - the event object from the click
         * @return  void
         */
        _listView.prototype.handleAssetMouseUp  = function (event) {
            this.mousedownOn = 0;
        }

        
        /**
         * isSelected - returns whether or not given asset is selected
         *
         * @param    int - id of item to check selection status of
         * @return  bool
         */
        _listView.prototype.isSelected  = function (id) {
            return $.inArray(id, this.selectedItems) != -1;
        }

        /**
         * _itemContainerID - returns name of the LI containing the asset with passed ID
         *
         * @param    int - id of item to get LI id for
         * @return  string
         */
        _listView.prototype._itemContainerID  = function (asset_id) {
            return this.id+'_li_'+asset_id;
        }
        
        /**
         * _assetIDFromElement - returns id of asset the given element is in the cell of
         *
         * @param    element - element to check
         * @return  int
         */
        _listView.prototype._assetIDFromElement  = function (el) {
            el = $(el);
            var liContainer = el.is('li') ? el : el.closest('li');
            var elid=liContainer[0].id;
            return elid.replace(this.id+'_li_', '')/1;
        }

        /**
         * wireUpSelectors - makes items marked with magic classes do appropriate selecting
         *
         * @param    listView object - the object we are doing this for (used to make sure called functions are called in correct context)
         * @param    [mixed] - optional truey/falsey to skip the wireup of selection events - defaults to false
         * @return  void
         */
        _listView.prototype.wireUpEvents  = function (that) {
            
            var skipSelection = (arguments.length>1) ? arguments[1] : false;
            
            if (!skipSelection) {
                // 'selection' events
                var listElement = $('#' + this.id);
                if (this.beforeSelectedChange) listElement.bind('beforeSelectedChange', this.beforeSelectedChange);
                if (this.afterSelectedChange) listElement.bind('afterSelectedChange', this.afterSelectedChange);
                // select, deselect and toggle switches
                if (this.allowSelection) {
                    var toggleswitches=$('ul#'+that.id);
                    toggleswitches.on("mousedown", 'li.asset-item .toggleSwitch', (function(event) { if (!$(event.target).hasClass('noToggle')) $.context(that).callback('handleAssetMouseDown')(event)}));
                    toggleswitches.on("mouseup",'li.asset-item .toggleSwitch', (function(event) { if (!$(event.target).hasClass('noToggle')) $.context(that).callback('handleAssetMouseUp')(event)}));
                    toggleswitches.on("click", 'li.asset-item .toggleSwitch', (function(event) { if (!$(event.target).hasClass('noToggle')) $.context(that).callback('handleAssetClick')(event)}));
                }
            }
            
            var LIs = false;
                        
            // dragging from
            if (this.allowReordering || this.draggable) {
                // check our LIs are not already draggable
                var LIs = $('#' + this.id + '>li');
                if (!LIs.hasClass('ui-draggable')) {
                    // make LIs draggable
                    var opts = {
                        helper:function(event){return that._buildHelper(event)}
                    };
                    $.extend(true, opts, this.draggableOptions);
                    LIs.draggable(opts);
                }
            }
            
            // dropping stuff on the list
            if (this.allowReordering || this.dropIns.length) {
                var all = LIs ? LIs.add($('ul#' + this.id)) : $('#' + this.id + '>li,ul#' + this.id);
                if (all.hasClass('ui-droppable')) all.droppable('destroy'); // make sure any previous droppable functionality removed
                // make all targets droppable
                all.droppable({
                    greedy    :        false,
                    accept    :    function(draggable) { return that._acceptDraggable(draggable) },
                    activate:    function(event, ui) { return that._dragActivate(event, ui, that) },
                    deactivate    :    function(event, ui) { return that._dragDeactivate(event, ui, that) },
                    over    :    function(event, ui) { return that._dragOver(event, ui, that) },
                    out        :    function(event, ui) { return that._dragOut(event, ui, that) },
                    drop    :    function(event, ui) { return that._dragDrop(event, ui, that) }
                });
            }
            
        }
        
        /**
         * _acceptDraggable - check if the passed draggable is acceptable for dropping on us
         *
         * @param    object - the draggable object to check
         * @return  boolean - accept draggable or not
         */
        _listView.prototype._acceptDraggable  = function (draggable) {
            var isDropIn = false;
            // if we are allowing re-ordering - is it one of ours?
            var isOurs = this.allowReordering ? draggable.is('ul#' + this.id + ' > li') : false;
            // is it one of the 'dropIns
            if (this.dropIns.length) {
                var checkIs = '';
                $.each(this.dropIns, function(pos, checkIn) { checkIs += (checkIs?',':'') + checkIn.selector; });
                isDropIn = draggable.is(checkIs);
            }
            return isOurs||isDropIn;
        }
            
        /**
         * _dragActivate - activate monitoring of draggable
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @param    object - listitem object that will monitor this draggable
         * @return  void
         */
        _listView.prototype._dragActivate  = function (event, ui, that) {
            // temporarily bind to the draggables 'drag' event so we can monitor where it is in relation to the current droppable
            ui.draggable.data('monitoredByAssetList', that);
            ui.draggable.bind('drag', that._monitorDraggable);
        }
        
        /**
         * _dragDeactivate - stop monitoring of draggable
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @param    object - listitem object that is monitoring the draggable
         * @return  void
         */
        _listView.prototype._dragDeactivate  = function (event, ui, that) {
            // unbind to the draggables 'drag' event so we can monitor where it is in relation to the current droppable
            ui.draggable.data('monitoredByAssetList', false);
            ui.draggable.unbind('drag', that._monitorDraggable);
        }
        
        /**
         * _dragOver - respond to something being dragged over
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @param    object - listitem object associated with the list being dragged over
         * @return  void
         */
        _listView.prototype._dragOver  = function (event, ui, that) {
            var tgt = $(event.target);
            var liContainer = tgt.is('li') ? tgt : tgt.closest('li');
            that.activeDroppable = !liContainer.is('li') ? false : {
                element : liContainer,
                offset : liContainer.offset(),
                draggableCursorAt : ui.draggable.draggable('option', 'cursorAt'),
                elementCentre : {left:liContainer.width()/2, top:liContainer.height()/2}
            };
        }
            
        /**
         * _dragOut - respond to something being dragged out
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @param    object - listitem object associated with the list being dragged out of
         * @return  void
         */
        _listView.prototype._dragOut  = function (event, ui, that) {
            var tgt = $(event.target);
            var liContainer = tgt.is('li') ? tgt : tgt.closest('li');
            that._setDropPosition({element:liContainer, position:false});
            that._setDropPosition({element:liContainer, position:''});
            //if (!that.activeDroppable.element || that.activeDroppable.element[0].id==liContainer[0].id)  that.activeDroppable = false;
                        if (liContainer[0] == undefined || !that.activeDroppable.element || that.activeDroppable.element[0].id==liContainer[0].id)  that.activeDroppable = false;
        }
        
        /**
         * _monitorDraggable - binds to a draggable to monitor its movement while over one of our droppables
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @return  void
         */
        _listView.prototype._monitorDraggable = function (event, ui) {
            var myAssetList = $(this).data('monitoredByAssetList');
            var dropElem = myAssetList.activeDroppable ? myAssetList.activeDroppable.element : false;
            var dropElemPos = dropElem ? myAssetList.activeDroppable.offset : false;
            var draggablePos = ui.offset;
            var cursorAtPos = myAssetList.activeDroppable ? myAssetList.activeDroppable.draggableCursorAt : false;
            
            if (dropElem) {
                var x = cursorAtPos.left + draggablePos.left - dropElemPos.left;
                var y = cursorAtPos.top + draggablePos.top - dropElemPos.top;
                var dw = myAssetList.activeDroppable.elementCentre.left;
                var dh = myAssetList.activeDroppable.elementCentre.top;
                var whichHalf = (myAssetList.orientationVertical ? (y<dh) : (x<dw)) ? -1 : 1;
                var dp = {element:dropElem, position:whichHalf};
                myAssetList._setDropPosition(dp);
            }
            
        }
            
        /**
         * _dragDrop - respond to something being dropped on
         *
         * @param    object - event object
         * @param    object - ui object (see jquery docs)
         * @param    object - listitem object associated with the list being dropped on
         * @return  void
         */
        _listView.prototype._dragDrop  = function (event, ui, that) {
            var tgt = $(event.target);
            var droppedOnCell = tgt.is('li') ? tgt : tgt.closest('li');
            
            // work out if we have dropped (either on cell or parent list)
            var dropped = (droppedOnCell.is('li') || (tgt.is('ul') && that.activeDroppable==false));

            // if we are allowing re-ordering - is draggable ours?
            if (dropped && (isOurs = this.allowReordering ? $(ui.draggable).is('ul#' + this.id + ' > li') : false)) {
                that._handleReorderDrop(that);
            }
            // is it one of the 'dropIns'
            if (dropped && this.dropIns.length) {
                $.each(this.dropIns, function(pos, dropIn) {
                    if ($(ui.draggable).is(dropIn.selector)) dropIn.handler(ui.draggable, that);
                });
            }
            
            
            // clear the active droppable if we have dropped on something other than an LI (or this is the second call from the parent ul)
            if (!droppedOnCell.is('li')) {
                that.activeDroppable = false;
            } else {
                // we did drop on an li so clear the position indicator from it
                that._setDropPosition({element:droppedOnCell, position:false});
            }
        }
        
        /**
         * _handleReorderDrop - handle a re-ordering drop
         *
         * @param    object - listitem object associated with the list being re-ordered
         * @return  void
         */
        _listView.prototype._handleReorderDrop  = function (assetList) {
            // first calculate the array position of the drop
            var pos;
            if (assetList['dropPosition']) {    
                if (!assetList.dropPosition.position) {
                    pos = 'xxx';
                } else {
                    pos = assetList.dropPosition.index + ((assetList.dropPosition.position<0)?0:assetList.dropPosition.position);
                }
            } else {
                pos = 'xxx';
            }
            if (pos=='xxx') return;
            // build new (proposed order array)
            assetList._fixOrderSelectedItems();
            var currentAssetIDs = assetList.order;
            var ids = assetList.selectedItems;
            $.each(currentAssetIDs, function(idx, id) { if ($.inArray(id, ids)>-1) currentAssetIDs[idx] = -999 });
            switch(pos)    {
                case 0:
                    var f = ids.concat(currentAssetIDs);
                    break;
                default:
                    var f = currentAssetIDs.slice(0,pos).concat(ids).concat(currentAssetIDs.slice(pos)); 
                    break;
            }
            var newOrder = [];
            $.each(f, function(k,v) { if (v!=-999) newOrder.push(v);});
            
            // fire 'before' event
            assetList.cancelReorder = false;
            assetList._fireEvent('beforeReorder', {proposed:newOrder});
            // if reorder not cancelled, set new order and fire 'after' event
            if (!assetList.cancelReorder) {
                assetList.order = newOrder;
                assetList._fireEvent('afterReorder');
                assetList.setShiftBase(0);
            }
            
        }
        
        /**
         * _fixOrderSelectedItems - max order of selected items match order in which they appear in asset list
         *
         * @return  void
         */
        _listView.prototype._fixOrderSelectedItems  = function () {
            var newList = [];
            var oldList = this.selectedItems;
            $.each(this.assets, function(id, asset) {
                if ($.inArray(id/1, oldList)>-1) newList.push(id/1);
            });
            this.selectedItems = newList;
        }
        
        /**
         * _setDropPosition - set the drop position in the list
         *
         * @param    object - details of the drop position - passed from one of the event handling functions
         * @return  void
         */
        _listView.prototype._setDropPosition  = function (params) {
            params['assetID'] = $(params['element']).is('li') ? this._assetIDFromElement($(params['element'])) : false;
            params['index'] = params['assetID'] ? $.inArray(params['assetID'], this.order) : false;
            this.dropPosition = (params['position']!==false) ? params : {};
            this._showDropPosition(params['element'], params['position'])
        }
        
        /**
         * _showDropPosition - respond to something being dropped on
         *
         * @param    element - LI element associated with the drop position
         * @return  string
         */
        _listView.prototype._showDropPosition  = function (li) {
            var position = (arguments.length > 1) ? arguments[1] : false;
            switch(position) {
                case -1:
                  $(li).removeClass('addAfter').addClass('addBefore');
                  break;
                case 1:
                  $(li).removeClass('addBefore').addClass('addAfter');
                  break;
                case false:
                  $(li).removeClass('addAfter').removeClass('addBefore');
            }
        }
            
        /**
         * _buildHelper - builds helper object for dragging
         *
         * @param    object - event object from drag event handler
         * @return  string
         */
        _listView.prototype._buildHelper  = function (event) {
            
            // do pending select if one waiting
            var pending = this.pendingSelectID;
            if (pending) {
                this.pendingSelectID = false;
                if($.inArray(pending, this.selectedItems)==-1) this.selectItem(pending);
            }
            
            var sel = this.selectedItems;
            var count = sel.length;
            
            var onSelected = (mdo=this.mousedownOn/1) ? $.inArray(mdo, sel)!=-1 : false;
            if (onSelected) {
                // fire the confirmed drag started function if we have one
                if (this.draggableOptions.onConfirmedDragStart) this.draggableOptions.onConfirmedDragStart();
                var singH = this.draggableOptions.helperSingle ? this.draggableOptions.helperSingle : this._buildHelperSingle;
                var multiH = this.draggableOptions.helperMulti ? this.draggableOptions.helperMulti : this._buildHelperMulti;
                return (count==1 ? singH(event) : multiH(event, count));
            } else {
                return $('<span></span>');
            }    

        }
        
        /**
         * _buildHelperSingle - builds default element for dragging single items
         *
         * @return  element
         */
        _listView.prototype._buildHelperSingle  = function (event) {
            var tgt = $(event.target);
            var liContainer = tgt.is('li') ? tgt : tgt.closest('li');
            return liContainer.clone();
        }
        
        /**
         * _buildHelperMulti - builds default element for dragging multiple items
         *
         * @return  element
         */
        _listView.prototype._buildHelperMulti  = function (event, count) {
            var tgt = $(event.target);
            var liContainer = tgt.is('li') ? tgt : tgt.closest('li');
            return liContainer.clone().append($('<span class="dragCount">' + count + '</span>'));
        }
        
        
        
    // end List View Class    
    
    
    /**
     * Public stuff
     */ 
     
    return  {
        
        // default template to use to build html for assets if none passed
        defaultTemplate: '<strong>Asset ID: <!id!></strong> - <em><!caption!></em><br /><img class="toggleSwitch" src="<!thumbURL!>" /><br />',
        // defaults for a new search object
        searchDefaults: {
            orderBy:'assets.id',
            orderDir:'ASC'
        },
        // default search parameters for a new search
        searchParamDefaults:{
            keywords:''
        },
        // defaults for a new list view object
        listViewDefaults:{
            assetTemplate:'',
            assets:{},
            selectedItems:[],
            allowReordering:false,
            listClass:'',
            multiSelect:true,
            beforeSelectedChange:false,
            afterSelectedChange:false,
            allowSelection:true,
            orientationVertical:false,
            draggable:false,
            draggableOptions:{
                zIndex:10000,
                opacity:0.5
            },
            dropIns:[]
        },

        /**
         * newAsset - create and return a new asset object
         *
         * @param    dets - asset details
         * @return  asset object
         */
        newAsset:function(dets) {
            return new _asset(dets);
        },
        
        /**
         * newListView - create and return a new listView object
         *
         * @param    string - id for UL
         * @param    [object] - options for list view
         * @return  listView
         */
        newListView:function(id) {
            var opts = (arguments.length > 1) ? arguments[1] : {};
            return new _listView(id, opts);
        },
        
        /**
         * newSearch - create and return a new search object
         *
         * @param    string - name for the search
         * @param    [object] - options for list view
         * @return  search object
         */
        newSearch:function(name) {
            var opts = (arguments.length > 1) ? arguments[1] : {};
            return new _search(name, opts);
        },
        
        /**
         * makeFlagList - convert the coded flags in the asset to a readable list
         *
         * @param    string - coded list
         * @return  string - readable list
         */
        makeFlagList:function(coded) {
            var flags = coded.replace(new RegExp('__', 'g'), ',').replace(new RegExp('_', 'g'), '').split(',');
            var read = [], i=0;
            for (i=0; i<flags.length; i++)  if (JSAsset.specialFlags.indexOf(flags[i]/1)==-1) read.push(JSAsset.flagNames[(flags[i]/1)]); 
            return read.join(', ');
        },
        
        IsValidImageUrl:function(url, id) {
            var img = new Image();
            img.onerror = function() { $.get(APP.baseURL+"assets/rebuildthumbandpreview/" + id + "/1/0"); }
            img.src = url;
        }
    };

}(); // the parens here cause the anonymous function to execute and return





 









/*********************
Including file: slideshow.js
*********************/
/**
 * slideshow.js - js functions relating to generic slideshow functionality
 *
 * @package    slideshow
 * @author     Jon Randy
 * @copyright  (c) 2010 OnAsia
 */
(function() {
    
slideshow = {
    
    _windowHeight: 845,
    _windowParams: 'width=1000,height=%h%,scrollbars=auto,toolbar=no,location=no,directories=no,status=no,menubar=no',
    slideshowID:false,
    slideCount:0,
    currentSlide:0,
    pages:[],
    pageCount:0,
    
    slideDelay:4000,
    slideHeight:0,        // will be set from PHP
    slideWidth:0,        // will be set from PHP
    
    pageLength: 0,        // will be set from PHP
    
    playing:false,
    _tempImages:[],
    currentSlideData:false,
    _imageLoadTimeout:false,
    _slideTimeout:false,
    _extraTimeout:false,
    
    currentSlideDiv:'#s2',
    spareSlideDiv:'#s1',
    
    _transitionInProgress:false,
    _mouseOverThumbs:false,
    currentThumbPage:0,
    _thumbPics:[],

    shareFilesSlide:false,
    allowShare:false, // if this slideshow is allowed to share/generate embeded codes
    shareID:0, // record ID of slideshow content which is being shared
    shareModule:'', // to retrieve search object when sharing slideshow
    shareAccessWrn:false, // show/hide warning message there're some files with limited access
        
    /**
     * setup
     *
     * @return  void
     */
    _setup:function() {
        // small correction intial window height if we are using chrome frame
        slideshow._windowHeight = CHROME_FRAME ? 904 : 845;
        slideshow._windowParams = slideshow._windowParams.replace('%h%', slideshow._windowHeight);
        
        // stuff to do if we are on an actual slideshow page
        if (slideshow._pageIsSlideshow()) {
            
            fullscreen.notify();                        // inform about fullscreen mode if we are actually on the slideshow page
            window.onbeforeunload = slideshow._cleanUp;    // clean up on window close
            
            slideshow.pageCount = 1+Math.floor((slideshow.slideCount-1)/slideshow.pageLength);
            slideshow._preloadImages(slideshow.pages[1]);
            if (slideshow.pageCount > 1) slideshow.loadPage(2, false, false);

            
            // play/pause controls
            $('#btnPlay').click(function(e) { e.preventDefault(); slideshow.play(); });
            $('#btnPause').click(function(e) { e.preventDefault(); slideshow.pause(); });
            
            // prev/next controls
            $('#prev,#next').hide();
            $('#prev').click(function(e) { e.preventDefault(); slideshow.clearSlideTimer(); slideshow.showPrevSlide(); });
            $('#next').click(function(e) { e.preventDefault(); slideshow.clearSlideTimer(); slideshow.showNextSlide(); });
            
            // mouseover for captions
            $('#slides img.main').hover(
                function() { $('#slides p').addClass('hovershow'); },
                function() { $('#slides p').removeClass('hovershow'); }
            );
            
            // monitor if mouse is over thumbnails
            $('#thumblist').hover(
                function() {
                    slideshow._mouseOverThumbs = true;
                    var reqdPageNum = slideshow._pageForSlideNum(slideshow.currentSlide);
                    if (reqdPageNum!=slideshow.currentThumbPage) slideshow.updateThumbs(reqdPageNum);
                },
                function() {
                    slideshow._mouseOverThumbs = false;
                }
            );
            
            // prev and next page actions
            $('#thumbprev a').click(function(e) { e.preventDefault(); slideshow.prevPage(); });
            $('#thumbnext a').click(function(e) { e.preventDefault(); slideshow.nextPage(); });
                        
            // go
            slideshow.play();
        }
    },
    
    /**
     * switch captions on/off
     *
     * @param  bool
     * @return  void
     */
    captions:function(state) {
        var div = $('#slides');
        state ? div.addClass('captionsOn') : div.removeClass('captionsOn');
    },
    
    /**
     * swap the slides (fade one to the other)
     *
     * @param  [function]    callback function to call on completion of swap
     * @return  void
     */
    swapSlides:function() {
        var onComplete = arguments.length ? arguments[0] : false;
        if (slideshow._transitionInProgress) return false;
        slideshow._transitionInProgress = true;
        slideshow.captions(false);
        $(slideshow.spareSlideDiv).fadeTo(1,0,function(){
            $(slideshow.currentSlideDiv).css('z-index', 9000);
            $(slideshow.spareSlideDiv).css('z-index', 10000);
            $(slideshow.spareSlideDiv).fadeTo(400, 1, function() {
                var temp = slideshow.currentSlideDiv;
                slideshow.currentSlideDiv = slideshow.spareSlideDiv;
                slideshow.spareSlideDiv = temp;
                slideshow.captions(true);
                $('#prev,#next').show();
                slideshow._transitionInProgress = false;
                if (onComplete) onComplete();
            });
        });
    },
    
    /**
     * play - play/pause the slideshow
     *
     * @param  [bool]        true - play, false - pause
     * @return  void
     */
    play:function() {
        var state = arguments.length ? arguments[0] : true;
        if (state) {
            // play
            $('#btnPlay').addClass('hideMe');
            $('#btnPause').removeClass('hideMe');
            slideshow.clearSlideTimer();
            slideshow.playing = true;
            slideshow.showNextSlide();
        } else {
            // pause
            $('#btnPlay').removeClass('hideMe');
            $('#btnPause').addClass('hideMe');
            slideshow.clearSlideTimer();
            slideshow.playing = false;
        }
    },
    pause:function(){slideshow.play(false);},
    
    /**
     * clear slide timer
     *
     * @return  void
     */
    clearSlideTimer:function() {
        if (slideshow._slideTimeout) clearTimeout(slideshow._slideTimeout);
        if (slideshow._extraTimeout) clearTimeout(slideshow._extraTimeout);
        slideshow._showLoading(false);
    },
    
    /**
     * start slide timer
     *
     * @return  void
     */
    startSlideTimer:function() {
        slideshow.clearSlideTimer();
        slideshow._slideTimeout = setTimeout(slideshow.showNextSlide, slideshow.slideDelay);
    },
    
    /**
     * show a slide
     *
     * @param  int            slide number
     * @param  [function]    callback function to call once slide displayed
     * @return  void
     */
    showSlide:function(slideNum) {
        var pg = slideshow._pageForSlideNum(slideNum);
        var onComplete = (arguments.length>1) ? arguments[1] : false;
        // check availability of slide
        if (slideshow._slideAvailable(slideNum)) {
            var slideDets = slideshow._slideDetails(slideNum);
            // load the image and make the slide display when it is loaded
            var carryOn = function() { slideshow._showLoading(false); slideshow._displaySlide(slideNum, onComplete); };
            if (!slideshow._tempImages[slideDets.previewURL]) {
                slideshow._tempImages[slideDets.previewURL] = new Image();
                slideshow._showLoading();
                $.each(slideshow._tempImages, function(k,v) { delete slideshow._tempImages[k].onload; });
                slideshow._tempImages[slideDets.previewURL].onload = carryOn;
                slideshow._tempImages[slideDets.previewURL].src = slideDets.previewURL;
            } else {
                if (slideshow._tempImages[slideDets.previewURL].complete) {
                    slideshow._displaySlide(slideNum, onComplete);
                } else {
                    $.each(slideshow._tempImages, function(k,v) { delete slideshow._tempImages[k].onload; });
                    slideshow._tempImages[slideDets.previewURL].onload = carryOn;
                }
            }
        } else {
            slideshow.loadPage(pg, function() { slideshow.showSlide(slideNum, onComplete); });
        }
    },
    
    /**
     * display a slide once image laoded
     *
     * @param  int            slide number
     * @param  [function]    callback function to call once slide displayed
     * @return  void
     */
    _displaySlide:function(slideNum) {
        var pg = slideshow._pageForSlideNum(slideNum);
        var onComplete = (arguments.length>1) ? arguments[1] : false;
        var slideDets = slideshow._slideDetails(slideNum);
        // put the image onto the slide
        var image = $(slideshow.spareSlideDiv+' img.main');
        image.css('background', 'url('+slideDets.previewURL+') no-repeat 0 0').attr('height', slideDets.height).attr('width', slideDets.width);
        // put the caption onto the slide
        var caption = $(slideshow.spareSlideDiv+' p');
        caption.css('margin-top', Math.floor((slideDets.height - slideshow.slideHeight)/2) + 'px');
        caption.html(slideDets.caption);
        // reposition prev and next 'buttons'
        $('#prev,#next').hide();
        var margin = ((slideDets.width < 80) ? 0 : Math.floor((slideDets.width/2) - 40)) + 'px';
        $('#prev').css('margin-right', margin);
        $('#next').css('margin-left', margin);
        slideshow._extraTimeout = setTimeout(function(){slideshow.swapSlides(function() {
            if ($('#thumblistcontainer').hasClass('hideMe')) slideshow.updateThumbs(slideshow._pageForSlideNum(slideshow.currentSlide));
            slideshow.highlightThumb(slideNum);
            if (onComplete) onComplete();
        });}, 1200);
    },
    
    /**
     * show next slide
     *
     * @return  void
     */
    showNextSlide:function() {
        if (slideshow.currentSlide===0) {
            slideshow.currentSlide = 1;
        } else {
            slideshow.currentSlide = 1 + (slideshow.currentSlide % slideshow.slideCount);
        }
        slideshow.showSlide(slideshow.currentSlide, slideshow.playing ? slideshow.startSlideTimer : false);
    },
    
    /**
     * show previous slide
     *
     * @return  void
     */
    showPrevSlide:function() {
        if (slideshow.currentSlide===0) {
            slideshow.currentSlide = 1;
        } else {
            slideshow.currentSlide -= 1;
            if (slideshow.currentSlide < 1) slideshow.currentSlide = slideshow.slideCount;
        }
        slideshow.showSlide(slideshow.currentSlide, slideshow.playing ? slideshow.startSlideTimer : false);
    },
    
    /**
     * Jump to a slide
     *
     * @param  int            slide number
     */
    jumpToSlide:function(slideNum) {
        slideshow.currentSlide = slideNum;
        slideshow.showSlide(slideNum, slideshow.playing ? slideshow.startSlideTimer : false);
    },
    
    
    
    /**
     * cleanup - delete related server session vars
     *
     * @return  void
     */
    _cleanUp:function() {
        if (slideshow.slideshowID) {
            var url = APP.baseURL + 'slideshow/cleanup/' + slideshow.slideshowID;
            $.post(url);
        }
    },
    
    /**
     * check if we are on slideshow page
     *
     * @return  boolean
     */
    _pageIsSlideshow:function() {
        return $('body').hasClass('slideshow');
    },
    
    /**
     * launch slideshow - called from a normal window, not a slideshow window
     *
     * @param  string - name of sess search object
     * @param  optional string - title for slideshow
     * @param  optional array - array of asset ids to restrict slideshow to
     * @return  void
     */
    launch:function(objName) {
        var showTitle = (arguments.length>1) ? arguments[1] : '';
        var restrictIDs = (arguments.length>2) ? arguments[2] : false;
        // call the server setup stuff
        var url = APP.baseURL + 'slideshow/init';
        var params = restrictIDs ? {sso:objName, title:showTitle, restrict:restrictIDs.join(',')} : {sso:objName, title:showTitle};
        if (slideshow.shareFilesSlide) $.extend(params, {shareFiles_slideshow:1});
        if (slideshow.allowShare) $.extend(params, {allowShare:1, module:slideshow.shareModule, shareID:slideshow.shareID, shareAccessWrn:slideshow.shareAccessWrn?1:0});
        // put up a message to let the user know something is happening
        alert(lang.slideshow.msg_preparing, {time:3600000});
        $.post(url, params,    slideshow._launch, "json");
    },
    _launch:function(data) {
        // did initialisation fail?
        if ((data.pID==-1)) {
            alert(lang.slideshow.msg_InitFailed);
            return false;
        // no viewable assets?
        } else if (data.count===0) {
            alert(lang.slideshow.msg_noViewableAssets);
        // Ready to go
        } else {
            // clear the message
            alert('');
            var showURL = APP.baseURL + 'slideshow/view/' + data.pID;
            
            //open blank_window
            var w = window.open('', 'slideshow_'+ data.pID, slideshow._windowParams);
            //set default loading content for slideshow
            var newContent = '<html style="height:100%;margin:0;padding:0"><head><title>'+lang.slideshow.msg_preparing+'</title></head>';
            newContent += '<body style="text-align:center;">';
            newContent += '<p style="font-family:sans-serif;font-size:1.5em;font-weight:bold;color:#999;margin-top:'+((slideshow._windowHeight/2)-20)+'px">';
            newContent += lang.slideshow.msg_loadingPage+'</p>';
            newContent += '<script>setTimeout(function(){window.location.href="'+showURL+'";},50)</script>';
            newContent += "</body></html>";
            // write HTML to new window document
            w.document.write(newContent);

            if (w !== undefined && window.focus) w.focus();
        }
    },
    
    /**
     * loadSlide
     *
     * @return  boolean
     */
    loadSlide:function(slideData) {
        // make sure image loading timeout initially cleared
        if (slideshow._imageLoadTimeout) clearTimeout(slideshow._imageLoadTimeout);
    },
    
    /**
     * loadPage - load all details for assets on specified page of slideshow
     *
     * @param  int            page number
     * @param  function        callback function to receive pageData
     * @return  void
     */
    loadPage:function(pageNum, callback) {
        var loadAhead = (arguments.length==3) ? arguments[2] : true;
        if (!slideshow._pageAvailable(pageNum)) {
            var url = APP.baseURL + 'slideshow/pagedetail';
            var params = {id:slideshow.slideshowID, page:pageNum, pageSize:slideshow.pageLength};
            $.post(url, params, function(pageData) {
                slideshow.pages[pageNum] = pageData;
                slideshow._preloadImages(pageData);
                if (callback) callback(pageData);
            }, "json");
        } else {
            if (callback) callback(slideshow.pages[pageNum]);
        }
        if (loadAhead && (pageNum < slideshow.pageCount)) {
            slideshow.loadPage(pageNum+1, false, false);
        }
    },
    
    /**
     * _preloadImages - preload thumbs for a page
     *
     * @param  object        page data
     * @return  void
     */
    _preloadImages:function(pgData) {
        $.each(pgData, function(idx, s) {
            var a = new Image();
            a.src = s.thumbURL;
            slideshow._tempImages[s.previewURL] = new Image();
            slideshow._tempImages[s.previewURL].src = s.previewURL;
            slideshow._thumbPics.push(a);
        });
    },
    
    /**
     * _pageForSlideNum - work out what page a given slide number is on
     *
     * @param  int            slide number
     * @return  int
     */
    _pageForSlideNum:function(slideNum) {
        return 1 + Math.floor((slideNum-1)/slideshow.pageLength);
    },
    
    /**
     * _slideDetails - get the details for given slide number
     *
     * @param  int            slide number
     * @return  object
     */
    _slideDetails:function(slideNum) {
        var pg = slideshow._pageForSlideNum(slideNum);
        return slideshow.pages[pg][(slideNum-1) % slideshow.pageLength];
    },
    
    /**
     * Is slide with given id available?
     *
     * @param  int            slide number
     * @return  boolean
     */
    _slideAvailable:function(slideNum) {
        var pg = slideshow._pageForSlideNum(slideNum);
        return slideshow._pageAvailable(pg);
    },
    
    /**
     * Is page with given number available?
     *
     * @param  int            page number
     * @return  boolean
     */
    _pageAvailable:function(pageNum) {
        return typeof(slideshow.pages[pageNum])!='undefined';
    },
    
    /**
     * thumbListHTML - produces html for full thumb list
     *
     * @param  int            page number
     * @param  [int]        optional active slide id
     * @return  string        required html
     */
    thumbListHTML:function(pageNum) {
        var activeSlide = (arguments.length > 1) ? arguments[1] : 0;
        var pageSlideCount = slideshow.pages[pageNum].length;
        var blankCount = slideshow.pageLength - pageSlideCount;
        var html = ''; var slideNum = 0; var highlight = false;
        $.each(slideshow.pages[pageNum], function(i, slide) {
            slideNum = ((pageNum - 1)*slideshow.pageLength) + i + 1;
            highlight = slideNum==activeSlide;
            html += slideshow.thumbHTML(slideNum, highlight);
        });
        while (blankCount--) html += '<li></li>';
        return html;
    },
    
    /**
     * thumbHTML - produces html for a single thumb list item
     *
     * @param  int            slide number
     * @param  int            highlight slide?
     * @return  string        required html
     */
    thumbHTML:function(slideNum, highlight) {
        var ts = 72;
        var d = slideshow._slideDetails(slideNum);
        var cls = highlight ? ' class="sl_active"' : '';
        var html = '<li' + cls + '><a href="#" id="slidethumb_' + slideNum + '">';
        var ah = d.thumbHeight; var aw = d.thumbWidth; var rw; var rh;
        if ((ah>ts)||(aw>ts)) {
            if (aw>=ah) {
                rw = ts;
                rh = Math.floor(ah * ts / aw);
            } else {
                rh = ts;
                rw = Math.floor(aw * ts / ah);
            }
        } else {
            rw = aw;
            rh = ah;
        }
        html += '<img src="' + d.thumbURL + '" width="' + rw + '" height="' + rh + '" alt="' + d.caption + '" title="' + d.caption + '" />';
        html += '</a></li>';
        return html;
    },
    
    /**
     * updateThumbs - update thumbs list
     *
     * @param  int            page number
     * @return  void
     */
    updateThumbs:function(pageNum) {
        $('#thumblist ul').html(slideshow.thumbListHTML(pageNum, slideshow.currentSlide));
        $('#thumblistcontainer').removeClass('hideMe');
        (pageNum==1) ? $('#thumbprev a').addClass('hideMe') : $('#thumbprev a').removeClass('hideMe');
        (pageNum==slideshow.pageCount) ? $('#thumbnext a').addClass('hideMe') : $('#thumbnext a').removeClass('hideMe');
        // click events
        $('#thumblist li').unbind('click');
        $('#thumblist li').click(function(e){
            slideshow.clearSlideTimer();
            ////// delete slideshow._tempImage;
            var sn = $(this).find('a')[0].id.replace('slidethumb_', '')/1;
            slideshow.highlightThumb(sn);
            slideshow.jumpToSlide(sn);
            e.preventDefault();
        });
        slideshow.currentThumbPage = pageNum;
    },
    updateThumbsWithPageCheck:function(pageNum) {
        if (slideshow._pageAvailable(pageNum)) {
            slideshow.updateThumbs(pageNum);
        } else {
            alert(lang.slideshow.msg_loadingPage);
            slideshow.loadPage(pageNum, function() { alert(''); slideshow.updateThumbs(pageNum);});
        }
    },
    
    /**
     * highlightThumb - highlight a thumbnail
     *
     * @param  int            slide number
     * @return  void
     */
    highlightThumb:function(slideNum) {
        $('#thumblist li').closest('li').removeClass('sl_active');
        $('#thumblist a#slidethumb_'+slideNum).closest('li').addClass('sl_active');
    },
    
    /**
     * prevPage - previous page
     *
     * @return  void
     */
    prevPage:function() {
        if (slideshow.currentThumbPage>1) {
            slideshow.currentThumbPage -= 1;
            slideshow.updateThumbsWithPageCheck(slideshow.currentThumbPage);
        }
    },
    
    /**
     * nextPage - duhhhh
     *
     * @return  void
     */
    nextPage:function(slideNum) {
        if (slideshow.currentThumbPage<slideshow.pageCount) {
            slideshow.currentThumbPage += 1;
            slideshow.updateThumbsWithPageCheck(slideshow.currentThumbPage);
        }
    },
    
    /**
     * _showLoading - show loading indicator
     *
     * @param  [boolean]    visible/invisible
     * @return  boolean
     */
    _showLoading:function() {
        var state = arguments.length ? arguments[0] : true;
        state ? $('h1').addClass('loading') : $('h1').removeClass('loading');
    }
    
    
    
};


})();

$(slideshow._setup);



/*********************
Including file: email_popup.js
*********************/
/**
 * email_popup.js - js functions relating to popup to share file
 *
 * @author     Tik Nipaporn
 * @copyright  (c) 2009 OnAsia
 */
 
(function() {
email_popup = $.extend({}, dialog, {
    params              : {},
    templateSelector    : "",
    boxId               : "",
    title               : "",
    show_form           : 1,
    field_default       : {
        mandatory   : true,     //field must to be filled?
        optional    : false,    //field can be absent?
        type        : "text",   //choose between text/email
    },
    fields:["fromName","toEmail","message","code"],
    field_definitions:{
        toEmail:{type:"email"},
        "g-recaptcha-response":{selector:"textarea.g-recaptcha-response"},
    },
    getTitle:function(){return ""},
    getBtnSend:function(){
        var that = this;
        return {
            label:lang.common.lbl_Send,
            events: {
                click:function(){$.proxy(function(){}, that)}, //proxy allows to pass the object that as context (e.g to define "this" in the function)
            },
            preventDismiss:true,
            classes:"btn-primary"
        };
    },
    getBtnCancel:function(){
        return {
            label:lang.common.lbl_Cancel,
            events:{
                click:function(){}
            },
        };
    },
    _setup:function(){
        this.formTemplate = _.template($(this.templateSelector).html());
        if(this.hiding){
            setTimeout(function(){this.begin(options)}, 500);
            return;
        }
        this.reset();
        $.extend(this.options,this.default_options,         
            {
                boxId : this.boxId,
                title: this.getTitle(),
                buttons:{
                    cancel:this.getBtnCancel(),
                    send:this.getBtnSend(),
                },
                hideCallback:this.onClose,
            }
        );
        //Set default field definitions
        var that = this;
        $.each(this.fields, function(){
            that.field_definitions[this] = (that.field_definitions[this] !== undefined)?$.extend({},that.field_default,that.field_definitions[this]):that.field_default;
        });
        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        this.makeButtonsDismiss();
        if(user.show_form) this.setButtonsHtml();
    },
    begin:function(params){
        $.extend(this.params, params);
        this._setup();
        this.beforeShow();
    },
    beforeShow:function(){
        this.makeBoxAndShow(this.params);
    },
    makeBoxAndShow:function(params){
        this.options.content = this.formTemplate(params);
        this.addBox();
        this.show();
        if ( $("#" + this.options.boxId + " #nocaptcha").val() === undefined || $("#" + this.options.boxId + " #nocaptcha").val() == 0) this.updateCaptcha();
        this.setButtonsEvents();
        this.extraActions();
    },
    updateCaptcha : function() {
        var captchaSel = $('#' + this.boxId).find('.g-recaptcha');
        try {
            grecaptcha.render(captchaSel[0], {'sitekey' : captchaSel.data('sitekey')});
        }
        catch(err) {
            grecaptcha.reset();
        }
    },
    _beforeSendMsg:function(){
        var that = this;
        $.each(this.fields, function(){
            var selector = "#"+that.options.boxId+" "+((that.field_definitions[this].selector)?that.field_definitions[this].selector:"#"+this);
            that.params[this] = $(selector).val();
        });
        errors = this.validateForm();
        if(errors.fields.length){
            this.showErrors(errors);
        }
        else
            this.sendMsg();
    },
    validateForm:function(){
        var errFields = [];
        var errMsgs = [];
        function addErr(field, type) {
            errFields.push(field);
            errMsgs.push(lang.contributors.sendMessageValidation[field][type]);
        }
        var that = this;
        $.each(this.fields, function(){
            if(that.field_definitions[this]["mandatory"]){
                if (that.params[this]==='') 
                    if(that.field_definitions[this]["optional"] === false || $("#"+that.options.boxId+" "+((that.field_definitions[this].selector)?that.field_definitions[this].selector:"#"+this)).length > 0)
                        addErr(this, 'required');
            }
            else that.params[this] = $.trim(that.params[this]);
            if(that.field_definitions[this]["type"] === "email" && that.params[this] !== "" && that.params[this] !== undefined){
                that.params[this] = that.params[this].replace("; ", ",").replace(", ", ",").replace(" ", ",").replace(";", ",");
                if((that.field_definitions[this]["optional"] === false || $("#"+that.options.boxId+" "+((that.field_definitions[this].selector)?that.field_definitions[this].selector:"#"+this)).length > 0) && !that.validEmail(that.params[this]))
                    addErr(this, 'email');
            }
        });
        // email address
        errFields = _.uniq(errFields);
        errMsgs = _.uniq(errMsgs);
        return {fields:errFields, messages:errMsgs};
    },
    extraActions:function(){},
    showErrors:function(errors){
        $("#"+this.options.boxId +' label').removeClass("text-danger");
        $("#"+this.options.boxId +' #error_send_msg').addClass("hideMe");
        if(errors){
            $("#"+this.options.boxId +' #error_send_msg').html(errors.messages.join("<br>"));
            $("#"+this.options.boxId +' #error_send_msg').removeClass("hideMe");
            var that = this;
            $.each(errors.fields, function(){
                $("#"+that.options.boxId +' label[for="'+this+'"').addClass("text-danger");
            });
        }
    },    
    // checks to see if an email address is valid
    validEmail:function(email) {
        var emails = email.split(",");
        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,}))$/;
        var ok = true;
        $.each(emails, function(){
            if(!re.test(this)){
                ok = false;
                return false;
            }
        });
        return ok;
    },
    onClose:function(){
    },
});
})();


/*********************
Including file: sharePreview.js
*********************/
/**
 * sharePreview.js - Object that allows to show a asset sharing popup
 *
 * @author     Romain Bouillard
 * @copyright  (c) 2018 Lightrocket
 */
 
(function() {
sharePreview = $.extend({}, email_popup,{
    params: {},
    templateSelector:"#popup-share-template",
    boxId:"share-asset-box",
    fields:["fromName","fromEmail","toEmail","message","g-recaptcha-response"],
    sendUrl: APP.baseURL + 'preview/shareasset',
    field_definitions:{
        fromEmail:{optional:true,type:"email"},
        toEmail:{type:"email"},
        message:{mandatory:false},
        "g-recaptcha-response":{selector:"textarea.g-recaptcha-response"},
    },
    getTitle:function(){return lang.search_results.lbl_ShareViaEmail},
    getBtnSend:function(){
        var that = this;
        return {
            label:lang.assetdata.lbl_SendEmailAsset,
            events:{
                click:function(){$.proxy(that._beforeSendMsg(),that)},
            },
            preventDismiss:true,
            classes:"btn-primary"
        };
    },

    sendMsg:function(){
        var that = this;
        $.post(this.sendUrl, this.params, function(data){
            $("#"+that.options.boxId +' #error_send_msg').text('');
            
            if(data.success === true){
                that.showErrors(false);
                alert(data.messages.join("<br>"));
                that.hide();
            }
            else{
                if(data.fields != undefined && $.isArray(data.fields)){
                    that.showErrors(data);
                }
            }
            if ( $("#" + that.options.boxId + " #nocaptcha").val() === undefined || $("#" + that.options.boxId + " #nocaptcha").val() == 0) that.updateCaptcha();
        }, "json");
    },
});
})();

/*********************
Including file: shareGroup.js
*********************/
/**
 * sharePreview.js - Object that allows to show a asset sharing popup
 *
 * @author     Romain Bouillard
 * @copyright  (c) 2017 Lightrocket
 */
 
(function() {
shareGroup = $.extend({}, sharePreview,{
    boxId:"share-group-box",
    //sendUrl: APP.baseURL+'share/submit',
    sendUrl: APP.baseURL+'group/share',
});
})();

/*********************
Including file: shareLightbox.js
*********************/
/**
 * sharePreview.js - Object that allows to show a asset sharing popup
 *
 * @author     Romain Bouillard
 * @copyright  (c) 2018 Lightrocket
 */
 
(function() {
shareLightbox = $.extend({}, sharePreview,{
    params: {
        confirm_send: 0,
        num_lbx_assets: 0,
    },
    templateSelector:"#popup-share-lightbox-template",
    boxId:"share-lightbox-box",
    getTitle:function(){return lang.lightbox.lbl_Share},
    getBtnSend:function(){
        var that = this;
        return {
            label:lang.common.lbl_Send,
            events:{
                click:function(){$.proxy(shareLightbox._beforeSendMsg(),that)},
            },
            preventDismiss:true,
            classes:"btn-primary"
        };
    },
    extraActions:function(){},
    sendMsg:function(){
        var url = APP.baseURL+'lightbox/share';
        $.post(url, shareLightbox.params, function(data){
            $("#"+shareLightbox.options.boxId +' #error_send_msg').text('');
            
            if(data.success === true){
                shareLightbox.showErrors(false);
                alert(data.messages.join("<br>"));
                shareLightbox.hide();
            }
            else{
                if(data.fields != undefined && $.isArray(data.fields)){
                    shareLightbox.showErrors(data);
                }
                else if(parseInt(data.result) === 2){
                    dialog.confirm({
                        message:data.result_txt,
                        actionOnYes : function(){
                            shareLightbox.params.confirm_send = 1;
                            shareLightbox.sendMsg();
                            shareLightbox.hide();
                        },
                        actionOnNo : function(){
                            shareLightbox.hide();
                        },
                    });
                }
                else if(parseInt(data.result) === 3){
                    dialog.alert({
                        message:data.result_txt,
                        actionOnOk : function(){
                            shareLightbox.hide();
                        },
                    });
                }
            }
        }, "json");
    },
});
})();

/*********************
Including file: contactContrib.js
*********************/
/**
 * contactContrib.js - js functions for using contact contributor popup
 *
 * @package    lightrocket/contributor
 * @author     Jon Randy
 * @copyright  (c) 2012 OnAsia
 */

ContactContrib = function() {

    // checks to see if an email address is valid
    function validEmail(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 re.test(email);
   }

   function proxy(fn, context) {
        var args = Array.prototype.slice.call(arguments, 2);
      var prxy = function () {
            return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
        };
        return prxy;
   }


   // Contributor email view
   var ContribEmailView = Backbone.View.extend({

        initialize:function(options) {
            // update email model on text field changes
            this.$('input[type=text],textarea').change(proxy(this.updateModelField, this));
            // attempt to send the email on form submission
            this.$('form').submit(proxy(this.sendEmail, this));
            // attempt to send the email on form submission
            var that = this;
            // handle clicks on reset/cancel
            this.$('#btn_cancel_email').click(proxy(this.handleReset, this));
            // display form validation errors when necessary
            this.model.on('error', proxy(this.handleFieldErrors, this));
            // handle completion of a send attempt
            this.model.on('sendDone', proxy(this.handleSendResult, this));
        },

        updateModelField : function(e) {
            var el = $(e.target);
            this.model.set(el.attr('name'), el.val());
        },

        resetForm : function() {
            this.$('form')[0].reset();
        },

        handleReset : function() {
            this.trigger('reset', this);
            this.clearErrors();
            setTimeout(proxy(this.initAllFields, this), 250);
        },

        initAllFields : function(e) {
            var that = this;
            _.each(['fromName', 'fromEmail', 'subject', 'message', 'code'], function(v) {
                that.updateModelField({target:'[name='+v+']'});
            });
        },

        sendEmail : function(e) {
            e.preventDefault();
            if (!this.blocked) {
                this.blocked =true;
                this.model.send();
            }
        },

        handleFieldErrors : function(m, err) {
            this.showErrors(err.messages, err.fields);
            this.blocked = false;
        },

        handleSendResult : function(m, res) {
            this.blocked = false;
            if (res && res.errors && res.errors.length) {
                this.showErrors(res.errors, res.fields);
                this.updateCaptcha();
            } else {
                this.showErrors([],[]);
                this.updateCaptcha();
                this.trigger('sendSuccess', this, res);
            }
        },

        showErrors : function(errors, fields) {
            var that = this;
            this.clearErrors();
            _.each(fields, function(v) {
                that.$('[name='+v+']').prev('label').addClass('error');
            });
            this.$('#error_send_msg').html(errors.join('<br />'));
            this.focusFirstErrored();
        },

        clearErrors : function() {
            this.$('label[for]').removeClass('error');
            this.$('#error_send_msg').html('');
        },

        updateCaptcha : function() {
            var that = this;
            this.$('#image_code')
                .addClass('loading')
                .css('visibility','hidden');
            this.$('#image_code img')
                .attr('src', APP.baseURL+'contactcontrib/captchaimage?' + Math.random())
                .load(function() {
                    $(this).css('visibility','visible');
                    that.$('#image_code').removeClass('loading');
                });
        },

        focusFirstEmpty : function() {
            $(this.$('input:text,textarea').filter(function() { return $.trim($(this).val()) === ""; })[0]).focus().select();
        },

        focusFirstErrored : function() {
            $(this.$('label.error')[0]).next('input:text,textarea').focus().select();
        }



   });

    
   // the model for the email we will be sending
    var ContribEmail = Backbone.Model.extend({

        sendURL : 'contactcontrib/send',

        defaults : {
            contribID        :    0,
            fromName            :    '',
            fromEmail        :    '',
            relatesTo        :    '',
            relatesToLink    :    '',
            subject            :    '',
            message            :    '',
            code                :    ''
        },

        // check if the email is valid (checks all fields except security code which we can only check on server)
        hasErrors : function() {
            var errFields = [];
            var errMsgs = [];
            var check = _.extend({}, this.attributes);
            _.each(check, function(v, k, o) { if (k!=='contribID') o[k] = $.trim(v);});
            function addErr(field, type) {
                errFields.push(field);
                errMsgs.push(lang.contributors.sendMessageValidation[field][type]);
            }
            // required
            var that = this;
            _.each(['fromName', 'fromEmail', 'message', 'code'], function(f) {
                if (check[f]==='') addErr(f, 'required');
            }, that);
            // email address
            _.each(['fromEmail'], function(f) {
                if(!validEmail(check[f])) addErr(f, 'email');
            });
            errFields = _.uniq(errFields);
            errMsgs = _.uniq(errMsgs);
            if (errFields.length) {
                var ret = {fields:errFields, messages:errMsgs};
                this.trigger('error', this, ret);
                return ret;
            }
        },

        // attempt to send the email, events will fire to signal completion
        send : function() {
            var res = false;
            if (!this.hasErrors()) {
                var that = this;
                this.trigger('sendStart', this, this.attributes);
                $.ajax({
                    url            :    APP.baseURL+this.sendURL,
                    data            :    this.attributes,
                    type            :    'POST',
                    cache            :    false,
                    success        :    function(res) {
                        that.sendDone(res);
                    },
                    error            :    function() {
                        that.sendDone({errors:[lang.contributors.FailSendMessage]});
                    },
                    dataType        :    'json'
                });
                res = true;
            }
            return res;
        },

        // signal completion of sending
        sendDone : function(result) {
            this.trigger('sendDone', this, result);
        }

    });

    return {
        emailModel:ContribEmail,
        view:ContribEmailView
    };


}();


/*********************
Including file: contribMessenger.js
*********************/
/**
 * contribMessenger.js - js functions for launching and monitoring the contributor messenger
 *
 * @package    core
 * @author     Jon Randy
 * @copyright  (c) 2012 OnAsia
 */
    
ContribMessenger = function() {

    var _initialised = false;
    var _email = new ContactContrib.emailModel();

    var _view = false;
    var _form = false;

    jQuery.fn.center = function () {
        this.css("position","absolute");
        this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
        this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
        return this;
    };

    var _init = function() {
        if (!_initialised) {

            // add the form
            _getForm().addClass('hideMe').appendTo('body');

            _view = new ContactContrib.view({el:_form, model:_email});

            _view.on('reset', _hideForm);
            _view.on('sendSuccess', _announceSuccess);
            $('#close_email_form').on('click', _hideForm);

            _initialised = true;
        }
    };

    var _launch = function(contribID) {
        var related = (arguments.length>1) ? arguments[1] : {relatesTo:'', relatesToLink: ''};
        _init();
        _view.resetForm();
        _email.set('contribID', contribID);
        _email.set('fromName', $('input[name="fromName"]').val());
        _email.set('fromEmail', $('input[name="fromEmail"]').val());
        _email.set(related);
        _showForm();
    };

    var _showForm = function() {
        $(document).bind('keyup', _handleKeyUp);
        _form.center().show();
        _view.focusFirstEmpty();
    };

    var _hideForm = function() {
        var e = arguments.length ? arguments[0] : false;
        if (e && e.preventDefault) e.preventDefault();
        $(document).unbind('keyup', _handleKeyUp);
        _form.hide();
    };

    var _announceSuccess = function(view, result) {
        _hideForm();
        alert(lang.contributors.SuccessSendMessage.format(result));
    };

    var _handleKeyUp = function(e) {
        if (e.which==27) _hideForm();
    };

    var _getForm = function() {
        var html = '<div id="msg_form">';
        alert(lang.common.lbl_PleaseWait);
        $.ajax({
            url:APP.baseURL + 'contactcontrib/form',
            success:function(r){
                html += r.html;
            },
            type:'POST',
            cache:false,
            dataType:'json',
            async:false
        });
        alert('');
        html += '</div>';
        return _form = $(html).draggable({
            containment: $('div#container'),
            scroll: false,
            cancel: 'input, textarea, a'
        });
    };


    return {
        launch:_launch,
        mail:_email
    };

}();

/*********************
Including file: socialmedia.js
*********************/
/**
 * socialmedia.js - js functions relating to social media icons
 *
 * @package    core
 * @author     Tik Nipaporn
 * @copyright  (c) 2014 OnAsia
 */
(function() {
socialmedia = {    
    /**
     * setup for social media icons
     *
     * @return  void
     */
    _setup:function() {
        $('#pageContent').on("click", ".social_icons .popShare", function(){
            var d = new Date();
            window.open($(this).attr('href'),'sharer_'+d.getTime(),'toolbar=0,resizable=1,status=0,width=755,height=528');
            return false;
        });
    }
};
})();


$(socialmedia._setup);

/*********************
Including file: nicescroll.js
*********************/
/* jquery.nicescroll 3.6.8 InuYaksa*2015 MIT http://nicescroll.areaaperta.com */(function(f){"function"===typeof define&&define.amd?define(["jquery"],f):"object"===typeof exports?module.exports=f(require("jquery")):f(jQuery)})(function(f){var B=!1,F=!1,O=0,P=2E3,A=0,J=["webkit","ms","moz","o"],v=window.requestAnimationFrame||!1,w=window.cancelAnimationFrame||!1;if(!v)for(var Q in J){var G=J[Q];if(v=window[G+"RequestAnimationFrame"]){w=window[G+"CancelAnimationFrame"]||window[G+"CancelRequestAnimationFrame"];break}}var x=window.MutationObserver||window.WebKitMutationObserver||
!1,K={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",cursorwidth:"6px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:60,mousescrollstep:24,touchbehavior:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0},
disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:function(){var f=document.getElementsByTagName("script"),f=f.length?f[f.length-
1].src.split("?")[0]:"";return 0<f.split("/").length?f.split("/").slice(0,-1).join("/")+"/":""}(),preventmultitouchscrolling:!0,disablemutationobserver:!1},H=!1,R=function(){if(H)return H;var f=document.createElement("DIV"),c=f.style,k=navigator.userAgent,l=navigator.platform,d={haspointerlock:"pointerLockElement"in document||"webkitPointerLockElement"in document||"mozPointerLockElement"in document};d.isopera="opera"in window;d.isopera12=d.isopera&&"getUserMedia"in navigator;d.isoperamini="[object OperaMini]"===
Object.prototype.toString.call(window.operamini);d.isie="all"in document&&"attachEvent"in f&&!d.isopera;d.isieold=d.isie&&!("msInterpolationMode"in c);d.isie7=d.isie&&!d.isieold&&(!("documentMode"in document)||7==document.documentMode);d.isie8=d.isie&&"documentMode"in document&&8==document.documentMode;d.isie9=d.isie&&"performance"in window&&9==document.documentMode;d.isie10=d.isie&&"performance"in window&&10==document.documentMode;d.isie11="msRequestFullscreen"in f&&11<=document.documentMode;d.isieedge12=
navigator.userAgent.match(/Edge\/12\./);d.isieedge="msOverflowStyle"in f;d.ismodernie=d.isie11||d.isieedge;d.isie9mobile=/iemobile.9/i.test(k);d.isie9mobile&&(d.isie9=!1);d.isie7mobile=!d.isie9mobile&&d.isie7&&/iemobile/i.test(k);d.ismozilla="MozAppearance"in c;d.iswebkit="WebkitAppearance"in c;d.ischrome="chrome"in window;d.ischrome38=d.ischrome&&"touchAction"in c;d.ischrome22=!d.ischrome38&&d.ischrome&&d.haspointerlock;d.ischrome26=!d.ischrome38&&d.ischrome&&"transition"in c;d.cantouch="ontouchstart"in
document.documentElement||"ontouchstart"in window;d.hasw3ctouch=(window.PointerEvent||!1)&&(0<navigator.MaxTouchPoints||0<navigator.msMaxTouchPoints);d.hasmstouch=!d.hasw3ctouch&&(window.MSPointerEvent||!1);d.ismac=/^mac$/i.test(l);d.isios=d.cantouch&&/iphone|ipad|ipod/i.test(l);d.isios4=d.isios&&!("seal"in Object);d.isios7=d.isios&&"webkitHidden"in document;d.isios8=d.isios&&"hidden"in document;d.isandroid=/android/i.test(k);d.haseventlistener="addEventListener"in f;d.trstyle=!1;d.hastransform=!1;
d.hastranslate3d=!1;d.transitionstyle=!1;d.hastransition=!1;d.transitionend=!1;l=["transform","msTransform","webkitTransform","MozTransform","OTransform"];for(k=0;k<l.length;k++)if(void 0!==c[l[k]]){d.trstyle=l[k];break}d.hastransform=!!d.trstyle;d.hastransform&&(c[d.trstyle]="translate3d(1px,2px,3px)",d.hastranslate3d=/translate3d/.test(c[d.trstyle]));d.transitionstyle=!1;d.prefixstyle="";d.transitionend=!1;for(var l="transition webkitTransition msTransition MozTransition OTransition OTransition KhtmlTransition".split(" "),
q=" -webkit- -ms- -moz- -o- -o -khtml-".split(" "),t="transitionend webkitTransitionEnd msTransitionEnd transitionend otransitionend oTransitionEnd KhtmlTransitionEnd".split(" "),k=0;k<l.length;k++)if(l[k]in c){d.transitionstyle=l[k];d.prefixstyle=q[k];d.transitionend=t[k];break}d.ischrome26&&(d.prefixstyle=q[1]);d.hastransition=d.transitionstyle;a:{k=["grab","-webkit-grab","-moz-grab"];if(d.ischrome&&!d.ischrome38||d.isie)k=[];for(l=0;l<k.length;l++)if(q=k[l],c.cursor=q,c.cursor==q){c=q;break a}c=
"url(//patriciaportfolio.googlecode.com/files/openhand.cur),n-resize"}d.cursorgrabvalue=c;d.hasmousecapture="setCapture"in f;d.hasMutationObserver=!1!==x;return H=d},S=function(h,c){function k(){var b=a.doc.css(e.trstyle);return b&&"matrix"==b.substr(0,6)?b.replace(/^.*\((.*)\)$/g,"$1").replace(/px/g,"").split(/, +/):!1}function l(){var b=a.win;if("zIndex"in b)return b.zIndex();for(;0<b.length&&9!=b[0].nodeType;){var g=b.css("zIndex");if(!isNaN(g)&&0!=g)return parseInt(g);b=b.parent()}return!1}function d(b,
g,u){g=b.css(g);b=parseFloat(g);return isNaN(b)?(b=z[g]||0,u=3==b?u?a.win.outerHeight()-a.win.innerHeight():a.win.outerWidth()-a.win.innerWidth():1,a.isie8&&b&&(b+=1),u?b:0):b}function q(b,g,u,c){a._bind(b,g,function(a){a=a?a:window.event;var c={original:a,target:a.target||a.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==a.type?0:1,deltaX:0,deltaZ:0,preventDefault:function(){a.preventDefault?a.preventDefault():a.returnValue=!1;return!1},stopImmediatePropagation:function(){a.stopImmediatePropagation?
a.stopImmediatePropagation():a.cancelBubble=!0}};"mousewheel"==g?(a.wheelDeltaX&&(c.deltaX=-.025*a.wheelDeltaX),a.wheelDeltaY&&(c.deltaY=-.025*a.wheelDeltaY),c.deltaY||c.deltaX||(c.deltaY=-.025*a.wheelDelta)):c.deltaY=a.detail;return u.call(b,c)},c)}function t(b,g,c){var d,e;0==b.deltaMode?(d=-Math.floor(a.opt.mousescrollstep/54*b.deltaX),e=-Math.floor(a.opt.mousescrollstep/54*b.deltaY)):1==b.deltaMode&&(d=-Math.floor(b.deltaX*a.opt.mousescrollstep),e=-Math.floor(b.deltaY*a.opt.mousescrollstep));
g&&a.opt.oneaxismousemode&&0==d&&e&&(d=e,e=0,c&&(0>d?a.getScrollLeft()>=a.page.maxw:0>=a.getScrollLeft())&&(e=d,d=0));a.isrtlmode&&(d=-d);d&&(a.scrollmom&&a.scrollmom.stop(),a.lastdeltax+=d,a.debounced("mousewheelx",function(){var b=a.lastdeltax;a.lastdeltax=0;a.rail.drag||a.doScrollLeftBy(b)},15));if(e){if(a.opt.nativeparentscrolling&&c&&!a.ispage&&!a.zoomactive)if(0>e){if(a.getScrollTop()>=a.page.maxh)return!0}else if(0>=a.getScrollTop())return!0;a.scrollmom&&a.scrollmom.stop();a.lastdeltay+=e;
a.synched("mousewheely",function(){var b=a.lastdeltay;a.lastdeltay=0;a.rail.drag||a.doScrollBy(b)},15)}b.stopImmediatePropagation();return b.preventDefault()}var a=this;this.version="3.6.8";this.name="nicescroll";this.me=c;this.opt={doc:f("body"),win:!1};f.extend(this.opt,K);this.opt.snapbackspeed=80;if(h)for(var r in a.opt)void 0!==h[r]&&(a.opt[r]=h[r]);a.opt.disablemutationobserver&&(x=!1);this.iddoc=(this.doc=a.opt.doc)&&this.doc[0]?this.doc[0].id||"":"";this.ispage=/^BODY|HTML/.test(a.opt.win?
a.opt.win[0].nodeName:this.doc[0].nodeName);this.haswrapper=!1!==a.opt.win;this.win=a.opt.win||(this.ispage?f(window):this.doc);this.docscroll=this.ispage&&!this.haswrapper?f(window):this.win;this.body=f("body");this.iframe=this.isfixed=this.viewport=!1;this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName;this.istextarea="TEXTAREA"==this.win[0].nodeName;this.forcescreen=!1;this.canshowonmouseevent="scroll"!=a.opt.autohidemode;this.page=this.view=this.onzoomout=this.onzoomin=
this.onscrollcancel=this.onscrollend=this.onscrollstart=this.onclick=this.ongesturezoom=this.onkeypress=this.onmousewheel=this.onmousemove=this.onmouseup=this.onmousedown=!1;this.scroll={x:0,y:0};this.scrollratio={x:0,y:0};this.cursorheight=20;this.scrollvaluemax=0;if("auto"==this.opt.rtlmode){r=this.win[0]==window?this.body:this.win;var p=r.css("writing-mode")||r.css("-webkit-writing-mode")||r.css("-ms-writing-mode")||r.css("-moz-writing-mode");"horizontal-tb"==p||"lr-tb"==p||""==p?(this.isrtlmode=
"rtl"==r.css("direction"),this.isvertical=!1):(this.isrtlmode="vertical-rl"==p||"tb"==p||"tb-rl"==p||"rl-tb"==p,this.isvertical="vertical-rl"==p||"tb"==p||"tb-rl"==p)}else this.isrtlmode=!0===this.opt.rtlmode,this.isvertical=!1;this.observerbody=this.observerremover=this.observer=this.scrollmom=this.scrollrunning=!1;do this.id="ascrail"+P++;while(document.getElementById(this.id));this.hasmousefocus=this.hasfocus=this.zoomactive=this.zoom=this.selectiondrag=this.cursorfreezed=this.cursor=this.rail=
!1;this.visibility=!0;this.hidden=this.locked=this.railslocked=!1;this.cursoractive=!0;this.wheelprevented=!1;this.overflowx=a.opt.overflowx;this.overflowy=a.opt.overflowy;this.nativescrollingarea=!1;this.checkarea=0;this.events=[];this.saved={};this.delaylist={};this.synclist={};this.lastdeltay=this.lastdeltax=0;this.detected=R();var e=f.extend({},this.detected);this.ishwscroll=(this.canhwscroll=e.hastransform&&a.opt.hwacceleration)&&a.haswrapper;this.hasreversehr=this.isrtlmode?this.isvertical?
!(e.iswebkit||e.isie||e.isie11):!(e.iswebkit||e.isie&&!e.isie10&&!e.isie11):!1;this.istouchcapable=!1;e.cantouch||!e.hasw3ctouch&&!e.hasmstouch?!e.cantouch||e.isios||e.isandroid||!e.iswebkit&&!e.ismozilla||(this.istouchcapable=!0):this.istouchcapable=!0;a.opt.enablemouselockapi||(e.hasmousecapture=!1,e.haspointerlock=!1);this.debounced=function(b,g,c){a&&(a.delaylist[b]||(g.call(a),a.delaylist[b]={h:v(function(){a.delaylist[b].fn.call(a);a.delaylist[b]=!1},c)}),a.delaylist[b].fn=g)};var I=!1;this.synched=
function(b,g){a.synclist[b]=g;(function(){I||(v(function(){if(a){I=!1;for(var b in a.synclist){var g=a.synclist[b];g&&g.call(a);a.synclist[b]=!1}}}),I=!0)})();return b};this.unsynched=function(b){a.synclist[b]&&(a.synclist[b]=!1)};this.css=function(b,g){for(var c in g)a.saved.css.push([b,c,b.css(c)]),b.css(c,g[c])};this.scrollTop=function(b){return void 0===b?a.getScrollTop():a.setScrollTop(b)};this.scrollLeft=function(b){return void 0===b?a.getScrollLeft():a.setScrollLeft(b)};var D=function(a,g,
c,d,e,f,k){this.st=a;this.ed=g;this.spd=c;this.p1=d||0;this.p2=e||1;this.p3=f||0;this.p4=k||1;this.ts=(new Date).getTime();this.df=this.ed-this.st};D.prototype={B2:function(a){return 3*a*a*(1-a)},B3:function(a){return 3*a*(1-a)*(1-a)},B4:function(a){return(1-a)*(1-a)*(1-a)},getNow:function(){var a=1-((new Date).getTime()-this.ts)/this.spd,g=this.B2(a)+this.B3(a)+this.B4(a);return 0>a?this.ed:this.st+Math.round(this.df*g)},update:function(a,g){this.st=this.getNow();this.ed=a;this.spd=g;this.ts=(new Date).getTime();
this.df=this.ed-this.st;return this}};if(this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"};e.hastranslate3d&&e.isios&&this.doc.css("-webkit-backface-visibility","hidden");this.getScrollTop=function(b){if(!b){if(b=k())return 16==b.length?-b[13]:-b[5];if(a.timerscroll&&a.timerscroll.bz)return a.timerscroll.bz.getNow()}return a.doc.translate.y};this.getScrollLeft=function(b){if(!b){if(b=k())return 16==b.length?-b[12]:-b[4];if(a.timerscroll&&a.timerscroll.bh)return a.timerscroll.bh.getNow()}return a.doc.translate.x};
this.notifyScrollEvent=function(a){var g=document.createEvent("UIEvents");g.initUIEvent("scroll",!1,!0,window,1);g.niceevent=!0;a.dispatchEvent(g)};var y=this.isrtlmode?1:-1;e.hastranslate3d&&a.opt.enabletranslate3d?(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle,
"translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])}):(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])})}else this.getScrollTop=
function(){return a.docscroll.scrollTop()},this.setScrollTop=function(b){return setTimeout(function(){a&&a.docscroll.scrollTop(b)},1)},this.getScrollLeft=function(){return a.hasreversehr?a.detected.ismozilla?a.page.maxw-Math.abs(a.docscroll.scrollLeft()):a.page.maxw-a.docscroll.scrollLeft():a.docscroll.scrollLeft()},this.setScrollLeft=function(b){return setTimeout(function(){if(a)return a.hasreversehr&&(b=a.detected.ismozilla?-(a.page.maxw-b):a.page.maxw-b),a.docscroll.scrollLeft(b)},1)};this.getTarget=
function(a){return a?a.target?a.target:a.srcElement?a.srcElement:!1:!1};this.hasParent=function(a,g){if(!a)return!1;for(var c=a.target||a.srcElement||a||!1;c&&c.id!=g;)c=c.parentNode||!1;return!1!==c};var z={thin:1,medium:3,thick:5};this.getDocumentScrollOffset=function(){return{top:window.pageYOffset||document.documentElement.scrollTop,left:window.pageXOffset||document.documentElement.scrollLeft}};this.getOffset=function(){if(a.isfixed){var b=a.win.offset(),g=a.getDocumentScrollOffset();b.top-=g.top;
b.left-=g.left;return b}b=a.win.offset();if(!a.viewport)return b;g=a.viewport.offset();return{top:b.top-g.top,left:b.left-g.left}};this.updateScrollBar=function(b){var g,c,e;if(a.ishwscroll)a.rail.css({height:a.win.innerHeight()-(a.opt.railpadding.top+a.opt.railpadding.bottom)}),a.railh&&a.railh.css({width:a.win.innerWidth()-(a.opt.railpadding.left+a.opt.railpadding.right)});else{var f=a.getOffset();g=f.top;c=f.left-(a.opt.railpadding.left+a.opt.railpadding.right);g+=d(a.win,"border-top-width",!0);
c+=a.rail.align?a.win.outerWidth()-d(a.win,"border-right-width")-a.rail.width:d(a.win,"border-left-width");if(e=a.opt.railoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);a.railslocked||a.rail.css({top:g,left:c,height:(b?b.h:a.win.innerHeight())-(a.opt.railpadding.top+a.opt.railpadding.bottom)});a.zoom&&a.zoom.css({top:g+1,left:1==a.rail.align?c-20:c+a.rail.width+4});if(a.railh&&!a.railslocked){g=f.top;c=f.left;if(e=a.opt.railhoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);b=a.railh.align?g+d(a.win,"border-top-width",
!0)+a.win.innerHeight()-a.railh.height:g+d(a.win,"border-top-width",!0);c+=d(a.win,"border-left-width");a.railh.css({top:b-(a.opt.railpadding.top+a.opt.railpadding.bottom),left:c,width:a.railh.width})}}};this.doRailClick=function(b,g,c){var d;a.railslocked||(a.cancelEvent(b),g?(g=c?a.doScrollLeft:a.doScrollTop,d=c?(b.pageX-a.railh.offset().left-a.cursorwidth/2)*a.scrollratio.x:(b.pageY-a.rail.offset().top-a.cursorheight/2)*a.scrollratio.y,g(d)):(g=c?a.doScrollLeftBy:a.doScrollBy,d=c?a.scroll.x:a.scroll.y,
b=c?b.pageX-a.railh.offset().left:b.pageY-a.rail.offset().top,c=c?a.view.w:a.view.h,g(d>=b?c:-c)))};a.hasanimationframe=v;a.hascancelanimationframe=w;a.hasanimationframe?a.hascancelanimationframe||(w=function(){a.cancelAnimationFrame=!0}):(v=function(a){return setTimeout(a,15-Math.floor(+new Date/1E3)%16)},w=clearTimeout);this.init=function(){a.saved.css=[];if(e.isie7mobile||e.isoperamini)return!0;e.hasmstouch&&a.css(a.ispage?f("html"):a.win,{_touchaction:"none"});var b=e.ismodernie||e.isie10?{"-ms-overflow-style":"none"}:
{"overflow-y":"hidden"};a.zindex="auto";a.zindex=a.ispage||"auto"!=a.opt.zindex?a.opt.zindex:l()||"auto";!a.ispage&&"auto"!=a.zindex&&a.zindex>A&&(A=a.zindex);a.isie&&0==a.zindex&&"auto"==a.opt.zindex&&(a.zindex="auto");if(!a.ispage||!e.cantouch&&!e.isieold&&!e.isie9mobile){var c=a.docscroll;a.ispage&&(c=a.haswrapper?a.win:a.doc);e.isie9mobile||a.css(c,b);a.ispage&&e.isie7&&("BODY"==a.doc[0].nodeName?a.css(f("html"),{"overflow-y":"hidden"}):"HTML"==a.doc[0].nodeName&&a.css(f("body"),b));!e.isios||
a.ispage||a.haswrapper||a.css(f("body"),{"-webkit-overflow-scrolling":"touch"});var d=f(document.createElement("div"));d.css({position:"relative",top:0,"float":"right",width:a.opt.cursorwidth,height:0,"background-color":a.opt.cursorcolor,border:a.opt.cursorborder,"background-clip":"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,"border-radius":a.opt.cursorborderradius});d.hborder=parseFloat(d.outerHeight()-d.innerHeight());d.addClass("nicescroll-cursors");
a.cursor=d;var m=f(document.createElement("div"));m.attr("id",a.id);m.addClass("nicescroll-rails nicescroll-rails-vr");var k,h,p=["left","right","top","bottom"],L;for(L in p)h=p[L],(k=a.opt.railpadding[h])?m.css("padding-"+h,k+"px"):a.opt.railpadding[h]=0;m.append(d);m.width=Math.max(parseFloat(a.opt.cursorwidth),d.outerWidth());m.css({width:m.width+"px",zIndex:a.zindex,background:a.opt.background,cursor:"default"});m.visibility=!0;m.scrollable=!0;m.align="left"==a.opt.railalign?0:1;a.rail=m;d=a.rail.drag=
!1;!a.opt.boxzoom||a.ispage||e.isieold||(d=document.createElement("div"),a.bind(d,"click",a.doZoom),a.bind(d,"mouseenter",function(){a.zoom.css("opacity",a.opt.cursoropacitymax)}),a.bind(d,"mouseleave",function(){a.zoom.css("opacity",a.opt.cursoropacitymin)}),a.zoom=f(d),a.zoom.css({cursor:"pointer",zIndex:a.zindex,backgroundImage:"url("+a.opt.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0px 0px"}),a.opt.dblclickzoom&&a.bind(a.win,"dblclick",a.doZoom),e.cantouch&&a.opt.gesturezoom&&
(a.ongesturezoom=function(b){1.5<b.scale&&a.doZoomIn(b);.8>b.scale&&a.doZoomOut(b);return a.cancelEvent(b)},a.bind(a.win,"gestureend",a.ongesturezoom)));a.railh=!1;var n;a.opt.horizrailenabled&&(a.css(c,{overflowX:"hidden"}),d=f(document.createElement("div")),d.css({position:"absolute",top:0,height:a.opt.cursorwidth,width:0,backgroundColor:a.opt.cursorcolor,border:a.opt.cursorborder,backgroundClip:"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,
"border-radius":a.opt.cursorborderradius}),e.isieold&&d.css("overflow","hidden"),d.wborder=parseFloat(d.outerWidth()-d.innerWidth()),d.addClass("nicescroll-cursors"),a.cursorh=d,n=f(document.createElement("div")),n.attr("id",a.id+"-hr"),n.addClass("nicescroll-rails nicescroll-rails-hr"),n.height=Math.max(parseFloat(a.opt.cursorwidth),d.outerHeight()),n.css({height:n.height+"px",zIndex:a.zindex,background:a.opt.background}),n.append(d),n.visibility=!0,n.scrollable=!0,n.align="top"==a.opt.railvalign?
0:1,a.railh=n,a.railh.drag=!1);a.ispage?(m.css({position:"fixed",top:0,height:"100%"}),m.align?m.css({right:0}):m.css({left:0}),a.body.append(m),a.railh&&(n.css({position:"fixed",left:0,width:"100%"}),n.align?n.css({bottom:0}):n.css({top:0}),a.body.append(n))):(a.ishwscroll?("static"==a.win.css("position")&&a.css(a.win,{position:"relative"}),c="HTML"==a.win[0].nodeName?a.body:a.win,f(c).scrollTop(0).scrollLeft(0),a.zoom&&(a.zoom.css({position:"absolute",top:1,right:0,"margin-right":m.width+4}),c.append(a.zoom)),
m.css({position:"absolute",top:0}),m.align?m.css({right:0}):m.css({left:0}),c.append(m),n&&(n.css({position:"absolute",left:0,bottom:0}),n.align?n.css({bottom:0}):n.css({top:0}),c.append(n))):(a.isfixed="fixed"==a.win.css("position"),c=a.isfixed?"fixed":"absolute",a.isfixed||(a.viewport=a.getViewport(a.win[0])),a.viewport&&(a.body=a.viewport,0==/fixed|absolute/.test(a.viewport.css("position"))&&a.css(a.viewport,{position:"relative"})),m.css({position:c}),a.zoom&&a.zoom.css({position:c}),a.updateScrollBar(),
a.body.append(m),a.zoom&&a.body.append(a.zoom),a.railh&&(n.css({position:c}),a.body.append(n))),e.isios&&a.css(a.win,{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),e.isie&&a.opt.disableoutline&&a.win.attr("hideFocus","true"),e.iswebkit&&a.opt.disableoutline&&a.win.css("outline","none"));!1===a.opt.autohidemode?(a.autohidedom=!1,a.rail.css({opacity:a.opt.cursoropacitymax}),a.railh&&a.railh.css({opacity:a.opt.cursoropacitymax})):!0===a.opt.autohidemode||"leave"===a.opt.autohidemode?
(a.autohidedom=f().add(a.rail),e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursor)),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh)),a.railh&&e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"scroll"==a.opt.autohidemode?(a.autohidedom=f().add(a.rail),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh))):"cursor"==a.opt.autohidemode?(a.autohidedom=f().add(a.cursor),a.railh&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"hidden"==a.opt.autohidemode&&(a.autohidedom=!1,a.hide(),a.railslocked=
!1);if(e.isie9mobile)a.scrollmom=new M(a),a.onmangotouch=function(){var b=a.getScrollTop(),c=a.getScrollLeft();if(b==a.scrollmom.lastscrolly&&c==a.scrollmom.lastscrollx)return!0;var g=b-a.mangotouch.sy,d=c-a.mangotouch.sx;if(0!=Math.round(Math.sqrt(Math.pow(d,2)+Math.pow(g,2)))){var e=0>g?-1:1,f=0>d?-1:1,u=+new Date;a.mangotouch.lazy&&clearTimeout(a.mangotouch.lazy);80<u-a.mangotouch.tm||a.mangotouch.dry!=e||a.mangotouch.drx!=f?(a.scrollmom.stop(),a.scrollmom.reset(c,b),a.mangotouch.sy=b,a.mangotouch.ly=
b,a.mangotouch.sx=c,a.mangotouch.lx=c,a.mangotouch.dry=e,a.mangotouch.drx=f,a.mangotouch.tm=u):(a.scrollmom.stop(),a.scrollmom.update(a.mangotouch.sx-d,a.mangotouch.sy-g),a.mangotouch.tm=u,g=Math.max(Math.abs(a.mangotouch.ly-b),Math.abs(a.mangotouch.lx-c)),a.mangotouch.ly=b,a.mangotouch.lx=c,2<g&&(a.mangotouch.lazy=setTimeout(function(){a.mangotouch.lazy=!1;a.mangotouch.dry=0;a.mangotouch.drx=0;a.mangotouch.tm=0;a.scrollmom.doMomentum(30)},100)))}},m=a.getScrollTop(),n=a.getScrollLeft(),a.mangotouch=
{sy:m,ly:m,dry:0,sx:n,lx:n,drx:0,lazy:!1,tm:0},a.bind(a.docscroll,"scroll",a.onmangotouch);else{if(e.cantouch||a.istouchcapable||a.opt.touchbehavior||e.hasmstouch){a.scrollmom=new M(a);a.ontouchstart=function(b){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;a.hasmoving=!1;if(!a.railslocked){var c;if(e.hasmstouch)for(c=b.target?b.target:!1;c;){var g=f(c).getNiceScroll();if(0<g.length&&g[0].me==a.me)break;if(0<g.length)return!1;if("DIV"==c.nodeName&&c.id==a.id)break;c=c.parentNode?
c.parentNode:!1}a.cancelScroll();if((c=a.getTarget(b))&&/INPUT/i.test(c.nodeName)&&/range/i.test(c.type))return a.stopPropagation(b);!("clientX"in b)&&"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);a.forcescreen&&(g=b,b={original:b.original?b.original:b},b.clientX=g.screenX,b.clientY=g.screenY);a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,st:a.getScrollTop(),sl:a.getScrollLeft(),pt:2,dl:!1};if(a.ispage||!a.opt.directionlockdeadzone)a.rail.drag.dl=
"f";else{var g=f(window).width(),d=f(window).height(),d=Math.max(0,Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-d),g=Math.max(0,Math.max(document.body.scrollWidth,document.documentElement.scrollWidth)-g);a.rail.drag.ck=!a.rail.scrollable&&a.railh.scrollable?0<d?"v":!1:a.rail.scrollable&&!a.railh.scrollable?0<g?"h":!1:!1;a.rail.drag.ck||(a.rail.drag.dl="f")}a.opt.touchbehavior&&a.isiframe&&e.isie&&(g=a.win.position(),a.rail.drag.x+=g.left,a.rail.drag.y+=g.top);a.hasmoving=
!1;a.lastmouseup=!1;a.scrollmom.reset(b.clientX,b.clientY);if(!e.cantouch&&!this.istouchcapable&&!b.pointerType){if(!c||!/INPUT|SELECT|TEXTAREA/i.test(c.nodeName))return!a.ispage&&e.hasmousecapture&&c.setCapture(),a.opt.touchbehavior?(c.onclick&&!c._onclick&&(c._onclick=c.onclick,c.onclick=function(b){if(a.hasmoving)return!1;c._onclick.call(this,b)}),a.cancelEvent(b)):a.stopPropagation(b);/SUBMIT|CANCEL|BUTTON/i.test(f(c).attr("type"))&&(pc={tg:c,click:!1},a.preventclick=pc)}}};a.ontouchend=function(b){if(!a.rail.drag)return!0;
if(2==a.rail.drag.pt){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;a.scrollmom.doMomentum();a.rail.drag=!1;if(a.hasmoving&&(a.lastmouseup=!0,a.hideCursor(),e.hasmousecapture&&document.releaseCapture(),!e.cantouch))return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmouseup(b)};var q=a.opt.touchbehavior&&a.isiframe&&!e.hasmousecapture;a.ontouchmove=function(b,c){if(!a.rail.drag||b.targetTouches&&a.opt.preventmultitouchscrolling&&1<b.targetTouches.length||b.pointerType&&
2!=b.pointerType&&"touch"!=b.pointerType)return!1;if(2==a.rail.drag.pt){if(e.cantouch&&e.isios&&void 0===b.original)return!0;a.hasmoving=!0;a.preventclick&&!a.preventclick.click&&(a.preventclick.click=a.preventclick.tg.onclick||!1,a.preventclick.tg.onclick=a.onpreventclick);b=f.extend({original:b},b);"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);if(a.forcescreen){var g=b;b={original:b.original?b.original:b};b.clientX=g.screenX;b.clientY=g.screenY}var d,
g=d=0;q&&!c&&(d=a.win.position(),g=-d.left,d=-d.top);var u=b.clientY+d;d=u-a.rail.drag.y;var m=b.clientX+g,k=m-a.rail.drag.x,h=a.rail.drag.st-d;a.ishwscroll&&a.opt.bouncescroll?0>h?h=Math.round(h/2):h>a.page.maxh&&(h=a.page.maxh+Math.round((h-a.page.maxh)/2)):(0>h&&(u=h=0),h>a.page.maxh&&(h=a.page.maxh,u=0));var l;a.railh&&a.railh.scrollable&&(l=a.isrtlmode?k-a.rail.drag.sl:a.rail.drag.sl-k,a.ishwscroll&&a.opt.bouncescroll?0>l?l=Math.round(l/2):l>a.page.maxw&&(l=a.page.maxw+Math.round((l-a.page.maxw)/
2)):(0>l&&(m=l=0),l>a.page.maxw&&(l=a.page.maxw,m=0)));g=!1;if(a.rail.drag.dl)g=!0,"v"==a.rail.drag.dl?l=a.rail.drag.sl:"h"==a.rail.drag.dl&&(h=a.rail.drag.st);else{d=Math.abs(d);var k=Math.abs(k),C=a.opt.directionlockdeadzone;if("v"==a.rail.drag.ck){if(d>C&&k<=.3*d)return a.rail.drag=!1,!0;k>C&&(a.rail.drag.dl="f",f("body").scrollTop(f("body").scrollTop()))}else if("h"==a.rail.drag.ck){if(k>C&&d<=.3*k)return a.rail.drag=!1,!0;d>C&&(a.rail.drag.dl="f",f("body").scrollLeft(f("body").scrollLeft()))}}a.synched("touchmove",
function(){a.rail.drag&&2==a.rail.drag.pt&&(a.prepareTransition&&a.prepareTransition(0),a.rail.scrollable&&a.setScrollTop(h),a.scrollmom.update(m,u),a.railh&&a.railh.scrollable?(a.setScrollLeft(l),a.showCursor(h,l)):a.showCursor(h),e.isie10&&document.selection.clear())});e.ischrome&&a.istouchcapable&&(g=!1);if(g)return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmousemove(b)}}a.onmousedown=function(b,c){if(!a.rail.drag||1==a.rail.drag.pt){if(a.railslocked)return a.cancelEvent(b);a.cancelScroll();
a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,pt:1,hr:!!c};var g=a.getTarget(b);!a.ispage&&e.hasmousecapture&&g.setCapture();a.isiframe&&!e.hasmousecapture&&(a.saved.csspointerevents=a.doc.css("pointer-events"),a.css(a.doc,{"pointer-events":"none"}));a.hasmoving=!1;return a.cancelEvent(b)}};a.onmouseup=function(b){if(a.rail.drag){if(1!=a.rail.drag.pt)return!0;e.hasmousecapture&&document.releaseCapture();a.isiframe&&!e.hasmousecapture&&a.doc.css("pointer-events",a.saved.csspointerevents);
a.rail.drag=!1;a.hasmoving&&a.triggerScrollEnd();return a.cancelEvent(b)}};a.onmousemove=function(b){if(a.rail.drag){if(1==a.rail.drag.pt){if(e.ischrome&&0==b.which)return a.onmouseup(b);a.cursorfreezed=!0;a.hasmoving=!0;if(a.rail.drag.hr){a.scroll.x=a.rail.drag.sx+(b.clientX-a.rail.drag.x);0>a.scroll.x&&(a.scroll.x=0);var c=a.scrollvaluemaxw;a.scroll.x>c&&(a.scroll.x=c)}else a.scroll.y=a.rail.drag.sy+(b.clientY-a.rail.drag.y),0>a.scroll.y&&(a.scroll.y=0),c=a.scrollvaluemax,a.scroll.y>c&&(a.scroll.y=
c);a.synched("mousemove",function(){a.rail.drag&&1==a.rail.drag.pt&&(a.showCursor(),a.rail.drag.hr?a.hasreversehr?a.doScrollLeft(a.scrollvaluemaxw-Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollLeft(Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollTop(Math.round(a.scroll.y*a.scrollratio.y),a.opt.cursordragspeed))});return a.cancelEvent(b)}}else a.checkarea=0};if(e.cantouch||a.opt.touchbehavior)a.onpreventclick=function(b){if(a.preventclick)return a.preventclick.tg.onclick=
a.preventclick.click,a.preventclick=!1,a.cancelEvent(b)},a.bind(a.win,"mousedown",a.ontouchstart),a.onclick=e.isios?!1:function(b){return a.lastmouseup?(a.lastmouseup=!1,a.cancelEvent(b)):!0},a.opt.grabcursorenabled&&e.cursorgrabvalue&&(a.css(a.ispage?a.doc:a.win,{cursor:e.cursorgrabvalue}),a.css(a.rail,{cursor:e.cursorgrabvalue}));else{var r=function(b){if(a.selectiondrag){if(b){var c=a.win.outerHeight();b=b.pageY-a.selectiondrag.top;0<b&&b<c&&(b=0);b>=c&&(b-=c);a.selectiondrag.df=b}0!=a.selectiondrag.df&&
(a.doScrollBy(2*-Math.floor(a.selectiondrag.df/6)),a.debounced("doselectionscroll",function(){r()},50))}};a.hasTextSelected="getSelection"in document?function(){return 0<document.getSelection().rangeCount}:"selection"in document?function(){return"None"!=document.selection.type}:function(){return!1};a.onselectionstart=function(b){a.ispage||(a.selectiondrag=a.win.offset())};a.onselectionend=function(b){a.selectiondrag=!1};a.onselectiondrag=function(b){a.selectiondrag&&a.hasTextSelected()&&a.debounced("selectionscroll",
function(){r(b)},250)}}e.hasw3ctouch?(a.css(a.rail,{"touch-action":"none"}),a.css(a.cursor,{"touch-action":"none"}),a.bind(a.win,"pointerdown",a.ontouchstart),a.bind(document,"pointerup",a.ontouchend),a.bind(document,"pointermove",a.ontouchmove)):e.hasmstouch?(a.css(a.rail,{"-ms-touch-action":"none"}),a.css(a.cursor,{"-ms-touch-action":"none"}),a.bind(a.win,"MSPointerDown",a.ontouchstart),a.bind(document,"MSPointerUp",a.ontouchend),a.bind(document,"MSPointerMove",a.ontouchmove),a.bind(a.cursor,"MSGestureHold",
function(a){a.preventDefault()}),a.bind(a.cursor,"contextmenu",function(a){a.preventDefault()})):this.istouchcapable&&(a.bind(a.win,"touchstart",a.ontouchstart),a.bind(document,"touchend",a.ontouchend),a.bind(document,"touchcancel",a.ontouchend),a.bind(document,"touchmove",a.ontouchmove));if(a.opt.cursordragontouch||!e.cantouch&&!a.opt.touchbehavior)a.rail.css({cursor:"default"}),a.railh&&a.railh.css({cursor:"default"}),a.jqbind(a.rail,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1;
a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.rail,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.rail,"click",function(b){a.doRailClick(b,!1,!1)}),a.bind(a.rail,"dblclick",function(b){a.doRailClick(b,!0,!1)}),a.bind(a.cursor,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursor,"dblclick",function(b){a.cancelEvent(b)})),a.railh&&(a.jqbind(a.railh,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1;a.canshowonmouseevent&&
a.showCursor();a.rail.active=!0}),a.jqbind(a.railh,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.railh,"click",function(b){a.doRailClick(b,!1,!0)}),a.bind(a.railh,"dblclick",function(b){a.doRailClick(b,!0,!0)}),a.bind(a.cursorh,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursorh,"dblclick",function(b){a.cancelEvent(b)})));e.cantouch||a.opt.touchbehavior?(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.ontouchend),a.bind(document,"mousemove",
a.ontouchmove),a.onclick&&a.bind(document,"click",a.onclick),a.opt.cursordragontouch?(a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.cursorh&&a.bind(a.cursorh,"mousedown",function(b){a.onmousedown(b,!0)}),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onmouseup)):(a.bind(a.rail,"mousedown",function(a){a.preventDefault()}),a.railh&&a.bind(a.railh,"mousedown",function(a){a.preventDefault()}))):(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.onmouseup),a.bind(document,
"mousemove",a.onmousemove),a.onclick&&a.bind(document,"click",a.onclick),a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.railh&&(a.bind(a.cursorh,"mousedown",function(b){a.onmousedown(b,!0)}),a.bind(a.cursorh,"mouseup",a.onmouseup)),!a.ispage&&a.opt.enablescrollonselection&&(a.bind(a.win[0],"mousedown",a.onselectionstart),a.bind(document,"mouseup",a.onselectionend),a.bind(a.cursor,"mouseup",a.onselectionend),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onselectionend),
a.bind(document,"mousemove",a.onselectiondrag)),a.zoom&&(a.jqbind(a.zoom,"mouseenter",function(){a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.zoom,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()})));a.opt.enablemousewheel&&(a.isiframe||a.mousewheel(e.isie&&a.ispage?document:a.win,a.onmousewheel),a.mousewheel(a.rail,a.onmousewheel),a.railh&&a.mousewheel(a.railh,a.onmousewheelhr));a.ispage||e.cantouch||/HTML|^BODY/.test(a.win[0].nodeName)||(a.win.attr("tabindex")||
a.win.attr({tabindex:O++}),a.jqbind(a.win,"focus",function(b){B=a.getTarget(b).id||!0;a.hasfocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,"blur",function(b){B=!1;a.hasfocus=!1}),a.jqbind(a.win,"mouseenter",function(b){F=a.getTarget(b).id||!0;a.hasmousefocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,"mouseleave",function(){F=!1;a.hasmousefocus=!1;a.rail.drag||a.hideCursor()}))}a.onkeypress=function(b){if(a.railslocked&&0==a.page.maxh)return!0;b=b?b:window.e;var c=
a.getTarget(b);if(c&&/INPUT|TEXTAREA|SELECT|OPTION/.test(c.nodeName)&&(!c.getAttribute("type")&&!c.type||!/submit|button|cancel/i.tp)||f(c).attr("contenteditable"))return!0;if(a.hasfocus||a.hasmousefocus&&!B||a.ispage&&!B&&!F){c=b.keyCode;if(a.railslocked&&27!=c)return a.cancelEvent(b);var g=b.ctrlKey||!1,d=b.shiftKey||!1,e=!1;switch(c){case 38:case 63233:a.doScrollBy(72);e=!0;break;case 40:case 63235:a.doScrollBy(-72);e=!0;break;case 37:case 63232:a.railh&&(g?a.doScrollLeft(0):a.doScrollLeftBy(72),
e=!0);break;case 39:case 63234:a.railh&&(g?a.doScrollLeft(a.page.maxw):a.doScrollLeftBy(-72),e=!0);break;case 33:case 63276:a.doScrollBy(a.view.h);e=!0;break;case 34:case 63277:a.doScrollBy(-a.view.h);e=!0;break;case 36:case 63273:a.railh&&g?a.doScrollPos(0,0):a.doScrollTo(0);e=!0;break;case 35:case 63275:a.railh&&g?a.doScrollPos(a.page.maxw,a.page.maxh):a.doScrollTo(a.page.maxh);e=!0;break;case 32:a.opt.spacebarenabled&&(d?a.doScrollBy(a.view.h):a.doScrollBy(-a.view.h),e=!0);break;case 27:a.zoomactive&&
(a.doZoom(),e=!0)}if(e)return a.cancelEvent(b)}};a.opt.enablekeyboard&&a.bind(document,e.isopera&&!e.isopera12?"keypress":"keydown",a.onkeypress);a.bind(document,"keydown",function(b){b.ctrlKey&&(a.wheelprevented=!0)});a.bind(document,"keyup",function(b){b.ctrlKey||(a.wheelprevented=!1)});a.bind(window,"blur",function(b){a.wheelprevented=!1});a.bind(window,"resize",a.lazyResize);a.bind(window,"orientationchange",a.lazyResize);a.bind(window,"load",a.lazyResize);if(e.ischrome&&!a.ispage&&!a.haswrapper){var t=
a.win.attr("style"),m=parseFloat(a.win.css("width"))+1;a.win.css("width",m);a.synched("chromefix",function(){a.win.attr("style",t)})}a.onAttributeChange=function(b){a.lazyResize(a.isieold?250:30)};a.isie11||!1===x||(a.observerbody=new x(function(b){b.forEach(function(b){if("attributes"==b.type)return f("body").hasClass("modal-open")&&f("body").hasClass("modal-dialog")&&!f.contains(f(".modal-dialog")[0],a.doc[0])?a.hide():a.show()});if(document.body.scrollHeight!=a.page.maxh)return a.lazyResize(30)}),
a.observerbody.observe(document.body,{childList:!0,subtree:!0,characterData:!1,attributes:!0,attributeFilter:["class"]}));a.ispage||a.haswrapper||(!1!==x?(a.observer=new x(function(b){b.forEach(a.onAttributeChange)}),a.observer.observe(a.win[0],{childList:!0,characterData:!1,attributes:!0,subtree:!1}),a.observerremover=new x(function(b){b.forEach(function(b){if(0<b.removedNodes.length)for(var c in b.removedNodes)if(a&&b.removedNodes[c]==a.win[0])return a.remove()})}),a.observerremover.observe(a.win[0].parentNode,
{childList:!0,characterData:!1,attributes:!1,subtree:!1})):(a.bind(a.win,e.isie&&!e.isie9?"propertychange":"DOMAttrModified",a.onAttributeChange),e.isie9&&a.win[0].attachEvent("onpropertychange",a.onAttributeChange),a.bind(a.win,"DOMNodeRemoved",function(b){b.target==a.win[0]&&a.remove()})));!a.ispage&&a.opt.boxzoom&&a.bind(window,"resize",a.resizeZoom);a.istextarea&&(a.bind(a.win,"keydown",a.lazyResize),a.bind(a.win,"mouseup",a.lazyResize));a.lazyResize(30)}if("IFRAME"==this.doc[0].nodeName){var N=
function(){a.iframexd=!1;var c;try{c="contentDocument"in this?this.contentDocument:this.contentWindow.document}catch(g){a.iframexd=!0,c=!1}if(a.iframexd)return"console"in window&&console.log("NiceScroll error: policy restriced iframe"),!0;a.forcescreen=!0;a.isiframe&&(a.iframe={doc:f(c),html:a.doc.contents().find("html")[0],body:a.doc.contents().find("body")[0]},a.getContentSize=function(){return{w:Math.max(a.iframe.html.scrollWidth,a.iframe.body.scrollWidth),h:Math.max(a.iframe.html.scrollHeight,
a.iframe.body.scrollHeight)}},a.docscroll=f(a.iframe.body));if(!e.isios&&a.opt.iframeautoresize&&!a.isiframe){a.win.scrollTop(0);a.doc.height("");var d=Math.max(c.getElementsByTagName("html")[0].scrollHeight,c.body.scrollHeight);a.doc.height(d)}a.lazyResize(30);e.isie7&&a.css(f(a.iframe.html),b);a.css(f(a.iframe.body),b);e.isios&&a.haswrapper&&a.css(f(c.body),{"-webkit-transform":"translate3d(0,0,0)"});"contentWindow"in this?a.bind(this.contentWindow,"scroll",a.onscroll):a.bind(c,"scroll",a.onscroll);
a.opt.enablemousewheel&&a.mousewheel(c,a.onmousewheel);a.opt.enablekeyboard&&a.bind(c,e.isopera?"keypress":"keydown",a.onkeypress);if(e.cantouch||a.opt.touchbehavior)a.bind(c,"mousedown",a.ontouchstart),a.bind(c,"mousemove",function(b){return a.ontouchmove(b,!0)}),a.opt.grabcursorenabled&&e.cursorgrabvalue&&a.css(f(c.body),{cursor:e.cursorgrabvalue});a.bind(c,"mouseup",a.ontouchend);a.zoom&&(a.opt.dblclickzoom&&a.bind(c,"dblclick",a.doZoom),a.ongesturezoom&&a.bind(c,"gestureend",a.ongesturezoom))};
this.doc[0].readyState&&"complete"==this.doc[0].readyState&&setTimeout(function(){N.call(a.doc[0],!1)},500);a.bind(this.doc,"load",N)}};this.showCursor=function(b,c){a.cursortimeout&&(clearTimeout(a.cursortimeout),a.cursortimeout=0);if(a.rail){a.autohidedom&&(a.autohidedom.stop().css({opacity:a.opt.cursoropacitymax}),a.cursoractive=!0);a.rail.drag&&1==a.rail.drag.pt||(void 0!==b&&!1!==b&&(a.scroll.y=Math.round(1*b/a.scrollratio.y)),void 0!==c&&(a.scroll.x=Math.round(1*c/a.scrollratio.x)));a.cursor.css({height:a.cursorheight,
top:a.scroll.y});if(a.cursorh){var d=a.hasreversehr?a.scrollvaluemaxw-a.scroll.x:a.scroll.x;!a.rail.align&&a.rail.visibility?a.cursorh.css({width:a.cursorwidth,left:d+a.rail.width}):a.cursorh.css({width:a.cursorwidth,left:d});a.cursoractive=!0}a.zoom&&a.zoom.stop().css({opacity:a.opt.cursoropacitymax})}};this.hideCursor=function(b){a.cursortimeout||!a.rail||!a.autohidedom||a.hasmousefocus&&"leave"==a.opt.autohidemode||(a.cursortimeout=setTimeout(function(){a.rail.active&&a.showonmouseevent||(a.autohidedom.stop().animate({opacity:a.opt.cursoropacitymin}),
a.zoom&&a.zoom.stop().animate({opacity:a.opt.cursoropacitymin}),a.cursoractive=!1);a.cursortimeout=0},b||a.opt.hidecursordelay))};this.noticeCursor=function(b,c,d){a.showCursor(c,d);a.rail.active||a.hideCursor(b)};this.getContentSize=a.ispage?function(){return{w:Math.max(document.body.scrollWidth,document.documentElement.scrollWidth),h:Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}}:a.haswrapper?function(){return{w:a.doc.outerWidth()+parseInt(a.win.css("paddingLeft"))+
parseInt(a.win.css("paddingRight")),h:a.doc.outerHeight()+parseInt(a.win.css("paddingTop"))+parseInt(a.win.css("paddingBottom"))}}:function(){return{w:a.docscroll[0].scrollWidth,h:a.docscroll[0].scrollHeight}};this.onResize=function(b,c){if(!a||!a.win)return!1;if(!a.haswrapper&&!a.ispage){if("none"==a.win.css("display"))return a.visibility&&a.hideRail().hideRailHr(),!1;a.hidden||a.visibility||a.showRail().showRailHr()}var d=a.page.maxh,e=a.page.maxw,f=a.view.h,k=a.view.w;a.view={w:a.ispage?a.win.width():
parseInt(a.win[0].clientWidth),h:a.ispage?a.win.height():parseInt(a.win[0].clientHeight)};a.page=c?c:a.getContentSize();a.page.maxh=Math.max(0,a.page.h-a.view.h);a.page.maxw=Math.max(0,a.page.w-a.view.w);if(a.page.maxh==d&&a.page.maxw==e&&a.view.w==k&&a.view.h==f){if(a.ispage)return a;d=a.win.offset();if(a.lastposition&&(e=a.lastposition,e.top==d.top&&e.left==d.left))return a;a.lastposition=d}0==a.page.maxh?(a.hideRail(),a.scrollvaluemax=0,a.scroll.y=0,a.scrollratio.y=0,a.cursorheight=0,a.setScrollTop(0),
a.rail&&(a.rail.scrollable=!1)):(a.page.maxh-=a.opt.railpadding.top+a.opt.railpadding.bottom,a.rail.scrollable=!0);0==a.page.maxw?(a.hideRailHr(),a.scrollvaluemaxw=0,a.scroll.x=0,a.scrollratio.x=0,a.cursorwidth=0,a.setScrollLeft(0),a.railh&&(a.railh.scrollable=!1)):(a.page.maxw-=a.opt.railpadding.left+a.opt.railpadding.right,a.railh&&(a.railh.scrollable=a.opt.horizrailenabled));a.railslocked=a.locked||0==a.page.maxh&&0==a.page.maxw;if(a.railslocked)return a.ispage||a.updateScrollBar(a.view),!1;a.hidden||
a.visibility?!a.railh||a.hidden||a.railh.visibility||a.showRailHr():a.showRail().showRailHr();a.istextarea&&a.win.css("resize")&&"none"!=a.win.css("resize")&&(a.view.h-=20);a.cursorheight=Math.min(a.view.h,Math.round(a.view.h/a.page.h*a.view.h));a.cursorheight=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight,a.cursorheight);a.cursorwidth=Math.min(a.view.w,Math.round(a.view.w/a.page.w*a.view.w));a.cursorwidth=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight,
a.cursorwidth);a.scrollvaluemax=a.view.h-a.cursorheight-a.cursor.hborder-(a.opt.railpadding.top+a.opt.railpadding.bottom);a.railh&&(a.railh.width=0<a.page.maxh?a.view.w-a.rail.width:a.view.w,a.scrollvaluemaxw=a.railh.width-a.cursorwidth-a.cursorh.wborder-(a.opt.railpadding.left+a.opt.railpadding.right));a.ispage||a.updateScrollBar(a.view);a.scrollratio={x:a.page.maxw/a.scrollvaluemaxw,y:a.page.maxh/a.scrollvaluemax};a.getScrollTop()>a.page.maxh?a.doScrollTop(a.page.maxh):(a.scroll.y=Math.round(a.getScrollTop()*
(1/a.scrollratio.y)),a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)),a.cursoractive&&a.noticeCursor());a.scroll.y&&0==a.getScrollTop()&&a.doScrollTo(Math.floor(a.scroll.y*a.scrollratio.y));return a};this.resize=a.onResize;this.hlazyresize=0;this.lazyResize=function(b){a.haswrapper||a.hide();a.hlazyresize&&clearTimeout(a.hlazyresize);a.hlazyresize=setTimeout(function(){a&&a.show().resize()},240);return a};this.jqbind=function(b,c,d){a.events.push({e:b,n:c,f:d,q:!0});f(b).bind(c,d)};this.mousewheel=
function(b,c,d){b="jquery"in b?b[0]:b;if("onwheel"in document.createElement("div"))a._bind(b,"wheel",c,d||!1);else{var e=void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";q(b,e,c,d||!1);"DOMMouseScroll"==e&&q(b,"MozMousePixelScroll",c,d||!1)}};e.haseventlistener?(this.bind=function(b,c,d,e){a._bind("jquery"in b?b[0]:b,c,d,e||!1)},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.addEventListener(c,d,e||!1)},this.cancelEvent=function(a){if(!a)return!1;a=a.original?a.original:
a;a.cancelable&&a.preventDefault();a.stopPropagation();a.preventManipulation&&a.preventManipulation();return!1},this.stopPropagation=function(a){if(!a)return!1;a=a.original?a.original:a;a.stopPropagation();return!1},this._unbind=function(a,c,d,e){a.removeEventListener(c,d,e)}):(this.bind=function(b,c,d,e){var f="jquery"in b?b[0]:b;a._bind(f,c,function(b){(b=b||window.event||!1)&&b.srcElement&&(b.target=b.srcElement);"pageY"in b||(b.pageX=b.clientX+document.documentElement.scrollLeft,b.pageY=b.clientY+
document.documentElement.scrollTop);return!1===d.call(f,b)||!1===e?a.cancelEvent(b):!0})},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.attachEvent?b.attachEvent("on"+c,d):b["on"+c]=d},this.cancelEvent=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;a.cancel=!0;return a.returnValue=!1},this.stopPropagation=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;return!1},this._unbind=function(a,c,d,e){a.detachEvent?a.detachEvent("on"+c,d):a["on"+c]=!1});
this.unbindAll=function(){for(var b=0;b<a.events.length;b++){var c=a.events[b];c.q?c.e.unbind(c.n,c.f):a._unbind(c.e,c.n,c.f,c.b)}};this.showRail=function(){0==a.page.maxh||!a.ispage&&"none"==a.win.css("display")||(a.visibility=!0,a.rail.visibility=!0,a.rail.css("display","block"));return a};this.showRailHr=function(){if(!a.railh)return a;0==a.page.maxw||!a.ispage&&"none"==a.win.css("display")||(a.railh.visibility=!0,a.railh.css("display","block"));return a};this.hideRail=function(){a.visibility=
!1;a.rail.visibility=!1;a.rail.css("display","none");return a};this.hideRailHr=function(){if(!a.railh)return a;a.railh.visibility=!1;a.railh.css("display","none");return a};this.show=function(){a.hidden=!1;a.railslocked=!1;return a.showRail().showRailHr()};this.hide=function(){a.hidden=!0;a.railslocked=!0;return a.hideRail().hideRailHr()};this.toggle=function(){return a.hidden?a.show():a.hide()};this.remove=function(){a.stop();a.cursortimeout&&clearTimeout(a.cursortimeout);for(var b in a.delaylist)a.delaylist[b]&&
w(a.delaylist[b].h);a.doZoomOut();a.unbindAll();e.isie9&&a.win[0].detachEvent("onpropertychange",a.onAttributeChange);!1!==a.observer&&a.observer.disconnect();!1!==a.observerremover&&a.observerremover.disconnect();!1!==a.observerbody&&a.observerbody.disconnect();a.events=null;a.cursor&&a.cursor.remove();a.cursorh&&a.cursorh.remove();a.rail&&a.rail.remove();a.railh&&a.railh.remove();a.zoom&&a.zoom.remove();for(b=0;b<a.saved.css.length;b++){var c=a.saved.css[b];c[0].css(c[1],void 0===c[2]?"":c[2])}a.saved=
!1;a.me.data("__nicescroll","");var d=f.nicescroll;d.each(function(b){if(this&&this.id===a.id){delete d[b];for(var c=++b;c<d.length;c++,b++)d[b]=d[c];d.length--;d.length&&delete d[d.length]}});for(var k in a)a[k]=null,delete a[k];a=null};this.scrollstart=function(b){this.onscrollstart=b;return a};this.scrollend=function(b){this.onscrollend=b;return a};this.scrollcancel=function(b){this.onscrollcancel=b;return a};this.zoomin=function(b){this.onzoomin=b;return a};this.zoomout=function(b){this.onzoomout=
b;return a};this.isScrollable=function(a){a=a.target?a.target:a;if("OPTION"==a.nodeName)return!0;for(;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a),c=c.css("overflowY")||c.css("overflowX")||c.css("overflow")||"";if(/scroll|auto/.test(c))return a.clientHeight!=a.scrollHeight;a=a.parentNode?a.parentNode:!1}return!1};this.getViewport=function(a){for(a=a&&a.parentNode?a.parentNode:!1;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a);if(/fixed|absolute/.test(c.css("position")))return c;
var d=c.css("overflowY")||c.css("overflowX")||c.css("overflow")||"";if(/scroll|auto/.test(d)&&a.clientHeight!=a.scrollHeight||0<c.getNiceScroll().length)return c;a=a.parentNode?a.parentNode:!1}return!1};this.triggerScrollEnd=function(){if(a.onscrollend){var b=a.getScrollLeft(),c=a.getScrollTop();a.onscrollend.call(a,{type:"scrollend",current:{x:b,y:c},end:{x:b,y:c}})}};this.onmousewheel=function(b){if(!a.wheelprevented){if(a.railslocked)return a.debounced("checkunlock",a.resize,250),!0;if(a.rail.drag)return a.cancelEvent(b);
"auto"==a.opt.oneaxismousemode&&0!=b.deltaX&&(a.opt.oneaxismousemode=!1);if(a.opt.oneaxismousemode&&0==b.deltaX&&!a.rail.scrollable)return a.railh&&a.railh.scrollable?a.onmousewheelhr(b):!0;var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;if(a.nativescrollingarea)return!0;if(b=t(b,!1,d))a.checkarea=0;return b}};this.onmousewheelhr=function(b){if(!a.wheelprevented){if(a.railslocked||!a.railh.scrollable)return!0;if(a.rail.drag)return a.cancelEvent(b);
var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;return a.nativescrollingarea?!0:a.railslocked?a.cancelEvent(b):t(b,!0,d)}};this.stop=function(){a.cancelScroll();a.scrollmon&&a.scrollmon.stop();a.cursorfreezed=!1;a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.noticeCursor();return a};this.getTransitionSpeed=function(b){b=Math.min(Math.round(10*a.opt.scrollspeed),Math.round(b/20*a.opt.scrollspeed));return 20<
b?b:0};a.opt.smoothscroll?a.ishwscroll&&e.hastransition&&a.opt.usetransition&&a.opt.smoothscroll?(this.prepareTransition=function(b,c){var d=c?20<b?b:0:a.getTransitionSpeed(b),f=d?e.prefixstyle+"transform "+d+"ms ease-out":"";a.lasttransitionstyle&&a.lasttransitionstyle==f||(a.lasttransitionstyle=f,a.doc.css(e.transitionstyle,f));return d},this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?
a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var f=a.getScrollTop(),k=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();0==a.opt.bouncescroll&&(0>c?c=0:c>a.page.maxh&&(c=a.page.maxh),0>b?b=0:b>a.page.maxw&&(b=a.page.maxw));if(a.scrollrunning&&b==a.newscrollx&&c==a.newscrolly)return!1;a.newscrolly=c;a.newscrollx=b;a.newscrollspeed=d||!1;if(a.timer)return!1;a.timer=setTimeout(function(){var d=a.getScrollTop(),f=a.getScrollLeft(),
k=Math.round(Math.sqrt(Math.pow(b-f,2)+Math.pow(c-d,2))),k=a.newscrollspeed&&1<a.newscrollspeed?a.newscrollspeed:a.getTransitionSpeed(k);a.newscrollspeed&&1>=a.newscrollspeed&&(k*=a.newscrollspeed);a.prepareTransition(k,!0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);0<k&&(!a.scrollrunning&&a.onscrollstart&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:f,y:d},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:k}),e.transitionend?a.scrollendtrapped||(a.scrollendtrapped=
!0,a.bind(a.doc,e.transitionend,a.onScrollTransitionEnd,!1)):(a.scrollendtrapped&&clearTimeout(a.scrollendtrapped),a.scrollendtrapped=setTimeout(a.onScrollTransitionEnd,k)),a.timerscroll={bz:new D(d,a.newscrolly,k,0,0,.58,1),bh:new D(f,a.newscrollx,k,0,0,.58,1)},a.cursorfreezed||(a.timerscroll.tm=setInterval(function(){a.showCursor(a.getScrollTop(),a.getScrollLeft())},60)));a.synched("doScroll-set",function(){a.timer=0;a.scrollendtrapped&&(a.scrollrunning=!0);a.setScrollTop(a.newscrolly);a.setScrollLeft(a.newscrollx);
if(!a.scrollendtrapped)a.onScrollTransitionEnd()})},50)},this.cancelScroll=function(){if(!a.scrollendtrapped)return!0;var b=a.getScrollTop(),c=a.getScrollLeft();a.scrollrunning=!1;e.transitionend||clearTimeout(e.transitionend);a.scrollendtrapped=!1;a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);a.prepareTransition(0);a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;a.cursorfreezed=!1;a.showCursor(b,c);return a},
this.onScrollTransitionEnd=function(){a.scrollendtrapped&&a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);a.scrollendtrapped=!1;a.prepareTransition(0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;var b=a.getScrollTop(),c=a.getScrollLeft();a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.noticeCursor(!1,b,c);a.cursorfreezed=!1;0>b?b=0:b>a.page.maxh&&(b=a.page.maxh);0>c?c=0:c>a.page.maxw&&(c=a.page.maxw);if(b!=a.newscrolly||c!=a.newscrollx)return a.doScrollPos(c,
b,a.opt.snapbackspeed);a.onscrollend&&a.scrollrunning&&a.triggerScrollEnd();a.scrollrunning=!1}):(this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){function e(){if(a.cancelAnimationFrame)return!0;a.scrollrunning=!0;if(p=1-p)return a.timer=v(e)||1;var b=0,c,d,f=d=a.getScrollTop();if(a.dst.ay){f=a.bzscroll?
a.dst.py+a.bzscroll.getNow()*a.dst.ay:a.newscrolly;c=f-d;if(0>c&&f<a.newscrolly||0<c&&f>a.newscrolly)f=a.newscrolly;a.setScrollTop(f);f==a.newscrolly&&(b=1)}else b=1;d=c=a.getScrollLeft();if(a.dst.ax){d=a.bzscroll?a.dst.px+a.bzscroll.getNow()*a.dst.ax:a.newscrollx;c=d-c;if(0>c&&d<a.newscrollx||0<c&&d>a.newscrollx)d=a.newscrollx;a.setScrollLeft(d);d==a.newscrollx&&(b+=1)}else b+=1;2==b?(a.timer=0,a.cursorfreezed=!1,a.bzscroll=!1,a.scrollrunning=!1,0>f?f=0:f>a.page.maxh&&(f=Math.max(0,a.page.maxh)),
0>d?d=0:d>a.page.maxw&&(d=a.page.maxw),d!=a.newscrollx||f!=a.newscrolly?a.doScrollPos(d,f):a.onscrollend&&a.triggerScrollEnd()):a.timer=v(e)||1}c=void 0===c||!1===c?a.getScrollTop(!0):c;if(a.timer&&a.newscrolly==c&&a.newscrollx==b)return!0;a.timer&&w(a.timer);a.timer=0;var f=a.getScrollTop(),k=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();a.newscrolly=c;a.newscrollx=b;a.bouncescroll&&a.rail.visibility||(0>a.newscrolly?a.newscrolly=0:a.newscrolly>a.page.maxh&&
(a.newscrolly=a.page.maxh));a.bouncescroll&&a.railh.visibility||(0>a.newscrollx?a.newscrollx=0:a.newscrollx>a.page.maxw&&(a.newscrollx=a.page.maxw));a.dst={};a.dst.x=b-k;a.dst.y=c-f;a.dst.px=k;a.dst.py=f;var h=Math.round(Math.sqrt(Math.pow(a.dst.x,2)+Math.pow(a.dst.y,2)));a.dst.ax=a.dst.x/h;a.dst.ay=a.dst.y/h;var l=0,n=h;0==a.dst.x?(l=f,n=c,a.dst.ay=1,a.dst.py=0):0==a.dst.y&&(l=k,n=b,a.dst.ax=1,a.dst.px=0);h=a.getTransitionSpeed(h);d&&1>=d&&(h*=d);a.bzscroll=0<h?a.bzscroll?a.bzscroll.update(n,h):
new D(l,n,h,0,1,0,1):!1;if(!a.timer){(f==a.page.maxh&&c>=a.page.maxh||k==a.page.maxw&&b>=a.page.maxw)&&a.checkContentSize();var p=1;a.cancelAnimationFrame=!1;a.timer=1;a.onscrollstart&&!a.scrollrunning&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:k,y:f},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:h});e();(f==a.page.maxh&&c>=f||k==a.page.maxw&&b>=k)&&a.checkContentSize();a.noticeCursor()}},this.cancelScroll=function(){a.timer&&w(a.timer);a.timer=0;a.bzscroll=!1;a.scrollrunning=
!1;return a}):(this.doScrollLeft=function(b,c){var d=a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var e=b>a.page.maxw?a.page.maxw:b;0>e&&(e=0);var f=c>a.page.maxh?a.page.maxh:c;0>f&&(f=0);a.synched("scroll",function(){a.setScrollTop(f);a.setScrollLeft(e)})},this.cancelScroll=function(){});this.doScrollBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.y-b)*a.scrollratio.y):(a.timer?a.newscrolly:
a.getScrollTop(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.h/2);d<-e?d=-e:d>a.page.maxh+e&&(d=a.page.maxh+e)}a.cursorfreezed=!1;e=a.getScrollTop(!0);if(0>d&&0>=e)return a.noticeCursor();if(d>a.page.maxh&&e>=a.page.maxh)return a.checkContentSize(),a.noticeCursor();a.doScrollTop(d)};this.doScrollLeftBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.x-b)*a.scrollratio.x):(a.timer?a.newscrollx:a.getScrollLeft(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.w/2);d<-e?d=-e:d>a.page.maxw+e&&(d=a.page.maxw+
e)}a.cursorfreezed=!1;e=a.getScrollLeft(!0);if(0>d&&0>=e||d>a.page.maxw&&e>=a.page.maxw)return a.noticeCursor();a.doScrollLeft(d)};this.doScrollTo=function(b,c){a.cursorfreezed=!1;a.doScrollTop(b)};this.checkContentSize=function(){var b=a.getContentSize();b.h==a.page.h&&b.w==a.page.w||a.resize(!1,b)};a.onscroll=function(b){a.rail.drag||a.cursorfreezed||a.synched("scroll",function(){a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.railh&&(a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)));
a.noticeCursor()})};a.bind(a.docscroll,"scroll",a.onscroll);this.doZoomIn=function(b){if(!a.zoomactive){a.zoomactive=!0;a.zoomrestore={style:{}};var c="position top left zIndex backgroundColor marginTop marginBottom marginLeft marginRight".split(" "),d=a.win[0].style,k;for(k in c){var h=c[k];a.zoomrestore.style[h]=void 0!==d[h]?d[h]:""}a.zoomrestore.style.width=a.win.css("width");a.zoomrestore.style.height=a.win.css("height");a.zoomrestore.padding={w:a.win.outerWidth()-a.win.width(),h:a.win.outerHeight()-
a.win.height()};e.isios4&&(a.zoomrestore.scrollTop=f(window).scrollTop(),f(window).scrollTop(0));a.win.css({position:e.isios4?"absolute":"fixed",top:0,left:0,zIndex:A+100,margin:0});c=a.win.css("backgroundColor");(""==c||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(c))&&a.win.css("backgroundColor","#fff");a.rail.css({zIndex:A+101});a.zoom.css({zIndex:A+102});a.zoom.css("backgroundPosition","0px -18px");a.resizeZoom();a.onzoomin&&a.onzoomin.call(a);return a.cancelEvent(b)}};this.doZoomOut=
function(b){if(a.zoomactive)return a.zoomactive=!1,a.win.css("margin",""),a.win.css(a.zoomrestore.style),e.isios4&&f(window).scrollTop(a.zoomrestore.scrollTop),a.rail.css({"z-index":a.zindex}),a.zoom.css({"z-index":a.zindex}),a.zoomrestore=!1,a.zoom.css("backgroundPosition","0px 0px"),a.onResize(),a.onzoomout&&a.onzoomout.call(a),a.cancelEvent(b)};this.doZoom=function(b){return a.zoomactive?a.doZoomOut(b):a.doZoomIn(b)};this.resizeZoom=function(){if(a.zoomactive){var b=a.getScrollTop();a.win.css({width:f(window).width()-
a.zoomrestore.padding.w+"px",height:f(window).height()-a.zoomrestore.padding.h+"px"});a.onResize();a.setScrollTop(Math.min(a.page.maxh,b))}};this.init();f.nicescroll.push(this)},M=function(f){var c=this;this.nc=f;this.steptime=this.lasttime=this.speedy=this.speedx=this.lasty=this.lastx=0;this.snapy=this.snapx=!1;this.demuly=this.demulx=0;this.lastscrolly=this.lastscrollx=-1;this.timer=this.chky=this.chkx=0;this.time=function(){return+new Date};this.reset=function(f,h){c.stop();var d=c.time();c.steptime=
0;c.lasttime=d;c.speedx=0;c.speedy=0;c.lastx=f;c.lasty=h;c.lastscrollx=-1;c.lastscrolly=-1};this.update=function(f,h){var d=c.time();c.steptime=d-c.lasttime;c.lasttime=d;var d=h-c.lasty,q=f-c.lastx,t=c.nc.getScrollTop(),a=c.nc.getScrollLeft(),t=t+d,a=a+q;c.snapx=0>a||a>c.nc.page.maxw;c.snapy=0>t||t>c.nc.page.maxh;c.speedx=q;c.speedy=d;c.lastx=f;c.lasty=h};this.stop=function(){c.nc.unsynched("domomentum2d");c.timer&&clearTimeout(c.timer);c.timer=0;c.lastscrollx=-1;c.lastscrolly=-1};this.doSnapy=function(f,
h){var d=!1;0>h?(h=0,d=!0):h>c.nc.page.maxh&&(h=c.nc.page.maxh,d=!0);0>f?(f=0,d=!0):f>c.nc.page.maxw&&(f=c.nc.page.maxw,d=!0);d?c.nc.doScrollPos(f,h,c.nc.opt.snapbackspeed):c.nc.triggerScrollEnd()};this.doMomentum=function(f){var h=c.time(),d=f?h+f:c.lasttime;f=c.nc.getScrollLeft();var q=c.nc.getScrollTop(),t=c.nc.page.maxh,a=c.nc.page.maxw;c.speedx=0<a?Math.min(60,c.speedx):0;c.speedy=0<t?Math.min(60,c.speedy):0;d=d&&60>=h-d;if(0>q||q>t||0>f||f>a)d=!1;f=c.speedx&&d?c.speedx:!1;if(c.speedy&&d&&c.speedy||
f){var r=Math.max(16,c.steptime);50<r&&(f=r/50,c.speedx*=f,c.speedy*=f,r=50);c.demulxy=0;c.lastscrollx=c.nc.getScrollLeft();c.chkx=c.lastscrollx;c.lastscrolly=c.nc.getScrollTop();c.chky=c.lastscrolly;var p=c.lastscrollx,e=c.lastscrolly,v=function(){var d=600<c.time()-h?.04:.02;c.speedx&&(p=Math.floor(c.lastscrollx-c.speedx*(1-c.demulxy)),c.lastscrollx=p,0>p||p>a)&&(d=.1);c.speedy&&(e=Math.floor(c.lastscrolly-c.speedy*(1-c.demulxy)),c.lastscrolly=e,0>e||e>t)&&(d=.1);c.demulxy=Math.min(1,c.demulxy+
d);c.nc.synched("domomentum2d",function(){c.speedx&&(c.nc.getScrollLeft(),c.chkx=p,c.nc.setScrollLeft(p));c.speedy&&(c.nc.getScrollTop(),c.chky=e,c.nc.setScrollTop(e));c.timer||(c.nc.hideCursor(),c.doSnapy(p,e))});1>c.demulxy?c.timer=setTimeout(v,r):(c.stop(),c.nc.hideCursor(),c.doSnapy(p,e))};v()}else c.doSnapy(c.nc.getScrollLeft(),c.nc.getScrollTop())}},y=f.fn.scrollTop;f.cssHooks.pageYOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll?c.getScrollTop():y.call(h)},set:function(h,
c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollTop(parseInt(c)):y.call(h,c);return this}};f.fn.scrollTop=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollTop():y.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollTop(parseInt(h)):y.call(f(this),h)})};var z=f.fn.scrollLeft;f.cssHooks.pageXOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll?
c.getScrollLeft():z.call(h)},set:function(h,c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollLeft(parseInt(c)):z.call(h,c);return this}};f.fn.scrollLeft=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollLeft():z.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollLeft(parseInt(h)):z.call(f(this),h)})};var E=function(h){var c=this;this.length=0;this.name="nicescrollarray";
this.each=function(d){f.each(c,d);return c};this.push=function(d){c[c.length]=d;c.length++};this.eq=function(d){return c[d]};if(h)for(var k=0;k<h.length;k++){var l=f.data(h[k],"__nicescroll")||!1;l&&(this[this.length]=l,this.length++)}return this};(function(f,c,k){for(var l=0;l<c.length;l++)k(f,c[l])})(E.prototype,"show hide toggle onResize resize remove stop doScrollPos".split(" "),function(f,c){f[c]=function(){var f=arguments;return this.each(function(){this[c].apply(this,f)})}});f.fn.getNiceScroll=
function(h){return void 0===h?new E(this):this[h]&&f.data(this[h],"__nicescroll")||!1};f.expr[":"].nicescroll=function(h){return void 0!==f.data(h,"__nicescroll")};f.fn.niceScroll=function(h,c){void 0!==c||"object"!=typeof h||"jquery"in h||(c=h,h=!1);c=f.extend({},c);var k=new E;void 0===c&&(c={});h&&(c.doc=f(h),c.win=f(this));var l=!("doc"in c);l||"win"in c||(c.win=f(this));this.each(function(){var d=f(this).data("__nicescroll")||!1;d||(c.doc=l?f(this):c.doc,d=new S(c,f(this)),f(this).data("__nicescroll",
d));k.push(d)});return 1==k.length?k[0]:k};window.NiceScroll={getjQuery:function(){return f}};f.nicescroll||(f.nicescroll=new E,f.nicescroll.options=K)});

/*********************
Including file: moment.min.js
*********************/
//! moment.js
//! version : 2.9.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function(a){function b(a,b,c){switch(arguments.length){case 2:return null!=a?a:b;case 3:return null!=a?a:null!=b?b:c;default:throw new Error("Implement me")}}function c(a,b){return Bb.call(a,b)}function d(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function e(a){vb.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+a)}function f(a,b){var c=!0;return o(function(){return c&&(e(a),c=!1),b.apply(this,arguments)},b)}function g(a,b){sc[a]||(e(b),sc[a]=!0)}function h(a,b){return function(c){return r(a.call(this,c),b)}}function i(a,b){return function(c){return this.localeData().ordinal(a.call(this,c),b)}}function j(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function k(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function l(){}function m(a,b){b!==!1&&H(a),p(this,a),this._d=new Date(+a._d),uc===!1&&(uc=!0,vb.updateOffset(this),uc=!1)}function n(a){var b=A(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=vb.localeData(),this._bubble()}function o(a,b){for(var d in b)c(b,d)&&(a[d]=b[d]);return c(b,"toString")&&(a.toString=b.toString),c(b,"valueOf")&&(a.valueOf=b.valueOf),a}function p(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=b._pf),"undefined"!=typeof b._locale&&(a._locale=b._locale),Kb.length>0)for(c in Kb)d=Kb[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function q(a){return 0>a?Math.ceil(a):Math.floor(a)}function r(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function s(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function t(a,b){var c;return b=M(b,a),a.isBefore(b)?c=s(a,b):(c=s(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function u(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(g(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=vb.duration(c,d),v(this,e,a),this}}function v(a,b,c,d){var e=b._milliseconds,f=b._days,g=b._months;d=null==d?!0:d,e&&a._d.setTime(+a._d+e*c),f&&pb(a,"Date",ob(a,"Date")+f*c),g&&nb(a,ob(a,"Month")+g*c),d&&vb.updateOffset(a,f||g)}function w(a){return"[object Array]"===Object.prototype.toString.call(a)}function x(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function y(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&C(a[d])!==C(b[d]))&&g++;return g+f}function z(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=lc[a]||mc[b]||b}return a}function A(a){var b,d,e={};for(d in a)c(a,d)&&(b=z(d),b&&(e[b]=a[d]));return e}function B(b){var c,d;if(0===b.indexOf("week"))c=7,d="day";else{if(0!==b.indexOf("month"))return;c=12,d="month"}vb[b]=function(e,f){var g,h,i=vb._locale[b],j=[];if("number"==typeof e&&(f=e,e=a),h=function(a){var b=vb().utc().set(d,a);return i.call(vb._locale,b,e||"")},null!=f)return h(f);for(g=0;c>g;g++)j.push(h(g));return j}}function C(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function D(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function E(a,b,c){return jb(vb([a,11,31+b-c]),b,c).week}function F(a){return G(a)?366:365}function G(a){return a%4===0&&a%100!==0||a%400===0}function H(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[Db]<0||a._a[Db]>11?Db:a._a[Eb]<1||a._a[Eb]>D(a._a[Cb],a._a[Db])?Eb:a._a[Fb]<0||a._a[Fb]>24||24===a._a[Fb]&&(0!==a._a[Gb]||0!==a._a[Hb]||0!==a._a[Ib])?Fb:a._a[Gb]<0||a._a[Gb]>59?Gb:a._a[Hb]<0||a._a[Hb]>59?Hb:a._a[Ib]<0||a._a[Ib]>999?Ib:-1,a._pf._overflowDayOfYear&&(Cb>b||b>Eb)&&(b=Eb),a._pf.overflow=b)}function I(b){return null==b._isValid&&(b._isValid=!isNaN(b._d.getTime())&&b._pf.overflow<0&&!b._pf.empty&&!b._pf.invalidMonth&&!b._pf.nullInput&&!b._pf.invalidFormat&&!b._pf.userInvalidated,b._strict&&(b._isValid=b._isValid&&0===b._pf.charsLeftOver&&0===b._pf.unusedTokens.length&&b._pf.bigHour===a)),b._isValid}function J(a){return a?a.toLowerCase().replace("_","-"):a}function K(a){for(var b,c,d,e,f=0;f<a.length;){for(e=J(a[f]).split("-"),b=e.length,c=J(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=L(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&y(e,c,!0)>=b-1)break;b--}f++}return null}function L(a){var b=null;if(!Jb[a]&&Lb)try{b=vb.locale(),require("./locale/"+a),vb.locale(b)}catch(c){}return Jb[a]}function M(a,b){var c,d;return b._isUTC?(c=b.clone(),d=(vb.isMoment(a)||x(a)?+a:+vb(a))-+c,c._d.setTime(+c._d+d),vb.updateOffset(c,!1),c):vb(a).local()}function N(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function O(a){var b,c,d=a.match(Pb);for(b=0,c=d.length;c>b;b++)d[b]=rc[d[b]]?rc[d[b]]:N(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function P(a,b){return a.isValid()?(b=Q(b,a.localeData()),nc[b]||(nc[b]=O(b)),nc[b](a)):a.localeData().invalidDate()}function Q(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Qb.lastIndex=0;d>=0&&Qb.test(a);)a=a.replace(Qb,c),Qb.lastIndex=0,d-=1;return a}function R(a,b){var c,d=b._strict;switch(a){case"Q":return _b;case"DDDD":return bc;case"YYYY":case"GGGG":case"gggg":return d?cc:Tb;case"Y":case"G":case"g":return ec;case"YYYYYY":case"YYYYY":case"GGGGG":case"ggggg":return d?dc:Ub;case"S":if(d)return _b;case"SS":if(d)return ac;case"SSS":if(d)return bc;case"DDD":return Sb;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return Wb;case"a":case"A":return b._locale._meridiemParse;case"x":return Zb;case"X":return $b;case"Z":case"ZZ":return Xb;case"T":return Yb;case"SSSS":return Vb;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"ww":case"WW":return d?ac:Rb;case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"W":case"e":case"E":return Rb;case"Do":return d?b._locale._ordinalParse:b._locale._ordinalParseLenient;default:return c=new RegExp($(Z(a.replace("\\","")),"i"))}}function S(a){a=a||"";var b=a.match(Xb)||[],c=b[b.length-1]||[],d=(c+"").match(jc)||["-",0,0],e=+(60*d[1])+C(d[2]);return"+"===d[0]?e:-e}function T(a,b,c){var d,e=c._a;switch(a){case"Q":null!=b&&(e[Db]=3*(C(b)-1));break;case"M":case"MM":null!=b&&(e[Db]=C(b)-1);break;case"MMM":case"MMMM":d=c._locale.monthsParse(b,a,c._strict),null!=d?e[Db]=d:c._pf.invalidMonth=b;break;case"D":case"DD":null!=b&&(e[Eb]=C(b));break;case"Do":null!=b&&(e[Eb]=C(parseInt(b.match(/\d{1,2}/)[0],10)));break;case"DDD":case"DDDD":null!=b&&(c._dayOfYear=C(b));break;case"YY":e[Cb]=vb.parseTwoDigitYear(b);break;case"YYYY":case"YYYYY":case"YYYYYY":e[Cb]=C(b);break;case"a":case"A":c._meridiem=b;break;case"h":case"hh":c._pf.bigHour=!0;case"H":case"HH":e[Fb]=C(b);break;case"m":case"mm":e[Gb]=C(b);break;case"s":case"ss":e[Hb]=C(b);break;case"S":case"SS":case"SSS":case"SSSS":e[Ib]=C(1e3*("0."+b));break;case"x":c._d=new Date(C(b));break;case"X":c._d=new Date(1e3*parseFloat(b));break;case"Z":case"ZZ":c._useUTC=!0,c._tzm=S(b);break;case"dd":case"ddd":case"dddd":d=c._locale.weekdaysParse(b),null!=d?(c._w=c._w||{},c._w.d=d):c._pf.invalidWeekday=b;break;case"w":case"ww":case"W":case"WW":case"d":case"e":case"E":a=a.substr(0,1);case"gggg":case"GGGG":case"GGGGG":a=a.substr(0,2),b&&(c._w=c._w||{},c._w[a]=C(b));break;case"gg":case"GG":c._w=c._w||{},c._w[a]=vb.parseTwoDigitYear(b)}}function U(a){var c,d,e,f,g,h,i;c=a._w,null!=c.GG||null!=c.W||null!=c.E?(g=1,h=4,d=b(c.GG,a._a[Cb],jb(vb(),1,4).year),e=b(c.W,1),f=b(c.E,1)):(g=a._locale._week.dow,h=a._locale._week.doy,d=b(c.gg,a._a[Cb],jb(vb(),g,h).year),e=b(c.w,1),null!=c.d?(f=c.d,g>f&&++e):f=null!=c.e?c.e+g:g),i=kb(d,e,f,h,g),a._a[Cb]=i.year,a._dayOfYear=i.dayOfYear}function V(a){var c,d,e,f,g=[];if(!a._d){for(e=X(a),a._w&&null==a._a[Eb]&&null==a._a[Db]&&U(a),a._dayOfYear&&(f=b(a._a[Cb],e[Cb]),a._dayOfYear>F(f)&&(a._pf._overflowDayOfYear=!0),d=fb(f,0,a._dayOfYear),a._a[Db]=d.getUTCMonth(),a._a[Eb]=d.getUTCDate()),c=0;3>c&&null==a._a[c];++c)a._a[c]=g[c]=e[c];for(;7>c;c++)a._a[c]=g[c]=null==a._a[c]?2===c?1:0:a._a[c];24===a._a[Fb]&&0===a._a[Gb]&&0===a._a[Hb]&&0===a._a[Ib]&&(a._nextDay=!0,a._a[Fb]=0),a._d=(a._useUTC?fb:eb).apply(null,g),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[Fb]=24)}}function W(a){var b;a._d||(b=A(a._i),a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],V(a))}function X(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function Y(b){if(b._f===vb.ISO_8601)return void ab(b);b._a=[],b._pf.empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=Q(b._f,b._locale).match(Pb)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(R(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&b._pf.unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length),rc[f]?(d?b._pf.empty=!1:b._pf.unusedTokens.push(f),T(f,d,b)):b._strict&&!d&&b._pf.unusedTokens.push(f);b._pf.charsLeftOver=i-j,h.length>0&&b._pf.unusedInput.push(h),b._pf.bigHour===!0&&b._a[Fb]<=12&&(b._pf.bigHour=a),b._a[Fb]=k(b._locale,b._a[Fb],b._meridiem),V(b),H(b)}function Z(a){return a.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e})}function $(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function _(a){var b,c,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;f<a._f.length;f++)g=0,b=p({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._pf=d(),b._f=a._f[f],Y(b),I(b)&&(g+=b._pf.charsLeftOver,g+=10*b._pf.unusedTokens.length,b._pf.score=g,(null==e||e>g)&&(e=g,c=b));o(a,c||b)}function ab(a){var b,c,d=a._i,e=fc.exec(d);if(e){for(a._pf.iso=!0,b=0,c=hc.length;c>b;b++)if(hc[b][1].exec(d)){a._f=hc[b][0]+(e[6]||" ");break}for(b=0,c=ic.length;c>b;b++)if(ic[b][1].exec(d)){a._f+=ic[b][0];break}d.match(Xb)&&(a._f+="Z"),Y(a)}else a._isValid=!1}function bb(a){ab(a),a._isValid===!1&&(delete a._isValid,vb.createFromInputFallback(a))}function cb(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function db(b){var c,d=b._i;d===a?b._d=new Date:x(d)?b._d=new Date(+d):null!==(c=Mb.exec(d))?b._d=new Date(+c[1]):"string"==typeof d?bb(b):w(d)?(b._a=cb(d.slice(0),function(a){return parseInt(a,10)}),V(b)):"object"==typeof d?W(b):"number"==typeof d?b._d=new Date(d):vb.createFromInputFallback(b)}function eb(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function fb(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function gb(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function hb(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function ib(a,b,c){var d=vb.duration(a).abs(),e=Ab(d.as("s")),f=Ab(d.as("m")),g=Ab(d.as("h")),h=Ab(d.as("d")),i=Ab(d.as("M")),j=Ab(d.as("y")),k=e<oc.s&&["s",e]||1===f&&["m"]||f<oc.m&&["mm",f]||1===g&&["h"]||g<oc.h&&["hh",g]||1===h&&["d"]||h<oc.d&&["dd",h]||1===i&&["M"]||i<oc.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,hb.apply({},k)}function jb(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=vb(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function kb(a,b,c,d,e){var f,g,h=fb(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:F(a-1)+g}}function lb(b){var c,d=b._i,e=b._f;return b._locale=b._locale||vb.localeData(b._l),null===d||e===a&&""===d?vb.invalid({nullInput:!0}):("string"==typeof d&&(b._i=d=b._locale.preparse(d)),vb.isMoment(d)?new m(d,!0):(e?w(e)?_(b):Y(b):db(b),c=new m(b),c._nextDay&&(c.add(1,"d"),c._nextDay=a),c))}function mb(a,b){var c,d;if(1===b.length&&w(b[0])&&(b=b[0]),!b.length)return vb();for(c=b[0],d=1;d<b.length;++d)b[d][a](c)&&(c=b[d]);return c}function nb(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),D(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function ob(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function pb(a,b,c){return"Month"===b?nb(a,c):a._d["set"+(a._isUTC?"UTC":"")+b](c)}function qb(a,b){return function(c){return null!=c?(pb(this,a,c),vb.updateOffset(this,b),this):ob(this,a)}}function rb(a){return 400*a/146097}function sb(a){return 146097*a/400}function tb(a){vb.duration.fn[a]=function(){return this._data[a]}}function ub(a){"undefined"==typeof ender&&(wb=zb.moment,zb.moment=a?f("Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release.",vb):vb)}for(var vb,wb,xb,yb="2.9.0",zb="undefined"==typeof global||"undefined"!=typeof window&&window!==global.window?this:global,Ab=Math.round,Bb=Object.prototype.hasOwnProperty,Cb=0,Db=1,Eb=2,Fb=3,Gb=4,Hb=5,Ib=6,Jb={},Kb=[],Lb="undefined"!=typeof module&&module&&module.exports,Mb=/^\/?Date\((\-?\d+)/i,Nb=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,Ob=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,Pb=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Qb=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Rb=/\d\d?/,Sb=/\d{1,3}/,Tb=/\d{1,4}/,Ub=/[+\-]?\d{1,6}/,Vb=/\d+/,Wb=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Xb=/Z|[\+\-]\d\d:?\d\d/gi,Yb=/T/i,Zb=/[\+\-]?\d+/,$b=/[\+\-]?\d+(\.\d{1,3})?/,_b=/\d/,ac=/\d\d/,bc=/\d{3}/,cc=/\d{4}/,dc=/[+-]?\d{6}/,ec=/[+-]?\d+/,fc=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gc="YYYY-MM-DDTHH:mm:ssZ",hc=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],ic=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],jc=/([\+\-]|\d\d)/gi,kc=("Date|Hours|Minutes|Seconds|Milliseconds".split("|"),{Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6}),lc={ms:"millisecond",s:"second",m:"minute",h:"hour",d:"day",D:"date",w:"week",W:"isoWeek",M:"month",Q:"quarter",y:"year",DDD:"dayOfYear",e:"weekday",E:"isoWeekday",gg:"weekYear",GG:"isoWeekYear"},mc={dayofyear:"dayOfYear",isoweekday:"isoWeekday",isoweek:"isoWeek",weekyear:"weekYear",isoweekyear:"isoWeekYear"},nc={},oc={s:45,m:45,h:22,d:26,M:11},pc="DDD w W M D d".split(" "),qc="M D H h m s w W".split(" "),rc={M:function(){return this.month()+1},MMM:function(a){return this.localeData().monthsShort(this,a)},MMMM:function(a){return this.localeData().months(this,a)},D:function(){return this.date()},DDD:function(){return this.dayOfYear()},d:function(){return this.day()},dd:function(a){return this.localeData().weekdaysMin(this,a)},ddd:function(a){return this.localeData().weekdaysShort(this,a)},dddd:function(a){return this.localeData().weekdays(this,a)},w:function(){return this.week()},W:function(){return this.isoWeek()},YY:function(){return r(this.year()%100,2)},YYYY:function(){return r(this.year(),4)},YYYYY:function(){return r(this.year(),5)},YYYYYY:function(){var a=this.year(),b=a>=0?"+":"-";return b+r(Math.abs(a),6)},gg:function(){return r(this.weekYear()%100,2)},gggg:function(){return r(this.weekYear(),4)},ggggg:function(){return r(this.weekYear(),5)},GG:function(){return r(this.isoWeekYear()%100,2)},GGGG:function(){return r(this.isoWeekYear(),4)},GGGGG:function(){return r(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.localeData().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.localeData().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return C(this.milliseconds()/100)},SS:function(){return r(C(this.milliseconds()/10),2)},SSS:function(){return r(this.milliseconds(),3)},SSSS:function(){return r(this.milliseconds(),3)},Z:function(){var a=this.utcOffset(),b="+";return 0>a&&(a=-a,b="-"),b+r(C(a/60),2)+":"+r(C(a)%60,2)},ZZ:function(){var a=this.utcOffset(),b="+";return 0>a&&(a=-a,b="-"),b+r(C(a/60),2)+r(C(a)%60,2)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},x:function(){return this.valueOf()},X:function(){return this.unix()},Q:function(){return this.quarter()}},sc={},tc=["months","monthsShort","weekdays","weekdaysShort","weekdaysMin"],uc=!1;pc.length;)xb=pc.pop(),rc[xb+"o"]=i(rc[xb],xb);for(;qc.length;)xb=qc.pop(),rc[xb+xb]=h(rc[xb],2);rc.DDDD=h(rc.DDD,3),o(l.prototype,{set:function(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(a){return this._months[a.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(a){return this._monthsShort[a.month()]},monthsParse:function(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=vb.utc([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(a){return this._weekdays[a.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(a){return this._weekdaysShort[a.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(a){return this._weekdaysMin[a.day()]},weekdaysParse:function(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=vb([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b},_longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},longDateFormat:function(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b},isPM:function(a){return"p"===(a+"").toLowerCase().charAt(0)},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.apply(b,[c]):d},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)},pastFuture:function(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)},ordinal:function(a){return this._ordinal.replace("%d",a)},_ordinal:"%d",_ordinalParse:/\d{1,2}/,preparse:function(a){return a},postformat:function(a){return a},week:function(a){return jb(a,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6},firstDayOfWeek:function(){return this._week.dow},firstDayOfYear:function(){return this._week.doy},_invalidDate:"Invalid date",invalidDate:function(){return this._invalidDate}}),vb=function(b,c,e,f){var g;return"boolean"==typeof e&&(f=e,e=a),g={},g._isAMomentObject=!0,g._i=b,g._f=c,g._l=e,g._strict=f,g._isUTC=!1,g._pf=d(),lb(g)},vb.suppressDeprecationWarnings=!1,vb.createFromInputFallback=f("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),vb.min=function(){var a=[].slice.call(arguments,0);return mb("isBefore",a)},vb.max=function(){var a=[].slice.call(arguments,0);return mb("isAfter",a)},vb.utc=function(b,c,e,f){var g;return"boolean"==typeof e&&(f=e,e=a),g={},g._isAMomentObject=!0,g._useUTC=!0,g._isUTC=!0,g._l=e,g._i=b,g._f=c,g._strict=f,g._pf=d(),lb(g).utc()},vb.unix=function(a){return vb(1e3*a)},vb.duration=function(a,b){var d,e,f,g,h=a,i=null;return vb.isDuration(a)?h={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(h={},b?h[b]=a:h.milliseconds=a):(i=Nb.exec(a))?(d="-"===i[1]?-1:1,h={y:0,d:C(i[Eb])*d,h:C(i[Fb])*d,m:C(i[Gb])*d,s:C(i[Hb])*d,ms:C(i[Ib])*d}):(i=Ob.exec(a))?(d="-"===i[1]?-1:1,f=function(a){var b=a&&parseFloat(a.replace(",","."));return(isNaN(b)?0:b)*d},h={y:f(i[2]),M:f(i[3]),d:f(i[4]),h:f(i[5]),m:f(i[6]),s:f(i[7]),w:f(i[8])}):null==h?h={}:"object"==typeof h&&("from"in h||"to"in h)&&(g=t(vb(h.from),vb(h.to)),h={},h.ms=g.milliseconds,h.M=g.months),e=new n(h),vb.isDuration(a)&&c(a,"_locale")&&(e._locale=a._locale),e},vb.version=yb,vb.defaultFormat=gc,vb.ISO_8601=function(){},vb.momentProperties=Kb,vb.updateOffset=function(){},vb.relativeTimeThreshold=function(b,c){return oc[b]===a?!1:c===a?oc[b]:(oc[b]=c,!0)},vb.lang=f("moment.lang is deprecated. Use moment.locale instead.",function(a,b){return vb.locale(a,b)}),vb.locale=function(a,b){var c;return a&&(c="undefined"!=typeof b?vb.defineLocale(a,b):vb.localeData(a),c&&(vb.duration._locale=vb._locale=c)),vb._locale._abbr},vb.defineLocale=function(a,b){return null!==b?(b.abbr=a,Jb[a]||(Jb[a]=new l),Jb[a].set(b),vb.locale(a),Jb[a]):(delete Jb[a],null)},vb.langData=f("moment.langData is deprecated. Use moment.localeData instead.",function(a){return vb.localeData(a)}),vb.localeData=function(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return vb._locale;if(!w(a)){if(b=L(a))return b;a=[a]}return K(a)},vb.isMoment=function(a){return a instanceof m||null!=a&&c(a,"_isAMomentObject")},vb.isDuration=function(a){return a instanceof n};for(xb=tc.length-1;xb>=0;--xb)B(tc[xb]);vb.normalizeUnits=function(a){return z(a)},vb.invalid=function(a){var b=vb.utc(0/0);return null!=a?o(b._pf,a):b._pf.userInvalidated=!0,b},vb.parseZone=function(){return vb.apply(null,arguments).parseZone()},vb.parseTwoDigitYear=function(a){return C(a)+(C(a)>68?1900:2e3)},vb.isDate=x,o(vb.fn=m.prototype,{clone:function(){return vb(this)},valueOf:function(){return+this._d-6e4*(this._offset||0)},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var a=vb(this).utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():P(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):P(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},toArray:function(){var a=this;return[a.year(),a.month(),a.date(),a.hours(),a.minutes(),a.seconds(),a.milliseconds()]},isValid:function(){return I(this)},isDSTShifted:function(){return this._a?this.isValid()&&y(this._a,(this._isUTC?vb.utc(this._a):vb(this._a)).toArray())>0:!1},parsingFlags:function(){return o({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(a){return this.utcOffset(0,a)},local:function(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(this._dateUtcOffset(),"m")),this},format:function(a){var b=P(this,a||vb.defaultFormat);return this.localeData().postformat(b)},add:u(1,"add"),subtract:u(-1,"subtract"),diff:function(a,b,c){var d,e,f=M(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=z(b),"year"===b||"month"===b||"quarter"===b?(e=j(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:q(e)},from:function(a,b){return vb.duration({to:this,from:a}).locale(this.locale()).humanize(!b)},fromNow:function(a){return this.from(vb(),a)},calendar:function(a){var b=a||vb(),c=M(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,vb(b)))},isLeapYear:function(){return G(this.year())},isDST:function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},day:function(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=gb(a,this.localeData()),this.add(a-b,"d")):b},month:qb("Month",!0),startOf:function(a){switch(a=z(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a?this.weekday(0):"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this},endOf:function(b){return b=z(b),b===a||"millisecond"===b?this:this.startOf(b).add(1,"isoWeek"===b?"week":b).subtract(1,"ms")},isAfter:function(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+this>+a):(c=vb.isMoment(a)?+a:+vb(a),c<+this.clone().startOf(b))},isBefore:function(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+a>+this):(c=vb.isMoment(a)?+a:+vb(a),+this.clone().endOf(b)<c)},isBetween:function(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)},isSame:function(a,b){var c;return b=z(b||"millisecond"),"millisecond"===b?(a=vb.isMoment(a)?a:vb(a),+this===+a):(c=+vb(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))},min:f("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(a){return a=vb.apply(null,arguments),this>a?this:a}),max:f("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(a){return a=vb.apply(null,arguments),a>this?this:a}),zone:f("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",function(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}),utcOffset:function(a,b){var c,d=this._offset||0;return null!=a?("string"==typeof a&&(a=S(a)),Math.abs(a)<16&&(a=60*a),!this._isUTC&&b&&(c=this._dateUtcOffset()),this._offset=a,this._isUTC=!0,null!=c&&this.add(c,"m"),d!==a&&(!b||this._changeInProgress?v(this,vb.duration(a-d,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,vb.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?d:this._dateUtcOffset()},isLocal:function(){return!this._isUTC},isUtcOffset:function(){return this._isUTC},isUtc:function(){return this._isUTC&&0===this._offset},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(S(this._i)),this},hasAlignedHourOffset:function(a){return a=a?vb(a).utcOffset():0,(this.utcOffset()-a)%60===0},daysInMonth:function(){return D(this.year(),this.month())},dayOfYear:function(a){var b=Ab((vb(this).startOf("day")-vb(this).startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")},quarter:function(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)},weekYear:function(a){var b=jb(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")},isoWeekYear:function(a){var b=jb(this,1,4).year;return null==a?b:this.add(a-b,"y")},week:function(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")},isoWeek:function(a){var b=jb(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")},weekday:function(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")},isoWeekday:function(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)},isoWeeksInYear:function(){return E(this.year(),1,4)},weeksInYear:function(){var a=this.localeData()._week;return E(this.year(),a.dow,a.doy)},get:function(a){return a=z(a),this[a]()},set:function(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else a=z(a),"function"==typeof this[a]&&this[a](b);return this},locale:function(b){var c;return b===a?this._locale._abbr:(c=vb.localeData(b),null!=c&&(this._locale=c),this)},lang:f("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(b){return b===a?this.localeData():this.locale(b)}),localeData:function(){return this._locale},_dateUtcOffset:function(){return 15*-Math.round(this._d.getTimezoneOffset()/15)}}),vb.fn.millisecond=vb.fn.milliseconds=qb("Milliseconds",!1),vb.fn.second=vb.fn.seconds=qb("Seconds",!1),vb.fn.minute=vb.fn.minutes=qb("Minutes",!1),vb.fn.hour=vb.fn.hours=qb("Hours",!0),vb.fn.date=qb("Date",!0),vb.fn.dates=f("dates accessor is deprecated. Use date instead.",qb("Date",!0)),vb.fn.year=qb("FullYear",!0),vb.fn.years=f("years accessor is deprecated. Use year instead.",qb("FullYear",!0)),vb.fn.days=vb.fn.day,vb.fn.months=vb.fn.month,vb.fn.weeks=vb.fn.week,vb.fn.isoWeeks=vb.fn.isoWeek,vb.fn.quarters=vb.fn.quarter,vb.fn.toJSON=vb.fn.toISOString,vb.fn.isUTC=vb.fn.isUtc,o(vb.duration.fn=n.prototype,{_bubble:function(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;g.milliseconds=d%1e3,a=q(d/1e3),g.seconds=a%60,b=q(a/60),g.minutes=b%60,c=q(b/60),g.hours=c%24,e+=q(c/24),h=q(rb(e)),e-=q(sb(h)),f+=q(e/30),e%=30,h+=q(f/12),f%=12,g.days=e,g.months=f,g.years=h},abs:function(){return this._milliseconds=Math.abs(this._milliseconds),this._days=Math.abs(this._days),this._months=Math.abs(this._months),this._data.milliseconds=Math.abs(this._data.milliseconds),this._data.seconds=Math.abs(this._data.seconds),this._data.minutes=Math.abs(this._data.minutes),this._data.hours=Math.abs(this._data.hours),this._data.months=Math.abs(this._data.months),this._data.years=Math.abs(this._data.years),this},weeks:function(){return q(this.days()/7)},valueOf:function(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*C(this._months/12)
},humanize:function(a){var b=ib(this,!a,this.localeData());return a&&(b=this.localeData().pastFuture(+this,b)),this.localeData().postformat(b)},add:function(a,b){var c=vb.duration(a,b);return this._milliseconds+=c._milliseconds,this._days+=c._days,this._months+=c._months,this._bubble(),this},subtract:function(a,b){var c=vb.duration(a,b);return this._milliseconds-=c._milliseconds,this._days-=c._days,this._months-=c._months,this._bubble(),this},get:function(a){return a=z(a),this[a.toLowerCase()+"s"]()},as:function(a){var b,c;if(a=z(a),"month"===a||"year"===a)return b=this._days+this._milliseconds/864e5,c=this._months+12*rb(b),"month"===a?c:c/12;switch(b=this._days+Math.round(sb(this._months/12)),a){case"week":return b/7+this._milliseconds/6048e5;case"day":return b+this._milliseconds/864e5;case"hour":return 24*b+this._milliseconds/36e5;case"minute":return 24*b*60+this._milliseconds/6e4;case"second":return 24*b*60*60+this._milliseconds/1e3;case"millisecond":return Math.floor(24*b*60*60*1e3)+this._milliseconds;default:throw new Error("Unknown unit "+a)}},lang:vb.fn.lang,locale:vb.fn.locale,toIsoString:f("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",function(){return this.toISOString()}),toISOString:function(){var a=Math.abs(this.years()),b=Math.abs(this.months()),c=Math.abs(this.days()),d=Math.abs(this.hours()),e=Math.abs(this.minutes()),f=Math.abs(this.seconds()+this.milliseconds()/1e3);return this.asSeconds()?(this.asSeconds()<0?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"},localeData:function(){return this._locale},toJSON:function(){return this.toISOString()}}),vb.duration.fn.toString=vb.duration.fn.toISOString;for(xb in kc)c(kc,xb)&&tb(xb.toLowerCase());vb.duration.fn.asMilliseconds=function(){return this.as("ms")},vb.duration.fn.asSeconds=function(){return this.as("s")},vb.duration.fn.asMinutes=function(){return this.as("m")},vb.duration.fn.asHours=function(){return this.as("h")},vb.duration.fn.asDays=function(){return this.as("d")},vb.duration.fn.asWeeks=function(){return this.as("weeks")},vb.duration.fn.asMonths=function(){return this.as("M")},vb.duration.fn.asYears=function(){return this.as("y")},vb.locale("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===C(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),Lb?module.exports=vb:"function"==typeof define&&define.amd?(define(function(a,b,c){return c.config&&c.config()&&c.config().noGlobal===!0&&(zb.moment=wb),vb}),ub(!0)):ub()}).call(this);

/*********************
Including file: preview.js
*********************/
/**
 * Preview js - js functions for preview asset page.
 *
 * @package    preview
 * @author     Tik Nipaporn
 * @modified   Laurent
 * @copyright  (c) 2016 Lightrocket
 */
var assetManagerOpener = assetManagerOpener || {};
var preview = {
    
    //Init for original image size
    fileType            : 0,
    mode                : false,
    previous_params     : {},
    next_params         : {},
    recordHit           : true,
    isRemoved           : false,
    URLPrefix           : '',
    // docking status :
    detailsDocked       : false,
    // previous/next preview :
    sessionVarName      : false,
    restrict            : false,
    cpos                : false,
    isShare             : false,
    _microSiteCName     : false,
    isPage              : false,
    avatarExists        : false,
    alreadyLoading      : false,
    logoImg             : '',
    logoAlt             : '',
    logo_width          : 300,
    lastSelect          : false,
    enableDL            : 0,
    swipeMinLength      : 100,
    initSwipeMinLength  : 100,
    back_end            : false,
    fileDetails         : {},
    feedbackVisible     : false,
    
    /**
     * launch a preview window
     *
     * @param  int                asset id to preview
     * @param  [string]        session object name of search object of preview 'group'
     * @return [array int]    array of asset ids to restrict 'group' to
     * @return  void
     */
    launch: function(data) {
        var objName             = (arguments.length>1) ? arguments[1] : '';
        var restrictIDs         = (arguments.length>2) ? arguments[2] : false;
        var currentPos          = (arguments.length>3) ? arguments[3] : false;
        var additionalParams    = (arguments.length>4) ? arguments[4] : false;
        preview.back_end        = (data.back_end !== undefined)?data.back_end:false;
        $.cookie('popup_view'+data.id, 1);
        if(preview.recordHit && !preview.isRemoved) {
            $.ajax({ url: preview._makeURL('preview/add_view_count/' + data.id)});
        }
        // build url for server setup stuff
        var params = restrictIDs ? {sso:objName, restrict:restrictIDs.join(',')} : {sso:objName};
        if(currentPos) params.cpos = currentPos;
        if(preview.isRemoved) $.extend(params, {removed:1});
        if(additionalParams!==false) {
            $.extend(params, additionalParams);
        }
        if (preview.isPage == false) {
            preview._loadPreviewPopup(data, params);
        }
        else if (preview.isPage == true){
            preview._loadPreviewWindow(data, params);
        }
    },
        
    // alternate version to call 'launch' and not use URLPrefix
    /*
     * 
     * @param {type} id
     * @returns {undefined}
     */
    launch_:function(id) {
        var oldPrefix = preview.URLPrefix;
        preview.URLPrefix = '';
        preview.launch.apply(this, arguments);
        preview.URLPrefix = oldPrefix;
    },
    
    /*
     * 
     * @param {type} id
     * @param {type} params
     * @returns {undefined}
     */
    _loadPreviewWindow:function(data, params){
        $('#wrapper').css('background', '#000');
        preview.initializePreview({
            fileType    : data.fileType,
            url_thumb   : data.url_thumb,
            isPage      : data.isPage,
            doPreview   : data.doPreview,
            previewDL   : preview.previewDL,
            context     : false,
        }, "#preview-container");
        preview._showPreviewPopup(data);
    },
    
    /*
     * 
     * @param {type} id
     * @param {type} params
     * @returns {undefined}
     */
    _loadPreviewPopup:function(data, params) {
        if ($('#previewPopupWindow').length == 0){
            var previewDivHtml = '<div id="previewPopupWindow"></div>';
            $('body').append(previewDivHtml);
        }
        preview.initializePreview(data, "#previewPopupWindow");
        /* LOAD CONTENT FROM 'previewPopup' VIEW */
        var url = preview._makeURL('preview/init?id=' + data.id + "&sso="+params.sso+"&cpos="+params.cpos+"&format=json");
        if (params.cshare && params.cshare != '0') {
            url += '&cshare=' + params.cshare;
            preview.isShare = params.cshare;
        }
        $('#previewPopupWindow').css('display','block');
        if (preview.isPage == false) {
            $('body').css('overflow', 'hidden');
        }
        preview.showLoading(true);
        $.ajax({ 
            url: url,
            success: function (data) {
                preview._showPreviewPopup(data);
                preview.loadNavBar();
            },
            error: function(e) { 
                $('#previewPopupWindow').html('');
                $('#previewPopupWindow').css('display','none');
                $('#previewWhileLoading').remove();
                $('body').css('overflow', 'auto');
                alert('Error');
                console.log('Error: ');
                console.log(e);
            },
            dataType: 'json'
        });
    },
    
    initializePreview:function(data, container){
        preview.showScrollButtons(false);
        data.isPage         = (data.isPage !== undefined)?data.isPage:false;
        data.doPreview      = (data.doPreview !== undefined)?data.doPreview:true;
        data.fileType       = (data.fileType !== undefined)?data.fileType:false;
        data.previewDL      = preview.previewDL;
        preview.fileType    = data.fileType;
        preview.context     = (data.context !== undefined && data.context)?data.context:false;
        data.context        = (preview.context)?true:false;
        data.is_selected    = (data.context && $.inArray( data.id, preview.context.selectedItemIds) !== -1)?true:false;
        var content         = preview.popupTemplate(data);
        if (preview.fileType == 'other'){
            preview.fileType = 'image';
        }
        $(container).html(content);
        $("#previewImg").css("background-image", "url('"+data.url_thumb+"')");
        $("#previewImg").addClass("content-type-"+preview.fileType);
        if($(window).width() <= 1024){
            //calculate height of thumb
            var path = data.url_thumb.split(".");
            delete path[path.length - 1];
            var thumbSelector = 'img[src^="'+path.join(".").replace(/\.+$/,'')+'_"], img[src^="'+path.join(".").replace(/\.+$/,'')+'."]';
            var realWidth = $(thumbSelector).width();
            var realHeight = $(thumbSelector).height();
            var height = parseInt(realHeight/(realWidth/$(window).width()));
            height = (height === undefined || height>$(window).height())?$(window).height():height;
            $("#ImageBlock").css("height", height+"px");
        }
        preview.initializeCloseHandlers();
    },

    _hidePreviewPopup:function(){
        $('#previewPopupWindow').html('');
        $('#previewPopupWindow').css('display','none');
        $('body').css('overflow', 'auto');
        if (!$('#email_asset_form').hasClass('hideMe')){
            $('#email_asset_form').addClass('hideMe');
        }
        $('#contribContact_btn_cancel_email').off('click');
        preview.resetKeyBind();
        if ($('#contextMenu').length){
            $('#contextMenu').remove();
        }
         $('#previewPopupWindow').off("click");
    },
    
    storeAssetDetails:function(data){
        preview.fileDetails = {
            description         : data.asset.description,
            created_on          : data.asset.created_on,
            credit              : data.asset.credit,
            copyright_notice    : data.asset.copyright_notice,
            filename            : data.asset.original_filename,
            width               : data.asset.width,
            height              : data.asset.height,
            location            : data.asset.location,
            country             : data.asset.country ,
            city                : data.asset.city,
            filesize            : data.asset.filesize,
            nb_pages            : data.asset.nb_pages,
        };
        if(data.pages != undefined){
            preview.fileDetails.pages = data.pages;
        }
    },

    formatDate: function(date, hideTime) {
        // currently, new dates are either in the following formats: (dd/mm/yyyy H:i:s) or (dd/mm/yyyy) or (yyyy)
        // however, there are ancient dates that are stored in different formats
        // to ensure that the metadata link is correct, let's make the date format uniform
        dateformat = [
            'DD/MM/YYYY',
            'YYYY-MM-DD',
            'MM/DD/YYYY',
            'YYYY-DD-MM',
        ];

        // we don't do anything for year only dates
        if (date.length >= 10) {
            $.each(dateformat, function(key, val) {
                dateTimeMoment = moment(date, val + ' HH:mm:ss', true);
                dateMoment = moment(date, val);
                if (dateTimeMoment.isValid()) {
                    date = dateTimeMoment.format('DD/MM/YYYY HH:mm:ss');
                    return false;
                } else if (dateMoment.isValid()) {
                    date = dateMoment.format('DD/MM/YYYY');
                    return false;
                }
            });

            if (date.length > 10 && hideTime) {
                date = date.split(' ')[0];
            }
        }

        return date;
    },
    
    _showPreviewPopup:function(data){
        if(data.doPreview == false){
            alert(lang.preview.msg_cannotPreview);
            preview._hidePreviewPopup();
            return false;
        }
        preview.storeAssetDetails(data);
        /* SHOW CONTENT LOADED */
        data.socialmedia = preview.socialmediaTemplate({
            url     : encodeURIComponent(APP.baseURL + "preview/" + data.asset.id),
            img_url : encodeURIComponent(data.asset.previewURL),
            desc    : encodeURIComponent(data.captionbit),
            flagged : data.asset.flagString,
        });
        data.manageFileEnabled = !$.isEmptyObject(assetManagerOpener);
        data.asset.date_created = preview.formatDate(data.asset.date_created, data.dateCreatedHideTime);
        data.asset.flagIcons = flags.makeFlagIconList(data.asset.flags, preview.flagTemplate);
        $('#flagIcons').html(data.asset.flagIcons);

        let toStrip = ["<p>\xa0</p>","<p>&nbsp;</p>"];
        $.each(toStrip, function(){
            if(preview.fileDetails.description.substr(-this.length) == this) 
                data.asset.description = preview.fileDetails.description.substr(0,preview.fileDetails.description.length-this.length);
        });

        let content = preview.blockContentTemplate(data);

        if(data.isRemoved) alert(lang.preview.msg_RemovedAsset, {background_color:"#ff8800"});
        $('#previewImg').html(data.imgHTML+'<div id="overlay_img"></div>');
        if (preview.fileType == 'image') {
            $('#previewImg img').load(function() {
                preview.afterLoading();
            });
        }
        else preview.afterLoading();
        $('#previewBlockDetails').html(content);
        if(!data.isRemoved){
            if(preview.isPage) APP._userKey = ((data.user && data.asset.user_id === data.user.id)?data.user.downloadKey:0);
            preview.sessionVarName = (data.sessionVarName !== undefined)?data.sessionVarName:"";
            preview.restrict = (data.restrict !== undefined)?data.restrict:"";
            preview.cpos = (data.cpos !== undefined)?data.cpos:"";
        }
        $("#assetid").val(data.asset.id);
        $("#ownasset").val((data.user || data.user.id === data.asset.user_id)?1:0);
        $("#assetAuthor").val(data.asset.author);
        preview.isShare = (data.isShare !== undefined && data.isShare)?data.isShare:0;
        preview.sid = (data.sid !== undefined)?data.sid:"";
        preview.forceHTTP = data.forceHttp;
        preview.imageWidthOriginal = (data.imgWidth !== undefined)?data.imgWidth:"";
        preview.imageHeightOriginal = (data.imgHeight !== undefined)?data.imgHeight:"";
        preview.enableDL = data.previewDL;
        preview.isDownloadable = data.isDownloadable;
        preview.contribContact = data.contribContact;
            
        //share with facebook popup
        $('.popShare.facebook').click(function(e) {
            e.preventDefault();
            window.open($(this).attr('href'), 'fbShareWindow', 'height=450, width=550, top=' + ($(window).height() / 2 - 275) + ', left=' + ($(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
            return false;
        });
        preview.initializeRightClick();
        preview.initializeActions();
        preview.initializeTabs();
        preview.initializeKeywordTab();            
        preview.initializeDetailsDocking();
        preview._setupPreviewPrintFrame();
        preview.checkPopupSize();
        $(window).resize(preview.checkPopupSize);
        $('#previewBlockContent').niceScroll();
        preview.setReadMore();
    },
    setReadMore:function(content) {
        let elt = $(".description-container");
        if(elt.length == 0) return false;
        elt.addClass("truncated");
        if(elt[0].clientHeight == elt[0].scrollHeight) elt.removeClass("truncated");

        $(document).on("click", ".read-more-lnk", function() {
            const parentElement = $(this).closest(".ckeditor-content");
            const content = parentElement.find(".description-container");
            content.removeClass("truncated");
            parentElement.find(".read-less-lnk").removeClass("hideMe");
        });

        $(document).on("click", ".read-less-lnk", function() {
            const parentElement = $(this).closest(".ckeditor-content");
            const content = parentElement.find(".description-container");
            content.addClass("truncated");
            $(this).addClass("hideMe");
        });
    },
    checkPopupSize:function(){
        var imgH = $("#ImageBlock").height();
        var screenH = $(window).height();
        var ImgPercent = 1/(screenH/imgH)*100;
        preview.showScrollButtons(ImgPercent>90);
    },
    showScrollButtons:function(state){
        $(".btn-scroll")[state?"removeClass":"addClass"]("hideMe");
    },
    afterLoading:function(){
        $("#ImageBlock").attr("style", "");
        $('#previewImg').css('background','none');
        preview.showLoading(false);
        preview.loadMultiPage();
    },
    showLoading:function(state){
        $("#ImageBlock .overlayLoading")[state?"removeClass":"addClass"]("hideMe");
    },
    loadMultiPage:function(){
        $("#ImageBlock").removeClass("multi-page");
        if(preview.fileDetails.pages !== undefined && preview.fileDetails.pages.length > 0){
            $("#ImageBlock").addClass("multi-page");
            $.each(preview.fileDetails.pages, function(){
                $("#previewImg").append("<img src=\""+this+"\" />");
            });
        }
    },
    initializeRightClick:function(){
        //If Can Download Preview (only image and other)
        if (preview.fileType == 'image') {
            $('#previewPopupWindow').off("mousedown").on("mousedown",function(e){
                if(e.which === 3) e.preventDefault(); //prevent default for right click
                if ($('#contextMenu').length){
                    $('#contextMenu').remove();
                }
            }); 
            preview._handleRightClick();
        }
    },
    initializeActions:function(){
        /* Downloadable action */
        $('#previewMainContent a[href="#"]').on('click', function(e){e.preventDefault()}); //Prevent go to top unwanted
        $('a.resultDL').on('click', function(e){
            if(typeof sharefiles == "undefined")
                download.begin($('#assetid').attr('value'),preview.back_end);
            else{
                sharefiles.handleAllSelection(false);
                results.assetSelect($('#assetid').attr('value'));
                sharefiles._handleDownload();
            }

        });
        // setup 'add to lightbox' links
        $('a.addToLbxFromPrev').on('click', function(e){
            e.stopPropagation();
            addToLightbox.begin();
        });
        if ($('#add_lightbox_form').length && preview.isPage == false) {
            var element = $('#add_lightbox_form').detach();
            $('body').append(element);
        }
        $('#add_lightbox_form').jqm({overlay: 50, trigger: false});
        $('#calcelAddToLbx').on('click', function(e){e.preventDefault();$('#add_lightbox_form').jqmHide();});
        $('#saveAddToLbx').on('click', function(e){e.preventDefault();preview.addToLightbox();});
        $(document).keydown(function(e){
            // press escape to delete
            if ($('#add_lightbox_form').css('display')=='block' && e.which==27) $('#add_lightbox_form').jqmHide();
        });
        if (preview.isPage == false) {
            $('#add_lightbox_form').mouseenter(function(){});
        }
        // social icon positionning
        if (!preview.isDownloadable && !preview.contribContact){
            $('.assetOpts .share>div').addClass('social_left');
        }
        // add email share
        $('#comblc_icons .assetOpts .share .social_icons').append('<a title="'+lang.search_results.lbl_ShareViaEmail+'" href="#" id="shareInPreview" class="email"></a>');
        $('#comblc_icons .assetOpts .share .social_icons .email').off('click');
        $('#comblc_icons .assetOpts .share .social_icons .email').on('click', function(event){
            event.preventDefault();
            sharePreview.begin({
                fullname: user.fullname,
                asset_id: $('#assetid').val(),
                prefix:"",
            });
        });
        $('#comblc_icons .assetOpts .share .social_icons').append('<a title="' + lang.common.lbl_copyLink + '" href="#" data-link="'+($('#assetid').attr('value')/1)+'" class="copylink"></a>');
        $('#comblc_icons .assetOpts .share .social_icons .copylink').off('click');
        $('#comblc_icons .assetOpts .share .social_icons .copylink').on('click', function(event){
            event.preventDefault();
            APP.copyToClipboard(APP.baseURL + 'preview/' + $(this).data('link'));
            alert(lang.common.msg_copiedToClipboard);
        });
        $('a.assetFeedback').on('click', function(event){
            event.preventDefault();
            preview.feedbackVisible = true;
            assetFeedback.begin({
                fullname: user.fullname,
                asset_id: $('#assetid').val(),
                prefix:"",
            });
        });
        //Allow printing
        $('a.assetPrint').on('click', function(event){
            event.preventDefault();
            preview.printPreviewPage();
        });
        $('a.manageFile').on('click', function(event){
            event.preventDefault();
            assetManagerOpener.open({metadataEditor:"",assetIdSelect:$('#assetid').attr('value')});
        });
        // setup 'Contact Contributor' links
        $('a.assetContactContrib').on('click', function(e) {
            e.preventDefault();
            preview.resetKeyBind();
            var link        = $(this);
            var contribID   = link.attr('data-contribid')/1;
            var assetID     = $('#assetid').attr('value')/1;
            preview.contactAssetContributor(contribID, assetID);
        });
        $('#assetSelection').on('click', function(e){
            e.preventDefault();
            var asset_id = parseInt($('#assetid').val());
            var asset = preview.context.collection._byId[asset_id];
            if($(this).hasClass('selected')){
                if(asset != undefined && asset) preview.context.collection._byId[asset_id].set('selected', false);
                preview.context.selectedItemIds = $.grep(preview.context.selectedItemIds, function(value) { return value != asset_id; });
                $(this).removeClass('selected');
            }
            else{
                preview.context.selectedItemIds.push(asset_id);
                $(this).addClass('selected');
            }
            assetSelector.selectAssets({}, preview.context.selectedItemIds, true);
        });
        if($('#asset-extra-info').length){
            $info = $('#asset-extra-info');
            $info.on('click', '*', function(e){
                if( !$info.hasClass('opened') ) $info.addClass("opened");
            });
            $info.on('click', '.close_displayed_info', function(e){
                $info.removeClass("opened");
            });
            if ($('#asset-flag-string').length ) $info.css('margin-top', "10px");
        }
        $('.simple_search').on('click', function(e) {e.preventDefault();preview.linkSimpleSearch($(this));});
        new Clipboard('#previewMainContent .copy-field-clipboard');
        $('.dotolltip').tooltip();
        $("#previewMainContent .copyAllData").click(preview._copyAllMetadata);
    },
    _copyAllMetadata:function(){
        navigator.clipboard.writeText(preview.getMetadataHoverText());
        alert(lang.common.msg_copiedToClipboard);
    },
    getMetadataHoverText:function(){
        let text = "";
        if($("#ctblc_headline").length > 0) text += $("#previewMainContent #ctblc_headline span").text()+"\n";
        if($("#previewMainContent #ctblc_desc p").length > 0){
            $.each($("#previewMainContent #ctblc_desc p"), function(){
                if($.inArray($(this).text().trim(),['','\xa0']) == -1) text += $(this).text()+"\n";
            });
        }
        else{
            text += $("#previewMainContent #ctblc_desc .description-container").text()+"\n";
        }
        if($("#assetCountry").length > 0) text += lang.assetdata.lbl_Country + " : " + $("#assetCountry").text()+"\n";
        if($("#dateCreated").length > 0) text += lang.assetdata.lbl_DateCreated + " : " + $("#dateCreated").text()+"\n";
        if($("#assetCredit").length > 0) text += lang.assetdata.lbl_Credit + " : " + $("#assetCredit").text()+"\n";
        if($("#copyrightNotice").length > 0) text += lang.assetdata.lbl_CopyrightNotice + " : " + $("#copyrightNotice").text()+"\n";
        if($("#referencePreview").length > 0) text += lang.assetdata.lbl_reference + " : " + $("#referencePreview").text()+"\n";
        return text;
    },
    
    initializeCloseHandlers:function(){
        /* to prevent click to close popup */
        if (preview.isPage == false) {
            $('#previewPopupWindow').on('click', function(e){
                if(e.target === e.delegateTarget)
                    preview._hidePreviewPopup();
            });
            $('#previewPopupWindow').on('click', ".btn-close-popup", preview._hidePreviewPopup);
        }
    },
    initializeTabs:function(){
        var count_menu_items = $('ul#previewBlockMenu li').length;
        $('ul#previewBlockMenu li').each(function(i){
            if (i == 0) {
                $('#' + this.id).addClass('menu_selected');
            }
            if (i < (count_menu_items - 1 )) {
                $('#' + this.id).css('border-right','solid 1.5px #f0f0f0');
            }
            $('#' + this.id).css('width', ((100 / count_menu_items) - 1) + '%');
        });
        /* display content details */
        $('#previewBlockContent > div').each(function(i){
            if (i>0) {$('#' + this.id).addClass('menu_content_hidden');}
        });
        $('#previewBlockMenu li').on('click', function(event){
            $('ul#previewBlockMenu li').removeClass('menu_selected');
            $('#' + this.id).addClass('menu_selected');
            $('#previewBlockContent > div').each(function(){
                $('#' + this.id).addClass('menu_content_hidden'); 
            });
            $('#' + this.id + 'Tab').removeClass('menu_content_hidden');
            if(this.id == 'menuKeywords'){
                $('.lbl_chkbox').each(function(){
                    var diff = ($(this).parent().width() - ($(this).width()+ 13));
                    if (diff <=5) {
                        $(this).parent().css('width','61%');
                    }
                });
            }
        });
    },
    initializeKeywordTab:function(){
        /* keywords section */
            
        preview.disableSelect(true, "#menuKeywordsTab ul li");

        $("#menuKeywordsTab ul li").off("click");
        $("#menuKeywordsTab ul li").on("click", function(event){
            var isShiftClick = event.shiftKey;
            if(isShiftClick && preview.lastSelect !== false){
                document.getSelection().removeAllRanges();
                var that = this;
                var from = (preview.lastSelect > $(that).index())?$(that).index():preview.lastSelect;
                var to = (preview.lastSelect > $(that).index())?preview.lastSelect:$(that).index();
                $.each($("#menuKeywordsTab ul li"), function(id, elt){
                    if(id >= from && id <= to) $(this).addClass("kwSelected");
                    else $(this).removeClass("kwSelected");
                });
            }
            else {
                if($(this).hasClass("kwSelected"))$(this).removeClass("kwSelected");
                else $(this).addClass("kwSelected");
                preview.lastSelect = $(this).index();
            }
        });

        $('#select_all').on('click', preview.selectAllKeywords);
        $('.lbl_chkbox').on('click', function(){
            var id = $(this).attr('for');
            if($('#' + id).is(':checked')) {
                $('#select_all_input').attr('checked', false);
            }
        });
        $('#key_search').on('click', preview.doKeywordsSearch);
    },
    centeringVideo:function(){
        return;
    },
        
    horizontalCenteringPreviewVideo:function(refWidth){
        return;
    },

    spinnerhtml:function(){
    },
        
    initializeDetailsDocking:function(){
        $("#previewMainContent")[preview.isDetailsDocked()?"addClass":"removeClass"]("dock-details");
        $('.btn-dock-details').on('click', function(e){
            e.preventDefault();
            preview.openCloseBlockDock('change');
        }); //Docking action
        $('.btn-scrollup-popup').on('click', function(e){
            e.preventDefault();
            preview.scollToImage();
        });
        $('.btn-scrolldown-popup').on('click', function(e){
            e.preventDefault();
            preview.scollToDetails();
        });
    },
    isDetailsDocked:function(){
        return (localStorage["detailsDocked"] == undefined || localStorage["detailsDocked"] == "0")?false:true;
    },        
    openCloseBlockDock:function(action){
        $("#previewMainContent").toggleClass("dock-details");
        localStorage["detailsDocked"] = $("#previewMainContent").hasClass("dock-details")?"1":"0";
    },
    scollToImage:function(){
        $("#previewMainContent").animate({
            scrollTop: 0
        }, 500,'swing');
    },
    scollToDetails:function(){
        $("#previewMainContent").animate({
            scrollTop: $("#previewBlockTop").offset().top
        }, 500,'swing');
    },

    enableBlockTransitions:function(){
    },
        
    disableBlockTransitions:function(){
    },

    _handleRightClick:function(){
        // FOR DOWNLOADING PREVIEW
        $("#overlay_img").contextmenu(function(e) {
            if ($('#contextMenu').length){
                $('#contextMenu').remove();
            }
            var details = {
                imgLink     : $('#previewImg img').attr('src'),
                DLavailable : preview.enableDL,
                prev        : $('.AssetChangePreview.prev').length,
                next        : $('.AssetChangePreview.next').length
            };
            var contextMenuHTML = _.template($('#template-context-menu').html());
            
            //paste popup menucontent
            $('body').append(contextMenuHTML(details));
            
            //trigger actions
            $('.menuCol.download a').off('click').on('click', function(){$('#contextMenu').remove();});
            $('.menuCol.prev a').off('click').on('click', function(){$('.AssetChangePreview.prev').click();$('#contextMenu').remove();});
            $('.menuCol.next a').off('click').on('click', function(){$('.AssetChangePreview.next').click();$('#contextMenu').remove();});
            $('.menuCol.close-preview a').off('click').on('click', function(){preview._hidePreviewPopup();});
            
            $('#contextMenu').css({
                'top'   : e.pageY + 'px',
                'left'  : e.pageX + 'px',
            });
            return false;
        });    
    },

    loadChangePreview:function(prevNext) {
        data = (prevNext == "next")?preview.next_params:preview.previous_params;
        if (preview.alreadyLoading == false){
            preview.alreadyLoading = true;            
            var url = APP.baseURL + 'preview/previous_next';
            preview.initializePreview({
                id          : data.asset_id,
                fileType    : preview[(prevNext == "next")?"nextType":"prevType"],
                url_thumb   : preview[(prevNext == "next")?"nextThumb":"prevThumb"],
                context     : preview.context?preview.context:false,
            },"#previewPopupWindow");
            $.post(url, data, function(res){
                preview._showPreviewPopup(res);
                preview.loadNavBar();
                preview.alreadyLoading = false;
            },"json");
        }
    },

    /**
    * select for all keywords
    */
    selectAllKeywords:function() {
        if($('#' + this.id + '_input').is(':checked')) {
            $('.lbl_chkbox').each(function(){
                var id = $(this).attr('for');
                $('#' + id).attr('checked', false);
            });
        }
        else{
            $('.lbl_chkbox').each(function(){
                var id = $(this).attr('for');
                $('#' + id).attr('checked', true);
            });
        }
    },

    /**
     * Contact a contributor about an asset
     *
     * @param    id of asset to view
     */
    contactAssetContributor:function(contribID, assetID) {
        var link = APP.baseURL+'preview/'+assetID;
        var applyForm = ContribMessenger.launch(contribID, {
                relatesTo       :   lang.contributors.sendMessageAboutAsset,
                relatesToLink   :   link,
                assetID         :   assetID
        });
        $.when(applyForm).done(function(){
            if (preview.isPage == false) {
                $('#contribContact_btn_cancel_email').on('click',function(){
                    $('body').css('overflow', 'hidden');
                    preview.handleKeyBind();
                });
                $('.jqmOverlay').on('click',function(){
                    $('body').css('overflow', 'hidden');
                    preview.handleKeyBind();
                });
            }
            else {
                $('#contribContact_btn_cancel_email').on('click',function(){
                    $('body').css('overflow', 'auto');
                });
                $('.jqmOverlay').on('click',function(){
                    $('body').css('overflow', 'auto');
                });
            }
        });

    },

    responsify_img:function(){
        return;
        $.fn.responsify = function() {
            return this.each(function() {
                var owidth, oheight,
                    twidth, theight,
                    fx1, fy1, fx2, fy2,
                    width, height, top, left,
                    $this = $(this);

                owidth = $this.width();
                oheight = $this.height();
                twidth = $this.parent().width();
                theight = $this.parent().height();
                fx1 = Number($this.attr('data-focus-left'));
                fy1 = Number($this.attr('data-focus-top'));
                fx2 = Number($this.attr('data-focus-right'));
                fy2 = Number($this.attr('data-focus-bottom'));
                if( owidth/oheight > twidth/theight ) {
                  var fwidth = (fx2-fx1) * owidth;
                  if ( fwidth/oheight > twidth/theight ) {
                    height = oheight*twidth/fwidth;
                    width = owidth*twidth/fwidth;
                    left = -fx1*width;
                    top = (theight-height)/2;
                  } else {
                    height = theight;
                    width = theight*owidth/oheight;
                    left = twidth/2 - (fx1 + fx2)*width/2;
                    // if left > 0, it will leave blank on the left, so set it to 0;
                    left = left>0?0:left;
                    // if width - left < twidth, it will leave blank on the right, so set left = width - twidth
                    left = (twidth - left - width)>0?(twidth-width):left;
                    top = 0;
                  }
                }
                else {
                  var fheight = (fy2-fy1) * oheight;
                  if ( fheight/owidth > theight/twidth ) {
                    width = owidth*theight/fheight;
                    height = oheight*theight/fheight;
                    top = -fy1*height;
                    left = (twidth-width)/2;
                  } else {
                    width = twidth;
                    height = twidth*oheight/owidth;
                    top = theight/2 - (fy1 + fy2)*height/2;
                    // if top > 0, it will leave blank on the top, so set it to 0;
                    top = top>0?0:top;
                    // if height - top < theight, it will leave blank on the bottom, so set top = height - theight
                    top = (theight - top - height)>0?(theight-height):top;
                    left = 0;
                  }
                }
                $this.parent().css({
                  "overflow": "hidden"
                })
                $this.css({
                  "position": "relative",
                  "height": height,
                  "width": width,
                  "left": left,
                  "top": top
                })
            });
        };  
        
    },

    /**
     * Launching Other URLs from Preview
     *
     * @param  string  url for search
     * @return  void
     */
    launchURL: function(url) {
        window.location.href=url;
    },
    
    /**
     * Builds a search URL from a provided object containing the search parameters
     * @param  obj parameter for search
     *
     * @return  string url for search
     */
    buildSearchURL: function(params) {
        var str_param = '?s[adv]=1';
        $.each(params, function(key, val) {
            if(key == 'keywords') {
                var keywords = [];
                if (!$.isArray(val)) val = [val];
                $.each(val, function(i, str) {
                    if(str.indexOf(' ') != -1){
                        str = str.replace(/\"/g,'');
                        keywords[i] = '"'+str+'"';
                    }else{
                        keywords[i] = str;
                    }
                });
                val = keywords.join(' ');
            }
            str_param += '&s['+key+']='+ encodeURIComponent(val);
        });

        var url = preview._makeURL('search/do'+str_param);
        return url;
    },

    /**
     * contributorSearch
     *
     * @param  integer contributorid
     * @return  void
     */
    contributorSearch: function(contributorid) {
        preview.launchURL(preview.buildSearchURL({contributor: contributorid}));
    },

    /**
     * _makeURL
     *
     * @param  string final segments of URL
     * @return  Full URL (wih APP base url and URLPrefix added to front)
     */
    _makeURL: function(mainURL) {
        var url = preview._microSiteCName?"http://"+preview._microSiteCName+"/":APP.baseURL;
        return url + preview.URLPrefix + mainURL;
    },

    /**
     * linkSimpleSearch
     *
     * @param  obj link for searching
     * @return  void
     */
    linkSimpleSearch: function(obj) {
        var params = {};
        var val = obj.data('val');
        var key = obj.data('search');

        if (key == 'date_created') {
            if (val.toString().length == 4) {
                // search for whole year
                params['datefrom']  = '01/01/' + val;
                params['dateto']    = '31/12/' + val;
            } else {
                if (moment(val, 'DD/MM/YYYY').isValid()) {
                    params['datefrom'] = params['dateto'] = val.split(' ')[0];
                } else {
                    preview._hidePreviewPopup();
                    alert(lang.preview.msg_InvalidDateFormat);
                }
            }
        } else {
            params[key] = val;
        }

        if (Object.entries(params).length !== 0) {
            preview.launchURL(preview.buildSearchURL(params));
        }
    },

    /**
    * prepare keyword search then
    */
    doKeywordsSearch:function(){
        var txts = [];
        $.each($("#menuKeywordsTab ul li.kwSelected span"), function(){
            var kword = $(this).text();
            txts.push(kword);
        });
        if(txts.length > 0) {
            preview.launchURL(preview.buildSearchURL({keywords: txts}));
        }
        else{
            alert(lang.preview.msg_PleaseSelectKeyword);
        }
    },

    disableSelect:function(state){
        var selector = (arguments.length > 1)? arguments[1]:"#previewMainContent";
        $(selector).css("-webkit-touch-callout", state?"none":"auto");
        $(selector).css("-webkit-user-select", state?"none":"auto");
        $(selector).css("-khtml-user-select", state?"none":"auto");
        $(selector).css("-moz-user-select", state?"none":"auto");
        $(selector).css("-ms-user-select", state?"none":"auto");
        $(selector).css("user-select", state?"none":"auto");
    },
    
    /**
     * load a new page of download usage
     *
     * @return  void
     */
    _goPage: function(pgNum) {
        $('h2.usage + div').block({ message: null,  overlayCSS: { backgroundColor: '#fff' } });
        var url = preview._makeURL('preview/followuppage');
        $.post(url, {id:$('#assetid').val(), pg:pgNum},    function(data){
            $('h2.usage + div').html(data).unblock();
        });
    },
    
    _setupPreviewPrintFrame:function(){
        $('#print_frame').remove();
        $('body').append('<iframe id="print_frame" name="print_frame" width="10" height="10" frameborder="0" src="about:blank"></iframe>');
        var title = '<title>' + $('input#assetAuthor').attr('value') + '-' + $('#file_title').text() + '</title>';
        var popup_print = window.frames["print_frame"];
        popup_print.document.head.innerHTML = title;
        popup_print.document.body.innerHTML = preview.previewPrintFormat();
    },
    
    /**
     * print preview page
     *
     * @return  void
     */
    printPreviewPage:function(){
        var popup_print = window.frames["print_frame"];
        popup_print.window.focus();
        if (preview.checkBrowserIE()) popup_print.document.execCommand('print', false, null);
        else {
            popup_print.window.print();
        }
    },
    
    /**
     * HTML print template filled
     * 
     * @returns string 
     */
    previewPrintFormat:function(){
        preview.fileDetails.headingTitle    = $('#headingTitle').length?$('#headingTitle').text():0;
        preview.fileDetails.contrib_name    = $('#contrib_name').text();
        preview.fileDetails.previewImg      = $('#previewImg img').attr('src');
        preview.printTemplate               = _.template($("#template-print-preview").html());
        return preview.printTemplate(preview.fileDetails);
    },
    
    /**
     * Check if browser is IE
     * 
     * @returns {Boolean}
     */
    checkBrowserIE:function(){
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var ie = false;
        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) ie = true;
        return ie;
    },

    /**
    * fix preview links
    *
    * @return  void
    */
    _fixPreviewLinks:function() {
        // fix preview Links on results if we need to
        var resultPreviewLinks = $('#searchResults a[tag].resView');
        if (resultPreviewLinks.length && preview.URLPrefix!=='') {
            resultPreviewLinks.each(function() {
                var o = $(this);
                o.attr('href', o.attr('href').replace(APP.baseURL, APP.baseURL+preview.URLPrefix));
            });
        }
    },
        
    loadNavBar:function(){
        var url = preview._makeURL('preview/getnavdetails');
        $.ajax({
            type: "GET",
            url: url,
            data: {'sessionVarName':preview.sessionVarName, 'restrict':preview.restrict, 'cpos':preview.cpos, 'isShare':preview.isShare, 'sid':preview.sid},
            async: true,
            success:function(data){
                if (data != null){
                    preview.updateNavBar(data);
                    if ($('#contextMenu').length){
                        $('#contextMenu').remove();
                    }
                }
                else {
                    $('#curPosition').remove();
                }
            },
            error: function(e) {
                console.log('Error : ');
                console.log(e);
            },
            dataType: 'json',
        });
    },
        
    updateNavBar:function(data){
        $('#curPosition').html(data.current_position);
        preview.prevThumb = data.previous_asset.url_thumb;
        if(data.previous_asset.id)
            $("#previousThumb").css("background-image", "url('"+preview.prevThumb+"')");
        $("#previousThumb").removeClass(function (index, className) {return (className.match (/(^|\s)content-type-\S+/g) || []).join(' ');});
        $("#previousThumb").addClass("content-type-"+data.previous_asset.fileType);
        preview.prevType = data.previous_asset.fileType;
        preview.previous_params = {
            asset_id:data.previous_asset['id'],
            sso:'assetGroupSearch',
            cpos:data.previous_asset['ppos'],
            sid:data.previous_asset['sid'],
            format:"json"
        };
        preview.nextThumb = data.next_asset.url_thumb;
        if(data.next_asset.id)
            $("#nextThumb").css("background-image", "url('"+preview.nextThumb+"')");
        $("#nextThumb").removeClass(function (index, className) {return (className.match (/(^|\s)content-type-\S+/g) || []).join(' ');});
        $("#nextThumb").addClass("content-type-"+data.next_asset.fileType);
        preview.nextType = data.next_asset.fileType;
        preview.next_params = {
            asset_id:data.next_asset['id'],
            id:data.next_asset['id'],
            sso:'assetGroupSearch',
            cpos:data.next_asset['npos'],
            sid:data.next_asset['sid'],
            format:"json"
        };
        if(preview.isShare) preview.previous_params.cshare = preview.isShare;
        if(preview.isShare) preview.next_params.cshare = preview.isShare;
        /* PREVIOUS PREVIEW */
        if (preview.previous_params.asset_id) {
            if ($('.AssetChangePreview.prev').length == 0) {
                $("#ImageBlock").append('<div class=" AssetChangePreview prev"></div>');
            }
            $('.AssetChangePreview.prev').on('click', function(e){
                e.preventDefault();
                e.stopPropagation();
                $('.AssetChangePreview.prev').off('click');
                this.disabled=true;
                preview.clickPrevNext("previous");
            });
            $("body").keydown(function(e) {
                if(e.keyCode == 37 && preview.feedbackVisible == false) { // right
                    preview.clickPrevNext("previous");
                }
            });
        }
        /* NEXT PREVIEW */
        if (preview.next_params.asset_id) {
            if ($('.AssetChangePreview.next').length == 0) {
                $("#ImageBlock").append('<div class="AssetChangePreview next"></div>');
            }
            $('.AssetChangePreview.next').on('click', function(e){
                e.preventDefault();
                e.stopPropagation();
                $('.AssetChangePreview.next').off('click');
                this.disabled=true;
                preview.clickPrevNext("next");
            });
            $("body").keydown(function(e) {
                if(e.keyCode == 39 && preview.feedbackVisible == false) { // left
                    preview.clickPrevNext("next");
                }
            });
        }
        $('#overlay_img').off("mouseup").off("mousedown").mousedown(function(e){
            e.stopPropagation();
            preview.touchstart(e.pageX);
        }).mouseup(function(e){
            e.stopPropagation();
            preview.touchend(e.pageX);
        });
        $('#overlay_img').off("touchstart").off("touchend").on("touchstart",function(e){
            e.stopPropagation();
//            preview.swipeMinLength = preview.initSwipeMinLength;
            preview.touchstart(e.originalEvent.touches[0].pageX);
        }).on("touchend", function(e){
            e.stopPropagation();
            preview.touchend(e.originalEvent.changedTouches[0].pageX);
        }).on("touchmove", function(e){
            e.stopPropagation();
            preview.touchmove(e.originalEvent.targetTouches[0].pageX);
        });
    },
    touchstart:function(pos){
        preview.swipeStart = pos;
    },
    touchend:function(pos){
        $("#previewImg img,#previewImg  #flashvideo").css("margin-left", "0");
        $("#previousThumb").css("transform", "translateX(0px)");
        $("#nextThumb").css("transform", "translateX(0px)");
        if(preview.swipeStart){
            preview.swipeStop = pos;
            if(Math.abs(preview.swipeStart - preview.swipeStop) >= preview.swipeMinLength){
                preview.clickPrevNext(((preview.swipeStart - preview.swipeStop) >= 0)?"next":"previous");
            }
        }
        preview.swipeStart = false;
        preview.swipeStop = false;
    },
    touchmove:function(pos){
        if(preview.swipeStart){            
            $("#previewImg img,#previewImg  #flashvideo").css("margin-left", (-(preview.swipeStart - pos))+"px");
            $("#previousThumb").css("transform", "translateX("+(pos-preview.swipeStart)+"px)");
            $("#nextThumb").css("transform", "translateX("+(pos - preview.swipeStart)+"px)");
        }
    },
    clickPrevNext:function(prevNext){
        if(preview[(prevNext == "next")?"next_params":"previous_params"].asset_id){
            preview.showLoading(true);
            preview.loadChangePreview(prevNext);
        }
    },
        
    handleKeyBind:function(){
        preview.resetKeyBind();
        if (preview.isPage == false) {
            $("body").keydown(function(e) {
                e.preventDefault();
                if(e.keyCode == 37) { // right
                    preview.loadChangePreview("previous");
                }
                if(e.keyCode == 39) { // left
                    preview.loadChangePreview("next");
                }
                if (e.keyCode == 27) { // escape
                    preview._hidePreviewPopup();
                }
                if (e.keyCode == 32) { // spacebar
                    preview.openCloseBlockDock('change'); 
                }
            });
        }
    },
        
    resetKeyBind:function(){
        $("body").off('keydown');
        $("body").off('keyup');
        $("body").on('keydown');
        $("body").on('keyup');
    },

    setup:function(){
        preview.flagTemplate            = _.template($("#flag-icon-template").html());
        preview.popupTemplate           = _.template($("#popup-template").html());
        preview.blockContentTemplate    = _.template($("#block-details-template").html());
        preview.socialmediaTemplate     = _.template($("#socialmedia-template").html());
        if (preview.isPage == true) {
            data    = preview.pageVars;
            data.id = data.asset.id;
            preview.launch(data);
        }
    }
};
$(function(){
    preview.setup();
});



(function() {
addToLightbox = $.extend({}, dialog,{
    _setup:function(){
        addToLightbox.listTemplate = _.template($("#template-add-to-lightbox").html());
        addToLightbox.listItemTemplate = _.template($("#template-lightbox-item").html());
        if(addToLightbox.hiding){
            setTimeout(function(){addToLightbox.begin(options)}, 500);
            return;
        }
        addToLightbox.reset();
        $.extend(addToLightbox.options,addToLightbox.default_options,         
            {
                boxId : "addToLightbox-box",
                title: lang.search_results.lbl_AddToLightbox,
                buttons:{
                    add:{
                        label:lang.common.lbl_Add,
                        events:{
                            click:addToLightbox.addToLightbox,
                        },
//                        preventDismiss:true,
                    },
                    cancel:{
                        label:lang.preview.lbl_done,
                        events:{
                            click:function(){}
                        },
                    },
                },
            }
        );
        //if defined, set event attached to click on No (otherwise leaves default action: dismiss modal)
        addToLightbox.makeButtonsDismiss();
        addToLightbox.setButtonsHtml();
    },
    begin:function(){
        addToLightbox._setup();
        addToLightbox.options.content = addToLightbox.listTemplate();
        addToLightbox.addBox();
        addToLightbox.getLightboxList(addToLightbox.setLightboxDD);
    },
    setLightboxDD:function(lightboxes) {
        $("#lightboxes").siblings(".dropdown-menu").html("");
        $.each(lightboxes.lightboxes_list, function(id, name){
            item = addToLightbox.listItemTemplate({
                id:id,
                name:name,
                sel:(id === lightboxes.lightboxID)?"sel":""
            });
            $("#lightboxes").siblings(".dropdown-menu").append(item);
        });
        $("#lightboxes").parent().parent().customDropDown();
        addToLightbox.show();
        addToLightbox.setButtonsEvents();
    },
    /**
    * Open add asset to lightbox form
    */
    getLightboxList:function(callback) {
        var url = APP.baseURL+'preview/refresh_my_lightbox';
        $.post({
            type: "GET",
            url: url,
            data: {},
            async: true,
            success:function(data){
                if(!data || data.length === 0) {
                    alert(lang.lightbox.lbl_MustLoginToUseLbx);
                }
                else {
                    callback(data);
                }
            },
            error: function(e) {
                console.log('Error : ');
                console.log(e);
            },
            dataType: 'json',
        });
    },
    
    /**
    * Add asset into lightbox
    */
    addToLightbox:function() {
        var url = APP.baseURL+'preview/add_to_lightbox';
        var lb = $('#lightboxes').val();
        $.post(url, {
            lightbox_id:lb, 
            asset_id:$('#assetid').val()},    
            function(data){
                if(data!==0) {
                    if(data==1){
                        if ($('#lightbox_body').length){
                            lightbox._loadAssets();
                        }
                        alert(lang.preview.msg_successAddToLightbox);
                    }else{
                        alert(lang.preview.msg_FileAlreadyInLightbox);
                    }
                }else{
                    alert(lang.lightbox.lbl_MustLoginToUseLbx);
                }
                $('#add_lightbox_form').jqmHide();
            }
        );
    },

});
})();

//addToLightbox._setup();


/*********************
Including file: clipboard.min.js
*********************/
/*!
 * clipboard.js v1.5.10
 * https://zenorocha.github.io/clipboard.js
 *
 * Licensed MIT © Zeno Rocha
 */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,o){function i(c,a){if(!n[c]){if(!e[c]){var s="function"==typeof require&&require;if(!a&&s)return s(c,!0);if(r)return r(c,!0);var l=new Error("Cannot find module '"+c+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[c]={exports:{}};e[c][0].call(u.exports,function(t){var n=e[c][1][t];return i(n?n:t)},u,u.exports,t,e,n,o)}return n[c].exports}for(var r="function"==typeof require&&require,c=0;c<o.length;c++)i(o[c]);return i}({1:[function(t,e,n){var o=t("matches-selector");e.exports=function(t,e,n){for(var i=n?t:t.parentNode;i&&i!==document;){if(o(i,e))return i;i=i.parentNode}}},{"matches-selector":5}],2:[function(t,e,n){function o(t,e,n,o,r){var c=i.apply(this,arguments);return t.addEventListener(n,c,r),{destroy:function(){t.removeEventListener(n,c,r)}}}function i(t,e,n,o){return function(n){n.delegateTarget=r(n.target,e,!0),n.delegateTarget&&o.call(t,n)}}var r=t("closest");e.exports=o},{closest:1}],3:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.fn=function(t){var e=Object.prototype.toString.call(t);return"[object Function]"===e}},{}],4:[function(t,e,n){function o(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!a.string(e))throw new TypeError("Second argument must be a String");if(!a.fn(n))throw new TypeError("Third argument must be a Function");if(a.node(t))return i(t,e,n);if(a.nodeList(t))return r(t,e,n);if(a.string(t))return c(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function i(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function r(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function c(t,e,n){return s(document.body,t,e,n)}var a=t("./is"),s=t("delegate");e.exports=o},{"./is":3,delegate:2}],5:[function(t,e,n){function o(t,e){if(r)return r.call(t,e);for(var n=t.parentNode.querySelectorAll(e),o=0;o<n.length;++o)if(n[o]==t)return!0;return!1}var i=Element.prototype,r=i.matchesSelector||i.webkitMatchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector;e.exports=o},{}],6:[function(t,e,n){function o(t){var e;if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName)t.focus(),t.setSelectionRange(0,t.value.length),e=t.value;else{t.hasAttribute("contenteditable")&&t.focus();var n=window.getSelection(),o=document.createRange();o.selectNodeContents(t),n.removeAllRanges(),n.addRange(o),e=n.toString()}return e}e.exports=o},{}],7:[function(t,e,n){function o(){}o.prototype={on:function(t,e,n){var o=this.e||(this.e={});return(o[t]||(o[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function o(){i.off(t,o),e.apply(n,arguments)}var i=this;return o._=e,this.on(t,o,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),o=0,i=n.length;for(o;i>o;o++)n[o].fn.apply(n[o].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),o=n[t],i=[];if(o&&e)for(var r=0,c=o.length;c>r;r++)o[r].fn!==e&&o[r].fn._!==e&&i.push(o[r]);return i.length?n[t]=i:delete n[t],this}},e.exports=o},{}],8:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","select"],r);else if("undefined"!=typeof o)r(n,e("select"));else{var c={exports:{}};r(c,i.select),i.clipboardAction=c.exports}}(this,function(t,e){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var i=n(e),r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol?"symbol":typeof t},c=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),a=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return t.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=e.action,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""},t.prototype.initSelection=function t(){this.text?this.selectFake():this.target&&this.selectTarget()},t.prototype.selectFake=function t(){var e=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return e.removeFake()}),this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="fixed",this.fakeElem.style[n?"right":"left"]="-9999px",this.fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=(0,i.default)(this.fakeElem),this.copyText()},t.prototype.removeFake=function t(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)},t.prototype.selectTarget=function t(){this.selectedText=(0,i.default)(this.target),this.copyText()},t.prototype.copyText=function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(n){e=!1}this.handleResult(e)},t.prototype.handleResult=function t(e){e?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},t.prototype.clearSelection=function t(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},t.prototype.destroy=function t(){this.removeFake()},c(t,[{key:"action",set:function t(){var e=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!==("undefined"==typeof e?"undefined":r(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function t(){return this._target}}]),t}();t.exports=a})},{select:6}],9:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","./clipboard-action","tiny-emitter","good-listener"],r);else if("undefined"!=typeof o)r(n,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var c={exports:{}};r(c,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=c.exports}}(this,function(t,e,n,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}var l=i(e),u=i(n),f=i(o),d=function(t){function e(n,o){r(this,e);var i=c(this,t.call(this));return i.resolveOptions(o),i.listenClick(n),i}return a(e,t),e.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText},e.prototype.listenClick=function t(e){var n=this;this.listener=(0,f.default)(e,"click",function(t){return n.onClick(t)})},e.prototype.onClick=function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new l.default({action:this.action(n),target:this.target(n),text:this.text(n),trigger:n,emitter:this})},e.prototype.defaultAction=function t(e){return s("action",e)},e.prototype.defaultTarget=function t(e){var n=s("target",e);return n?document.querySelector(n):void 0},e.prototype.defaultText=function t(e){return s("text",e)},e.prototype.destroy=function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)},e}(u.default);t.exports=d})},{"./clipboard-action":8,"good-listener":4,"tiny-emitter":7}]},{},[9])(9)});

/*********************
Including file: assetManagerOpener.js
*********************/
/**
 * 
 *
 * @package    assetManager
 * @author     Romain Bouillard
 * @copyright  (c) 2017 Lightrocket
 */
(function() {
    
assetManagerOpener = {
    open:function(options){
        var options_uri = [];
        $.each(options, function(key,value){
            options_uri.push((value && value !== "")?key+"="+value:key);
        });
        var features = "height=610,width=860,scrollTo,resizable=1,scrollbars=1,location=no";
        var popup_id = 'AssetManager_' + (new Date()).getTime();
        newwindow = window.open(APP.baseURL+'managearchive'+((options_uri.length > 0)?"?"+options_uri.join("&"):""), popup_id, features);
    },
};
})();


/*********************
Including file: niftyplayer.js
*********************/
// Script for NiftyPlayer 1.7, by tvst from varal.org
// Released under the MIT License: http://www.opensource.org/licenses/mit-license.php

var FlashHelper =
{
    movieIsLoaded : function (theMovie)
    {
        if (typeof(theMovie) != "undefined") return theMovie.PercentLoaded() == 100;
        else return
        false;
  },

    getMovie : function (movieName)
    {
      if (navigator.appName.indexOf ("Microsoft") !=-1) return window[movieName];
      else return document[movieName];
    }
};

function niftyplayer(name)
{
    this.obj = FlashHelper.getMovie(name);

    if (!FlashHelper.movieIsLoaded(this.obj)) return;

    this.play = function () {
        this.obj.TCallLabel('/','play');
    };

    this.stop = function () {
        this.obj.TCallLabel('/','stop');
    };

    this.pause = function () {
        this.obj.TCallLabel('/','pause');
    };

    this.playToggle = function () {
        this.obj.TCallLabel('/','playToggle');
    };

    this.reset = function () {
        this.obj.TCallLabel('/','reset');
    };

    this.load = function (url) {
        this.obj.SetVariable('currentSong', url);
        this.obj.TCallLabel('/','load');
    };

    this.loadAndPlay = function (url) {
        this.load(url);
        this.play();
    };

    this.getState = function () {
        var ps = this.obj.GetVariable('playingState');
        var ls = this.obj.GetVariable('loadingState');

        // returns
        //   'empty' if no file is loaded
        //   'loading' if file is loading
        //   'playing' if user has pressed play AND file has loaded
        //   'stopped' if not empty and file is stopped
        //   'paused' if file is paused
        //   'finished' if file has finished playing
        //   'error' if an error occurred
        if (ps == 'playing')
            if (ls == 'loaded') return ps;
            else return ls;

        if (ps == 'stopped')
            if (ls == 'empty') return ls;
            if (ls == 'error') return ls;
            else return ps;

        return ps;

    };

    this.getPlayingState = function () {
        // returns 'playing', 'paused', 'stopped' or 'finished'
        return this.obj.GetVariable('playingState');
    };

    this.getLoadingState = function () {
        // returns 'empty', 'loading', 'loaded' or 'error'
        return this.obj.GetVariable('loadingState');
    };

    this.registerEvent = function (eventName, action) {
        // eventName is a string with one of the following values: onPlay, onStop, onPause, onError, onSongOver, onBufferingComplete, onBufferingStarted
        // action is a string with the javascript code to run.
        //
        // example: niftyplayer('niftyPlayer1').registerEvent('onPlay', 'alert("playing!")');

        this.obj.SetVariable(eventName, action);
    };

    return this;
}


/*********************
Including file: swfobject.js
*********************/
/*!    SWFObject v2.2 <http://code.google.com/p/swfobject/> 
    is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

var swfobject = function() {
    
    var UNDEF = "undefined",
        OBJECT = "object",
        SHOCKWAVE_FLASH = "Shockwave Flash",
        SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
        FLASH_MIME_TYPE = "application/x-shockwave-flash",
        EXPRESS_INSTALL_ID = "SWFObjectExprInst",
        ON_READY_STATE_CHANGE = "onreadystatechange",
        
        win = window,
        doc = document,
        nav = navigator,
        
        plugin = false,
        domLoadFnArr = [main],
        regObjArr = [],
        objIdArr = [],
        listenersArr = [],
        storedAltContent,
        storedAltContentId,
        storedCallbackFn,
        storedCallbackObj,
        isDomLoaded = false,
        isExpressInstallActive = false,
        dynamicStylesheet,
        dynamicStylesheetMedia,
        autoHideShow = true,
    
    /* Centralized function for browser feature detection
        - User agent string detection is only used when no good alternative is possible
        - Is executed directly for optimal performance
    */    
    ua = function() {
        var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
            u = nav.userAgent.toLowerCase(),
            p = nav.platform.toLowerCase(),
            windows = p ? /win/.test(p) : /win/.test(u),
            mac = p ? /mac/.test(p) : /mac/.test(u),
            webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
            ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
            playerVersion = [0,0,0],
            d = null;
        if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
            d = nav.plugins[SHOCKWAVE_FLASH].description;
            if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
                plugin = true;
                ie = false; // cascaded feature detection for Internet Explorer
                d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
                playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
                playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
                playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
            }
        }
        else if (typeof win.ActiveXObject != UNDEF) {
            try {
                var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
                if (a) { // a will return null when ActiveX is disabled
                    d = a.GetVariable("$version");
                    if (d) {
                        ie = true; // cascaded feature detection for Internet Explorer
                        d = d.split(" ")[1].split(",");
                        playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
                    }
                }
            }
            catch(e) {}
        }
        return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
    }(),
    
    /* Cross-browser onDomLoad
        - Will fire an event as soon as the DOM of a web page is loaded
        - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
        - Regular onload serves as fallback
    */ 
    onDomLoad = function() {
        if (!ua.w3) { return; }
        if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically 
            callDomLoadFunctions();
        }
        if (!isDomLoaded) {
            if (typeof doc.addEventListener != UNDEF) {
                doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
            }        
            if (ua.ie && ua.win) {
                doc.attachEvent(ON_READY_STATE_CHANGE, function() {
                    if (doc.readyState == "complete") {
                        doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
                        callDomLoadFunctions();
                    }
                });
                if (win == top) { // if not inside an iframe
                    (function(){
                        if (isDomLoaded) { return; }
                        try {
                            doc.documentElement.doScroll("left");
                        }
                        catch(e) {
                            setTimeout(arguments.callee, 0);
                            return;
                        }
                        callDomLoadFunctions();
                    })();
                }
            }
            if (ua.wk) {
                (function(){
                    if (isDomLoaded) { return; }
                    if (!/loaded|complete/.test(doc.readyState)) {
                        setTimeout(arguments.callee, 0);
                        return;
                    }
                    callDomLoadFunctions();
                })();
            }
            addLoadEvent(callDomLoadFunctions);
        }
    }();
    
    function callDomLoadFunctions() {
        if (isDomLoaded) { return; }
        try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
            var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
            t.parentNode.removeChild(t);
        }
        catch (e) { return; }
        isDomLoaded = true;
        var dl = domLoadFnArr.length;
        for (var i = 0; i < dl; i++) {
            domLoadFnArr[i]();
        }
    }
    
    function addDomLoadEvent(fn) {
        if (isDomLoaded) {
            fn();
        }
        else { 
            domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
        }
    }
    
    /* Cross-browser onload
        - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
        - Will fire an event as soon as a web page including all of its assets are loaded 
     */
    function addLoadEvent(fn) {
        if (typeof win.addEventListener != UNDEF) {
            win.addEventListener("load", fn, false);
        }
        else if (typeof doc.addEventListener != UNDEF) {
            doc.addEventListener("load", fn, false);
        }
        else if (typeof win.attachEvent != UNDEF) {
            addListener(win, "onload", fn);
        }
        else if (typeof win.onload == "function") {
            var fnOld = win.onload;
            win.onload = function() {
                fnOld();
                fn();
            };
        }
        else {
            win.onload = fn;
        }
    }
    
    /* Main function
        - Will preferably execute onDomLoad, otherwise onload (as a fallback)
    */
    function main() { 
        if (plugin) {
            testPlayerVersion();
        }
        else {
            matchVersions();
        }
    }
    
    /* Detect the Flash Player version for non-Internet Explorer browsers
        - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
          a. Both release and build numbers can be detected
          b. Avoid wrong descriptions by corrupt installers provided by Adobe
          c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
        - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
    */
    function testPlayerVersion() {
        var b = doc.getElementsByTagName("body")[0];
        var o = createElement(OBJECT);
        o.setAttribute("type", FLASH_MIME_TYPE);
        var t = b.appendChild(o);
        if (t) {
            var counter = 0;
            (function(){
                if (typeof t.GetVariable != UNDEF) {
                    var d = t.GetVariable("$version");
                    if (d) {
                        d = d.split(" ")[1].split(",");
                        ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
                    }
                }
                else if (counter < 10) {
                    counter++;
                    setTimeout(arguments.callee, 10);
                    return;
                }
                b.removeChild(o);
                t = null;
                matchVersions();
            })();
        }
        else {
            matchVersions();
        }
    }
    
    /* Perform Flash Player and SWF version matching; static publishing only
    */
    function matchVersions() {
        var rl = regObjArr.length;
        if (rl > 0) {
            for (var i = 0; i < rl; i++) { // for each registered object element
                var id = regObjArr[i].id;
                var cb = regObjArr[i].callbackFn;
                var cbObj = {success:false, id:id};
                if (ua.pv[0] > 0) {
                    var obj = getElementById(id);
                    if (obj) {
                        if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
                            setVisibility(id, true);
                            if (cb) {
                                cbObj.success = true;
                                cbObj.ref = getObjectById(id);
                                cb(cbObj);
                            }
                        }
                        else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
                            var att = {};
                            att.data = regObjArr[i].expressInstall;
                            att.width = obj.getAttribute("width") || "0";
                            att.height = obj.getAttribute("height") || "0";
                            if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
                            if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
                            // parse HTML object param element's name-value pairs
                            var par = {};
                            var p = obj.getElementsByTagName("param");
                            var pl = p.length;
                            for (var j = 0; j < pl; j++) {
                                if (p[j].getAttribute("name").toLowerCase() != "movie") {
                                    par[p[j].getAttribute("name")] = p[j].getAttribute("value");
                                }
                            }
                            showExpressInstall(att, par, id, cb);
                        }
                        else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
                            displayAltContent(obj);
                            if (cb) { cb(cbObj); }
                        }
                    }
                }
                else {    // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
                    setVisibility(id, true);
                    if (cb) {
                        var o = getObjectById(id); // test whether there is an HTML object element or not
                        if (o && typeof o.SetVariable != UNDEF) { 
                            cbObj.success = true;
                            cbObj.ref = o;
                        }
                        cb(cbObj);
                    }
                }
            }
        }
    }
    
    function getObjectById(objectIdStr) {
        var r = null;
        var o = getElementById(objectIdStr);
        if (o && o.nodeName == "OBJECT") {
            if (typeof o.SetVariable != UNDEF) {
                r = o;
            }
            else {
                var n = o.getElementsByTagName(OBJECT)[0];
                if (n) {
                    r = n;
                }
            }
        }
        return r;
    }
    
    /* Requirements for Adobe Express Install
        - only one instance can be active at a time
        - fp 6.0.65 or higher
        - Win/Mac OS only
        - no Webkit engines older than version 312
    */
    function canExpressInstall() {
        return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
    }
    
    /* Show the Adobe Express Install dialog
        - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
    */
    function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
        isExpressInstallActive = true;
        storedCallbackFn = callbackFn || null;
        storedCallbackObj = {success:false, id:replaceElemIdStr};
        var obj = getElementById(replaceElemIdStr);
        if (obj) {
            if (obj.nodeName == "OBJECT") { // static publishing
                storedAltContent = abstractAltContent(obj);
                storedAltContentId = null;
            }
            else { // dynamic publishing
                storedAltContent = obj;
                storedAltContentId = replaceElemIdStr;
            }
            att.id = EXPRESS_INSTALL_ID;
            if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
            if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
            doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
            var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
                fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
            if (typeof par.flashvars != UNDEF) {
                par.flashvars += "&" + fv;
            }
            else {
                par.flashvars = fv;
            }
            // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
            // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
            if (ua.ie && ua.win && obj.readyState != 4) {
                var newObj = createElement("div");
                replaceElemIdStr += "SWFObjectNew";
                newObj.setAttribute("id", replaceElemIdStr);
                obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
                obj.style.display = "none";
                (function(){
                    if (obj.readyState == 4) {
                        obj.parentNode.removeChild(obj);
                    }
                    else {
                        setTimeout(arguments.callee, 10);
                    }
                })();
            }
            createSWF(att, par, replaceElemIdStr);
        }
    }
    
    /* Functions to abstract and display alternative content
    */
    function displayAltContent(obj) {
        if (ua.ie && ua.win && obj.readyState != 4) {
            // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
            // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
            var el = createElement("div");
            obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
            el.parentNode.replaceChild(abstractAltContent(obj), el);
            obj.style.display = "none";
            (function(){
                if (obj.readyState == 4) {
                    obj.parentNode.removeChild(obj);
                }
                else {
                    setTimeout(arguments.callee, 10);
                }
            })();
        }
        else {
            obj.parentNode.replaceChild(abstractAltContent(obj), obj);
        }
    } 

    function abstractAltContent(obj) {
        var ac = createElement("div");
        if (ua.win && ua.ie) {
            ac.innerHTML = obj.innerHTML;
        }
        else {
            var nestedObj = obj.getElementsByTagName(OBJECT)[0];
            if (nestedObj) {
                var c = nestedObj.childNodes;
                if (c) {
                    var cl = c.length;
                    for (var i = 0; i < cl; i++) {
                        if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
                            ac.appendChild(c[i].cloneNode(true));
                        }
                    }
                }
            }
        }
        return ac;
    }
    
    /* Cross-browser dynamic SWF creation
    */
    function createSWF(attObj, parObj, id) {
        var r, el = getElementById(id);
        if (ua.wk && ua.wk < 312) { return r; }
        if (el) {
            if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
                attObj.id = id;
            }
            if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
                var att = "";
                for (var i in attObj) {
                    if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
                        if (i.toLowerCase() == "data") {
                            parObj.movie = attObj[i];
                        }
                        else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
                            att += ' class="' + attObj[i] + '"';
                        }
                        else if (i.toLowerCase() != "classid") {
                            att += ' ' + i + '="' + attObj[i] + '"';
                        }
                    }
                }
                var par = "";
                for (var j in parObj) {
                    if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
                        par += '<param name="' + j + '" value="' + parObj[j] + '" />';
                    }
                }
                el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
                objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
                r = getElementById(attObj.id);    
            }
            else { // well-behaving browsers
                var o = createElement(OBJECT);
                o.setAttribute("type", FLASH_MIME_TYPE);
                for (var m in attObj) {
                    if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
                        if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
                            o.setAttribute("class", attObj[m]);
                        }
                        else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
                            o.setAttribute(m, attObj[m]);
                        }
                    }
                }
                for (var n in parObj) {
                    if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
                        createObjParam(o, n, parObj[n]);
                    }
                }
                el.parentNode.replaceChild(o, el);
                r = o;
            }
        }
        return r;
    }
    
    function createObjParam(el, pName, pValue) {
        var p = createElement("param");
        p.setAttribute("name", pName);    
        p.setAttribute("value", pValue);
        el.appendChild(p);
    }
    
    /* Cross-browser SWF removal
        - Especially needed to safely and completely remove a SWF in Internet Explorer
    */
    function removeSWF(id) {
        var obj = getElementById(id);
        if (obj && obj.nodeName == "OBJECT") {
            if (ua.ie && ua.win) {
                obj.style.display = "none";
                (function(){
                    if (obj.readyState == 4) {
                        removeObjectInIE(id);
                    }
                    else {
                        setTimeout(arguments.callee, 10);
                    }
                })();
            }
            else {
                obj.parentNode.removeChild(obj);
            }
        }
    }
    
    function removeObjectInIE(id) {
        var obj = getElementById(id);
        if (obj) {
            for (var i in obj) {
                if (typeof obj[i] == "function") {
                    obj[i] = null;
                }
            }
            obj.parentNode.removeChild(obj);
        }
    }
    
    /* Functions to optimize JavaScript compression
    */
    function getElementById(id) {
        var el = null;
        try {
            el = doc.getElementById(id);
        }
        catch (e) {}
        return el;
    }
    
    function createElement(el) {
        return doc.createElement(el);
    }
    
    /* Updated attachEvent function for Internet Explorer
        - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
    */    
    function addListener(target, eventType, fn) {
        target.attachEvent(eventType, fn);
        listenersArr[listenersArr.length] = [target, eventType, fn];
    }
    
    /* Flash Player and SWF content version matching
    */
    function hasPlayerVersion(rv) {
        var pv = ua.pv, v = rv.split(".");
        v[0] = parseInt(v[0], 10);
        v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
        v[2] = parseInt(v[2], 10) || 0;
        return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
    }
    
    /* Cross-browser dynamic CSS creation
        - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
    */    
    function createCSS(sel, decl, media, newStyle) {
        if (ua.ie && ua.mac) { return; }
        var h = doc.getElementsByTagName("head")[0];
        if (!h) { return; } // to also support badly authored HTML pages that lack a head element
        var m = (media && typeof media == "string") ? media : "screen";
        if (newStyle) {
            dynamicStylesheet = null;
            dynamicStylesheetMedia = null;
        }
        if (!dynamicStylesheet || dynamicStylesheetMedia != m) { 
            // create dynamic stylesheet + get a global reference to it
            var s = createElement("style");
            s.setAttribute("type", "text/css");
            s.setAttribute("media", m);
            dynamicStylesheet = h.appendChild(s);
            if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
                dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
            }
            dynamicStylesheetMedia = m;
        }
        // add style rule
        if (ua.ie && ua.win) {
            if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
                dynamicStylesheet.addRule(sel, decl);
            }
        }
        else {
            if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
                dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
            }
        }
    }
    
    function setVisibility(id, isVisible) {
        if (!autoHideShow) { return; }
        var v = isVisible ? "visible" : "hidden";
        if (isDomLoaded && getElementById(id)) {
            getElementById(id).style.visibility = v;
        }
        else {
            createCSS("#" + id, "visibility:" + v);
        }
    }

    /* Filter to avoid XSS attacks
    */
    function urlEncodeIfNecessary(s) {
        var regex = /[\\\"<>\.;]/;
        var hasBadChars = regex.exec(s) != null;
        return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
    }
    
    /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
    */
    var cleanup = function() {
        if (ua.ie && ua.win) {
            window.attachEvent("onunload", function() {
                // remove listeners to avoid memory leaks
                var ll = listenersArr.length;
                for (var i = 0; i < ll; i++) {
                    listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
                }
                // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
                var il = objIdArr.length;
                for (var j = 0; j < il; j++) {
                    removeSWF(objIdArr[j]);
                }
                // cleanup library's main closures to avoid memory leaks
                for (var k in ua) {
                    ua[k] = null;
                }
                ua = null;
                for (var l in swfobject) {
                    swfobject[l] = null;
                }
                swfobject = null;
            });
        }
    }();
    
    return {
        /* Public API
            - Reference: http://code.google.com/p/swfobject/wiki/documentation
        */ 
        registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
            if (ua.w3 && objectIdStr && swfVersionStr) {
                var regObj = {};
                regObj.id = objectIdStr;
                regObj.swfVersion = swfVersionStr;
                regObj.expressInstall = xiSwfUrlStr;
                regObj.callbackFn = callbackFn;
                regObjArr[regObjArr.length] = regObj;
                setVisibility(objectIdStr, false);
            }
            else if (callbackFn) {
                callbackFn({success:false, id:objectIdStr});
            }
        },
        
        getObjectById: function(objectIdStr) {
            if (ua.w3) {
                return getObjectById(objectIdStr);
            }
        },
        
        embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
            var callbackObj = {success:false, id:replaceElemIdStr};
            if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
                setVisibility(replaceElemIdStr, false);
                addDomLoadEvent(function() {
                    widthStr += ""; // auto-convert to string
                    heightStr += "";
                    var att = {};
                    if (attObj && typeof attObj === OBJECT) {
                        for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
                            att[i] = attObj[i];
                        }
                    }
                    att.data = swfUrlStr;
                    att.width = widthStr;
                    att.height = heightStr;
                    var par = {}; 
                    if (parObj && typeof parObj === OBJECT) {
                        for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
                            par[j] = parObj[j];
                        }
                    }
                    if (flashvarsObj && typeof flashvarsObj === OBJECT) {
                        for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
                            if (typeof par.flashvars != UNDEF) {
                                par.flashvars += "&" + k + "=" + flashvarsObj[k];
                            }
                            else {
                                par.flashvars = k + "=" + flashvarsObj[k];
                            }
                        }
                    }
                    if (hasPlayerVersion(swfVersionStr)) { // create SWF
                        var obj = createSWF(att, par, replaceElemIdStr);
                        if (att.id == replaceElemIdStr) {
                            setVisibility(replaceElemIdStr, true);
                        }
                        callbackObj.success = true;
                        callbackObj.ref = obj;
                    }
                    else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
                        att.data = xiSwfUrlStr;
                        showExpressInstall(att, par, replaceElemIdStr, callbackFn);
                        return;
                    }
                    else { // show alternative content
                        setVisibility(replaceElemIdStr, true);
                    }
                    if (callbackFn) { callbackFn(callbackObj); }
                });
            }
            else if (callbackFn) { callbackFn(callbackObj);    }
        },
        
        switchOffAutoHideShow: function() {
            autoHideShow = false;
        },
        
        ua: ua,
        
        getFlashPlayerVersion: function() {
            return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
        },
        
        hasFlashPlayerVersion: hasPlayerVersion,
        
        createSWF: function(attObj, parObj, replaceElemIdStr) {
            if (ua.w3) {
                return createSWF(attObj, parObj, replaceElemIdStr);
            }
            else {
                return undefined;
            }
        },
        
        showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
            if (ua.w3 && canExpressInstall()) {
                showExpressInstall(att, par, replaceElemIdStr, callbackFn);
            }
        },
        
        removeSWF: function(objElemIdStr) {
            if (ua.w3) {
                removeSWF(objElemIdStr);
            }
        },
        
        createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
            if (ua.w3) {
                createCSS(selStr, declStr, mediaStr, newStyleBoolean);
            }
        },
        
        addDomLoadEvent: addDomLoadEvent,
        
        addLoadEvent: addLoadEvent,
        
        getQueryParamValue: function(param) {
            var q = doc.location.search || doc.location.hash;
            if (q) {
                if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
                if (param == null) {
                    return urlEncodeIfNecessary(q);
                }
                var pairs = q.split("&");
                for (var i = 0; i < pairs.length; i++) {
                    if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
                        return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
                    }
                }
            }
            return "";
        },
        
        // For internal usage only
        expressInstallCallback: function() {
            if (isExpressInstallActive) {
                var obj = getElementById(EXPRESS_INSTALL_ID);
                if (obj && storedAltContent) {
                    obj.parentNode.replaceChild(storedAltContent, obj);
                    if (storedAltContentId) {
                        setVisibility(storedAltContentId, true);
                        if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
                    }
                    if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
                }
                isExpressInstallActive = false;
            } 
        }
    };
}();


/*********************
Including file: custom_bootstrap_dropdown.js
*********************/
/**
 * custom_bootstrap_dropdown.js - js functions relating to common dropdown
 *
 * @package    core
 * @author     Romain Bouillard
 * @copyright  (c) 2016 OnAsia
 */
(function() {
    
customBootstrapDropdown = {
    keysPressed: "",
    timeKeyDelay: 1000, //time in microsecond the previous key pressed will stay in memory when searching in dropdown
    timeKeyPress: 0,
    /**
     * setup dropdowns
     *
     * @return  void
     */
    setup:function(elt) {
        $(elt).addClass("custom-bootstrap-dropdown");
        // handle a click on list item
        $(elt).find('.dropdown-menu .dropdown-item').click(customBootstrapDropdown._handleItemClick);
        $(elt).find(".dropdown-item.sel").trigger("click");
        $(elt).on("hidden.bs.dropdown", function(event){
            let value = $(elt).find(".sel a").html();
            let button = $(elt).find('button');
            customBootstrapDropdown.setButtonText(button, value);
        });
        let value = $(elt).find(".sel a").html();
        let button = $(elt).find("button");
        customBootstrapDropdown.setButtonText(button, value);
        $(elt).find("button").on("keydown", function(e){
            var match = e.key.match("^([a-zA-Z\\-\\s])");
            if($.isArray(match) && match[0] == e.key){
                var time = $.now();
                if(time - customBootstrapDropdown.timeKeyPress > customBootstrapDropdown.timeKeyDelay) customBootstrapDropdown.keysPressed = "";
                customBootstrapDropdown.keysPressed += e.key;
                customBootstrapDropdown.timeKeyPress = time;
                container = customBootstrapDropdown.getDropDownContainer(this);
                customBootstrapDropdown.scrollToChar(container, customBootstrapDropdown.keysPressed);
            }
        });
    },
    
    getDropDownContainer:function(context){
        container = $(context).closest('.custom-bootstrap-dropdown');
        return $(container);
    },
    /**
     * handle 'click' on item
     *
     * @return  void
     */
    _handleItemClick:function(event) {
        if($(this).attr("disabled") == "disabled") return false;
        $.each(customBootstrapDropdown.getDropDownContainer(this).find(".dropdown-item.sel"), function(){$(this).removeClass("sel")});
        $(this).addClass("sel");
        customBootstrapDropdown.getDropDownContainer(this).find('input[type="hidden"]').val($(this).attr("data-val"));
        customBootstrapDropdown._handleValueChange(this);
        customBootstrapDropdown.selectItem($(this), $(this).attr("data-val"));
    },
    
    _handleValueChange:function(elt){
        customBootstrapDropdown.getDropDownContainer(elt).find('input[type="hidden"]').trigger("change");        
    },
    
    scrollToChar:function(elt,char){
        items = elt.find(".dropdown-menu div");
        var pos = 0;
        var match = false;
        $.each(items,function(){
            value = $(this).find("a").html();
            if(value.substring(0, char.length).toLowerCase() == char){
                match = true;
                return false;
           }
           else
           pos += $(this).outerHeight();
        });
        if(match) elt.find(".dropdown-menu").scrollTop(pos);
    },
    selectItem:function(elt,val){
        container = customBootstrapDropdown.getDropDownContainer(elt);
        container.find('input[type="hidden"]').val(val);
        container.find(".dropdown-item").removeClass("sel");
        container.find(".dropdown-item[data-val=\""+val+"\"]").addClass("sel");
        let value = container.find(".dropdown-item.sel>a").html();
        let button = container.find('button');
        customBootstrapDropdown.setButtonText(button, value);
        return container.find(".dropdown-item[data-val=\""+val+"\"]").text();
    },
    addItem:function(elt, val, text){
        var template = (arguments.length > 3)?arguments[3]:_.template('<div data-val="<%-value%>" class="dropdown-item"><a href="#"><%-text%></a></div>');
        var container = customBootstrapDropdown.getDropDownContainer(elt);
        if(template){
            newItem = template({
                value: val,
                text: text
            });
        }
        else{
            newItem = container.find(".dropdown-item:first-child").clone();
            $(newItem).attr("data-val",val);
            $(newItem).removeClass("sel");
            $(newItem).find("a").html(text);   
        }
        $(newItem).appendTo(container.find(".dropdown-menu"));        
        container.find(".dropdown-item:last-child").click(customBootstrapDropdown._handleItemClick);
    },
    removeItem:function(elt,val){
        container = customBootstrapDropdown.getDropDownContainer(elt);
        container.find('.dropdown-item[data-val="'+val+'"]').remove();
    },
    removeAllItems:function(elt){
        container = customBootstrapDropdown.getDropDownContainer(elt);
        container.find('.dropdown-item').remove();
    },
    setButtonText:function(button, value){
        value = (value == "" && button.data("placeholder"))?button.data("placeholder"):value;
        button.html(value);        
    },
};
})();

(function($){
    $.fn.customDropDown = function() {
        customBootstrapDropdown.setup(this);
    };
})(jQuery); 

/*********************
Including file: resultTooltip.js
*********************/
/**
 * resultTooltip.js - js functions to handle search result page tooltip events.
 * This should stay blank
 *
 * @package    search
 * @author     Romain Bouillard
 * @copyright  (c) 2022 Lightrocket
 */
var resultTooltip = {
    globalSearchUrl: false,
    globalSearchAdvParams: ["keywords","horizontal","vertical","square","panoramic","country","datefrom","dateto"],
    // display:true,
    _setup:function() {
        resultTooltip.globalSearchUrl += resultTooltip.globalSearchUrl.endsWith("/") ? "" : "/";
        if(results.searchUri == "search"){
            $(".result-tooltip").removeClass("hideMe");
            // resultTooltip.display = false;
        }
        $(".btn-search-global").click(resultTooltip._launchGlobalSearch);
    },
    _launchGlobalSearch:function(){
        resultTooltip.launchGlobalSearch();
    },
    launchGlobalSearch:function(){
        let params = resultTooltip.getParams();
        let uri = (keywords != "")?'results?panel=adv-search&s[adv]=1&'+$.param(params):"";
        window.open(resultTooltip.globalSearchUrl+uri);
    },
    getParams:function(){
        // &s[keywords]='+keywords.replace(" ","+")
        let params = {};
        $.each(results.searchParams.s, function(k,v){
            if($.inArray(k, resultTooltip.globalSearchAdvParams) != -1){
                if(k.indexOf("date") == -1)
                    params['s['+k+']'] = v;
                else
                    params['s['+k+']'] = v.substr(6,4) + "-" + v.substr(3,2) + "-" + v.substr(0,2);
            }
        });
        return params;
    },
};



/*********************
Including file: bootstrap-multiselect.min.js
*********************/
/**
 * Bootstrap Multiselect (http://davidstutz.de/bootstrap-multiselect/)
 *
 * Apache License, Version 2.0:
 * Copyright (c) 2012 - 2022 David Stutz
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * BSD 3-Clause License:
 * Copyright (c) 2012 - 2022 David Stutz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    - Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *    - Neither the name of David Stutz nor the names of its contributors may be
 *      used to endorse or promote products derived from this software without
 *      specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
!function(root,factory){"function"==typeof define&&define.amd&&"function"==typeof require&&"function"==typeof require.specified&&require.specified("knockout")?define(["jquery","knockout"],factory):factory(root.jQuery,root.ko)}(this,(function($,ko){"use strict";function forEach(array,callback){for(var index=0;index<array.length;++index)callback(array[index],index)}void 0!==ko&&ko.bindingHandlers&&!ko.bindingHandlers.multiselect&&(ko.bindingHandlers.multiselect={after:["options","value","selectedOptions","enable","disable"],init:function(element,valueAccessor,allBindings,viewModel,bindingContext){var $element=$(element),config=ko.toJS(valueAccessor());if($element.multiselect(config),allBindings.has("options")){var options=allBindings.get("options");ko.isObservable(options)&&ko.computed({read:function(){options(),setTimeout((function(){var ms=$element.data("multiselect");ms&&ms.updateOriginalOptions(),$element.multiselect("rebuild")}),1)},disposeWhenNodeIsRemoved:element})}if(allBindings.has("value")){var value=allBindings.get("value");ko.isObservable(value)&&ko.computed({read:function(){value(),setTimeout((function(){$element.multiselect("refresh")}),1)},disposeWhenNodeIsRemoved:element}).extend({rateLimit:100,notifyWhenChangesStop:!0})}if(allBindings.has("selectedOptions")){var selectedOptions=allBindings.get("selectedOptions");ko.isObservable(selectedOptions)&&ko.computed({read:function(){selectedOptions(),setTimeout((function(){$element.multiselect("refresh")}),1)},disposeWhenNodeIsRemoved:element}).extend({rateLimit:100,notifyWhenChangesStop:!0})}var setEnabled=function(enable){setTimeout((function(){enable?$element.multiselect("enable"):$element.multiselect("disable")}))};if(allBindings.has("enable")){var enable=allBindings.get("enable");ko.isObservable(enable)?ko.computed({read:function(){setEnabled(enable())},disposeWhenNodeIsRemoved:element}).extend({rateLimit:100,notifyWhenChangesStop:!0}):setEnabled(enable)}if(allBindings.has("disable")){var disable=allBindings.get("disable");ko.isObservable(disable)?ko.computed({read:function(){setEnabled(!disable())},disposeWhenNodeIsRemoved:element}).extend({rateLimit:100,notifyWhenChangesStop:!0}):setEnabled(!disable)}ko.utils.domNodeDisposal.addDisposeCallback(element,(function(){$element.multiselect("destroy")}))},update:function(element,valueAccessor,allBindings,viewModel,bindingContext){var $element=$(element),config=ko.toJS(valueAccessor());$element.multiselect("setOptions",config),$element.multiselect("rebuild")}});var multiselectCount=0;function Multiselect(select,options){this.$select=$(select),this.options=this.mergeOptions($.extend({},options,this.$select.data())),this.$select.attr("data-placeholder")&&(this.options.nonSelectedText=this.$select.data("placeholder")),this.originalOptions=this.$select.clone()[0].options,this.query="",this.searchTimeout=null,this.lastToggledInput=null,this.multiselectId=this.generateUniqueId()+"_0",this.internalIdCount=0,this.options.multiple="multiple"===this.$select.attr("multiple"),this.options.onChange=$.proxy(this.options.onChange,this),this.options.onSelectAll=$.proxy(this.options.onSelectAll,this),this.options.onDeselectAll=$.proxy(this.options.onDeselectAll,this),this.options.onDropdownShow=$.proxy(this.options.onDropdownShow,this),this.options.onDropdownHide=$.proxy(this.options.onDropdownHide,this),this.options.onDropdownShown=$.proxy(this.options.onDropdownShown,this),this.options.onDropdownHidden=$.proxy(this.options.onDropdownHidden,this),this.options.onInitialized=$.proxy(this.options.onInitialized,this),this.options.onFiltering=$.proxy(this.options.onFiltering,this),this.buildContainer(),this.buildButton(),this.buildDropdown(),this.buildReset(),this.buildSelectAll(),this.buildDropdownOptions(),this.buildFilter(),this.buildButtons(),this.updateButtonText(),this.updateSelectAll(!0),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups(),this.options.wasDisabled=this.$select.prop("disabled"),this.options.disableIfEmpty&&$("option",this.$select).length<=0&&!this.options.wasDisabled&&this.disable(!0),this.$select.wrap('<span class="multiselect-native-select" />').after(this.$container),this.$select.prop("tabindex","-1"),"never"!==this.options.widthSynchronizationMode&&this.synchronizeButtonAndPopupWidth(),this.$select.data("multiselect",this),this.options.onInitialized(this.$select,this.$container)}Multiselect.prototype={defaults:{buttonText:function(selectedOptions,select){if(this.disabledText.length>0&&select.prop("disabled"))return this.disabledText;if(0===selectedOptions.length)return this.nonSelectedText;if(this.allSelectedText&&selectedOptions.length===$("option",$(select)).length&&1!==$("option",$(select)).length&&this.multiple)return this.selectAllNumber?this.allSelectedText+" ("+selectedOptions.length+")":this.allSelectedText;if(0!=this.numberDisplayed&&selectedOptions.length>this.numberDisplayed)return selectedOptions.length+" "+this.nSelectedText;var selected="",delimiter=this.delimiterText;return selectedOptions.each((function(){var label=void 0!==$(this).attr("label")?$(this).attr("label"):$(this).text();selected+=label+delimiter})),selected.substr(0,selected.length-this.delimiterText.length)},buttonTitle:function(options,select){if(0===options.length)return this.nonSelectedText;var selected="",delimiter=this.delimiterText;return options.each((function(){var label=void 0!==$(this).attr("label")?$(this).attr("label"):$(this).text();selected+=label+delimiter})),selected.substr(0,selected.length-this.delimiterText.length)},checkboxName:function(option){return!1},optionLabel:function(element){return $(element).attr("label")||$(element).text()},optionClass:function(element){return $(element).attr("class")||""},onChange:function(option,checked){},onDropdownShow:function(event){},onDropdownHide:function(event){},onDropdownShown:function(event){},onDropdownHidden:function(event){},onSelectAll:function(selectedOptions){},onDeselectAll:function(deselectedOptions){},onInitialized:function($select,$container){},onFiltering:function($filter){},enableHTML:!1,buttonClass:"custom-select",inheritClass:!1,buttonWidth:"auto",buttonContainer:'<div class="btn-group" />',dropRight:!1,dropUp:!1,selectedClass:"active",maxHeight:null,includeSelectAllOption:!1,includeSelectAllIfMoreThan:0,selectAllText:" Select all",selectAllValue:"multiselect-all",selectAllName:!1,selectAllNumber:!0,selectAllJustVisible:!0,enableFiltering:!1,enableCaseInsensitiveFiltering:!1,enableFullValueFiltering:!1,enableClickableOptGroups:!1,enableCollapsibleOptGroups:!1,collapseOptGroupsByDefault:!1,filterPlaceholder:"Search",filterBehavior:"text",includeFilterClearBtn:!0,preventInputChangeEvent:!1,nonSelectedText:"None selected",nSelectedText:"selected",allSelectedText:"All selected",resetButtonText:"Reset",numberDisplayed:3,disableIfEmpty:!1,disabledText:"",delimiterText:", ",includeResetOption:!1,includeResetDivider:!1,resetText:"Reset",indentGroupOptions:!0,widthSynchronizationMode:"never",buttonTextAlignment:"center",enableResetButton:!1,templates:{button:'<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"><span class="multiselect-selected-text"></span></button>',popupContainer:'<div class="multiselect-container dropdown-menu"></div>',filter:'<div class="multiselect-filter d-flex align-items-center"><i class="fas fa-sm fa-search text-muted"></i><input type="search" class="multiselect-search form-control" /></div>',buttonGroup:'<div class="multiselect-buttons btn-group" style="display:flex;"></div>',buttonGroupReset:'<button type="button" class="multiselect-reset btn btn-secondary btn-block"></button>',option:'<button type="button" class="multiselect-option dropdown-item"></button>',divider:'<div class="dropdown-divider"></div>',optionGroup:'<button type="button" class="multiselect-group dropdown-item"></button>',resetButton:'<div class="multiselect-reset text-center p-2"><button type="button" class="btn btn-sm btn-block btn-outline-secondary"></button></div>'}},constructor:Multiselect,buildContainer:function(){this.$container=$(this.options.buttonContainer),"never"!==this.options.widthSynchronizationMode?this.$container.on("show.bs.dropdown",$.proxy((function(){this.synchronizeButtonAndPopupWidth(),this.options.onDropdownShow()}),this)):this.$container.on("show.bs.dropdown",this.options.onDropdownShow),this.$container.on("hide.bs.dropdown",this.options.onDropdownHide),this.$container.on("shown.bs.dropdown",this.options.onDropdownShown),this.$container.on("hidden.bs.dropdown",this.options.onDropdownHidden)},buildButton:function(){if(this.$button=$(this.options.templates.button).addClass(this.options.buttonClass),this.$select.attr("class")&&this.options.inheritClass&&this.$button.addClass(this.$select.attr("class")),this.$select.prop("disabled")?this.disable():this.enable(),this.options.buttonWidth&&"auto"!==this.options.buttonWidth&&(this.$button.css({width:"100%"}),this.$container.css({width:this.options.buttonWidth})),this.options.buttonTextAlignment)switch(this.options.buttonTextAlignment){case"left":this.$button.addClass("text-left");break;case"center":this.$button.addClass("text-center");break;case"right":this.$button.addClass("text-right")}var tabindex=this.$select.attr("tabindex");tabindex&&this.$button.attr("tabindex",tabindex),this.$container.prepend(this.$button)},buildDropdown:function(){this.$popupContainer=$(this.options.templates.popupContainer),this.options.dropRight?this.$container.addClass("dropright"):this.options.dropUp&&this.$container.addClass("dropup"),this.options.maxHeight&&this.$popupContainer.css({"max-height":this.options.maxHeight+"px","overflow-y":"auto","overflow-x":"hidden"}),"never"!==this.options.widthSynchronizationMode&&this.$popupContainer.css("overflow-x","hidden"),this.$popupContainer.on("touchstart click",(function(e){e.stopPropagation()})),this.$container.append(this.$popupContainer)},synchronizeButtonAndPopupWidth:function(){if(this.$popupContainer&&"never"!==this.options.widthSynchronizationMode){var buttonWidth=this.$button.outerWidth();switch(this.options.widthSynchronizationMode){case"always":this.$popupContainer.css("min-width",buttonWidth),this.$popupContainer.css("max-width",buttonWidth);break;case"ifPopupIsSmaller":this.$popupContainer.css("min-width",buttonWidth);break;case"ifPopupIsWider":this.$popupContainer.css("max-width",buttonWidth)}}},buildDropdownOptions:function(){if(this.$select.children().each($.proxy((function(index,element){var $element=$(element),tag=$element.prop("tagName").toLowerCase();$element.prop("value")!==this.options.selectAllValue&&("optgroup"===tag?this.createOptgroup(element):"option"===tag&&("divider"===$element.data("role")?this.createDivider():this.createOptionValue(element,!1)))}),this)),$(this.$popupContainer).off("change",'> *:not(.multiselect-group) input[type="checkbox"], > *:not(.multiselect-group) input[type="radio"]'),$(this.$popupContainer).on("change",'> *:not(.multiselect-group) input[type="checkbox"], > *:not(.multiselect-group) input[type="radio"]',$.proxy((function(event){var $target=$(event.target),checked=$target.prop("checked")||!1,isSelectAllOption=$target.val()===this.options.selectAllValue;this.options.selectedClass&&(checked?$target.closest(".multiselect-option").addClass(this.options.selectedClass):$target.closest(".multiselect-option").removeClass(this.options.selectedClass));var id=$target.attr("id"),$option=this.getOptionById(id),$optionsNotThis=$("option",this.$select).not($option),$checkboxesNotThis=$("input",this.$container).not($target);if(isSelectAllOption?checked?this.selectAll(this.options.selectAllJustVisible,!0):this.deselectAll(this.options.selectAllJustVisible,!0):(checked?($option.prop("selected",!0),this.options.multiple?$option.prop("selected",!0):(this.options.selectedClass&&$($checkboxesNotThis).closest(".dropdown-item").removeClass(this.options.selectedClass),$($checkboxesNotThis).prop("checked",!1),$optionsNotThis.prop("selected",!1),this.$button.click()),"active"===this.options.selectedClass&&$optionsNotThis.closest(".dropdown-item").css("outline","")):$option.prop("selected",!1),this.options.onChange($option,checked),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()),this.$select.change(),this.updateButtonText(),this.options.preventInputChangeEvent)return!1}),this)),$(".multiselect-option",this.$popupContainer).off("mousedown"),$(".multiselect-option",this.$popupContainer).on("mousedown",(function(e){if(e.shiftKey)return!1})),$(this.$popupContainer).off("touchstart click",".multiselect-option, .multiselect-all, .multiselect-group"),$(this.$popupContainer).on("touchstart click",".multiselect-option, .multiselect-all, .multiselect-group",$.proxy((function(event){event.stopPropagation();var $target=$(event.target),$input;if(event.shiftKey&&this.options.multiple){$target.is("input")||(event.preventDefault(),($target=$target.closest(".multiselect-option").find("input")).prop("checked",!$target.prop("checked")));var checked=$target.prop("checked")||!1;if(null!==this.lastToggledInput&&this.lastToggledInput!==$target){var from=this.$popupContainer.find(".multiselect-option:visible").index($target.closest(".multiselect-option")),to=this.$popupContainer.find(".multiselect-option:visible").index(this.lastToggledInput.closest(".multiselect-option"));if(from>to){var tmp=to;to=from,from=tmp}++to;var range=this.$popupContainer.find(".multiselect-option:not(.multiselect-filter-hidden)").slice(from,to).find("input");range.prop("checked",checked),this.options.selectedClass&&range.closest(".multiselect-option").toggleClass(this.options.selectedClass,checked);for(var i=0,j=range.length;i<j;i++){var $checkbox=$(range[i]),$option;this.getOptionById($checkbox.attr("id")).prop("selected",checked)}}$target.trigger("change")}else if(!$target.is("input")){var $checkbox;if(($checkbox=$target.closest(".multiselect-option, .multiselect-all").find(".form-check-input")).length>0)!this.options.multiple&&$checkbox.prop("checked")||($checkbox.prop("checked",!$checkbox.prop("checked")),$checkbox.change());else if(this.options.enableClickableOptGroups&&this.options.multiple&&!$target.hasClass("caret-container")){var groupItem=$target;groupItem.hasClass("multiselect-group")||(groupItem=$target.closest(".multiselect-group")),($checkbox=groupItem.find(".form-check-input")).length>0&&($checkbox.prop("checked",!$checkbox.prop("checked")),$checkbox.change())}event.preventDefault()}$target.closest(".multiselect-option").find("input[type='checkbox'], input[type='radio']").length>0?this.lastToggledInput=$target:this.lastToggledInput=null,$target.blur()}),this)),this.$container.off("keydown.multiselect").on("keydown.multiselect",$.proxy((function(event){var $items=$(this.$container).find(".multiselect-option:not(.disabled), .multiselect-group:not(.disabled), .multiselect-all").filter(":visible"),index=$items.index($items.filter(":focus")),$search=$(".multiselect-search",this.$container);if(9===event.keyCode&&this.$container.hasClass("show"))this.$button.click();else if(13==event.keyCode){var $current=$items.eq(index);setTimeout((function(){$current.focus()}),1)}else if(38==event.keyCode)0!=index||$search.is(":focus")||setTimeout((function(){$search.focus()}),1);else if(40==event.keyCode)if($search.is(":focus")){var $first=$items.eq(0);setTimeout((function(){$search.blur(),$first.focus()}),1)}else-1==index&&setTimeout((function(){$search.focus()}),1)}),this)),this.options.enableClickableOptGroups&&this.options.multiple&&($(".multiselect-group input",this.$popupContainer).off("change"),$(".multiselect-group input",this.$popupContainer).on("change",$.proxy((function(event){event.stopPropagation();var $target,checked=$(event.target).prop("checked")||!1,$item=$(event.target).closest(".dropdown-item"),$group,$inputs=$item.nextUntil(".multiselect-group").not(".multiselect-filter-hidden").not(".disabled").find("input"),$options=[];this.options.selectedClass&&(checked?$item.addClass(this.options.selectedClass):$item.removeClass(this.options.selectedClass)),$.each($inputs,$.proxy((function(index,input){var $input=$(input),id=$input.attr("id"),$option=this.getOptionById(id);checked?($input.prop("checked",!0),$input.closest(".dropdown-item").addClass(this.options.selectedClass),$option.prop("selected",!0)):($input.prop("checked",!1),$input.closest(".dropdown-item").removeClass(this.options.selectedClass),$option.prop("selected",!1)),$options.push($option)}),this)),this.options.onChange($options,checked),this.$select.change(),this.updateButtonText(),this.updateSelectAll()}),this))),this.options.enableCollapsibleOptGroups){let clickableSelector=this.options.enableClickableOptGroups?".multiselect-group .caret-container":".multiselect-group";$(clickableSelector,this.$popupContainer).off("click"),$(clickableSelector,this.$popupContainer).on("click",$.proxy((function(event){var $group=$(event.target).closest(".multiselect-group"),$inputs=$group.nextUntil(".multiselect-group").not(".multiselect-filter-hidden"),visible=!0;$inputs.each((function(){visible=visible&&!$(this).hasClass("multiselect-collapsible-hidden")})),visible?($inputs.hide().addClass("multiselect-collapsible-hidden"),$group.get(0).classList.add("closed")):($inputs.show().removeClass("multiselect-collapsible-hidden"),$group.get(0).classList.remove("closed"))}),this))}},createCheckbox:function($item,labelContent,name,value,title,inputType,internalId){var $wrapper=$("<span />");$wrapper.addClass("form-check");var $checkboxLabel=$('<label class="form-check-label" />');this.options.enableHTML&&$(labelContent).length>0?$checkboxLabel.html(labelContent):$checkboxLabel.text(labelContent),$wrapper.append($checkboxLabel);var $checkbox=$('<input class="form-check-input"/>').attr("type",inputType);return $checkbox.val(value),$wrapper.prepend($checkbox),internalId&&($checkbox.attr("id",internalId),$checkboxLabel.attr("for",internalId)),name&&$checkbox.attr("name",name),$item.prepend($wrapper),$item.attr("title",title||labelContent),$checkbox},createOptionValue:function(element,isGroupOption){var $element=$(element);$element.is(":selected")&&$element.prop("selected",!0);var label=this.options.optionLabel(element),classes=this.options.optionClass(element),value=$element.val(),inputType=this.options.multiple?"checkbox":"radio",title=$element.attr("title"),$option=$(this.options.templates.option);$option.addClass(classes),isGroupOption&&this.options.indentGroupOptions&&(this.options.enableCollapsibleOptGroups?$option.addClass("multiselect-group-option-indented-full"):$option.addClass("multiselect-group-option-indented")),this.options.collapseOptGroupsByDefault&&"optgroup"===$(element).parent().prop("tagName").toLowerCase()&&($option.addClass("multiselect-collapsible-hidden"),$option.hide());var name=this.options.checkboxName($element),checkboxId=this.createAndApplyUniqueId($element),$checkbox=this.createCheckbox($option,label,name,value,title,inputType,checkboxId),selected=$element.prop("selected")||!1;value===this.options.selectAllValue&&($option.addClass("multiselect-all"),$option.removeClass("multiselect-option"),$checkbox.parent().parent().addClass("multiselect-all")),this.$popupContainer.append($option),$element.is(":disabled")&&$checkbox.attr("disabled","disabled").prop("disabled",!0).closest(".dropdown-item").addClass("disabled"),$checkbox.prop("checked",selected),selected&&this.options.selectedClass&&$checkbox.closest(".dropdown-item").addClass(this.options.selectedClass)},createDivider:function(element){var $divider=$(this.options.templates.divider);this.$popupContainer.append($divider)},createOptgroup:function(group){var $group=$(group),label=$group.attr("label"),value=$group.attr("value"),title=$group.attr("title"),$groupOption=$("<span class='multiselect-group dropdown-item-text'></span>");if(this.options.enableClickableOptGroups&&this.options.multiple){$groupOption=$(this.options.templates.optionGroup);var checkboxId=this.createAndApplyUniqueId($group),$checkbox=this.createCheckbox($groupOption,label,null,value,title,"checkbox",checkboxId)}else this.options.enableHTML?$groupOption.html(" "+label):$groupOption.text(" "+label);var classes=this.options.optionClass(group);$groupOption.addClass(classes),this.options.enableCollapsibleOptGroups&&($groupOption.find(".form-check").addClass("d-inline-block"),$groupOption.get(0).insertAdjacentHTML("afterbegin",'<span class="caret-container dropdown-toggle"></span>')),$group.is(":disabled")&&$groupOption.addClass("disabled"),this.$popupContainer.append($groupOption),$("option",group).each($.proxy((function($,group){this.createOptionValue(group,!0)}),this))},buildReset:function(){if(this.options.includeResetOption){if(this.options.includeResetDivider){var divider=$(this.options.templates.divider);divider.addClass("mt-0"),this.$popupContainer.prepend(divider)}var $resetButton=$(this.options.templates.resetButton);this.options.enableHTML?$("button",$resetButton).html(this.options.resetText):$("button",$resetButton).text(this.options.resetText),$("button",$resetButton).click($.proxy((function(){this.clearSelection()}),this)),this.$popupContainer.prepend($resetButton)}},buildSelectAll:function(){var alreadyHasSelectAll;if("number"==typeof this.options.selectAllValue&&(this.options.selectAllValue=this.options.selectAllValue.toString()),!this.hasSelectAll()&&this.options.includeSelectAllOption&&this.options.multiple&&$("option",this.$select).length>this.options.includeSelectAllIfMoreThan){this.options.includeSelectAllDivider&&this.$popupContainer.prepend($(this.options.templates.divider));var $option=$(this.options.templates.li||this.options.templates.option),$checkbox=this.createCheckbox($option,this.options.selectAllText,this.options.selectAllName,this.options.selectAllValue,this.options.selectAllText,"checkbox",this.createAndApplyUniqueId(null));$option.addClass("multiselect-all"),$option.removeClass("multiselect-option"),$option.find(".form-check-label").addClass("font-weight-bold"),this.$popupContainer.prepend($option),$checkbox.prop("checked",!1)}},buildFilter:function(){if(this.options.enableFiltering||this.options.enableCaseInsensitiveFiltering){var enableFilterLength=Math.max(this.options.enableFiltering,this.options.enableCaseInsensitiveFiltering);this.$select.find("option").length>=enableFilterLength&&(this.$filter=$(this.options.templates.filter),$("input",this.$filter).attr("placeholder",this.options.filterPlaceholder),this.options.includeFilterClearBtn?(this.isFirefox()&&0===this.$filter.find(".multiselect-clear-filter").length&&this.$filter.append("<i class='fas fa-times text-muted multiselect-clear-filter multiselect-moz-clear-filter'></i>"),this.$filter.find(".multiselect-clear-filter").on("click",$.proxy((function(event){clearTimeout(this.searchTimeout),this.query="",this.$filter.find(".multiselect-search").val(""),$(".dropdown-item",this.$popupContainer).show().removeClass("multiselect-filter-hidden"),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()}),this))):(this.$filter.find(".multiselect-search").attr("type","text"),this.$filter.find(".multiselect-clear-filter").remove()),this.$popupContainer.prepend(this.$filter),this.$filter.val(this.query).on("click",(function(event){event.stopPropagation()})).on("input keydown",$.proxy((function(event){13===event.which&&event.preventDefault(),this.isFirefox()&&this.options.includeFilterClearBtn&&(event.target.value?this.$filter.find(".multiselect-moz-clear-filter").show():this.$filter.find(".multiselect-moz-clear-filter").hide()),clearTimeout(this.searchTimeout),this.searchTimeout=this.asyncFunction($.proxy((function(){var currentGroup,currentGroupVisible;this.query!==event.target.value&&(this.query=event.target.value,$.each($(".multiselect-option, .multiselect-group",this.$popupContainer),$.proxy((function(index,element){var value=$("input",element).length>0?$("input",element).val():"",text=$(".form-check-label",element).text(),filterCandidate="";if("text"===this.options.filterBehavior?filterCandidate=text:"value"===this.options.filterBehavior?filterCandidate=value:"both"===this.options.filterBehavior&&(filterCandidate=text+"\n"+value),value!==this.options.selectAllValue&&text){var showElement=!1;if(this.options.enableCaseInsensitiveFiltering&&(filterCandidate=filterCandidate.toLowerCase(),this.query=this.query.toLowerCase()),this.options.enableFullValueFiltering&&"both"!==this.options.filterBehavior){var valueToMatch=filterCandidate.trim().substring(0,this.query.length);this.query.indexOf(valueToMatch)>-1&&(showElement=!0)}else filterCandidate.indexOf(this.query)>-1&&(showElement=!0);showElement||($(element).css("display","none"),$(element).addClass("multiselect-filter-hidden")),showElement&&($(element).css("display","block"),$(element).removeClass("multiselect-filter-hidden")),$(element).hasClass("multiselect-group")?(currentGroup=element,currentGroupVisible=showElement):(showElement&&$(currentGroup).show().removeClass("multiselect-filter-hidden"),!showElement&&currentGroupVisible&&$(element).show().removeClass("multiselect-filter-hidden"))}}),this)));this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups(),this.updatePopupPosition(),this.options.onFiltering(event.target)}),this),300,this)}),this)))}},buildButtons:function(){if(this.options.enableResetButton){var $buttonGroup=$(this.options.templates.buttonGroup);this.$buttonGroupReset=$(this.options.templates.buttonGroupReset).text(this.options.resetButtonText),$buttonGroup.append(this.$buttonGroupReset),this.$popupContainer.prepend($buttonGroup),this.defaultSelection={},$("option",this.$select).each($.proxy((function(index,element){var $option=$(element);this.defaultSelection[$option.val()]=$option.prop("selected")}),this)),this.$buttonGroupReset.on("click",$.proxy((function(event){$("option",this.$select).each($.proxy((function(index,element){var $option=$(element);$option.prop("selected",this.defaultSelection[$option.val()])}),this)),this.refresh(),this.options.enableFiltering&&(this.$filter.trigger("keydown"),$("input",this.$filter).val(""))}),this))}},updatePopupPosition:function(){var transformMatrix=this.$popupContainer.css("transform"),matrixType=transformMatrix.substring(0,transformMatrix.indexOf("(")),values,valuesArray=transformMatrix.substring(transformMatrix.indexOf("(")+1,transformMatrix.length-1).split(","),valueIndex=5;if("matrix3d"===matrixType&&(valueIndex=13),!(valuesArray.length<valueIndex)){var yTransformation=valuesArray[valueIndex];(yTransformation=void 0===yTransformation?0:yTransformation.trim())<0&&(yTransformation=-1*this.$popupContainer.css("height").replace("px",""),valuesArray[valueIndex]=yTransformation,transformMatrix=matrixType+"("+valuesArray.join(",")+")",this.$popupContainer.css("transform",transformMatrix))}},destroy:function(){this.$container.remove(),this.$select.unwrap(),this.$select.show(),this.$select.prop("disabled",this.options.wasDisabled),this.$select.find("option, optgroup").removeAttr("data-multiselectid"),this.$select.data("multiselect",null)},refresh:function(){var inputs={};$(".multiselect-option input",this.$popupContainer).each((function(){inputs[$(this).val()]=$(this)})),$("option",this.$select).each($.proxy((function(index,element){var $elem=$(element),$input=inputs[$(element).val()];$elem.is(":selected")?($input.prop("checked",!0),this.options.selectedClass&&$input.closest(".multiselect-option").addClass(this.options.selectedClass)):($input.prop("checked",!1),this.options.selectedClass&&$input.closest(".multiselect-option").removeClass(this.options.selectedClass)),$elem.is(":disabled")?$input.attr("disabled","disabled").prop("disabled",!0).closest(".multiselect-option").addClass("disabled"):$input.prop("disabled",!1).closest(".multiselect-option").removeClass("disabled")}),this)),this.updateButtonText(),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()},select:function(selectValues,triggerOnChange){$.isArray(selectValues)||(selectValues=[selectValues]);for(var i=0;i<selectValues.length;i++){var value=selectValues[i];if(null!=value){var $checkboxes=this.getInputsByValue(value);if($checkboxes&&0!==$checkboxes.length)for(var checkboxIndex=0;checkboxIndex<$checkboxes.length;++checkboxIndex){var $checkbox=$checkboxes[checkboxIndex],$option=this.getOptionById($checkbox.attr("id"));if(void 0!==$option){if(this.options.selectedClass&&$checkbox.closest(".dropdown-item").addClass(this.options.selectedClass),$checkbox.prop("checked",!0),$option.prop("selected",!0),!this.options.multiple){var $checkboxesNotThis=$("input",this.$container).not($checkbox),$optionsNotThis;$($checkboxesNotThis).prop("checked",!1),$($checkboxesNotThis).closest(".multiselect-option").removeClass("active"),$("option",this.$select).not($option).prop("selected",!1)}triggerOnChange&&this.options.onChange($option,!0)}}}}this.updateButtonText(),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()},clearSelection:function(){this.deselectAll(!1),this.updateButtonText(),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()},deselect:function(deselectValues,triggerOnChange){if(this.options.multiple){$.isArray(deselectValues)||(deselectValues=[deselectValues]);for(var i=0;i<deselectValues.length;i++){var value=deselectValues[i];if(null!=value){var $checkboxes=this.getInputsByValue(value);if($checkboxes&&0!==$checkboxes.length)for(var checkboxIndex=0;checkboxIndex<$checkboxes.length;++checkboxIndex){var $checkbox=$checkboxes[checkboxIndex],$option=this.getOptionById($checkbox.attr("id"));$option&&(this.options.selectedClass&&$checkbox.closest(".dropdown-item").removeClass(this.options.selectedClass),$checkbox.prop("checked",!1),$option.prop("selected",!1),triggerOnChange&&this.options.onChange($option,!1))}}}this.updateButtonText(),this.updateSelectAll(),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups()}},selectAll:function(justVisible,triggerOnSelectAll){if(this.options.multiple){var selected=[],justVisible;if(justVisible=void 0===justVisible||justVisible){var visibleOptions=$(".multiselect-option:not(.disabled):not(.multiselect-filter-hidden)",this.$popupContainer);$("input:enabled",visibleOptions).prop("checked",!0),visibleOptions.addClass(this.options.selectedClass),$("input:enabled",visibleOptions).each($.proxy((function(index,element){var id=$(element).attr("id"),option=this.getOptionById(id);$(option).prop("selected")||selected.push(option),$(option).prop("selected",!0)}),this))}else{var allOptions=$(".multiselect-option:not(.disabled)",this.$popupContainer);$("input:enabled",allOptions).prop("checked",!0),allOptions.addClass(this.options.selectedClass),$("input:enabled",allOptions).each($.proxy((function(index,element){var id=$(element).attr("id"),option=this.getOptionById(id);$(option).prop("selected")||selected.push(option),$(option).prop("selected",!0)}),this))}$('.multiselect-option input[value="'+this.options.selectAllValue+'"]',this.$popupContainer).prop("checked",!0),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups(),this.updateButtonText(),this.updateSelectAll(),triggerOnSelectAll&&this.options.onSelectAll(selected)}},deselectAll:function(justVisible,triggerOnDeselectAll){if(this.options.multiple){var deselected=[],justVisible;if(justVisible=void 0===justVisible||justVisible){var visibleOptions=$(".multiselect-option:not(.disabled):not(.multiselect-filter-hidden)",this.$popupContainer);$('input[type="checkbox"]:enabled',visibleOptions).prop("checked",!1),visibleOptions.removeClass(this.options.selectedClass),$('input[type="checkbox"]:enabled',visibleOptions).each($.proxy((function(index,element){var id=$(element).attr("id"),option=this.getOptionById(id);$(option).prop("selected")&&deselected.push(option),$(option).prop("selected",!1)}),this))}else{var allOptions=$(".multiselect-option:not(.disabled):not(.multiselect-group)",this.$popupContainer);$('input[type="checkbox"]:enabled',allOptions).prop("checked",!1),allOptions.removeClass(this.options.selectedClass),$('input[type="checkbox"]:enabled',allOptions).each($.proxy((function(index,element){var id=$(element).attr("id"),option=this.getOptionById(id);$(option).prop("selected")&&deselected.push(option),$(option).prop("selected",!1)}),this))}$('.multiselect-all input[value="'+this.options.selectAllValue+'"]',this.$popupContainer).prop("checked",!1),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups(),this.updateButtonText(),this.updateSelectAll(),triggerOnDeselectAll&&this.options.onDeselectAll(deselected)}},rebuild:function(){this.internalIdCount=0,this.$popupContainer.html(""),this.$select.find("option, optgroup").removeAttr("data-multiselectid"),this.options.multiple="multiple"===this.$select.attr("multiple"),this.buildSelectAll(),this.buildDropdownOptions(),this.buildFilter(),this.buildButtons(),this.updateButtonText(),this.updateSelectAll(!0),this.options.enableClickableOptGroups&&this.options.multiple&&this.updateOptGroups(),this.options.disableIfEmpty&&($("option",this.$select).length<=0?this.$select.prop("disabled")||this.disable(!0):this.$select.data("disabled-by-option")&&this.enable()),this.options.dropRight?this.$container.addClass("dropright"):this.options.dropUp&&this.$container.addClass("dropup"),"never"!==this.options.widthSynchronizationMode&&this.synchronizeButtonAndPopupWidth()},dataprovider:function(dataprovider){var groupCounter=0,$select=this.$select.empty();$.each(dataprovider,(function(index,option){var $tag;if($.isArray(option.children))groupCounter++,$tag=$("<optgroup/>").attr({label:option.label||"Group "+groupCounter,disabled:!!option.disabled,value:option.value}),forEach(option.children,(function(subOption){var attributes={value:subOption.value,label:void 0!==subOption.label&&null!==subOption.label?subOption.label:subOption.value,title:subOption.title,selected:!!subOption.selected,disabled:!!subOption.disabled};for(var key in subOption.attributes)attributes["data-"+key]=subOption.attributes[key];$tag.append($("<option/>").attr(attributes))}));else{var attributes={value:option.value,label:void 0!==option.label&&null!==option.label?option.label:option.value,title:option.title,class:option.class,selected:!!option.selected,disabled:!!option.disabled};for(var key in option.attributes)attributes["data-"+key]=option.attributes[key];($tag=$("<option/>").attr(attributes)).text(void 0!==option.label&&null!==option.label?option.label:option.value)}$select.append($tag)})),this.rebuild()},enable:function(){this.$select.prop("disabled",!1),this.$button.prop("disabled",!1).removeClass("disabled"),this.updateButtonText()},disable:function(disableByOption){this.$select.prop("disabled",!0),this.$button.prop("disabled",!0).addClass("disabled"),disableByOption?this.$select.data("disabled-by-option",!0):this.$select.data("disabled-by-option",null),this.updateButtonText()},setOptions:function(options){this.options=this.mergeOptions(options)},mergeOptions:function(options){return $.extend(!0,{},this.defaults,this.options,options)},hasSelectAll:function(){return $(".multiselect-all",this.$popupContainer).length>0},updateOptGroups:function(){var $groups=$(".multiselect-group",this.$popupContainer),selectedClass=this.options.selectedClass;$groups.each((function(){var $options=$(this).nextUntil(".multiselect-group").not(".multiselect-filter-hidden").not(".disabled"),checked=!0;$options.each((function(){var $input;$("input",this).prop("checked")||(checked=!1)})),selectedClass&&(checked?$(this).addClass(selectedClass):$(this).removeClass(selectedClass)),$("input",this).prop("checked",checked)}))},updateSelectAll:function(notTriggerOnSelectAll){if(this.hasSelectAll()){var allBoxes=$(".multiselect-option:not(.multiselect-filter-hidden):not(.multiselect-group):not(.disabled) input:enabled",this.$popupContainer),allBoxesLength=allBoxes.length,checkedBoxesLength=allBoxes.filter(":checked").length,selectAllItem=$(".multiselect-all",this.$popupContainer),selectAllInput=selectAllItem.find("input");checkedBoxesLength>0&&checkedBoxesLength===allBoxesLength?(selectAllInput.prop("checked",!0),selectAllItem.addClass(this.options.selectedClass)):(selectAllInput.prop("checked",!1),selectAllItem.removeClass(this.options.selectedClass))}},updateButtonText:function(){var options=this.getSelected();this.options.enableHTML?$(".multiselect .multiselect-selected-text",this.$container).html(this.options.buttonText(options,this.$select)):$(".multiselect .multiselect-selected-text",this.$container).text(this.options.buttonText(options,this.$select)),$(".multiselect",this.$container).attr("title",this.options.buttonTitle(options,this.$select)),this.$button.trigger("change")},getSelected:function(){return $("option",this.$select).filter(":selected")},getOptionById:function(id){return id?this.$select.find("option[data-multiselectid="+id+"], optgroup[data-multiselectid="+id+"]"):null},getInputsByValue:function(value){for(var checkboxes=$(".multiselect-option input:not(.multiselect-search)",this.$popupContainer),valueToCompare=value.toString(),matchingCheckboxes=[],i=0;i<checkboxes.length;i+=1){var checkbox=checkboxes[i];checkbox.value===valueToCompare&&matchingCheckboxes.push($(checkbox))}return matchingCheckboxes},updateOriginalOptions:function(){this.originalOptions=this.$select.clone()[0].options},asyncFunction:function(callback,timeout,self){var args=Array.prototype.slice.call(arguments,3);return setTimeout((function(){callback.apply(self||window,args)}),timeout)},setAllSelectedText:function(allSelectedText){this.options.allSelectedText=allSelectedText,this.updateButtonText()},isFirefox:function(){var firefoxIdentifier="firefox",valueNotFoundIndex=-1;return!(!navigator||!navigator.userAgent)&&navigator.userAgent.toLocaleLowerCase().indexOf("firefox")>-1},createAndApplyUniqueId:function($relatedElement){var id="multiselect_"+this.multiselectId+"_"+this.internalIdCount++;return $relatedElement&&($relatedElement[0].dataset.multiselectid=id),id},generateUniqueId:function(){return Math.random().toString(36).substr(2)}},$.fn.multiselect=function(option,parameter,extraOptions){return this.each((function(){var data=$(this).data("multiselect"),options;data||(data=new Multiselect(this,"object"==typeof option&&option)),"string"==typeof option&&data[option](parameter,extraOptions)}))},$.fn.multiselect.Constructor=Multiselect,$((function(){$("select[data-role=multiselect]").multiselect()}))}));

/*********************
Including file: assetFeedback.js
*********************/
/**
 * assetFeedback.js - Object that allows to send asset feedback to Site Owner
 *
 * @author     Mark Anthony Bautista
 * @copyright  (c) 2018 Lightrocket
 */
 
(function() {
assetFeedback = $.extend({}, email_popup,{
    params: {},
    templateSelector:"#asset-feedback-template",
    boxId:"asset-feedback-box",
    fields:["message","g-recaptcha-response"],
    sendUrl: APP.baseURL + 'preview/assetfeedback',
    field_definitions:{
        message:{mandatory:false},
        "g-recaptcha-response":{selector:"textarea.g-recaptcha-response"},
    },
    getTitle:function(){return lang.search_results.lbl_Feedback},
    getBtnSend:function(){
        var that = this;
        return {
            label:lang.assetdata.lbl_SendEmailAsset,
            events:{
                click:function(){$.proxy(that._beforeSendMsg(),that)},
            },
            preventDismiss:true,
            classes:"btn-primary"
        };
    },
    sendMsg:function(){
        var that = this;
        $.post(this.sendUrl, this.params, function(data){
            $("#"+that.options.boxId +' #error_send_msg').text('');
            
            if(data.success === true){
                that.showErrors(false);
                alert(data.messages.join("<br>"));
                that.hide();
            }
            else{
                if(data.fields != undefined && $.isArray(data.fields)){
                    that.showErrors(data);
                }
            }
            if ( $("#" + that.options.boxId + " #nocaptcha").val() === undefined || $("#" + that.options.boxId + " #nocaptcha").val() == 0) that.updateCaptcha();
        }, "json");
    },
    onClose:function(){
        preview.feedbackVisible = false;
    },
});
})();