<commit_before>/*
 * Copyright 2005-2013 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {
	$.fn.selectTab = function(options){
		return this.each(function(){
			options = options || {};
			//default setting
			options = $.extend({
				selectPage: ""
			}, options);

			if(options.selectPage){
                var oldTab = $(this).find(".ui-state-active");
                if(oldTab.length){
                    oldTab.removeClass("ui-state-active");
                }

				var currentTab = $(this).find("a[name='" + options.selectPage + "']");
				if(currentTab.length){
					currentTab.parent().addClass("ui-state-active");
				}
			}
		});
	}

	$.fn.tabMenu = function(options){
		return this.each(function(){
			options = options || {};
			//default setting
			options = $.extend({
				defaultSelectFirst: true,
				currentPage: ""
			}, options);

			//element id strings
			var id = $(this).parent().attr('id');
			var list_elements = "#" + id + " li";
			var link_elements = list_elements + " a";

			//Styling
			$(this).parent().addClass("ui-tabs tab-navigation-block");
			$(this).addClass("ui-helper-reset ui-helper-clearfix uif-tabMenu");
			$(list_elements).addClass("ui-state-default ui-corner-top");
			if(options.currentPage){
				var currentTab = $(this).find("a[name='" + options.currentPage + "']");
				if(currentTab){
					currentTab.closest("li").addClass("ui-state-active");
				}
			}
			//Handlers and animation
			$(document).ready(function()
			{
					$(link_elements).each(function(i)
					{
						if(i == 0 && options.defaultSelectFirst && !options.currentPage){
							$(this).closest("li").addClass("ui-state-active");
						}
						$(this).focus(
						function()
						{
							$(this).closest("li").addClass("ui-state-focus");
						});

                        $(this).click(
						function()
						{
							$(link_elements).each(function(){$(this).closest("li").removeClass("ui-state-active")});
							$(this).closest("li").addClass("ui-state-active");
						});

						$(this).hover(
						function()
						{
							$(this).closest("li").addClass("ui-state-hover");
						},
						function()
						{
							$(this).closest("li").removeClass("ui-state-hover");
						});

						$(this).blur(
						function()
						{
							$(this).closest("li").removeClass("ui-state-focus");
						});
					});
			});
		});
	}
})(jQuery);<commit_msg>UXI-86 Swapping out JQuery UI styling with Bootstrap classes & styling<commit_after>/*
 * Copyright 2005-2013 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {
	$.fn.selectTab = function(options){
		return this.each(function(){
			options = options || {};
			//default setting
			options = $.extend({
				selectPage: ""
			}, options);

			if(options.selectPage){
                var oldTab = $(this).find(".active");
                if(oldTab.length){
                    oldTab.removeClass("active");
                }

				var currentTab = $(this).find("a[name='" + options.selectPage + "']");
				if(currentTab.length){
					currentTab.parent().addClass("active");
				}
			}
		});
	}

	$.fn.tabMenu = function(options){
		return this.each(function(){
			options = options || {};
			//default setting
			options = $.extend({
				defaultSelectFirst: true,
				currentPage: ""
			}, options);

			//element id strings
			var id = $(this).parent().attr('id');
			var list_elements = "#" + id + " li";
			var link_elements = list_elements + " a";

			//Styling
			$(this).parent().addClass("");
			$(this).addClass("uif-tabMenu");
			$(list_elements).addClass("");
			if(options.currentPage){
				var currentTab = $(this).find("a[name='" + options.currentPage + "']");
				if(currentTab){
					currentTab.closest("li").addClass("active");
				}
			}
			//Handlers and animation
			$(document).ready(function()
			{
					$(link_elements).each(function(i)
					{
						if(i == 0 && options.defaultSelectFirst && !options.currentPage){
							$(this).closest("li").addClass("active");
						}
						$(this).focus(
						function()
						{
							$(this).closest("li").addClass("");
						});

                        $(this).click(
						function()
						{
							$(link_elements).each(function(){$(this).closest("li").removeClass("active")});
							$(this).closest("li").addClass("active");
						});

						$(this).hover(
						function()
						{
							$(this).closest("li").addClass("");
						},
						function()
						{
							$(this).closest("li").removeClass("");
						});

						$(this).blur(
						function()
						{
							$(this).closest("li").removeClass("");
						});
					});
			});
		});
	}
})(jQuery);<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";

    var derive = require("base/derive");
    var assert = require("base/assert");
    var Event = require("boost/Event");
    var NativeElement = require("boost/NativeElement");
    var LayoutPropTypes = require("boost/LayoutPropTypes");
    var StyleSheet = require("boost/StyleSheet");

    var NATIVE_VIEW_TYPE = 20;
    var ViewStyle = derive(StyleSheet, LayoutPropTypes);
    var FgBoostPage = derive(NativeElement, function () {
        //this._super(NATIVE_VIEW_TYPE, "FgBoostPage");
        NativeElement.call(this, NATIVE_VIEW_TYPE, "FgBoostPage");
    }, {
        __onEvent: function (type, event) {
            // 从前台页面传来的消息与页面刷新事件，抛出事件供背景页监听
            if (type === "message") {
                this.dispatchEvent({
                    type: "message",
                    data: event.data
                });
            } else if (type === "pagestarted") {
                this.dispatchEvent({
                    type: "pagestarted",
                    data: event.data
                });
            }
            return event && event.propagationStoped;
        },
        __getStyle: function () {
            return new ViewStyle();
        },
        loadUrl: function (url) {
            this.nativeObject.__callNative("loadUrl", [url]);
        },
        reload: function () {
            this.nativeObject.__callNative("reload", []);
        },
        canGoBackOrForward: function (steps, callback) {
            this.nativeObject.__callNative("canGoBackOrForward", [steps], callback);
        },
        goBackOrForward: function (steps) {
            this.nativeObject.__callNative("goBackOrForward", [steps]);
        },
        goBack: function () {
            this.nativeObject.__callNative("goBack", []);
        },
        dispatchWindowEvent: function (type, data) {
            var javascriptUrl = [
                "javascript:  (function(){" +
                "console.info('event from bg: " + type + ", " + JSON.stringify(data) + "');",
                "   var data = " + JSON.stringify(data) + ";",
                "   var event = document.createEvent('Event');",
                "   event.initEvent(\"" + type + "\" , false, false);",
                "   event.data = data;",
                "   window.dispatchEvent(event);" +
                "})();"
            ].join('');
            this.loadUrl(javascriptUrl);
            console.info("loadUrl of boostPage: ", javascriptUrl);
        },

        updateMenu: function (menuNativeObjectId) {
            this.nativeObject.__callNative("updateMenu", [menuNativeObjectId]);
        },
        dismissMenu: function () {
            this.nativeObject.__callNative("dismissMenu", []);
        },
        //展示关闭按钮
        showExitButton: function (show) {
            this.nativeObject.__callNative("showExitButton", [show]);
        }
    });
    module.exports = FgBoostPage;
});
<commit_msg>增加◊setLoadingTextOnce方法<commit_after>define(function (require, exports, module) {
    "use strict";

    var derive = require("base/derive");
    var assert = require("base/assert");
    var Event = require("boost/Event");
    var NativeElement = require("boost/NativeElement");
    var LayoutPropTypes = require("boost/LayoutPropTypes");
    var StyleSheet = require("boost/StyleSheet");

    var NATIVE_VIEW_TYPE = 20;
    var ViewStyle = derive(StyleSheet, LayoutPropTypes);
    var FgBoostPage = derive(NativeElement, function () {
        //this._super(NATIVE_VIEW_TYPE, "FgBoostPage");
        NativeElement.call(this, NATIVE_VIEW_TYPE, "FgBoostPage");
    }, {
        __onEvent: function (type, event) {
            // 从前台页面传来的消息与页面刷新事件，抛出事件供背景页监听
            if (type === "message") {
                this.dispatchEvent({
                    type: "message",
                    data: event.data
                });
            } else if (type === "pagestarted") {
                this.dispatchEvent({
                    type: "pagestarted",
                    data: event.data
                });
            }
            return event && event.propagationStoped;
        },
        __getStyle: function () {
            return new ViewStyle();
        },
        loadUrl: function (url) {
            this.nativeObject.__callNative("loadUrl", [url]);
        },
        reload: function () {
            this.nativeObject.__callNative("reload", []);
        },
        canGoBackOrForward: function (steps, callback) {
            this.nativeObject.__callNative("canGoBackOrForward", [steps], callback);
        },
        goBackOrForward: function (steps) {
            this.nativeObject.__callNative("goBackOrForward", [steps]);
        },
        goBack: function () {
            this.nativeObject.__callNative("goBack", []);
        },
        dispatchWindowEvent: function (type, data) {
            var javascriptUrl = [
                "javascript:  (function(){" +
                "console.info('event from bg: " + type + ", " + JSON.stringify(data) + "');",
                "   var data = " + JSON.stringify(data) + ";",
                "   var event = document.createEvent('Event');",
                "   event.initEvent(\"" + type + "\" , false, false);",
                "   event.data = data;",
                "   window.dispatchEvent(event);" +
                "})();"
            ].join('');
            this.loadUrl(javascriptUrl);
            console.info("loadUrl of boostPage: ", javascriptUrl);
        },

        updateMenu: function (menuNativeObjectId) {
            this.nativeObject.__callNative("updateMenu", [menuNativeObjectId]);
        },
        dismissMenu: function () {
            this.nativeObject.__callNative("dismissMenu", []);
        },
        //展示关闭按钮
        showExitButton: function (show) {
            this.nativeObject.__callNative("showExitButton", [show]);
        },

        setLoadingTextOnce: function (text) {
            this.nativeObject.__callNative("setLoadingTextOnce", [text]);
        }
    });
    module.exports = FgBoostPage;
});
<|endoftext|>


<commit_before>/*
main.js handles all communication between index.html, api.js and database.js.
And is responsibly for rendering the interface.
Like a spider.
JQuery fetches references to elements in the html to update data there.
When relevant a call is made to functions in api.js, database.js or both.
When sending a request to the api, remember to include a callback function.
*/

$( document ).ready(function() {

//Use as callback when you just want to see response from api call in console
function printToConsole(response) {
  console.log(response);
}

//Update interface (list) when change in database detected
var listRef = document.getElementById("list");
var dbRefList = firebase.database().ref().child('recent');
dbRefList.on('child_added', snap => {
  const li = document.createElement('li');
  li.innerText = snap.val().word;
  listRef.appendChild(li);
});

/********************************************************
* Takes the input from searchfield and makes the API call
*********************************************************/
$( "#searchButton" ).click(function() {
  var searchInput = $( "#searchInput" ).val()
  database.writeWordToRecent(searchInput);
  api.getStation(searchInput, printToConsole);

});

//Handles "enter" press. Suppress standard form submit and instead make API call
$('#custom-search-form').submit(function(e){
  e.preventDefault();
  var searchInput = $( "#searchInput" ).val()
  database.writeWordToRecent(searchInput);
  api.getStation(searchInput, printToConsole);
});

/***********************************************
* Gets the 10 closest stations to Mårdstigen 15
************************************************/
$( "#getNearbyStations" ).click(function() {
 api.getNearbyStations(printToConsole);

});

 /***********************************************
 * Get realtime data for kungshamra?
 ************************************************/
 $( "#getRealTest" ).click(function() {
  api.APIcall_realtid();
});

/***********************************************
* Draw circles on map
************************************************/
var listOfStations = {
  1234: {
    center: {lat: 59.878, lng: 18.629},
    population: 2713
  }
};

$("#ShowMap").click(function () {
 map.drawCircles(listOfStations);
});
console.log( "main.js completely ready" );
});

/***********************************************
* Gets the 10 closest stations to Mårdstigen 15
************************************************/
$( "#getCurrentStations" ).click(function() {
 database.getCurrentStations();

});

/***********************************************
* Generate fake map_data
************************************************/
$( "#fakeMapdata" ).click(function() {
  console.log('Generating fake mapdata...');
  database.updateDelay('siteID3','lat3','long3','avgdelay3','timestamp3');
});

function extractJSON(data){
  console.log('extractJSON');
  console.log(data);
}

$( "#readCurrent" ).click(function() {
  console.log('Reading current data...');
  database.readCurrentDelays(extractJSON);
});

/*********************
* ACTUAL START OF MAIN
**********************/
var LIST_OF_STATIONS = [];

/***************************************
* Generate mapdata and put into database
****************************************/
function updateDatabase(){
  //listOfStations = ["karolinska sjukhuset", "norrtull", "ruddammen", "östra station", "hjorthagen", "storängsbotten", "ropsten", "odenplan", "s:t eriksplan", "karlsbergs station", "karolinska institutet", "hornsberg", "fridhemsplan", "fredhäll", "stora essingen", "centralen", "kungsträdgården", "karlaplan", "radiohuset", "skansen", "skeppsholmen", "reimersholme", "långholmen", "hornstull", "södra station", "tanto", "liljeholmen", "södersjukhuset", "mariatorget", "slussen", "waldemarsudde", "sofia", "gullmarsplan", "norra hammarbyhamnen", "sickla udde", "henriksdalsberget", "sickla köpkvarter", "finnberget", "frihamnen", "kaknästornet"];
  for (i = 0; i<100; i++){
    delaycalculator.platsuppslag(LIST_OF_STATIONS[i], database.updateDelay);
  }
}

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
    console.log("asdf");
     end = new Date().getTime();
  }
}

/*********************
* Generate heat map
**********************/
//Get data from database

function extractionCallback(data){
  console.log('inside extractionCallback');
    var heatmapData = [];
  for(var key in data){
    if(data.hasOwnProperty(key) && data[key].avgDelay > 0){// && (Date.now() - data[key].timestamp) < 900000 ){ //15min
      //console.log(data[key]);
      //console.log(data[key].center.lat);
      //map.drawCircle(data[key]);
        //console.log("hej"+data[key].center.lat);
        heatmapData.push({location: new google.maps.LatLng(data[key].center.lat, data[key].center.lng), weight:data[key].avgDelay});
    }
  }
    map.drawHeatmap(heatmapData);
}

function extractionCallbackStations(data){
  for(var key in data){
      //console.log(data[key]);
      LIST_OF_STATIONS.push(data[key].station);

  }
  console.log(LIST_OF_STATIONS.length);
}

function generateMapCircles(){
  //console.log('inside generateMapCircles');
  map.clearMap();
  database.readCurrentDelays(extractionCallback); //extract from
}

function generateStationList(){

  database.readCurrentStations(extractionCallbackStations);
}

//updateDatabase(getStations.listOfStations);
setInterval(generateMapCircles, 10000);
//setInterval(updateDatabase, 5000);

/***************************************
* Build rest of UI
****************************************/

<commit_msg>added weight<commit_after>/*
main.js handles all communication between index.html, api.js and database.js.
And is responsibly for rendering the interface.
Like a spider.
JQuery fetches references to elements in the html to update data there.
When relevant a call is made to functions in api.js, database.js or both.
When sending a request to the api, remember to include a callback function.
*/

$( document ).ready(function() {

//Use as callback when you just want to see response from api call in console
function printToConsole(response) {
  console.log(response);
}

//Update interface (list) when change in database detected
var listRef = document.getElementById("list");
var dbRefList = firebase.database().ref().child('recent');
dbRefList.on('child_added', snap => {
  const li = document.createElement('li');
  li.innerText = snap.val().word;
  listRef.appendChild(li);
});

/********************************************************
* Takes the input from searchfield and makes the API call
*********************************************************/
$( "#searchButton" ).click(function() {
  var searchInput = $( "#searchInput" ).val()
  database.writeWordToRecent(searchInput);
  api.getStation(searchInput, printToConsole);

});

//Handles "enter" press. Suppress standard form submit and instead make API call
$('#custom-search-form').submit(function(e){
  e.preventDefault();
  var searchInput = $( "#searchInput" ).val()
  database.writeWordToRecent(searchInput);
  api.getStation(searchInput, printToConsole);
});

/***********************************************
* Gets the 10 closest stations to Mårdstigen 15
************************************************/
$( "#getNearbyStations" ).click(function() {
 api.getNearbyStations(printToConsole);

});

 /***********************************************
 * Get realtime data for kungshamra?
 ************************************************/
 $( "#getRealTest" ).click(function() {
  api.APIcall_realtid();
});

/***********************************************
* Draw circles on map
************************************************/
var listOfStations = {
  1234: {
    center: {lat: 59.878, lng: 18.629},
    population: 2713
  }
};

$("#ShowMap").click(function () {
 map.drawCircles(listOfStations);
});
console.log( "main.js completely ready" );
});

/***********************************************
* Gets the 10 closest stations to Mårdstigen 15
************************************************/
$( "#getCurrentStations" ).click(function() {
 database.getCurrentStations();

});

/***********************************************
* Generate fake map_data
************************************************/
$( "#fakeMapdata" ).click(function() {
  console.log('Generating fake mapdata...');
  database.updateDelay('siteID3','lat3','long3','avgdelay3','timestamp3');
});

function extractJSON(data){
  console.log('extractJSON');
  console.log(data);
}

$( "#readCurrent" ).click(function() {
  console.log('Reading current data...');
  database.readCurrentDelays(extractJSON);
});

/*********************
* ACTUAL START OF MAIN
**********************/
var LIST_OF_STATIONS = [];

/***************************************
* Generate mapdata and put into database
****************************************/
function updateDatabase(){
  //listOfStations = ["karolinska sjukhuset", "norrtull", "ruddammen", "östra station", "hjorthagen", "storängsbotten", "ropsten", "odenplan", "s:t eriksplan", "karlsbergs station", "karolinska institutet", "hornsberg", "fridhemsplan", "fredhäll", "stora essingen", "centralen", "kungsträdgården", "karlaplan", "radiohuset", "skansen", "skeppsholmen", "reimersholme", "långholmen", "hornstull", "södra station", "tanto", "liljeholmen", "södersjukhuset", "mariatorget", "slussen", "waldemarsudde", "sofia", "gullmarsplan", "norra hammarbyhamnen", "sickla udde", "henriksdalsberget", "sickla köpkvarter", "finnberget", "frihamnen", "kaknästornet"];
  for (i = 0; i<100; i++){
    delaycalculator.platsuppslag(LIST_OF_STATIONS[i], database.updateDelay);
  }
}

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
    console.log("asdf");
     end = new Date().getTime();
  }
}

/*********************
* Generate heat map
**********************/
//Get data from database

function extractionCallback(data){
  console.log('inside extractionCallback');
    var heatmapData = [];
  for(var key in data){
    if(data.hasOwnProperty(key) && data[key].avgDelay > 0){// && (Date.now() - data[key].timestamp) < 900000 ){ //15min
      //console.log(data[key]);
      //console.log(data[key].center.lat);
      //map.drawCircle(data[key]);
        //console.log("hej"+data[key].center.lat);
        heatmapData.push({location: new google.maps.LatLng(data[key].center.lat, data[key].center.lng), weight:(data[key].avgDelay*12)});
    }
  }
    map.drawHeatmap(heatmapData);
}

function extractionCallbackStations(data){
  for(var key in data){
      //console.log(data[key]);
      LIST_OF_STATIONS.push(data[key].station);

  }
  console.log(LIST_OF_STATIONS.length);
}

function generateMapCircles(){
  //console.log('inside generateMapCircles');
  map.clearMap();
  database.readCurrentDelays(extractionCallback); //extract from
}

function generateStationList(){

  database.readCurrentStations(extractionCallbackStations);
}

//updateDatabase(getStations.listOfStations);
generateMapCircles();
setInterval(generateMapCircles, 10000);
generateStationList(updateDatabase);
setInterval(updateDatabase, 60000);

/***************************************
* Build rest of UI
****************************************/

<|endoftext|>


<commit_before>import enquire from 'enquire.js';

const TABLET_AND_SMALLER = 'screen and (max-width: 975px)',
      DESKTOP_AND_LARGER = 'screen and (min-width: 61em)';
// eslint-disable-next-line import/prefer-default-export
export function initTray() {

  // console.log( 'tray...', $( '.tray-toggle' ));

  function toggleTray() {
    $( '.tray' ).toggleClass( 'tray-closed', 'normal' );
    $( '.tray' ).toggleClass( 'tray-open', 'normal' );

    $( 'body' ).toggleClass( 'noscroll' );
  }

  $( '.tray-toggle' ).click(( e ) => {
    toggleTray();
    // return false;
    e.preventDefault();

  });

  $( '.expanded-draw' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
  });
  $( '.tray-close' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
  });

  $( '.search-toggle' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
    setTimeout(() => {
      $('.tray .search-input').focus();
    }, 500);
  });

  $( 'body' ).on( 'click', ( e ) => {

    // console.log( e.target.className, 'clicked' );
    if ( e.target.className.includes( 'tray-open' )) {
      e.preventDefault();
      toggleTray();
    }

  });

  // $('.search-button-inside form').on('focus', (e) => {
  //   $( this ).toggleClass('focus')
  //   console.log( $(this) );

  // })

  // sidemenu tray

  const SIDEMENU_TOGGLE_CLASS   = 'sidemenu-toggle';
  const SIDEMENU_EXPANDER_CLASS = 'btn-expander';
  const SIDEMENU_SUBMENU_CLASS  = 'has-submenu';

  const SIDEMENU_SELECTED_ITEM_CLASS = 'active';
  const SIDEMENU_EXPANDED_CLASS      = 'expanded';

  function buildTray(index, item) {
    // console.log(index);

    // console.log( 'nav item', $(this).parent().children('a').text() );
    const nav = $(this);

    let navClassString = $(this).parent().children('a').text();
    let titleLink = $(this).parent().children('a').attr('href');
    // console.log(titleLink);

    //push into traw div
    nav.clone().appendTo('.draw-nav').addClass( navClassString ).attr("data-index",index);
    //add title
    $( `.draw-nav ul[data-index='${index}']` ).prepend(`<h4 class="sub-draw-title"><a href="${titleLink}">${navClassString}</a></h4>`);
  }

  let sidemeneuExpanded = false;
  const $draw = $('.sidemenu-drawer');

  function expandTray(index, button) {

    $( button ).on( 'click', () => {

      //toggle sidemenu draw and content

      if( $(button).parent().hasClass('expanded-draw') ) {

        // console.log('has class button close tray');
        sidemeneuExpanded = !sidemeneuExpanded;
        $draw.toggleClass('active');
        $(button).parent().removeClass('expanded-draw');

      } else {

        //show tray
        if (sidemeneuExpanded === false) {
          $draw.addClass('active');
          sidemeneuExpanded = !sidemeneuExpanded;
        }

        $( '.sidemenu-homepage > ul > li').removeClass('expanded-draw');

        $(button).parent().addClass('expanded-draw');
      }

      // console.log(index, button);
      let matchingNavGroup = $(`.draw-nav ul[data-index='${index}']`);
      $('.draw-nav > ul').removeClass('active-nav-group');
      matchingNavGroup.toggleClass('active-nav-group');

    });

  }

  function expandDrawSubContent() {
    // console.log('expand expandDrawSubContent');
    let subDrawExpander = $('.sidemenu-drawer .draw-nav ul ').find('.btn-expander');
    // console.log(subDrawExpander);

    subDrawExpander.each( (i, button) => {

      let $button = $(button);

      $button.on('click', () => {
        console.log($button);
        $button.parent('li').toggleClass('expanded');

      });
    });

  }

  function closeSideMenuDraw() {
    $('.close-draw').on( 'click', ()=> {
      if(sidemeneuExpanded) {
        sidemeneuExpanded = !sidemeneuExpanded;
        $( '.sidemenu-homepage .expanded-draw' ).removeClass( 'expanded-draw' );
        $draw.toggleClass('active');
      }
    });

    //close if body is clicked on?? tbd
    // $( 'body' ).on( 'click', ( e ) => {

    //   console.log( e.target.className, 'clicked' );
    //   // if ( e.target.className.includes( 'tray-open' )) {
    //   //   e.preventDefault();
    //   //   toggleTray();
    //   // }
    //   if(sidemeneuExpanded) {
    //     console.log('sidemenu is expanded');
    //     // sidemeneuExpanded = !sidemeneuExpanded;
    //     // $( '.sidemenu-homepage .expanded-draw' ).removeClass( 'expanded-draw' );
    //     // $draw.toggleClass('active');
    //   } else {
    //     console.log('draw not expanded');
    //   }

    // });

  }

  function sidemenuTray() {
    const menu = $('.sidemenu-homepage');
    // console.log(menu);

    //build tray nav content
    const trayNavItems = $( '.sidemenu-homepage > ul > li > ul' );

    const buttonExpander = $('.sidemenu-homepage > ul > li > .btn-expander');

    // console.log(trayNavItems);

    buttonExpander.each( expandTray );

    trayNavItems.each( buildTray );

    expandDrawSubContent();

    closeSideMenuDraw();

  }

  if ($('.sidemenu-homepage').length  ) {
    // console.log('sidemeny homepage init');

    // enquire.register( TABLET_AND_SMALLER, () => {
    //   console.log('tray is small size for mob');
    //   initSidemenuExpandability( sidemenu-homepage );
    // });

    enquire.register( DESKTOP_AND_LARGER, () => {
      // console.log('Tray is large size cool ');
      sidemenuTray();

    });

  }

}

<commit_msg>Close menu if expanded and clicked outside menu<commit_after>import enquire from 'enquire.js';

const TABLET_AND_SMALLER = 'screen and (max-width: 975px)',
      DESKTOP_AND_LARGER = 'screen and (min-width: 61em)';
// eslint-disable-next-line import/prefer-default-export
export function initTray() {

  // console.log( 'tray...', $( '.tray-toggle' ));

  function toggleTray() {
    $( '.tray' ).toggleClass( 'tray-closed', 'normal' );
    $( '.tray' ).toggleClass( 'tray-open', 'normal' );

    $( 'body' ).toggleClass( 'noscroll' );
  }

  $( '.tray-toggle' ).click(( e ) => {
    toggleTray();
    // return false;
    e.preventDefault();

  });

  $( '.expanded-draw' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
  });
  $( '.tray-close' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
  });

  $( '.search-toggle' ).click(( e ) => {
    e.preventDefault();
    toggleTray();
    setTimeout(() => {
      $('.tray .search-input').focus();
    }, 500);
  });

  $( 'body' ).on( 'click', ( e ) => {

    // console.log( e.target.className, 'clicked' );
    if ( e.target.className.includes( 'tray-open' )) {
      e.preventDefault();
      toggleTray();
    }

  });

  // $('.search-button-inside form').on('focus', (e) => {
  //   $( this ).toggleClass('focus')
  //   console.log( $(this) );

  // })

  // sidemenu tray

  const SIDEMENU_TOGGLE_CLASS   = 'sidemenu-toggle';
  const SIDEMENU_EXPANDER_CLASS = 'btn-expander';
  const SIDEMENU_SUBMENU_CLASS  = 'has-submenu';

  const SIDEMENU_SELECTED_ITEM_CLASS = 'active';
  const SIDEMENU_EXPANDED_CLASS      = 'expanded';

  function buildTray(index, item) {
    // console.log(index);

    // console.log( 'nav item', $(this).parent().children('a').text() );
    const nav = $(this);

    let navClassString = $(this).parent().children('a').text();
    let titleLink = $(this).parent().children('a').attr('href');
    // console.log(titleLink);

    //push into traw div
    nav.clone().appendTo('.draw-nav').addClass( navClassString ).attr("data-index",index);
    //add title
    $( `.draw-nav ul[data-index='${index}']` ).prepend(`<h4 class="sub-draw-title"><a href="${titleLink}">${navClassString}</a></h4>`);
  }

  let sidemeneuExpanded = false;
  const $draw = $('.sidemenu-drawer');

  function expandTray(index, button) {

    $( button ).on( 'click', () => {

      //toggle sidemenu draw and content

      if( $(button).parent().hasClass('expanded-draw') ) {

        // console.log('has class button close tray');
        sidemeneuExpanded = !sidemeneuExpanded;
        $draw.toggleClass('active');
        $(button).parent().removeClass('expanded-draw');

      } else {

        //show tray
        if (sidemeneuExpanded === false) {
          $draw.addClass('active');
          sidemeneuExpanded = !sidemeneuExpanded;
        }

        $( '.sidemenu-homepage > ul > li').removeClass('expanded-draw');

        $(button).parent().addClass('expanded-draw');
      }

      // console.log(index, button);
      let matchingNavGroup = $(`.draw-nav ul[data-index='${index}']`);
      $('.draw-nav > ul').removeClass('active-nav-group');
      matchingNavGroup.toggleClass('active-nav-group');

    });

  }

  function expandDrawSubContent() {
    // console.log('expand expandDrawSubContent');
    let subDrawExpander = $('.sidemenu-drawer .draw-nav ul ').find('.btn-expander');
    // console.log(subDrawExpander);

    subDrawExpander.each( (i, button) => {

      let $button = $(button);

      $button.on('click', () => {
        console.log($button);
        $button.parent('li').toggleClass('expanded');

      });
    });

  }

  function closeSideMenuDraw() {
    $('.close-draw').on( 'click', ()=> {
      if(sidemeneuExpanded) {
        sidemeneuExpanded = !sidemeneuExpanded;
        $( '.sidemenu-homepage .expanded-draw' ).removeClass( 'expanded-draw' );
        $draw.toggleClass('active');
      }
    });

    $( 'body' ).on( 'click', ( e ) => {
      console.log(e.target);

      let sidemenu = $('.sidemenu-homepage');
      // let  megamenu = $('.sidemenu-drawer');
      if (!sidemenu.is(e.target) // if the target of the click isn't the container...
      && sidemenu.has(e.target).length === 0) // ... nor a descendant of the container
        {
          sidemeneuExpanded = !sidemeneuExpanded;
          $( '.sidemenu-homepage .expanded-draw' ).removeClass( 'expanded-draw' );
          $draw.toggleClass('active');
        }

      // console.log( e.target.className, 'clicked' );
      // if ( e.target.className.includes( 'tray-open' )) {
      //   e.preventDefault();
      //   toggleTray();
      // }
      // if(sidemeneuExpanded) {
      //   console.log('sidemenu is expanded');
      //   // sidemeneuExpanded = !sidemeneuExpanded;
      //   // $( '.sidemenu-homepage .expanded-draw' ).removeClass( 'expanded-draw' );
      //   // $draw.toggleClass('active');
      // } else {
      //   console.log('draw not expanded');
      // }

    });

  }

  function sidemenuTray() {
    const menu = $('.sidemenu-homepage');
    // console.log(menu);

    //build tray nav content
    const trayNavItems = $( '.sidemenu-homepage > ul > li > ul' );

    const buttonExpander = $('.sidemenu-homepage > ul > li > .btn-expander');

    // console.log(trayNavItems);

    buttonExpander.each( expandTray );

    trayNavItems.each( buildTray );

    expandDrawSubContent();

    closeSideMenuDraw();

  }

  if ($('.sidemenu-homepage').length  ) {
    // console.log('sidemeny homepage init');

    // enquire.register( TABLET_AND_SMALLER, () => {
    //   console.log('tray is small size for mob');
    //   initSidemenuExpandability( sidemenu-homepage );
    // });

    enquire.register( DESKTOP_AND_LARGER, () => {
      // console.log('Tray is large size cool ');
      sidemenuTray();

    });

  }

}

<|endoftext|>


<commit_before>let Eris        = require('eris');
let reload      = require('require-reload')(require);
let http        = require('http');
let https       = require('https');
let fs          = require('fs');
let _config     = require('./config.json');
let express     = require('express');
let request     = require('request');

let _stickers;
let stickerServer;

try {
    _stickers = reload('./stickers.json');
} catch (e) {
    _stickers = {};
    let json = JSON.stringify(_stickers);
    fs.writeFile('stickers.json', json, 'utf8', function(){
        reloadStickers();
    });
}

let kuro = new Eris.CommandClient(_config.token, { userAccount: true }, {
    description: 'A nice selfbot built in eris',
    owner: _config.owner,
    prefix: '/',
    ignoreSelf: false,
    defaultHelpCommand: false,
    defaultCommandOptions: {
        requirements: {
            'userIDs': [_config.userID]
        }
    }
});

kuro.on('ready', () => {
    console.log('[Kuro]: Ready!');
});

/*
    Usage: /sticker add _name_ attachment|_url_
    Kuro will try to upload a new sticker to stickers.json. She will either try
    to parse the url from a given string and if there is none try to get the
    public link of an attached file.

    Usage: /sticker del _name_
    Kuro will try to delete a sticker by that name on stickers.json

    Usage: /sticker list
    Kuro will list all the stickers in stickers.json

    Usage: /sticker _name_
    Kuro will try to map _file_ to an existing image through stickers.json and
    then upload said image. After it's done, she will delete the message that
    triggered the command.
*/

kuro.registerCommand('sticker', (msg, args) => {

    if(args.length === 0)
        return;

    let command = args[0];
    if (command.toString().trim() === 'add'){

        // Treat this as the name of the new sticker. Return error if name wasnt provided
        if(args[1] === undefined){
            kuro.editMessage(msg.channel.id, msg.id, 'You forgot the sticker name, dumdum').then(() => delMessage(msg));
            return;
        }

        let name = args[1];

        // Is the name of the sticker already used?
        if(name in _stickers){
            kuro.editMessage(msg.channel.id, msg.id, 'You already used that name.').then(() => delMessage(msg));
            return;
        }

        // Prepare the destination container
        let dest = './stickers/' + name;
        let url = '';

        // Stupid discord renaming stuff, breaks everything
        let discordFilename = '';

        if(args[2] !== undefined)
            url = args[2];
        else
            if(msg.attachments.length > 0)
                if('proxy_url' in msg.attachments[0]){
                    url = msg.attachments[0].proxy_url;
                    discordFilename = msg.attachments[0].filename;
                }

        if(url === ''){
            // Welp, couldn't figure out a url
            kuro.editMessage(msg.channel.id, msg.id, 'You didnt supply either a url nor attachment, or there was an error with the attachment.').then(() => delMessage(msg));
            return;
        }

        // Try and gather the extension of the file
        let re = /(?:\.([^.]+))?$/;
        let ext;

        if(discordFilename !== '')
            ext = re.exec(discordFilename)[1];
        else
            ext = re.exec(url)[1];

        if(ext === undefined){
            kuro.editMessage(msg.channel.id, msg.id, "The file you are linking or trying to attach doesn't have an extension. Kuro needs that thingy").then(() => delMessage(msg));
            return;
        }

        dest = dest + '.' + ext;
        downloadImage(name, url, dest, ext, msg);

    }else if (command.toString().trim() === 'del'){
        if(args[1] !== undefined){
            delSticker(args[1], msg);
        }
    }else if (command.toString().trim() === 'list'){

        /*Depending on the configuration specified, we either return a list
        of all the stickers or launch a http server trying to grab the
        external ip of the computer the script is running on.*/

        if(_config.server.enabled === true)
            startServer(msg);
        else{
            let list = '';
            for(let sticker in _stickers)
                list = list + ' ' + sticker + '\n';

            kuro.editMessage(msg.channel.id, msg.id, '```' + list + '```').then(() => delMessage(msg, 5000));
        }

    }else if (command.toString().trim() === 'show'){
        // Soon

    }else{

        let name = command;

        if(_stickers[name] === undefined){
            kuro.editMessage(msg.channel.id, msg.id, 'That sticker doesnt exist. rip').then(() => delMessage(msg));
            return;
        }

        let img = fs.readFileSync('stickers/' + _stickers[name]);
        kuro.editMessage(msg.channel.id, msg.id, 'Loading...');
        kuro.createMessage(msg.channel.id, '', {file: img, name: _stickers[name]}).then(() => delMessage(msg, 0));

    }

});

/*
    Usage: /purge _number_
    Kuro will get the last _number_ messages from the channel where the command
    was triggered.
*/

kuro.registerCommand('purge', (msg, args) => {
    let msgCount = parseInt(args);
    kuro.getMessages(msg.channel.id, 100)
        .then((messages) => {
            let filtered = messages.filter(m => m.author.id === kuro.user.id);
            filtered.length = msgCount + 1;
            filtered.map((msg) => kuro.deleteMessage(msg.channel.id, msg.id));
        });
});

/*
    Usage: /status online|idle|dnd|offline
    Since this is a self bot, even if you close Discord you remain connected through
    Kuro. This command will enable you to set the status of your account whenever
    you're not on the app. So if you want to appear as 'Busy' whenever you're offline
    you can just /status dnd
*/

kuro.registerCommand('status', (msg, args) => {

    if(args.length === 0){
        kuro.editMessage(msg.channel.id, msg.id, 'Your offline status is: ' + msg.member.status).then(() => delMessage(msg));
        return;
    }

    switch(args[0]){
        case 'idle':
        case 'online':
        case 'dnd':
        case 'invisible':
            kuro.editStatus(args[0]);
            kuro.editMessage(msg.channel.id, msg.id, 'Next time you are offline your status will be set to: ' + args[0]).then(() => delMessage(msg));
            break;
        default:
            kuro.editMessage(msg.channel.id, msg.id, 'Wrong option. You need to specify away|busy|online|invisible').then(() => delMessage(msg));
            break;
    }

});

/*
    Usage: /playing string
    It will change the 'Playing' status below the users name to the string
    entered above.
*/

kuro.registerCommand('playing', (msg, args) => {
    if(args.length === 0)
        return;

    kuro.editStatus({name: args.join(' ')});
});

/* HELPER FUNCTIONS */
let startServer = function(msg){

    // Can we get an external IP?
    getExternalIP((err, body) => {
        if (!err) {

            // This is such a bad approach
            // DELET THIS
            fs.writeFileSync('./public/stickers.json', fs.readFileSync('./stickers.json'));

            if(stickerServer !== undefined){
                kuro.editMessage(msg.channel.id, msg.id, 'To view your sticker list go to http://' + body + ':' + _config.server.port + ' for the next ' + _config.server.duration + ' minutes.').then(() => delMessage(msg, 5000));
                delMessage(msg);
                return;
            }

            stickerServer = express();
            stickerServer.use(express.static('public'));
            stickerServer.use(express.static('stickers'));
            stickerServer.listen(_config.server.port);

            setTimeout( () => stickerServer.close(), (_config.server.duration * 60 * 1000));
            kuro.editMessage(msg.channel.id, msg.id, 'To view your sticker list go to http://' + body + ':' + _config.server.port + ' for the next ' + _config.server.duration + ' minutes.').then(() => delMessage(msg, 5000));
        } else {
            kuro.editMessage(msg.channel.id, msg.id, 'Unfortunately we couldnt get your external IP.').then(() => delMessage(msg));
        }
    });

};

let delMessage = function(msg, delay){
    if (typeof delay === 'undefined' || delay === null)
        delay = 3000;
    setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), delay);
};

let addNewSticker = function(name, ext, msg){

    _stickers[name] = name + '.' + ext;
    let json = JSON.stringify(_stickers);
    fs.writeFile('stickers.json', json, 'utf8', function(){
        reloadStickers();
        kuro.deleteMessage(msg.channel.id, msg.id);
        kuro.createMessage(msg.channel.id, 'Sticker added succesfully fam \o/').then(function(newmsg){
            setTimeout( () => kuro.deleteMessage(newmsg.channel.id, newmsg.id), 3000);
        });
    });

};

let delSticker = function(name, msg){

    if(name in _stickers){

        delete(_stickers[name]);
        let json = JSON.stringify(_stickers);
        fs.writeFile('stickers.json', json, 'utf8', function(){
            reloadStickers();
            kuro.editMessage(msg.channel.id, msg.id, 'The sticker was removed o7').then(() => setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), 3000));
        });

    }else{
        kuro.editMessage(msg.channel.id, msg.id, 'There is no sticker by that name, you wonderful person.').then(() => setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), 3000));
    }

};

let reloadStickers = function(){
    _stickers = reload('./stickers.json');
};

let downloadImage = function(name, url, dest, ext, msg) {
    let file = fs.createWriteStream(dest);

    let protocol = https;
    if (url.indexOf('http://') === 0)
        protocol = http;

    protocol.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(addNewSticker(name, ext, msg));  // close() is async, call cb after close completes.
        });
    }).on('error', function(err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        kuro.editMessage(msg.channel.id, msg.id, '***Error:*** ' + err.message);
    });
};

function getExternalIP (callback) {
    if(_config.server.islocal === false){
        request('http://wtfismyip.com/text', (err, res, body) => {
            body = body.toString().trim();
            if(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/.test(body))
                return callback(null, body);
            else{
                //console.log(body);
                return callback('error');
            }
        });
    }else{
        return callback(null, '127.0.0.1');
    }
}

kuro.connect();
<commit_msg>Last commit was a lie.<commit_after>let Eris        = require('eris');
let reload      = require('require-reload')(require);
let http        = require('http');
let https       = require('https');
let fs          = require('fs');
let _config     = require('./config.json');
let express     = require('express');
let request     = require('request');

let _stickers;
let stickerServer;

try {
    _stickers = reload('./stickers.json');
} catch (e) {
    _stickers = {};
    let json = JSON.stringify(_stickers);
    fs.writeFile('stickers.json', json, 'utf8', function(){
        reloadStickers();
    });
}

let kuro = new Eris.CommandClient(_config.token, { userAccount: true }, {
    description: 'A nice selfbot built in eris',
    owner: _config.owner,
    prefix: '/',
    ignoreSelf: false,
    defaultHelpCommand: false,
    defaultCommandOptions: {
        requirements: {
            'userIDs': [_config.userID]
        }
    }
});

kuro.on('ready', () => {
    console.log('[Kuro]: Ready!');
});

/*
    Usage: /sticker add _name_ attachment|_url_
    Kuro will try to upload a new sticker to stickers.json. She will either try
    to parse the url from a given string and if there is none try to get the
    public link of an attached file.

    Usage: /sticker del _name_
    Kuro will try to delete a sticker by that name on stickers.json

    Usage: /sticker list
    Kuro will list all the stickers in stickers.json

    Usage: /sticker _name_
    Kuro will try to map _file_ to an existing image through stickers.json and
    then upload said image. After it's done, she will delete the message that
    triggered the command.
*/

kuro.registerCommand('sticker', (msg, args) => {

    if(args.length === 0)
        return;

    let command = args[0];
    if (command.toString().trim() === 'add'){

        // Treat this as the name of the new sticker. Return error if name wasnt provided
        if(args[1] === undefined){
            kuro.editMessage(msg.channel.id, msg.id, 'You forgot the sticker name, dumdum').then(() => delMessage(msg));
            return;
        }

        let name = args[1];

        // Is the name of the sticker already used?
        if(name in _stickers){
            kuro.editMessage(msg.channel.id, msg.id, 'You already used that name.').then(() => delMessage(msg));
            return;
        }

        // Prepare the destination container
        let dest = './stickers/' + name;
        let url = '';

        // Stupid discord renaming stuff, breaks everything
        let discordFilename = '';

        if(args[2] !== undefined)
            url = args[2];
        else
            if(msg.attachments.length > 0)
                if('proxy_url' in msg.attachments[0]){
                    url = msg.attachments[0].proxy_url;
                    discordFilename = msg.attachments[0].filename;
                }

        if(url === ''){
            // Welp, couldn't figure out a url
            kuro.editMessage(msg.channel.id, msg.id, 'You didnt supply either a url nor attachment, or there was an error with the attachment.').then(() => delMessage(msg));
            return;
        }

        // Try and gather the extension of the file
        let re = /(?:\.([^.]+))?$/;
        let ext;

        if(discordFilename !== '')
            ext = re.exec(discordFilename)[1];
        else
            ext = re.exec(url)[1];

        if(ext === undefined){
            kuro.editMessage(msg.channel.id, msg.id, "The file you are linking or trying to attach doesn't have an extension. Kuro needs that thingy").then(() => delMessage(msg));
            return;
        }

        dest = dest + '.' + ext;
        downloadImage(name, url, dest, ext, msg);

    }else if (command.toString().trim() === 'del'){
        if(args[1] !== undefined){
            delSticker(args[1], msg);
        }
    }else if (command.toString().trim() === 'list'){

        /*Depending on the configuration specified, we either return a list
        of all the stickers or launch a http server trying to grab the
        external ip of the computer the script is running on.*/

        if(_config.server.enabled === true)
            startServer(msg);
        else{
            let list = '';
            for(let sticker in _stickers)
                list = list + ' ' + sticker + '\n';

            kuro.editMessage(msg.channel.id, msg.id, '```' + list + '```').then(() => delMessage(msg, 5000));
        }

    }else if (command.toString().trim() === 'show'){
        // Soon

    }else{

        let name = command;

        if(_stickers[name] === undefined){
            kuro.editMessage(msg.channel.id, msg.id, 'That sticker doesnt exist. rip').then(() => delMessage(msg));
            return;
        }

        let img = fs.readFileSync('stickers/' + _stickers[name]);
        kuro.editMessage(msg.channel.id, msg.id, 'Loading...');
        kuro.createMessage(msg.channel.id, '', {file: img, name: _stickers[name]}).then(() => delMessage(msg, 0));

    }

});

/*
    Usage: /purge _number_
    Kuro will get the last _number_ messages from the channel where the command
    was triggered.
*/

kuro.registerCommand('purge', (msg, args) => {
    let msgCount = parseInt(args);
    kuro.getMessages(msg.channel.id, 100)
        .then((messages) => {
            let filtered = messages.filter(m => m.author.id === kuro.user.id);
            filtered.length = msgCount + 1;
            filtered.map((msg) => kuro.deleteMessage(msg.channel.id, msg.id));
        });
});

/*
    Usage: /status online|idle|dnd|offline
    Since this is a self bot, even if you close Discord you remain connected through
    Kuro. This command will enable you to set the status of your account whenever
    you're not on the app. So if you want to appear as 'Busy' whenever you're offline
    you can just /status dnd
*/

kuro.registerCommand('status', (msg, args) => {

    if(args.length === 0){
        kuro.editMessage(msg.channel.id, msg.id, 'Your offline status is: ' + msg.member.status).then(() => delMessage(msg));
        return;
    }

    switch(args[0]){
        case 'idle':
        case 'online':
        case 'dnd':
        case 'invisible':
            kuro.editStatus(args[0]);
            kuro.editMessage(msg.channel.id, msg.id, 'Next time you are offline your status will be set to: ' + args[0]).then(() => delMessage(msg));
            break;
        default:
            kuro.editMessage(msg.channel.id, msg.id, 'Wrong option. You need to specify away|busy|online|invisible').then(() => delMessage(msg));
            break;
    }

});

/*
    Usage: /playing string
    It will change the 'Playing' status below the users name to the string
    entered above.
*/

/*
kuro.registerCommand('playing', (msg, args) => {
    if(args.length === 0){
        kuro.editStatus({});
        kuro.editMessage(msg.channel.id, msg.id, 'You succesfully removed your playing status').then(() => delMessage(msg));
        return;
    }

    let text = args.join(' ');
    console.log(text);
    kuro.editStatus({name: text});
    kuro.editMessage(msg.channel.id, msg.id, 'Succesfully changed your playing status o7').then(() => delMessage(msg));
});
*/

/* HELPER FUNCTIONS */
let startServer = function(msg){

    // Can we get an external IP?
    getExternalIP((err, body) => {
        if (!err) {

            // This is such a bad approach
            // DELET THIS
            fs.writeFileSync('./public/stickers.json', fs.readFileSync('./stickers.json'));

            if(stickerServer !== undefined){
                kuro.editMessage(msg.channel.id, msg.id, 'To view your sticker list go to http://' + body + ':' + _config.server.port + ' for the next ' + _config.server.duration + ' minutes.').then(() => delMessage(msg, 5000));
                delMessage(msg);
                return;
            }

            stickerServer = express();
            stickerServer.use(express.static('public'));
            stickerServer.use(express.static('stickers'));
            stickerServer.listen(_config.server.port);

            setTimeout( () => stickerServer.close(), (_config.server.duration * 60 * 1000));
            kuro.editMessage(msg.channel.id, msg.id, 'To view your sticker list go to http://' + body + ':' + _config.server.port + ' for the next ' + _config.server.duration + ' minutes.').then(() => delMessage(msg, 5000));
        } else {
            kuro.editMessage(msg.channel.id, msg.id, 'Unfortunately we couldnt get your external IP.').then(() => delMessage(msg));
        }
    });

};

let delMessage = function(msg, delay){
    if (typeof delay === 'undefined' || delay === null)
        delay = 3000;
    setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), delay);
};

let addNewSticker = function(name, ext, msg){

    _stickers[name] = name + '.' + ext;
    let json = JSON.stringify(_stickers);
    fs.writeFile('stickers.json', json, 'utf8', function(){
        reloadStickers();
        kuro.deleteMessage(msg.channel.id, msg.id);
        kuro.createMessage(msg.channel.id, 'Sticker added succesfully fam \o/').then(function(newmsg){
            setTimeout( () => kuro.deleteMessage(newmsg.channel.id, newmsg.id), 3000);
        });
    });

};

let delSticker = function(name, msg){

    if(name in _stickers){

        delete(_stickers[name]);
        let json = JSON.stringify(_stickers);
        fs.writeFile('stickers.json', json, 'utf8', function(){
            reloadStickers();
            kuro.editMessage(msg.channel.id, msg.id, 'The sticker was removed o7').then(() => setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), 3000));
        });

    }else{
        kuro.editMessage(msg.channel.id, msg.id, 'There is no sticker by that name, you wonderful person.').then(() => setTimeout( () => kuro.deleteMessage(msg.channel.id, msg.id), 3000));
    }

};

let reloadStickers = function(){
    _stickers = reload('./stickers.json');
};

let downloadImage = function(name, url, dest, ext, msg) {
    let file = fs.createWriteStream(dest);

    let protocol = https;
    if (url.indexOf('http://') === 0)
        protocol = http;

    protocol.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(addNewSticker(name, ext, msg));  // close() is async, call cb after close completes.
        });
    }).on('error', function(err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        kuro.editMessage(msg.channel.id, msg.id, '***Error:*** ' + err.message);
    });
};

function getExternalIP (callback) {
    if(_config.server.islocal === false){
        request('http://wtfismyip.com/text', (err, res, body) => {
            body = body.toString().trim();
            if(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/.test(body))
                return callback(null, body);
            else{
                //console.log(body);
                return callback('error');
            }
        });
    }else{
        return callback(null, '127.0.0.1');
    }
}

kuro.connect();
<|endoftext|>


<commit_before>'use strict';

var db                      = require('../../../db')
  , assign                  = require('es5-ext/object/assign')
  , getCostsPrintController = require('eregistrations/server/routes/business-process-costs-print');

module.exports = assign(require('eregistrations/server/routes/authenticated')(), {
	'costs-print': getCostsPrintController(db.BusinessProcessDemo)
});
<commit_msg>Update up to changes in eregistrations<commit_after>// Server-only GET router

'use strict';

var getRoutes = require('eregistrations/server/routes/business-process')
  , db        = require('../../../db');

module.exports = getRoutes(db.BusinessProcessDemo);
<|endoftext|>


<commit_before>/**
* oEmbed Plugin plugin
* Licensed under the MIT license
* jQuery Embed Plugin: http://code.google.com/p/jquery-oembed/ (MIT License)
* Plugin for: http://ckeditor.com/license (GPL/LGPL/MPL: http://ckeditor.com/license)
*/

(function () {
    CKEDITOR.plugins.add('oembed', {
        icons: 'oembed',
        hidpi: true,
        requires: 'widget,dialog',
        lang: 'de,en,fr,nl,pl,pt-br,ru,tr', // %REMOVE_LINE_CORE%
        version: 1.16,
        init: function (editor) {
            // Load jquery?
            loadjQueryLibaries();

            CKEDITOR.tools.extend(CKEDITOR.editor.prototype, {
                oEmbed: function (url, maxWidth, maxHeight, responsiveResize) {

                    if (url.length < 1 || url.indexOf('http') < 0) {
                        alert(editor.lang.oembed.invalidUrl);
                        return false;
                    }

                    function embed() {
                        if (maxWidth == null || maxWidth == 'undefined') {
                            maxWidth = null;
                        }

                        if (maxHeight == null || maxHeight == 'undefined') {
                            maxHeight = null;
                        }

                        if (responsiveResize == null || responsiveResize == 'undefined') {
                            responsiveResize = false;
                        }

                        embedCode(url, editor, false, maxWidth, maxHeight, responsiveResize);
                    }

                    if (typeof(jQuery.fn.oembed) === 'undefined') {
                        CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js'), function() {
                            embed();
                        });
                    } else {
                        embed();
                    }

                    return true;
                }
            });

            editor.widgets.add('oembed', {
                draggable: false,
                mask: true,
                dialog: 'oembed',
                allowedContent: {
                    div: {
                        styles: 'text-align,float',
                        attributes: '*',
                        classes: editor.config.oembed_WrapperClass != null ? editor.config.oembed_WrapperClass : "embeddedContent"
                    },
                    'div(embeddedContent) iframe': {
                        attributes: '*'
                    },
                    'div(embeddedContent) blockquote': {
                        attributes: '*'
                    },
                    'div(embeddedContent) script': {
                        attributes: '*'
                    }
                },
                template:
                    '
' +
                        '
',
                upcast: function (element) {
                    return element.name == 'div' && element.hasClass(editor.config.oembed_WrapperClass != null ? editor.config.oembed_WrapperClass : "embeddedContent");
                },
                init: function () {
                    var data = {
                        oembed: this.element.data('oembed') || '',
                        resizeType: this.element.data('resizeType') || 'noresize',
						maxWidth : this.element.data('maxWidth') || 560,
						maxHeight: this.element.data('maxHeight') || 315,
                        align: this.element.data('align') || 'none'
                        };

                    this.setData(data);

                    this.on('dialog', function (evt) {
                        evt.data.widget = this;
                    }, this);
                }
            });

            editor.ui.addButton('oembed', {
                label: editor.lang.oembed.button,
                command: 'oembed',
                toolbar: 'insert,10',
                icon: this.path + "icons/" + (CKEDITOR.env.hidpi ? "hidpi/" : "") + "oembed.png"
            });

            var resizeTypeChanged = function () {
                var dialog = this.getDialog(),
                    resizetype = this.getValue(),
                    maxSizeBox = dialog.getContentElement('general', 'maxSizeBox').getElement(),
                    sizeBox = dialog.getContentElement('general', 'sizeBox').getElement();

                if (resizetype == 'noresize') {
                    maxSizeBox.hide();

                    sizeBox.hide();
                } else if (resizetype == "custom") {
                    maxSizeBox.hide();

                    sizeBox.show();
                } else {
                    maxSizeBox.show();

                    sizeBox.hide();
                }

            };

            String.prototype.beginsWith = function(string) {
                return (this.indexOf(string) === 0);
            };

            function loadjQueryLibaries() {
                if (typeof(jQuery) === 'undefined') {
                    CKEDITOR.scriptLoader.load('//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function() {
                        jQuery.noConflict();
                        if (typeof(jQuery.fn.oembed) === 'undefined') {
                            CKEDITOR.scriptLoader.load(
                                CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js')
                            );
                        }
                    });

                } else if (typeof(jQuery.fn.oembed) === 'undefined') {
                    CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js'));
                }
            }

            function embedCode(url, instance, maxWidth, maxHeight, responsiveResize, resizeType, align, widget) {
                jQuery('body').oembed(url, {
                    onEmbed: function(e) {
                        var elementAdded = false;

						widget.element.data('resizeType', resizeType);
						if(resizeType == "responsive" || resizeType == "custom")
						{
							widget.element.data('maxWidth', maxWidth);
							widget.element.data('maxHeight', maxHeight);
						}

						widget.element.data('align', align);

                        // TODO handle align
						if (align == 'center') {
						    if (!widget.inline)
						        widget.element.setStyle('text-align', 'center');

						    widget.element.removeStyle('float');
						} else {
						    if (!widget.inline)
						        widget.element.removeStyle('text-align');

						    if (align == 'none')
						        widget.element.removeStyle('float');
						    else
						        widget.element.setStyle('float', align);
						}

						if (typeof e.code === 'string') {
                            if (widget.element.$.firstChild) {
                                widget.element.$.removeChild(widget.element.$.firstChild);
                            }

                            widget.element.appendHtml(e.code);
                            widget.element.data('oembed', url);

                            elementAdded = true;
                        } else if (typeof e.code[0].outerHTML === 'string') {

                            if (widget.element.$.firstChild) {
                               widget.element.$.removeChild(widget.element.$.firstChild);
                            }

                            widget.element.appendHtml(e.code[0].outerHTML);
                            widget.element.data('oembed', url);

                            elementAdded = true;
                        } else {
                            alert(editor.lang.oembed.noEmbedCode);
                        }
                    },
                    onError: function(externalUrl) {
                        if (externalUrl.indexOf("vimeo.com") > 0) {
                            alert(editor.lang.oembed.noVimeo);
                        } else {
                            alert(editor.lang.oembed.Error);
                        }

                    },
                    maxHeight: maxHeight,
                    maxWidth: maxWidth,
                    useResponsiveResize: responsiveResize,
                    embedMethod: 'editor'
                });
            }

            CKEDITOR.dialog.add('oembed', function(editor) {
                return {
                    title: editor.lang.oembed.title,
                    minWidth: CKEDITOR.env.ie && CKEDITOR.env.quirks ? 568 : 550,
                    minHeight: 155,
                    onShow: function() {
                        var data = {
                            oembed: this.widget.element.data('oembed') || '',
                            resizeType: this.widget.element.data('resizeType') || 'noresize',
                            maxWidth: this.widget.element.data('maxWidth'),
                            maxHeight: this.widget.element.data('maxHeight'),
                            align: this.widget.element.data('align') || 'none'
                        };

						this.widget.setData(data);

						this.getContentElement('general', 'resizeType').setValue(data.resizeType);

						this.getContentElement('general', 'align').setValue(data.align);

                        var resizetype = this.getContentElement('general', 'resizeType').getValue(),
                            maxSizeBox = this.getContentElement('general', 'maxSizeBox').getElement(),
                            sizeBox = this.getContentElement('general', 'sizeBox').getElement();

                        if (resizetype == 'noresize') {
                            maxSizeBox.hide();
                            sizeBox.hide();
                        } else if (resizetype == "custom") {
                            maxSizeBox.hide();

                            sizeBox.show();
                        } else {
                            maxSizeBox.show();

                            sizeBox.hide();
                        }
                    },

                    onOk: function() {
                    },
                    contents: [{
                        label: editor.lang.common.generalTab,
                        id: 'general',
                        elements: [{
                                type: 'html',
                                id: 'oembedHeader',
                                html: '
' + editor.lang.oembed.pasteUrl + '
'
                            }, {
                                type: 'text',
                                id: 'embedCode',
                                focus: function() {
                                    this.getElement().focus();
                                },
                                label: editor.lang.oembed.url,
                                title: editor.lang.oembed.pasteUrl,
                                setup: function(widget) {
                                    if (widget.data.oembed) {
                                       this.setValue(widget.data.oembed);
                                    }
                                },
                                commit: function(widget) {
                                    var dialog = CKEDITOR.dialog.getCurrent(),
                                        inputCode = dialog.getValueOf('general', 'embedCode').replace(/\s/g, ""),
                                        resizeType = dialog.getContentElement('general', 'resizeType').
                                            getValue(),
                                        align = dialog.getContentElement('general', 'align').
                                            getValue(),
                                        maxWidth = null,
                                        maxHeight = null,
                                        responsiveResize = false,
                                        editorInstance = dialog.getParentEditor();

                                    if (inputCode.length < 1 || inputCode.indexOf('http') < 0) {
                                        alert(editor.lang.oembed.invalidUrl);
                                        return false;
                                    }

                                    if (resizeType == "noresize") {
                                        responsiveResize = false;
                                        maxWidth = null;
                                        maxHeight = null;
                                    } else if (resizeType == "responsive") {
                                        maxWidth = dialog.getContentElement('general', 'maxWidth').
                                            getInputElement().
                                            getValue();
                                        maxHeight = dialog.getContentElement('general', 'maxHeight').
                                            getInputElement().
                                            getValue();

                                        responsiveResize = true;
                                    } else if (resizeType == "custom") {
                                        maxWidth = dialog.getContentElement('general', 'width').
                                            getInputElement().
                                            getValue();
                                        maxHeight = dialog.getContentElement('general', 'height').
                                            getInputElement().
                                            getValue();

                                        responsiveResize = false;
                                    }

                                    embedCode(inputCode, editorInstance, maxWidth, maxHeight, responsiveResize, resizeType, align, widget);

                                    widget.setData('oembed', inputCode);
                                    widget.setData('resizeType', resizeType);
                                    widget.setData('align', align);
                                    widget.setData('maxWidth', maxWidth);
                                    widget.setData('maxHeight', maxHeight);
                                }
                            }, {
                                type: 'hbox',
                                widths: ['50%', '50%'],
                                children: [{
                                        id: 'resizeType',
                                        type: 'select',
                                        label: editor.lang.oembed.resizeType,
                                        'default': 'noresize',
										setup: function(widget) {
											if (widget.data.resizeType) {
											   this.setValue(widget.data.resizeType);
											}
										},
                                        items: [
                                            [editor.lang.oembed.noresize, 'noresize'],
                                            [editor.lang.oembed.responsive, 'responsive'],
                                            [editor.lang.oembed.custom, 'custom']
                                        ],
                                        onChange: resizeTypeChanged
                                    }, {
                                        type: 'hbox',
                                        id: 'maxSizeBox',
                                        widths: ['120px', '120px'],
                                        style: 'float:left;position:absolute;left:58%;width:200px',
                                        children: [{
                                                type: 'text',
                                                width: '100px',
                                                id: 'maxWidth',
                                                'default': editor.config.oembed_maxWidth != null ? editor.config.oembed_maxWidth : '560',
                                                label: editor.lang.oembed.maxWidth,
                                                title: editor.lang.oembed.maxWidthTitle,
												setup: function(widget) {
													if (widget.data.maxWidth) {
														this.setValue(widget.data.maxWidth);
													}
												}
                                            }, {
                                                type: 'text',
                                                id: 'maxHeight',
                                                width: '120px',
                                                'default': editor.config.oembed_maxHeight != null ? editor.config.oembed_maxHeight : '315',
                                                label: editor.lang.oembed.maxHeight,
                                                title: editor.lang.oembed.maxHeightTitle,
												setup: function(widget) {
													if (widget.data.maxHeight) {
														this.setValue(widget.data.maxHeight);
													}
												}
                                            }]
                                    }, {
                                        type: 'hbox',
                                        id: 'sizeBox',
                                        widths: ['120px', '120px'],
                                        style: 'float:left;position:absolute;left:58%;width:200px',
                                        children: [{
                                                type: 'text',
                                                id: 'width',
                                                width: '100px',
                                                'default': editor.config.oembed_maxWidth != null ? editor.config.oembed_maxWidth : '560',
                                                label: editor.lang.oembed.width,
                                                title: editor.lang.oembed.widthTitle,
												setup: function(widget) {
													if (widget.data.maxWidth) {
													   this.setValue(widget.data.maxWidth);
													}
												}
                                            }, {
                                                type: 'text',
                                                id: 'height',
                                                width: '120px',
                                                'default': editor.config.oembed_maxHeight != null ? editor.config.oembed_maxHeight : '315',
                                                label: editor.lang.oembed.height,
                                                title: editor.lang.oembed.heightTitle,
												setup: function(widget) {
													if (widget.data.maxHeight) {
													   this.setValue(widget.data.maxHeight);
													}
												}
                                            }]
                                    }]
                            }, {
                                type: 'hbox',
                                id: 'alignment',
                                children: [
                                    {
                                        id: 'align',
                                        type: 'radio',
                                        items: [
                                            [editor.lang.oembed.none, 'none'],
                                            [editor.lang.common.alignLeft, 'left'],
                                            [editor.lang.common.alignCenter, 'center'],
                                            [editor.lang.common.alignRight, 'right']],
                                        label: editor.lang.common.align,
                                        setup: function( widget ) {
                                            this.setValue(widget.data.align);
                                        }
                                    }
                                ]
                            }]
                    }]
                };
            });
        }//
    });

}
)();
<commit_msg>Whitespace cleanup<commit_after>/**
* oEmbed Plugin plugin
* Licensed under the MIT license
* jQuery Embed Plugin: http://code.google.com/p/jquery-oembed/ (MIT License)
* Plugin for: http://ckeditor.com/license (GPL/LGPL/MPL: http://ckeditor.com/license)
*/

(function () {
    CKEDITOR.plugins.add('oembed', {
        icons: 'oembed',
        hidpi: true,
        requires: 'widget,dialog',
        lang: 'de,en,fr,nl,pl,pt-br,ru,tr', // %REMOVE_LINE_CORE%
        version: 1.16,
        init: function (editor) {
            // Load jquery?
            loadjQueryLibaries();

            CKEDITOR.tools.extend(CKEDITOR.editor.prototype, {
                oEmbed: function (url, maxWidth, maxHeight, responsiveResize) {

                    if (url.length < 1 || url.indexOf('http') < 0) {
                        alert(editor.lang.oembed.invalidUrl);
                        return false;
                    }

                    function embed() {
                        if (maxWidth == null || maxWidth == 'undefined') {
                            maxWidth = null;
                        }

                        if (maxHeight == null || maxHeight == 'undefined') {
                            maxHeight = null;
                        }

                        if (responsiveResize == null || responsiveResize == 'undefined') {
                            responsiveResize = false;
                        }

                        embedCode(url, editor, false, maxWidth, maxHeight, responsiveResize);
                    }

                    if (typeof(jQuery.fn.oembed) === 'undefined') {
                        CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js'), function() {
                            embed();
                        });
                    } else {
                        embed();
                    }

                    return true;
                }
            });

            editor.widgets.add('oembed', {
                draggable: false,
                mask: true,
                dialog: 'oembed',
                allowedContent: {
                    div: {
                        styles: 'text-align,float',
                        attributes: '*',
                        classes: editor.config.oembed_WrapperClass != null ? editor.config.oembed_WrapperClass : "embeddedContent"
                    },
                    'div(embeddedContent) iframe': {
                        attributes: '*'
                    },
                    'div(embeddedContent) blockquote': {
                        attributes: '*'
                    },
                    'div(embeddedContent) script': {
                        attributes: '*'
                    }
                },
                template:
                    '
' +
                        '
',
                upcast: function (element) {
                    return element.name == 'div' && element.hasClass(editor.config.oembed_WrapperClass != null ? editor.config.oembed_WrapperClass : "embeddedContent");
                },
                init: function () {
                    var data = {
                        oembed: this.element.data('oembed') || '',
                        resizeType: this.element.data('resizeType') || 'noresize',
                        maxWidth : this.element.data('maxWidth') || 560,
                        maxHeight: this.element.data('maxHeight') || 315,
                        align: this.element.data('align') || 'none'
                        };

                    this.setData(data);

                    this.on('dialog', function (evt) {
                        evt.data.widget = this;
                    }, this);
                }
            });

            editor.ui.addButton('oembed', {
                label: editor.lang.oembed.button,
                command: 'oembed',
                toolbar: 'insert,10',
                icon: this.path + "icons/" + (CKEDITOR.env.hidpi ? "hidpi/" : "") + "oembed.png"
            });

            var resizeTypeChanged = function () {
                var dialog = this.getDialog(),
                    resizetype = this.getValue(),
                    maxSizeBox = dialog.getContentElement('general', 'maxSizeBox').getElement(),
                    sizeBox = dialog.getContentElement('general', 'sizeBox').getElement();

                if (resizetype == 'noresize') {
                    maxSizeBox.hide();

                    sizeBox.hide();
                } else if (resizetype == "custom") {
                    maxSizeBox.hide();

                    sizeBox.show();
                } else {
                    maxSizeBox.show();

                    sizeBox.hide();
                }

            };

            String.prototype.beginsWith = function(string) {
                return (this.indexOf(string) === 0);
            };

            function loadjQueryLibaries() {
                if (typeof(jQuery) === 'undefined') {
                    CKEDITOR.scriptLoader.load('//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function() {
                        jQuery.noConflict();
                        if (typeof(jQuery.fn.oembed) === 'undefined') {
                            CKEDITOR.scriptLoader.load(
                                CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js')
                            );
                        }
                    });

                } else if (typeof(jQuery.fn.oembed) === 'undefined') {
                    CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('oembed') + 'libs/jquery.oembed.min.js'));
                }
            }

            function embedCode(url, instance, maxWidth, maxHeight, responsiveResize, resizeType, align, widget) {
                jQuery('body').oembed(url, {
                    onEmbed: function(e) {
                        var elementAdded = false;

                        widget.element.data('resizeType', resizeType);
                        if(resizeType == "responsive" || resizeType == "custom")
                        {
                            widget.element.data('maxWidth', maxWidth);
                            widget.element.data('maxHeight', maxHeight);
                        }

                        widget.element.data('align', align);

                        // TODO handle align
                        if (align == 'center') {
                            if (!widget.inline)
                                widget.element.setStyle('text-align', 'center');

                            widget.element.removeStyle('float');
                        } else {
                            if (!widget.inline)
                                widget.element.removeStyle('text-align');

                            if (align == 'none')
                                widget.element.removeStyle('float');
                            else
                                widget.element.setStyle('float', align);
                        }

                        if (typeof e.code === 'string') {
                            if (widget.element.$.firstChild) {
                                widget.element.$.removeChild(widget.element.$.firstChild);
                            }

                            widget.element.appendHtml(e.code);
                            widget.element.data('oembed', url);

                            elementAdded = true;
                        } else if (typeof e.code[0].outerHTML === 'string') {

                            if (widget.element.$.firstChild) {
                               widget.element.$.removeChild(widget.element.$.firstChild);
                            }

                            widget.element.appendHtml(e.code[0].outerHTML);
                            widget.element.data('oembed', url);

                            elementAdded = true;
                        } else {
                            alert(editor.lang.oembed.noEmbedCode);
                        }
                    },
                    onError: function(externalUrl) {
                        if (externalUrl.indexOf("vimeo.com") > 0) {
                            alert(editor.lang.oembed.noVimeo);
                        } else {
                            alert(editor.lang.oembed.Error);
                        }

                    },
                    maxHeight: maxHeight,
                    maxWidth: maxWidth,
                    useResponsiveResize: responsiveResize,
                    embedMethod: 'editor'
                });
            }

            CKEDITOR.dialog.add('oembed', function(editor) {
                return {
                    title: editor.lang.oembed.title,
                    minWidth: CKEDITOR.env.ie && CKEDITOR.env.quirks ? 568 : 550,
                    minHeight: 155,
                    onShow: function() {
                        var data = {
                            oembed: this.widget.element.data('oembed') || '',
                            resizeType: this.widget.element.data('resizeType') || 'noresize',
                            maxWidth: this.widget.element.data('maxWidth'),
                            maxHeight: this.widget.element.data('maxHeight'),
                            align: this.widget.element.data('align') || 'none'
                        };

                        this.widget.setData(data);

                        this.getContentElement('general', 'resizeType').setValue(data.resizeType);

                        this.getContentElement('general', 'align').setValue(data.align);

                        var resizetype = this.getContentElement('general', 'resizeType').getValue(),
                            maxSizeBox = this.getContentElement('general', 'maxSizeBox').getElement(),
                            sizeBox = this.getContentElement('general', 'sizeBox').getElement();

                        if (resizetype == 'noresize') {
                            maxSizeBox.hide();
                            sizeBox.hide();
                        } else if (resizetype == "custom") {
                            maxSizeBox.hide();

                            sizeBox.show();
                        } else {
                            maxSizeBox.show();

                            sizeBox.hide();
                        }
                    },

                    onOk: function() {
                    },
                    contents: [{
                        label: editor.lang.common.generalTab,
                        id: 'general',
                        elements: [{
                                type: 'html',
                                id: 'oembedHeader',
                                html: '
' + editor.lang.oembed.pasteUrl + '
'
                            }, {
                                type: 'text',
                                id: 'embedCode',
                                focus: function() {
                                    this.getElement().focus();
                                },
                                label: editor.lang.oembed.url,
                                title: editor.lang.oembed.pasteUrl,
                                setup: function(widget) {
                                    if (widget.data.oembed) {
                                       this.setValue(widget.data.oembed);
                                    }
                                },
                                commit: function(widget) {
                                    var dialog = CKEDITOR.dialog.getCurrent(),
                                        inputCode = dialog.getValueOf('general', 'embedCode').replace(/\s/g, ""),
                                        resizeType = dialog.getContentElement('general', 'resizeType').
                                            getValue(),
                                        align = dialog.getContentElement('general', 'align').
                                            getValue(),
                                        maxWidth = null,
                                        maxHeight = null,
                                        responsiveResize = false,
                                        editorInstance = dialog.getParentEditor();

                                    if (inputCode.length < 1 || inputCode.indexOf('http') < 0) {
                                        alert(editor.lang.oembed.invalidUrl);
                                        return false;
                                    }

                                    if (resizeType == "noresize") {
                                        responsiveResize = false;
                                        maxWidth = null;
                                        maxHeight = null;
                                    } else if (resizeType == "responsive") {
                                        maxWidth = dialog.getContentElement('general', 'maxWidth').
                                            getInputElement().
                                            getValue();
                                        maxHeight = dialog.getContentElement('general', 'maxHeight').
                                            getInputElement().
                                            getValue();

                                        responsiveResize = true;
                                    } else if (resizeType == "custom") {
                                        maxWidth = dialog.getContentElement('general', 'width').
                                            getInputElement().
                                            getValue();
                                        maxHeight = dialog.getContentElement('general', 'height').
                                            getInputElement().
                                            getValue();

                                        responsiveResize = false;
                                    }

                                    embedCode(inputCode, editorInstance, maxWidth, maxHeight, responsiveResize, resizeType, align, widget);

                                    widget.setData('oembed', inputCode);
                                    widget.setData('resizeType', resizeType);
                                    widget.setData('align', align);
                                    widget.setData('maxWidth', maxWidth);
                                    widget.setData('maxHeight', maxHeight);
                                }
                            }, {
                                type: 'hbox',
                                widths: ['50%', '50%'],
                                children: [{
                                        id: 'resizeType',
                                        type: 'select',
                                        label: editor.lang.oembed.resizeType,
                                        'default': 'noresize',
                                        setup: function(widget) {
                                            if (widget.data.resizeType) {
                                               this.setValue(widget.data.resizeType);
                                            }
                                        },
                                        items: [
                                            [editor.lang.oembed.noresize, 'noresize'],
                                            [editor.lang.oembed.responsive, 'responsive'],
                                            [editor.lang.oembed.custom, 'custom']
                                        ],
                                        onChange: resizeTypeChanged
                                    }, {
                                        type: 'hbox',
                                        id: 'maxSizeBox',
                                        widths: ['120px', '120px'],
                                        style: 'float:left;position:absolute;left:58%;width:200px',
                                        children: [{
                                                type: 'text',
                                                width: '100px',
                                                id: 'maxWidth',
                                                'default': editor.config.oembed_maxWidth != null ? editor.config.oembed_maxWidth : '560',
                                                label: editor.lang.oembed.maxWidth,
                                                title: editor.lang.oembed.maxWidthTitle,
                                                setup: function(widget) {
                                                    if (widget.data.maxWidth) {
                                                        this.setValue(widget.data.maxWidth);
                                                    }
                                                }
                                            }, {
                                                type: 'text',
                                                id: 'maxHeight',
                                                width: '120px',
                                                'default': editor.config.oembed_maxHeight != null ? editor.config.oembed_maxHeight : '315',
                                                label: editor.lang.oembed.maxHeight,
                                                title: editor.lang.oembed.maxHeightTitle,
                                                setup: function(widget) {
                                                    if (widget.data.maxHeight) {
                                                        this.setValue(widget.data.maxHeight);
                                                    }
                                                }
                                            }]
                                    }, {
                                        type: 'hbox',
                                        id: 'sizeBox',
                                        widths: ['120px', '120px'],
                                        style: 'float:left;position:absolute;left:58%;width:200px',
                                        children: [{
                                                type: 'text',
                                                id: 'width',
                                                width: '100px',
                                                'default': editor.config.oembed_maxWidth != null ? editor.config.oembed_maxWidth : '560',
                                                label: editor.lang.oembed.width,
                                                title: editor.lang.oembed.widthTitle,
                                                setup: function(widget) {
                                                    if (widget.data.maxWidth) {
                                                       this.setValue(widget.data.maxWidth);
                                                    }
                                                }
                                            }, {
                                                type: 'text',
                                                id: 'height',
                                                width: '120px',
                                                'default': editor.config.oembed_maxHeight != null ? editor.config.oembed_maxHeight : '315',
                                                label: editor.lang.oembed.height,
                                                title: editor.lang.oembed.heightTitle,
                                                setup: function(widget) {
                                                    if (widget.data.maxHeight) {
                                                       this.setValue(widget.data.maxHeight);
                                                    }
                                                }
                                            }]
                                    }]
                            }, {
                                type: 'hbox',
                                id: 'alignment',
                                children: [
                                    {
                                        id: 'align',
                                        type: 'radio',
                                        items: [
                                            [editor.lang.oembed.none, 'none'],
                                            [editor.lang.common.alignLeft, 'left'],
                                            [editor.lang.common.alignCenter, 'center'],
                                            [editor.lang.common.alignRight, 'right']],
                                        label: editor.lang.common.align,
                                        setup: function( widget ) {
                                            this.setValue(widget.data.align);
                                        }
                                    }
                                ]
                            }]
                    }]
                };
            });
        }//
    });

}
)();
<|endoftext|>