

/*********************
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) 2009 Lightrocket
 */
var headerSearch = {
        
    
    _setup:function() {
        
        $('#search #header_search').focus(function() {
            if(this.value == $('#search #header_search').attr('tag')) {
                this.value = '';
            } else {
                this.select();
            }
        });
        $('#block_search').find('br').remove();
        $('#main_search_btn').attr("value",lang.common.lbl_headerSearchBtn);
        
        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);
        
    }
};

// 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: 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: 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: 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: 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: 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: 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: 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: 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: 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)});