<commit_before>$(document).ready(function () {
    if($('pre').length){
      string=$('pre').text().trim()
      if(string.indexOf('{')==0)
        json = JSON.parse(string)
      else
        json=null
      if(json){
        var pre = ''
        $('body').append('

')
        exports = {};
        exports.beautifyJson = beautifyJson = (function () {
            var textcss = function ( /* [class, text]+ */ ) {
                var spans = [];
                while (arguments.length)
                    spans.push(append(span(Array.prototype.shift.call(arguments)),
                        text(Array.prototype.shift.call(arguments))));
                return spans;
            };
            var append = function ( /* el, ... */ ) {
                var el = Array.prototype.shift.call(arguments);
                for (var a = 0; a < arguments.length; a++)
                    if (arguments[a].constructor == Array){
                        append.apply(this, [el].concat(arguments[a]));
                    }else{
                        if($(arguments[a]).text().replace(/\"/g,'').indexOf('http')==0){
                          $(arguments[a]).html(''+$(arguments[a]).text()+'')
                        }
                          el.appendChild(arguments[a]);
                    }
                return el;
            };
            var prepend = function (el, child) {
                el.insertBefore(child, el.firstChild);
                return el;
            }
            var isempty = function (obj) {
                for (var k in obj)
                    if (obj.hasOwnProperty(k)) return false;
                return true;
            }
            var text = function (txt) {
                  return document.createTextNode(txt)
            };
            var div = function () {
                return document.createElement("div")
            };
            var span = function (classname) {
                var s = document.createElement("span");
                if (classname) s.className = classname;
                return s;
            };
            var A = function A(txt, classname, callback) {
                var a = document.createElement("a");
                if (classname) a.className = classname;
                a.appendChild(text(txt));
                a.href = '#';
                a.onclick = function () {
                    callback();
                    return false;
                };
                return a;
            };

            function _beautifyJson(json, indent, dont_indent, show_level) {
                var my_indent = dont_indent ? "" : indent;

                if (json === null) return textcss(null, my_indent, "keyword", "null");
                if (json === void 0) return textcss(null, my_indent, "keyword", "undefined");
                if (typeof (json) != "object") // Strings, numbers and bools
                    return textcss(null, my_indent, typeof (json), JSON.stringify(json));

                var expandableSection = function (open, close, type, builder) {
                    var content;
                    var empty = span(type);
                    var show = function () {
                        if (!content) append(empty.parentNode,
                            content = prepend(builder(),
                                A(beautifyJson.hide, "expandableSection",
                                    function () {
                                        content.style.display = "none";
                                        empty.style.display = "inline";
                                    })));
                        content.style.display = "inline";
                        empty.style.display = "none";
                    };
                    append(empty,
                        A(beautifyJson.show, "expandableSection", show),
                        textcss(type + " separator", open),
                        A("..", null, show),
                        textcss(type + " separator", close));
                    var el = append(span(), text(my_indent.slice(0, -1)), empty);
                    if (show_level > 0)
                        show();
                    return el;
                };

                if (json.constructor == Array) {
                    if (json.length == 0) return textcss(null, my_indent, "array separator", "[]");

                    return expandableSection("[", "]", "array", function () {
                        var as = append(span("array"), textcss("array separator", "[", null, "\n"));
                        for (var i = 0; i < json.length; i++)
                            append(as,
                                _beautifyJson(json[i], indent + "    ", false, show_level - 1),
                                i != json.length - 1 ? textcss("separator", ",") : [],
                                text("\n"));
                        append(as, textcss(null, indent, "array separator", "]"));
                        return as;
                    });
                }

                // object
                if (isempty(json))
                    return textcss(null, my_indent, "object separator", "{}");

                return expandableSection("{", "}", "object", function () {
                    var os = append(span("object"), textcss("object separator", "{", null, "\n"));
                    for (var k in json) var last = k;
                    for (var k in json)
                        append(os, textcss(null, indent + "    ", "key", '"' + k + '"', "object separator", ': '),
                            _beautifyJson(json[k], indent + "    ", true, show_level - 1),
                            k != last ? textcss("separator", ",") : [],
                            text("\n"));
                    append(os, textcss(null, indent, "object separator", "}"));
                    return os;
                });
            }

            var beautifyJson = function beautifyJson(json) {
                pre = append(document.createElement("pre"), _beautifyJson(json, "", false, beautifyJson.show_to_level));
                pre.className = "beautifyJson";
                return pre;
            }
            beautifyJson.set_icons = function (show, hide) {
                beautifyJson.show = show;
                beautifyJson.hide = hide;
                return beautifyJson;
            };
            beautifyJson.set_show_to_level = function (level) {
                beautifyJson.show_to_level = typeof level == "string" &&
                    level.toLowerCase() === "all" ? Number.MAX_VALUE : level;
                return beautifyJson;
            };
            // Backwards compatiblity. Use set_show_to_level() for new code.
            beautifyJson.set_show_by_default = function (show) {
                beautifyJson.show_to_level = show ? Number.MAX_VALUE : 0;
                return beautifyJson;
            };
            beautifyJson.set_icons('+', '-');
            beautifyJson.set_show_by_default(true);
            return beautifyJson;
        })();
        beautifyJson(json)
        $('pre').attr('class', 'no-display')
        $("#beautified").html(pre);
        $('body').append('
View Source
')
        $('body').append('
View Beautified
')
        $('body').attr('class','jsbBody')

        $('.source').bind('click', function () {
            $('pre').attr('class', '')
            $('.beautified').attr('class', 'beautified no-display')
            $('.view-beautified').attr('class', 'view-beautified')
            $('.source').attr('class', 'source no-display')
        })
        $('.view-beautified').bind('click', function () {
            $('pre').attr('class', 'no-display')
            $('.beautified').attr('class', 'beautified')
            $('.beautified').children('pre').attr('class', '')
            $('.view-beautified').attr('class', 'view-beautified no-display')
            $('.source').attr('class', 'source')
        })
      }
    }
});<commit_msg>credits added<commit_after>//credits : https://github.com/caldwell/

$(document).ready(function () {
    if($('pre').length){
      string=$('pre').text().trim()
      if(string.indexOf('{')==0)
        json = JSON.parse(string)
      else
        json=null
      if(json){
        var pre = ''
        $('body').append('

')
        exports = {};
        exports.beautifyJson = beautifyJson = (function () {
            var textcss = function ( /* [class, text]+ */ ) {
                var spans = [];
                while (arguments.length)
                    spans.push(append(span(Array.prototype.shift.call(arguments)),
                        text(Array.prototype.shift.call(arguments))));
                return spans;
            };
            var append = function ( /* el, ... */ ) {
                var el = Array.prototype.shift.call(arguments);
                for (var a = 0; a < arguments.length; a++)
                    if (arguments[a].constructor == Array){
                        append.apply(this, [el].concat(arguments[a]));
                    }else{
                        if($(arguments[a]).text().replace(/\"/g,'').indexOf('http')==0){
                          $(arguments[a]).html(''+$(arguments[a]).text()+'')
                        }
                          el.appendChild(arguments[a]);
                    }
                return el;
            };
            var prepend = function (el, child) {
                el.insertBefore(child, el.firstChild);
                return el;
            }
            var isempty = function (obj) {
                for (var k in obj)
                    if (obj.hasOwnProperty(k)) return false;
                return true;
            }
            var text = function (txt) {
                  return document.createTextNode(txt)
            };
            var div = function () {
                return document.createElement("div")
            };
            var span = function (classname) {
                var s = document.createElement("span");
                if (classname) s.className = classname;
                return s;
            };
            var A = function A(txt, classname, callback) {
                var a = document.createElement("a");
                if (classname) a.className = classname;
                a.appendChild(text(txt));
                a.href = '#';
                a.onclick = function () {
                    callback();
                    return false;
                };
                return a;
            };

            function _beautifyJson(json, indent, dont_indent, show_level) {
                var my_indent = dont_indent ? "" : indent;

                if (json === null) return textcss(null, my_indent, "keyword", "null");
                if (json === void 0) return textcss(null, my_indent, "keyword", "undefined");
                if (typeof (json) != "object") // Strings, numbers and bools
                    return textcss(null, my_indent, typeof (json), JSON.stringify(json));

                var expandableSection = function (open, close, type, builder) {
                    var content;
                    var empty = span(type);
                    var show = function () {
                        if (!content) append(empty.parentNode,
                            content = prepend(builder(),
                                A(beautifyJson.hide, "expandableSection",
                                    function () {
                                        content.style.display = "none";
                                        empty.style.display = "inline";
                                    })));
                        content.style.display = "inline";
                        empty.style.display = "none";
                    };
                    append(empty,
                        A(beautifyJson.show, "expandableSection", show),
                        textcss(type + " separator", open),
                        A("..", null, show),
                        textcss(type + " separator", close));
                    var el = append(span(), text(my_indent.slice(0, -1)), empty);
                    if (show_level > 0)
                        show();
                    return el;
                };

                if (json.constructor == Array) {
                    if (json.length == 0) return textcss(null, my_indent, "array separator", "[]");

                    return expandableSection("[", "]", "array", function () {
                        var as = append(span("array"), textcss("array separator", "[", null, "\n"));
                        for (var i = 0; i < json.length; i++)
                            append(as,
                                _beautifyJson(json[i], indent + "    ", false, show_level - 1),
                                i != json.length - 1 ? textcss("separator", ",") : [],
                                text("\n"));
                        append(as, textcss(null, indent, "array separator", "]"));
                        return as;
                    });
                }

                // object
                if (isempty(json))
                    return textcss(null, my_indent, "object separator", "{}");

                return expandableSection("{", "}", "object", function () {
                    var os = append(span("object"), textcss("object separator", "{", null, "\n"));
                    for (var k in json) var last = k;
                    for (var k in json)
                        append(os, textcss(null, indent + "    ", "key", '"' + k + '"', "object separator", ': '),
                            _beautifyJson(json[k], indent + "    ", true, show_level - 1),
                            k != last ? textcss("separator", ",") : [],
                            text("\n"));
                    append(os, textcss(null, indent, "object separator", "}"));
                    return os;
                });
            }

            var beautifyJson = function beautifyJson(json) {
                pre = append(document.createElement("pre"), _beautifyJson(json, "", false, beautifyJson.show_to_level));
                pre.className = "beautifyJson";
                return pre;
            }
            beautifyJson.set_icons = function (show, hide) {
                beautifyJson.show = show;
                beautifyJson.hide = hide;
                return beautifyJson;
            };
            beautifyJson.set_show_to_level = function (level) {
                beautifyJson.show_to_level = typeof level == "string" &&
                    level.toLowerCase() === "all" ? Number.MAX_VALUE : level;
                return beautifyJson;
            };
            // Backwards compatiblity. Use set_show_to_level() for new code.
            beautifyJson.set_show_by_default = function (show) {
                beautifyJson.show_to_level = show ? Number.MAX_VALUE : 0;
                return beautifyJson;
            };
            beautifyJson.set_icons('+', '-');
            beautifyJson.set_show_by_default(true);
            return beautifyJson;
        })();
        beautifyJson(json)
        $('pre').attr('class', 'no-display')
        $("#beautified").html(pre);
        $('body').append('
View Source
')
        $('body').append('
View Beautified
')
        $('body').attr('class','jsbBody')

        $('.source').bind('click', function () {
            $('pre').attr('class', '')
            $('.beautified').attr('class', 'beautified no-display')
            $('.view-beautified').attr('class', 'view-beautified')
            $('.source').attr('class', 'source no-display')
        })
        $('.view-beautified').bind('click', function () {
            $('pre').attr('class', 'no-display')
            $('.beautified').attr('class', 'beautified')
            $('.beautified').children('pre').attr('class', '')
            $('.view-beautified').attr('class', 'view-beautified no-display')
            $('.source').attr('class', 'source')
        })
      }
    }
});<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: UndoManager.js                                                       \\
// Module: DataStore                                                          \\
// Requires: Core, Foundation                                                 \\
// Author: Neil Jenkins                                                       \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed.                       \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

/**
    Class: O.UndoManager
*/

var UndoManager = NS.Class({

    Extends: NS.Object,

    init: function ( mixin ) {
        this._undoStack = [];
        this._redoStack = [];

        this._isInUndoState = false;

        this.canUndo = false;
        this.canRedo = false;

        this.maxUndoCount = 1;

        UndoManager.parent.init.call( this, mixin );
    },

    _pushState: function ( stack, data ) {
        stack.push( data );
        while ( stack.length > this.maxUndoCount ) {
            stack.shift();
        }
        this._isInUndoState = true;
    },

    dataDidChange: function () {
        this._isInUndoState = false;
        this._redoStack.length = 0;
        this.set( 'canRedo', false )
            .set( 'canUndo', true )
            .fire( 'input' );
        return this;
    },

    saveUndoCheckpoint: function () {
        if ( !this._isInUndoState ) {
            var data = this.getUndoData();
            if ( data !== null ) {
                this._pushState( this._undoStack, data );
            } else {
                this._isInUndoState = true;
                this.set( 'canUndo', !!this._undoStack.length );
            }
        }
        return this;
    },

    undo: function () {
        if ( this.get( 'canUndo' ) ) {
            if ( !this._isInUndoState ) {
                this.saveUndoCheckpoint();
                this.undo();
            } else {
                this._pushState( this._redoStack,
                    this.applyChange( this._undoStack.pop(), false )
                );
                this.set( 'canUndo', !!this._undoStack.length )
                    .set( 'canRedo', true )
                    .fire( 'undo' );
            }
        }
        return this;
    },

    redo: function () {
        if ( this.get( 'canRedo' ) ) {
            this._pushState( this._undoStack,
                this.applyChange( this._redoStack.pop(), true )
            );
            this.set( 'canUndo', true )
                .set( 'canRedo', !!this._redoStack.length )
                .fire( 'redo' );
        }
        return this;
    },

    getUndoData: function () {},

    applyChange: function (/* data, isRedo */) {}
});

var StoreUndoManager = NS.Class({

    Extends: UndoManager,

    init: function ( mixin ) {
        var store = mixin.store;
        store.on( 'willCommit', this, 'saveUndoCheckpoint' )
             .on( 'record:user:create', this, 'dataDidChange' )
             .on( 'record:user:update', this, 'dataDidChange' )
             .on( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.init.call( this, mixin );
    },

    destroy: function () {
        this.store.off( 'willCommit', this, 'saveUndoCheckpoint' )
                  .off( 'record:user:create', this, 'dataDidChange' )
                  .off( 'record:user:update', this, 'dataDidChange' )
                  .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    getUndoData: function () {
        var store = this.store;
        return store.hasChanges() ? store.getInverseChanges() : null;
    },

    applyChange: function ( data ) {
        var store = this.store,
            inverse;
        store.applyChanges( data );
        inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    }
});

NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;

}( O ) );
<commit_msg>Don't allow undo from store in uncommitted state.<commit_after>// -------------------------------------------------------------------------- \\
// File: UndoManager.js                                                       \\
// Module: DataStore                                                          \\
// Requires: Core, Foundation                                                 \\
// Author: Neil Jenkins                                                       \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed.                       \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

/**
    Class: O.UndoManager
*/

var UndoManager = NS.Class({

    Extends: NS.Object,

    init: function ( mixin ) {
        this._undoStack = [];
        this._redoStack = [];

        this._isInUndoState = false;

        this.canUndo = false;
        this.canRedo = false;

        this.maxUndoCount = 1;

        UndoManager.parent.init.call( this, mixin );
    },

    _pushState: function ( stack, data ) {
        stack.push( data );
        while ( stack.length > this.maxUndoCount ) {
            stack.shift();
        }
        this._isInUndoState = true;
    },

    dataDidChange: function () {
        this._isInUndoState = false;
        this._redoStack.length = 0;
        this.set( 'canRedo', false )
            .set( 'canUndo', true )
            .fire( 'input' );
        return this;
    },

    saveUndoCheckpoint: function () {
        if ( !this._isInUndoState ) {
            var data = this.getUndoData();
            if ( data !== null ) {
                this._pushState( this._undoStack, data );
            } else {
                this._isInUndoState = true;
                this.set( 'canUndo', !!this._undoStack.length );
            }
        }
        return this;
    },

    undo: function () {
        if ( this.get( 'canUndo' ) ) {
            if ( !this._isInUndoState ) {
                this.saveUndoCheckpoint();
                this.undo();
            } else {
                this._pushState( this._redoStack,
                    this.applyChange( this._undoStack.pop(), false )
                );
                this.set( 'canUndo', !!this._undoStack.length )
                    .set( 'canRedo', true )
                    .fire( 'undo' );
            }
        }
        return this;
    },

    redo: function () {
        if ( this.get( 'canRedo' ) ) {
            this._pushState( this._undoStack,
                this.applyChange( this._redoStack.pop(), true )
            );
            this.set( 'canUndo', true )
                .set( 'canRedo', !!this._redoStack.length )
                .fire( 'redo' );
        }
        return this;
    },

    getUndoData: function () {},

    applyChange: function (/* data, isRedo */) {}
});

var StoreUndoManager = NS.Class({

    Extends: UndoManager,

    init: function ( mixin ) {
        StoreUndoManager.parent.init.call( this, mixin );
        this.get( 'store' )
            .on( 'willCommit', this, 'saveUndoCheckpoint' )
            .on( 'record:user:create', this, 'dataDidChange' )
            .on( 'record:user:update', this, 'dataDidChange' )
            .on( 'record:user:destroy', this, 'dataDidChange' );
    },

    destroy: function () {
        this.get( 'store' )
            .off( 'willCommit', this, 'saveUndoCheckpoint' )
            .off( 'record:user:create', this, 'dataDidChange' )
            .off( 'record:user:update', this, 'dataDidChange' )
            .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    getUndoData: function () {
        var store = this.get( 'store' );
        return store.hasChanges() ? store.getInverseChanges() : null;
    },

    applyChange: function ( data ) {
        var store = this.get( 'store' ),
            inverse;
        store.applyChanges( data );
        inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    },

    undo: function () {
        if ( this._isInUndoState || !this.get( 'store' ).hasChanges() ) {
            StoreUndoManager.parent.undo.call( this );
        }
        return this;
    }
});

NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;

}( O ) );
<|endoftext|>


<commit_before>var fw = require('knockout/build/output/knockout-latest');
var _ = require('lodash');

var util = require('../../../misc/util');
var isAmdResolved = util.isAmdResolved;
var isPath = util.isPath;

var bindingElement = require('../../../binding/binding-element');
var getLoadingTracker = require('../../../misc/loading-tracker').get;

function outletViewModel() {
  fw.outlet.boot(this);
}

/**
 * This outlet loader has two functions:
 * 1. provides the outlet template used to programmatically control display/output of its area via the component: binding
 * 2. provides the outlet viewModel to bind against and control an outlets display
 */
fw.components.loaders.unshift(fw.components.outletLoader = {
  getConfig: function (componentName, callback) {
    if (componentName === 'outlet') {
      callback({
        viewModel: { createViewModel: outletViewModel },
        template: bindingElement.open.prefix + '$lifecycle, $outlet' + bindingElement.open.postfix +
          '
' +
            '' +
          '
' +
          '
' +
            '' +
          '
' +
        bindingElement.close

      });
    } else {
      callback(null);
    }
  }
});
<commit_msg>simplified outlet template<commit_after>var fw = require('knockout/build/output/knockout-latest');
var _ = require('lodash');

var util = require('../../../misc/util');
var isAmdResolved = util.isAmdResolved;
var isPath = util.isPath;

var bindingElement = require('../../../binding/binding-element');
var getLoadingTracker = require('../../../misc/loading-tracker').get;

function Outlet() {
  fw.outlet.boot(this);
}

/**
 * This outlet loader has two functions:
 * 1. provides the outlet template used to programmatically control display/output of its area via the component: binding
 * 2. provides the outlet viewModel to bind against and control an outlets display
 */
fw.components.loaders.unshift(fw.components.outletLoader = {
  getConfig: function (componentName, callback) {
    if (componentName === 'outlet') {
      callback({
        viewModel: { createViewModel: Outlet },
        template: bindingElement.open.prefix + '$lifecycle, $outlet' + bindingElement.open.postfix +
          '

' +
          '

' +
        bindingElement.close

      });
    } else {
      callback(null);
    }
  }
});
<|endoftext|>


<commit_before>// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

/**
 * The root the martinCostello namespace.
 */
martinCostello = {
};
<commit_msg>Be fancy<commit_after>// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

/**
 * The root the martinCostello namespace.
 */
martinCostello = {
};

(function () {
    console.log("%cDownload the London Travel Alexa skill from Amazon: https://www.amazon.co.uk/dp/B01NB0T86R", "color: #2c3e50;");
}());
<|endoftext|>


<commit_before>/**
 * {{User}} manager function.
 *
 * require jQuery, datatable, toaster
 */
function TableManager(options) {
    this.options = $.extend(true, {
        restApi : window.location.href,
        csrfToken : null,
        datatableApi : null,
        entity : null,
        dom : null,
        columnDefs : [],
        renderIdAsButton: true, //id should be placed at last cols
        buttonColumnWidth : '150px',
        buttonRenderer : null,
        immediateInit : true,
        on : {},
    }, options);

    if (!this.options.entity) {
        throw new Error('Entity name not defined!');
    }

    this.snakeCasedEntity = this.options.entity.replace(/-/g, '_');
    this.kebabCasedEntity = this.options.entity.replace(/_/g, '-');
    this.baseTable      = $('#' + this.snakeCasedEntity + '_table');
    this.datatable      = null;
    this.event          = this.initEventDispatcher();
    this.options.dom    = this.options.dom || "<'row'<'col-md-12'<'box box-primary'<'box-header with-border'<'row'<'col-md-6'<'#" + this.snakeCasedEntity + "_button_wrapper'>><'col-md-3 hidden-xs'l><'col-md-3 hidden-xs'f>>> <'box-body no-padding'tr><'box-footer clearfix'<'col-sm-5'i><'col-sm-7'p>>>>>";

    if (window.toastr) {
        this.notifier   = toastr;
    } else {
        this.notifier   = {
            success : alert,
            error   : alert,
            warning : alert,
            info    : alert
        }
    }
    for (var ev in this.options.on) {
        this.event.listen(ev, this.options.on[ev]);
    }

    if (this.options.immediateInit) {
        this.init();
    }
}

TableManager.fn = TableManager.prototype;

TableManager.fn.init = function() {
    var self = this;

    this.event.dispatch('before_init');

    if (this.options.renderIdAsButton) {
        var renderer = this.options.buttonRenderer ? this.options.buttonRenderer : function (data, type, row, meta) {
            var button = '<button href="#' + self.kebabCasedEntity + '-edit" class="btn btn-xs btn-default btn-' + self.kebabCasedEntity + '-edit" data-id="' + data + '"> edit</button>';
                button += '<button href="#' + self.kebabCasedEntity + '-delete" class="btn btn-xs btn-danger btn-' + self.kebabCasedEntity + '-delete" data-id="' + data + '" style="margin-left: 5px"> delete</button>';

            return button;
        };

        this.options.columnDefs.push({
            targets     : -1,
            className   : 'text-center',
            orderable   : false,
            data        : 'id',
            searchable  : false,
            width       : this.options.buttonColumnWidth,
            render      : renderer
        });
    }

    $(document).ready(function(){
        self.event.dispatch('table.before_init', {table : self.baseTable});

        self.initDatatable()
        self.baseTable.on('click', '.btn-' + self.kebabCasedEntity + '-edit', function(e){
            e.preventDefault();

            var button = $(this).prop('disabled', true);
            var entityId = button.attr('data-id');

            button.find('i').attr('class', 'fa fa-fw fa-spin fa-spinner');

            self.edit(entityId).always(function() {
                button.prop('disabled', false).html(' edit');
            });
        });

        self.baseTable.on('click', '.btn-' + self.kebabCasedEntity + '-delete', function(e){
            e.preventDefault();

            if(confirm('Are you sure want to delete this ' + self.snakeCasedEntity.replace(/_/g, ' ') + '?')){
                var button = $(this).prop('disabled', true);
                var entityId = button.attr('data-id');

                button.find('i').attr('class', 'fa fa-fw fa-spin fa-spinner');

                self.delete(entityId).always(function() {
                    button.prop('disabled', false).html(' delete');
                });
            }
        });

        $('#btn_' + self.snakeCasedEntity + '_save').click(function(e) {
            e.preventDefault();

            var button      = $(this).prop('disabled', true).text('saving...');
            var entityData  = $('#' + self.snakeCasedEntity + '_form').serializeJSON();
            var method      = $('#' + self.snakeCasedEntity + '_method_field').val();
            var enableBtn   = function() {
                button.prop('disabled', false).text('save');
            }

            if (method == 'PUT') {
                self.update(entityData[self.snakeCasedEntity + '_data']).always(enableBtn);
            } else {
                self.store(entityData[self.snakeCasedEntity + '_data']).always(enableBtn);
            }
        });

        $('#btn_' + self.snakeCasedEntity + '_create').appendTo('#' + self.snakeCasedEntity + '_button_wrapper').click(function(e){
            e.preventDefault();
            self.create();
        });

        self.event.dispatch('table.after_init', {table: self.baseTable});
    });

    this.notifier.options = {
        "closeButton": true,
        "newestOnTop": true,
        "positionClass": "toast-top-right",
    }

    this.event.dispatch('after_init');
}

TableManager.fn.initEventDispatcher = function() {
    var self = this;
    /**
     * @author mrdoob / http://mrdoob.com/
     */

    function EventDispatcher() {}

    Object.assign(EventDispatcher.prototype, {
        listen: function (type, listener) {
            if (this._listeners === undefined) this._listeners = {};

            var listeners = this._listeners;
            if (listeners[type] === undefined) {
                listeners[type] = [];
            }

            if (listeners[type].indexOf(listener) === - 1) {
                listeners[type].push(listener);
            }
        },

        hasListener: function (type, listener) {
            if (this._listeners === undefined) return false;

            return this._listeners[type] !== undefined && this._listeners[type].indexOf(listener) !== - 1;
        },

        removeListener: function (type, listener) {
            if (this._listeners === undefined) return;

            var listenerArray = this._listeners[type];

            if (listenerArray !== undefined) {
                var index = listenerArray.indexOf(listener);

                if (index !== - 1) {
                    listenerArray.splice(index, 1);
                }
            }
        },

        dispatch: function (eventName, eventData) {
            if (this._listeners === undefined) return;

            eventData = eventData || {};
            var listeners = this._listeners[eventName];

            if (listeners !== undefined) {
                eventData.target = self;

                var listeners = listeners.slice(0);
                for (var i = 0, l = listeners.length; i < l; i ++) {
                    listeners[i].call(this, eventData);
                }
            }
        }
    });

    return new EventDispatcher();
}

TableManager.fn.reload = function() {
    this.datatable.ajax.reload(null, false);
}

/**
 * Fetch entity data from the server
 */
TableManager.fn.fetch = function(entityId) {
    return $.ajax({
        'method' : 'GET',
        'url' : this.options.restApi + entityId
    });
}

/**
 * Display edit form
 */
TableManager.fn.edit = function(entityId) {
    var self = this;

    return this.fetch(entityId)
        .done(function(data, status, xhr) {
            self.event.dispatch('edit_form.before_shown', {entity : data});

            $('#' + self.snakeCasedEntity + '_form')[0].reset();

            var elem;
            for(var a in data){
                elem = $('#' + self.snakeCasedEntity + '_'+a+'_field');
                elem.val(data[a]);
            }

            $('#' + self.snakeCasedEntity + '_form_title').text('Edit ' + self.snakeCasedEntity.replace(/_/g, ' '));
            $('#' + self.snakeCasedEntity + '_method_field').val('PUT');
            $('#' + self.snakeCasedEntity + '_token_field').val(self.options.csrfToken);
            $('#' + self.snakeCasedEntity + '_form_modal').modal('show');

            self.event.dispatch('edit_form.after_shown');
        })
        .fail(function(xhr, status, error) {
            self.showErrorResponse(xhr);
        });
}

/**
 * Send entity data to server for update
 */
TableManager.fn.update = function(entity) {
    var self = this;

    entity._token   = this.options.csrfToken;
    fieldGroup      = self.snakeCasedEntity + '_data';
    entityData      = {};

    entityData[fieldGroup] = entity;

    return $.ajax({
        method  : 'PUT',
        url     : self.options.restApi + entity.id,
        data    : entityData
    }).done(function(data, status, xhr){
        self.notifier.success(data.content);

        $('#btn_' + self.snakeCasedEntity + '_save').prop('disabled', false).text('save');
        $('#' + self.snakeCasedEntity + '_form_modal').modal('hide');
        self.reload();
    }).fail(function(hxr, status, error){
        $('#btn_' + self.snakeCasedEntity + '_save').prop('disabled', false).text('save');
        self.showErrorResponse(hxr);
    });
}

/**
 * Delete entity data from server
 */
TableManager.fn.delete = function(entityId) {
    var self = this;

    return $.ajax({
        method  : 'DELETE',
        data    : {_token : self.options.csrfToken},
        url     : self.options.restApi + entityId
    }).done(function(data, status, xhr){
        self.notifier.success(data.content);
        self.reload();
    }).fail(function(xhr, status, error){
        self.showErrorResponse(xhr);
    });
}

/**
 * Display create form
 */
TableManager.fn.create = function() {
    this.event.dispatch('create_form.before_shown');

    $('#' + this.snakeCasedEntity + '_form_title').text('Create new ' + this.snakeCasedEntity.replace(/_/g, ' '));
    $('#' + this.snakeCasedEntity + '_form')[0].reset();

    $('#' + this.snakeCasedEntity + '_method_field').val('POST');
    $('#' + this.snakeCasedEntity + '_token_field').val(this.options.csrfToken);
    $('#' + this.snakeCasedEntity + '_id_field').val('');

    $('#' + this.snakeCasedEntity + '_form_modal').modal('show');

    this.event.dispatch('create_form.after_shown');
}

/**
 * Send data to server for create
 */
TableManager.fn.store = function(entity) {
    var self = this;

    entity._token   = this.options.csrfToken;
    fieldGroup      = self.snakeCasedEntity + '_data';
    entityData      = {};

    entityData[fieldGroup] = entity;

    return $.ajax({
        method  : 'POST',
        url     : self.options.restApi,
        data    : entityData
    }).done(function(data, status, xhr){
        $('#' + self.snakeCasedEntity + '_form_modal').modal('hide');
        self.notifier.success(data.content);
        self.reload();
    }).fail(function(xhr, status, error){
        self.showErrorResponse(xhr);
    });
}

/**
 * Display notification on error
 */
TableManager.fn.showErrorResponse = function(response) {
    if(response.status == 401){
        this.notifier.error('Your session is expired!\n\nYou will be redirected to the login page shortly.');
        setTimeout(function() {
            window.location.reload();
        }, 1000)
    } else {
        var message = 'Unknown error occured';

        if (response.responseJSON && response.responseJSON.message) {
            message = '' + response.responseJSON.message + ''
        }

        if (response.responseJSON && response.responseJSON.errors) {
            var errors = response.responseJSON.errors;

            message += '
';

            for (var e in errors) {
                if (typeof errors[e] == 'string') {
                    message += '
' + e + ' : ' + errors[e] + '
';
                } else {
                    var detailedMessage = '';

                    for (var d in errors[e]) {
                        detailedMessage += '
' + errors[e][d] + '
';
                    }

                    message += '
' + e + ' :
' + detailedMessage + '

';
                }
            }

            message += '
';
        }

        this.notifier.error(message);
    }
}

/**
 * Initialize datatable
 */
TableManager.fn.initDatatable = function() {
    var self = this;

    this.datatable = self.baseTable.DataTable({
        processing  : true,
        scrollX     : true,
        serverSide  : true,
        responsive  : true,
        dom         : this.options.dom,
        /** column definition for action column */
        columnDefs  : self.options.columnDefs,
        autoWidth   : false,
        language    : {
            paginate: {
                previous: '«',
                next    : '»'
            }
        },
        ajax: {
            url     : self.options.datatableApi,
            type    : 'POST',
            data    : {
                _token : self.options.csrfToken
            },
            error   : function(resp){
                self.showErrorResponse(resp);
            }
        }
    });

    return this.datatable;
}
<commit_msg>add options for scrollX<commit_after>/**
 * {{User}} manager function.
 *
 * require jQuery, datatable, toaster
 */
function TableManager(options) {
    this.options = $.extend(true, {
        restApi : window.location.href,
        csrfToken : null,
        datatableApi : null,
        entity : null,
        dom : null,
        scrollX : false,
        columnDefs : [],
        renderIdAsButton: true, //id should be placed at last cols
        buttonColumnWidth : '150px',
        buttonRenderer : null,
        immediateInit : true,
        on : {},
    }, options);

    if (!this.options.entity) {
        throw new Error('Entity name not defined!');
    }

    this.snakeCasedEntity = this.options.entity.replace(/-/g, '_');
    this.kebabCasedEntity = this.options.entity.replace(/_/g, '-');
    this.baseTable      = $('#' + this.snakeCasedEntity + '_table');
    this.datatable      = null;
    this.event          = this.initEventDispatcher();
    this.options.dom    = this.options.dom || "<'row'<'col-md-12'<'box box-primary'<'box-header with-border'<'row'<'col-md-6'<'#" + this.snakeCasedEntity + "_button_wrapper'>><'col-md-3 hidden-xs'l><'col-md-3 hidden-xs'f>>> <'box-body no-padding'tr><'box-footer clearfix'<'col-sm-5'i><'col-sm-7'p>>>>>";

    if (window.toastr) {
        this.notifier   = toastr;
    } else {
        this.notifier   = {
            success : alert,
            error   : alert,
            warning : alert,
            info    : alert
        }
    }
    for (var ev in this.options.on) {
        this.event.listen(ev, this.options.on[ev]);
    }

    if (this.options.immediateInit) {
        this.init();
    }
}

TableManager.fn = TableManager.prototype;

TableManager.fn.init = function() {
    var self = this;

    this.event.dispatch('before_init');

    if (this.options.renderIdAsButton) {
        var renderer = this.options.buttonRenderer ? this.options.buttonRenderer : function (data, type, row, meta) {
            var button = '<button href="#' + self.kebabCasedEntity + '-edit" class="btn btn-xs btn-default btn-' + self.kebabCasedEntity + '-edit" data-id="' + data + '"> edit</button>';
                button += '<button href="#' + self.kebabCasedEntity + '-delete" class="btn btn-xs btn-danger btn-' + self.kebabCasedEntity + '-delete" data-id="' + data + '" style="margin-left: 5px"> delete</button>';

            return button;
        };

        this.options.columnDefs.push({
            targets     : -1,
            className   : 'text-center',
            orderable   : false,
            data        : 'id',
            searchable  : false,
            width       : this.options.buttonColumnWidth,
            render      : renderer
        });
    }

    $(document).ready(function(){
        self.event.dispatch('table.before_init', {table : self.baseTable});

        self.initDatatable()
        self.baseTable.on('click', '.btn-' + self.kebabCasedEntity + '-edit', function(e){
            e.preventDefault();

            var button = $(this).prop('disabled', true);
            var entityId = button.attr('data-id');

            button.find('i').attr('class', 'fa fa-fw fa-spin fa-spinner');

            self.edit(entityId).always(function() {
                button.prop('disabled', false).html(' edit');
            });
        });

        self.baseTable.on('click', '.btn-' + self.kebabCasedEntity + '-delete', function(e){
            e.preventDefault();

            if(confirm('Are you sure want to delete this ' + self.snakeCasedEntity.replace(/_/g, ' ') + '?')){
                var button = $(this).prop('disabled', true);
                var entityId = button.attr('data-id');

                button.find('i').attr('class', 'fa fa-fw fa-spin fa-spinner');

                self.delete(entityId).always(function() {
                    button.prop('disabled', false).html(' delete');
                });
            }
        });

        $('#btn_' + self.snakeCasedEntity + '_save').click(function(e) {
            e.preventDefault();

            var button      = $(this).prop('disabled', true).text('saving...');
            var entityData  = $('#' + self.snakeCasedEntity + '_form').serializeJSON();
            var method      = $('#' + self.snakeCasedEntity + '_method_field').val();
            var enableBtn   = function() {
                button.prop('disabled', false).text('save');
            }

            if (method == 'PUT') {
                self.update(entityData[self.snakeCasedEntity + '_data']).always(enableBtn);
            } else {
                self.store(entityData[self.snakeCasedEntity + '_data']).always(enableBtn);
            }
        });

        $('#btn_' + self.snakeCasedEntity + '_create').appendTo('#' + self.snakeCasedEntity + '_button_wrapper').click(function(e){
            e.preventDefault();
            self.create();
        });

        self.event.dispatch('table.after_init', {table: self.baseTable});
    });

    this.notifier.options = {
        "closeButton": true,
        "newestOnTop": true,
        "positionClass": "toast-top-right",
    }

    this.event.dispatch('after_init');
}

TableManager.fn.initEventDispatcher = function() {
    var self = this;
    /**
     * @author mrdoob / http://mrdoob.com/
     */

    function EventDispatcher() {}

    Object.assign(EventDispatcher.prototype, {
        listen: function (type, listener) {
            if (this._listeners === undefined) this._listeners = {};

            var listeners = this._listeners;
            if (listeners[type] === undefined) {
                listeners[type] = [];
            }

            if (listeners[type].indexOf(listener) === - 1) {
                listeners[type].push(listener);
            }
        },

        hasListener: function (type, listener) {
            if (this._listeners === undefined) return false;

            return this._listeners[type] !== undefined && this._listeners[type].indexOf(listener) !== - 1;
        },

        removeListener: function (type, listener) {
            if (this._listeners === undefined) return;

            var listenerArray = this._listeners[type];

            if (listenerArray !== undefined) {
                var index = listenerArray.indexOf(listener);

                if (index !== - 1) {
                    listenerArray.splice(index, 1);
                }
            }
        },

        dispatch: function (eventName, eventData) {
            if (this._listeners === undefined) return;

            eventData = eventData || {};
            var listeners = this._listeners[eventName];

            if (listeners !== undefined) {
                eventData.target = self;

                var listeners = listeners.slice(0);
                for (var i = 0, l = listeners.length; i < l; i ++) {
                    listeners[i].call(this, eventData);
                }
            }
        }
    });

    return new EventDispatcher();
}

TableManager.fn.reload = function() {
    this.datatable.ajax.reload(null, false);
}

/**
 * Fetch entity data from the server
 */
TableManager.fn.fetch = function(entityId) {
    return $.ajax({
        'method' : 'GET',
        'url' : this.options.restApi + entityId
    });
}

/**
 * Display edit form
 */
TableManager.fn.edit = function(entityId) {
    var self = this;

    return this.fetch(entityId)
        .done(function(data, status, xhr) {
            self.event.dispatch('edit_form.before_shown', {entity : data});

            $('#' + self.snakeCasedEntity + '_form')[0].reset();

            var elem;
            for(var a in data){
                elem = $('#' + self.snakeCasedEntity + '_'+a+'_field');
                elem.val(data[a]);
            }

            $('#' + self.snakeCasedEntity + '_form_title').text('Edit ' + self.snakeCasedEntity.replace(/_/g, ' '));
            $('#' + self.snakeCasedEntity + '_method_field').val('PUT');
            $('#' + self.snakeCasedEntity + '_token_field').val(self.options.csrfToken);
            $('#' + self.snakeCasedEntity + '_form_modal').modal('show');

            self.event.dispatch('edit_form.after_shown');
        })
        .fail(function(xhr, status, error) {
            self.showErrorResponse(xhr);
        });
}

/**
 * Send entity data to server for update
 */
TableManager.fn.update = function(entity) {
    var self = this;

    entity._token   = this.options.csrfToken;
    fieldGroup      = self.snakeCasedEntity + '_data';
    entityData      = {};

    entityData[fieldGroup] = entity;

    return $.ajax({
        method  : 'PUT',
        url     : self.options.restApi + entity.id,
        data    : entityData
    }).done(function(data, status, xhr){
        self.notifier.success(data.content);

        $('#btn_' + self.snakeCasedEntity + '_save').prop('disabled', false).text('save');
        $('#' + self.snakeCasedEntity + '_form_modal').modal('hide');
        self.reload();
    }).fail(function(hxr, status, error){
        $('#btn_' + self.snakeCasedEntity + '_save').prop('disabled', false).text('save');
        self.showErrorResponse(hxr);
    });
}

/**
 * Delete entity data from server
 */
TableManager.fn.delete = function(entityId) {
    var self = this;

    return $.ajax({
        method  : 'DELETE',
        data    : {_token : self.options.csrfToken},
        url     : self.options.restApi + entityId
    }).done(function(data, status, xhr){
        self.notifier.success(data.content);
        self.reload();
    }).fail(function(xhr, status, error){
        self.showErrorResponse(xhr);
    });
}

/**
 * Display create form
 */
TableManager.fn.create = function() {
    this.event.dispatch('create_form.before_shown');

    $('#' + this.snakeCasedEntity + '_form_title').text('Create new ' + this.snakeCasedEntity.replace(/_/g, ' '));
    $('#' + this.snakeCasedEntity + '_form')[0].reset();

    $('#' + this.snakeCasedEntity + '_method_field').val('POST');
    $('#' + this.snakeCasedEntity + '_token_field').val(this.options.csrfToken);
    $('#' + this.snakeCasedEntity + '_id_field').val('');

    $('#' + this.snakeCasedEntity + '_form_modal').modal('show');

    this.event.dispatch('create_form.after_shown');
}

/**
 * Send data to server for create
 */
TableManager.fn.store = function(entity) {
    var self = this;

    entity._token   = this.options.csrfToken;
    fieldGroup      = self.snakeCasedEntity + '_data';
    entityData      = {};

    entityData[fieldGroup] = entity;

    return $.ajax({
        method  : 'POST',
        url     : self.options.restApi,
        data    : entityData
    }).done(function(data, status, xhr){
        $('#' + self.snakeCasedEntity + '_form_modal').modal('hide');
        self.notifier.success(data.content);
        self.reload();
    }).fail(function(xhr, status, error){
        self.showErrorResponse(xhr);
    });
}

/**
 * Display notification on error
 */
TableManager.fn.showErrorResponse = function(response) {
    if(response.status == 401){
        this.notifier.error('Your session is expired!\n\nYou will be redirected to the login page shortly.');
        setTimeout(function() {
            window.location.reload();
        }, 1000)
    } else {
        var message = 'Unknown error occured';

        if (response.responseJSON && response.responseJSON.message) {
            message = '' + response.responseJSON.message + ''
        }

        if (response.responseJSON && response.responseJSON.errors) {
            var errors = response.responseJSON.errors;

            message += '
';

            for (var e in errors) {
                if (typeof errors[e] == 'string') {
                    message += '
' + e + ' : ' + errors[e] + '
';
                } else {
                    var detailedMessage = '';

                    for (var d in errors[e]) {
                        detailedMessage += '
' + errors[e][d] + '
';
                    }

                    message += '
' + e + ' :
' + detailedMessage + '

';
                }
            }

            message += '
';
        }

        this.notifier.error(message);
    }
}

/**
 * Initialize datatable
 */
TableManager.fn.initDatatable = function() {
    var self = this;

    this.datatable = self.baseTable.DataTable({
        processing  : true,
        scrollX     : this.options.scrollX,
        serverSide  : true,
        responsive  : true,
        dom         : this.options.dom,
        /** column definition for action column */
        columnDefs  : self.options.columnDefs,
        autoWidth   : false,
        language    : {
            paginate: {
                previous: '«',
                next    : '»'
            }
        },
        ajax: {
            url     : self.options.datatableApi,
            type    : 'POST',
            data    : {
                _token : self.options.csrfToken
            },
            error   : function(resp){
                self.showErrorResponse(resp);
            }
        }
    });

    return this.datatable;
}
<|endoftext|>


<commit_before>/**
 * @ngdoc directive
 * @name umbraco.directives.directive:umbTreeItem
 * @element li
 * @function
 *
 * @description
 * Renders a list item, representing a single node in the tree.
 * Includes element to toggle children, and a menu toggling button
 *
 * **note:** This directive is only used internally in the umbTree directive
 *
 * @example
   <example module="umbraco">
    <file name="index.html">
         <umb-tree-item ng-repeat="child in tree.children" node="child" callback="callback" section="content"></umb-tree-item>
    </file>
   </example>
 */
angular.module("umbraco.directives")
.directive('umbTreeItem', function ($compile, $http, $templateCache, $interpolate, $log, $location, $rootScope, $window, treeService, $timeout) {
  return {
    restrict: 'E',
    replace: true,

    scope: {
      section: '@',
      cachekey: '@',
      eventhandler: '=',
      currentNode:'=',
      node:'=',
      tree:'='
    },

    template: '

' +
        '' +
        '' +
        '' +
        '{{node.name}}' +
        '' +
        '

' +
        '
' +
        '
',

    link: function (scope, element, attrs) {

        //flag to enable/disable delete animations, default for an item is tru
        var deleteAnimations = true;

        /** Helper function to emit tree events */
        function emitEvent(eventName, args) {
          if(scope.eventhandler){
            $(scope.eventhandler).trigger(eventName,args);
          }
        }

        /** updates the node's styles */
        function styleNode(node) {
            node.stateCssClass = (node.cssClasses || []).join(" ");

            if (node.style) {
                $(element).find("i").attr("style", node.style);
            }
        }

        /** This will deleteAnimations to true after the current digest */
        function enableDeleteAnimations() {
            //do timeout so that it re-enables them after this digest
            $timeout(function () {
                //enable delete animations
                deleteAnimations = true;
            }, 0, false);
        }

        //add a method to the node which we can use to call to update the node data if we need to ,
        // this is done by sync tree, we don't want to add a $watch for each node as that would be crazy insane slow
        // so we have to do this
        scope.node.updateNodeData = function (newNode) {
            _.extend(scope.node, newNode);
            //now update the styles
            styleNode(scope.node);
        };

        /**
          Method called when the options button next to a node is called
          In the main tree this opens the menu, but internally the tree doesnt
          know about this, so it simply raises an event to tell the parent controller
          about it.
        */
        scope.options = function(e, n, ev){
          emitEvent("treeOptionsClick", {element: e, tree: scope.tree, node: n, event: ev});
        };

        /**
          Method called when an item is clicked in the tree, this passes the
          DOM element, the tree node object and the original click
          and emits it as a treeNodeSelect element if there is a callback object
          defined on the tree
        */
        scope.select = function(e,n,ev){
            emitEvent("treeNodeSelect", { element: e, tree: scope.tree, node: n, event: ev });
        };

        /**
          Method called when an item is right-clicked in the tree, this passes the
          DOM element, the tree node object and the original click
          and emits it as a treeNodeSelect element if there is a callback object
          defined on the tree
        */
        scope.altSelect = function(e,n,ev){
            emitEvent("treeNodeAltSelect", { element: e, tree: scope.tree, node: n, event: ev });
        };

        /** method to set the current animation for the node.
        *  This changes dynamically based on if we are changing sections or just loading normal tree data.
        *  When changing sections we don't want all of the tree-ndoes to do their 'leave' animations.
        */
        scope.animation = function () {
            if (deleteAnimations && scope.node.expanded) {
                return { leave: 'tree-node-delete-leave' };
            }
            else {
                return {};
            }
        };

        /**
          Method called when a node in the tree is expanded, when clicking the arrow
          takes the arrow DOM element and node data as parameters
          emits treeNodeCollapsing event if already expanded and treeNodeExpanding if collapsed
        */
        scope.load = function(node) {
            if (node.expanded) {
                deleteAnimations = false;
                emitEvent("treeNodeCollapsing", {tree: scope.tree, node: node });
                node.expanded = false;
            }
            else {
                scope.loadChildren(node, false);
            }
        };

        /* helper to force reloading children of a tree node */
        scope.loadChildren = function(node, forceReload){
            //emit treeNodeExpanding event, if a callback object is set on the tree
            emitEvent("treeNodeExpanding", { tree: scope.tree, node: node });

            if (node.hasChildren && (forceReload || !node.children || (angular.isArray(node.children) && node.children.length === 0))) {
                //get the children from the tree service
                treeService.loadNodeChildren({ node: node, section: scope.section })
                    .then(function(data) {
                        //emit expanded event
                        emitEvent("treeNodeExpanded", {tree: scope.tree, node: node, children: data });
                        enableDeleteAnimations();
                    });
            }
            else {
                emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: node.children });
                node.expanded = true;
                enableDeleteAnimations();
            }
        };

        /**
          Helper method for setting correct element padding on tree DOM elements
          Since elements are not children of eachother, we need this indenting done
          manually
        */
        scope.setTreePadding = function(node) {
          return { 'padding-left': (node.level * 20) + "px" };
        };

        //if the current path contains the node id, we will auto-expand the tree item children

        styleNode(scope.node);

        var template = '
<umb-tree-item  ng-repeat="child in node.children" eventhandler="eventhandler" tree="tree" current-node="currentNode" node="child" section="{{section}}" ng-animate="animation()"></umb-tree-item>
';
        var newElement = angular.element(template);
        $compile(newElement)(scope);
        element.append(newElement);
    }
  };
});
<commit_msg>fixes tree item style reload<commit_after>/**
 * @ngdoc directive
 * @name umbraco.directives.directive:umbTreeItem
 * @element li
 * @function
 *
 * @description
 * Renders a list item, representing a single node in the tree.
 * Includes element to toggle children, and a menu toggling button
 *
 * **note:** This directive is only used internally in the umbTree directive
 *
 * @example
   <example module="umbraco">
    <file name="index.html">
         <umb-tree-item ng-repeat="child in tree.children" node="child" callback="callback" section="content"></umb-tree-item>
    </file>
   </example>
 */
angular.module("umbraco.directives")
.directive('umbTreeItem', function ($compile, $http, $templateCache, $interpolate, $log, $location, $rootScope, $window, treeService, $timeout) {
  return {
    restrict: 'E',
    replace: true,

    scope: {
      section: '@',
      cachekey: '@',
      eventhandler: '=',
      currentNode:'=',
      node:'=',
      tree:'='
    },

    template: '

' +
        '' +
        '' +
        '' +
        '{{node.name}}' +
        '' +
        '

' +
        '
' +
        '
',

    link: function (scope, element, attrs) {

        //flag to enable/disable delete animations, default for an item is tru
        var deleteAnimations = true;

        /** Helper function to emit tree events */
        function emitEvent(eventName, args) {
          if(scope.eventhandler){
            $(scope.eventhandler).trigger(eventName,args);
          }
        }

        /** updates the node's styles */
        function styleNode(node) {
            node.stateCssClass = (node.cssClasses || []).join(" ");

            if (node.style) {
                $(element).find("i").attr("style", node.style);
            }
        }

        /** This will deleteAnimations to true after the current digest */
        function enableDeleteAnimations() {
            //do timeout so that it re-enables them after this digest
            $timeout(function () {
                //enable delete animations
                deleteAnimations = true;
            }, 0, false);
        }

        //add a method to the node which we can use to call to update the node data if we need to ,
        // this is done by sync tree, we don't want to add a $watch for each node as that would be crazy insane slow
        // so we have to do this
        scope.node.updateNodeData = function (newNode) {
            _.extend(scope.node, newNode);
            //now update the styles
            styleNode(scope.node);
        };

        /**
          Method called when the options button next to a node is called
          In the main tree this opens the menu, but internally the tree doesnt
          know about this, so it simply raises an event to tell the parent controller
          about it.
        */
        scope.options = function(e, n, ev){
          emitEvent("treeOptionsClick", {element: e, tree: scope.tree, node: n, event: ev});
        };

        /**
          Method called when an item is clicked in the tree, this passes the
          DOM element, the tree node object and the original click
          and emits it as a treeNodeSelect element if there is a callback object
          defined on the tree
        */
        scope.select = function(e,n,ev){
            emitEvent("treeNodeSelect", { element: e, tree: scope.tree, node: n, event: ev });
        };

        /**
          Method called when an item is right-clicked in the tree, this passes the
          DOM element, the tree node object and the original click
          and emits it as a treeNodeSelect element if there is a callback object
          defined on the tree
        */
        scope.altSelect = function(e,n,ev){
            emitEvent("treeNodeAltSelect", { element: e, tree: scope.tree, node: n, event: ev });
        };

        /** method to set the current animation for the node.
        *  This changes dynamically based on if we are changing sections or just loading normal tree data.
        *  When changing sections we don't want all of the tree-ndoes to do their 'leave' animations.
        */
        scope.animation = function () {
            if (deleteAnimations && scope.node.expanded) {
                return { leave: 'tree-node-delete-leave' };
            }
            else {
                return {};
            }
        };

        /**
          Method called when a node in the tree is expanded, when clicking the arrow
          takes the arrow DOM element and node data as parameters
          emits treeNodeCollapsing event if already expanded and treeNodeExpanding if collapsed
        */
        scope.load = function(node) {
            if (node.expanded) {
                deleteAnimations = false;
                emitEvent("treeNodeCollapsing", {tree: scope.tree, node: node });
                node.expanded = false;
            }
            else {
                scope.loadChildren(node, false);
            }
        };

        /* helper to force reloading children of a tree node */
        scope.loadChildren = function(node, forceReload){
            //emit treeNodeExpanding event, if a callback object is set on the tree
            emitEvent("treeNodeExpanding", { tree: scope.tree, node: node });

            if (node.hasChildren && (forceReload || !node.children || (angular.isArray(node.children) && node.children.length === 0))) {
                //get the children from the tree service
                treeService.loadNodeChildren({ node: node, section: scope.section })
                    .then(function(data) {
                        //emit expanded event
                        emitEvent("treeNodeExpanded", {tree: scope.tree, node: node, children: data });
                        enableDeleteAnimations();
                    });
            }
            else {
                emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: node.children });
                node.expanded = true;
                enableDeleteAnimations();
            }
        };

        /**
          Helper method for setting correct element padding on tree DOM elements
          Since elements are not children of eachother, we need this indenting done
          manually
        */
        scope.setTreePadding = function(node) {
          return { 'padding-left': (node.level * 20) + "px" };
        };

        //if the current path contains the node id, we will auto-expand the tree item children

        styleNode(scope.node);

        var template = '
<umb-tree-item  ng-repeat="child in node.children" eventhandler="eventhandler" tree="tree" current-node="currentNode" node="child" section="{{section}}" ng-animate="animation()"></umb-tree-item>
';
        var newElement = angular.element(template);
        $compile(newElement)(scope);
        element.append(newElement);
    }
  };
});
<|endoftext|>


<commit_before>sap.ui.define([
		'jquery.sap.global',
		'sap/ui/core/Fragment',
		'sap/ui/core/mvc/Controller',
		'sap/ui/model/json/JSONModel'
	], function(jQuery, Fragment, Controller, JSONModel) {
	"use strict";

	var CController = Controller.extend("sap.m.sample.ObjectHeaderTitleSel.C", {

		onInit : function (evt) {
			// set explored app's demo model on this sample
			var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json"));
			oModel.setDefaultBindingMode("OneWay");
			this.getView().setModel(oModel);
		},

		onExit : function () {
			if (this._oPopover) {
				this._oPopover.destroy();
			}
		},

		_getResponsivePopover: function () {
			if (! this._oPopover) {
				this._oPopover = sap.ui.xmlfragment("sap.m.sample.ObjectHeaderTitleSel.Popover", this);
			}
			return this._oPopover;
		},

		handleItemSelect: function (oEvent) {
			var oItem = oEvent.getParameter("listItem");
			var oObjectHeader = this.getView().byId("idObjectHeader");
			oObjectHeader.setTitle(oItem.getTitle());
			oObjectHeader.setBindingContext(oItem.getBindingContext());
			this._oPopover.close();
		},

		handleTitleSelectorPress: function (oEvent) {
			var _oPopover = this._getResponsivePopover();
			_oPopover.openBy(oEvent.getParameter("domRef"));
			_oPopover.setModel(oEvent.getSource().getModel());
		}

	});

	return CController;

});
<commit_msg>[INTERNAL][FIX] ObjectHeaderTitleSel explored sample fixed<commit_after>sap.ui.define([
		'jquery.sap.global',
		'sap/ui/core/Fragment',
		'sap/ui/core/mvc/Controller',
		'sap/ui/model/json/JSONModel'
	], function(jQuery, Fragment, Controller, JSONModel) {
	"use strict";

	var CController = Controller.extend("sap.m.sample.ObjectHeaderTitleSel.C", {

		onInit : function (evt) {
			// set explored app's demo model on this sample
			var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json"));
			oModel.setDefaultBindingMode("OneWay");
			this.getView().setModel(oModel);
		},

		onExit : function () {
			if (this._oPopover) {
				this._oPopover.destroy();
			}
		},

		_getResponsivePopover: function () {
			if (! this._oPopover) {
				this._oPopover = sap.ui.xmlfragment("sap.m.sample.ObjectHeaderTitleSel.Popover", this);
			}
			return this._oPopover;
		},

		handleItemSelect: function (oEvent) {
			var oItem = oEvent.getParameter("listItem");
			var oObjectHeader = this.getView().byId("idObjectHeader");
			oObjectHeader.setTitle(oItem.getTitle());
			oObjectHeader.setBindingContext(oItem.getBindingContext());
			this._oPopover.close();
		},

		handleTitleSelectorPress: function (oEvent) {
			var _oPopover = this._getResponsivePopover();
			_oPopover.setModel(oEvent.getSource().getModel());
			_oPopover.openBy(oEvent.getParameter("domRef"));
		}

	});

	return CController;

});
<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/youtube', [
    'providers','utils/str',
    'jquery','jquery/tmpl','jquery/jsonp',
    'jqueryui/draggable',
    'providers/youtube/adaptor',
    'tmpl!livedesk>providers/youtube',
    'tmpl!livedesk>providers/youtube/clip-item',
    'tmpl!livedesk>providers/youtube/favorite-item',
    'tmpl!livedesk>providers/google-more',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/jsonp-error',
    'tmpl!livedesk>providers/loading'
    ], function( providers, str, $ ) {
        $.extend(providers.youtube, {
            initialized: false,

            data: [],
            init: function(){
                if(!this.initialized || !this.el.children(":first").length) {
                    this.adaptor.init();
                    this.render();
                }
                this.initialized = true;
            },
            render: function() {
                var self = this;
                this.el.tmpl('livedesk>providers/youtube', {}, function(){
                    $(self.el)
                    .off('click.livedesk')
                    .on('click.livedesk', '#ytb-search-controls>li', function(ev){
                        $(this).siblings().removeClass('active') .end()
                        .addClass('active');
                        var myArr = $(this).attr('id').split('-');

                        //hide all ggl result holders
                        self.el.find('.scroller').css('visibility', 'hidden');
                        //show only the one we need
                        $('#ytb-'+myArr[1]+'-holder').css('visibility', 'visible');
                        //show/hide the 'order by' drop down'
                        if (myArr[1] != 'src') {
                            $('#ytb-order-by').css('display','none');
                        } else {
                            $('#ytb-order-by').css('display','inline');
                        }

                        self.startSearch(true);
                    })
                    .off('keyup.livedesk')
                    .on('keyup.livedesk','#youtube-search-text', function(e){
                        if(e.keyCode == 13 && $(this).val().length > 0) {
                            //enter press on youtube search text
                            //check what search it is
                            self.startSearch(true);
                        }
                    })
                    .off('change' ,'#ytb-order-by')
                    .on('change' ,'#ytb-order-by', function(){
                        self.startSearch(true);
                    })
                    ;
                });
            },
            startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                var searchVal = $('#youtube-search-text').val();
                if ( $('#ytb-src-tab').hasClass('active') ) {
                    //do youtube search
                    if ( (fresh || $('#ytb-src-results').html() == '') && searchVal != '') {
                        self.doSearch(1);
                    }
                }

                if ( $('#ytb-fav-tab').hasClass('active') ) {
                    //do youtube search
                    if (fresh || $('#ytb-fav-results').html() == '') {
                        self.doFavorites();
                    }
                }

                if ( $('#ytb-usr-tab').hasClass('active') ) {
                    //do youtube search
                    if (fresh || $('#ytb-usr-results').html() == '') {
                        self.doUsers();
                    }

                }
            },

            showLoading : function(where) {
                $(where).tmpl('livedesk>providers/loading', function(){
                    });
            },
            stopLoading : function(where) {
                $(where).html('');
            },
            noResults : function(where) {
                $.tmpl('livedesk>providers/no-results', {}, function(e,o) {
                    $(where).html(o);
                });
            },

            trimDesc : function(desc) {
                if (desc.length > 200) {
                    return desc.substring(0, 200) + ' ...;'
                } else {
                    return desc;
                }
            },
            cleanContent : function(results) {
                for(var i = 0; i < results.length; i ++) {
                    if ( results[i].video ) {
                        results[i].video.description = this.trimDesc(results[i].video.description);
                        var upDate = new Date(results[i].video.uploaded);
                        results[i].video.uploaded = upDate.toDateString();
                    } else {
                        results[i].description = this.trimDesc(results[i].description);
                        var upDate = new Date(results[i].uploaded);
                        results[i].uploaded = upDate.toDateString();
                    }
                }
                return results;
            },
            doSearch: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                var relevance = $('#ytb-order-by').val();
                start = typeof start !== 'undefined' ? start : 1;

                this.showLoading('#ytb-src-more');
                if (start == 1) {
                    self.data = [];
                    $('#ytb-src-results').html('');
                }
                var fullUrl = 'http://gdata.youtube.com/feeds/api/videos?v=2&max-results=20&alt=jsonc&orderby='+ relevance +'&q='+key+'&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-src-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-src-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/clip-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-src-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }

                        if (parseInt(start + ipp) < total) {
                            $('#ytb-src-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-src-load-more'
                            }, function(){
                                $(this).find('[name="ytb-src-load-more"]').on('click', function(){
                                    self.doSearch(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-src-more');
                    self.noResults('#ytb-usr-results');
                })
            },
            doFavorites: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                start = typeof start !== 'undefined' ? start : 1;
                this.showLoading('#ytb-fav-more');
                if (start == 1) {
                    $('#ytb-fav-results').html('');
                    self.data = [];
                }

                var fullUrl = 'http://gdata.youtube.com/feeds/api/users/'+key+'/favorites?v=2&max-results=20&alt=jsonc&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-fav-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-fav-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/favorite-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-fav-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        results[idx].id = results[idx].video.id;
                                        results[idx].uploaded = results[idx].video.uploaded;
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }
                        if (parseInt(start + ipp) < total) {
                            $('#ytb-fav-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-fav-load-more'
                            }, function(){
                                $(this).find('[name="ytb-fav-load-more"]').on('click', function(){
                                    self.doFavorites(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-fav-more');
                    self.noResults('#ytb-fav-results');
                });

            },
            doUsers: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                start = typeof start !== 'undefined' ? start : 1;

                this.showLoading('#ytb-usr-more');
                if (start == 1) {
                    $('#ytb-usr-results').html('');
                }
                var fullUrl = 'http://gdata.youtube.com/feeds/api/users/'+key+'/uploads?v=2&max-results=20&alt=jsonc&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-usr-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-usr-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/clip-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-usr-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }

                        if (parseInt(start + ipp) < total) {
                            $('#ytb-usr-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-usr-load-more'
                            }, function(){
                                $(this).find('[name="ytb-usr-load-more"]').on('click', function(){
                                    self.doUsers(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-usr-more');
                    self.noResults('#ytb-usr-results');
                });

            }
        });
        return providers;
    });<commit_msg>NR-444 : the youtube video uploader's name is sometimes displayed as undefined<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/youtube', [
    'providers','utils/str',
    'jquery','jquery/tmpl','jquery/jsonp',
    'jqueryui/draggable',
    'providers/youtube/adaptor',
    'tmpl!livedesk>providers/youtube',
    'tmpl!livedesk>providers/youtube/clip-item',
    'tmpl!livedesk>providers/youtube/favorite-item',
    'tmpl!livedesk>providers/google-more',
    'tmpl!livedesk>providers/load-more',
    'tmpl!livedesk>providers/no-results',
    'tmpl!livedesk>providers/jsonp-error',
    'tmpl!livedesk>providers/loading'
    ], function( providers, str, $ ) {
        $.extend(providers.youtube, {
            initialized: false,

            data: [],
            init: function(){
                if(!this.initialized || !this.el.children(":first").length) {
                    this.adaptor.init();
                    this.render();
                }
                this.initialized = true;
            },
            render: function() {
                var self = this;
                this.el.tmpl('livedesk>providers/youtube', {}, function(){
                    $(self.el)
                    .off('click.livedesk')
                    .on('click.livedesk', '#ytb-search-controls>li', function(ev){
                        $(this).siblings().removeClass('active') .end()
                        .addClass('active');
                        var myArr = $(this).attr('id').split('-');

                        //hide all ggl result holders
                        self.el.find('.scroller').css('visibility', 'hidden');
                        //show only the one we need
                        $('#ytb-'+myArr[1]+'-holder').css('visibility', 'visible');
                        //show/hide the 'order by' drop down'
                        if (myArr[1] != 'src') {
                            $('#ytb-order-by').css('display','none');
                        } else {
                            $('#ytb-order-by').css('display','inline');
                        }

                        self.startSearch(true);
                    })
                    .off('keyup.livedesk')
                    .on('keyup.livedesk','#youtube-search-text', function(e){
                        if(e.keyCode == 13 && $(this).val().length > 0) {
                            //enter press on youtube search text
                            //check what search it is
                            self.startSearch(true);
                        }
                    })
                    .off('change' ,'#ytb-order-by')
                    .on('change' ,'#ytb-order-by', function(){
                        self.startSearch(true);
                    })
                    ;
                });
            },
            startSearch: function(fresh) {
                var self = this;
                fresh = typeof fresh !== 'undefined' ? fresh : false;
                var searchVal = $('#youtube-search-text').val();
                if ( $('#ytb-src-tab').hasClass('active') ) {
                    //do youtube search
                    if ( (fresh || $('#ytb-src-results').html() == '') && searchVal != '') {
                        self.doSearch(1);
                    }
                }

                if ( $('#ytb-fav-tab').hasClass('active') ) {
                    //do youtube search
                    if (fresh || $('#ytb-fav-results').html() == '') {
                        self.doFavorites();
                    }
                }

                if ( $('#ytb-usr-tab').hasClass('active') ) {
                    //do youtube search
                    if (fresh || $('#ytb-usr-results').html() == '') {
                        self.doUsers();
                    }

                }
            },

            showLoading : function(where) {
                $(where).tmpl('livedesk>providers/loading', function(){
                    });
            },
            stopLoading : function(where) {
                $(where).html('');
            },
            noResults : function(where) {
                $.tmpl('livedesk>providers/no-results', {}, function(e,o) {
                    $(where).html(o);
                });
            },

            trimDesc : function(desc) {
                if (desc.length > 200) {
                    return desc.substring(0, 200) + ' ...;'
                } else {
                    return desc;
                }
            },
            cleanContent : function(results) {
                for(var i = 0; i < results.length; i ++) {
                    if ( results[i].video ) {
                        results[i].video.description = this.trimDesc(results[i].video.description);
                        var upDate = new Date(results[i].video.uploaded);
                        results[i].video.uploaded = upDate.toDateString();
                        results[i].uploader = results[i].video.uploader;
                    } else {
                        results[i].description = this.trimDesc(results[i].description);
                        var upDate = new Date(results[i].uploaded);
                        results[i].uploaded = upDate.toDateString();
                    }
                }
                return results;
            },
            doSearch: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                var relevance = $('#ytb-order-by').val();
                start = typeof start !== 'undefined' ? start : 1;

                this.showLoading('#ytb-src-more');
                if (start == 1) {
                    self.data = [];
                    $('#ytb-src-results').html('');
                }
                var fullUrl = 'http://gdata.youtube.com/feeds/api/videos?v=2&max-results=20&alt=jsonc&orderby='+ relevance +'&q='+key+'&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-src-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-src-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/clip-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-src-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }

                        if (parseInt(start + ipp) < total) {
                            $('#ytb-src-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-src-load-more'
                            }, function(){
                                $(this).find('[name="ytb-src-load-more"]').on('click', function(){
                                    self.doSearch(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-src-more');
                    self.noResults('#ytb-usr-results');
                })
            },
            doFavorites: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                start = typeof start !== 'undefined' ? start : 1;
                this.showLoading('#ytb-fav-more');
                if (start == 1) {
                    $('#ytb-fav-results').html('');
                    self.data = [];
                }

                var fullUrl = 'http://gdata.youtube.com/feeds/api/users/'+key+'/favorites?v=2&max-results=20&alt=jsonc&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-fav-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-fav-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/favorite-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-fav-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        results[idx].id = results[idx].video.id;
                                        results[idx].uploaded = results[idx].video.uploaded;
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }
                        if (parseInt(start + ipp) < total) {
                            $('#ytb-fav-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-fav-load-more'
                            }, function(){
                                $(this).find('[name="ytb-fav-load-more"]').on('click', function(){
                                    self.doFavorites(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-fav-more');
                    self.noResults('#ytb-fav-results');
                });

            },
            doUsers: function (start) {
                var self = this;
                var key = $('#youtube-search-text').val();
                if(key == '') {
                    return 1;
                }
                start = typeof start !== 'undefined' ? start : 1;

                this.showLoading('#ytb-usr-more');
                if (start == 1) {
                    $('#ytb-usr-results').html('');
                }
                var fullUrl = 'http://gdata.youtube.com/feeds/api/users/'+key+'/uploads?v=2&max-results=20&alt=jsonc&start-index='+start;
                $.ajax({
                    url : fullUrl,
                    dataType: 'json',
                    success : function(myData){
                        self.stopLoading('#ytb-usr-more');
                        var myJson = myData;
                        var results = myJson.data.items;
                        var total = myJson.data.totalItems;
                        var ipp = myJson.data.itemsPerPage;
                        var start = myJson.data.startIndex;

                        if( start == 1 && total == 0) {
                            self.noResults('#ytb-usr-results');
                        } else {
                            $.tmpl('livedesk>providers/youtube/clip-item', {results : self.cleanContent(results)}, function(e,o) {
                                $('#ytb-usr-results').append(o).find('.youtube').draggable({
                                    revert: 'invalid',
                                    helper: 'clone',
                                    appendTo: 'body',
                                    zIndex: 2700,
                                    clone: true,
                                    start: function() {
                                        var idx = parseInt($(this).attr('idx'),10);
                                        $(this).data('data', self.adaptor.universal( results[idx] ));
                                    }
                                });
                            });
                        }

                        if (parseInt(start + ipp) < total) {
                            $('#ytb-usr-more').tmpl('livedesk>providers/load-more', {
                                name : 'ytb-usr-load-more'
                            }, function(){
                                $(this).find('[name="ytb-usr-load-more"]').on('click', function(){
                                    self.doUsers(parseInt(start + ipp));
                                });
                            });
                        }
                    },
                    error : function(data){
                        self.noResults('#ytb-usr-results');
                    }
                }).fail(function() {
                    self.stopLoading('#ytb-usr-more');
                    self.noResults('#ytb-usr-results');
                });

            }
        });
        return providers;
    });<|endoftext|>