<commit_before>/**
 * jquery.textareaHighlighter.js 0.3.7
 * jQuery plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gmail.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var cloneCSSProperties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'
    ];

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            matches: [
                // {'matchClass': '', 'match': []}
            ],
            maxlength: -1,
            maxlengthWarning: '',
            maxlengthElement: null,
            debug: false,
            isAutoExpand: true,
            typingDelay: 30
        };

    // constructor
    function Plugin ( element, options ) {
        this.isInited  = false;
        this.element   = element;
        this.$element  = $(this.element);
        this.settings  = $.extend( {}, defaults, this.$element.data(), options );
        this._defaults = defaults;
        this._name     = pluginName;

        this.style = {};
        this.$wrapDiv       = $(document.createElement('div')).addClass('textarea-highlighter-wrap');
        this.$backgroundDiv = $(document.createElement('div')),
        this.$autoSize = $('

').hide();

        this.init();
    }

    Plugin.prototype = {
        init: function() {
            var _this          = this,
                $this          = this.$element,
                style          = this.style,
                settings       = this.settings,
                $wrapDiv       = this.$wrapDiv,
                $backgroundDiv = this.$backgroundDiv;

            _this.updateStyle();

            $this
                .data('highlighterTimerId', -1)
                // Bind events
                .on('scroll.textarea.highlighter', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                // ORIGINAL EVENTS
                .on('textarea.highlighter.destroy', function(){
                    _this.destroy();
                })
                .on('textarea.highlighter.updateStyle', function(){
                    _this.updateStyle();
                    _this.updateHeight();
                })
                .on('textarea.highlighter.change', function(){
                    _this.change({});
                })
                // debug mode toggle
                .on('textarea.highlighter.debug.on', function(){
                    _this.debugModeOn();
                })
                .on('textarea.highlighter.debug.off', function(){
                    _this.debugModeOff();
                });

            if ('onpropertychange' in _this.element) {
                if ('oninput' in _this.element) {
                    // IE 9+
                    $this.on('input.textarea.highlighter keyup.textarea.highlighter', function(e){
                        _this.change(e);
                    });
                    // on backspace key long press
                    var lastUpdate = new Date().getTime();
                    var timeDiff = 0;
                    $this.on('keydown.textarea.highlighter', function(e){
                        timeDiff = Math.abs(lastUpdate - new Date().getTime());
                        if (e.which === 8 && (timeDiff < 10 || 250 < timeDiff)) {
                            _this.change(e);
                            lastUpdate = new Date().getTime();
                        }
                    });
                }
                else {
                    // IE 7/8
                    $this.on('propertychange.textarea.highlighter', function(e){
                        _this.change(e);
                    });
                }
            }
            else {
                // Modern browsers
                $this.on('input.textarea.highlighter', function(e){
                    _this.change(e);
                });
            }

            // insert backgroundDiv
            $this.wrap( $wrapDiv ).before( $backgroundDiv );

            if (settings.isAutoExpand) {
                $this.after( _this.$autoSize );
            }
            // do initial check for input
            _this.change({});
        },
        updateStyle: function(){
            var _this    = this,
                $this    = this.$element,
                settings = this.settings,
                style    = this.style;

            // textarea style
            style = {
                // background   : this.$element.css('background'),
                paddingTop   : parseInt( $this.css('padding-top'), 10 ),
                paddingRight : parseInt( $this.css('padding-right'), 10 ),
                paddingBottom: parseInt( $this.css('padding-bottom'), 10 ),
                paddingLeft  : parseInt( $this.css('padding-left'), 10 ),
            };

            // Hack for firefox, some how width needs to be 2px smallet then the textarea
            // and padding-left needs to be added 1px
            if( browser.firefox ){
                style.paddingRight += 1;
                style.paddingLeft += 1;
            }
            if( browser.iphone ){
                style.paddingRight += 3;
                style.paddingLeft += 3;
            }

            // wrap div
            this.$wrapDiv.css({
                'position': 'relative'
            });

            // background div
            this.$backgroundDiv.addClass('background-div').addClass( $this.attr('class') ).css({
                'height'    : '100%',
                'color'     : ( settings.debug ) ? '#f00' : 'transparent',
                'background': ( settings.debug ) ? '#fee' : style.background,
                'position'  : 'absolute',
                'padding-top'   : style.paddingTop,
                'padding-right' : style.paddingRight,
                'padding-bottom': style.paddingBottom,
                'padding-left'  : style.paddingLeft
            });
            _this.cloneCSSToTarget( _this.$backgroundDiv );

            // auto size div
            _this.$autoSize.addClass( $this.attr('class') ).css({
                'position': 'absolute',
                'top'     : 0,
                'left'    : 0,
                'padding-top'   : style.paddingTop,
                'padding-right' : style.paddingRight,
                'padding-bottom': style.paddingBottom,
                'padding-left'  : style.paddingLeft
            });
            _this.cloneCSSToTarget( _this.$autoSize );

            // text area element
            $this.css({
                'color'     : ( settings.debug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });
        },
        change: function(e){
            var _this = this,
                settings = _this.settings;
            // if arrow keys, don't do anything
            if (/(37|38|39|40)/.test(e.keyCode)) { return true; }

            if (_this.isInited) {
                _this.updateHeight();
            }

            // check for last update, this is for performace
            if (_this.$element.data('highlighterTimerId') !== -1) {
                clearTimeout( _this.$element.data('highlighterTimerId') );
                _this.$element.data('highlighterTimerId', -1);
            }

            // id for set timeout
            var changeId = setTimeout(function(){
                var tmpMaxLengthObj = _this.checkMaxLength();
                var tmpMatchedObj = _this.checkMatchWords( tmpMaxLengthObj.notOverMaxText );

                // update background div content
                _this.$backgroundDiv.html( tmpMatchedObj.txt + tmpMaxLengthObj.overMaxText );
                // trigger update event
                _this.$element.trigger('textarea.highlighter.update', {'textList': tmpMatchedObj.matchedList});

                // if not initialize execution the trigger an initialization complete event
                if (!_this.isInited) {
                    _this.isInited = true;
                    _this.$element.trigger('textarea.highlighter.init.complete');
                    _this.updateHeight();
                }
            }, settings.typingDelay);
            // set setTimeout id
            _this.$element.data('highlighterTimerId', changeId);
        },
        // wrap matched text with an HTML element
        getWrapedText: function( text, matchedText, matchClass ){
            return text.replace( new RegExp( helper.escapeRegExp( matchedText ), 'g'), this.getTextInSpan( matchClass, matchedText ) );
        },
        getTextInSpan: function( className, text ){
            return ''+ text +'';
        },

        checkMaxLength: function(){
            var _this = this,
                textareaText = _this.$element.val(),
                settings = _this.settings,
                maxSize = 0,
                overMaxText = '',
                notOverMaxText = '';

            if (0 < settings.maxlength) {
                // check for max length
                if ( settings.maxlength < textareaText.length) {
                    // get text that was over max length
                    overMaxText = textareaText.slice( settings.maxlength, settings.maxlength + textareaText.length - 1 );
                    overMaxText = helper.escapeHTML( overMaxText );
                    overMaxText = _this.getTextInSpan(settings.maxlengthWarning, overMaxText);
                }
                // update text max length
                if (settings.maxlengthElement !== null) {
                    maxSize = settings.maxlength - textareaText.length;

                    if (maxSize < 0) {
                        // add max length warning class
                        if (! settings.maxlengthElement.hasClass( settings.maxlengthWarning )) {
                            settings.maxlengthElement.addClass( settings.maxlengthWarning );
                        }
                    }
                    else {
                        // remove max length warning class
                        if (settings.maxlengthElement.hasClass( settings.maxlengthWarning )) {
                            settings.maxlengthElement.removeClass( settings.maxlengthWarning );
                        }
                    }
                    // update max length
                    settings.maxlengthElement.text( maxSize );
                }
                // set text that wasn't over max length
                notOverMaxText = textareaText.slice( 0, settings.maxlength );
            }
            else {
                // max length wasn't set so use input text without any extra settings
                notOverMaxText = textareaText;
            }

            return {
                'overMaxText': overMaxText,
                'notOverMaxText': helper.escapeHTML( notOverMaxText )
            };
        },

        checkMatchWords: function( escapedTargetText ){
            var settings = this.settings;
            var i = 0, imax = 0, j = 0, jmax = 0,
                matchesList = [], matchTextList = [],
                matchText = '', matchTextEscape = '', matchClass = '',
                matched = null;

            // check for matching words
            for (i = 0, imax = settings.matches.length; i < imax; i++) {

                // check if match match is a RegExp
                if (settings.matches[i].match instanceof RegExp) {
                    // set matched words array
                    matchesList = helper.getUniqueArray( escapedTargetText.match( settings.matches[i].match ) || [] );
                }
                else {
                    // copy words array
                    matchesList = settings.matches[i].match;
                }

                for (j = 0, jmax = matchesList.length; j < jmax; j++) {
                    // get word to match
                    matchText = matchesList[j];
                    matchTextEscape = helper.escapeHTML( matchText );
                    matchClass = '';

                    matched = escapedTargetText.match(new RegExp( helper.escapeRegExp(matchTextEscape), 'g' ));
                    // check if word exists in input text
                    if (matched && 0 < matched.length){
                        matchTextList.push({
                            text: matchText,
                            matched: matched
                        });

                        // check for match class name
                        if (settings.matches[i].hasOwnProperty('matchClass')) {
                            matchClass = settings.matches[i].matchClass;
                        }
                        // update replaced text
                        escapedTargetText = this.getWrapedText( escapedTargetText, matchTextEscape, matchClass );
                    }
                }
            }

            return {
                'txt': escapedTargetText,
                'matchedList': matchTextList
            };
        },

        updateHeight: function(){
            var _this = this;

            if (_this.settings.isAutoExpand) {
                _this.$autoSize.find('.autosize').html( _this.$element.val().replace(/\r\n/g, "\n") + ' ' );
                _this.$element.height( _this.$autoSize.height() );
            }
        },

        cloneCSSToTarget: function( $t ){
            var $element = this.$element;
            var val = null;
            $.each(cloneCSSProperties, function(i, p) {
                val = $element.css(p);
                // Only set if different to prevent overriding percentage css values.
                if ($t.css(p) !== val) {
                    $t.css(p, val);
                }
            });
        },

        // Destroy plugin in settings & extra elements that were added
        destroy: function(){
            $.data( this.element, "plugin_" + pluginName, false );
            this.$backgroundDiv.remove();
            this.$element
                .off('scroll.textarea.highlighter')
                .off('input.textarea.highlighter keyup.textarea.highlighter')
                .off('textarea.highlighter.destroy')
                .off('textarea.highlighter.update')
                .off('textarea.highlighter.change')
                .css({
                    'color'     : '',
                    'position'  : '',
                    'background': ''
                })
                .unwrap();
        },
        // Turn on debug mode
        debugModeOn: function(){
            this.settings.debug = true;
            this.$backgroundDiv.css({ 'color': '#f00' });
            this.$element.css({ 'color': 'rgba(0,0,0,0.5)' });
        },
        // Turn off debug mode
        debugModeOff: function(){
            this.settings.debug = false;
            this.$backgroundDiv.css({ 'color': 'transparent' });
            this.$element.css({ 'color': 'inherit' });
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var helper = {
        escapeHTML: function(str){
            return $( document.createElement('div') ).text(str).html();
        },
        escapeRegExp: function(str){
            return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
        },
        getUniqueArray: function( array ){
            return array.filter(function(elem, pos, self) {
                if ( elem === '' ) {
                    return false;
                }
                return self.indexOf(elem) === pos;
            });
        }
    };
    // get curretn bworser type
    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

})( jQuery, window, document );<commit_msg>update style when change event is callend<commit_after>/**
 * jquery.textareaHighlighter.js 0.3.7
 * jQuery plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gmail.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var cloneCSSProperties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'
    ];

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            matches: [
                // {'matchClass': '', 'match': []}
            ],
            maxlength: -1,
            maxlengthWarning: '',
            maxlengthElement: null,
            debug: false,
            isAutoExpand: true,
            typingDelay: 30
        };

    // constructor
    function Plugin ( element, options ) {
        this.isInited  = false;
        this.element   = element;
        this.$element  = $(this.element);
        this.settings  = $.extend( {}, defaults, this.$element.data(), options );
        this._defaults = defaults;
        this._name     = pluginName;

        this.style = {};
        this.$wrapDiv       = $(document.createElement('div')).addClass('textarea-highlighter-wrap');
        this.$backgroundDiv = $(document.createElement('div')),
        this.$autoSize = $('

').hide();

        this.init();
    }

    Plugin.prototype = {
        init: function() {
            var _this          = this,
                $this          = this.$element,
                style          = this.style,
                settings       = this.settings,
                $wrapDiv       = this.$wrapDiv,
                $backgroundDiv = this.$backgroundDiv;

            _this.updateStyle();

            $this
                .data('highlighterTimerId', -1)
                // Bind events
                .on('scroll.textarea.highlighter', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                // ORIGINAL EVENTS
                .on('textarea.highlighter.destroy', function(){
                    _this.destroy();
                })
                .on('textarea.highlighter.updateStyle', function(){
                    _this.updateStyle();
                    _this.updateHeight();
                })
                .on('textarea.highlighter.change', function(){
                    _this.updateStyle();
                    _this.updateHeight();
                    _this.change({});
                })
                // debug mode toggle
                .on('textarea.highlighter.debug.on', function(){
                    _this.debugModeOn();
                })
                .on('textarea.highlighter.debug.off', function(){
                    _this.debugModeOff();
                });

            if ('onpropertychange' in _this.element) {
                if ('oninput' in _this.element) {
                    // IE 9+
                    $this.on('input.textarea.highlighter keyup.textarea.highlighter', function(e){
                        _this.change(e);
                    });
                    // on backspace key long press
                    var lastUpdate = new Date().getTime();
                    var timeDiff = 0;
                    $this.on('keydown.textarea.highlighter', function(e){
                        timeDiff = Math.abs(lastUpdate - new Date().getTime());
                        if (e.which === 8 && (timeDiff < 10 || 250 < timeDiff)) {
                            _this.change(e);
                            lastUpdate = new Date().getTime();
                        }
                    });
                }
                else {
                    // IE 7/8
                    $this.on('propertychange.textarea.highlighter', function(e){
                        _this.change(e);
                    });
                }
            }
            else {
                // Modern browsers
                $this.on('input.textarea.highlighter', function(e){
                    _this.change(e);
                });
            }

            // insert backgroundDiv
            $this.wrap( $wrapDiv ).before( $backgroundDiv );

            if (settings.isAutoExpand) {
                $this.after( _this.$autoSize );
            }
            // do initial check for input
            _this.change({});
        },
        updateStyle: function(){
            var _this    = this,
                $this    = this.$element,
                settings = this.settings,
                style    = this.style;

            // textarea style
            style = {
                // background   : this.$element.css('background'),
                paddingTop   : parseInt( $this.css('padding-top'), 10 ),
                paddingRight : parseInt( $this.css('padding-right'), 10 ),
                paddingBottom: parseInt( $this.css('padding-bottom'), 10 ),
                paddingLeft  : parseInt( $this.css('padding-left'), 10 ),
            };

            // Hack for firefox, some how width needs to be 2px smallet then the textarea
            // and padding-left needs to be added 1px
            if( browser.firefox ){
                style.paddingRight += 1;
                style.paddingLeft += 1;
            }
            if( browser.iphone ){
                style.paddingRight += 3;
                style.paddingLeft += 3;
            }

            // wrap div
            this.$wrapDiv.css({
                'position': 'relative'
            });

            // background div
            this.$backgroundDiv.addClass('background-div').addClass( $this.attr('class') ).css({
                'height'    : '100%',
                'color'     : ( settings.debug ) ? '#f00' : 'transparent',
                'background': ( settings.debug ) ? '#fee' : style.background,
                'position'  : 'absolute',
                'padding-top'   : style.paddingTop,
                'padding-right' : style.paddingRight,
                'padding-bottom': style.paddingBottom,
                'padding-left'  : style.paddingLeft
            });
            _this.cloneCSSToTarget( _this.$backgroundDiv );

            // auto size div
            _this.$autoSize.addClass( $this.attr('class') ).css({
                'position': 'absolute',
                'top'     : 0,
                'left'    : 0,
                'padding-top'   : style.paddingTop,
                'padding-right' : style.paddingRight,
                'padding-bottom': style.paddingBottom,
                'padding-left'  : style.paddingLeft
            });
            _this.cloneCSSToTarget( _this.$autoSize );

            // text area element
            $this.css({
                'color'     : ( settings.debug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });
        },
        change: function(e){
            var _this = this,
                settings = _this.settings;
            // if arrow keys, don't do anything
            if (/(37|38|39|40)/.test(e.keyCode)) { return true; }

            if (_this.isInited) {
                _this.updateHeight();
            }

            // check for last update, this is for performace
            if (_this.$element.data('highlighterTimerId') !== -1) {
                clearTimeout( _this.$element.data('highlighterTimerId') );
                _this.$element.data('highlighterTimerId', -1);
            }

            // id for set timeout
            var changeId = setTimeout(function(){
                var tmpMaxLengthObj = _this.checkMaxLength();
                var tmpMatchedObj = _this.checkMatchWords( tmpMaxLengthObj.notOverMaxText );

                // update background div content
                _this.$backgroundDiv.html( tmpMatchedObj.txt + tmpMaxLengthObj.overMaxText );
                // trigger update event
                _this.$element.trigger('textarea.highlighter.update', {'textList': tmpMatchedObj.matchedList});

                // if not initialize execution the trigger an initialization complete event
                if (!_this.isInited) {
                    _this.isInited = true;
                    _this.$element.trigger('textarea.highlighter.init.complete');
                    _this.updateHeight();
                }
            }, settings.typingDelay);
            // set setTimeout id
            _this.$element.data('highlighterTimerId', changeId);
        },
        // wrap matched text with an HTML element
        getWrapedText: function( text, matchedText, matchClass ){
            return text.replace( new RegExp( helper.escapeRegExp( matchedText ), 'g'), this.getTextInSpan( matchClass, matchedText ) );
        },
        getTextInSpan: function( className, text ){
            return ''+ text +'';
        },

        checkMaxLength: function(){
            var _this = this,
                textareaText = _this.$element.val(),
                settings = _this.settings,
                maxSize = 0,
                overMaxText = '',
                notOverMaxText = '';

            if (0 < settings.maxlength) {
                // check for max length
                if ( settings.maxlength < textareaText.length) {
                    // get text that was over max length
                    overMaxText = textareaText.slice( settings.maxlength, settings.maxlength + textareaText.length - 1 );
                    // escape HTML
                    overMaxText = helper.escapeHTML( overMaxText );
                    // wrap matched text with  tags
                    overMaxText = _this.getTextInSpan(settings.maxlengthWarning, overMaxText);
                }
                // update text max length
                if (settings.maxlengthElement !== null) {
                    maxSize = settings.maxlength - textareaText.length;

                    if (maxSize < 0) {
                        // add max length warning class
                        if (! settings.maxlengthElement.hasClass( settings.maxlengthWarning )) {
                            settings.maxlengthElement.addClass( settings.maxlengthWarning );
                        }
                    }
                    else {
                        // remove max length warning class
                        if (settings.maxlengthElement.hasClass( settings.maxlengthWarning )) {
                            settings.maxlengthElement.removeClass( settings.maxlengthWarning );
                        }
                    }
                    // update max length
                    settings.maxlengthElement.text( maxSize );
                }
                // set text that wasn't over max length
                notOverMaxText = textareaText.slice( 0, settings.maxlength );
            }
            else {
                // max length wasn't set so use input text without any extra settings
                notOverMaxText = textareaText;
            }

            return {
                'overMaxText': overMaxText,
                'notOverMaxText': helper.escapeHTML( notOverMaxText )
            };
        },

        checkMatchWords: function( escapedTargetText ){
            var settings = this.settings;
            var i = 0, imax = 0, j = 0, jmax = 0,
                matchesList = [], matchTextList = [],
                matchText = '', matchTextEscape = '', matchClass = '',
                matched = null;

            // check for matching words
            for (i = 0, imax = settings.matches.length; i < imax; i++) {

                // check if match match is a RegExp
                if (settings.matches[i].match instanceof RegExp) {
                    // set matched words array
                    matchesList = helper.getUniqueArray( escapedTargetText.match( settings.matches[i].match ) || [] );
                }
                else {
                    // copy words array
                    matchesList = settings.matches[i].match;
                }

                for (j = 0, jmax = matchesList.length; j < jmax; j++) {
                    // get word to match
                    matchText = matchesList[j];
                    matchTextEscape = helper.escapeHTML( matchText );
                    matchClass = '';

                    matched = escapedTargetText.match(new RegExp( helper.escapeRegExp(matchTextEscape), 'g' ));
                    // check if word exists in input text
                    if (matched && 0 < matched.length){
                        matchTextList.push({
                            text: matchText,
                            matched: matched
                        });

                        // check for match class name
                        if (settings.matches[i].hasOwnProperty('matchClass')) {
                            matchClass = settings.matches[i].matchClass;
                        }
                        // update replaced text
                        escapedTargetText = this.getWrapedText( escapedTargetText, matchTextEscape, matchClass );
                    }
                }
            }

            return {
                'txt': escapedTargetText,
                'matchedList': matchTextList
            };
        },

        updateHeight: function(){
            var _this = this;

            if (_this.settings.isAutoExpand) {
                _this.$autoSize.find('.autosize').html( _this.$element.val().replace(/\r\n/g, "\n") + ' ' );
                _this.$element.height( _this.$autoSize.height() );
            }
        },

        cloneCSSToTarget: function( $t ){
            var $element = this.$element;
            var val = null;
            $.each(cloneCSSProperties, function(i, p) {
                val = $element.css(p);
                // Only set if different to prevent overriding percentage css values.
                if ($t.css(p) !== val) {
                    $t.css(p, val);
                }
            });
        },

        // Destroy plugin in settings & extra elements that were added
        destroy: function(){
            $.data( this.element, "plugin_" + pluginName, false );
            this.$backgroundDiv.remove();
            this.$element
                .off('scroll.textarea.highlighter')
                .off('input.textarea.highlighter keyup.textarea.highlighter')
                .off('textarea.highlighter.destroy')
                .off('textarea.highlighter.update')
                .off('textarea.highlighter.change')
                .css({
                    'color'     : '',
                    'position'  : '',
                    'background': ''
                })
                .unwrap();
        },
        // Turn on debug mode
        debugModeOn: function(){
            this.settings.debug = true;
            this.$backgroundDiv.css({ 'color': '#f00' });
            this.$element.css({ 'color': 'rgba(0,0,0,0.5)' });
        },
        // Turn off debug mode
        debugModeOff: function(){
            this.settings.debug = false;
            this.$backgroundDiv.css({ 'color': 'transparent' });
            this.$element.css({ 'color': 'inherit' });
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var helper = {
        escapeHTML: function(str){
            return $( document.createElement('div') ).text(str).html();
        },
        escapeRegExp: function(str){
            return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
        },
        getUniqueArray: function( array ){
            return array.filter(function(elem, pos, self) {
                if ( elem === '' ) {
                    return false;
                }
                return self.indexOf(elem) === pos;
            });
        }
    };
    // get curretn bworser type
    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

})( jQuery, window, document );<|endoftext|>


<commit_before>/**
 * jquery.textareaHighlighter.js 0.1.0
 * Plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gengo.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            matches: [
                {'className': '', 'words': []}
            ],
            isDebug: false
        };

    // constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(this.element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;

        // textarea style
        this.style = {
            backgroundColor: this.$element.css('background-color'),
            paddingTop   : parseInt( this.$element.css('padding-top'), 10 ),
            paddingRight : parseInt( this.$element.css('padding-right'), 10 ),
            paddingBottom: parseInt( this.$element.css('padding-bottom'), 10 ),
            paddingLeft  : parseInt( this.$element.css('padding-left'), 10 ),
            borderTop    : parseInt( this.$element.css('border-top-width'), 10 ),
            borderRight  : parseInt( this.$element.css('border-right-width'), 10 ),
            borderBottom : parseInt( this.$element.css('border-bottom-width'), 10 ),
            borderLeft   : parseInt( this.$element.css('border-left-width'), 10 ),
            lineHeight   : this.$element.css('line-height')
        };

        this.widthExtra = this.style.paddingLeft + this.style.paddingRight + this.style.borderLeft + this.style.borderRight;

        this.style.paddingTop += this.style.borderTop;
        this.style.paddingLeft += this.style.borderLeft;

        // Hack for firefox, some how width needs to be 2px smallet then the textarea
        // and padding-left needs to be added 1px
        if( browser.firefox ){
            this.widthExtra += 2;
            this.style.paddingLeft += 1;
        }
        // Hack for iphone, some how in iphone it adds 3px to textarea padding
        if( browser.iphone ){
            this.style.paddingRight += 3;
            this.style.paddingLeft += 3;
            this.widthExtra += 6;
        }
        if( browser.msie ){
            this.style.paddingTop += -1;
            this.style.paddingLeft += 1;
            this.style.paddingBottom += 2;
        }

        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var _this          = this,
                $this          = this.$element,
                $wrapDiv       = $(document.createElement('div')).addClass('textarea-wrap'),
                $backgroundDiv = $(document.createElement('div')),
                lastUpdate     = new Date().getTime();

            $wrapDiv.css({
                'position'     : 'relative',
                'word-wrap'    : 'break-word',
                'word-break'   : 'break-all',
                'margin'       : 0,
                'padding-right': _this.style.paddingLeft + _this.style.paddingRight + _this.style.borderLeft + _this.style.borderRight + 'px'
            });
            $backgroundDiv.addClass('background-div').css({
                'height': 0,
                'width' : 0,
                'color'           : ( _this.settings.isDebug ) ? '#f00' : 'transparent',
                'background-color': ( _this.settings.isDebug ) ? '#fee' : _this.style.backgroundColor,
                'line-height'   : _this.style.lineHeight,
                'padding-top'   : _this.style.paddingTop,
                'padding-right' : _this.style.paddingRight,
                'padding-bottom': _this.style.paddingBottom,
                'padding-left'  : _this.style.paddingLeft,
                'position'      : 'absolute',
                'overflow'      : 'auto',
                'white-space'   : 'pre-wrap',
                // this is for IE
                'border'        : '0px',
                'text-decoration': 'none'
            });
            $this.css({
                'color'     : ( _this.settings.isDebug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });

            $this
                .on('scroll', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                .on('change keyup keydown', function(e){
                    // if arrow keys, don't do anything
                    if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) { return; }
                    // check for last update, this is for performace
                    if (new Date().getTime() - lastUpdate < 30) { return; }

                    var textareaText = $(document.createElement('div')).text( $this.val() ).html(),
                        key, ruleTextList, matchText, spanText, i, imax, j, jmax;

                    for (i = 0, imax = _this.settings.matches.length; i < imax; i++) {
                        for (j = 0, jmax = _this.settings.matches[i].words.length; j < jmax; j++) {
                            // get word to match
                            matchText = _this.settings.matches[i].words[j];
                            // check if word exists in input text
                            if( textareaText.indexOf( matchText ) !== -1 ){
                                spanText = ''+ matchText +'';
                                textareaText = textareaText.replace( new RegExp( _escapeRegExp( matchText ), 'g'), spanText );
                            }
                        }
                    }

                    $backgroundDiv.html( textareaText );
                    resize();
                    lastUpdate = new Date().getTime();
                });

            // update backgroundDiv size
            var resize = function(){
                if( $backgroundDiv.height() !== $this.height() || $backgroundDiv.width() !== $this.width() ){
                    $backgroundDiv.css({
                        'width' : $this.outerWidth() - _this.widthExtra,
                        'height': $this.height()
                    });
                }
            };

            $this.wrap( $wrapDiv ).before( $backgroundDiv );
            resize();
        }
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var _escapeRegExp = function(str){
        return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );<commit_msg>remove some unnecessary style for IE<commit_after>/**
 * jquery.textareaHighlighter.js 0.1.0
 * Plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gengo.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            matches: [
                {'className': '', 'words': []}
            ],
            isDebug: false
        };

    // constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(this.element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;

        // textarea style
        this.style = {
            backgroundColor: this.$element.css('background-color'),
            paddingTop   : parseInt( this.$element.css('padding-top'), 10 ),
            paddingRight : parseInt( this.$element.css('padding-right'), 10 ),
            paddingBottom: parseInt( this.$element.css('padding-bottom'), 10 ),
            paddingLeft  : parseInt( this.$element.css('padding-left'), 10 ),
            borderTop    : parseInt( this.$element.css('border-top-width'), 10 ),
            borderRight  : parseInt( this.$element.css('border-right-width'), 10 ),
            borderBottom : parseInt( this.$element.css('border-bottom-width'), 10 ),
            borderLeft   : parseInt( this.$element.css('border-left-width'), 10 ),
            lineHeight   : this.$element.css('line-height')
        };

        this.widthExtra = this.style.paddingLeft + this.style.paddingRight + this.style.borderLeft + this.style.borderRight;

        this.style.paddingTop += this.style.borderTop;
        this.style.paddingLeft += this.style.borderLeft;

        // Hack for firefox, some how width needs to be 2px smallet then the textarea
        // and padding-left needs to be added 1px
        if( browser.firefox ){
            this.widthExtra += 2;
            this.style.paddingLeft += 1;
        }
        // Hack for iphone, some how in iphone it adds 3px to textarea padding
        if( browser.iphone ){
            this.style.paddingRight += 3;
            this.style.paddingLeft += 3;
            this.widthExtra += 6;
        }
        if( browser.msie ){
            this.style.paddingTop += -1;
            this.style.paddingLeft += 1;
            this.style.paddingBottom += 2;
        }

        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var _this          = this,
                $this          = this.$element,
                $wrapDiv       = $(document.createElement('div')).addClass('textarea-wrap'),
                $backgroundDiv = $(document.createElement('div')),
                lastUpdate     = new Date().getTime();

            $wrapDiv.css({
                'position'     : 'relative',
                'word-wrap'    : 'break-word',
                'word-break'   : 'break-all',
                'margin'       : 0,
                'padding-right': _this.style.paddingLeft + _this.style.paddingRight + _this.style.borderLeft + _this.style.borderRight + 'px'
            });
            $backgroundDiv.addClass('background-div').css({
                'height': 0,
                'width' : 0,
                'color'           : ( _this.settings.isDebug ) ? '#f00' : 'transparent',
                'background-color': ( _this.settings.isDebug ) ? '#fee' : _this.style.backgroundColor,
                'line-height'   : _this.style.lineHeight,
                'padding-top'   : _this.style.paddingTop,
                'padding-right' : _this.style.paddingRight,
                'padding-bottom': _this.style.paddingBottom,
                'padding-left'  : _this.style.paddingLeft,
                'position'      : 'absolute',
                'overflow'      : 'auto',
                'white-space'   : 'pre-wrap'
            });
            $this.css({
                'color'     : ( _this.settings.isDebug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });

            $this
                .on('scroll', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                .on('change keyup keydown', function(e){
                    // if arrow keys, don't do anything
                    if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) { return; }
                    // check for last update, this is for performace
                    if (new Date().getTime() - lastUpdate < 30) { return; }

                    var textareaText = $(document.createElement('div')).text( $this.val() ).html(),
                        key, ruleTextList, matchText, spanText, i, imax, j, jmax;

                    for (i = 0, imax = _this.settings.matches.length; i < imax; i++) {
                        for (j = 0, jmax = _this.settings.matches[i].words.length; j < jmax; j++) {
                            // get word to match
                            matchText = _this.settings.matches[i].words[j];
                            // check if word exists in input text
                            if( textareaText.indexOf( matchText ) !== -1 ){
                                spanText = ''+ matchText +'';
                                textareaText = textareaText.replace( new RegExp( _escapeRegExp( matchText ), 'g'), spanText );
                            }
                        }
                    }

                    $backgroundDiv.html( textareaText );
                    resize();
                    lastUpdate = new Date().getTime();
                });

            // update backgroundDiv size
            var resize = function(){
                if( $backgroundDiv.height() !== $this.height() || $backgroundDiv.width() !== $this.width() ){
                    $backgroundDiv.css({
                        'width' : $this.outerWidth() - _this.widthExtra,
                        'height': $this.height()
                    });
                }
            };

            $this.wrap( $wrapDiv ).before( $backgroundDiv );
            resize();
        }
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var _escapeRegExp = function(str){
        return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );<|endoftext|>


<commit_before>var markers_array = new Array();

/* Creation of map object */
var map = new OpenLayers.Map("map");

/* Declaring base layer */
var osm = new OpenLayers.Layer.OSM();

/* Adding layer to map */
map.addLayer(osm);

/* Zooming inital to extend */
map.zoomToMaxExtent();

/* Centering and zooming to fit global view */
map.setCenter(new OpenLayers.LonLat(0,10), 2);
map.zoomToMaxExtent();
map.setCenter(new OpenLayers.LonLat(0,15).transform(
    new OpenLayers.Projection("EPSG:4326"),
    new OpenLayers.Projection("EPSG:900913")
), 2);

/* initialize markers overlay */
var markers = new OpenLayers.Layer.Markers("Reps");
map.addLayer(markers);
var size = new OpenLayers.Size(21, 33);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('/media/img/remo/marker.png',size,offset);
markers.setOpacity(0.7);

$(function() {
    $('#searchform').submit(function(event) {
	event.preventDefault();
    })

    $('#listviewbutton').bind('click', (function() {
	$('#profiles_listview').hide();
	$('#profiles_gridview').show();
	qs.cache();
    }))

    $('#gridviewbutton').bind('click', (function() {
	$('#profiles_gridview').hide();
	$('#profiles_listview').show();
	qs1.cache();
    }))

    var qs = $('input#searchfield').quicksearch('ul#searchlist li', {
	'show': function () {
	    markers_array[$(this).attr('id')].display(true);
	    $(this).show();
	},
	'hide': function () {
	    markers_array[$(this).attr('id')].display(false);
	    $(this).hide();
	}
    })

    var qs1 = $('input#searchfield').quicksearch('table#list-people-view tr td')

    search_string = window.location.pathname.substr(8);
    if (search_string.length > 0) {
	$('input#searchfield').val(search_string);
	qs.cache();
    }
});
<commit_msg>Fix for quicksearch bug 726360<commit_after>var markers_array = new Array();

/* Creation of map object */
var map = new OpenLayers.Map("map");

/* Declaring base layer */
var osm = new OpenLayers.Layer.OSM();

/* Adding layer to map */
map.addLayer(osm);

/* Zooming inital to extend */
map.zoomToMaxExtent();

/* Centering and zooming to fit global view */
map.setCenter(new OpenLayers.LonLat(0,10), 2);
map.zoomToMaxExtent();
map.setCenter(new OpenLayers.LonLat(0,15).transform(
    new OpenLayers.Projection("EPSG:4326"),
    new OpenLayers.Projection("EPSG:900913")
), 2);

/* initialize markers overlay */
var markers = new OpenLayers.Layer.Markers("Reps");
map.addLayer(markers);
var size = new OpenLayers.Size(21, 33);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('/media/img/remo/marker.png',size,offset);
markers.setOpacity(0.7);

$(function() {
    $('#searchform').submit(function(event) {
	event.preventDefault();
    })

    $('#listviewbutton').bind('click', (function() {
	$('#profiles_listview').hide();
	$('#profiles_gridview').show();
	qs.cache();
    }))

    $('#gridviewbutton').bind('click', (function() {
	$('#profiles_gridview').hide();
	$('#profiles_listview').show();
	qs1.cache();
    }))

    var qs = $('input#searchfield').quicksearch('ul#searchlist li', {
	'show': function () {
	    markers_array[$(this).attr('id')].display(true);
	    $(this).show();
	},
	'hide': function () {
	    markers_array[$(this).attr('id')].display(false);
	    $(this).hide();
	}
    })

    qs1 = $('input#searchfield').quicksearch('table#list-people-view tbody tr');
    var qs1 = $('input#searchfield').quicksearch('table#list-people-view tr td')

    search_string = window.location.pathname.substr(8);
    if (search_string.length > 0) {
	$('input#searchfield').val(search_string);
	qs.cache();
    }
});
<|endoftext|>


<commit_before>/**
 * jquery.textareaHighlighter.js 0.1.0
 * Plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gengo.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            maxLength: 150,
            maxClass: 'error',
            matches: [
                // {'className': '', 'words': []}
            ],
            isDebug: false
        };

    // constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(this.element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;

        // textarea style
        this.style = {
            backgroundColor: this.$element.css('background-color'),
            paddingTop   : parseInt( this.$element.css('padding-top'), 10 ),
            paddingRight : parseInt( this.$element.css('padding-right'), 10 ),
            paddingBottom: parseInt( this.$element.css('padding-bottom'), 10 ),
            paddingLeft  : parseInt( this.$element.css('padding-left'), 10 ),
            borderTop    : parseInt( this.$element.css('border-top-width'), 10 ),
            borderRight  : parseInt( this.$element.css('border-right-width'), 10 ),
            borderBottom : parseInt( this.$element.css('border-bottom-width'), 10 ),
            borderLeft   : parseInt( this.$element.css('border-left-width'), 10 ),
            lineHeight   : this.$element.css('line-height')
        };

        this.widthExtra = this.style.paddingLeft + this.style.paddingRight + this.style.borderLeft + this.style.borderRight;

        this.style.paddingTop += this.style.borderTop;
        this.style.paddingLeft += this.style.borderLeft;

        // Hack for firefox, some how width needs to be 2px smallet then the textarea
        // and padding-left needs to be added 1px
        if( browser.firefox ){
            this.widthExtra += 2;
            this.style.paddingLeft += 1;
        }
        // Hack for iphone, some how in iphone it adds 3px to textarea padding
        if( browser.iphone ){
            this.style.paddingRight += 3;
            this.style.paddingLeft += 3;
            this.widthExtra += 6;
        }
        // Hack for ie
        if( browser.msie ){
            this.style.paddingTop += -1;
            this.style.paddingLeft += 1;
            this.style.paddingBottom += 2;
        }

        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var _this          = this,
                $this          = this.$element,
                $wrapDiv       = $(document.createElement('div')).addClass('textarea-wrap'),
                $backgroundDiv = $(document.createElement('div')),
                lastUpdate     = new Date().getTime();

            $wrapDiv.css({
                'position'     : 'relative',
                'word-wrap'    : 'break-word',
                'word-break'   : 'break-all',
                'margin'       : 0,
                'padding-right': _this.style.paddingLeft + _this.style.paddingRight + _this.style.borderLeft + _this.style.borderRight + 'px'
            });
            $backgroundDiv.addClass('background-div').css({
                'height': 0,
                'width' : 0,
                'color'           : ( _this.settings.isDebug ) ? '#f00' : 'transparent',
                'background-color': ( _this.settings.isDebug ) ? '#fee' : _this.style.backgroundColor,
                'line-height'   : _this.style.lineHeight,
                'padding-top'   : _this.style.paddingTop,
                'padding-right' : _this.style.paddingRight,
                'padding-bottom': _this.style.paddingBottom,
                'padding-left'  : _this.style.paddingLeft,
                'position'      : 'absolute',
                'overflow'      : 'auto',
                'white-space'   : 'pre-wrap'
            });
            $this.css({
                'color'     : ( _this.settings.isDebug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });

            $this
                .on('scroll', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                .on('change keyup keydown', function(e){
                    // if arrow keys, don't do anything
                    if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) { return; }
                    // check for last update, this is for performace
                    if (new Date().getTime() - lastUpdate < 30) { return; }

                    var textareaText = $(document.createElement('div')).text( $this.val() ).html(),
                        key, ruleTextList, matchText, spanText,
                        notOverMaxText = '', overMaxText ='',
                        i, imax, j, jmax;

                    // check for max length
                    if (_this.settings.maxLength < $this.val().length) {
                        matchText = $this.val().slice( _this.settings.maxLength, _this.settings.maxLength + $this.val().length - 1 );
                        overMaxText = ''+ matchText +'';
                    }

                    notOverMaxText = $this.val().slice( 0, _this.settings.maxLength );

                    // check for matching words
                    for (i = 0, imax = _this.settings.matches.length; i < imax; i++) {
                        for (j = 0, jmax = _this.settings.matches[i].words.length; j < jmax; j++) {
                            // get word to match
                            matchText = _this.settings.matches[i].words[j];
                            // check if word exists in input text
                            if( notOverMaxText.indexOf( matchText ) !== -1 ){
                                spanText = ''+ matchText +'';
                                notOverMaxText = notOverMaxText.replace( new RegExp( _escapeRegExp( matchText ), 'g'), spanText );
                            }
                        }
                    }
                    // update background div content
                    $backgroundDiv.html( notOverMaxText + overMaxText );
                    // check if textarea changed size
                    _this.resize( $this, $backgroundDiv );
                    // save last update time
                    lastUpdate = new Date().getTime();
                });

            $this.wrap( $wrapDiv ).before( $backgroundDiv );
            _this.resize( $this, $backgroundDiv );
        },
        /**
         * update backgroundDiv size
         * @param  {jQuery} $target
         * @param  {jQuery} $bgDiv
         */
        resize: function( $target, $bgDiv ){
            var _this = this;

            if( $bgDiv.height() !== $target.height() || $bgDiv.width() !== $target.width() ){
                $bgDiv.css({
                    'width' : $target.outerWidth() - _this.widthExtra,
                    'height': $target.height()
                });
            }
        }
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var _escapeRegExp = function(str){
        return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );<commit_msg>disable max text length check by default<commit_after>/**
 * jquery.textareaHighlighter.js 0.1.0
 * Plugin for highlighting text in textarea.
 *
 * alexandre.kirillov@gengo.com
 * MIT license. http://opensource.org/licenses/MIT
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var browser = (function(){
        var userAgent = navigator.userAgent,
            msie    = /(msie|trident)/i.test( userAgent ),
            chrome  = /chrome/i.test( userAgent ),
            firefox = /firefox/i.test( userAgent ),
            safari  = /safari/i.test( userAgent ) && !chrome,
            iphone  = /iphone/i.test( userAgent );

        if( msie ){ return { msie: true }; }
        if( chrome ){ return { chrome: true }; }
        if( firefox ){ return { firefox: true }; }
        if( iphone ){ return { iphone: true }; }
        if( safari ){ return { safari: true }; }

        return {
            msie   : false,
            chrome : false,
            firefox: false,
            safari : false,
            iphone : false
        };
    }());

    /**
     *
     * PLUGIN CORE
     *
     */
    var pluginName = "textareaHighlighter",
        defaults = {
            maxLength: -1,
            maxClass: 'error',
            matches: [
                // {'className': '', 'words': []}
            ],
            isDebug: false
        };

    // constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(this.element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;

        // textarea style
        this.style = {
            backgroundColor: this.$element.css('background-color'),
            paddingTop   : parseInt( this.$element.css('padding-top'), 10 ),
            paddingRight : parseInt( this.$element.css('padding-right'), 10 ),
            paddingBottom: parseInt( this.$element.css('padding-bottom'), 10 ),
            paddingLeft  : parseInt( this.$element.css('padding-left'), 10 ),
            borderTop    : parseInt( this.$element.css('border-top-width'), 10 ),
            borderRight  : parseInt( this.$element.css('border-right-width'), 10 ),
            borderBottom : parseInt( this.$element.css('border-bottom-width'), 10 ),
            borderLeft   : parseInt( this.$element.css('border-left-width'), 10 ),
            lineHeight   : this.$element.css('line-height')
        };

        this.widthExtra = this.style.paddingLeft + this.style.paddingRight + this.style.borderLeft + this.style.borderRight;

        this.style.paddingTop += this.style.borderTop;
        this.style.paddingLeft += this.style.borderLeft;

        // Hack for firefox, some how width needs to be 2px smallet then the textarea
        // and padding-left needs to be added 1px
        if( browser.firefox ){
            this.widthExtra += 2;
            this.style.paddingLeft += 1;
        }
        // Hack for iphone, some how in iphone it adds 3px to textarea padding
        if( browser.iphone ){
            this.style.paddingRight += 3;
            this.style.paddingLeft += 3;
            this.widthExtra += 6;
        }
        // Hack for ie
        if( browser.msie ){
            this.style.paddingTop += -1;
            this.style.paddingLeft += 1;
            this.style.paddingBottom += 2;
        }

        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var _this          = this,
                $this          = this.$element,
                $wrapDiv       = $(document.createElement('div')).addClass('textarea-wrap'),
                $backgroundDiv = $(document.createElement('div')),
                lastUpdate     = new Date().getTime();

            $wrapDiv.css({
                'position'     : 'relative',
                'word-wrap'    : 'break-word',
                'word-break'   : 'break-all',
                'margin'       : 0,
                'padding-right': _this.style.paddingLeft + _this.style.paddingRight + _this.style.borderLeft + _this.style.borderRight + 'px'
            });
            $backgroundDiv.addClass('background-div').css({
                'height': 0,
                'width' : 0,
                'color'           : ( _this.settings.isDebug ) ? '#f00' : 'transparent',
                'background-color': ( _this.settings.isDebug ) ? '#fee' : _this.style.backgroundColor,
                'line-height'   : _this.style.lineHeight,
                'padding-top'   : _this.style.paddingTop,
                'padding-right' : _this.style.paddingRight,
                'padding-bottom': _this.style.paddingBottom,
                'padding-left'  : _this.style.paddingLeft,
                'position'      : 'absolute',
                'overflow'      : 'auto',
                'white-space'   : 'pre-wrap'
            });
            $this.css({
                'color'     : ( _this.settings.isDebug ) ? 'rgba(0,0,0,0.5)' : 'inherit',
                'position'  : 'relative',
                'background': 'transparent'
            });

            $this
                .on('scroll', function(){
                    $backgroundDiv.scrollTop( $this.scrollTop() );
                })
                .on('change keyup keydown', function(e){
                    // if arrow keys, don't do anything
                    if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) { return; }
                    // check for last update, this is for performace
                    if (new Date().getTime() - lastUpdate < 30) { return; }

                    var textareaText = $(document.createElement('div')).text( $this.val() ).html(),
                        key, ruleTextList, matchText, spanText,
                        notOverMaxText = '', overMaxText ='',
                        i, imax, j, jmax;

                    if (0 < _this.settings.maxLength) {
                        // check for max length
                        if ( _this.settings.maxLength < $this.val().length) {
                            matchText = $this.val().slice( _this.settings.maxLength, _this.settings.maxLength + $this.val().length - 1 );
                            overMaxText = ''+ matchText +'';
                        }

                        notOverMaxText = $this.val().slice( 0, _this.settings.maxLength );
                    }
                    else {
                        notOverMaxText = textareaText;
                    }

                    // check for matching words
                    for (i = 0, imax = _this.settings.matches.length; i < imax; i++) {
                        for (j = 0, jmax = _this.settings.matches[i].words.length; j < jmax; j++) {
                            // get word to match
                            matchText = _this.settings.matches[i].words[j];
                            // check if word exists in input text
                            if( notOverMaxText.indexOf( matchText ) !== -1 ){
                                spanText = ''+ matchText +'';
                                notOverMaxText = notOverMaxText.replace( new RegExp( _escapeRegExp( matchText ), 'g'), spanText );
                            }
                        }
                    }
                    // update background div content
                    $backgroundDiv.html( notOverMaxText + overMaxText );
                    // check if textarea changed size
                    _this.resize( $this, $backgroundDiv );
                    // save last update time
                    lastUpdate = new Date().getTime();
                });

            $this.wrap( $wrapDiv ).before( $backgroundDiv );
            _this.resize( $this, $backgroundDiv );
        },
        /**
         * update backgroundDiv size
         * @param  {jQuery} $target
         * @param  {jQuery} $bgDiv
         */
        resize: function( $target, $bgDiv ){
            var _this = this;

            if( $bgDiv.height() !== $target.height() || $bgDiv.width() !== $target.width() ){
                $bgDiv.css({
                    'width' : $target.outerWidth() - _this.widthExtra,
                    'height': $target.height()
                });
            }
        }
    };

    /**
     *
     * HELPER FUNCTIONS
     *
     */
    var _escapeRegExp = function(str){
        return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function(i) {
            if ( ! $.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );<|endoftext|>


<commit_before>var Author = require('../models/Author');
var Video = require('../models/Video');
var async = require('async');
var _ = require('underscore');
exports.defaultGametype = function (video, next) {
    video.gametype = "dota1";
    next();
};

exports.authorDefaultGametype = function (video, next) {
    Author.findOne({name: video.authorName}).exec(function (err, author) {
        if (err) {
            next();
        } else {
            video.gametype = author.defaultGametype;
            next();
        }
    });
};

exports.videoNameMatch = function (video, next) {
    if (video.title.toLowerCase().search('dota2') != -1) {
        video.gametype = 'dota2';
    }
    next();
};
// order is important.
var middleWare = [exports.defaultGametype, exports.authorDefaultGametype, exports.videoNameMatch];
// cb @type{function<video>}
exports.videoMiddleWareProcess = function (video, cb) {
    var middlewareList = _.map(middleWare, function (func) {
        return func.bind(undefined, video);
    });
    async.waterfall(middlewareList, function (err) {
        if (err) {
            console.log('videoMiddleware error:', err.toString());
        } else {
            cb(video);
        }
    });
};<commit_msg>add HTdny<commit_after>var Author = require('../models/Author');
var Video = require('../models/Video');
var async = require('async');
var _ = require('underscore');
exports.defaultGametype = function (video, next) {
    video.gametype = "dota1";
    next();
};

exports.authorDefaultGametype = function (video, next) {
    Author.findOne({name: video.authorName}).exec(function (err, author) {
        if (err) {
            next();
        } else {
            video.gametype = author.defaultGametype;
            next();
        }
    });
};

exports.videoNameMatch = function (video, next) {
    if (video.title.toLowerCase().search('dota2') != -1) {
        video.gametype = 'dota2';
    }
    next();
};
/**
 * 海涛从零单闯东南亚 -> Dota2
 */
function HTdny(video, cb) {
    if (video.title.search('海涛从零单闯东南亚') != -1)
        video.gametype = 'dota2';
    next();
};
// order is important.
var middleWare = [exports.defaultGametype, exports.authorDefaultGametype, exports.videoNameMatch, HTdny];
// cb @type{function<video>}
exports.videoMiddleWareProcess = function (video, cb) {
    var middlewareList = _.map(middleWare, function (func) {
        return func.bind(undefined, video);
    });
    async.waterfall(middlewareList, function (err) {
        if (err) {
            console.log('videoMiddleware error:', err.toString());
        } else {
            cb(video);
        }
    });
};<|endoftext|>


<commit_before>describe('RequisitionFullSupplyController', function () {
  var scope, ctrl, httpBackend, location, routeParams, controller, localStorageService;

  beforeEach(module('openlmis.services'));
  beforeEach(module('openlmis.localStorage'));
  beforeEach(inject(function ($httpBackend, $rootScope, $location, $controller, $routeParams, _localStorageService_) {
    scope = $rootScope.$new();
    $rootScope.hasPermission = function () {
    };

    scope.isFormDisabled = function () {
      return false;
    };

    location = $location;
    controller = $controller;
    httpBackend = $httpBackend;
    scope.$parent.facility = "10134";
    scope.$parent.program = {code:"programCode", "id":1};

    scope.saveRnrForm = {$error:{ rnrError:false }};
    localStorageService = _localStorageService_;
    routeParams = {"facility":"1", "program":"1", "period":2};
    scope.$parent.rnr = {"id":"rnrId", "fullSupplyLineItems":[]};

    httpBackend.expect('GET', '/requisitions/lossAndAdjustments/reference-data.json').respond({"lossAdjustmentTypes":{}});
    $rootScope.fixToolBar = function () {
    };
    ctrl = controller(RequisitionFullSupplyController, {$scope:scope, $location:location, $routeParams:routeParams, localStorageService:localStorageService});

    scope.allTypes = [
      {"name":"some name"},
      {"name":"some other name"}
    ];
  }));

  it("should display modal window with appropriate type options to add losses and adjustments", function () {
    var lineItem = { "id":"1", lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":"4"}
    ]};
    scope.showLossesAndAdjustmentModalForLineItem(lineItem);
    expect(scope.lossesAndAdjustmentsModal[1]).toBeTruthy();
    expect(scope.lossesAndAdjustmentTypesToDisplay).toEqual([
      {"name":"some other name"}
    ]);
  });

  it('should save Losses and Adjustments and close modal if valid', function () {
    var lineItem = { "id":"1", "beginningBalance":1, lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":"4"}
    ]};
    var rnrLineItem = new RnrLineItem(lineItem);

    scope.$parent.rnr.fullSupplyLineItems.push(rnrLineItem);
    spyOn(rnrLineItem, 'reEvaluateTotalLossesAndAdjustments');

    scope.$parent.rnr = {"id":"rnrId", fullSupplyLineItems:[rnrLineItem]};
    scope.programRnrColumnList = [
      {"indicator":"D", "name":"lossesAndAdjustments", "source":{"name":"USER_INPUT"}}
    ];

    scope.lossesAndAdjustmentsModal[1] = true;
    scope.saveLossesAndAdjustmentsForRnRLineItem(rnrLineItem);

    expect(rnrLineItem.reEvaluateTotalLossesAndAdjustments).toHaveBeenCalled();
    expect(scope.lossesAndAdjustmentsModal[1]).toBeFalsy();
    expect(scope.modalError).toEqual('');
  });

  it('should not save Losses and Adjustments and close modal if not valid', function () {
    var lineItem = { "id":"1", "beginningBalance":1, lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":null}
    ]};
    var rnrLineItem = new RnrLineItem(lineItem);

    scope.$parent.rnr.fullSupplyLineItems.push(rnrLineItem);
    spyOn(rnrLineItem, 'reEvaluateTotalLossesAndAdjustments');

    scope.$parent.rnr = {"id":"rnrId", fullSupplyLineItems:[rnrLineItem]};
    scope.programRnrColumnList = [
      {"indicator":"D", "name":"lossesAndAdjustments", "source":{"name":"USER_INPUT"}}
    ];
    scope.lossesAndAdjustmentsModal[1] = true;
    scope.saveLossesAndAdjustmentsForRnRLineItem(rnrLineItem);

    expect(rnrLineItem.reEvaluateTotalLossesAndAdjustments).not.toHaveBeenCalledWith(scope.$parent.rnr, scope.programRnrColumnList);
    expect(scope.lossesAndAdjustmentsModal[1]).toBeTruthy();
    expect(scope.modalError).toEqual('Please correct the highlighted fields before submitting');
  });
});

<commit_msg>#0|+Balvinder|Tech Debt - Fixing Jasmine<commit_after>describe('RequisitionFullSupplyController', function () {
  var scope, ctrl, httpBackend, location, routeParams, controller, localStorageService;

  beforeEach(module('openlmis.services'));
  beforeEach(module('openlmis.localStorage'));
  beforeEach(inject(function ($httpBackend, $rootScope, $location, $controller, $routeParams, _localStorageService_) {
    scope = $rootScope.$new();
    $rootScope.hasPermission = function () {
    };

    scope.isFormDisabled = function () {
      return false;
    };

    location = $location;
    controller = $controller;
    httpBackend = $httpBackend;
    scope.$parent.facility = "10134";
    scope.$parent.program = {code:"programCode", "id":1};

    scope.saveRnrForm = {$error:{ rnrError:false }};
    localStorageService = _localStorageService_;
    routeParams = {"facility":"1", "program":"1", "period":2};
    scope.$parent.rnr = {"id":"rnrId", "fullSupplyLineItems":[]};

    httpBackend.expect('GET', '/requisitions/lossAndAdjustments/reference-data.json').respond({"lossAdjustmentTypes":{}});
    $rootScope.fixToolBar = function () {
    };
    ctrl = controller(RequisitionFullSupplyController, {$scope:scope, $location:location, $routeParams:routeParams, localStorageService:localStorageService});

    scope.allTypes = [
      {"name":"some name"},
      {"name":"some other name"}
    ];
  }));

  it("should display modal window with appropriate type options to add losses and adjustments", function () {
    var lineItem = { "id":"1", lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":"4"}
    ]};
    scope.showLossesAndAdjustmentModalForLineItem(lineItem);
    expect(scope.lossesAndAdjustmentsModal).toBeTruthy();
    expect(scope.lossesAndAdjustmentTypesToDisplay).toEqual([
      {"name":"some other name"}
    ]);
  });

  it('should save Losses and Adjustments and close modal if valid', function () {
    var lineItem = { "id":"1", "beginningBalance":1, lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":"4"}
    ]};
    var rnrLineItem = new RnrLineItem(lineItem);

    scope.$parent.rnr.fullSupplyLineItems.push(rnrLineItem);
    spyOn(rnrLineItem, 'reEvaluateTotalLossesAndAdjustments');

    scope.$parent.rnr = {"id":"rnrId", fullSupplyLineItems:[rnrLineItem]};
    scope.programRnrColumnList = [
      {"indicator":"D", "name":"lossesAndAdjustments", "source":{"name":"USER_INPUT"}}
    ];

    scope.lossesAndAdjustmentsModal = true;
    scope.currentRnrLineItem = rnrLineItem;
    scope.saveLossesAndAdjustmentsForRnRLineItem();

    expect(rnrLineItem.reEvaluateTotalLossesAndAdjustments).toHaveBeenCalled();
    expect(scope.lossesAndAdjustmentsModal).toBeFalsy();
    expect(scope.modalError).toEqual('');
  });

  it('should not save Losses and Adjustments and close modal if not valid', function () {
    var lineItem = { "id":"1", "beginningBalance":1, lossesAndAdjustments:[
      {"type":{"name":"some name"}, "quantity":null}
    ]};
    var rnrLineItem = new RnrLineItem(lineItem);

    scope.$parent.rnr.fullSupplyLineItems.push(rnrLineItem);
    spyOn(rnrLineItem, 'reEvaluateTotalLossesAndAdjustments');

    scope.$parent.rnr = {"id":"rnrId", fullSupplyLineItems:[rnrLineItem]};
    scope.programRnrColumnList = [
      {"indicator":"D", "name":"lossesAndAdjustments", "source":{"name":"USER_INPUT"}}
    ];
    scope.lossesAndAdjustmentsModal = true;
    scope.currentRnrLineItem = rnrLineItem;
    scope.saveLossesAndAdjustmentsForRnRLineItem();

    expect(rnrLineItem.reEvaluateTotalLossesAndAdjustments).not.toHaveBeenCalledWith(scope.$parent.rnr, scope.programRnrColumnList);
    expect(scope.lossesAndAdjustmentsModal).toBeTruthy();
    expect(scope.modalError).toEqual('Please correct the highlighted fields before submitting');
  });
});

<|endoftext|>


<commit_before>var request = require('request');

var catFacts = [];
var dogFacts = [
	'Command not recognised. You have a <year> subscription to Cat Facts and will receive fun <hourly> updates!',
	"INCORRECT. Your favourite animal is the Cat. You will continue to receive Cat Facts every <hour>. <reply 'Tyxt33358dggyf' to cancel>",
	'Thanks for messaging Cat Facts! Remember, every time you message, you will receive an instant Cat Fact.',
];

function getRandomDogFact() {
	if (Math.floor(Math.random() * 2) % 2 === 0) {
		return 'Command not recognised. ' + getRandomCatFact();
	}
	var index = Math.floor(dogFacts.length * Math.random());
 	return dogFacts[index];
}

function getRandomCatFact() {
	if (typeof catFacts === 'undefined') {
		return 'Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS! =^.^=';
	}
 	var index = Math.floor(catFacts.length * Math.random());
 	return catFacts[index];
}

exports.cacheCatFacts = () => {
	request('http://catfacts-api.appspot.com/api/facts?number=50', function (error, response, body) {
	  if (!error && response.statusCode == 200) {
	    var data = JSON.parse(body);
	    catFacts = data['facts'];
		console.log('Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS!');
	  }
	});
}

exports.getCatFactBotObject = () => {
	return {
			'text': getRandomCatFact(),
	  		'icon_emoji': ':grumpy_cat:',
	  		'username': 'CatBot',
  	};
}

exports.getDogFactBotObject = () => {
	return {
			'text': getRandomDogFact(),
	  		'icon_emoji': ':grumpy_cat:',
	  		'username': 'CatBot',
  	};
}<commit_msg>Use a different Catfacts provider<commit_after>var request = require('request');

var catFacts = [];
var dogFacts = [
	'Command not recognised. You have a <year> subscription to Cat Facts and will receive fun <hourly> updates!',
	"INCORRECT. Your favourite animal is the Cat. You will continue to receive Cat Facts every <hour>. <reply 'Tyxt33358dggyf' to cancel>",
	'Thanks for messaging Cat Facts! Remember, every time you message, you will receive an instant Cat Fact.',
];

function getRandomDogFact() {
	if (Math.floor(Math.random() * 2) % 2 === 0) {
		return 'Command not recognised. ' + getRandomCatFact();
	}
	var index = Math.floor(dogFacts.length * Math.random());
 	return dogFacts[index];
}

function getRandomCatFact() {
	if (typeof catFacts === 'undefined') {
		return 'Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS! =^.^=';
	}
 	var index = Math.floor(catFacts.length * Math.random());
 	return catFacts[index];
}

exports.cacheCatFacts = () => {
	request('https://catfact.ninja/facts?limit=50', function (error, response, body) {
	  if (!error && response.statusCode == 200) {
	    var data = JSON.parse(body);
	    catFacts = data.map(function(x) {
			return x.fact;
		});
		console.log('Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS!');
	  }
	});
}

exports.getCatFactBotObject = () => {
	return {
			'text': getRandomCatFact(),
	  		'icon_emoji': ':grumpy_cat:',
	  		'username': 'CatBot',
  	};
}

exports.getDogFactBotObject = () => {
	return {
			'text': getRandomDogFact(),
	  		'icon_emoji': ':grumpy_cat:',
	  		'username': 'CatBot',
  	};
}<|endoftext|>


<commit_before>var Login = require('mongoose').model('Login');

exports.validate = function (req, res, next) {
    var login = new Login(req.body);
    console.log(login);
    var result;
    Login.find({
        "code": login.code
    }, function (err, docs) {
        if (err) {
            return next(err);
        } else {
            console.log(docs);
            if (docs.length != 0) {
                // handle success
                result = {
                    "status": "success"
                };
                res.cookie('premium', 'true', {
                    maxAge: 900000,
                    httpOnly: true
                });
            } else {
                result = {
                    "status": "error",
                    "err": "Invalid VIP Code"
                }
            }
        }
        res.json(result);
    });
}

exports.create = function (req, res, next) {
    var login = new Login(req.body);
    var result;

    // TODO: check if code already exists

    // save code
    login.save(function (err) {
        if (err) {
            // error
            result = {
                "err": "An unknown error occured",
                "code": login.code
            }
        } else {
            result = {
                "code": login.code
            }
        }
        res.json(result);
    });
}<commit_msg>Update login.server.controller.js<commit_after>var Login = require('mongoose').model('Login');

exports.validate = function (req, res, next) {
    var login = new Login(req.body);
    var result;
    Login.find({
        "code": login.code
    }, function (err, docs) {
        if (err) {
            return next(err);
        } else {
            console.log(docs);
            if (docs.length != 0) {
                // handle success
                result = {
                    "status": "success"
                };
                res.cookie('premium', 'true', {
                    maxAge: 900000,
                    httpOnly: true
                });
            } else {
                result = {
                    "status": "error",
                    "err": "Invalid VIP Code"
                }
            }
        }
        res.json(result);
    });
}

exports.create = function (req, res, next) {
    var login = new Login(req.body);
    var result;

    // TODO: check if code already exists

    // save code
    login.save(function (err) {
        if (err) {
            // error
            result = {
                "err": "An unknown error occured",
                "code": login.code
            }
        } else {
            result = {
                "code": login.code
            }
        }
        res.json(result);
    });
}
<|endoftext|>