<commit_before>/*****************************************************
* #### Chat Realtime (BETA) ####
* Coded by Ican Bachors 2016.
* http://ibacor.com/labs/chat-realtime
* Updates will be posted to this site.
* Aplikasi ini akan selalu bersetatus (BETA)
* Karena akan terus di update & dikembangkan.
* Maka dari itu jangan lupa di fork & like ya sob :).
*****************************************************/

var chat_realtime = function(j, k, l, m, n) {

    userMysql();

    j.on("child_added", function(a) {
        console.log("added", a.key(), a.val());
        if (a.val().tipe == 'login') {
            if (a.val().name != m) {
                if ($('#' + a.val().name).length) {
                    $('#' + a.val().name + ' .fa-circle').addClass('online');
                    $('#' + a.val().name + ' .time').html(timing(new Date(a.val().login)))
                } else {
                    var b = '
';
                    b += '	';
                    b += '		';
                    b += '
';
                    b += '			 ' + a.val().name + '';
                    b += '
';
                    b += '

';
                    b += '		' + timing(new Date(a.val().login)) + '';
                    b += '		0';
                    b += '	';
                    b += '
';
                    $('.users-list').prepend(b)
                }
            }
        } else {
            $('#' + a.val().name + ' .fa-circle').removeClass('online')
        }
        j.child(a.key()).remove()
    });

    k.on("child_added", function(a) {
        console.log("added", a.key(), a.val());
        var b = a.val().name,
            ke = a.val().ke;
        if (ke == m) {
            document.querySelector('#' + b + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + b + ' .last-message').innerHTML = ' ' + htmlEntities(a.val().message);
            if ($('#' + b).hasClass('active')) {
                document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
            } else {
                $('#' + b + ' .chat-alert').show();
                document.querySelector('#' + b + ' .chat-alert').innerHTML = (parseInt(document.querySelector('#' + b + ' .chat-alert').innerHTML) + 1)
            }
        } else if (ke != m && $('#' + ke).data('tipe') == 'rooms') {
            document.querySelector('#' + ke + ' strong').innerHTML = a.val().name;
            document.querySelector('#' + ke + ' img').src = a.val().avatar;
            document.querySelector('#' + ke + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + ke + ' .last-message').innerHTML = htmlEntities(a.val().message);
            if ($('#' + ke).hasClass('active')) {
                document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
            } else {
                $('#' + ke + ' .chat-alert').show();
                document.querySelector('#' + ke + ' .chat-alert').innerHTML = (parseInt(document.querySelector('#' + ke + ' .chat-alert').innerHTML) + 1)
            }
        } else if (b == m) {
            document.querySelector('#' + ke + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + ke + ' .last-message').innerHTML = ' ' + htmlEntities(a.val().message);
            document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
        }
        var c = $('.chat');
        var d = c[0].scrollHeight;
        c.scrollTop(d);
        k.child(a.key()).remove()
    });

    document.querySelector('#send').addEventListener("click", function(h) {
        var a = new Date(),
            b = a.getDate(),
            c = (a.getMonth() + 1),
            d = a.getFullYear(),
            e = a.getHours(),
            f = a.getMinutes(),
            g = a.getSeconds(),
            date = d + '-' + (c < 10 ? '0' + c : c) + '-' + (b < 10 ? '0' + b : b) + ' ' + (e < 10 ? '0' + e : e) + ':' + (f < 10 ? '0' + f : f) + ':' + (g < 10 ? '0' + g : g);
        h.preventDefault();
        if (document.querySelector('#message').value != '') {
            var i = {
                data: 'send',
                name: m,
                ke: document.querySelector('#ke').value,
                avatar: n,
                message: document.querySelector('#message').value,
                tipe: document.querySelector('#tipe').value,
                date: date
            };
            k.push(i);
            $.ajax({
                url: l,
                type: "post",
                data: i,
                crossDomain: true
            });
            document.querySelector('#message').value = ''
        } else {
            alert('Please fill atlease message!')
        }
    }, false);

    $('body').on('click', '.user', function() {
        $('.chat').html('');
        $('.user').removeClass("active");
        $(this).addClass("active");
        var a = $(this).attr('id'),
            tipe = $(this).data('tipe');
        $('#' + a + ' .chat-alert').hide();
        $('#' + a + ' .chat-alert').html(0);
        $("#ke").val(a);
        $("#tipe").val(tipe);
        chatMysql(tipe, a);
        return false
    });

    function userMysql() {
        $.ajax({
            url: l,
            type: "post",
            data: 'data=user',
            crossDomain: true,
            dataType: 'json',
            success: function(a) {
                var b = '';
                $.each(a, function(i, a) {
                    if (a.name != m) {
                        b += '
';
                        b += '	';
                        b += '		';
                        b += '
';
                        b += '			 ' + a.name + '';
                        b += '
';
                        b += '

';
                        b += '		' + timing(new Date(a.login)) + '';
                        b += '		0';
                        b += '	';
                        b += '
'
                    }
                });
                $('.users-list').html(b);
                chatMysql('rooms', 'all');
                chatMysql('users', 'all')
            }
        })
    }

    function chatFirebase(a) {
        console.log(a);
        var b = '';
        if (a.name == m) {
            b = '
' + '' + '' + '' + '
' + '
' + htmlEntities(a.message) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
        } else {
            b = '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + htmlEntities(a.message) + '
' + '
' + '
'
        }
        return b
    }

    function chatMysql(e, f) {
        $.ajax({
            url: l,
            type: "post",
            data: {
                data: 'message',
                ke: f,
                tipe: e
            },
            crossDomain: true,
            dataType: 'json',
            success: function(a) {
                var b = '';
                if (f == 'all') {
                    $.each(a, function(i, a) {
                        if ($('#' + a.selektor).hasClass('active')) {
                            if (a.name == m) {
                                b += '
' + '' + '' + '' + '
' + '
' + htmlEntities(a.message) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
                            } else {
                                b += '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + htmlEntities(a.message) + '
' + '
' + '
'
                            }
                            $('.chat').html(b)
                        }
                        if (a.tipe == 'rooms') {
                            document.querySelector('#' + a.selektor + ' strong').innerHTML = a.name;
                            document.querySelector('#' + a.selektor + ' img').src = a.avatar;
                            document.querySelector('#' + a.selektor + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + a.selektor + ' .last-message').innerHTML = htmlEntities(a.message)
                        } else if (a.tipe == 'users') {
                            document.querySelector('#' + a.selektor + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + a.selektor + ' .last-message').innerHTML = (a.name == m ? ' ' + htmlEntities(a.message) : ' ' + htmlEntities(a.message))
                        }
                    })
                } else {
                    $.each(a, function(i, a) {
                        if (a.name == m) {
                            b += '
' + '' + '' + '' + '
' + '
' + htmlEntities(a.message) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
                        } else {
                            b += '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + htmlEntities(a.message) + '
' + '
' + '
'
                        }
                        if (a.tipe == 'rooms') {
                            document.querySelector('#' + f + ' strong').innerHTML = a.name;
                            document.querySelector('#' + f + ' img').src = a.avatar;
                            document.querySelector('#' + f + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + f + ' .last-message').innerHTML = htmlEntities(a.message)
                        } else if (a.tipe == 'users') {
                            document.querySelector('#' + f + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + f + ' .last-message').innerHTML = (a.name == m ? ' ' + htmlEntities(a.message) : ' ' + htmlEntities(a.message))
                        }
                    });
                    $('.chat').html(b)
                }
                var c = $('.chat');
                var d = c[0].scrollHeight;
                c.scrollTop(d)
            }
        })
    }

    function htmlEntities(a) {
        return String(a).replace(/</g, '<').replace(/>/g, '>')
    }

    function timing(a) {
        var s = Math.floor((new Date() - a) / 1000),
            i = Math.floor(s / 31536000);
        if (i > 1) {
            return i + " yrs ago"
        }
        i = Math.floor(s / 2592000);
        if (i > 1) {
            return i + " mon ago"
        }
        i = Math.floor(s / 86400);
        if (i > 1) {
            return i + " dys ago"
        }
        i = Math.floor(s / 3600);
        if (i > 1) {
            return i + " hrs ago"
        }
        i = Math.floor(s / 60);
        if (i > 1) {
            return i + " min ago"
        }
        return (Math.floor(s) > 0 ? Math.floor(s) + " sec ago" : "just now")
    }

}
<commit_msg>add link, email & emoticon<commit_after>/*****************************************************
* #### Chat Realtime (BETA) ####
* Coded by Ican Bachors 2016.
* http://ibacor.com/labs/chat-realtime
* Updates will be posted to this site.
* Aplikasi ini akan selalu bersetatus (BETA)
* Karena akan terus di update & dikembangkan.
* Maka dari itu jangan lupa di fork & like ya sob :).
*****************************************************/

var chat_realtime = function(j, k, l, m, n) {

    userMysql();

    j.on("child_added", function(a) {
        console.log("added", a.key(), a.val());
        if (a.val().tipe == 'login') {
            if (a.val().name != m) {
                if ($('#' + a.val().name).length) {
                    $('#' + a.val().name + ' .fa-circle').addClass('online');
                    $('#' + a.val().name + ' .time').html(timing(new Date(a.val().login)))
                } else {
                    var b = '
';
                    b += '	';
                    b += '		';
                    b += '
';
                    b += '			 ' + a.val().name + '';
                    b += '
';
                    b += '

';
                    b += '		' + timing(new Date(a.val().login)) + '';
                    b += '		0';
                    b += '	';
                    b += '
';
                    $('.users-list').prepend(b)
                }
            }
        } else {
            $('#' + a.val().name + ' .fa-circle').removeClass('online')
        }
        j.child(a.key()).remove()
    });

    k.on("child_added", function(a) {
        console.log("added", a.key(), a.val());
        var b = a.val().name,
            ke = a.val().ke;
        if (ke == m) {
            document.querySelector('#' + b + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + b + ' .last-message').innerHTML = ' ' + htmlEntities(a.val().message);
            if ($('#' + b).hasClass('active')) {
                document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
            } else {
                $('#' + b + ' .chat-alert').show();
                document.querySelector('#' + b + ' .chat-alert').innerHTML = (parseInt(document.querySelector('#' + b + ' .chat-alert').innerHTML) + 1)
            }
        } else if (ke != m && $('#' + ke).data('tipe') == 'rooms') {
            document.querySelector('#' + ke + ' strong').innerHTML = a.val().name;
            document.querySelector('#' + ke + ' img').src = a.val().avatar;
            document.querySelector('#' + ke + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + ke + ' .last-message').innerHTML = htmlEntities(a.val().message);
            if ($('#' + ke).hasClass('active')) {
                document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
            } else {
                $('#' + ke + ' .chat-alert').show();
                document.querySelector('#' + ke + ' .chat-alert').innerHTML = (parseInt(document.querySelector('#' + ke + ' .chat-alert').innerHTML) + 1)
            }
        } else if (b == m) {
            document.querySelector('#' + ke + ' .time').innerHTML = timing(new Date(a.val().date));
            document.querySelector('#' + ke + ' .last-message').innerHTML = ' ' + htmlEntities(a.val().message);
            document.querySelector('.chat').innerHTML += (chatFirebase(a.val()))
        }
        var c = $('.chat');
        var d = c[0].scrollHeight;
        c.scrollTop(d);
        k.child(a.key()).remove()
    });

    document.querySelector('#send').addEventListener("click", function(h) {
        var a = new Date(),
            b = a.getDate(),
            c = (a.getMonth() + 1),
            d = a.getFullYear(),
            e = a.getHours(),
            f = a.getMinutes(),
            g = a.getSeconds(),
            date = d + '-' + (c < 10 ? '0' + c : c) + '-' + (b < 10 ? '0' + b : b) + ' ' + (e < 10 ? '0' + e : e) + ':' + (f < 10 ? '0' + f : f) + ':' + (g < 10 ? '0' + g : g);
        h.preventDefault();
        if (document.querySelector('#message').value != '') {
            var i = {
                data: 'send',
                name: m,
                ke: document.querySelector('#ke').value,
                avatar: n,
                message: document.querySelector('#message').value,
                tipe: document.querySelector('#tipe').value,
                date: date
            };
            k.push(i);
            $.ajax({
                url: l,
                type: "post",
                data: i,
                crossDomain: true
            });
            document.querySelector('#message').value = ''
        } else {
            alert('Please fill atlease message!')
        }
    }, false);

    $('body').on('click', '.user', function() {
        $('.chat').html('');
        $('.user').removeClass("active");
        $(this).addClass("active");
        var a = $(this).attr('id'),
            tipe = $(this).data('tipe');
        $('#' + a + ' .chat-alert').hide();
        $('#' + a + ' .chat-alert').html(0);
        $("#ke").val(a);
        $("#tipe").val(tipe);
        chatMysql(tipe, a);
        return false
    });

    function userMysql() {
        $.ajax({
            url: l,
            type: "post",
            data: 'data=user',
            crossDomain: true,
            dataType: 'json',
            success: function(a) {
                var b = '';
                $.each(a, function(i, a) {
                    if (a.name != m) {
                        b += '
';
                        b += '	';
                        b += '		';
                        b += '
';
                        b += '			 ' + a.name + '';
                        b += '
';
                        b += '

';
                        b += '		' + timing(new Date(a.login)) + '';
                        b += '		0';
                        b += '	';
                        b += '
'
                    }
                });
                $('.users-list').html(b);
                chatMysql('rooms', 'all');
                chatMysql('users', 'all')
            }
        })
    }

    function chatFirebase(a) {
        console.log(a);
        var b = '';
        if (a.name == m) {
            b = '
' + '' + '' + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
        } else {
            b = '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + '
' + '
'
        }
        return b
    }

    function chatMysql(e, f) {
        $.ajax({
            url: l,
            type: "post",
            data: {
                data: 'message',
                ke: f,
                tipe: e
            },
            crossDomain: true,
            dataType: 'json',
            success: function(a) {
                var b = '';
                if (f == 'all') {
                    $.each(a, function(i, a) {
                        if ($('#' + a.selektor).hasClass('active')) {
                            if (a.name == m) {
                                b += '
' + '' + '' + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
                            } else {
                                b += '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + '
' + '
'
                            }
                            $('.chat').html(b)
                        }
                        if (a.tipe == 'rooms') {
                            document.querySelector('#' + a.selektor + ' strong').innerHTML = a.name;
                            document.querySelector('#' + a.selektor + ' img').src = a.avatar;
                            document.querySelector('#' + a.selektor + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + a.selektor + ' .last-message').innerHTML = htmlEntities(a.message)
                        } else if (a.tipe == 'users') {
                            document.querySelector('#' + a.selektor + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + a.selektor + ' .last-message').innerHTML = (a.name == m ? ' ' + htmlEntities(a.message) : ' ' + htmlEntities(a.message))
                        }
                    })
                } else {
                    $.each(a, function(i, a) {
                        if (a.name == m) {
                            b += '
' + '' + '' + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + ' ' + timing(new Date(a.date)) + '' + '
' + '
'
                        } else {
                            b += '
' + '' + '' + '' + '
' + '
' + '' + a.name + '' + ' ' + timing(new Date(a.date)) + '' + '
' + '
' + urltag(htmlEntities(a.message)) + '
' + '
' + '
'
                        }
                        if (a.tipe == 'rooms') {
                            document.querySelector('#' + f + ' strong').innerHTML = a.name;
                            document.querySelector('#' + f + ' img').src = a.avatar;
                            document.querySelector('#' + f + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + f + ' .last-message').innerHTML = htmlEntities(a.message)
                        } else if (a.tipe == 'users') {
                            document.querySelector('#' + f + ' .time').innerHTML = timing(new Date(a.date));
                            document.querySelector('#' + f + ' .last-message').innerHTML = (a.name == m ? ' ' + htmlEntities(a.message) : ' ' + htmlEntities(a.message))
                        }
                    });
                    $('.chat').html(b)
                }
                var c = $('.chat');
                var d = c[0].scrollHeight;
                c.scrollTop(d)
            }
        })
    }

    function htmlEntities(a) {
        return String(a).replace(/</g, '<').replace(/>/g, '>')
    }

    function timing(a) {
        var s = Math.floor((new Date() - a) / 1000),
            i = Math.floor(s / 31536000);
        if (i > 1) {
            return i + " yrs ago"
        }
        i = Math.floor(s / 2592000);
        if (i > 1) {
            return i + " mon ago"
        }
        i = Math.floor(s / 86400);
        if (i > 1) {
            return i + " dys ago"
        }
        i = Math.floor(s / 3600);
        if (i > 1) {
            return i + " hrs ago"
        }
        i = Math.floor(s / 60);
        if (i > 1) {
            return i + " min ago"
        }
        return (Math.floor(s) > 0 ? Math.floor(s) + " sec ago" : "just now")
    }

	function urltag(d, e) {
        var f = {
            link: {
                regex: /((^|)(https|http|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
                template: "$1"
            },
            email: {
                regex: /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,
                template: '$1'
            },
            smile: {
                regex: /(^|):\)/gi,
                template: ''
            },
            cool: {
                regex: /(^|)B\)/gi,
                template: ''
            },
            lol: {
                regex: /(^|):v/gi,
                template: ''
            },
            haha: {
                regex: /(^|):D/gi,
                template: ''
            },
            sad: {
                regex: /(^|):\(/gi,
                template: ''
            },
            like: {
                regex: /(^|)\(y\)/gi,
                template: ''
            }
        };
        var g = $.extend(f, e);
        $.each(g, function(a, b) {
            d = d.replace(b.regex, b.template)
        });
        return d
    }

}
<|endoftext|>


<commit_before>/* jshint -W051, -W020 */
/* global global:true, window, require */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / @brief ArangoShell client API
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Achim Brandt
// / @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

if (typeof global === 'undefined' && typeof window !== 'undefined') {
  global = window;
}

// //////////////////////////////////////////////////////////////////////////////
// @brief common globals
// //////////////////////////////////////////////////////////////////////////////

global.Buffer = require('buffer').Buffer;
global.process = require('process');
global.setInterval = global.setInterval || function () {};
global.clearInterval = global.clearInterval || function () {};
global.setTimeout = global.setTimeout || function () {};
global.clearTimeout = global.clearTimeout || function () {};

// //////////////////////////////////////////////////////////////////////////////
// / @brief start paging
// //////////////////////////////////////////////////////////////////////////////

global.start_pager = function start_pager () {
  var internal = require('internal');
  internal.startPager();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief stop paging
// //////////////////////////////////////////////////////////////////////////////

global.stop_pager = function stop_pager () {
  var internal = require('internal');
  internal.stopPager();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief print the overall help
// //////////////////////////////////////////////////////////////////////////////

global.help = function help () {
  var internal = require('internal');
  var arangodb = require('@arangodb');
  var arangosh = require('@arangodb/arangosh');

  internal.print(arangosh.HELP);
  arangodb.ArangoDatabase.prototype._help();
  arangodb.ArangoCollection.prototype._help();
  arangodb.ArangoStatement.prototype._help();
  arangodb.ArangoQueryCursor.prototype._help();
  internal.print(arangosh.helpExtended);
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief clear screen (poor man's way)
// //////////////////////////////////////////////////////////////////////////////

global.clear = function clear () {
  var internal = require('internal');
  var result = '';

  for (var i = 0; i < 100; ++i) {
    result += '\n';
  }
  internal.print(result);
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'console'
// //////////////////////////////////////////////////////////////////////////////

global.console = global.console || require('console');

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'db'
// //////////////////////////////////////////////////////////////////////////////

global.db = require('@arangodb').db;

// //////////////////////////////////////////////////////////////////////////////
// / @brief template string generator for building an AQL query
// //////////////////////////////////////////////////////////////////////////////

global.aql = global.aqlQuery = require('@arangodb').aql;

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'arango'
// //////////////////////////////////////////////////////////////////////////////

global.arango = require('@arangodb').arango;

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'fm'
// //////////////////////////////////////////////////////////////////////////////

global.fm = require('@arangodb/foxx/manager');

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'ArangoStatement'
// //////////////////////////////////////////////////////////////////////////////

global.ArangoStatement = require('@arangodb/arango-statement').ArangoStatement;

// //////////////////////////////////////////////////////////////////////////////
// / @brief shell tutorial
// //////////////////////////////////////////////////////////////////////////////

global.tutorial = require('@arangodb/tutorial');

let withTimeout = function(connection, timeout, cb) {
  if (!connection) {
    return;
  }
  let oldTimeout = connection.timeout();
  try {
    try {
      connection.timeout(timeout);
    } catch (err) {}
    return cb();
  } finally {
    try {
      connection.timeout(oldTimeout);
    } catch (err) {}
  }
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief prints help
// //////////////////////////////////////////////////////////////////////////////

var initHelp = function () {
  var internal = require('internal');

  if (internal.db) {
    try {
      // cap request timeout to 10 seconds for initially fetching
      // the list of collections
      // this allows going on and using the arangosh even if the list
      // of collections cannot be fetched in sensible time
      withTimeout(internal.db._connection, 10, function() {
        internal.db._collections();
      });
    } catch (e) {}
  }

  if (internal.quiet !== true) {
    require('@arangodb').checkAvailableVersions();

    if (internal.arango && internal.arango.isConnected && internal.arango.isConnected()) {
      internal.print("Type 'tutorial' for a tutorial or 'help' to see common examples");
    }
  }
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief read rc file
// //////////////////////////////////////////////////////////////////////////////

if (typeof window === 'undefined') {
  // We're in arangosh
  initHelp();
  // these variables are not defined in the browser context
  if (!(
    global.IS_EXECUTE_SCRIPT ||
    global.IS_EXECUTE_STRING ||
    global.IS_CHECK_SCRIPT ||
    global.IS_UNIT_TESTS ||
    global.IS_JS_LINT
    )) {
    try {
      // this will not work from within a browser
      var __fs__ = require('fs');
      var __rcf__ = __fs__.join(__fs__.home(), '.arangosh.rc');

      if (__fs__.exists(__rcf__)) {
        /* jshint evil: true */
        var __content__ = __fs__.read(__rcf__);
        eval(__content__);
      }
    } catch (e) {
      require('console').warn('arangosh.rc: %s', String(e));
    }
  }

  delete global.IS_EXECUTE_SCRIPT;
  delete global.IS_EXECUTE_STRING;
  delete global.IS_CHECK_SCRIPT;
  delete global.IS_UNIT_TESTS;
  delete global.IS_JS_LINT;
}
<commit_msg>use log level debug for startup warnings<commit_after>/* jshint -W051, -W020 */
/* global global:true, window, require */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / @brief ArangoShell client API
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Achim Brandt
// / @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

if (typeof global === 'undefined' && typeof window !== 'undefined') {
  global = window;
}

// //////////////////////////////////////////////////////////////////////////////
// @brief common globals
// //////////////////////////////////////////////////////////////////////////////

global.Buffer = require('buffer').Buffer;
global.process = require('process');
global.setInterval = global.setInterval || function () {};
global.clearInterval = global.clearInterval || function () {};
global.setTimeout = global.setTimeout || function () {};
global.clearTimeout = global.clearTimeout || function () {};

// //////////////////////////////////////////////////////////////////////////////
// / @brief start paging
// //////////////////////////////////////////////////////////////////////////////

global.start_pager = function start_pager () {
  var internal = require('internal');
  internal.startPager();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief stop paging
// //////////////////////////////////////////////////////////////////////////////

global.stop_pager = function stop_pager () {
  var internal = require('internal');
  internal.stopPager();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief print the overall help
// //////////////////////////////////////////////////////////////////////////////

global.help = function help () {
  var internal = require('internal');
  var arangodb = require('@arangodb');
  var arangosh = require('@arangodb/arangosh');

  internal.print(arangosh.HELP);
  arangodb.ArangoDatabase.prototype._help();
  arangodb.ArangoCollection.prototype._help();
  arangodb.ArangoStatement.prototype._help();
  arangodb.ArangoQueryCursor.prototype._help();
  internal.print(arangosh.helpExtended);
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief clear screen (poor man's way)
// //////////////////////////////////////////////////////////////////////////////

global.clear = function clear () {
  var internal = require('internal');
  var result = '';

  for (var i = 0; i < 100; ++i) {
    result += '\n';
  }
  internal.print(result);
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'console'
// //////////////////////////////////////////////////////////////////////////////

global.console = global.console || require('console');

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'db'
// //////////////////////////////////////////////////////////////////////////////

global.db = require('@arangodb').db;

// //////////////////////////////////////////////////////////////////////////////
// / @brief template string generator for building an AQL query
// //////////////////////////////////////////////////////////////////////////////

global.aql = global.aqlQuery = require('@arangodb').aql;

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'arango'
// //////////////////////////////////////////////////////////////////////////////

global.arango = require('@arangodb').arango;

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'fm'
// //////////////////////////////////////////////////////////////////////////////

global.fm = require('@arangodb/foxx/manager');

// //////////////////////////////////////////////////////////////////////////////
// / @brief global 'ArangoStatement'
// //////////////////////////////////////////////////////////////////////////////

global.ArangoStatement = require('@arangodb/arango-statement').ArangoStatement;

// //////////////////////////////////////////////////////////////////////////////
// / @brief shell tutorial
// //////////////////////////////////////////////////////////////////////////////

global.tutorial = require('@arangodb/tutorial');

let withTimeout = function(connection, timeout, cb) {
  if (!connection) {
    return;
  }
  let oldTimeout = connection.timeout();
  try {
    try {
      connection.timeout(timeout);
    } catch (err) {}
    return cb();
  } finally {
    try {
      connection.timeout(oldTimeout);
    } catch (err) {}
  }
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief prints help
// //////////////////////////////////////////////////////////////////////////////

var initHelp = function () {
  var internal = require('internal');

  if (internal.db) {
    try {
      // cap request timeout to 10 seconds for initially fetching
      // the list of collections
      // this allows going on and using the arangosh even if the list
      // of collections cannot be fetched in sensible time
      withTimeout(internal.db._connection, 10, function() {
        internal.db._collections();
      });
    } catch (e) {}
  }

  if (internal.quiet !== true) {
    require('@arangodb').checkAvailableVersions();

    if (internal.arango && internal.arango.isConnected && internal.arango.isConnected()) {
      internal.print("Type 'tutorial' for a tutorial or 'help' to see common examples");
    }
  }
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief read rc file
// //////////////////////////////////////////////////////////////////////////////

if (typeof window === 'undefined') {
  // We're in arangosh
  initHelp();
  // these variables are not defined in the browser context
  if (!(
    global.IS_EXECUTE_SCRIPT ||
    global.IS_EXECUTE_STRING ||
    global.IS_CHECK_SCRIPT ||
    global.IS_UNIT_TESTS ||
    global.IS_JS_LINT
    )) {
    try {
      // this will not work from within a browser
      let __fs__ = require('fs');
      let __rcf__ = __fs__.join(__fs__.home(), '.arangosh.rc');

      if (__fs__.exists(__rcf__)) {
        /* jshint evil: true */
        let __content__ = __fs__.read(__rcf__);
        eval(__content__);
      }
    } catch (e) {
      require('console').debug('arangosh.rc: %s', String(e));
    }
  }

  delete global.IS_EXECUTE_SCRIPT;
  delete global.IS_EXECUTE_STRING;
  delete global.IS_CHECK_SCRIPT;
  delete global.IS_UNIT_TESTS;
  delete global.IS_JS_LINT;
}
<|endoftext|>


<commit_before>/* global jQuery, chrome, _, Promise */

var $ = jQuery;
var NEXT_TASK_WAIT = 100;

chrome.runtime.onMessage.addListener(function( msg, sender, sendResponse ) {

    var msgType = msg && msg.type;

    if ( msgType === 'run-task' ) {

        runTasks();
    }
});

// if tasks still left run next
chrome.runtime.sendMessageAsync({
    type: 'load-tasks'
}).then(function( res ) {

    if ( res && Array.isArray( res.tasks ) && res.tasks.length ) {

        runNextTask();
        return;
    }

    chrome.runtime.sendMessageAsync({
        type: 'is-run-onload'
    }).then(( res ) => {

        // run on reload
        res && runTasks();
    });
});

// function

function runTasks() {

    chrome.storage.local.get(['tasks', 'jobs', 'selectedJobId'], function( storage ) {

        var selectedJob, runningTasks;

        if ( !storage.jobs || !storage.jobs.length ) {

            return;
        }

        selectedJob = storage.jobs.find(function( v ) {

            return v.jobId === storage.selectedJobId;
        });

        // remove disabled task
        runningTasks = ( selectedJob.tasks || []).filter(function( v ) {

            return !v.disabled;
        });

        chrome.runtime.sendMessageAsync({
            type: 'save-running-tasks',
            data: runningTasks
        }).then(function() {

            return chrome.runtime.sendMessageAsync({
                type: 'listen-connection-changed'
            });
        }).then( runNextTask );
    });
}

function runNextTask() {

    var task;
    var promise = waitConn().then(function() {

        return chrome.runtime.sendMessageAsync({
            type: 'next-task'
        }).then(function( res ) {

            if ( !res || !res.task ) {

                chrome.runtime.sendMessage({
                    type: 'ignore-connection-changed'
                });
                promise.cancel();
            } else {

                task = res.task;
            }

            return null;
        });
    }).then(function() {

        // wait process
        return new Promise(function( resolve ) {

            setTimeout( resolve, ( isNaN( +task.wait ) ? 0 : +task.wait ) + NEXT_TASK_WAIT );
        });
    }).then(function() {

        return execTask( task );
    }).then(function() {

        runNextTask();
        return null;
    }).catch(function() {

        return chrome.runtime.sendMessage({
            type: 'task-failed'
        });
    });
}

function execTask( task ) {

    var $ele = $( task.selector );
    var ele = $ele[0];

    if ( task.type === 'url' ) {

        window.location.href = task.data;
        return end();
    }

    if ( !ele ) {

        console.error( 'Element not found', task );
        return Promise.reject( new Error( 'Element not found' ));
    }

    if ( task.type === 'click' || task.type === 'dblclick' ) {

        ele.dispatchEvent( new MouseEvent( task.type, {
            bubbles: true
        } ));

    } else if ( task.type === 'val' ) {

        $ele.val( task.data );

        ele.dispatchEvent( new Event( 'change' ));
    } else if ( task.type === 'text' ) {

        $ele.text( task.data );
    } else if ( task.type === 'html' ) {

        $ele.html( task.data );
    }

    return end();

    function end() {

        return new Promise(function( resolve ) {

            setTimeout(function() {

                resolve();
            }, 1 );
        });
    }
}

function waitConn() {

    return new Promise(function( resolve, reject ) {

        conn(function( res ) {

            // console.warn( 'wait conn resolved.' );

            resolve( res );
        });
    });

    function conn( cb ) {

        setTimeout(function() {

            chrome.runtime.sendMessage({
                type: 'get-connection'
            }, function( res ) {

                var counted = _.countBy( res, function( v ) {

                    return v.state;
                });

                if ( !counted.before || counted.before.length ) {

                    cb( counted );
                } else {

                    conn( cb );
                }

            });
        }, 100 );
    }
}
<commit_msg>bug fix<commit_after>/* global jQuery, chrome, _, Promise */

var $ = jQuery;
var NEXT_TASK_WAIT = 100;

chrome.runtime.onMessage.addListener(function( msg, sender, sendResponse ) {

    var msgType = msg && msg.type;

    if ( msgType === 'run-task' ) {

        runTasks();
    }
});

// if tasks still left run next
chrome.runtime.sendMessageAsync({
    type: 'load-tasks'
}).then(function( res ) {

    if ( res && Array.isArray( res.tasks ) && res.tasks.length ) {

        runNextTask();
        return;
    }

    chrome.runtime.sendMessageAsync({
        type: 'is-run-onload'
    }).then(( res ) => {

        // run on reload
        res && runTasks();
    });
});

// function

function runTasks() {

    chrome.storage.local.get(['tasks', 'jobs', 'selectedJobId'], function( storage ) {

        var selectedJob, runningTasks;

        if ( !storage.jobs || !storage.jobs.length ) {

            return;
        }

        selectedJob = storage.jobs.find(function( v ) {

            return v.jobId === storage.selectedJobId;
        });

        // remove disabled task
        runningTasks = ( selectedJob.tasks || []).filter(function( v ) {

            return !v.disabled;
        });

        chrome.runtime.sendMessageAsync({
            type: 'save-running-tasks',
            data: runningTasks
        }).then(function() {

            return chrome.runtime.sendMessageAsync({
                type: 'listen-connection-changed'
            });
        }).then( runNextTask );
    });
}

function runNextTask() {

    var task;
    var promise = waitConn().then(function() {

        return chrome.runtime.sendMessageAsync({
            type: 'next-task'
        }).then(function( res ) {

            if ( !res || !res.task ) {

                chrome.runtime.sendMessage({
                    type: 'ignore-connection-changed'
                });
                promise.cancel();
            } else {

                task = res.task;
            }

            return null;
        });
    }).then(function() {

        // wait process
        return new Promise(function( resolve ) {

            setTimeout( resolve, ( isNaN( +task.wait ) ? 0 : +task.wait ) + NEXT_TASK_WAIT );
        });
    }).then(function() {

        return execTask( task );
    }).then(function() {

        runNextTask();
        return null;
    }).catch(function() {

        return chrome.runtime.sendMessage({
            type: 'task-failed'
        });
    });
}

function execTask( task ) {

    var $ele;
    var ele;

    if ( task.type === 'url' ) {

        window.location.href = task.data;
        return end();
    }

    $ele = $( task.selector );
    ele = $ele[0];

    if ( !ele ) {

        console.error( 'Element not found', task );
        return Promise.reject( new Error( 'Element not found' ));
    }

    if ( task.type === 'click' || task.type === 'dblclick' ) {

        ele.dispatchEvent( new MouseEvent( task.type, {
            bubbles: true,
            cancelable: true,
            view: window
        }));

    } else if ( task.type === 'val' ) {

        $ele.val( task.data );

        ele.dispatchEvent( new Event( 'change' ));
    } else if ( task.type === 'text' ) {

        $ele.text( task.data );
    } else if ( task.type === 'html' ) {

        $ele.html( task.data );
    }

    return end();

    function end() {

        return new Promise(function( resolve ) {

            setTimeout(function() {

                resolve();
            }, 1 );
        });
    }
}

function waitConn() {

    return new Promise(function( resolve, reject ) {

        conn(function( res ) {

            // console.warn( 'wait conn resolved.' );

            resolve( res );
        });
    });

    function conn( cb ) {

        setTimeout(function() {

            chrome.runtime.sendMessage({
                type: 'get-connection'
            }, function( res ) {

                var counted = _.countBy( res, function( v ) {

                    return v.state;
                });

                if ( !counted.before || counted.before.length ) {

                    cb( counted );
                } else {

                    conn( cb );
                }

            });
        }, 100 );
    }
}
<|endoftext|>


<commit_before>define(["js/core/EventDispatcher", "js/lib/parser", "js/core/Binding","underscore"],
    function (EventDispatcher, Parser, Binding, _) {

        // global invalidation timer

        var globalInvalidationQueue = (function() {

            var id,
                callbacks = [],
                work = function() {
                    for (var i = 0; i < callbacks.length; i++) {
                        try {
                            callbacks[i]();
                        } catch (e) {
                            (console.warn || console.log).call(console, e);
                        }
                    }

                    callbacks = [];
                    id = null;
                };

            return {
                addCallback: function(callback) {
                    callbacks.push(callback);

                    if (!id) {
                        id = setTimeout(work, 1000 / 60);
                    }
                }
            }
        })();

        var Bindable = EventDispatcher.inherit("js.core.Bindable",
            {
                /***
                 * creates a new instance of bindable, which can be bound to components
                 *
                 * @param {Object} [attributes] the default attributes which will be set during instantiation
                 */
                ctor: function (attributes) {
                    this.$eventBindables = [];

                    // call the base class constructor
                    this.callBase(null);

                    this.$ = {};
                    this.$invalidatedProperties = {};
                    this.$invalidated = false;

                    _.extend(this._eventAttributes, this.base._eventAttributes || {});

                    attributes = attributes || {};

                    var defaultAttributes = this._defaultAttributes();
                    for (var key in defaultAttributes) {
                        if (defaultAttributes.hasOwnProperty(key)) {
                            if (!attributes.hasOwnProperty(key)) {
                                if (_.isFunction(defaultAttributes[key])) {
                                    // Function as default -> construct new Object
                                    attributes[key] = new (defaultAttributes[key])();
                                } else {
                                    attributes[key] = _.clone(defaultAttributes[key]);
                                }
                            }
                        }
                    }

                    this.$ = attributes;
                    // TODO: clone and keep prototype for attribute the same -> write own clone method
                    this.$previousAttributes = _.clone(attributes);

                },
                /**
                 * Here you can define the default attributes of the instance.
                 *
                 * @static
                 */
                defaults: {
                },

                /***
                 *
                 * @return {Object} returns the default attributes and includes the defaults from base classes
                 * @private
                 */
                _defaultAttributes: function () {
                    return this._generateDefaultsChain("defaults");
                },

                /***
                 * generates a default chain containing the values from this instance and base classes
                 *
                 * @param {String} property - the name of the static property used to find defaults
                 * @return {*}
                 * @private
                 */
                _generateDefaultsChain: function (property) {
                    var ret = this[property],
                        base = this.base;

                    while (base) {
                        _.defaults(ret, base[property]);
                        base = base.base;
                    }

                    return ret;
                },

                /**
                 * Sets new values for attributes and notify about changes
                 *
                 * @param {String} key The attribute key
                 * @param {String} value The attribute value
                 * @param {Object} options A hash of options
                 * @param {Boolean} [options.silent=false] if true no event is triggered on change
                 * @param {Boolean} [options.unset=false] if true the attribute gets deleted
                 */
                set: function (key, value, options) {
                    var attributes = {};

                    if (_.isString(key)) {
                        // check for path
                        var path = key.split(".");
                        if (path.length > 1) {
                            var scope = this.get(path.shift());
                            if (scope && scope.set) {
                                scope.set(path.join("."), value, options);
                                return this;
                            }

                        }

                        attributes[key] = value;
                    } else {
                        options = value;
                        attributes = key;
                    }

                    options = options || {silent: false, unset: false};

                    // for un-setting attributes
                    if (options.unset) {
                        for (key in attributes) {
                            if (attributes.hasOwnProperty(key)) {
                                attributes[key] = void 0;
                            }
                        }
                    }

                    var changedAttributes = {},
                        changedAttributesCount = 0,
                        now = this.$,
                        val, prev;

                    for (key in attributes) {
                        if (attributes.hasOwnProperty(key)) {
                            // get the value
                            val = attributes[key];
                            // unset attribute or change it ...
                            if (options.unset === true) {
                                delete now[key];
                            } else {
                                if (!_.isEqual(now[key], attributes[key])) {
                                    prev = now[key];
                                    this.$previousAttributes[key] = prev;
                                    now[key] = attributes[key];
                                    changedAttributes[key] = now[key];

                                    changedAttributesCount++;
                                }
                            }
                        }
                    }

                    if (changedAttributesCount) {
                        for (key in changedAttributes) {
                            if (changedAttributes.hasOwnProperty(key)) {
                                var commitMethodName = '_commit' + key.charAt(0).toUpperCase() + key.substr(1);

                                if (this[commitMethodName] instanceof Function) {
                                    // call method

                                    if (this[commitMethodName](now[key], this.$previousAttributes[key]) === false) {
                                        // false returned rollback
                                        changedAttributesCount--;
                                        now[key] = this.$previousAttributes[key];
                                    }
                                }
                            }
                        }

                        if (changedAttributesCount) {

                            this._commitChangedAttributes(changedAttributes);

                            if (options.silent === false) {
                                for (key in changedAttributes) {
                                    if (changedAttributes.hasOwnProperty(key)) {
                                        this.trigger('change:' + key, changedAttributes[key], this);
                                    }
                                }
                                this.trigger('change', changedAttributes, this);
                            }
                        }

                    }

                    return this;
                },

                setLater: function(key, value) {

                    if (_.isString(key)) {
                        key = {
                            key: value
                        }
                    }

                    _.extend(this.$invalidatedProperties, key);

                    if (!this.$invalidated) {
                        this.$invalidated = true;
                        globalInvalidationQueue.addCallback(this._commitInvalidatedAttributes);
                    }

                },

                _commitInvalidatedAttributes: function() {
                    this.set(this.$invalidatedProperties);
                    this.$invalidatedProperties = {};
                },

                /***
                 * evaluates a path to retrieve a value
                 *
                 * @param {Object} [scope=this] the scope where the path is evaluated
                 * @param {String} key
                 * @returns the value for the path or undefined
                 */
                get: function(scope, key) {
                    if(!key){
                        key = scope;
                        scope = this;
                    }

                    if(!key) {
                        return null;
                    }

                    var path;

                    // if we have a path object
                    if(_.isArray(key)){
                        path = key;
                    // path element
                    }else if(_.isObject(key)){
                        path = [key];
                    }else{
                        path = Parser.parse(key, "path");
                    }

                    var pathElement;
                    // go through the path
                    while (scope && path.length > 0) {
                        pathElement = path.shift();
                        if (pathElement.type == "fnc") {
                            var fnc = scope[pathElement.name];
                            var parameters = pathElement.parameter;
                            for (var i = 0; i < parameters.length; i++) {
                                var param = parameters[i];
                                if (_.isObject(param)) {
                                    param.type = "static";
                                    parameters[i] = this.get(param.path);
                                }
                            }
                            scope = fnc.apply(scope, parameters);
                        } else if (pathElement.type == "var") {
                            if (scope instanceof Bindable) {
                                if(path.length === 0){
                                    scope = scope.$[pathElement.name];
                                }else{
                                    scope = scope.get(pathElement.name);
                                }

                            } else {
                                scope = scope[pathElement.name];
                            }
                        }

                        if(scope && pathElement.index !== ''){
                            // if it's an array
                            if(_.isArray(scope)){
                                scope = scope[pathElement.index];
                            // if it's a list
                            }else if(scope.at){
                                scope = scope.at(pathElement.index);
                            }
                        }
                    }
                    return scope;
                },

                /***
                 * determinate if a attribute is available
                 *
                 * @param {String} path - to get the value
                 * @returns {Boolean} true if attribute is not undefined
                 */
                has: function (path) {
                    return !_.isUndefined(this.get(path));
                },

                /***
                 * called after attributes has set and some of the has been changed
                 *
                 * @param {Object} attributes - contains the changed attributes
                 *
                 * @abstract
                 * @private
                 */
                _commitChangedAttributes: function (attributes) {
                    // override
                },

                /***
                 * Unset attribute on $
                 * @param {String|Object} key - the attribute or attributes to unset
                 * @param {Object} [options]
                 * @return {this}
                 */
                unset: function (key, options) {
                    (options || (options = {})).unset = true;
                    return this.set(key, null, options);
                },

                /***
                 * Clears all attributes
                 * @return {this}
                 */
                clear: function () {
                    return this.set(this.$, {unset: true});
                },

                /***
                 * Binds an event handler function to an EventDispatcher
                 *
                 * @param {String} path - a binding path e.g. a.b.c
                 * @param {String} event - the type of the event which should be bound
                 * @param {Function} callback - the event handler function
                 * @param {Object} [thisArg] - the thisArg used for calling the event handler
                 */
                bind: function (path, event, callback, thisArg) {
                    if (event instanceof Function && _.isString(path)) {
                        this.callBase(path, event, callback);
                    } else {
                        if(_.isArray(path) && path.length > 0){
                            thisArg = callback;
                            callback = event;
                            event = path[1];
                            path = path[0];
                        }
                        var eb = new EventBindable({
                            path: path,
                            event: event,
                            scope: thisArg,
                            callback: callback,
                            value: null
                        });
                        eb.set('binding', new Binding({path: path, scope: this, target: eb, targetKey: 'value'}));
                        this.$eventBindables.push(eb);
                    }
                },

                /***
                 * Unbinds an bound event handler from an EventDispatcher.
                 *
                 * @param {String} [path] - the path from which the event should be unbound
                 * @param {String} event - the type of the event
                 * @param {Function} callback - the event handler which is currently bound
                 * TODO: why a scope is passed here?
                 * @param {Object} [scope]
                 */
                unbind: function (path, event, callback, scope) {
                    if (event instanceof Function) {
                        this.callBase(path, event, callback);
                    } else {
                        var eb;
                        for (var i = this.$eventBindables.length - 1; i >= 0; i--) {
                            eb = this.$eventBindables[i];
                            if (eb.$.scope === scope && eb.$.path === path && eb.$.event === event && eb.$.callback === callback) {
                                // unbind
                                eb.destroy();
                                this.$eventBindables.slice(i, 1);
                            }
                        }
                    }
                },

                /***
                 * Destroys all event bindings and triggers a destroy event
                 * @return {this}
                 */
                destroy: function() {
                    this.callBase();
                    for(var i = 0; i < this.$eventBindables.length; i++){
                        this.$eventBindables[i].destroy();
                    }

                    this.trigger('destroy',this);
                    return this;
                }
            });

        var EventBindable = Bindable.inherit({
            _commitChangedAttributes: function(attributes){
                this.callBase();
                if(attributes.binding){
                    this.set('value', attributes.binding.getValue());
                }else if(attributes.value){
                    var value = attributes.value;
                    this._unbindEvent(this.$previousAttributes['value']);
                    if (!_.isUndefined(value)) {
                        this._bindEvent(value);
                    }
                }

            },
            _unbindEvent: function (value) {
                if (value && value instanceof EventDispatcher) {
                    value.unbind(this.$.event, this.$.callback, this.$.scope);
                }
            },
            _bindEvent: function (value) {
                if (value && value instanceof EventDispatcher) {
                    value.bind(this.$.event, this.$.callback, this.$.scope);
                }
            },
            destroy: function () {
                this._unbindEvent(this.$.value);
                this.$.binding.destroy();

                this.callBase();
            }
        });

        return Bindable;

    });<commit_msg>fixed unset fixed using a number as key removed manipulation of path for get<commit_after>define(["js/core/EventDispatcher", "js/lib/parser", "js/core/Binding","underscore"],
    function (EventDispatcher, Parser, Binding, _) {

        // global invalidation timer

        var globalInvalidationQueue = (function() {

            var id,
                callbacks = [],
                work = function() {
                    for (var i = 0; i < callbacks.length; i++) {
                        try {
                            callbacks[i]();
                        } catch (e) {
                            (console.warn || console.log).call(console, e);
                        }
                    }

                    callbacks = [];
                    id = null;
                };

            return {
                addCallback: function(callback) {
                    callbacks.push(callback);

                    if (!id) {
                        id = setTimeout(work, 1000 / 60);
                    }
                }
            }
        })();

        var Bindable = EventDispatcher.inherit("js.core.Bindable",
            {
                /***
                 * creates a new instance of bindable, which can be bound to components
                 *
                 * @param {Object} [attributes] the default attributes which will be set during instantiation
                 */
                ctor: function (attributes) {
                    this.$eventBindables = [];

                    // call the base class constructor
                    this.callBase(null);

                    this.$ = {};
                    this.$invalidatedProperties = {};
                    this.$invalidated = false;

                    _.extend(this._eventAttributes, this.base._eventAttributes || {});

                    attributes = attributes || {};

                    var defaultAttributes = this._defaultAttributes();
                    for (var key in defaultAttributes) {
                        if (defaultAttributes.hasOwnProperty(key)) {
                            if (!attributes.hasOwnProperty(key)) {
                                if (_.isFunction(defaultAttributes[key])) {
                                    // Function as default -> construct new Object
                                    attributes[key] = new (defaultAttributes[key])();
                                } else {
                                    attributes[key] = _.clone(defaultAttributes[key]);
                                }
                            }
                        }
                    }

                    this.$ = attributes;
                    // TODO: clone and keep prototype for attribute the same -> write own clone method
                    this.$previousAttributes = _.clone(attributes);

                },
                /**
                 * Here you can define the default attributes of the instance.
                 *
                 * @static
                 */
                defaults: {
                },

                /***
                 *
                 * @return {Object} returns the default attributes and includes the defaults from base classes
                 * @private
                 */
                _defaultAttributes: function () {
                    return this._generateDefaultsChain("defaults");
                },

                /***
                 * generates a default chain containing the values from this instance and base classes
                 *
                 * @param {String} property - the name of the static property used to find defaults
                 * @return {*}
                 * @private
                 */
                _generateDefaultsChain: function (property) {
                    var ret = this[property],
                        base = this.base;

                    while (base) {
                        _.defaults(ret, base[property]);
                        base = base.base;
                    }

                    return ret;
                },

                /**
                 * Sets new values for attributes and notify about changes
                 *
                 * @param {String} key The attribute key
                 * @param {String} value The attribute value
                 * @param {Object} options A hash of options
                 * @param {Boolean} [options.silent=false] if true no event is triggered on change
                 * @param {Boolean} [options.unset=false] if true the attribute gets deleted
                 */
                set: function (key, value, options) {
                    var attributes = {};

                    if(_.isNumber(key)){
                        key = String(key);
                    }

                    if (_.isString(key)) {
                        // check for path
                        var path = key.split(".");
                        if (path.length > 1) {
                            var scope = this.get(path.shift());
                            if (scope && scope.set) {
                                scope.set(path.join("."), value, options);
                                return this;
                            }

                        }

                        attributes[key] = value;
                    } else {
                        options = value;
                        attributes = key;
                    }

                    options = options || {silent: false, unset: false};

                    // for un-setting attributes
                    if (options.unset) {
                        for (key in attributes) {
                            if (attributes.hasOwnProperty(key)) {
                                attributes[key] = void 0;
                            }
                        }
                    }

                    var changedAttributes = {},
                        changedAttributesCount = 0,
                        now = this.$,
                        val, prev;

                    for (key in attributes) {
                        if (attributes.hasOwnProperty(key)) {
                            // get the value
                            val = attributes[key];
                            // unset attribute or change it ...
                            if (options.unset === true) {
                                prev = now[key];
                                delete now[key];
                                changedAttributes[key] = undefined;
                                changedAttributesCount++;
                                this.$previousAttributes[key] = prev;
                            } else {
                                if (!_.isEqual(now[key], attributes[key])) {
                                    prev = now[key];
                                    this.$previousAttributes[key] = prev;
                                    now[key] = attributes[key];
                                    changedAttributes[key] = now[key];

                                    changedAttributesCount++;
                                }
                            }
                        }
                    }

                    if (changedAttributesCount) {
                        for (key in changedAttributes) {
                            if (changedAttributes.hasOwnProperty(key)) {
                                var commitMethodName = '_commit' + key.charAt(0).toUpperCase() + key.substr(1);

                                if (this[commitMethodName] instanceof Function) {
                                    // call method

                                    if (this[commitMethodName](now[key], this.$previousAttributes[key]) === false) {
                                        // false returned rollback
                                        changedAttributesCount--;
                                        now[key] = this.$previousAttributes[key];
                                    }
                                }
                            }
                        }

                        if (changedAttributesCount) {

                            this._commitChangedAttributes(changedAttributes);

                            if (options.silent === false) {
                                for (key in changedAttributes) {
                                    if (changedAttributes.hasOwnProperty(key)) {
                                        this.trigger('change:' + key, changedAttributes[key], this);
                                    }
                                }
                                this.trigger('change', changedAttributes, this);
                            }
                        }

                    }

                    return this;
                },

                setLater: function(key, value) {

                    if (_.isString(key)) {
                        key = {
                            key: value
                        }
                    }

                    _.extend(this.$invalidatedProperties, key);

                    if (!this.$invalidated) {
                        this.$invalidated = true;
                        globalInvalidationQueue.addCallback(this._commitInvalidatedAttributes);
                    }

                },

                _commitInvalidatedAttributes: function() {
                    this.set(this.$invalidatedProperties);
                    this.$invalidatedProperties = {};
                },

                /***
                 * evaluates a path to retrieve a value
                 *
                 * @param {Object} [scope=this] the scope where the path is evaluated
                 * @param {String} key
                 * @returns the value for the path or undefined
                 */
                get: function(scope, key) {
                    if(!key){
                        key = scope;
                        scope = this;
                    }

                    if(!key) {
                        return null;
                    }

                    var path;

                    // if we have a path object
                    if(_.isArray(key)){
                        path = key;
                    // path element
                    }else if(_.isObject(key)){
                        path = [key];
                    }else{
                        path = Parser.parse(key, "path");
                    }

                    var pathElement, val;
                    for (var j = 0; scope && j < path.length; j++) {
                        pathElement = path[j];
                        if (pathElement.type == "fnc") {
                            var fnc = scope[pathElement.name];
                            var parameters = pathElement.parameter;
                            for (var i = 0; i < parameters.length; i++) {
                                var param = parameters[i];
                                if (_.isObject(param)) {
                                    param.type = "static";
                                    parameters[i] = this.get(param.path);
                                }
                            }
                            scope = fnc.apply(scope, parameters);
                        } else if (pathElement.type == "var") {
                            if (scope instanceof Bindable) {
                                if (path.length - 1 === j ) {
                                    val = scope.$[pathElement.name];
                                    if(_.isUndefined(val)){
                                        val = scope[pathElement.name];
                                    }
                                    scope = val;
                                } else {
                                    scope = scope.get(pathElement.name);
                                }

                            } else {
                                scope = scope[pathElement.name];
                            }
                        }

                        if (scope && pathElement.index !== '') {
                            // if it's an array
                            if (_.isArray(scope)) {
                                scope = scope[pathElement.index];
                                // if it's a list
                            } else if (scope.at) {
                                scope = scope.at(pathElement.index);
                            }
                        }
                    }
                    return scope;
                },

                /***
                 * determinate if a attribute is available
                 *
                 * @param {String} path - to get the value
                 * @returns {Boolean} true if attribute is not undefined
                 */
                has: function (path) {
                    return !_.isUndefined(this.get(path));
                },

                /***
                 * called after attributes has set and some of the has been changed
                 *
                 * @param {Object} attributes - contains the changed attributes
                 *
                 * @abstract
                 * @private
                 */
                _commitChangedAttributes: function (attributes) {
                    // override
                },

                /***
                 * Unset attribute on $
                 * @param {String|Object} key - the attribute or attributes to unset
                 * @param {Object} [options]
                 * @return {this}
                 */
                unset: function (key, options) {
                    (options || (options = {})).unset = true;
                    return this.set(key, null, options);
                },

                /***
                 * Clears all attributes
                 * @return {this}
                 */
                clear: function () {
                    return this.set(this.$, {unset: true});
                },

                /***
                 * Binds an event handler function to an EventDispatcher
                 *
                 * @param {String} path - a binding path e.g. a.b.c
                 * @param {String} event - the type of the event which should be bound
                 * @param {Function} callback - the event handler function
                 * @param {Object} [thisArg] - the thisArg used for calling the event handler
                 */
                bind: function (path, event, callback, thisArg) {
                    if (event instanceof Function && _.isString(path)) {
                        this.callBase(path, event, callback);
                    } else {
                        if(_.isArray(path) && path.length > 0){
                            thisArg = callback;
                            callback = event;
                            event = path[1];
                            path = path[0];
                        }
                        var eb = new EventBindable({
                            path: path,
                            event: event,
                            scope: thisArg,
                            callback: callback,
                            value: null
                        });
                        eb.set('binding', new Binding({path: path, scope: this, target: eb, targetKey: 'value'}));
                        this.$eventBindables.push(eb);
                    }
                },

                /***
                 * Unbinds an bound event handler from an EventDispatcher.
                 *
                 * @param {String} [path] - the path from which the event should be unbound
                 * @param {String} event - the type of the event
                 * @param {Function} callback - the event handler which is currently bound
                 * TODO: why a scope is passed here?
                 * @param {Object} [scope]
                 */
                unbind: function (path, event, callback, scope) {
                    if (event instanceof Function) {
                        this.callBase(path, event, callback);
                    } else {
                        var eb;
                        for (var i = this.$eventBindables.length - 1; i >= 0; i--) {
                            eb = this.$eventBindables[i];
                            if (eb.$.scope === scope && eb.$.path === path && eb.$.event === event && eb.$.callback === callback) {
                                // unbind
                                eb.destroy();
                                this.$eventBindables.slice(i, 1);
                            }
                        }
                    }
                },

                /***
                 * Destroys all event bindings and triggers a destroy event
                 * @return {this}
                 */
                destroy: function() {
                    this.callBase();
                    for(var i = 0; i < this.$eventBindables.length; i++){
                        this.$eventBindables[i].destroy();
                    }

                    this.trigger('destroy',this);
                    return this;
                }
            });

        var EventBindable = Bindable.inherit({
            _commitChangedAttributes: function(attributes){
                this.callBase();
                if(attributes.binding){
                    this.set('value', attributes.binding.getValue());
                }else if(attributes.value){
                    var value = attributes.value;
                    this._unbindEvent(this.$previousAttributes['value']);
                    if (!_.isUndefined(value)) {
                        this._bindEvent(value);
                    }
                }

            },
            _unbindEvent: function (value) {
                if (value && value instanceof EventDispatcher) {
                    value.unbind(this.$.event, this.$.callback, this.$.scope);
                }
            },
            _bindEvent: function (value) {
                if (value && value instanceof EventDispatcher) {
                    value.bind(this.$.event, this.$.callback, this.$.scope);
                }
            },
            destroy: function () {
                this._unbindEvent(this.$.value);
                this.$.binding.destroy();

                this.callBase();
            }
        });

        return Bindable;

    });<|endoftext|>


<commit_before>import {clone} from 'lodash/lang';
import {forOwn} from 'lodash/object';
import {pull} from 'lodash/array';
import {contains} from 'lodash/collection';

export function addNode(nodes, name) {
  const node = nodes[name];

  if (node) {
    throw new Error(`Node "${name}" already exists`);
  }

  nodes[name] = {
    dependencies: [],
    dependents: []
  };
}

export function removeNode(nodes, name) {
  const node = nodes[name];

  if (!node) {
    throw new Error(`Node "${name}" does not exist`);
  }

  nodes[name] = undefined;
}

export function addEdge(nodes, head, tail) {
  const headNode = nodes[head];
  const tailNode = nodes[tail];

  if (!headNode) {
    throw new Error(`Cannot add edge from "${head}" -> "${tail}" as "${head}" has not been defined`);
  }
  if (!tailNode) {
    throw new Error(`Cannot add edge from "${head}" -> "${tail}" as "${tail}" has not been defined`);
  }

  const dependencies = headNode.dependencies;
  if (!contains(dependencies, tail)) {
    dependencies.push(tail);
  }

  const dependents = tailNode.dependents;
  if (!contains(dependents, head)) {
    dependents.push(head);
  }
}

export function removeEdge(nodes, head, tail) {
  const headNode = nodes[head];
  const tailNode = nodes[tail];

  if (!headNode) {
    throw new Error(`Cannot remove edge from "${head}" -> "${tail}" as "${head}" has not been defined`);
  }
  if (!tailNode) {
    throw new Error(`Cannot remove edge from "${head}" -> "${tail}" as "${tail}" has not been defined`);
  }

  pull(headNode.dependencies, tail);
  pull(tailNode.dependents, head);
}

export function getNodesWithoutPredecessors(nodes) {
  const nodesWithoutPredecessors = [];

  forOwn(nodes, (node, name) => {
    if (node && node.dependents.length === 0) {
      nodesWithoutPredecessors.push(name);
    }
  });

  return nodesWithoutPredecessors;
}

export function pruneFromNode(nodes, name, ignore=[]) {
  const node = nodes[name];
  let nodesPruned = [name];

  if (node.dependents.length) {
    // Clone the array to avoid mutations during iteration
    const dependents = clone(node.dependents);
    dependents.forEach(dependentName => {
      removeEdge(nodes, dependentName, name);
    });
  }

  if (node.dependencies.length) {
    // Clone the array to avoid mutations during iteration
    const dependencies = clone(node.dependencies);
    dependencies.forEach(dependencyName => {
      removeEdge(nodes, name, dependencyName);

      if (
        nodes[dependencyName].dependents.length == 0 &&
        ignore.indexOf(dependencyName) === -1
      ) {
        const dependencyNodesPruned = pruneFromNode(nodes, dependencyName, ignore);
        nodesPruned.push.apply(nodesPruned, dependencyNodesPruned);
      }
    });
  }

  removeNode(nodes, name);

  return nodesPruned;
}
<commit_msg>Cleanup<commit_after>import {clone} from 'lodash/lang';
import {forOwn} from 'lodash/object';
import {pull} from 'lodash/array';
import {contains} from 'lodash/collection';

export function addNode(nodes, name) {
  const node = nodes[name];

  if (node) {
    throw new Error(`Node "${name}" already exists`);
  }

  nodes[name] = {
    dependencies: [],
    dependents: []
  };
}

export function removeNode(nodes, name) {
  const node = nodes[name];

  if (!node) {
    throw new Error(`Node "${name}" does not exist`);
  }

  nodes[name] = undefined;
}

export function addEdge(nodes, head, tail) {
  const headNode = nodes[head];
  const tailNode = nodes[tail];

  if (!headNode) {
    throw new Error(`Cannot add edge from "${head}" -> "${tail}" as "${head}" has not been defined`);
  }
  if (!tailNode) {
    throw new Error(`Cannot add edge from "${head}" -> "${tail}" as "${tail}" has not been defined`);
  }

  const dependencies = headNode.dependencies;
  if (!contains(dependencies, tail)) {
    dependencies.push(tail);
  }

  const dependents = tailNode.dependents;
  if (!contains(dependents, head)) {
    dependents.push(head);
  }
}

export function removeEdge(nodes, head, tail) {
  const headNode = nodes[head];
  const tailNode = nodes[tail];

  if (!headNode) {
    throw new Error(`Cannot remove edge from "${head}" -> "${tail}" as "${head}" has not been defined`);
  }
  if (!tailNode) {
    throw new Error(`Cannot remove edge from "${head}" -> "${tail}" as "${tail}" has not been defined`);
  }

  pull(headNode.dependencies, tail);
  pull(tailNode.dependents, head);
}

export function getNodesWithoutPredecessors(nodes) {
  const nodesWithoutPredecessors = [];

  forOwn(nodes, (node, name) => {
    if (node && node.dependents.length === 0) {
      nodesWithoutPredecessors.push(name);
    }
  });

  return nodesWithoutPredecessors;
}

export function pruneFromNode(nodes, name, ignore=[]) {
  const node = nodes[name];
  let nodesPruned = [name];

  if (node.dependents.length) {
    // Clone the array to avoid mutations during iteration
    const dependents = clone(node.dependents);
    dependents.forEach(dependentName => {
      removeEdge(nodes, dependentName, name);
    });
  }

  if (node.dependencies.length) {
    // Clone the array to avoid mutations during iteration
    const dependencies = clone(node.dependencies);
    dependencies.forEach(dependencyName => {
      removeEdge(nodes, name, dependencyName);

      if (
        nodes[dependencyName].dependents.length == 0 &&
        !contains(ignore, dependencyName)
      ) {
        const dependencyNodesPruned = pruneFromNode(nodes, dependencyName, ignore);
        nodesPruned.push.apply(nodesPruned, dependencyNodesPruned);
      }
    });
  }

  removeNode(nodes, name);

  return nodesPruned;
}
<|endoftext|>


<commit_before>/*
 * DAlert jQueryPlugin
 * dalert.alert("Making the Alert Box much simpler, yet fancy");
 * Version: 1.0 (Alpha)
 * Author: Andrew dEX (Dilusha)
 * Dependencies : Jquery 1.6 + , Jquery UI 1.6 + Jquery UI CSS Framework
 * Info & API : http://dalert.andrewdex.com
 * Contribute : http://www.github.com/andrewdex/dalert
 *
 * Copyright 2013 Andrew dEX (Dilusha Gonagala)
 *
 * Released under the MIT license
 *http://opensource.org/licenses/MIT
 *Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 *
 */

var dalert = {

	byPassjQueryUI : function() {

		$(".ui-button-text-only .ui-button-text").css("padding-left","20px");
		$(".ui-button-text-only .ui-button-text").css("padding-right","20px");
		$(".ui-button-text-only .ui-button-text").css("padding-top", "0px");
		$(".ui-button-text-only .ui-button-text").css("padding-bottom","0px");

	},

	alert : function(dalert_msg, title_msg, FontColor, bodyColor) {
		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalert_msg)
			dalert_msg = 'This is a Dalert !';

		try {
			$("

").html(dalert_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						$(this).dialog("close");

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);
			dalert.byPassjQueryUI();

		} catch (error) {

			alert(dalert_msg);
		}

	},

	// DAlert Confirm Dialog
	confirm : function(dalertConf_msg, trueFunction, falseFunction, title_msg,
			FontColor, bodyColor) {

		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalertConf_msg)
			dalertConf_msg = 'This is a Dalert Confirm !';

		try {
			$("

").html(dalertConf_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						if (!trueFunction) {
							$(this).dialog("close");
						} else {
							eval(trueFunction)();
							$(this).dialog("close");

						}

					},
					Cancel : function() {
						if (!falseFunction) {
							$(this).dialog("close");
						} else {
							eval(falseFunction)();
							$(this).dialog("close");

						}

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

		} catch (error) {

			alert(dalertConf_msg);
		}

	},

	// Replace DAlert With Window JavaScript Original objects : alert, confirm.
	ReplaceAlert : function() {

		window.alert = dalert.alert;

	},

	ReplaceConfirm : function() {

		window.confirm = dalert.confirm;

	}

};
<commit_msg>Button Padding Set<commit_after>/*
 * DAlert jQueryPlugin
 * dalert.alert("Making the Alert Box much simpler, yet fancy");
 * Version: 1.0 (Alpha)
 * Author: Andrew dEX (Dilusha)
 * Dependencies : Jquery 1.6 + , Jquery UI 1.6 + Jquery UI CSS Framework
 * Info & API : http://dalert.andrewdex.com
 * Contribute : http://www.github.com/andrewdex/dalert
 *
 * Copyright 2013 Andrew dEX (Dilusha Gonagala)
 *
 * Released under the MIT license
 *http://opensource.org/licenses/MIT
 *Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 *
 */

var dalert = {

	//jQuery UI Override for button padding
	byPassjQueryUI : function() {

		$(".ui-button-text-only .ui-button-text").css("padding-left", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-right", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-top", "0px");
		$(".ui-button-text-only .ui-button-text").css("padding-bottom", "0px");

	},

	alert : function(dalert_msg, title_msg, FontColor, bodyColor) {
		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalert_msg)
			dalert_msg = 'This is a Dalert !';

		try {
			$("

").html(dalert_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						$(this).dialog("close");

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();

		} catch (error) {

			alert(dalert_msg);
		}

	},

	// DAlert Confirm Dialog
	confirm : function(dalertConf_msg, trueFunction, falseFunction, title_msg,
			FontColor, bodyColor) {

		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalertConf_msg)
			dalertConf_msg = 'This is a Dalert Confirm !';

		try {
			$("

").html(dalertConf_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						if (!trueFunction) {
							$(this).dialog("close");
						} else {
							eval(trueFunction)();
							$(this).dialog("close");

						}

					},
					Cancel : function() {
						if (!falseFunction) {
							$(this).dialog("close");
						} else {
							eval(falseFunction)();
							$(this).dialog("close");

						}

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();

		} catch (error) {

			alert(dalertConf_msg);
		}

	},

	// Replace DAlert With Window JavaScript Original objects : alert, confirm.
	ReplaceAlert : function() {

		window.alert = dalert.alert;

	},

	ReplaceConfirm : function() {

		window.confirm = dalert.confirm;

	}

};
<|endoftext|>


<commit_before><commit_msg>[Admin] Don't add attributes if no new have been selected<commit_after><|endoftext|>