<commit_before>(function ($) {
	"use strict";

    var bootsnav = {
        initialize: function() {
            this.event();
            this.hoverDropdown();
            this.navbarSticky();
            this.navbarScrollspy();
        },
        event : function(){

            // ------------------------------------------------------------------------------ //
            // Variable
            // ------------------------------------------------------------------------------ //
            var getNav = $("nav.navbar.bootsnav");

            // ------------------------------------------------------------------------------ //
            // Navbar Sticky
            // ------------------------------------------------------------------------------ //
            var navSticky = getNav.hasClass("navbar-sticky");
            if( navSticky ){
                // Wraped navigation
                getNav.wrap("

");
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Center
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("brand-center")){
                var postsArr = new Array(),
                    index = $("nav.brand-center"),
                    $postsList = index.find('ul.navbar-nav');

                //Create array of all posts in lists
                index.find('ul.navbar-nav > li').each(function(){
                    postsArr.push($(this).html());
                });

                //Split the array at this point. The original array is altered.
                var firstList = postsArr.splice(0, Math.round(postsArr.length / 2)),
                    secondList = postsArr,
                    ListHTML = '';

                var createHTML = function(list){
                    ListHTML = '';
                    for (var i = 0; i < list.length; i++) {
                        ListHTML += '
' + list[i] + '
'
                    }
                }

                //Generate HTML for first list
                createHTML(firstList);
                $postsList.html(ListHTML);
                index.find("ul.nav").first().addClass("navbar-left");

                //Generate HTML for second list
                createHTML(secondList);
                //Create new list after original one
                $postsList.after('

').next().html(ListHTML);
                index.find("ul.nav").last().addClass("navbar-right");

                //Wrap navigation menu
                index.find("ul.nav.navbar-left").wrap("

");
                index.find("ul.nav.navbar-right").wrap("

");

                //Selection Class
                index.find('ul.navbar-nav > li').each(function(){
                    var dropDown = $("ul.dropdown-menu", this),
                        megaMenu = $("ul.megamenu-content", this);
                    dropDown.closest("li").addClass("dropdown");
                    megaMenu.closest("li").addClass("megamenu-fw");
                });
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Sidebar
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("navbar-sidebar")){
                // Add Class to body
                $("body").addClass("wrap-nav-sidebar");
                getNav.wrapInner("

");
            }else{
                $(".bootsnav").addClass("on");
            }

            // ------------------------------------------------------------------------------ //
            // Menu Center
            // ------------------------------------------------------------------------------ //
            if( getNav.find("ul.nav").hasClass("navbar-center")){
                getNav.addClass("menu-center");
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Full
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("navbar-full")){
                // Add Class to body
                $("nav.navbar.bootsnav").find("ul.nav").wrap("

");
                $(".wrap-full-menu").wrap("

");
                $("ul.nav.navbar-nav").prepend("

");
            }else if( getNav.hasClass("navbar-mobile")){
                getNav.removeClass("no-full");
            }else{
                getNav.addClass("no-full");
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Mobile
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("navbar-mobile")){
                // Add Class to body
                $('.navbar-collapse').on('shown.bs.collapse', function() {
                    $("body").addClass("side-right");
                });
                $('.navbar-collapse').on('hide.bs.collapse', function() {
                    $("body").removeClass("side-right");
                });

                $(window).on("resize", function(){
                    $("body").removeClass("side-right");
                });
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Fixed
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("no-background")){
                $(window).on("scroll", function(){
                    var scrollTop = $(window).scrollTop();
                    if(scrollTop >34){
                        $(".navbar-fixed").removeClass("no-background");
                    }else {
                        $(".navbar-fixed").addClass("no-background");
                    }
                });
            }

            // ------------------------------------------------------------------------------ //
            // Navbar Fixed
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("navbar-transparent")){
                $(window).on("scroll", function(){
                    var scrollTop = $(window).scrollTop();
                    if(scrollTop >34){
                        $(".navbar-fixed").removeClass("navbar-transparent");
                    }else {
                        $(".navbar-fixed").addClass("navbar-transparent");
                    }
                });
            }

            // ------------------------------------------------------------------------------ //
            // Button Cart
            // ------------------------------------------------------------------------------ //
            $(".btn-cart").on("click", function(e){
                e.stopPropagation();
            });

            // ------------------------------------------------------------------------------ //
            // Toggle Search
            // ------------------------------------------------------------------------------ //
            $("nav.navbar.bootsnav .attr-nav").each(function(){
                $("li.search > a", this).on("click", function(e){
                    e.preventDefault();
                    $(".top-search").slideToggle();
                });
            });
            $(".input-group-addon.close-search").on("click", function(){
                $(".top-search").slideUp();
            });

            // ------------------------------------------------------------------------------ //
            // Toggle Side Menu
            // ------------------------------------------------------------------------------ //
            $("nav.navbar.bootsnav .attr-nav").each(function(){
                $("li.side-menu > a", this).on("click", function(e){
                    e.preventDefault();
                    $("nav.navbar.bootsnav > .side").toggleClass("on");
                    $("body").toggleClass("on-side");
                });
            });
            $(".side .close-side").on("click", function(e){
                e.preventDefault();
                $("nav.navbar.bootsnav > .side").removeClass("on");
                $("body").removeClass("on-side");
            });

            // ------------------------------------------------------------------------------ //
            // Wrapper
            // ------------------------------------------------------------------------------ //
            $("body").wrapInner( "

");
        },

        // ------------------------------------------------------------------------------ //
        // Change dropdown to hover on dekstop
        // ------------------------------------------------------------------------------ //
        hoverDropdown : function(){
            var getNav = $("nav.navbar.bootsnav"),
                getWindow = $(window).width(),
                getHeight = $(window).height(),
                getIn = getNav.find("ul.nav").data("in"),
                getOut = getNav.find("ul.nav").data("out");

            if( getWindow < 981 ){

                // Height of scroll navigation sidebar
                $(".scroller").css("height", "auto");

                // Disable mouseenter event
                $("nav.navbar.bootsnav ul.nav").find("li.dropdown").off("mouseenter");
                $("nav.navbar.bootsnav ul.nav").find("li.dropdown").off("mouseleave");
                $("nav.navbar.bootsnav ul.nav").find(".title").off("mouseenter");
                $("nav.navbar.bootsnav ul.nav").off("mouseleave");
                $(".navbar-collapse").removeClass("animated");

                // Enable click event
                $("nav.navbar.bootsnav ul.nav").each(function(){
                    $(".dropdown-menu", this).addClass("animated");
                    $(".dropdown-menu", this).removeClass(getOut);

                    // Dropdown Fade Toggle
                    $("a.dropdown-toggle", this).off('click');
                    $("a.dropdown-toggle", this).on('click', function (e) {
                        e.stopPropagation();
                        $(this).closest("li.dropdown").find(".dropdown-menu").first().stop().fadeToggle().toggleClass(getIn);
                        $(this).closest("li.dropdown").first().toggleClass("on");
                        return false;
                    });

                    // Hidden dropdown action
                    $('li.dropdown', this).each(function () {
                        $(this).find(".dropdown-menu").stop().fadeOut();
                        $(this).on('hidden.bs.dropdown', function () {
                            $(this).find(".dropdown-menu").stop().fadeOut();
                        });
                        return false;
                    });

                    // Megamenu style
                    $(".megamenu-fw", this).each(function(){
                        $(".col-menu", this).each(function(){
                            $(".content", this).addClass("animated");
                            $(".content", this).stop().fadeOut();
                            $(".title", this).off("click");
                            $(".title", this).on("click", function(){
                                $(this).closest(".col-menu").find(".content").stop().fadeToggle().addClass(getIn);
                                $(this).closest(".col-menu").toggleClass("on");
                                return false;
                            });

                            $(".content", this).on("click", function(e){
                                e.stopPropagation();
                            });
                        });
                    });
                });

                // Hidden dropdown
                var cleanOpen = function(){
                    $('li.dropdown', this).removeClass("on");
                    $(".dropdown-menu", this).stop().fadeOut();
                    $(".dropdown-menu", this).removeClass(getIn);
                    $(".col-menu", this).removeClass("on");
                    $(".col-menu .content", this).stop().fadeOut();
                    $(".col-menu .content", this).removeClass(getIn);
                }

                // Hidden om mouse leave
                $("nav.navbar.bootsnav").on("mouseleave", function(){
                    cleanOpen();
                });

                // Enable click atribute navigation
                $("nav.navbar.bootsnav .attr-nav").each(function(){
                    $(".dropdown-menu", this).removeClass("animated");
                    $("li.dropdown", this).off("mouseenter");
                    $("li.dropdown", this).off("mouseleave");
                    $("a.dropdown-toggle", this).off('click');
                    $("a.dropdown-toggle", this).on('click', function (e) {
                        e.stopPropagation();
                        $(this).closest("li.dropdown").find(".dropdown-menu").first().stop().fadeToggle();
                        $(".navbar-toggle").each(function(){
                            $(".fa", this).removeClass("fa-times");
                            $(".fa", this).addClass("fa-bars");
                            $(".navbar-collapse").removeClass("in");
                            $(".navbar-collapse").removeClass("on");
                        });
                    });

                    $(this).on("mouseleave", function(){
                        $(".dropdown-menu", this).stop().fadeOut();
                        $("li.dropdown", this).removeClass("on");
                        return false;
                    });
                });

                // Toggle Bars
                $(".navbar-toggle").each(function(){
                    $(this).off("click");
                    $(this).on("click", function(){
                        $(".fa", this).toggleClass("fa-bars");
                        $(".fa", this).toggleClass("fa-times");
                        cleanOpen();
                    });
                });

            }else if( getWindow > 981 ){
                // Height of scroll navigation sidebar
                $(".scroller").css("height", getHeight + "px");

                // Navbar Sidebar
                if( getNav.hasClass("navbar-sidebar")){
                    // Hover effect Sidebar Menu
                    $("nav.navbar.bootsnav ul.nav").each(function(){
                        $("a.dropdown-toggle", this).off('click');
                        $("a.dropdown-toggle", this).on('click', function (e) {
                            e.stopPropagation();
                        });

                        $(".dropdown-menu", this).addClass("animated");
                        $("li.dropdown", this).on("mouseenter", function(){
                            $(".dropdown-menu", this).eq(0).removeClass(getOut);
                            $(".dropdown-menu", this).eq(0).stop().fadeIn().addClass(getIn);
                            $(this).addClass("on");
                            return false;
                        });

                        $(".col-menu").each(function(){
                            $(".content", this).addClass("animated");
                            $(".title", this).on("mouseenter", function(){
                                $(this).closest(".col-menu").find(".content").stop().fadeIn().addClass(getIn);
                                $(this).closest(".col-menu").addClass("on");
                                return false;
                            });
                        });

                        $(this).on("mouseleave", function(){
                            $(".dropdown-menu", this).stop().removeClass(getIn);
                            $(".dropdown-menu", this).stop().addClass(getOut).fadeOut();
                            $(".col-menu", this).find(".content").stop().fadeOut().removeClass(getIn);
                            $(".col-menu", this).removeClass("on");
                            $("li.dropdown", this).removeClass("on");
                            return false;
                        });
                    });
                }else{
                    // Hover effect Default Menu
                    $("nav.navbar.bootsnav ul.nav").each(function(){
                        $("a.dropdown-toggle", this).off('click');
                        $("a.dropdown-toggle", this).on('click', function (e) {
                            e.stopPropagation();
                        });

                        $(".megamenu-fw", this).each(function(){
                            $(".title", this).off("click");
                            $("a.dropdown-toggle", this).off("click");
                            $(".content").removeClass("animated");
                        });

                        $(".dropdown-menu", this).addClass("animated");
                        $("li.dropdown", this).on("mouseenter", function(){
                            $(".dropdown-menu", this).eq(0).removeClass(getOut);
                            $(".dropdown-menu", this).eq(0).stop().fadeIn().addClass(getIn);
                            $(this).addClass("on");
                            return false;
                        });

                        $("li.dropdown", this).on("mouseleave", function(){
                            $(".dropdown-menu", this).eq(0).removeClass(getIn);
                            $(".dropdown-menu", this).eq(0).stop().fadeOut().addClass(getOut);
                            $(this).removeClass("on");
                        });

                        $(this).on("mouseleave", function(){
                            $(".dropdown-menu", this).removeClass(getIn);
                            $(".dropdown-menu", this).eq(0).stop().fadeOut().addClass(getOut);
                            $("li.dropdown", this).removeClass("on");
                            return false;
                        });
                    });
                }

                // ------------------------------------------------------------------------------ //
                // Hover effect Atribute Navigation
                // ------------------------------------------------------------------------------ //
                $("nav.navbar.bootsnav .attr-nav").each(function(){
                    $("a.dropdown-toggle", this).off('click');
                    $("a.dropdown-toggle", this).on('click', function (e) {
                        e.stopPropagation();
                    });

                    $(".dropdown-menu", this).addClass("animated");
                    $("li.dropdown", this).on("mouseenter", function(){
                        $(".dropdown-menu", this).eq(0).removeClass(getOut);
                        $(".dropdown-menu", this).eq(0).stop().fadeIn().addClass(getIn);
                        $(this).addClass("on");
                        return false;
                    });

                    $("li.dropdown", this).on("mouseleave", function(){
                        $(".dropdown-menu", this).eq(0).removeClass(getIn);
                        $(".dropdown-menu", this).eq(0).stop().fadeOut().addClass(getOut);
                        $(this).removeClass("on");
                    });

                    $(this).on("mouseleave", function(){
                        $(".dropdown-menu", this).removeClass(getIn);
                        $(".dropdown-menu", this).eq(0).stop().fadeOut().addClass(getOut);
                        $("li.dropdown", this).removeClass("on");
                        return false;
                    });
                });
            }

            // ------------------------------------------------------------------------------ //
            // Menu Fullscreen
            // ------------------------------------------------------------------------------ //
            if( getNav.hasClass("navbar-full")){
                var windowHeight = $(window).height(),
                    windowWidth =  $(window).width();

                $(".nav-full").css("height", windowHeight + "px");
                $(".wrap-full-menu").css("height", windowHeight + "px");
                $(".wrap-full-menu").css("width", windowWidth + "px");

                $(".navbar-collapse").addClass("animated");
                $(".navbar-toggle").each(function(){
                    var getId = $(this).data("target");
                    $(this).off("click");
                    $(this).on("click", function(e){
                        e.preventDefault();
                        $(getId).removeClass(getOut);
                        $(getId).addClass("in");
                        $(getId).addClass(getIn);
                        return false;
                    });

                    $("li.close-full-menu").on("click", function(e){
                        e.preventDefault();
                        $(getId).addClass(getOut);
                        setTimeout(function(){
                            $(getId).removeClass("in");
                            $(getId).removeClass(getIn);
                        }, 500);
                        return false;
                    });
                });
            }
        },

        // ------------------------------------------------------------------------------ //
        // Navbar Sticky
        // ------------------------------------------------------------------------------ //
        navbarSticky : function(){
            var getNav = $("nav.navbar.bootsnav"),
                navSticky = getNav.hasClass("navbar-sticky");

            if( navSticky ){

                // Set Height Navigation
                var getHeight = getNav.height();
                $(".wrap-sticky").height(getHeight);

                // Windown on scroll
                var getOffset = $(".wrap-sticky").offset().top;
                $(window).on("scroll", function(){
                    var scrollTop = $(window).scrollTop();
                    if(scrollTop > getOffset){
                        getNav.addClass("sticked");
                    }else {
                        getNav.removeClass("sticked");
                    }
                });
            }
        },

        // ------------------------------------------------------------------------------ //
        // Navbar Scrollspy
        // ------------------------------------------------------------------------------ //
        navbarScrollspy : function(){
            var navScrollSpy = $(".navbar-scrollspy"),
                $body   = $('body'),
                getNav = $('nav.navbar.bootsnav'),
                offset  = getNav.outerHeight();

            if( navScrollSpy.length ){
                $body.scrollspy({target: '.navbar', offset: offset });

                // Animation Scrollspy
                $('.scroll').on('click', function(event) {
                    event.preventDefault();

                    // Active link
                    $('.scroll').removeClass("active");
                    $(this).addClass("active");

                    // Remove navbar collapse
                    $(".navbar-collapse").removeClass("in");

                    // Toggle Bars
                    $(".navbar-toggle").each(function(){
                        $(".fa", this).removeClass("fa-times");
                        $(".fa", this).addClass("fa-bars");
                    });

                    // Scroll
                    var scrollTop = $(window).scrollTop(),
                        $anchor = $(this).find('a'),
                        $section = $($anchor.attr('href')).offset().top,
                        $window = $(window).width(),
                        $minusDesktop = getNav.data("minus-value-desktop"),
                        $minusMobile = getNav.data("minus-value-mobile"),
                        $speed = getNav.data("speed");

                    if( $window > 992 ){
                        var $position = $section - $minusDesktop;
                    }else{
                        var $position = $section - $minusMobile;
                    }

                    $('html, body').stop().animate({
                        scrollTop: $position
                    }, $speed);
                });

                // Activate Navigation
                var fixSpy = function() {
                    var data = $body.data('bs.scrollspy');
                    if (data) {
                        offset = getNav.outerHeight();
                        data.options.offset = offset;
                        $body.data('bs.scrollspy', data);
                        $body.scrollspy('refresh');
                    }
                }

                // Activate Navigation on resize
                var resizeTimer;
                $(window).on('resize', function() {
                    clearTimeout(resizeTimer);
                    var resizeTimer = setTimeout(fixSpy, 200);
                });
            }
        }
    };

    // Initialize
    $(document).ready(function(){
        bootsnav.initialize();
    });

    // Reset on resize
    $(window).on("resize", function(){
        bootsnav.hoverDropdown();

        $(".top-search").slideUp();
        setTimeout(function(){
            bootsnav.navbarSticky();
        }, 500);

        // Toggle Bars
        $(".navbar-toggle").each(function(){
            $(".fa", this).removeClass("fa-times");
            $(".fa", this).addClass("fa-bars");
            $(this).removeClass("fixed");
        });
        $(".navbar-collapse").removeClass("in");
        $(".navbar-collapse").removeClass("on");
        $(".navbar-collapse").removeClass("bounceIn");
    });

}(jQuery));

<commit_msg>Delete bootsnav.js<commit_after><|endoftext|>


<commit_before>window.onload = function() {

    // References to elements on the page
    var form = document.getElementById('message-form');
    var serverField = document.getElementById('server');
    var channelField = document.getElementById('channel');
    var idField = document.getElementById('idNum');
    var results = document.getElementById('results');
    var details = document.getElementById('details');
    var subscriptionList = document.getElementById('subscriptions');
    var connectBtn = document.getElementById('connect');
    var disconnectBtn = document.getElementById('disconnect');
    var subscribeBtn = document.getElementById('subscribe');
    var pauseBtn = document.getElementById('pause');
    var resumeBtn = document.getElementById('resume');
    var unsubscribeBtn = document.getElementById('unsubscribe');
    var clearBtn = document.getElementById('clear');

    var socket;
    var selectedEvent;
    var selectedId;

    var eventDetails = [];

    serverField.value = "ws://" + window.location.host + "/web-pods/socket";

    function addEventDetails(event) {
        eventDetails.unshift('

' + JSON.stringify(event, null, '     ') + '

');
    }

    function addNewSubscription(channel, id) {
        var newChannel = document.createElement('option');
        subscriptionList.appendChild(newChannel);
        newChannel.appendChild(document.createTextNode('id: ' + id + ', channel: ' + channel));
    }

    function newMessage(event) {
        var eventDisplay = getEventDisplay(event);
        var newEvent = document.createElement('option');
        results.insertBefore(newEvent, results.childNodes[0]);
        newEvent.appendChild(document.createTextNode(eventDisplay));
        addEventDetails(event);
    }

    function getEventDisplay(event) {
        if (event.type == 'error') { // Error
            return 'Error';
        }
        else if (event.type == 'connection') { // New subscription
            return 'Successful subscription';
        }
        else if (event.value.type.name == 'VTable') { // Table
            return 'Table';
        }
        else if (event.type == 'value') { // New value
            return event.value.value;
        }
    }

    function displayDetails(index) {
        details.innerHTML = eventDetails[index];
    }

    connectBtn.onclick = function() {
        socket = new Client(serverField.value);
        idField.value = 0;
    }

    disconnectBtn.onclick = function() {
        socket.close();
    }

    subscribeBtn.onclick = function() {
        var channel = channelField.value;
        var id = idField.value;
        socket.subscribeChannel(channel, newMessage);
        addNewSubscription(channel, id);
        subscriptionList.selectedIndex = id;
        selectedId = id;
        id++;
        idField.value = id;
    }

    pauseBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.pause();
    }

    resumeBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.resume();
    }

    unsubscribeBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.unsubscribe();
    }

    results.onchange = function() {
        selectedEvent = results.selectedIndex;
        displayDetails(selectedEvent);
    }

    subscriptionList.onchange = function() {
        selectedId = subscriptionList.selectedIndex;
    }

    clearBtn.onclick = function() {
        var node = document.getElementById('results');
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
    }

}<commit_msg>Some filtering supported in new probe<commit_after>window.onload = function() {

    // References to elements on the page
    var form = document.getElementById('message-form');
    var serverField = document.getElementById('server');
    var channelField = document.getElementById('channel');
    var idField = document.getElementById('idNum');
    var results = document.getElementById('results');
    var details = document.getElementById('details');
    var subscriptionList = document.getElementById('subscriptions');
    var connectBtn = document.getElementById('connect');
    var disconnectBtn = document.getElementById('disconnect');
    var subscribeBtn = document.getElementById('subscribe');
    var pauseBtn = document.getElementById('pause');
    var resumeBtn = document.getElementById('resume');
    var unsubscribeBtn = document.getElementById('unsubscribe');
    var clearBtn = document.getElementById('clear');
    var filterBtn = document.getElementById('filter');
    var showAllBtn = document.getElementById('showAll');

    var socket;
    var selectedEvent;
    var selectedId;
    var filter = 'none';

    var events = [];
    var eventDetails = [];
    var eventDetailsFiltered = [];

    serverField.value = "ws://" + window.location.host + "/web-pods/socket";

    function addNewSubscription(channel, id) {
        var newChannel = document.createElement('option');
        subscriptionList.appendChild(newChannel);
        newChannel.appendChild(document.createTextNode('id: ' + id + ', channel: ' + channel));
        eventDetailsFiltered.push([]);
    }

    function addEventDetails(event) {
        eventDetails.unshift('

' + JSON.stringify(event, null, '     ') + '

');
        eventDetailsFiltered[event.id].unshift('

' + JSON.stringify(event, null, '     ') + '

');
    }

    function displayEvent(eventDisplay, event) {
        events.unshift(eventDisplay);
        var newEvent = document.createElement('option');
        results.insertBefore(newEvent, results.childNodes[0]);
        newEvent.appendChild(document.createTextNode(eventDisplay));
        var att = document.createAttribute('eventId');
        att.value = event.id;
        newEvent.setAttributeNode(att);
    }

    function getEventDisplay(event) {
        if (event.type == 'error') { // Error
            return 'Error';
        }
        else if (event.type == 'connection') { // New subscription
            return 'Successful subscription';
        }
        else if (event.value.type.name == 'VTable') { // Table
            return 'Table';
        }
        else if (event.type == 'value') { // New value
            return event.value.value;
        }
    }

    function newMessage(event) {
        var eventDisplay = getEventDisplay(event);
        addEventDetails(event);
        if (event.id == filter || filter == 'none') {
            displayEvent(eventDisplay, event);
        }
    }

    function displayDetails(index) {
        details.innerHTML = eventDetails[index];
    }

    connectBtn.onclick = function() {
        socket = new Client(serverField.value);
        idField.value = 0;
    }

    disconnectBtn.onclick = function() {
        socket.close();
    }

    subscribeBtn.onclick = function() {
        var channel = channelField.value;
        var id = idField.value;
        socket.subscribeChannel(channel, newMessage);
        addNewSubscription(channel, id);
        subscriptionList.selectedIndex = id;
        selectedId = id;
        id++;
        idField.value = id;
    }

    pauseBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.pause();
    }

    resumeBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.resume();
    }

    unsubscribeBtn.onclick = function() {
        var channel = socket.getChannel(selectedId);
        channel.unsubscribe();
    }

    results.onchange = function() {
        selectedEvent = results.selectedIndex;
        displayDetails(selectedEvent);
    }

    subscriptionList.onchange = function() {
        selectedId = subscriptionList.selectedIndex;
    }

    clearBtn.onclick = function() {
        var node = document.getElementById('results');
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
    }

    function resetEventDisplay() {
        // TODO: repopulate display with events from events[]
    }

    filterBtn.onclick = function() {
        filter = selectedId;
        // TODO: if needed, resetEventDisplay
        var children = results.children
        for (var i = 0; i < children.length; i++) {
            if (children[i].getAttribute('eventId') != filter) {
                results.removeChild(children[i]);
                i--;
            }
        }
    }

    showAllBtn.onclick = function() {
        filter = 'none';
        // TODO: reset DOM
    }

}<|endoftext|>


<commit_before>Ohhman = function () {
	this.sprite = null;
	this.speed = 200;

	this.direction; //LEFT, RIGHT, UP, DOWN

	this.score = 0;
	this.scoreText = null;
};

Ohhman.prototype = {
	preload : function() {
		//Carrega o sprite do ohhMan
		game.load.image('ohhMan', fp_ohhMan);
	},

	create : function() {
		//Adiciona o ohhMan na tela
		this.sprite = game.add.sprite(game.world.width/2 - 18, game.height/2 + 60, 'ohhMan');
		game.physics.enable(this.sprite);

		//Impede que o ohhMan saia dos limites da tela
		this.sprite.body.collideWorldBounds = true;

		//Insere pontuao na tela
		var style = { font: "25px Arial", fill: "#ffffff", align: "right" };
		this.scoreText = game.add.text(game.width/2, 20 , "" + this.score, style);
	},

	update : function() {
		this.moveByKeyboard();
		this.verifyMapCollision();
		this.verifyGhostCollision();
		this.verifyBallCollision();
	},

	//Move o ohhMan
	moveByKeyboard : function() {
		//Move o ohhMan na horizontal (esquerda/direita)
		if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
			this.direction = "LEFT";
			this.sprite.body.velocity.x = -this.speed;
			this.sprite.body.velocity.y = 0;
		}
		if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
			this.direction = "RIGHT";
			this.sprite.body.velocity.x = this.speed;
			this.sprite.body.velocity.y = 0;
		}

		//Move o ohhMan na vertical (cima/baixo)
		if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
			this.direction = "UP";
			this.sprite.body.velocity.x = 0;
			this.sprite.body.velocity.y = -this.speed;
		}
		if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
			this.direction = "DOWN";
			this.sprite.body.velocity.x = 0;
			this.sprite.body.velocity.y = this.speed;
		}
	},

	//Verifica a coliso do ohhMan com o mapa
	verifyMapCollision : function() {
		game.physics.arcade.collide(this.sprite, map.layer);
	},

	//Verifica a coliso do ohhMan com os fantasminhas
	verifyGhostCollision : function() {
		if (this.checkOverlap(this.sprite, blinky.sprite) ||
			this.checkOverlap(this.sprite, clyde.sprite) ||
			this.checkOverlap(this.sprite, inkey.sprite) ||
			this.checkOverlap(this.sprite, pinky.sprite))

			game.state.start('sceneLose');
	},

	//Verifica se 2 sprites se sobreporam, ou seja, se eles colidiram
	//VER DEPOIS: VERIFICAR QUAL O MELHOR ARQUIVO PRA ESTE MDOTO FICAR
	checkOverlap : function(spriteA, spriteB) {
	    var boundsA = spriteA.getBounds();
	    var boundsB = spriteB.getBounds();

	    return Phaser.Rectangle.intersects(boundsA, boundsB);
	},

	//Verifica a coliso do ohhMan com as bolinhas amarelas
	verifyBallCollision : function() {
		//this.sprite.body.setSize(6, 6);
		game.physics.arcade.overlap(this.sprite, map.balls, this.removeBall, null, this);
		//this.sprite.body.setSize(36, 36);
	},

	//Remove a bolinha amarela aps coliso com o Ohhman
	removeBall : function(player, ball) {
		 ball.kill();
		 this.punctuate();
	},

	//Soma dez pontos a cada bolinha removida
	punctuate : function () {
		this.score += 10;
	    this.scoreText.setText( "" + this.score );
	}
};
<commit_msg>[Ohhman][Phaser] New score position<commit_after>Ohhman = function () {
	this.sprite = null;
	this.speed = 200;

	this.direction; //LEFT, RIGHT, UP, DOWN

	this.score = 0;
	this.scoreText = null;
};

Ohhman.prototype = {
	preload : function() {
		//Carrega o sprite do ohhMan
		game.load.image('ohhMan', fp_ohhMan);
	},

	create : function() {
		//Adiciona o ohhMan na tela
		this.sprite = game.add.sprite(game.world.width/2 - 18, game.height/2 + 60, 'ohhMan');
		game.physics.enable(this.sprite);

		//Impede que o ohhMan saia dos limites da tela
		this.sprite.body.collideWorldBounds = true;

		//Insere pontuao na tela
		var style = { font: "25px Arial", fill: "#ffffff", align: "right" };
		this.scoreText = game.add.text(game.width/2, 10 , "" + this.score, style);
	},

	update : function() {
		this.moveByKeyboard();
		this.verifyMapCollision();
		this.verifyGhostCollision();
		this.verifyBallCollision();
	},

	//Move o ohhMan
	moveByKeyboard : function() {
		//Move o ohhMan na horizontal (esquerda/direita)
		if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
			this.direction = "LEFT";
			this.sprite.body.velocity.x = -this.speed;
			this.sprite.body.velocity.y = 0;
		}
		if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
			this.direction = "RIGHT";
			this.sprite.body.velocity.x = this.speed;
			this.sprite.body.velocity.y = 0;
		}

		//Move o ohhMan na vertical (cima/baixo)
		if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
			this.direction = "UP";
			this.sprite.body.velocity.x = 0;
			this.sprite.body.velocity.y = -this.speed;
		}
		if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
			this.direction = "DOWN";
			this.sprite.body.velocity.x = 0;
			this.sprite.body.velocity.y = this.speed;
		}
	},

	//Verifica a coliso do ohhMan com o mapa
	verifyMapCollision : function() {
		game.physics.arcade.collide(this.sprite, map.layer);
	},

	//Verifica a coliso do ohhMan com os fantasminhas
	verifyGhostCollision : function() {
		if (this.checkOverlap(this.sprite, blinky.sprite) ||
			this.checkOverlap(this.sprite, clyde.sprite) ||
			this.checkOverlap(this.sprite, inkey.sprite) ||
			this.checkOverlap(this.sprite, pinky.sprite))

			game.state.start('sceneLose');
	},

	//Verifica se 2 sprites se sobreporam, ou seja, se eles colidiram
	//VER DEPOIS: VERIFICAR QUAL O MELHOR ARQUIVO PRA ESTE MDOTO FICAR
	checkOverlap : function(spriteA, spriteB) {
	    var boundsA = spriteA.getBounds();
	    var boundsB = spriteB.getBounds();

	    return Phaser.Rectangle.intersects(boundsA, boundsB);
	},

	//Verifica a coliso do ohhMan com as bolinhas amarelas
	verifyBallCollision : function() {
		//this.sprite.body.setSize(6, 6);
		game.physics.arcade.overlap(this.sprite, map.balls, this.removeBall, null, this);
		//this.sprite.body.setSize(36, 36);
	},

	//Remove a bolinha amarela aps coliso com o Ohhman
	removeBall : function(player, ball) {
		 ball.kill();
		 this.punctuate();
	},

	//Soma dez pontos a cada bolinha removida
	punctuate : function () {
		this.score += 10;
	    this.scoreText.setText( "" + this.score );
	}
};
<|endoftext|>


<commit_before>"use strict";
var mysql = require('mysql');

var fs = require('fs');
var conf = JSON.parse(fs.readFileSync('conf.json'));

/**
 * add a page to the database
 */
var add = function(opts) {
    var connection = mysql.createConnection(conf.mysql);

    console.log("store: " + opts.url);
    connection.query(
        {
            sql:'SELECT COUNT(*) AS tally FROM pages WHERE url = ?',
            values: [opts.url]
        },
        function(err, rows, fields) {
            if (err) throw err;

            if ( rows[0].tally > 0 ) {
                console.log("looks like " + opts.url + "is already in the db");
                connection.end(function(err) {
                    //console.log("mysql connection closed: " + err);
                });

            }
            else {
                connection.query("INSERT INTO pages SET ?", {
                    url: opts.url,
                    score: opts.score,
                    title: opts.title,
                    tstamp: opts.tstamp,
                    generator: opts.generator,
                    created_at: new Date()
                }, function(err, result) {
                    console.log(err);
                    console.log(result);
                });

                connection.end(function(err) {
                    //console.log("mysql connection closed: " + err);
                });
            }
        });

};

/**
 * Pick a random page from the datavase, and mark is as posted so we only render it at once.
 * Using RAND() here is pretty awful but performance isn't much of an issue.
 */
var getAndMarkRandom = function(cb) {
    var connection = mysql.createConnection(conf.mysql);
    connection.query(
        {
            sql:'SELECT * FROM pages ORDER BY RAND() LIMIT 1'
        },
        function(err, rows, fields) {
            if (err) throw err;
            var result = rows[0];
            console.log(result);
            connection.query("UPDATE pages SET posted_at = NOW() WHERE id = " + result.id,
                             function(err, result) {
                                 console.log(err);
                                 console.log(result);
                             });

            connection.end(function(err) {
            });

            cb(result);
        });

};

exports.add = add;
exports.getAndMarkRandom = getAndMarkRandom;<commit_msg>oops, this query wasn't checking if the page was already posts<commit_after>"use strict";
var mysql = require('mysql');

var fs = require('fs');
var conf = JSON.parse(fs.readFileSync('conf.json'));

/**
 * add a page to the database
 */
var add = function(opts) {
    var connection = mysql.createConnection(conf.mysql);

    console.log("store: " + opts.url);
    connection.query(
        {
            sql:'SELECT COUNT(*) AS tally FROM pages WHERE url = ?',
            values: [opts.url]
        },
        function(err, rows, fields) {
            if (err) throw err;

            if ( rows[0].tally > 0 ) {
                console.log("looks like " + opts.url + "is already in the db");
                connection.end(function(err) {
                    //console.log("mysql connection closed: " + err);
                });

            }
            else {
                connection.query("INSERT INTO pages SET ?", {
                    url: opts.url,
                    score: opts.score,
                    title: opts.title,
                    tstamp: opts.tstamp,
                    generator: opts.generator,
                    created_at: new Date()
                }, function(err, result) {
                    console.log(err);
                    console.log(result);
                });

                connection.end(function(err) {
                    //console.log("mysql connection closed: " + err);
                });
            }
        });

};

/**
 * Pick a random page from the datavase, and mark is as posted so we only render it at once.
 * Using RAND() here is pretty awful but performance isn't much of an issue.
 */
var getAndMarkRandom = function(cb) {
    var connection = mysql.createConnection(conf.mysql);
    connection.query(
        {
            sql:'SELECT * FROM pages WHERE posted_at IS NULL ORDER BY RAND() LIMIT 1'
        },
        function(err, rows, fields) {
            if (err) throw err;
            var result = rows[0];
            console.log(result);
            connection.query("UPDATE pages SET posted_at = NOW() WHERE id = " + result.id,
                             function(err, result) {
                                 console.log(err);
                                 console.log(result);
                             });

            connection.end(function(err) {
            });

            cb(result);
        });

};

exports.add = add;
exports.getAndMarkRandom = getAndMarkRandom;
<|endoftext|>


<commit_before>/*
Copyright 2011 Museum of Moving Image

Licensed under the Educational Community License (ECL), Version 2.0.
You may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global cspace:true, jQuery, fluid*/

cspace = cspace || {};

(function ($, fluid) {
    "use strict";

    fluid.defaults("cspace.mediaUploader", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        parentBundle: "{globalBundle}",
        preInitFunction: "cspace.mediaUploader.preInit",
        finalInitFunction: "cspace.mediaUploader.finalInit",
        invokers: {
            displayErrorMessage: "cspace.util.displayErrorMessage"
        },
        elPaths: {
            blobCsid: "fields.blobCsid",
            sourceUrl: "fields.sourceUrl",
            blobs: "fields.blobs",
            externalUrl: "fields.externalUrl",
            required: "fields.identificationNumber"
        },
        mergePolicy: {
            model: "preserve",
            applier: "nomerge"
        },
        selectors: {
            uploader: ".csc-mediaUploader",
            uploadButton: ".csc-mediaUploader-uploadButton",
            uploadButtonLabel: ".csc-mediaUploader-uploadButtonLabel",
            uploadButtonInput: ".csc-mediaUploader-uploadButtonInput",
            uploadMediaLabel: ".csc-mediaUploader-uploadMedia-label",
            linkInput: ".csc-mediaUploader-linkInput",
            linkButton: ".csc-mediaUploader-linkButton",
            linkMediaLabel: ".csc-mediaUploader-linkMedia-label",
            removeButton: ".csc-mediaUploader-removeMedia",
            note: ".csc-mediaUploader-note"
        },
        strings: {},
        styles: {
            uploadButton: "cs-mediaUploader-uploadButton",
            uploadButtonLabel: "cs-mediaUploader-uploadButtonLabel",
            uploadButtonInput: "cs-mediaUploader-uploadButtonInput",
            fileInputFocused: "cs-mediaUploader-fileInputFocused",
            button: "cs-mediaUploader-button",
            hidden: "hidden",
            removeButton: "cs-mediaUploader-removeMedia",
            disabled: "cs-disabled",
            note: "cs-mediaUploader-note"
        },
        events: {
            onLink: null,
            onRemove: null,
            onFileSelected: null,
            onSuccess: null,
            onError: null
        },
        listeners: {
            onSuccess: "{that}.onSuccess",
            onError: "{that}.onError",
            onFileSelected: "{loadingIndicator}.events.showOn.fire"
        },
        produceTree: "cspace.mediaUploader.produceTree",
        renderOnInit: true,
        components: {
            confirmation: "{confirmation}"
        },
        resources: {
            template: {
                expander: {
                    type: "fluid.deferredInvokeCall",
                    func: "cspace.specBuilder",
                    args: {
                        forceCache: true,
                        fetchClass: "fastTemplate",
                        url: "%webapp/html/components/MediaUploaderTemplate.html",
                        options: {
                            dataType: "html"
                        }
                    }
                }
            }
        }
    });

    cspace.mediaUploader.produceTree = function (that) {
        return {
            expander: [{
                type: "fluid.renderer.condition",
                condition: "${" + that.options.elPaths.blobCsid + "}",
                trueTree: {
                    removeButton: {
                        messagekey: "mediaUploader-removeButton",
                        decorators: [{
                            type: "addClass",
                            classes: that.options.styles.removeButton
                        }, {
                            type: "jQuery",
                            func: "click",
                            args: that.removeMedia
                        }]
                    },
                    uploader: {
                        decorators: {addClass: "{styles}.hidden"}
                    }
                },
                falseTree: {
                    uploader: {},
                    removeButton: {
                        decorators: {addClass: "{styles}.hidden"}
                    }
                }
            }],
            uploadMediaLabel: {
                messagekey: "mediaUploader-uploadMediaLabel"
            },
            linkMediaLabel: {
                messagekey: "mediaUploader-linkMediaLabel"
            },
            uploadButton: {
                decorators: [{
                    addClass: "{styles}.button"
                }, {
                    addClass: "{styles}.uploadButton"
                }]
            },
            uploadButtonLabel: {
                messagekey: "mediaUploader-uploadButton",
                decorators: [{addClass: "{styles}.uploadButtonLabel"}]
            },
            uploadButtonInput: {
                decorators: [{
                    addClass: "{styles}.uploadButtonInput"
                }, {
                    type: "jQuery",
                    func: "focus",
                    args: that.uploadFocus
                }, {
                    type: "jQuery",
                    func: "blur",
                    args: that.uploadBlur
                }, {
                    type: "jQuery",
                    func: "change",
                    args: that.upload
                }]
            },
            linkInput: {
                decorators: [{
                    type: "jQuery",
                    func: "keyup",
                    args: that.processLink
                }]
            },
            linkButton: {
                messagekey: "mediaUploader-linkButton",
                decorators: [{
                    type: "addClass",
                    classes: that.options.styles.button
                }, {
                    type: "jQuery",
                    func: "click",
                    args: that.linkMedia
                }]
            },
            note: {
                messagekey: "mediaUploader-note",
                decorators: {addClass: "{styles}.note"}
            }
        };
    };

    cspace.mediaUploader.preInit = function (that) {
        that.uploadFocus = function () {
            that.locate("uploadButton").addClass(that.options.styles.fileInputFocused);
            if (that.file) {
                delete that.file;
            }
        };
        that.uploadBlur = function () {
            that.locate("uploadButton").removeClass(that.options.styles.fileInputFocused);
        };
        that.processLink = function () {
            var linkButton = that.locate("linkButton"),
                allow = fluid.get(that.model, that.options.elPaths.required);
            linkButton.prop("disabled", that.locate("linkInput").val() && allow ? false : true);
        };
        that.linkMedia = function () {
            var sourceUrl = that.locate("linkInput").val();
            that.applier.requestChange(that.options.elPaths.sourceUrl, sourceUrl);
            that.applier.requestChange(that.options.elPaths.externalUrl, sourceUrl);
            that.applier.modelChanged.removeListener("allowButtons");
            that.events.onLink.fire();
        };
        that.onSuccess = function (response, xhr) {
            that.applier.requestChange(that.options.elPaths.sourceUrl, response.file);
            delete response.file;
            that.applier.requestChange(that.options.elPaths.blobs, [response]);
            that.applier.requestChange(that.options.elPaths.blobCsid, response.csid);
            that.applier.modelChanged.removeListener("allowButtons");
            // TODO: When the onLink event listener triggers rerender and reinstantiation of media uploader this uploader dies :(.
            setTimeout(function () {
                that.events.onLink.fire();
            }, 1);
        };
        that.onError = function (error, responseText, xhr) {
            cspace.util.provideErrorCallback(that, that.options.urls.upload, "errorWriting")(error, responseText, xhr);
        };
        that.removeMedia = function () {
            that.confirmation.open("cspace.confirmation.deleteDialog", undefined, {
                model: {
                    messages: ["mediaUploader-dialog-removePrimaryMessage", "mediaUploader-dialog-removeSecondaryMessage"],
                    messagekeys: {
                        actText: "mediaUploader-dialog-removeActText",
                        actAlt: "mediaUploader-dialog-removeActAlt"
                    }
                },
                listeners: {
                    onClose: function (userAction) {
                        if (userAction === "act") {
                            that.applier.requestChange(that.options.elPaths.blobCsid, "");
                            that.events.onRemove.fire();
                        }
                    }
                },
                parentBundle: that.options.parentBundle
            });
        };
        that.upload = function () {
            that.file = this.files[0];
            var data = new FormData();
            data.append("file", that.file);
            that.events.onFileSelected.fire();
            $.ajax({
                url: that.options.urls.upload,
                type: "POST",
                cache: false,
                contentType: false,
                processData: false,
                data: data,
                dataType: "json",
                success: that.events.onSuccess.fire,
                error: that.events.onError.fire
            });
        };
    };

    cspace.mediaUploader.finalInit = function (that) {
        var allowButtons = function () {
            var allow = fluid.get(that.model, that.options.elPaths.required),
                buttons = that.locate("uploadButton")
                    .add(that.locate("uploadButtonInput"));
            buttons[allow ? "removeAttr" : "attr"]("disabled", "disabled");
            that.processLink();
        };

        that.applier.modelChanged.addListener(
            that.options.elPaths.required, allowButtons, "allowButtons"
        );
        allowButtons();
    };

    cspace.mediaUploader.assertBlob = function (blobCsid) {
        return !!blobCsid;
    };

    fluid.fetchResources.primeCacheFromResources("cspace.mediaUploader");

})(jQuery, fluid);<commit_msg>NOJIRA: Added comments to media uploader.<commit_after>/*
Copyright 2011 Museum of Moving Image

Licensed under the Educational Community License (ECL), Version 2.0.
You may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global cspace:true, jQuery, fluid*/

cspace = cspace || {};

(function ($, fluid) {
    "use strict";

    // Media uploader component used by media records.
    // Displays upload UI when no media uploaded OR
    // info about the media if it was already uploaded.
    fluid.defaults("cspace.mediaUploader", {
        gradeNames: ["fluid.rendererComponent", "autoInit"],
        parentBundle: "{globalBundle}",
        preInitFunction: "cspace.mediaUploader.preInit",
        finalInitFunction: "cspace.mediaUploader.finalInit",
        invokers: {
            displayErrorMessage: "cspace.util.displayErrorMessage"
        },
        elPaths: {
            blobCsid: "fields.blobCsid",
            sourceUrl: "fields.sourceUrl",
            blobs: "fields.blobs",
            externalUrl: "fields.externalUrl",
            required: "fields.identificationNumber"
        },
        mergePolicy: {
            model: "preserve",
            applier: "nomerge"
        },
        selectors: {
            uploader: ".csc-mediaUploader",
            uploadButton: ".csc-mediaUploader-uploadButton",
            uploadButtonLabel: ".csc-mediaUploader-uploadButtonLabel",
            uploadButtonInput: ".csc-mediaUploader-uploadButtonInput",
            uploadMediaLabel: ".csc-mediaUploader-uploadMedia-label",
            linkInput: ".csc-mediaUploader-linkInput",
            linkButton: ".csc-mediaUploader-linkButton",
            linkMediaLabel: ".csc-mediaUploader-linkMedia-label",
            removeButton: ".csc-mediaUploader-removeMedia",
            note: ".csc-mediaUploader-note"
        },
        strings: {},
        styles: {
            uploadButton: "cs-mediaUploader-uploadButton",
            uploadButtonLabel: "cs-mediaUploader-uploadButtonLabel",
            uploadButtonInput: "cs-mediaUploader-uploadButtonInput",
            fileInputFocused: "cs-mediaUploader-fileInputFocused",
            button: "cs-mediaUploader-button",
            hidden: "hidden",
            removeButton: "cs-mediaUploader-removeMedia",
            disabled: "cs-disabled",
            note: "cs-mediaUploader-note"
        },
        events: {
            onLink: null,
            onRemove: null,
            onFileSelected: null,
            onSuccess: null,
            onError: null
        },
        listeners: {
            onSuccess: "{that}.onSuccess",
            onError: "{that}.onError",
            onFileSelected: "{loadingIndicator}.events.showOn.fire"
        },
        produceTree: "cspace.mediaUploader.produceTree",
        renderOnInit: true,
        components: {
            confirmation: "{confirmation}"
        },
        // Media uploader template.
        resources: {
            template: {
                expander: {
                    type: "fluid.deferredInvokeCall",
                    func: "cspace.specBuilder",
                    args: {
                        forceCache: true,
                        fetchClass: "fastTemplate",
                        url: "%webapp/html/components/MediaUploaderTemplate.html",
                        options: {
                            dataType: "html"
                        }
                    }
                }
            }
        }
    });

    // Media uploader's produce tree.
    cspace.mediaUploader.produceTree = function (that) {
        return {
            // If no media uploaded render uploader part.
            // Otherwise the info part.
            expander: [{
                type: "fluid.renderer.condition",
                condition: "${" + that.options.elPaths.blobCsid + "}",
                trueTree: {
                    removeButton: {
                        messagekey: "mediaUploader-removeButton",
                        decorators: [{
                            type: "addClass",
                            classes: that.options.styles.removeButton
                        }, {
                            type: "jQuery",
                            func: "click",
                            args: that.removeMedia
                        }]
                    },
                    uploader: {
                        decorators: {addClass: "{styles}.hidden"}
                    }
                },
                falseTree: {
                    uploader: {},
                    removeButton: {
                        decorators: {addClass: "{styles}.hidden"}
                    }
                }
            }],
            uploadMediaLabel: {
                messagekey: "mediaUploader-uploadMediaLabel"
            },
            linkMediaLabel: {
                messagekey: "mediaUploader-linkMediaLabel"
            },
            uploadButton: {
                decorators: [{
                    addClass: "{styles}.button"
                }, {
                    addClass: "{styles}.uploadButton"
                }]
            },
            uploadButtonLabel: {
                messagekey: "mediaUploader-uploadButton",
                decorators: [{addClass: "{styles}.uploadButtonLabel"}]
            },
            uploadButtonInput: {
                decorators: [{
                    addClass: "{styles}.uploadButtonInput"
                }, {
                    type: "jQuery",
                    func: "focus",
                    args: that.uploadFocus
                }, {
                    type: "jQuery",
                    func: "blur",
                    args: that.uploadBlur
                }, {
                    type: "jQuery",
                    func: "change",
                    args: that.upload
                }]
            },
            linkInput: {
                decorators: [{
                    type: "jQuery",
                    func: "keyup",
                    args: that.processLink
                }]
            },
            linkButton: {
                messagekey: "mediaUploader-linkButton",
                decorators: [{
                    type: "addClass",
                    classes: that.options.styles.button
                }, {
                    type: "jQuery",
                    func: "click",
                    args: that.linkMedia
                }]
            },
            note: {
                messagekey: "mediaUploader-note",
                decorators: {addClass: "{styles}.note"}
            }
        };
    };

    cspace.mediaUploader.preInit = function (that) {
        // Handler focus on the upload button.
        that.uploadFocus = function () {
            that.locate("uploadButton").addClass(that.options.styles.fileInputFocused);
            // Clear if file was selected.
            if (that.file) {
                delete that.file;
            }
        };
        // Handler blur on the upload button.
        that.uploadBlur = function () {
            that.locate("uploadButton").removeClass(that.options.styles.fileInputFocused);
        };
        // Process link that was typed into the link text field.
        that.processLink = function () {
            var linkButton = that.locate("linkButton"),
                allow = fluid.get(that.model, that.options.elPaths.required);
            linkButton.prop("disabled", that.locate("linkInput").val() && allow ? false : true);
        };
        // Link media in the model and fire onLink that will trigger record
        // save.
        that.linkMedia = function () {
            var sourceUrl = that.locate("linkInput").val();
            that.applier.requestChange(that.options.elPaths.sourceUrl, sourceUrl);
            that.applier.requestChange(that.options.elPaths.externalUrl, sourceUrl);
            that.applier.modelChanged.removeListener("allowButtons");
            that.events.onLink.fire();
        };
        // OnSuccess upload event handler, will trigger onLink consequent
        // record save.
        that.onSuccess = function (response, xhr) {
            that.applier.requestChange(that.options.elPaths.sourceUrl, response.file);
            delete response.file;
            that.applier.requestChange(that.options.elPaths.blobs, [response]);
            that.applier.requestChange(that.options.elPaths.blobCsid, response.csid);
            that.applier.modelChanged.removeListener("allowButtons");
            // TODO: When the onLink event listener triggers rerender and reinstantiation of media uploader this uploader dies :(.
            setTimeout(function () {
                that.events.onLink.fire();
            }, 1);
        };
        // If upload resulted in error, update message bar.
        that.onError = function (error, responseText, xhr) {
            cspace.util.provideErrorCallback(that, that.options.urls.upload, "errorWriting")(error, responseText, xhr);
        };
        // Remove media link from the model.
        that.removeMedia = function () {
            that.confirmation.open("cspace.confirmation.deleteDialog", undefined, {
                model: {
                    messages: ["mediaUploader-dialog-removePrimaryMessage", "mediaUploader-dialog-removeSecondaryMessage"],
                    messagekeys: {
                        actText: "mediaUploader-dialog-removeActText",
                        actAlt: "mediaUploader-dialog-removeActAlt"
                    }
                },
                listeners: {
                    onClose: function (userAction) {
                        if (userAction === "act") {
                            that.applier.requestChange(that.options.elPaths.blobCsid, "");
                            that.events.onRemove.fire();
                        }
                    }
                },
                parentBundle: that.options.parentBundle
            });
        };
        // A method that does the actual upload through input file.
        that.upload = function () {
            that.file = this.files[0];
            var data = new FormData();
            data.append("file", that.file);
            that.events.onFileSelected.fire();
            $.ajax({
                url: that.options.urls.upload,
                type: "POST",
                cache: false,
                contentType: false,
                processData: false,
                data: data,
                dataType: "json",
                success: that.events.onSuccess.fire,
                error: that.events.onError.fire
            });
        };
    };

    cspace.mediaUploader.finalInit = function (that) {
        var allowButtons = function () {
            var allow = fluid.get(that.model, that.options.elPaths.required),
                buttons = that.locate("uploadButton")
                    .add(that.locate("uploadButtonInput"));
            buttons[allow ? "removeAttr" : "attr"]("disabled", "disabled");
            that.processLink();
        };

        that.applier.modelChanged.addListener(
            that.options.elPaths.required, allowButtons, "allowButtons"
        );
        allowButtons();
    };

    // Assert if media was already uploaded to the record.
    cspace.mediaUploader.assertBlob = function (blobCsid) {
        return !!blobCsid;
    };

    fluid.fetchResources.primeCacheFromResources("cspace.mediaUploader");

})(jQuery, fluid);<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var TestApp = (function () {
  function TestApp() {
    _classCallCheck(this, TestApp);
  }

  _createClass(TestApp, [{
    key: "testfunction",
    value: function testfunction() {
      console.log("hello World!");
    }
  }]);

  return TestApp;
})();

},{}]},{},[1])
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCIvVXNlcnMvc2NvdHQvRGV2L2d1bHAtYnVpbGQvYXBwL3NyYy90ZXN0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7O0lDQU0sT0FBTztXQUFQLE9BQU87MEJBQVAsT0FBTzs7O2VBQVAsT0FBTzs7V0FDQyx3QkFBRztBQUNiLGFBQU8sQ0FBQyxHQUFHLENBQUMsY0FBYyxDQUFDLENBQUM7S0FDN0I7OztTQUhHLE9BQU8iLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbIihmdW5jdGlvbiBlKHQsbixyKXtmdW5jdGlvbiBzKG8sdSl7aWYoIW5bb10pe2lmKCF0W29dKXt2YXIgYT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2lmKCF1JiZhKXJldHVybiBhKG8sITApO2lmKGkpcmV0dXJuIGkobywhMCk7dmFyIGY9bmV3IEVycm9yKFwiQ2Fubm90IGZpbmQgbW9kdWxlICdcIitvK1wiJ1wiKTt0aHJvdyBmLmNvZGU9XCJNT0RVTEVfTk9UX0ZPVU5EXCIsZn12YXIgbD1uW29dPXtleHBvcnRzOnt9fTt0W29dWzBdLmNhbGwobC5leHBvcnRzLGZ1bmN0aW9uKGUpe3ZhciBuPXRbb11bMV1bZV07cmV0dXJuIHMobj9uOmUpfSxsLGwuZXhwb3J0cyxlLHQsbixyKX1yZXR1cm4gbltvXS5leHBvcnRzfXZhciBpPXR5cGVvZiByZXF1aXJlPT1cImZ1bmN0aW9uXCImJnJlcXVpcmU7Zm9yKHZhciBvPTA7bzxyLmxlbmd0aDtvKyspcyhyW29dKTtyZXR1cm4gc30pIiwiY2xhc3MgVGVzdEFwcCB7XG4gIHRlc3RmdW5jdGlvbigpIHtcbiAgICBjb25zb2xlLmxvZyhcImhlbGxvIFdvcmxkIVwiKTtcbiAgfVxufVxuIl19
<commit_msg>stuff<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var _createClass = (function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
    }
  }return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  };
})();

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var TestApp = (function () {
  function TestApp() {
    _classCallCheck(this, TestApp);
  }

  _createClass(TestApp, [{
    key: "testfunction",
    value: function testfunction() {
      console.log("hello World!");
    }
  }]);

  return TestApp;
})();

},{}]},{},[1])
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCIvVXNlcnMvc2NvdHQvRGV2L2d1bHAtYnVpbGQvYXBwL3NyYy90ZXN0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FDQUEsWUFBWSxDQUFDOztBQUViLElBQUksWUFBWSxHQUFHLENBQUMsWUFBWTtBQUFFLFdBQVMsZ0JBQWdCLENBQUMsTUFBTSxFQUFFLEtBQUssRUFBRTtBQUFFLFNBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxLQUFLLENBQUMsTUFBTSxFQUFFLENBQUMsRUFBRSxFQUFFO0FBQUUsVUFBSSxVQUFVLEdBQUcsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLFVBQVcsQ0FBQyxVQUFVLEdBQUcsVUFBVSxDQUFDLFVBQVUsSUFBSSxLQUFLLENBQUMsVUFBVyxDQUFDLFlBQVksR0FBRyxJQUFJLENBQUMsSUFBSyxPQUFPLElBQUksVUFBVSxFQUFFLFVBQVUsQ0FBQyxRQUFRLEdBQUcsSUFBSSxDQUFDLE1BQU8sQ0FBQyxjQUFjLENBQUMsTUFBTSxFQUFFLFVBQVUsQ0FBQyxHQUFHLEVBQUUsVUFBVSxDQUFDLENBQUM7S0FBRTtHQUFFLE9BQVEsVUFBVSxXQUFXLEVBQUUsVUFBVSxFQUFFLFdBQVcsRUFBRTtBQUFFLFFBQUksVUFBVSxFQUFFLGdCQUFnQixDQUFDLFdBQVcsQ0FBQyxTQUFTLEVBQUUsVUFBVSxDQUFDLENBQUMsSUFBSyxXQUFXLEVBQUUsZ0JBQWdCLENBQUMsV0FBVyxFQUFFLFdBQVcsQ0FBQyxDQUFDLE9BQVEsV0FBVyxDQUFDO0dBQUUsQ0FBQztDQUFFLENBQUEsRUFBRyxDQUFDOztBQUV0akIsU0FBUyxlQUFlLENBQUMsUUFBUSxFQUFFLFdBQVcsRUFBRTtBQUFFLE1BQUksRUFBRSxRQUFRLFlBQVksV0FBVyxDQUFBLEVBQUc7QUFBRSxVQUFNLElBQUksU0FBUyxDQUFDLG1DQUFtQyxDQUFDLENBQUM7R0FBRTtDQUFFOztBQUV6SixJQU5NLE9BQU8sR0FBQSxDQUFBLFlBQUE7QUFPWCxXQVBJLE9BQU8sR0FBQTtBQVFULG1CQUFlLENBQUMsSUFBSSxFQVJsQixPQUFPLENBQUEsQ0FBQTtHQVNWOztBQUVELGNBQVksQ0FYUixPQUFPLEVBQUEsQ0FBQTtBQVlULE9BQUcsRUFBRSxjQUFjO0FBQ25CLFNBQUssRUFaSyxTQUFBLFlBQUEsR0FBRztBQUNiLGFBQU8sQ0FBQyxHQUFHLENBQUMsY0FBYyxDQUFDLENBQUM7S0FDN0I7R0FhQSxDQUFDLENBQUMsQ0FBQzs7QUFFSixTQWxCSSxPQUFPLENBQUE7Q0FtQlosQ0FBQSxFQUFHLENBQUMiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbIihmdW5jdGlvbiBlKHQsbixyKXtmdW5jdGlvbiBzKG8sdSl7aWYoIW5bb10pe2lmKCF0W29dKXt2YXIgYT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2lmKCF1JiZhKXJldHVybiBhKG8sITApO2lmKGkpcmV0dXJuIGkobywhMCk7dmFyIGY9bmV3IEVycm9yKFwiQ2Fubm90IGZpbmQgbW9kdWxlICdcIitvK1wiJ1wiKTt0aHJvdyBmLmNvZGU9XCJNT0RVTEVfTk9UX0ZPVU5EXCIsZn12YXIgbD1uW29dPXtleHBvcnRzOnt9fTt0W29dWzBdLmNhbGwobC5leHBvcnRzLGZ1bmN0aW9uKGUpe3ZhciBuPXRbb11bMV1bZV07cmV0dXJuIHMobj9uOmUpfSxsLGwuZXhwb3J0cyxlLHQsbixyKX1yZXR1cm4gbltvXS5leHBvcnRzfXZhciBpPXR5cGVvZiByZXF1aXJlPT1cImZ1bmN0aW9uXCImJnJlcXVpcmU7Zm9yKHZhciBvPTA7bzxyLmxlbmd0aDtvKyspcyhyW29dKTtyZXR1cm4gc30pIiwiY2xhc3MgVGVzdEFwcCB7XG4gIHRlc3RmdW5jdGlvbigpIHtcbiAgICBjb25zb2xlLmxvZyhcImhlbGxvIFdvcmxkIVwiKTtcbiAgfVxufVxuIl19
<|endoftext|>


<commit_before>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    // get current user
    getCurrentUser();
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // update the view with the new user info
      updateLoginDisplayElements(data);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "http://localhost:4200?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;

}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info', 'fetched API Key ' + apiKey);
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {
  localStorage.removeItem('APIKey');
  updateLoginDisplayElements(undefined);
  replaceALLApiKeyByStoredApiKey(undefined);
}

function updateLoginDisplayElements(currentUser) {
  if (currentUser) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('welcome ' + currentUser.email);
    $('#header-welcome-message').css('display', 'inline-block');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

/**
 * copy the content of the element given in param
 *
 * @param {*} elementId id of the HTML element
 */
function copyToClipBoard(elementId) {
  var range = document.createRange();
  var copyText = document.getElementById(elementId);
  if (!copyText) {
    return;
  }
  range.selectNode(copyText);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy")
  selection.removeAllRanges();
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  console.log('here', apiKey);
  $("body").children().each(function () {
    if (!apiKey) {
      $(this).html($(this).html().replace(/\$API_KEY/g,
        ""
        + "login to retrieve your api-key"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

$(document).ready(function () {

  //get ApiKey if one time login token present in url
  getApiKeyIfOneTimeLoginTokenIsPresent();

  formatJSONCode();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<commit_msg>not always try to log the user. More to come<commit_after>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "http://localhost:4200?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;

}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info', 'fetched API Key ' + apiKey);
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');
  updateLoginDisplayElements(undefined);
  replaceALLApiKeyByStoredApiKey(undefined);
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

/**
 * copy the content of the element given in param
 *
 * @param {*} elementId id of the HTML element
 */
function copyToClipBoard(elementId) {
  var range = document.createRange();
  var copyText = document.getElementById(elementId);
  if (!copyText) {
    return;
  }
  range.selectNode(copyText);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy")
  selection.removeAllRanges();
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {
      $(this).html($(this).html().replace(/\$API_KEY/g,
        ""
        + "login to retrieve your api-key"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

$(document).ready(function () {
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<|endoftext|>


<commit_before>sap.ui.define(['sap/ui/core/UIComponent'],
	function(UIComponent) {
	"use strict";

	var Component = UIComponent.extend("sap.ui.core.sample.OpaTestLibrary.Component", {

		metadata : {
			dependencies : {
				libs : [
					"sap.m"
				]
			},
			config : {
				sample : {
					iframe : "OpaTestLibrary.html?opaExecutionDelay=700",
					stretch : true,
					files : [
						"OpaTestLibrary.html",
						"OpaTestLibrary.js",
						"applicationUnderTest/index.html",
						"applicationUnderTest/Component.js",
						"applicationUnderTest/view/Main.view.xml",
						"applicationUnderTest/view/Main.controller.js",
						"pageObjects/Item.js",
						"testLibrary/pageObjects/List.js"
					]
				}
			}
		}

	});

	return Component;

});
<commit_msg>[INTERNAL][FIX] Opa: add missing test library sample files<commit_after>sap.ui.define(['sap/ui/core/UIComponent'],
	function(UIComponent) {
	"use strict";

	var Component = UIComponent.extend("sap.ui.core.sample.OpaTestLibrary.Component", {

		metadata : {
			dependencies : {
				libs : [
					"sap.m"
				]
			},
			config : {
				sample : {
					iframe : "OpaTestLibrary.html?opaExecutionDelay=700",
					stretch : true,
					files : [
						"OpaTestLibrary.html",
						"OpaTestLibrary.js",
						"applicationUnderTest/index.html",
						"applicationUnderTest/Component.js",
						"applicationUnderTest/view/Main.view.xml",
						"applicationUnderTest/view/Main.controller.js",
						"pageObjects/Item.js",
						"testLibrary/pageObjects/List.js",
						"testLibrary/pageObjects/Common1.js",
						"testLibrary/pageObjects/Common2.js"
					]
				}
			}
		}

	});

	return Component;

});
<|endoftext|>