From dc238cf74a41d96340d9d807249bdeeb20a7959c Mon Sep 17 00:00:00 2001 From: artica Date: Wed, 30 Jan 2019 12:27:18 +0100 Subject: [PATCH] Changed the format of the .js and .html files Former-commit-id: 7a06315787b85355f4840cbfb0431d55dea4293d --- pandora_console/attachment/index.html | 2 +- pandora_console/attachment/mibs/index.html | 2 +- pandora_console/attachment/plugin/index.html | 2 +- pandora_console/composer.json | 22 +- .../realtime_graphs/realtime_graphs.js | 386 +- .../general/license/pandora_info_ast.html | 912 +- .../general/license/pandora_info_ca.html | 860 +- .../general/license/pandora_info_en.html | 701 +- .../general/license/pandora_info_es.html | 911 +- .../general/license/pandora_info_fr.html | 982 +- .../general/license/pandora_info_it.html | 505 +- .../general/license/pandora_info_ja.html | 815 +- .../general/license/pandora_info_pt_BR.html | 879 +- .../visual_console_builder.editor.js | 10820 +++++++++------- .../include/graphs/flot/pandora.flot.js | 5716 ++++---- pandora_console/include/graphs/pandora.d3.js | 4516 ++++--- pandora_console/include/javascript/clippy.js | 8 +- .../javascript/encode_decode_base64.js | 225 +- .../include/javascript/fixed-bottom-box.js | 673 +- .../functions_pandora_networkmap.js | 7471 ++++++----- .../include/javascript/openlayers.pandora.js | 1299 +- .../include/javascript/pandora.base64.js | 221 +- pandora_console/include/javascript/pandora.js | 2971 +++-- .../include/javascript/pandora_alerts.js | 80 +- .../include/javascript/pandora_events.js | 1165 +- .../include/javascript/pandora_modules.js | 1971 +-- .../javascript/pandora_snmp_browser.js | 645 +- .../javascript/pandora_visual_console.js | 307 +- .../include/javascript/tree/TreeController.js | 1670 +-- .../include/javascript/update_manager.js | 3689 +++--- pandora_console/include/javascript/webchat.js | 79 +- pandora_console/include/test.js | 23 +- pandora_console/include/web2image.js | 92 +- 33 files changed, 27562 insertions(+), 23058 deletions(-) diff --git a/pandora_console/attachment/index.html b/pandora_console/attachment/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/index.html +++ b/pandora_console/attachment/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/attachment/mibs/index.html b/pandora_console/attachment/mibs/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/mibs/index.html +++ b/pandora_console/attachment/mibs/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/attachment/plugin/index.html b/pandora_console/attachment/plugin/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/plugin/index.html +++ b/pandora_console/attachment/plugin/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/composer.json b/pandora_console/composer.json index 1138ecf522..acc6a3e352 100644 --- a/pandora_console/composer.json +++ b/pandora_console/composer.json @@ -1,14 +1,14 @@ { - "name": "Pandora FMS", - "description": "Pandora Flexible Monitoring System ", - "authors": [ - { - "name": "Artica", - "email": "info@artica.es" - } - ], - "require": { - "mpdf/mpdf": "^7.1", - "swiftmailer/swiftmailer": "^6.0" + "name": "Pandora FMS", + "description": "Pandora Flexible Monitoring System ", + "authors": [ + { + "name": "Artica", + "email": "info@artica.es" } + ], + "require": { + "mpdf/mpdf": "^7.1", + "swiftmailer/swiftmailer": "^6.0" + } } diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.js b/pandora_console/extensions/realtime_graphs/realtime_graphs.js index 924331cafe..7140d245d4 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.js +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.js @@ -1,210 +1,218 @@ -(function () { - var numberOfPoints = 100; - var refresh = parseInt($('#refresh').val()); - var incremental = $('#checkbox-incremental').is(':checked') || $('#hidden-incremental').val() == 1; - var lastIncVal = null; - var intervalRef = null; - var currentXHR = null; +(function() { + var numberOfPoints = 100; + var refresh = parseInt($("#refresh").val()); + var incremental = + $("#checkbox-incremental").is(":checked") || + $("#hidden-incremental").val() == 1; + var lastIncVal = null; + var intervalRef = null; + var currentXHR = null; - var plot; - var plotOptions = { - legend: { container: $("#chartLegend") }, - xaxis: { - tickFormatter: function (timestamp, axis) { - var date = new Date(timestamp * 1000); - - var server_timezone_offset = get_php_value('timezone_offset'); - var local_timezone_offset = date.getTimezoneOffset()*60*-1; - - if (server_timezone_offset != local_timezone_offset) { - // If timezone of server and client is different, adjust the time to the server - date = new Date((timestamp + (server_timezone_offset - local_timezone_offset)) * 1000); - } - - var hours = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()); - var minutes = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()); - var seconds = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()); - var formattedTime = hours + ':' + minutes + ':' + seconds; - return formattedTime; - } - }, - yaxis: { - tickFormatter: function (value, axis) { - return shortNumber(roundToTwo(value)) ; - } - }, - series: { - lines: { - lineWidth: 2, - fill: true - } - }, - colors: ['#6db431'] - }; + var plot; + var plotOptions = { + legend: { container: $("#chartLegend") }, + xaxis: { + tickFormatter: function(timestamp, axis) { + var date = new Date(timestamp * 1000); - function updatePlot (data) { - plot = $.plot($('.graph'), data, plotOptions); - } + var server_timezone_offset = get_php_value("timezone_offset"); + var local_timezone_offset = date.getTimezoneOffset() * 60 * -1; - function requestData () { - var rel_path = $("#hidden-rel_path").val(); + if (server_timezone_offset != local_timezone_offset) { + // If timezone of server and client is different, adjust the time to the server + date = new Date( + (timestamp + (server_timezone_offset - local_timezone_offset)) * + 1000 + ); + } - currentXHR = $.ajax({ - url: rel_path + "extensions/realtime_graphs/ajax.php", - type: "POST", - dataType: "json", - data: { - graph: $('#graph :selected').val(), - graph_title: $('#graph :selected').html(), - snmp_community: $('#text-snmp_community').val(), - snmp_oid: $('#text-snmp_oid').val(), - snmp_ver: $('#snmp_version :selected').val(), - snmp_address: $('#text-ip_target').val(), - refresh: refresh - }, - success: function (serie) { - var timestamp = serie.data[0][0]; - var data = plot.getData(); - - if (incremental) { - var currentVal = serie.data[0][1]; - // Try to avoid the first value, cause we need at least two values to get the increment - serie.data[0][1] = lastIncVal == null ? 0 : currentVal - lastIncVal; - // Incremental is always positive - if (serie.data[0][1] < 0) serie.data[0][1] = 0; - // Store the current value to use it into the next request - lastIncVal = currentVal; - } - - if (data.length === 0) { - for (i = 0; i < numberOfPoints; i++) { - var step = i * (refresh / 1000); - serie.data.unshift([timestamp - step, 0]); - } - - serie = [serie]; - updatePlot(serie); - return; - } + var hours = + date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = + date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = + date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + var formattedTime = hours + ":" + minutes + ":" + seconds; + return formattedTime; + } + }, + yaxis: { + tickFormatter: function(value, axis) { + return shortNumber(roundToTwo(value)); + } + }, + series: { + lines: { + lineWidth: 2, + fill: true + } + }, + colors: ["#6db431"] + }; - data[0].label = serie.label; - if (data[0].data.length >= numberOfPoints) { - data[0].data.shift(); - } - - data[0].data.push(serie.data[0]); - updatePlot(data); - } - }); - } - - function startDataPooling () { - intervalRef = window.setInterval(requestData, refresh); - } + function updatePlot(data) { + plot = $.plot($(".graph"), data, plotOptions); + } - function resetDataPooling () { - if (currentXHR !== null) currentXHR.abort(); - // Stop and start the interval - window.clearInterval(intervalRef); - startDataPooling(); - } + function requestData() { + var rel_path = $("#hidden-rel_path").val(); - function clearGraph () { - var data = plot.getData(); - if (data.length === 0) return; + currentXHR = $.ajax({ + url: rel_path + "extensions/realtime_graphs/ajax.php", + type: "POST", + dataType: "json", + data: { + graph: $("#graph :selected").val(), + graph_title: $("#graph :selected").html(), + snmp_community: $("#text-snmp_community").val(), + snmp_oid: $("#text-snmp_oid").val(), + snmp_ver: $("#snmp_version :selected").val(), + snmp_address: $("#text-ip_target").val(), + refresh: refresh + }, + success: function(serie) { + var timestamp = serie.data[0][0]; + var data = plot.getData(); - for (i = 0; i < data[0].data.length; i ++) { - data[0].data[i][1] = 0; - } - if (incremental) lastIncVal = null; - - updatePlot(data); + if (incremental) { + var currentVal = serie.data[0][1]; + // Try to avoid the first value, cause we need at least two values to get the increment + serie.data[0][1] = lastIncVal == null ? 0 : currentVal - lastIncVal; + // Incremental is always positive + if (serie.data[0][1] < 0) serie.data[0][1] = 0; + // Store the current value to use it into the next request + lastIncVal = currentVal; + } - resetDataPooling(); - } + if (data.length === 0) { + for (i = 0; i < numberOfPoints; i++) { + var step = i * (refresh / 1000); + serie.data.unshift([timestamp - step, 0]); + } - // Set the form OID to the value selected in the SNMP browser - function setOID () { - if ($('#snmp_browser_version').val() == '3') { - $('#text-snmp_oid').val($('#table1-0-1').text()); - } else { - $('#text-snmp_oid').val($('#snmp_selected_oid').text()); - } - - // Close the SNMP browser - $('.ui-dialog-titlebar-close').trigger('click'); - } + serie = [serie]; + updatePlot(serie); + return; + } - // Show the SNMP browser window - function snmpBrowserWindow () { - - // Keep elements in the form and the SNMP browser synced - $('#text-target_ip').val($('#text-ip_target').val()); - $('#text-community').val($('#text-snmp_community').val()); - $('#snmp_browser_version').val($('#snmp_version').val()); - $('#snmp3_browser_auth_user').val($('#snmp3_auth_user').val()); - $('#snmp3_browser_security_level').val($('#snmp3_security_level').val()); - $('#snmp3_browser_auth_method').val($('#snmp3_auth_method').val()); - $('#snmp3_browser_auth_pass').val($('#snmp3_auth_pass').val()); - $('#snmp3_browser_privacy_method').val($('#snmp3_privacy_method').val()); - $('#snmp3_browser_privacy_pass').val($('#snmp3_privacy_pass').val()); - - $("#snmp_browser_container").show().dialog ({ - title: '', - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: "black" - }, - width: 920, - height: 500 - }); - } + data[0].label = serie.label; + if (data[0].data.length >= numberOfPoints) { + data[0].data.shift(); + } - function shortNumber (number) { - if (Math.round(number) != number) return number; - number = Number.parseInt(number); - if (Number.isNaN(number)) return number; + data[0].data.push(serie.data[0]); + updatePlot(data); + } + }); + } - var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; - var pos = 0; + function startDataPooling() { + intervalRef = window.setInterval(requestData, refresh); + } - while (number >= 1000 || number <= -1000) { - pos++; - number = number / 1000; - } + function resetDataPooling() { + if (currentXHR !== null) currentXHR.abort(); + // Stop and start the interval + window.clearInterval(intervalRef); + startDataPooling(); + } - return number + " " + shorts[pos]; - } - function roundToTwo(num) { - return +(Math.round(num + "e+2") + "e-2"); - } + function clearGraph() { + var data = plot.getData(); + if (data.length === 0) return; - $('#graph').change(function() { - $('form#realgraph').submit(); - }); + for (i = 0; i < data[0].data.length; i++) { + data[0].data[i][1] = 0; + } + if (incremental) lastIncVal = null; - $('#refresh').change(function () { - refresh = parseInt($('#refresh').val()); - resetDataPooling(); - }); + updatePlot(data); - $('#checkbox-incremental').change(function() { - incremental = $('#checkbox-incremental').is(':checked'); - clearGraph(); - }); + resetDataPooling(); + } - updatePlot([]); - requestData(); - startDataPooling(); + // Set the form OID to the value selected in the SNMP browser + function setOID() { + if ($("#snmp_browser_version").val() == "3") { + $("#text-snmp_oid").val($("#table1-0-1").text()); + } else { + $("#text-snmp_oid").val($("#snmp_selected_oid").text()); + } - // Expose this functions - window.realtimeGraphs = { - clearGraph: clearGraph, - setOID: setOID, - snmpBrowserWindow: snmpBrowserWindow - } + // Close the SNMP browser + $(".ui-dialog-titlebar-close").trigger("click"); + } -})(); \ No newline at end of file + // Show the SNMP browser window + function snmpBrowserWindow() { + // Keep elements in the form and the SNMP browser synced + $("#text-target_ip").val($("#text-ip_target").val()); + $("#text-community").val($("#text-snmp_community").val()); + $("#snmp_browser_version").val($("#snmp_version").val()); + $("#snmp3_browser_auth_user").val($("#snmp3_auth_user").val()); + $("#snmp3_browser_security_level").val($("#snmp3_security_level").val()); + $("#snmp3_browser_auth_method").val($("#snmp3_auth_method").val()); + $("#snmp3_browser_auth_pass").val($("#snmp3_auth_pass").val()); + $("#snmp3_browser_privacy_method").val($("#snmp3_privacy_method").val()); + $("#snmp3_browser_privacy_pass").val($("#snmp3_privacy_pass").val()); + + $("#snmp_browser_container") + .show() + .dialog({ + title: "", + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 920, + height: 500 + }); + } + + function shortNumber(number) { + if (Math.round(number) != number) return number; + number = Number.parseInt(number); + if (Number.isNaN(number)) return number; + + var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; + var pos = 0; + + while (number >= 1000 || number <= -1000) { + pos++; + number = number / 1000; + } + + return number + " " + shorts[pos]; + } + function roundToTwo(num) { + return +(Math.round(num + "e+2") + "e-2"); + } + + $("#graph").change(function() { + $("form#realgraph").submit(); + }); + + $("#refresh").change(function() { + refresh = parseInt($("#refresh").val()); + resetDataPooling(); + }); + + $("#checkbox-incremental").change(function() { + incremental = $("#checkbox-incremental").is(":checked"); + clearGraph(); + }); + + updatePlot([]); + requestData(); + startDataPooling(); + + // Expose this functions + window.realtimeGraphs = { + clearGraph: clearGraph, + setOID: setOID, + snmpBrowserWindow: snmpBrowserWindow + }; +})(); diff --git a/pandora_console/general/license/pandora_info_ast.html b/pandora_console/general/license/pandora_info_ast.html index d7c82ff2da..98cd25040d 100644 --- a/pandora_console/general/license/pandora_info_ast.html +++ b/pandora_console/general/license/pandora_info_ast.html @@ -1,392 +1,542 @@ - - -Licencia Pública GNU - - - -

Licencia Pública GNU

-

Contenido

+ + + Licencia Pública GNU + + +

Licencia Pública GNU

+

Contenido

- -
-

Licencia Pública GNU

-

-Esta es la conocida GNU Public License (GPL), versión 2 (de junio -de 1.991), que cubre la mayor parte del software de la Free Software Foundation, -y muchos más programas.

+ +
+

Licencia Pública GNU

+

+ Esta es la conocida GNU Public License (GPL), versión 2 (de junio + de 1.991), que cubre la mayor parte del software de la Free Software + Foundation, y muchos más programas. +

-

Los autores de esta traducción son:

- +

Los autores de esta traducción son:

+ -
-
-NOTA IMPORTANTE: -

-Esta es una traducción no oficial al español de la GNU General Public -License. No ha sido publicada por la Free Software Foundation, y no -establece legalmente las condiciones de distribución para el software -que usa la GNU GPL. Estas condiciones se establecen solamente por -el texto original, en inglés, de la GNU GPL. Sin embargo, esperamos -que esta traducción ayude a los hispanohablantes a entender mejor la -GNU GPL. -

+

+
+ NOTA IMPORTANTE: +

+ Esta es una traducción no oficial al español de la GNU + General Public License. No ha sido publicada por la Free Software + Foundation, y no establece legalmente las condiciones de + distribución para el software que usa la GNU GPL. Estas + condiciones se establecen solamente por el texto original, en + inglés, de la GNU GPL. Sin embargo, esperamos que esta + traducción ayude a los hispanohablantes a entender mejor la GNU + GPL. +

+

IMPORTANT NOTICE:

+

+ This is an unofficial translation of the GNU General Public License into + Spanish. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, + we hope that this translation will help Spanish speakers understand the + GNU GPL better. +

+

+
+
-IMPORTANT NOTICE: -

-This is an unofficial translation of the GNU General Public License -into Spanish. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL--only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Spanish speakers understand the GNU GPL better. -

-


-
+

Copyright (C) 1989, 1991 Free Software Foundation, Inc.

+

675 Mass Ave, Cambridge, MA 02139, EEUU

+

+ Se permite la copia y distribución de copias literales de este + documento, pero no se permite su modificación. +

-

Copyright (C) 1989, 1991 Free Software Foundation, Inc. -

675 Mass Ave, Cambridge, MA 02139, EEUU -

Se permite la copia y distribución de copias literales de este -documento, pero no se permite su modificación. -

+

Preámbulo

+

+ Las licencias que cubren la mayor parte del software están + diseñadas para quitarle a usted la libertad de compartirlo y + modificarlo. Por el contrario, la Licencia Pública General de GNU + pretende garantizarle la libertad de compartir y modificar software libre, + para asegurar que el software es libre para todos sus usuarios. Esta + Licencia Pública General se aplica a la mayor parte del software + del la Free Software Foundation y a cualquier otro programa si sus autores + se comprometen a utilizarla. (Existe otro software de la Free Software + Foundation que está cubierto por la Licencia Pública General + de GNU para Bibliotecas). Si quiere, también puede aplicarla a sus + propios programas. +

+

+ Cuando hablamos de software libre, estamos refiriéndonos a + libertad, no a precio. Nuestras Licencias Públicas Generales + están diseñadas para asegurarnos de que tenga la libertad de + distribuir copias de software libre (y cobrar por ese servicio si quiere), + de que reciba el código fuente o que pueda conseguirlo si lo + quiere, de que pueda modificar el software o usar fragmentos de él + en nuevos programas libres, y de que sepa que puede hacer todas estas + cosas. +

+

+ Para proteger sus derechos necesitamos algunas restricciones que prohiban + a cualquiera negarle a usted estos derechos o pedirle que renuncie a + ellos. Estas restricciones se traducen en ciertas obligaciones que le + afectan si distribuye copias del software, o si lo modifica. +

+

+ Por ejemplo, si distribuye copias de uno de estos programas, sea + gratuitamente, o a cambio de una contraprestación, debe dar a los + receptores todos los derechos que tiene. Debe asegurarse de que ellos + también reciben, o pueden conseguir, el código fuente. Y + debe mostrarles estas condiciones de forma que conozcan sus derechos. +

+

Protegemos sus derechos con la combinación de dos medidas:

+
    +
  1. Ponemos el software bajo copyright y
  2. +
  3. + le ofrecemos esta licencia, que le da permiso legal para copiar, + distribuir y/o modificar el software. +
  4. +
+

+ También, para la protección de cada autor y la nuestra + propia, queremos asegurarnos de que todo el mundo comprende que no se + proporciona ninguna garantía para este software libre. Si el + software se modifica por cualquiera y éste a su vez lo distribuye, + queremos que sus receptores sepan que lo que tienen no es el original, de + forma que cualquier problema introducido por otros no afecte a la + reputación de los autores originales. +

+

+ Por último, cualquier programa libre está constantemente + amenazado por patentes sobre el software. Queremos evitar el peligro de + que los redistribuidores de un programa libre obtengan patentes por su + cuenta, convirtiendo de facto el programa en propietario. Para evitar + esto, hemos dejado claro que cualquier patente debe ser pedida para el uso + libre de cualquiera, o no ser pedida. +

+

+ Los términos exactos y las condiciones para la copia, + distribución y modificación se exponen a + continuación. +

+

+ Términos y condiciones para la copia, distribución y + modificación +

-

Preámbulo

-

-Las licencias que cubren la mayor parte del software están diseñadas -para quitarle a usted la libertad de compartirlo y modificarlo. Por el -contrario, la Licencia Pública General de GNU pretende garantizarle -la libertad de compartir y modificar software libre, para asegurar que -el software es libre para todos sus usuarios. Esta Licencia Pública -General se aplica a la mayor parte del software del la Free Software Foundation -y a cualquier otro programa si sus autores se comprometen a utilizarla. -(Existe otro software de la Free Software Foundation que está cubierto -por la Licencia Pública General de GNU para Bibliotecas). Si quiere, -también puede aplicarla a sus propios programas.

-

Cuando hablamos de software libre, estamos refiriéndonos a libertad, -no a precio. Nuestras Licencias Públicas Generales están -diseñadas para asegurarnos de que tenga la libertad de distribuir -copias de software libre (y cobrar por ese servicio si quiere), de que -reciba el código fuente o que pueda conseguirlo si lo quiere, de -que pueda modificar el software o usar fragmentos de él en nuevos -programas libres, y de que sepa que puede hacer todas estas cosas. -

Para proteger sus derechos necesitamos algunas restricciones que prohiban -a cualquiera negarle a usted estos derechos o pedirle que renuncie a ellos. -Estas restricciones se traducen en ciertas obligaciones que le afectan -si distribuye copias del software, o si lo modifica. -

Por ejemplo, si distribuye copias de uno de estos programas, sea gratuitamente, -o a cambio de una contraprestación, debe dar a los receptores todos -los derechos que tiene. Debe asegurarse de que ellos también reciben, -o pueden conseguir, el código fuente. Y debe mostrarles estas condiciones -de forma que conozcan sus derechos. -

Protegemos sus derechos con la combinación de dos medidas: -

    -
  1. Ponemos el software bajo copyright y -
  2. le ofrecemos esta licencia, que le da permiso legal para copiar, distribuir -y/o modificar el software.
-

-También, para la protección de cada autor y la nuestra propia, -queremos asegurarnos de que todo el mundo comprende que no se proporciona -ninguna garantía para este software libre. Si el software se modifica -por cualquiera y éste a su vez lo distribuye, queremos que sus receptores -sepan que lo que tienen no es el original, de forma que cualquier problema -introducido por otros no afecte a la reputación de los autores originales.

-

Por último, cualquier programa libre está constantemente -amenazado por patentes sobre el software. Queremos evitar el peligro de -que los redistribuidores de un programa libre obtengan patentes por su -cuenta, convirtiendo de facto el programa en propietario. Para evitar esto, -hemos dejado claro que cualquier patente debe ser pedida para el uso libre -de cualquiera, o no ser pedida. -

Los términos exactos y las condiciones para la copia, distribución -y modificación se exponen a continuación.

+
    +
  1. + Esta Licencia se aplica a cualquier programa u otro tipo de trabajo que + contenga una nota colocada por el tenedor del copyright diciendo que + puede ser distribuido bajo los términos de esta Licencia + Pública General. En adelante, «Programa» se + referirá a cualquier programa o trabajo que cumpla esa + condición y «trabajo basado en el Programa» se + referirá bien al Programa o a cualquier trabajo derivado de + él según la ley de copyright. Esto es, un trabajo que + contenga el programa o una proción de él, bien en forma + literal o con modificaciones y/o traducido en otro lenguaje. Por lo + tanto, la traducción está incluida sin limitaciones en el + término «modificación». Cada concesionario + (licenciatario) será denominado «usted». +

    + Cualquier otra actividad que no sea la copia, distribución o + modificación no está cubierta por esta Licencia, + está fuera de su ámbito. El acto de ejecutar el Programa + no está restringido, y los resultados del Programa están + cubiertos únicamente si sus contenidos constituyen un trabajo + basado en el Programa, independientemente de haberlo producido + mediante la ejecución del programa. El que esto se cumpla, + depende de lo que haga el programa. +

    +
  2. +
  3. + Usted puede copiar y distribuir copias literales del código + fuente del Programa, según lo has recibido, en cualquier medio, + supuesto que de forma adecuada y bien visible publique en cada copia un + anuncio de copyright adecuado y un repudio de garantía, mantenga + intactos todos los anuncios que se refieran a esta Licencia y a la + ausencia de garantía, y proporcione a cualquier otro receptor del + programa una copia de esta Licencia junto con el Programa. +

    + Puede cobrar un precio por el acto físico de transferir una + copia, y puede, según su libre albedrío, ofrecer + garantía a cambio de unos honorarios. +

    +
  4. +
  5. + Puede modificar su copia o copias del Programa o de cualquier + porción de él, formando de esta manera un trabajo basado + en el Programa, y copiar y distribuir esa modificación o trabajo + bajo los términos del apartado 1, antedicho, supuesto que + además cumpla las siguientes condiciones: +
      +
    1. + Debe hacer que los ficheros modificados lleven anuncios prominentes + indicando que los ha cambiado y la fecha de cualquier cambio. +
    2. +
    3. + Debe hacer que cualquier trabajo que distribuya o publique y que en + todo o en parte contenga o sea derivado del Programa o de cualquier + parte de él sea licenciada como un todo, sin carga alguna, a + todas las terceras partes y bajo los términos de esta + Licencia. +
    4. +
    5. + Si el programa modificado lee normalmente órdenes + interactivamente cuando es ejecutado, debe hacer que, cuando + comience su ejecución para ese uso interactivo de la forma + más habitual, muestre o escriba un mensaje que incluya un + anuncio de copyright y un anuncio de que no se ofrece ninguna + garantía (o por el contrario que sí se ofrece + garantía) y que los usuarios pueden redistribuir el programa + bajo estas condiciones, e indicando al usuario cómo ver una + copia de esta licencia. (Excepción: si el propio programa es + interactivo pero normalmente no muestra ese anuncio, no se requiere + que su trabajo basado en el Programa muestre ningún anuncio). +
    6. +
    + Estos requisitos se aplican al trabajo modificado como un todo. Si + partes identificables de ese trabajo no son derivadas del Programa, y + pueden, razonablemente, ser consideradas trabajos independientes y + separados por ellos mismos, entonces esta Licencia y sus términos + no se aplican a esas partes cuando sean distribuidas como trabajos + separados. Pero cuando distribuya esas mismas secciones como partes de + un todo que es un trabajo basado en el Programa, la distribución + del todo debe ser según los términos de esta licencia, + cuyos permisos para otros licenciatarios se extienden al todo completo, + y por lo tanto a todas y cada una de sus partes, con independencia de + quién la escribió. +

    + Por lo tanto, no es la intención de este apartado reclamar + derechos o desafiar sus derechos sobre trabajos escritos totalmente + por usted mismo. El intento es ejercer el derecho a controlar la + distribución de trabajos derivados o colectivos basados en el + Programa. +

    +

    + Además, el simple hecho de reunir un trabajo no basado en el + Programa con el Programa (o con un trabajo basado en el Programa) en + un volumen de almacenamiento o en un medio de distribución no + hace que dicho trabajo entre dentro del ámbito cubierto por + esta Licencia. +

    +
  6. +
  7. + Puede copiar y distribuir el Programa (o un trabajo basado en él, + según se especifica en el apartado 2, como código objeto o + en formato ejecutable según los términos de los apartados + 1 y 2, supuesto que además cumpla una de las siguientes + condiciones: +
      +
    1. + Acompañarlo con el código fuente completo + correspondiente, en formato electrónico, que debe ser + distribuido según se especifica en los apartados 1 y 2 de + esta Licencia en un medio habitualmente utilizado para el + intercambio de programas, o +
    2. +
    3. + Acompañarlo con una oferta por escrito, válida durante + al menos tres años, de proporcionar a cualquier tercera parte + una copia completa en formato electrónico del código + fuente correspondiente, a un coste no mayor que el de realizar + físicamente la distribución del fuente, que + será distribuido bajo las condiciones descritas en los + apartados 1 y 2 anteriores, en un medio habitualmente utilizado para + el intercambio de programas, o +
    4. +
    5. + Acompañarlo con la información que recibiste + ofreciendo distribuir el código fuente correspondiente. (Esta + opción se permite sólo para distribución no + comercial y sólo si usted recibió el programa como + código objeto o en formato ejecutable con tal oferta, de + acuerdo con el apartado b anterior). +
    6. +
    + Por código fuente de un trabajo se entiende la forma preferida + del trabajo cuando se le hacen modificaciones. Para un trabajo + ejecutable, se entiende por código fuente completo todo el + código fuente para todos los módulos que contiene, + más cualquier fichero asociado de definición de + interfaces, más los guiones utilizados para controlar la + compilación e instalación del ejecutable. Como + excepción especial el código fuente distribuido no + necesita incluir nada que sea distribuido normalmente (bien como fuente, + bien en forma binaria) con los componentes principales (compilador, + kernel y similares) del sistema operativo en el cual funciona el + ejecutable, a no ser que el propio componente acompañe al + ejecutable. +

    + Si la distribución del ejecutable o del código objeto se + hace mediante la oferta acceso para copiarlo de un cierto lugar, + entonces se considera la oferta de acceso para copiar el código + fuente del mismo lugar como distribución del código + fuente, incluso aunque terceras partes no estén forzadas a + copiar el fuente junto con el código objeto. +

    +
  8. +
  9. + No puede copiar, modificar, sublicenciar o distribuir el Programa + excepto como prevé expresamente esta Licencia. Cualquier intento + de copiar, modificar sublicenciar o distribuir el Programa de otra forma + es inválida, y hará que cesen automáticamente los + derechos que te proporciona esta Licencia. En cualquier caso, las partes + que hayan recibido copias o derechos de usted bajo esta Licencia no + cesarán en sus derechos mientras esas partes continúen + cumpliéndola. +
  10. +
  11. + No está obligado a aceptar esta licencia, ya que no la ha + firmado. Sin embargo, no hay hada más que le proporcione permiso + para modificar o distribuir el Programa o sus trabajos derivados. Estas + acciones están prohibidas por la ley si no acepta esta Licencia. + Por lo tanto, si modifica o distribuye el Programa (o cualquier trabajo + basado en el Programa), está indicando que acepta esta Licencia + para poder hacerlo, y todos sus términos y condiciones para + copiar, distribuir o modificar el Programa o trabajos basados en + él. +
  12. +
  13. + Cada vez que redistribuya el Programa (o cualquier trabajo basado en el + Programa), el receptor recibe automáticamente una licencia del + licenciatario original para copiar, distribuir o modificar el Programa, + de forma sujeta a estos términos y condiciones. No puede imponer + al receptor ninguna restricción más sobre el ejercicio de + los derechos aquí garantizados. No es usted responsable de hacer + cumplir esta licencia por terceras partes. +
  14. +
  15. + Si como consecuencia de una resolución judicial o de una + alegación de infracción de patente o por cualquier otra + razón (no limitada a asuntos relacionados con patentes) se le + imponen condiciones (ya sea por mandato judicial, por acuerdo o por + cualquier otra causa) que contradigan las condiciones de esta Licencia, + ello no le exime de cumplir las condiciones de esta Licencia. Si no + puede realizar distribuciones de forma que se satisfagan + simultáneamente sus obligaciones bajo esta licencia y cualquier + otra obligación pertinente entonces, como consecuencia, no puede + distribuir el Programa de ninguna forma. Por ejemplo, si una patente no + permite la redistribución libre de derechos de autor del Programa + por parte de todos aquellos que reciban copias directa o indirectamente + a través de usted, entonces la única forma en que + podría satisfacer tanto esa condición como esta Licencia + sería evitar completamente la distribución del Programa. +

    + Si cualquier porción de este apartado se considera + inválida o imposible de cumplir bajo cualquier circunstancia + particular ha de cumplirse el resto y la sección por entero ha + de cumplirse en cualquier otra circunstancia. +

    +

    + No es el propósito de este apartado inducirle a infringir + ninguna reivindicación de patente ni de ningún otro + derecho de propiedad o impugnar la validez de ninguna de dichas + reivindicaciones. Este apartado tiene el único propósito + de proteger la integridad del sistema de distribución de + software libre, que se realiza mediante prácticas de licencia + pública. Mucha gente ha hecho contribuciones generosas a la + gran variedad de software distribuido mediante ese sistema con la + confianza de que el sistema se aplicará consistentemente. + Será el autor/donante quien decida si quiere distribuir + software mediante cualquier otro sistema y una licencia no puede + imponer esa elección. +

    +

    + Este apartado pretende dejar completamente claro lo que se cree que es + una consecuencia del resto de esta Licencia. +

    +
  16. +
  17. + Si la distribución y/o uso de el Programa está restringida + en ciertos países, bien por patentes o por interfaces bajo + copyright, el tenedor del copyright que coloca este Programa bajo esta + Licencia puede añadir una limitación explícita de + distribución geográfica excluyendo esos países, de + forma que la distribución se permita sólo en o entre los + países no excluidos de esta manera. En ese caso, esta Licencia + incorporará la limitación como si estuviese escrita en el + cuerpo de esta Licencia. +
  18. +
  19. + La Free Software Foundation puede publicar versiones revisadas y/o + nuevas de la Licencia Pública General de tiempo en tiempo. Dichas + nuevas versiones serán similares en espíritu a la presente + versión, pero pueden ser diferentes en detalles para considerar + nuevos problemas o situaciones. +

    + Cada versión recibe un número de versión que la + distingue de otras. Si el Programa especifica un número de + versión de esta Licencia que se refiere a ella y a + «cualquier versión posterior», tienes la + opción de seguir los términos y condiciones, bien de esa + versión, bien de cualquier versión posterior publicada + por la Free Software Foundation. Si el Programa no especifica un + número de versión de esta Licencia, puedes escoger + cualquier versión publicada por la Free Software Foundation. +

    +
  20. +
  21. + Si quiere incorporar partes del Programa en otros programas libres cuyas + condiciones de distribución son diferentes, escribe al autor para + pedirle permiso. Si el software tiene copyright de la Free Software + Foundation, escribe a la Free Software Foundation: algunas veces hacemos + excepciones en estos casos. Nuestra decisión estará guiada + por el doble objetivo de de preservar la libertad de todos los derivados + de nuestro software libre y promover el que se comparta y reutilice el + software en general. +
  22. +
-

Términos y condiciones para la copia, -distribución y modificación

+

AUSENCIA DE GARANTÍA

-
    -
  1. Esta Licencia se aplica a cualquier programa u otro tipo -de trabajo que contenga una nota colocada por el tenedor del copyright -diciendo que puede ser distribuido bajo los términos de esta Licencia -Pública General. En adelante, «Programa» se referirá -a cualquier programa o trabajo que cumpla esa condición y «trabajo -basado en el Programa» se referirá bien al Programa o a cualquier -trabajo derivado de él según la ley de copyright. Esto es, -un trabajo que contenga el programa o una proción de él, -bien en forma literal o con modificaciones y/o traducido en otro lenguaje. -Por lo tanto, la traducción está incluida sin limitaciones -en el término «modificación». Cada concesionario -(licenciatario) será denominado «usted». -

    Cualquier otra actividad que no sea la copia, distribución o -modificación no está cubierta por esta Licencia, está -fuera de su ámbito. El acto de ejecutar el Programa no está -restringido, y los resultados del Programa están cubiertos únicamente -si sus contenidos constituyen un trabajo basado en el Programa, independientemente -de haberlo producido mediante la ejecución del programa. El que -esto se cumpla, depende de lo que haga el programa. -

  2. Usted puede copiar y distribuir copias literales del código fuente -del Programa, según lo has recibido, en cualquier medio, supuesto -que de forma adecuada y bien visible publique en cada copia un anuncio -de copyright adecuado y un repudio de garantía, mantenga intactos -todos los anuncios que se refieran a esta Licencia y a la ausencia de garantía, -y proporcione a cualquier otro receptor del programa una copia de esta -Licencia junto con el Programa. -

    Puede cobrar un precio por el acto físico de transferir una copia, -y puede, según su libre albedrío, ofrecer garantía -a cambio de unos honorarios. -

  3. Puede modificar su copia o copias del Programa o de cualquier porción -de él, formando de esta manera un trabajo basado en el Programa, -y copiar y distribuir esa modificación o trabajo bajo los términos -del apartado 1, antedicho, supuesto que además cumpla las siguientes -condiciones: -
    1. Debe hacer que los ficheros modificados lleven anuncios -prominentes indicando que los ha cambiado y la fecha de cualquier cambio. -
    2. Debe hacer que cualquier trabajo que distribuya o publique y que en -todo o en parte contenga o sea derivado del Programa o de cualquier parte -de él sea licenciada como un todo, sin carga alguna, a todas las -terceras partes y bajo los términos de esta Licencia. -
    3. Si el programa modificado lee normalmente órdenes interactivamente -cuando es ejecutado, debe hacer que, cuando comience su ejecución -para ese uso interactivo de la forma más habitual, muestre o escriba -un mensaje que incluya un anuncio de copyright y un anuncio de que no se -ofrece ninguna garantía (o por el contrario que sí se ofrece -garantía) y que los usuarios pueden redistribuir el programa bajo -estas condiciones, e indicando al usuario cómo ver una copia de -esta licencia. (Excepción: si el propio programa es interactivo -pero normalmente no muestra ese anuncio, no se requiere que su trabajo -basado en el Programa muestre ningún anuncio).
    -Estos requisitos se aplican al trabajo modificado como un todo. Si partes -identificables de ese trabajo no son derivadas del Programa, y pueden, -razonablemente, ser consideradas trabajos independientes y separados por -ellos mismos, entonces esta Licencia y sus términos no se aplican -a esas partes cuando sean distribuidas como trabajos separados. Pero cuando -distribuya esas mismas secciones como partes de un todo que es un trabajo -basado en el Programa, la distribución del todo debe ser según -los términos de esta licencia, cuyos permisos para otros licenciatarios -se extienden al todo completo, y por lo tanto a todas y cada una de sus -partes, con independencia de quién la escribió. -

    Por lo tanto, no es la intención de este apartado reclamar derechos -o desafiar sus derechos sobre trabajos escritos totalmente por usted mismo. -El intento es ejercer el derecho a controlar la distribución de -trabajos derivados o colectivos basados en el Programa. -

    Además, el simple hecho de reunir un trabajo no basado en el -Programa con el Programa (o con un trabajo basado en el Programa) en un -volumen de almacenamiento o en un medio de distribución no hace -que dicho trabajo entre dentro del ámbito cubierto por esta Licencia. -

  4. Puede copiar y distribuir el Programa (o un trabajo basado en él, -según se especifica en el apartado 2, como código objeto -o en formato ejecutable según los términos de los apartados -1 y 2, supuesto que además cumpla una de las siguientes condiciones: -
    1. Acompañarlo con el código fuente completo -correspondiente, en formato electrónico, que debe ser distribuido -según se especifica en los apartados 1 y 2 de esta Licencia en un -medio habitualmente utilizado para el intercambio de programas, o -
    2. Acompañarlo con una oferta por escrito, válida durante -al menos tres años, de proporcionar a cualquier tercera parte una -copia completa en formato electrónico del código fuente correspondiente, -a un coste no mayor que el de realizar físicamente la distribución -del fuente, que será distribuido bajo las condiciones descritas -en los apartados 1 y 2 anteriores, en un medio habitualmente utilizado -para el intercambio de programas, o -
    3. Acompañarlo con la información que recibiste ofreciendo -distribuir el código fuente correspondiente. (Esta opción -se permite sólo para distribución no comercial y sólo -si usted recibió el programa como código objeto o en formato -ejecutable con tal oferta, de acuerdo con el apartado b anterior).
    -Por código fuente de un trabajo se entiende la forma preferida del -trabajo cuando se le hacen modificaciones. Para un trabajo ejecutable, -se entiende por código fuente completo todo el código fuente -para todos los módulos que contiene, más cualquier fichero -asociado de definición de interfaces, más los guiones utilizados -para controlar la compilación e instalación del ejecutable. -Como excepción especial el código fuente distribuido no necesita -incluir nada que sea distribuido normalmente (bien como fuente, bien en -forma binaria) con los componentes principales (compilador, kernel y similares) -del sistema operativo en el cual funciona el ejecutable, a no ser que el -propio componente acompañe al ejecutable. -

    Si la distribución del ejecutable o del código objeto -se hace mediante la oferta acceso para copiarlo de un cierto lugar, entonces -se considera la oferta de acceso para copiar el código fuente del -mismo lugar como distribución del código fuente, incluso -aunque terceras partes no estén forzadas a copiar el fuente junto -con el código objeto. -

  5. No puede copiar, modificar, sublicenciar o distribuir el Programa excepto -como prevé expresamente esta Licencia. Cualquier intento de copiar, -modificar sublicenciar o distribuir el Programa de otra forma es inválida, -y hará que cesen automáticamente los derechos que te proporciona -esta Licencia. En cualquier caso, las partes que hayan recibido copias -o derechos de usted bajo esta Licencia no cesarán en sus derechos -mientras esas partes continúen cumpliéndola. -
  6. No está obligado a aceptar esta licencia, ya que no la ha firmado. -Sin embargo, no hay hada más que le proporcione permiso para modificar -o distribuir el Programa o sus trabajos derivados. Estas acciones están -prohibidas por la ley si no acepta esta Licencia. Por lo tanto, si modifica -o distribuye el Programa (o cualquier trabajo basado en el Programa), está -indicando que acepta esta Licencia para poder hacerlo, y todos sus términos -y condiciones para copiar, distribuir o modificar el Programa o trabajos -basados en él. -
  7. Cada vez que redistribuya el Programa (o cualquier trabajo basado en -el Programa), el receptor recibe automáticamente una licencia del -licenciatario original para copiar, distribuir o modificar el Programa, -de forma sujeta a estos términos y condiciones. No puede imponer -al receptor ninguna restricción más sobre el ejercicio de -los derechos aquí garantizados. No es usted responsable de hacer -cumplir esta licencia por terceras partes. -
  8. Si como consecuencia de una resolución judicial o de una alegación -de infracción de patente o por cualquier otra razón (no limitada -a asuntos relacionados con patentes) se le imponen condiciones (ya sea -por mandato judicial, por acuerdo o por cualquier otra causa) que contradigan -las condiciones de esta Licencia, ello no le exime de cumplir las condiciones -de esta Licencia. Si no puede realizar distribuciones de forma que se satisfagan -simultáneamente sus obligaciones bajo esta licencia y cualquier -otra obligación pertinente entonces, como consecuencia, no puede -distribuir el Programa de ninguna forma. Por ejemplo, si una patente no -permite la redistribución libre de derechos de autor del Programa -por parte de todos aquellos que reciban copias directa o indirectamente -a través de usted, entonces la única forma en que podría -satisfacer tanto esa condición como esta Licencia sería evitar -completamente la distribución del Programa. -

    Si cualquier porción de este apartado se considera inválida -o imposible de cumplir bajo cualquier circunstancia particular ha de cumplirse -el resto y la sección por entero ha de cumplirse en cualquier otra -circunstancia. -

    No es el propósito de este apartado inducirle a infringir ninguna -reivindicación de patente ni de ningún otro derecho de propiedad -o impugnar la validez de ninguna de dichas reivindicaciones. Este apartado -tiene el único propósito de proteger la integridad del sistema -de distribución de software libre, que se realiza mediante prácticas -de licencia pública. Mucha gente ha hecho contribuciones generosas -a la gran variedad de software distribuido mediante ese sistema con la -confianza de que el sistema se aplicará consistentemente. Será -el autor/donante quien decida si quiere distribuir software mediante cualquier -otro sistema y una licencia no puede imponer esa elección. -

    Este apartado pretende dejar completamente claro lo que se cree que -es una consecuencia del resto de esta Licencia. -

  9. Si la distribución y/o uso de el Programa está restringida -en ciertos países, bien por patentes o por interfaces bajo copyright, -el tenedor del copyright que coloca este Programa bajo esta Licencia puede -añadir una limitación explícita de distribución -geográfica excluyendo esos países, de forma que la distribución -se permita sólo en o entre los países no excluidos de esta -manera. En ese caso, esta Licencia incorporará la limitación -como si estuviese escrita en el cuerpo de esta Licencia. -
  10. La Free Software Foundation puede publicar versiones revisadas y/o nuevas -de la Licencia Pública General de tiempo en tiempo. Dichas nuevas -versiones serán similares en espíritu a la presente versión, -pero pueden ser diferentes en detalles para considerar nuevos problemas -o situaciones. -

    Cada versión recibe un número de versión que la -distingue de otras. Si el Programa especifica un número de versión -de esta Licencia que se refiere a ella y a «cualquier versión -posterior», tienes la opción de seguir los términos -y condiciones, bien de esa versión, bien de cualquier versión -posterior publicada por la Free Software Foundation. Si el Programa no -especifica un número de versión de esta Licencia, puedes -escoger cualquier versión publicada por la Free Software Foundation. -

  11. Si quiere incorporar partes del Programa en otros programas libres cuyas -condiciones de distribución son diferentes, escribe al autor para -pedirle permiso. Si el software tiene copyright de la Free Software Foundation, -escribe a la Free Software Foundation: algunas veces hacemos excepciones -en estos casos. Nuestra decisión estará guiada por el doble -objetivo de de preservar la libertad de todos los derivados de nuestro -software libre y promover el que se comparta y reutilice el software en -general.
+
    +
  1. + Como el programa se licencia libre de cargas, no se ofrece ninguna + garantía sobre el programa, en todas la extensión + permitida por la legislación aplicable. Excepto cuando se indique + de otra forma por escrito, los tenedores del copyright y/u otras partes + proporcionan el programa «tal cual», sin garantía de + ninguna clase, bien expresa o implícita, con inclusión, + pero sin limitación a las garantías mercantiles + implícitas o a la conveniencia para un propósito + particular. Cualquier riesgo referente a la calidad y prestaciones del + programa es asumido por usted. Si se probase que el Programa es + defectuoso, asume el coste de cualquier servicio, reparación o + corrección. +
  2. +
  3. + En ningún caso, salvo que lo requiera la legislación + aplicable o haya sido acordado por escrito, ningún tenedor del + copyright ni ninguna otra parte que modifique y/o redistribuya el + Programa según se permite en esta Licencia será + responsable ante usted por daños, incluyendo cualquier + daño general, especial, incidental o resultante producido por el + uso o la imposibilidad de uso del Programa (con inclusión, pero + sin limitación a la pérdida de datos o a la + generación incorrecta de datos o a pérdidas sufridas por + usted o por terceras partes o a un fallo del Programa al funcionar en + combinación con cualquier otro programa), incluso si dicho + tenedor u otra parte ha sido advertido de la posibilidad de dichos + daños. +
  4. +
-

AUSENCIA DE GARANTÍA

+

FIN DE TÉRMINOS Y CONDICIONES

-
    -
  1. Como el programa se licencia libre de cargas, -no se ofrece ninguna garantía sobre el programa, en todas la extensión -permitida por la legislación aplicable. Excepto cuando se indique -de otra forma por escrito, los tenedores del copyright y/u otras partes -proporcionan el programa «tal cual», sin garantía de -ninguna clase, bien expresa o implícita, con inclusión, pero -sin limitación a las garantías mercantiles implícitas -o a la conveniencia para un propósito particular. Cualquier riesgo -referente a la calidad y prestaciones del programa es asumido por usted. -Si se probase que el Programa es defectuoso, asume el coste de cualquier -servicio, reparación o corrección. -
  2. En ningún caso, salvo que lo requiera la legislación aplicable -o haya sido acordado por escrito, ningún tenedor del copyright ni -ninguna otra parte que modifique y/o redistribuya el Programa según -se permite en esta Licencia será responsable ante usted por daños, -incluyendo cualquier daño general, especial, incidental o resultante -producido por el uso o la imposibilidad de uso del Programa (con inclusión, -pero sin limitación a la pérdida de datos o a la generación -incorrecta de datos o a pérdidas sufridas por usted o por terceras -partes o a un fallo del Programa al funcionar en combinación con -cualquier otro programa), incluso si dicho tenedor u otra parte ha sido -advertido de la posibilidad de dichos daños.
- -

FIN DE TÉRMINOS Y CONDICIONES

- -

Apéndice: Cómo aplicar estos -términos a sus nuevos programas.

-

-Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso posible -para el público en general, la mejor forma de conseguirlo es convirtiéndolo -en software libre que cualquiera pueda redistribuir y cambiar bajo estos -términos.

-

Para hacerlo, añada los siguientes anuncios al programa. Lo más -seguro es añadirlos al principio de cada fichero fuente para transmitir -lo más efectivamente posible la ausencia de garantía. Además -cada fichero debería tener al menos la línea de «copyright» -y un indicador a dónde puede encontrarse el anuncio completo. -

<una línea para indicar el nombre -del programa y una rápida idea de qué hace.> -

Copyright (C) 19aa <nombre del autor> -

Este programa es software libre. Puede redistribuirlo y/o modificarlo -bajo los términos de la Licencia Pública General de GNU según -es publicada por la Free Software Foundation, bien de la versión -2 de dicha Licencia o bien (según su elección) de cualquier -versión posterior. -

Este programa se distribuye con la esperanza de que sea útil, -pero SIN NINGUNA GARANTÍA, incluso sin la garantía MERCANTIL -implícita o sin garantizar la CONVENIENCIA PARA UN PROPÓSITO -PARTICULAR. Véase la Licencia Pública General de GNU para -más detalles. -

Debería haber recibido una copia de la Licencia Pública -General junto con este programa. Si no ha sido así, escriba a la -Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU.

-

-Añada también información sobre cómo contactar -con usted mediante correo electrónico y postal.

-

Si el programa es interactivo, haga que muestre un pequeño anuncio -como el siguiente, cuando comienza a funcionar en modo interactivo: -

Gnomovision versión 69, Copyright -(C) 19aa nombre del autor -

Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para más -detalles escriba «show w».

-

-Los comandos hipotéticos «show w» y «show c» -deberían mostrar las partes adecuadas de la Licencia Pública -General. Por supuesto, los comandos que use pueden llamarse de cualquier -otra manera. Podrían incluso ser pulsaciones del ratón o -elementos de un menú (lo que sea apropiado para su programa).

-

También deberías conseguir que su empleador (si trabaja -como programador) o tu Universidad (si es el caso) firme un «renuncia -de copyright» para el programa, si es necesario. A continuación -se ofrece un ejemplo, altere los nombres según sea conveniente: -

-
-Yoyodyne, Inc. mediante este documento renuncia -a cualquier interés de derechos de copyright con respecto al programa -Gnomovision (que hace pasadas a compiladores) escrito por Pepe Programador. -

<firma de Pepito Grillo>, 20 de diciembre de 1996 -

Pepito Grillo, Presidente de Asuntillos Varios.

-
-

-Esta Licencia Pública General no permite que incluya sus programas -en programas propietarios. Si su programa es una biblioteca de subrutinas, -puede considerar más útil el permitir el enlazado de aplicaciones -propietarias con la biblioteca. Si este es el caso, use la Licencia Pública -General de GNU para Bibliotecas en lugar de esta Licencia.

- - \ No newline at end of file +

+ Apéndice: Cómo aplicar estos + términos a sus nuevos programas. +

+

+ Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso + posible para el público en general, la mejor forma de conseguirlo + es convirtiéndolo en software libre que cualquiera pueda + redistribuir y cambiar bajo estos términos. +

+

+ Para hacerlo, añada los siguientes anuncios al programa. Lo + más seguro es añadirlos al principio de cada fichero fuente + para transmitir lo más efectivamente posible la ausencia de + garantía. Además cada fichero debería tener al menos + la línea de «copyright» y un indicador a dónde + puede encontrarse el anuncio completo. +

+
+ <una línea para indicar el nombre del programa y una + rápida idea de qué hace.> +

Copyright (C) 19aa <nombre del autor>

+

+ Este programa es software libre. Puede redistribuirlo y/o modificarlo + bajo los términos de la Licencia Pública General de GNU + según es publicada por la Free Software Foundation, bien de la + versión 2 de dicha Licencia o bien (según su + elección) de cualquier versión posterior. +

+

+ Este programa se distribuye con la esperanza de que sea útil, + pero SIN NINGUNA GARANTÍA, incluso sin la garantía + MERCANTIL implícita o sin garantizar la CONVENIENCIA PARA UN + PROPÓSITO PARTICULAR. Véase la Licencia Pública + General de GNU para más detalles. +

+

+ Debería haber recibido una copia de la Licencia Pública + General junto con este programa. Si no ha sido así, escriba a la + Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, + EEUU. +

+
+

+ Añada también información sobre cómo contactar + con usted mediante correo electrónico y postal. +

+

+ Si el programa es interactivo, haga que muestre un pequeño anuncio + como el siguiente, cuando comienza a funcionar en modo interactivo: +

+
+ Gnomovision versión 69, Copyright (C) 19aa nombre del autor +

+ Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para + más detalles escriba «show w». +

+
+

+ Los comandos hipotéticos «show w» y «show + c» deberían mostrar las partes adecuadas de la Licencia + Pública General. Por supuesto, los comandos que use pueden llamarse + de cualquier otra manera. Podrían incluso ser pulsaciones del + ratón o elementos de un menú (lo que sea apropiado para su + programa). +

+

+ También deberías conseguir que su empleador (si trabaja como + programador) o tu Universidad (si es el caso) firme un «renuncia de + copyright» para el programa, si es necesario. A continuación + se ofrece un ejemplo, altere los nombres según sea conveniente: +

+
+ Yoyodyne, Inc. mediante este documento renuncia a cualquier interés + de derechos de copyright con respecto al programa Gnomovision (que hace + pasadas a compiladores) escrito por Pepe Programador. +

<firma de Pepito Grillo>, 20 de diciembre de 1996

+

Pepito Grillo, Presidente de Asuntillos Varios.

+
+

+ Esta Licencia Pública General no permite que incluya sus programas + en programas propietarios. Si su programa es una biblioteca de subrutinas, + puede considerar más útil el permitir el enlazado de + aplicaciones propietarias con la biblioteca. Si este es el caso, use la + Licencia Pública General de GNU para Bibliotecas en lugar de esta + Licencia. +

+ + diff --git a/pandora_console/general/license/pandora_info_ca.html b/pandora_console/general/license/pandora_info_ca.html index e2828b4237..09fbfe8411 100644 --- a/pandora_console/general/license/pandora_info_ca.html +++ b/pandora_console/general/license/pandora_info_ca.html @@ -1,348 +1,460 @@ - -Llicència Pública General de GNU - - + + Llicència Pública General de GNU + + +

Llicència Pública General de GNU

-

Llicència Pública General de GNU

+

Advertiment

+ This is an unofficial translation of the GNU General Public License into + Catalan. It was not published by the Free Software Foundation, and does not + legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help Catalan speakers understand the GNU GPL + better +

+ Ve't aquí una traducció no oficial al català de la + llicència pública general (GPL) de GNU. No ha estat + publicada per la Free Software Foundation (fundació per al + programari lliure), i no defineix legalment els termes de + distribució del programari que utilitza la GPL de GNU -- + només el text original en anglès ho fa. Tot i això, + esperem que aquesta traducció ajudi els catalanoparlants a entendre + millor la GPL de GNU. +

-

Advertiment

-This is an unofficial translation of the GNU General Public License into -Catalan. It was not published by the Free Software Foundation, and does -not legally state the distribution terms for software that uses the GNU -GPL--only the original English text of the GNU GPL does that. However, -we hope that this translation will help Catalan speakers understand the -GNU GPL better -

Ve't aquí una traducció no oficial al català de -la llicència pública general (GPL) de GNU. No ha estat publicada -per la Free Software Foundation (fundació per al programari lliure), -i no defineix legalment els termes de distribució del programari -que utilitza la GPL de GNU -- només el text original en anglès -ho fa. Tot i això, esperem que aquesta traducció ajudi els -catalanoparlants a entendre millor la GPL de GNU.

+

Índex

-

Índex

+

-

+

- + - - -
-

-LLICÈNCIA -PÚBLICA GENERAL DE GNU

-Versió 2, Juny de 1991 -
Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
+    
+

+ LLICÈNCIA PÚBLICA GENERAL DE GNU +

+ Versió 2, Juny de 1991 +
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
 
 Es permet que tothom faci còpies literals d'aquest document de
  llicència i les distribueixi, però no és permès modificar-lo.
-
+
-

Preàmbul

-Les llicències de la major part de programari estan pensades per -prendre-us la llibertat de compartir-lo i modificar-lo. Contràriament, -la Llicència pública general de GNU pretén garantir-vos -la llibertat de compartir i modificar el programari lliure -- assegurar-se -que el programari sigui lliure per a tots els seus usuaris i usuàries. -Aquesta Llicència pública general de GNU afecta la majoria -del programari de la Free Software Foundation (fundació pel programari -lliure) i a qualsevol altre programa els autors o autores del qual decideixin -usar-la (algun altre programari de la Free Software Foundation, en canvi, -està protegit per la Llicència pública general per -a biblioteques de GNU [NdeT: aquesta llicència, la LGPL, és -la que actualment la FSF anomena Llicència pública menys -general]). També podeu aplicar-la als vostres programes. -

Quan parlem de programari lliure (free software) ens referim a la llibertat, -no al preu [NdeT: en català no hi ha l'ambigüitat que hi ha -en anglès]. Les nostres llicències públiques generals -estan pensades per assegurar que tingueu la llibertat de distribuir còpies -del programari lliure (i cobrar per aquest servei si així ho voleu), -que rebeu el codi font o que el pugueu rebre si el voleu, que pugueu modificar -el programari o fer-ne servir parts en programes lliures nous; i que sapigueu

-que podeu fer aquestes coses. -

Per protegir els vostres drets, hem d'imposar restriccions que prohibeixin -a tothom denegar-vos aquests drets o demanar-vos que hi renuncieu. Aquestes -restriccions suposen algunes responsabilitats per a vós si distribuïu -còpies del programari o si el modifiqueu.

-

Per exemple, si distribuïu còpies d'un aquests programes, -tant si és de franc com per un preu, heu de donar als destinataris -els mateixos drets que teniu vós. Us heu d'assegurar que també -ells rebin o puguin obtenir el codi font. I els heu de fer saber aquests -termes per tal que coneguin els seus drets.

-

Protegim els vostres drets en dos passos: (1) Ens reservem el copyright -del programari, i (2) us oferim aquesta llicència que us dóna -permís legal per copiar, distribuir i/o modificar el programari.

-

A més a més, per protegir-nos i protegir l'autor o autora, -volem estar segurs que tothom entén que no hi ha cap garantia per -a aquest programari lliure. Si algú modifica el programari i el -passa, volem que els destinataris sàpiguen que el que tenen no és -l'original, per tal que qualsevol problema que haguessin pogut introduir -terceres persones no repercuteixi en la reputació de l'autor o autora -original.

-

Finalment, qualsevol programa lliure està constantment amenaçat -per les patents de programari. Volem evitar el perill de que els redistribuïdors -d'un programa lliure acabin obtenint llicències de patents, i de -resultes el programa esdevingui propietat exclusiva d'algú. Per -evitar-ho, he deixat clar que de qualsevol patent se n'han d'emetre llicències -per a tothom o no emetre'n cap.

-

Les condicions exactes per a la còpia, distribució i modificació -són les següents.

+

Preàmbul

+ Les llicències de la major part de programari estan pensades per + prendre-us la llibertat de compartir-lo i modificar-lo. + Contràriament, la Llicència pública general de GNU + pretén garantir-vos la llibertat de compartir i modificar el + programari lliure -- assegurar-se que el programari sigui lliure per a tots + els seus usuaris i usuàries. Aquesta Llicència pública + general de GNU afecta la majoria del programari de la Free Software + Foundation (fundació pel programari lliure) i a qualsevol altre + programa els autors o autores del qual decideixin usar-la (algun altre + programari de la Free Software Foundation, en canvi, està protegit + per la Llicència pública general per a biblioteques de GNU + [NdeT: aquesta llicència, la LGPL, és la que actualment la FSF + anomena Llicència pública menys general]). També podeu + aplicar-la als vostres programes. +

+ Quan parlem de programari lliure (free software) ens referim a la + llibertat, no al preu [NdeT: en català no hi ha l'ambigüitat + que hi ha en anglès]. Les nostres llicències + públiques generals estan pensades per assegurar que tingueu la + llibertat de distribuir còpies del programari lliure (i cobrar per + aquest servei si així ho voleu), que rebeu el codi font o que el + pugueu rebre si el voleu, que pugueu modificar el programari o fer-ne + servir parts en programes lliures nous; i que sapigueu +

+ que podeu fer aquestes coses. +

+ Per protegir els vostres drets, hem d'imposar restriccions que prohibeixin + a tothom denegar-vos aquests drets o demanar-vos que hi renuncieu. + Aquestes restriccions suposen algunes responsabilitats per a vós si + distribuïu còpies del programari o si el modifiqueu. +

+

+ Per exemple, si distribuïu còpies d'un aquests programes, tant + si és de franc com per un preu, heu de donar als destinataris els + mateixos drets que teniu vós. Us heu d'assegurar que també + ells rebin o puguin obtenir el codi font. I els heu de fer saber aquests + termes per tal que coneguin els seus drets. +

+

+ Protegim els vostres drets en dos passos: (1) Ens reservem el copyright + del programari, i (2) us oferim aquesta llicència que us + dóna permís legal per copiar, distribuir i/o modificar el + programari. +

+

+ A més a més, per protegir-nos i protegir l'autor o autora, + volem estar segurs que tothom entén que no hi ha cap garantia per a + aquest programari lliure. Si algú modifica el programari i el + passa, volem que els destinataris sàpiguen que el que tenen no + és l'original, per tal que qualsevol problema que haguessin pogut + introduir terceres persones no repercuteixi en la reputació de + l'autor o autora original. +

+

+ Finalment, qualsevol programa lliure està constantment + amenaçat per les patents de programari. Volem evitar el perill de + que els redistribuïdors d'un programa lliure acabin obtenint + llicències de patents, i de resultes el programa esdevingui + propietat exclusiva d'algú. Per evitar-ho, he deixat clar que de + qualsevol patent se n'han d'emetre llicències per a tothom o no + emetre'n cap. +

+

+ Les condicions exactes per a la còpia, distribució i + modificació són les següents. +

-

TERMES -I CONDICIONS PER A LA CÒPIA, DISTRIBUCIÓ I MODIFICACIÓ

+

+ TERMES I CONDICIONS PER A LA CÒPIA, DISTRIBUCIÓ I + MODIFICACIÓ +

-

-0. Aquesta llicència afecta a qualsevol programa o altra -obra que contingui un avís del posseïdor del copyright que -digui que es pot distribuir sota els termes d'aquesta llicència -pública general. D'ara endavant, el "programa" es refereix a aquest -programa o obra, i una "obra basada en el programa" voldrà dir el -programa o qualsevol obra derivada segons la llei de copyright: és -a dir una obra que contingui el programa o alguna part d'ell, ja sigui -literalment o amb modificacions o bé traduït a altres llengües. -(Per això mateix, les traduccions s'inclouen sense cap limitació -en el terme "modificació"). Ens referim a Cada beneficiari de la -llicència com a "vós".

-

Les activitats que no siguin còpia, distribució o modificació -no estan contemplades en aquesta llicència, queden fora del seu -àmbit. No es restringeix l'acte d'executar el programa, i la sortida -del programa queda contemplada només si el seu contingut constitueix -una obra basada en el programa (independentment de que s'hagi creat executant -el programa). Que aquest sigui el cas o no depèn de què faci -el programa.

-

1. Podeu copiar i distribuir còpies literals del codi -font del programa tal i com el rebeu, en qualsevol mitjà, sempre -i quan publiqueu en cada còpia, de manera adient i ben visible, -una nota de copyright i una renúncia de garantia; manteniu intactes -tots els avisos que fan referència a aquesta llicència i -a l'absència de garanties de cap mena; i lliureu a qualsevol altre -destinatari del programa una còpia d'aquesta llicència juntament -amb el programa.

-

Podeu cobrar un preu per l'acte físic de trametre una còpia -i podeu, si així ho voleu, oferir alguna garantia a canvi d'un preu.

-

2. Podeu modificar la còpia o còpies del programa -o qualsevol tros, tot fornint una obra basada en el programa, i podeu copiar -i distribuir aquestes modificacions o obres sota els termes de la Secció -1 anterior, sempre i quan també compliu les següents condicions:

- + El codi font per a una obra vol dir la forma preferida de l'obra per tal de + fer-hi modificacions. Per una obra executable, el codi font complet vol dir + tot el codi font per tots els mòduls que conté, més + tots els fitxers de definició d'interfícies associats si + s'escau, més els scripts que es facin servir per controlar la + compilació i la instal·lació de l'executable si + s'escau. Tanmateix, fent una excepció especial, el codi font que es + distribueixi no cal que inclogui res del que normalment es distribueixi (sia + en forma binària o de codi font) amb els components principals + (compilador, nucli o similars) del sistema operatiu en què s'executa + el programa, tret que el component en qüestió acompanyi + l'executable. +

+ Si la distribució de l'executable consisteix en donar accés + per copiar-lo d'un lloc determinat, aleshores serveix com a + distribució del codi font el fet de donar un accés + equivalent per copiar el codi font, encara que les terceres parts no + estiguin obligades a copiar el codi font en copiar el codi objecte. +

+

+ 4. No podeu copiar, modificar, reemetre llicències, o + distribuir el programa si no és de la forma expressa que atorga + aquesta Llicència. Qualsevol altre intent de copiar, modificar, + reemetre llicències, o distribuir el programa és + il·lícit i finalitzarà automàticament els + drets que hagueu obtingut d'aquesta llicència. Tanmateix, les parts + que hagin rebut de vós còpies o drets d'acord amb aquesta + llicència no veuran les seves llicències finalitzades mentre + segueixin observant-les estrictament. +

+

+ 5. No esteu obligat a acceptar aquesta llicència, donat que + no l'heu signada. Tanmateix, no hi ha cap altra opció que us doni + permís per modificar o distribuir el programa o les seves obres + derivades. Aquestes accions queden prohibides per la llei si no accepteu + aquesta llicència. Així doncs, en modificar o distribuir el + programa o les seves obres derivades, esteu indicant que accepteu aquesta + llicència per fer-ho, i tots els seus termes i condicions per + copiar, distribuir o modificar el programa o obres basades en ell. +

+

+ 6. Cada cop que distribuïu el programa (o qualsevol obra + basada en el programa), el destinatari rep automàticament, de qui + va emetre la llicència originàriament, una llicència + per copiar, distribuir o modificar el programa sotmesa a aquests termes i + condicions. No podeu imposar cap més restricció a l'exercici + dels drets que aquí es confereixen. No sou responsable de fer + complir aquesta llicència a terceres parts. +

+

+ 7. Si, a conseqüència d'una decisió judicial, + una demanda per infracció d'una patent o per qualsevol altra + raó (no exclusivament relacionada amb patents), se us imposen + condicions (tant si és per ordre judicial, acord, o el que sigui) + que contradiuen les condicions d'aquesta llicència, no quedeu + excusat de les condicions d'aquesta llicència. Si no us és + possible distribuir de manera que satisfeu alhora les obligacions que us + imposa aquesta llicència i qualsevol altra obligació + pertinent, aleshores resulta que no podeu distribuir el programa en + absolut. Per exemple, si una llicència de patent no permetés + redistribuir gratuïtament el programa a aquells que hagin rebut + còpies de vós directament o indirecta, aleshores la + única manera en què podríeu satisfer tant això + com aquesta llicència seria abstenir-vos completament de distribuir + el programa. +

+

+ Si qualsevol fragment d'aquesta secció quedés invalidat o no + es pogués fer complir en qualsevol circumstància particular, + la intenció és que s'apliqui el balanç de la + secció, i que s'apliqui la secció en la seva totalitat en + altres circumstàncies. +

+

+ El propòsit d'aquesta secció no és induir-vos a + infringir cap patent ni cap altre requeriment del dret a la propietat, o a + discutir-ne la validesa; l'únic propòsit d'aquesta + secció és protegir la integritat del sistema de + distribució de programari lliure, que s'implementa amb + pràctiques de llicència pública. Molta gent ha fet + generoses contribucions a l'ampli ventall de programari distribuït + per aquest sistema refiant-se de l'aplicació consistent del + sistema; li pertoca a l'autor, autora o donant decidir si vol distribuir + programari per algun altre sistema, i un beneficiari de la + llicència no pot imposar aquesta opció. +

+

+ Aquesta secció pretén deixar del tot clar el que es + considera una conseqüència de la resta de la llicència. +

+

+ 8. Si hi ha països que restringeixen la distribució o + l'ús del programari, ja sigui per patents o per interfícies + sota copyright, el posseïdor del copyright original que posi el + programa sota aquesta llicència pot afegir limitacions + geogràfiques explícites que excloguin aquests països, + de manera que la distribució només quedi permesa dintre dels + països no exclosos, o entre ells. En tal cas, aquesta + llicència incorpora la limitació com si estigués + escrita en el text de la llicència. +

+

+ 9. La Free Software Foundation (Fundació per al programari + lliure) pot publicar versions revisades o noves de la llicència + pública general de tant en tant. Aquestes versions noves seran + semblants en esperit a la versió present, però poden diferir + en detalls per tractar nous neguits o problemes. +

+

+ Cada versió rep un número de versió distintiu. Si el + programa especifica un número de versió d'aquesta + llicència que li és aplicable i "qualsevol versió + posterior", teniu l'opció de seguir els termes i condicions de la + versió especificada o de qualsevol versió publicada + posteriorment per la Free Software Foundation. Si el programa no + especifica un número de versió d'aquesta llicència, + podeu triar qualsevol versió que hagi publicat la Free Software + Foundation en qualsevol data. +

+

+ 10. Si voleu incorporar parts del programa en altres programes + lliures les condicions de distribució dels quals són + diferents, escriviu a l'autor per demanar-li permís. Per al + programari que està sota copyright de la Free Software Foundation, + escriviu a la Free Software Foundation; de vegades fem excepcions per + permetre-ho. Prendrem la nostra decisió guiats pels dos objectius + de mantenir la condició de lliure de tots els derivats del nostre + programari lliure i de promoure la compartició i la + reutilització del programari en general. +

+

ABSÈNCIA DE GARANTIES

+

+ 11. COM QUE LA LLICÈNCIA DEL PROGRAMA ÉS + GRATUÏTA, NO HI HA GARANTIA PER AL PROGRAMA, EN LA MESURA QUE HO + PERMETI LA LLEI APLICABLE. EXCEPTE EL QUE ALTRAMENT ES DIGUI PER ESCRIT, + ELS POSSEÏDORS DEL COPYRIGHT I/O ALTRES PARTS SUBMINISTREN EL + PROGRAMA "TAL QUAL" SENSE CAP MENA DE GARANTIA, NI EXPLÍCITA NI + IMPLÍCITA, INCLOSES, ENTRE ALTRES, LES GARANTIES IMPLÍCITES + DE COMERCIALITZABILITAT I APTITUD PER A PROPÒSITS DETERMINATS. TOT + EL RISC PEL QUE FA A LA QUALITAT I RENDIMENT DEL PROGRAMA ÉS + VOSTRE. EN CAS QUE EL PROGRAMA RESULTÉS DEFECTUÓS, + VÓS ASSUMIU TOT EL COST D'ASSISTÈNCIA, REPARACIÓ O + CORRECCIÓ. +

+

+ 12. EL POSSEÏDOR DEL COPYRIGHT, O QUALSEVOL ALTRA PART QUE + PUGUI MODIFICAR O REDISTRIBUIR EL PROGRAMA TAL I COM ES PERMET MÉS + AMUNT NO US HAURÀ DE RESPONDRE EN CAP CAS, TRET DEL QUE REQUEREIXI + LA LLEI APLICABLE O ELS ACORDS PER ESCRIT, PER PERJUDICIS, INCLOSOS ELS + INCIDENTALS, DERIVATS, ESPECIALS O GENERALS QUE ES DERIVIN DE L'ÚS + O DE LA IMPOSSIBILITAT D'ÚS DEL PROGRAMA (INCLOSES ENTRE D'ALTRES + LES PÈRDUES DE DADES, LES DADES QUE EL PROGRAMA HAGI MALMÈS, + LES PÈRDUES QUE US HAGI PROVOCAT A VÓS O A TERCERS O LA + IMPOSSIBILITAT DE QUE EL PROGRAMA FUNCIONI AMB QUALSEVOL ALTRE PROGRAMA), + FINS I TOT SI AQUEST POSSEÏDOR O ALTRA PART HA ESTAT ADVERTIDA DE LA + POSSIBILITAT D'AQUESTS PERJUDICIS. +

+

FINAL DELS TERMES I CONDICIONS

+ +

+ Com podeu aplicar aquests termes als vostres programes nous +

+ Si desenvolupeu un programa nou, i voleu que tingui l'ús més + gran possible per part del públic, la millor manera d'aconseguir-ho + és fer-lo programari lliure que tothom podrà redistribuir i + modificar d'acord amb aquests termes. +

+ Per fer-ho, afegiu els avisos següents al programa. El més + segur és posar-los al començament de cada fitxer font per + transmetre de la manera més efectiva l'exclusió de + garanties; i cada fitxer hauria de portar com a mínim la + línia de "copyright" i un apuntador que indiqui on es pot trobar la + nota sencera. +

+
Una línia amb el nom del programa i una idea de què fa.
 Copyright (C) any  nom de l'autor o autora
 
 Aquest programa és lliure; el podeu redistribuir i/o modificar
@@ -360,51 +472,67 @@ la Llicència general pública de GNU per a més detalls. 
 Hauríeu d'haver rebut una còpia de la llicència pública general 
 de GNU amb aquest programa; si no, escriviu a la Free Software 
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-Poseu-hi la informació que calgui per contactar amb vós per -correu electrònic i de paper. -

Si el programa és interactiu, feu-lo treure una breu nota com -aquesta quan arrenca en mode interactiu:

-
Gnomovisió versió 69, Copyright (C) any nom de l'autor o autora
+    Poseu-hi la informació que calgui per contactar amb vós per
+    correu electrònic i de paper.
+    

+ Si el programa és interactiu, feu-lo treure una breu nota com + aquesta quan arrenca en mode interactiu: +

+
Gnomovisió versió 69, Copyright (C) any nom de l'autor o autora
 El Gnomovisió va SENSE CAP MENA DE GARANTIA; premeu 'mostra g' per saber-ne 
 els detalls.  Això és programari lliure, i se us convida a redistribuir-lo
 d'acord amb certes condicions; piqueu 'mostra c' per saber-ne els detalls.
-

Les instruccions hipotètiques 'mostra g' i 'mostra -c' haurien de mostrar les parts escaients de la llicència pública -general. Naturalment, les instruccions poden tenir altres noms que no siguin -'mostra -g' i -'mostra c'; fins i tot podrien ser pics amb el ratolí -o opcions de menú, o el que li vagi bé al vostre programa. -

També hauríeu d'aconseguir que l'empresari per qui treballeu -(si treballeu de programador) o la vostra escola, si és el cas, -signin una "renúncia de copyright" pel programa, si s'escau. Aquí -teniu un exemple, canvieu-hi els noms:

-
Ioiodina, S.A. , per la present renuncia a tot interès 
+    

+ Les instruccions hipotètiques 'mostra g' i + 'mostra c' haurien de mostrar les parts escaients de la + llicència pública general. Naturalment, les instruccions poden + tenir altres noms que no siguin 'mostra g' i 'mostra c'; + fins i tot podrien ser pics amb el ratolí o opcions de menú, o + el que li vagi bé al vostre programa. +

+ També hauríeu d'aconseguir que l'empresari per qui treballeu + (si treballeu de programador) o la vostra escola, si és el cas, + signin una "renúncia de copyright" pel programa, si s'escau. + Aquí teniu un exemple, canvieu-hi els noms: +

+
Ioiodina, S.A. , per la present renuncia a tot interès 
 en el copyright del programa `Gnomovisió' (que fa l'aleta 
 als compiladors) escrit   pel Jordi Pica Codi
 
 signat per Mag Nat, 28 de desembre de 1989
 Mag Nat, Vici-President
-Aquesta Llicència pública general no us permet incorporar -el vostre programa en programes de propietat. Si el vostre programa és -una biblioteca de subrutines, potser trobeu més útil permetre -enllaçar (link) aplicacions de propietat amb la biblioteca. Si és -això el que voleu, feu servir la Llicència pública -general per a biblioteques de GNU per comptes d'aquesta llicència -[NdeT: la FSF ara li diu llicència pública menys general -per comptes de llicència pública general per a biblioteques].  -
Torna a la pàgina principal -de GNU. -

Per preguntes i aclariments de GNU i la FSF escriviu a: gnu@gnu.org. -Altres maneres de contactar -amb -la FSF:

-

Envieu comentaris sobre aquestes planes de web a webmasters@www.gnu.org, -Envieu altres preguntes a gnu@gnu.org.

-

La nota de Copyright és més amunt.

-
Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -MA 02111, USA -

Actualitzat:3 Jan 2000 rms

-
- - \ No newline at end of file + Aquesta Llicència pública general no us permet incorporar el + vostre programa en programes de propietat. Si el vostre programa és + una biblioteca de subrutines, potser trobeu més útil permetre + enllaçar (link) aplicacions de propietat amb la biblioteca. Si + és això el que voleu, feu servir la Llicència + pública general per a biblioteques de GNU per comptes d'aquesta + llicència [NdeT: la FSF ara li diu llicència pública + menys general per comptes de llicència pública general per a + biblioteques].  +
+ Torna a + la pàgina principal de GNU. +

+ Per preguntes i aclariments de GNU i la FSF escriviu a: + gnu@gnu.org. Altres + maneres de contactar amb la FSF: +

+

+ Envieu comentaris sobre aquestes planes de web a + webmasters@www.gnu.org, Envieu altres preguntes a + gnu@gnu.org. +

+

La nota de Copyright és més amunt.

+
Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, + MA 02111, USA +

Actualitzat:3 Jan 2000 rms

+
+ + diff --git a/pandora_console/general/license/pandora_info_en.html b/pandora_console/general/license/pandora_info_en.html index 8abb8c934c..d92b2df1b4 100644 --- a/pandora_console/general/license/pandora_info_en.html +++ b/pandora_console/general/license/pandora_info_en.html @@ -1,364 +1,353 @@ - - - GNU General Public License - - -

GNU General Public License

-

Table of Contents

- -
-

-

GNU GENERAL PUBLIC LICENSE

-

Version 2, June 1991

-
Copyright (C) 1989, 1991 Free Software Foundation, Inc. 
+
+  
+    GNU General Public License
+  
+  
+    

GNU General Public License

+

Table of Contents

+ + +
+

+

GNU GENERAL PUBLIC LICENSE

+

Version 2, June 1991

+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc. 
 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
 Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
+of this license document, but changing it is not allowed.
-

Preamble

+

Preamble

-

-The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. -

-

-When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. -

-

-To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. -

-

-For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. -

-

-We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. -

-

-Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. -

-

-Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. -

-

-The precise terms and conditions for copying, distribution and -modification follow. -

+

+ The licenses for most software are designed to take away your freedom to + share and change it. By contrast, the GNU General Public License is + intended to guarantee your freedom to share and change free software--to + make sure the software is free for all its users. This General Public + License applies to most of the Free Software Foundation's software and to + any other program whose authors commit to using it. (Some other Free + Software Foundation software is covered by the GNU Library General Public + License instead.) You can apply it to your programs, too. +

+

+ When we speak of free software, we are referring to freedom, not price. + Our General Public Licenses are designed to make sure that you have the + freedom to distribute copies of free software (and charge for this service + if you wish), that you receive source code or can get it if you want it, + that you can change the software or use pieces of it in new free programs; + and that you know you can do these things. +

+

+ To protect your rights, we need to make restrictions that forbid anyone to + deny you these rights or to ask you to surrender the rights. These + restrictions translate to certain responsibilities for you if you + distribute copies of the software, or if you modify it. +

+

+ For example, if you distribute copies of such a program, whether gratis or + for a fee, you must give the recipients all the rights that you have. You + must make sure that they, too, receive or can get the source code. And you + must show them these terms so they know their rights. +

+

+ We protect your rights with two steps: (1) copyright the software, and (2) + offer you this license which gives you legal permission to copy, + distribute and/or modify the software. +

+

+ Also, for each author's protection and ours, we want to make certain that + everyone understands that there is no warranty for this free software. If + the software is modified by someone else and passed on, we want its + recipients to know that what they have is not the original, so that any + problems introduced by others will not reflect on the original authors' + reputations. +

+

+ Finally, any free program is threatened constantly by software patents. We + wish to avoid the danger that redistributors of a free program will + individually obtain patent licenses, in effect making the program + proprietary. To prevent this, we have made it clear that any patent must + be licensed for everyone's free use or not licensed at all. +

+

+ The precise terms and conditions for copying, distribution and + modification follow. +

-

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

+

+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +

-

-0. -This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". -

-

-Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. -

-

-1. -You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. -

-

-You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. -

-

-2. - You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: -

-

+

+ 0. This License applies to any program or other work + which contains a notice placed by the copyright holder saying it may be + distributed under the terms of this General Public License. The "Program", + below, refers to any such program or work, and a "work based on the + Program" means either the Program or any derivative work under copyright + law: that is to say, a work containing the Program or a portion of it, + either verbatim or with modifications and/or translated into another + language. (Hereinafter, translation is included without limitation in the + term "modification".) Each licensee is addressed as "you". +

+

+ Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of running + the Program is not restricted, and the output from the Program is covered + only if its contents constitute a work based on the Program (independent + of having been made by running the Program). Whether that is true depends + on what the Program does. +

+

+ 1. You may copy and distribute verbatim copies of the + Program's source code as you receive it, in any medium, provided that you + conspicuously and appropriately publish on each copy an appropriate + copyright notice and disclaimer of warranty; keep intact all the notices + that refer to this License and to the absence of any warranty; and give + any other recipients of the Program a copy of this License along with the + Program. +

+

+ You may charge a fee for the physical act of transferring a copy, and you + may at your option offer warranty protection in exchange for a fee. +

+

+ 2. You may modify your copy or copies of the Program or + any portion of it, thus forming a work based on the Program, and copy and + distribute such modifications or work under the terms of Section 1 above, + provided that you also meet all of these conditions: +

+

-
-
-a) - You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. -
-
-
-
-b) - You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. -
-
-
-
-c) - If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) -
-
-

-These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. -

-

-Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. -

-

In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. -

-

3. - You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: -

-
-
-a) - Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, -
-
-b) - Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, -
-
-
-
-c) - Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) -
-
-

-The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. -

-

-If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. -

-

-4. -You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. -

-

-5. -You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. -

-

-6. -Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. -

-

-7. -If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. -

-

-If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. -

-

-It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. -

-

-This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. -

-

-8. - If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. -

-

-9. - The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. -

-

-Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. -

-

-10. -If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. -

-

-NO WARRANTY -

-

-11. -BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. -

-

-12. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. -

-

-

END OF TERMS AND CONDITIONS

- \ No newline at end of file +
+
+ a) You must cause the modified files to carry prominent + notices stating that you changed the files and the date of any change. +
+
+
+
+ b) You must cause any work that you distribute or + publish, that in whole or in part contains or is derived from the + Program or any part thereof, to be licensed as a whole at no charge to + all third parties under the terms of this License. +
+
+
+
+ c) If the modified program normally reads commands + interactively when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a notice that + there is no warranty (or else, saying that you provide a warranty) and + that users may redistribute the program under these conditions, and + telling the user how to view a copy of this License. (Exception: if the + Program itself is interactive but does not normally print such an + announcement, your work based on the Program is not required to print an + announcement.) +
+
+

+ These requirements apply to the modified work as a whole. If identifiable + sections of that work are not derived from the Program, and can be + reasonably considered independent and separate works in themselves, then + this License, and its terms, do not apply to those sections when you + distribute them as separate works. But when you distribute the same + sections as part of a whole which is a work based on the Program, the + distribution of the whole must be on the terms of this License, whose + permissions for other licensees extend to the entire whole, and thus to + each and every part regardless of who wrote it. +

+

+ Thus, it is not the intent of this section to claim rights or contest your + rights to work written entirely by you; rather, the intent is to exercise + the right to control the distribution of derivative or collective works + based on the Program. +

+

+ In addition, mere aggregation of another work not based on the Program + with the Program (or with a work based on the Program) on a volume of a + storage or distribution medium does not bring the other work under the + scope of this License. +

+

+ 3. You may copy and distribute the Program (or a work + based on it, under Section 2) in object code or executable form under the + terms of Sections 1 and 2 above provided that you also do one of the + following: +

+
+
+ a) Accompany it with the complete corresponding + machine-readable source code, which must be distributed under the terms + of Sections 1 and 2 above on a medium customarily used for software + interchange; or, +
+
+ b) Accompany it with a written offer, valid for at + least three years, to give any third party, for a charge no more than + your cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, +
+
+
+
+ c) Accompany it with the information you received as to + the offer to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you received the + program in object code or executable form with such an offer, in accord + with Subsection b above.) +
+
+

+ The source code for a work means the preferred form of the work for making + modifications to it. For an executable work, complete source code means + all the source code for all modules it contains, plus any associated + interface definition files, plus the scripts used to control compilation + and installation of the executable. However, as a special exception, the + source code distributed need not include anything that is normally + distributed (in either source or binary form) with the major components + (compiler, kernel, and so on) of the operating system on which the + executable runs, unless that component itself accompanies the executable. +

+

+ If distribution of executable or object code is made by offering access to + copy from a designated place, then offering equivalent access to copy the + source code from the same place counts as distribution of the source code, + even though third parties are not compelled to copy the source along with + the object code. +

+

+ 4. You may not copy, modify, sublicense, or distribute + the Program except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense or distribute the Program is void, + and will automatically terminate your rights under this License. However, + parties who have received copies, or rights, from you under this License + will not have their licenses terminated so long as such parties remain in + full compliance. +

+

+ 5. You are not required to accept this License, since you + have not signed it. However, nothing else grants you permission to modify + or distribute the Program or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Program (or any work based on the Program), + you indicate your acceptance of this License to do so, and all its terms + and conditions for copying, distributing or modifying the Program or works + based on it. +

+

+ 6. Each time you redistribute the Program (or any work + based on the Program), the recipient automatically receives a license from + the original licensor to copy, distribute or modify the Program subject to + these terms and conditions. You may not impose any further restrictions on + the recipients' exercise of the rights granted herein. You are not + responsible for enforcing compliance by third parties to this License. +

+

+ 7. If, as a consequence of a court judgment or allegation + of patent infringement or for any other reason (not limited to patent + issues), conditions are imposed on you (whether by court order, agreement + or otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot distribute + so as to satisfy simultaneously your obligations under this License and + any other pertinent obligations, then as a consequence you may not + distribute the Program at all. For example, if a patent license would not + permit royalty-free redistribution of the Program by all those who receive + copies directly or indirectly through you, then the only way you could + satisfy both it and this License would be to refrain entirely from + distribution of the Program. +

+

+ If any portion of this section is held invalid or unenforceable under any + particular circumstance, the balance of the section is intended to apply + and the section as a whole is intended to apply in other circumstances. +

+

+ It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any such + claims; this section has the sole purpose of protecting the integrity of + the free software distribution system, which is implemented by public + license practices. Many people have made generous contributions to the + wide range of software distributed through that system in reliance on + consistent application of that system; it is up to the author/donor to + decide if he or she is willing to distribute software through any other + system and a licensee cannot impose that choice. +

+

+ This section is intended to make thoroughly clear what is believed to be a + consequence of the rest of this License. +

+

+ 8. If the distribution and/or use of the Program is + restricted in certain countries either by patents or by copyrighted + interfaces, the original copyright holder who places the Program under + this License may add an explicit geographical distribution limitation + excluding those countries, so that distribution is permitted only in or + among countries not thus excluded. In such case, this License incorporates + the limitation as if written in the body of this License. +

+

+ 9. The Free Software Foundation may publish revised + and/or new versions of the General Public License from time to time. Such + new versions will be similar in spirit to the present version, but may + differ in detail to address new problems or concerns. +

+

+ Each version is given a distinguishing version number. If the Program + specifies a version number of this License which applies to it and "any + later version", you have the option of following the terms and conditions + either of that version or of any later version published by the Free + Software Foundation. If the Program does not specify a version number of + this License, you may choose any version ever published by the Free + Software Foundation. +

+

+ 10. If you wish to incorporate parts of the Program into + other free programs whose distribution conditions are different, write to + the author to ask for permission. For software which is copyrighted by the + Free Software Foundation, write to the Free Software Foundation; we + sometimes make exceptions for this. Our decision will be guided by the two + goals of preserving the free status of all derivatives of our free + software and of promoting the sharing and reuse of software generally. +

+

NO WARRANTY

+

+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE + IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. + EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER + PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER + EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE + ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. + SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY + SERVICING, REPAIR OR CORRECTION. +

+

+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR + AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY + MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO + YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE + PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED + INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE + PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER + PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +

+

+

END OF TERMS AND CONDITIONS

+ + diff --git a/pandora_console/general/license/pandora_info_es.html b/pandora_console/general/license/pandora_info_es.html index aa20e3bc57..39f337a006 100644 --- a/pandora_console/general/license/pandora_info_es.html +++ b/pandora_console/general/license/pandora_info_es.html @@ -1,391 +1,542 @@ - - -Licencia Pública GNU - - + + + Licencia Pública GNU + + +

Licencia Pública GNU

+

Contenido

-

Licencia Pública GNU

-

Contenido

+ +
+

Licencia Pública GNU

+

+ Esta es la conocida GNU Public License (GPL), versión 2 (de junio + de 1.991), que cubre la mayor parte del software de la Free Software + Foundation, y muchos más programas. +

- -
-

Licencia Pública GNU

-

-Esta es la conocida GNU Public License (GPL), versión 2 (de junio -de 1.991), que cubre la mayor parte del software de la Free Software Foundation, -y muchos más programas.

+

Los autores de esta traducción son:

+ -

Los autores de esta traducción son: -

+
+
+ NOTA IMPORTANTE: +

+ Esta es una traducción no oficial al español de la GNU + General Public License. No ha sido publicada por la Free Software + Foundation, y no establece legalmente las condiciones de + distribución para el software que usa la GNU GPL. Estas + condiciones se establecen solamente por el texto original, en + inglés, de la GNU GPL. Sin embargo, esperamos que esta + traducción ayude a los hispanohablantes a entender mejor la GNU + GPL. +

+

IMPORTANT NOTICE:

+

+ This is an unofficial translation of the GNU General Public License into + Spanish. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, + we hope that this translation will help Spanish speakers understand the + GNU GPL better. +

+

+
+
-
-
-NOTA IMPORTANTE: -

-Esta es una traducción no oficial al español de la GNU General Public -License. No ha sido publicada por la Free Software Foundation, y no -establece legalmente las condiciones de distribución para el software -que usa la GNU GPL. Estas condiciones se establecen solamente por -el texto original, en inglés, de la GNU GPL. Sin embargo, esperamos -que esta traducción ayude a los hispanohablantes a entender mejor la -GNU GPL. -

+

Copyright (C) 1989, 1991 Free Software Foundation, Inc.

+

675 Mass Ave, Cambridge, MA 02139, EEUU

+

+ Se permite la copia y distribución de copias literales de este + documento, pero no se permite su modificación. +

-IMPORTANT NOTICE: -

-This is an unofficial translation of the GNU General Public License -into Spanish. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL--only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Spanish speakers understand the GNU GPL better. -

-


-
+

Preámbulo

+

+ Las licencias que cubren la mayor parte del software están + diseñadas para quitarle a usted la libertad de compartirlo y + modificarlo. Por el contrario, la Licencia Pública General de GNU + pretende garantizarle la libertad de compartir y modificar software libre, + para asegurar que el software es libre para todos sus usuarios. Esta + Licencia Pública General se aplica a la mayor parte del software + del la Free Software Foundation y a cualquier otro programa si sus autores + se comprometen a utilizarla. (Existe otro software de la Free Software + Foundation que está cubierto por la Licencia Pública General + de GNU para Bibliotecas). Si quiere, también puede aplicarla a sus + propios programas. +

+

+ Cuando hablamos de software libre, estamos refiriéndonos a + libertad, no a precio. Nuestras Licencias Públicas Generales + están diseñadas para asegurarnos de que tenga la libertad de + distribuir copias de software libre (y cobrar por ese servicio si quiere), + de que reciba el código fuente o que pueda conseguirlo si lo + quiere, de que pueda modificar el software o usar fragmentos de él + en nuevos programas libres, y de que sepa que puede hacer todas estas + cosas. +

+

+ Para proteger sus derechos necesitamos algunas restricciones que prohiban + a cualquiera negarle a usted estos derechos o pedirle que renuncie a + ellos. Estas restricciones se traducen en ciertas obligaciones que le + afectan si distribuye copias del software, o si lo modifica. +

+

+ Por ejemplo, si distribuye copias de uno de estos programas, sea + gratuitamente, o a cambio de una contraprestación, debe dar a los + receptores todos los derechos que tiene. Debe asegurarse de que ellos + también reciben, o pueden conseguir, el código fuente. Y + debe mostrarles estas condiciones de forma que conozcan sus derechos. +

+

Protegemos sus derechos con la combinación de dos medidas:

+
    +
  1. Ponemos el software bajo copyright y
  2. +
  3. + le ofrecemos esta licencia, que le da permiso legal para copiar, + distribuir y/o modificar el software. +
  4. +
+

+ También, para la protección de cada autor y la nuestra + propia, queremos asegurarnos de que todo el mundo comprende que no se + proporciona ninguna garantía para este software libre. Si el + software se modifica por cualquiera y éste a su vez lo distribuye, + queremos que sus receptores sepan que lo que tienen no es el original, de + forma que cualquier problema introducido por otros no afecte a la + reputación de los autores originales. +

+

+ Por último, cualquier programa libre está constantemente + amenazado por patentes sobre el software. Queremos evitar el peligro de + que los redistribuidores de un programa libre obtengan patentes por su + cuenta, convirtiendo de facto el programa en propietario. Para evitar + esto, hemos dejado claro que cualquier patente debe ser pedida para el uso + libre de cualquiera, o no ser pedida. +

+

+ Los términos exactos y las condiciones para la copia, + distribución y modificación se exponen a + continuación. +

-

Copyright (C) 1989, 1991 Free Software Foundation, Inc. -

675 Mass Ave, Cambridge, MA 02139, EEUU -

Se permite la copia y distribución de copias literales de este -documento, pero no se permite su modificación. -

+

+ Términos y condiciones para la copia, distribución y + modificación +

+
    +
  1. + Esta Licencia se aplica a cualquier programa u otro tipo de trabajo que + contenga una nota colocada por el tenedor del copyright diciendo que + puede ser distribuido bajo los términos de esta Licencia + Pública General. En adelante, �Programa� se referirá a + cualquier programa o trabajo que cumpla esa condición y �trabajo + basado en el Programa� se referirá bien al Programa o a cualquier + trabajo derivado de él según la ley de copyright. Esto es, + un trabajo que contenga el programa o una proción de él, + bien en forma literal o con modificaciones y/o traducido en otro + lenguaje. Por lo tanto, la traducción está incluida sin + limitaciones en el término �modificación�. Cada + concesionario (licenciatario) será denominado �usted�. +

    + Cualquier otra actividad que no sea la copia, distribución o + modificación no está cubierta por esta Licencia, + está fuera de su ámbito. El acto de ejecutar el Programa + no está restringido, y los resultados del Programa están + cubiertos únicamente si sus contenidos constituyen un trabajo + basado en el Programa, independientemente de haberlo producido + mediante la ejecución del programa. El que esto se cumpla, + depende de lo que haga el programa. +

    +
  2. +
  3. + Usted puede copiar y distribuir copias literales del código + fuente del Programa, según lo has recibido, en cualquier medio, + supuesto que de forma adecuada y bien visible publique en cada copia un + anuncio de copyright adecuado y un repudio de garantía, mantenga + intactos todos los anuncios que se refieran a esta Licencia y a la + ausencia de garantía, y proporcione a cualquier otro receptor del + programa una copia de esta Licencia junto con el Programa. +

    + Puede cobrar un precio por el acto físico de transferir una + copia, y puede, según su libre albedrío, ofrecer + garantía a cambio de unos honorarios. +

    +
  4. +
  5. + Puede modificar su copia o copias del Programa o de cualquier + porción de él, formando de esta manera un trabajo basado + en el Programa, y copiar y distribuir esa modificación o trabajo + bajo los términos del apartado 1, antedicho, supuesto que + además cumpla las siguientes condiciones: +
      +
    1. + Debe hacer que los ficheros modificados lleven anuncios prominentes + indicando que los ha cambiado y la fecha de cualquier cambio. +
    2. +
    3. + Debe hacer que cualquier trabajo que distribuya o publique y que en + todo o en parte contenga o sea derivado del Programa o de cualquier + parte de él sea licenciada como un todo, sin carga alguna, a + todas las terceras partes y bajo los términos de esta + Licencia. +
    4. +
    5. + Si el programa modificado lee normalmente órdenes + interactivamente cuando es ejecutado, debe hacer que, cuando + comience su ejecución para ese uso interactivo de la forma + más habitual, muestre o escriba un mensaje que incluya un + anuncio de copyright y un anuncio de que no se ofrece ninguna + garantía (o por el contrario que sí se ofrece + garantía) y que los usuarios pueden redistribuir el programa + bajo estas condiciones, e indicando al usuario cómo ver una + copia de esta licencia. (Excepción: si el propio programa es + interactivo pero normalmente no muestra ese anuncio, no se requiere + que su trabajo basado en el Programa muestre ningún anuncio). +
    6. +
    + Estos requisitos se aplican al trabajo modificado como un todo. Si + partes identificables de ese trabajo no son derivadas del Programa, y + pueden, razonablemente, ser consideradas trabajos independientes y + separados por ellos mismos, entonces esta Licencia y sus términos + no se aplican a esas partes cuando sean distribuidas como trabajos + separados. Pero cuando distribuya esas mismas secciones como partes de + un todo que es un trabajo basado en el Programa, la distribución + del todo debe ser según los términos de esta licencia, + cuyos permisos para otros licenciatarios se extienden al todo completo, + y por lo tanto a todas y cada una de sus partes, con independencia de + quién la escribió. +

    + Por lo tanto, no es la intención de este apartado reclamar + derechos o desafiar sus derechos sobre trabajos escritos totalmente + por usted mismo. El intento es ejercer el derecho a controlar la + distribución de trabajos derivados o colectivos basados en el + Programa. +

    +

    + Además, el simple hecho de reunir un trabajo no basado en el + Programa con el Programa (o con un trabajo basado en el Programa) en + un volumen de almacenamiento o en un medio de distribución no + hace que dicho trabajo entre dentro del ámbito cubierto por + esta Licencia. +

    +
  6. +
  7. + Puede copiar y distribuir el Programa (o un trabajo basado en él, + según se especifica en el apartado 2, como código objeto o + en formato ejecutable según los términos de los apartados + 1 y 2, supuesto que además cumpla una de las siguientes + condiciones: +
      +
    1. + Acompañarlo con el código fuente completo + correspondiente, en formato electrónico, que debe ser + distribuido según se especifica en los apartados 1 y 2 de + esta Licencia en un medio habitualmente utilizado para el + intercambio de programas, o +
    2. +
    3. + Acompañarlo con una oferta por escrito, válida durante + al menos tres años, de proporcionar a cualquier tercera parte + una copia completa en formato electrónico del código + fuente correspondiente, a un coste no mayor que el de realizar + físicamente la distribución del fuente, que + será distribuido bajo las condiciones descritas en los + apartados 1 y 2 anteriores, en un medio habitualmente utilizado para + el intercambio de programas, o +
    4. +
    5. + Acompañarlo con la información que recibiste + ofreciendo distribuir el código fuente correspondiente. (Esta + opción se permite sólo para distribución no + comercial y sólo si usted recibió el programa como + código objeto o en formato ejecutable con tal oferta, de + acuerdo con el apartado b anterior). +
    6. +
    + Por código fuente de un trabajo se entiende la forma preferida + del trabajo cuando se le hacen modificaciones. Para un trabajo + ejecutable, se entiende por código fuente completo todo el + código fuente para todos los módulos que contiene, + más cualquier fichero asociado de definición de + interfaces, más los guiones utilizados para controlar la + compilación e instalación del ejecutable. Como + excepción especial el código fuente distribuido no + necesita incluir nada que sea distribuido normalmente (bien como fuente, + bien en forma binaria) con los componentes principales (compilador, + kernel y similares) del sistema operativo en el cual funciona el + ejecutable, a no ser que el propio componente acompañe al + ejecutable. +

    + Si la distribución del ejecutable o del código objeto se + hace mediante la oferta acceso para copiarlo de un cierto lugar, + entonces se considera la oferta de acceso para copiar el código + fuente del mismo lugar como distribución del código + fuente, incluso aunque terceras partes no estén forzadas a + copiar el fuente junto con el código objeto. +

    +
  8. +
  9. + No puede copiar, modificar, sublicenciar o distribuir el Programa + excepto como prevé expresamente esta Licencia. Cualquier intento + de copiar, modificar sublicenciar o distribuir el Programa de otra forma + es inválida, y hará que cesen automáticamente los + derechos que te proporciona esta Licencia. En cualquier caso, las partes + que hayan recibido copias o derechos de usted bajo esta Licencia no + cesarán en sus derechos mientras esas partes continúen + cumpliéndola. +
  10. +
  11. + No está obligado a aceptar esta licencia, ya que no la ha + firmado. Sin embargo, no hay hada más que le proporcione permiso + para modificar o distribuir el Programa o sus trabajos derivados. Estas + acciones están prohibidas por la ley si no acepta esta Licencia. + Por lo tanto, si modifica o distribuye el Programa (o cualquier trabajo + basado en el Programa), está indicando que acepta esta Licencia + para poder hacerlo, y todos sus términos y condiciones para + copiar, distribuir o modificar el Programa o trabajos basados en + él. +
  12. +
  13. + Cada vez que redistribuya el Programa (o cualquier trabajo basado en el + Programa), el receptor recibe automáticamente una licencia del + licenciatario original para copiar, distribuir o modificar el Programa, + de forma sujeta a estos términos y condiciones. No puede imponer + al receptor ninguna restricción más sobre el ejercicio de + los derechos aquí garantizados. No es usted responsable de hacer + cumplir esta licencia por terceras partes. +
  14. +
  15. + Si como consecuencia de una resolución judicial o de una + alegación de infracción de patente o por cualquier otra + razón (no limitada a asuntos relacionados con patentes) se le + imponen condiciones (ya sea por mandato judicial, por acuerdo o por + cualquier otra causa) que contradigan las condiciones de esta Licencia, + ello no le exime de cumplir las condiciones de esta Licencia. Si no + puede realizar distribuciones de forma que se satisfagan + simultáneamente sus obligaciones bajo esta licencia y cualquier + otra obligación pertinente entonces, como consecuencia, no puede + distribuir el Programa de ninguna forma. Por ejemplo, si una patente no + permite la redistribución libre de derechos de autor del Programa + por parte de todos aquellos que reciban copias directa o indirectamente + a través de usted, entonces la única forma en que + podría satisfacer tanto esa condición como esta Licencia + sería evitar completamente la distribución del Programa. +

    + Si cualquier porción de este apartado se considera + inválida o imposible de cumplir bajo cualquier circunstancia + particular ha de cumplirse el resto y la sección por entero ha + de cumplirse en cualquier otra circunstancia. +

    +

    + No es el propósito de este apartado inducirle a infringir + ninguna reivindicación de patente ni de ningún otro + derecho de propiedad o impugnar la validez de ninguna de dichas + reivindicaciones. Este apartado tiene el único propósito + de proteger la integridad del sistema de distribución de + software libre, que se realiza mediante prácticas de licencia + pública. Mucha gente ha hecho contribuciones generosas a la + gran variedad de software distribuido mediante ese sistema con la + confianza de que el sistema se aplicará consistentemente. + Será el autor/donante quien decida si quiere distribuir + software mediante cualquier otro sistema y una licencia no puede + imponer esa elección. +

    +

    + Este apartado pretende dejar completamente claro lo que se cree que es + una consecuencia del resto de esta Licencia. +

    +
  16. +
  17. + Si la distribución y/o uso de el Programa está restringida + en ciertos países, bien por patentes o por interfaces bajo + copyright, el tenedor del copyright que coloca este Programa bajo esta + Licencia puede añadir una limitación explícita de + distribución geográfica excluyendo esos países, de + forma que la distribución se permita sólo en o entre los + países no excluidos de esta manera. En ese caso, esta Licencia + incorporará la limitación como si estuviese escrita en el + cuerpo de esta Licencia. +
  18. +
  19. + La Free Software Foundation puede publicar versiones revisadas y/o + nuevas de la Licencia Pública General de tiempo en tiempo. Dichas + nuevas versiones serán similares en espíritu a la presente + versión, pero pueden ser diferentes en detalles para considerar + nuevos problemas o situaciones. +

    + Cada versión recibe un número de versión que la + distingue de otras. Si el Programa especifica un número de + versión de esta Licencia que se refiere a ella y a �cualquier + versión posterior�, tienes la opción de seguir los + términos y condiciones, bien de esa versión, bien de + cualquier versión posterior publicada por la Free Software + Foundation. Si el Programa no especifica un número de + versión de esta Licencia, puedes escoger cualquier + versión publicada por la Free Software Foundation. +

    +
  20. +
  21. + Si quiere incorporar partes del Programa en otros programas libres cuyas + condiciones de distribución son diferentes, escribe al autor para + pedirle permiso. Si el software tiene copyright de la Free Software + Foundation, escribe a la Free Software Foundation: algunas veces hacemos + excepciones en estos casos. Nuestra decisión estará guiada + por el doble objetivo de de preservar la libertad de todos los derivados + de nuestro software libre y promover el que se comparta y reutilice el + software en general. +
  22. +
-

Preámbulo

-

-Las licencias que cubren la mayor parte del software están diseñadas -para quitarle a usted la libertad de compartirlo y modificarlo. Por el -contrario, la Licencia Pública General de GNU pretende garantizarle -la libertad de compartir y modificar software libre, para asegurar que -el software es libre para todos sus usuarios. Esta Licencia Pública -General se aplica a la mayor parte del software del la Free Software Foundation -y a cualquier otro programa si sus autores se comprometen a utilizarla. -(Existe otro software de la Free Software Foundation que está cubierto -por la Licencia Pública General de GNU para Bibliotecas). Si quiere, -también puede aplicarla a sus propios programas.

-

Cuando hablamos de software libre, estamos refiriéndonos a libertad, -no a precio. Nuestras Licencias Públicas Generales están -diseñadas para asegurarnos de que tenga la libertad de distribuir -copias de software libre (y cobrar por ese servicio si quiere), de que -reciba el código fuente o que pueda conseguirlo si lo quiere, de -que pueda modificar el software o usar fragmentos de él en nuevos -programas libres, y de que sepa que puede hacer todas estas cosas. -

Para proteger sus derechos necesitamos algunas restricciones que prohiban -a cualquiera negarle a usted estos derechos o pedirle que renuncie a ellos. -Estas restricciones se traducen en ciertas obligaciones que le afectan -si distribuye copias del software, o si lo modifica. -

Por ejemplo, si distribuye copias de uno de estos programas, sea gratuitamente, -o a cambio de una contraprestación, debe dar a los receptores todos -los derechos que tiene. Debe asegurarse de que ellos también reciben, -o pueden conseguir, el código fuente. Y debe mostrarles estas condiciones -de forma que conozcan sus derechos. -

Protegemos sus derechos con la combinación de dos medidas: -

    -
  1. Ponemos el software bajo copyright y -
  2. le ofrecemos esta licencia, que le da permiso legal para copiar, distribuir -y/o modificar el software.
-

-También, para la protección de cada autor y la nuestra propia, -queremos asegurarnos de que todo el mundo comprende que no se proporciona -ninguna garantía para este software libre. Si el software se modifica -por cualquiera y éste a su vez lo distribuye, queremos que sus receptores -sepan que lo que tienen no es el original, de forma que cualquier problema -introducido por otros no afecte a la reputación de los autores originales.

-

Por último, cualquier programa libre está constantemente -amenazado por patentes sobre el software. Queremos evitar el peligro de -que los redistribuidores de un programa libre obtengan patentes por su -cuenta, convirtiendo de facto el programa en propietario. Para evitar esto, -hemos dejado claro que cualquier patente debe ser pedida para el uso libre -de cualquiera, o no ser pedida. -

Los términos exactos y las condiciones para la copia, distribución -y modificación se exponen a continuación.

+

AUSENCIA DE GARANTÍA

-

Términos y condiciones para la copia, -distribución y modificación

+
    +
  1. + Como el programa se licencia libre de cargas, no se ofrece ninguna + garantía sobre el programa, en todas la extensión + permitida por la legislación aplicable. Excepto cuando se indique + de otra forma por escrito, los tenedores del copyright y/u otras partes + proporcionan el programa �tal cual�, sin garantía de ninguna + clase, bien expresa o implícita, con inclusión, pero sin + limitación a las garantías mercantiles implícitas o + a la conveniencia para un propósito particular. Cualquier riesgo + referente a la calidad y prestaciones del programa es asumido por usted. + Si se probase que el Programa es defectuoso, asume el coste de cualquier + servicio, reparación o corrección. +
  2. +
  3. + En ningún caso, salvo que lo requiera la legislación + aplicable o haya sido acordado por escrito, ningún tenedor del + copyright ni ninguna otra parte que modifique y/o redistribuya el + Programa según se permite en esta Licencia será + responsable ante usted por daños, incluyendo cualquier + daño general, especial, incidental o resultante producido por el + uso o la imposibilidad de uso del Programa (con inclusión, pero + sin limitación a la pérdida de datos o a la + generación incorrecta de datos o a pérdidas sufridas por + usted o por terceras partes o a un fallo del Programa al funcionar en + combinación con cualquier otro programa), incluso si dicho + tenedor u otra parte ha sido advertido de la posibilidad de dichos + daños. +
  4. +
-
    -
  1. Esta Licencia se aplica a cualquier programa u otro tipo -de trabajo que contenga una nota colocada por el tenedor del copyright -diciendo que puede ser distribuido bajo los términos de esta Licencia -Pública General. En adelante, �Programa� se referirá -a cualquier programa o trabajo que cumpla esa condición y �trabajo -basado en el Programa� se referirá bien al Programa o a cualquier -trabajo derivado de él según la ley de copyright. Esto es, -un trabajo que contenga el programa o una proción de él, -bien en forma literal o con modificaciones y/o traducido en otro lenguaje. -Por lo tanto, la traducción está incluida sin limitaciones -en el término �modificación�. Cada concesionario -(licenciatario) será denominado �usted�. -

    Cualquier otra actividad que no sea la copia, distribución o -modificación no está cubierta por esta Licencia, está -fuera de su ámbito. El acto de ejecutar el Programa no está -restringido, y los resultados del Programa están cubiertos únicamente -si sus contenidos constituyen un trabajo basado en el Programa, independientemente -de haberlo producido mediante la ejecución del programa. El que -esto se cumpla, depende de lo que haga el programa. -

  2. Usted puede copiar y distribuir copias literales del código fuente -del Programa, según lo has recibido, en cualquier medio, supuesto -que de forma adecuada y bien visible publique en cada copia un anuncio -de copyright adecuado y un repudio de garantía, mantenga intactos -todos los anuncios que se refieran a esta Licencia y a la ausencia de garantía, -y proporcione a cualquier otro receptor del programa una copia de esta -Licencia junto con el Programa. -

    Puede cobrar un precio por el acto físico de transferir una copia, -y puede, según su libre albedrío, ofrecer garantía -a cambio de unos honorarios. -

  3. Puede modificar su copia o copias del Programa o de cualquier porción -de él, formando de esta manera un trabajo basado en el Programa, -y copiar y distribuir esa modificación o trabajo bajo los términos -del apartado 1, antedicho, supuesto que además cumpla las siguientes -condiciones: -
    1. Debe hacer que los ficheros modificados lleven anuncios -prominentes indicando que los ha cambiado y la fecha de cualquier cambio. -
    2. Debe hacer que cualquier trabajo que distribuya o publique y que en -todo o en parte contenga o sea derivado del Programa o de cualquier parte -de él sea licenciada como un todo, sin carga alguna, a todas las -terceras partes y bajo los términos de esta Licencia. -
    3. Si el programa modificado lee normalmente órdenes interactivamente -cuando es ejecutado, debe hacer que, cuando comience su ejecución -para ese uso interactivo de la forma más habitual, muestre o escriba -un mensaje que incluya un anuncio de copyright y un anuncio de que no se -ofrece ninguna garantía (o por el contrario que sí se ofrece -garantía) y que los usuarios pueden redistribuir el programa bajo -estas condiciones, e indicando al usuario cómo ver una copia de -esta licencia. (Excepción: si el propio programa es interactivo -pero normalmente no muestra ese anuncio, no se requiere que su trabajo -basado en el Programa muestre ningún anuncio).
    -Estos requisitos se aplican al trabajo modificado como un todo. Si partes -identificables de ese trabajo no son derivadas del Programa, y pueden, -razonablemente, ser consideradas trabajos independientes y separados por -ellos mismos, entonces esta Licencia y sus términos no se aplican -a esas partes cuando sean distribuidas como trabajos separados. Pero cuando -distribuya esas mismas secciones como partes de un todo que es un trabajo -basado en el Programa, la distribución del todo debe ser según -los términos de esta licencia, cuyos permisos para otros licenciatarios -se extienden al todo completo, y por lo tanto a todas y cada una de sus -partes, con independencia de quién la escribió. -

    Por lo tanto, no es la intención de este apartado reclamar derechos -o desafiar sus derechos sobre trabajos escritos totalmente por usted mismo. -El intento es ejercer el derecho a controlar la distribución de -trabajos derivados o colectivos basados en el Programa. -

    Además, el simple hecho de reunir un trabajo no basado en el -Programa con el Programa (o con un trabajo basado en el Programa) en un -volumen de almacenamiento o en un medio de distribución no hace -que dicho trabajo entre dentro del ámbito cubierto por esta Licencia. -

  4. Puede copiar y distribuir el Programa (o un trabajo basado en él, -según se especifica en el apartado 2, como código objeto -o en formato ejecutable según los términos de los apartados -1 y 2, supuesto que además cumpla una de las siguientes condiciones: -
    1. Acompañarlo con el código fuente completo -correspondiente, en formato electrónico, que debe ser distribuido -según se especifica en los apartados 1 y 2 de esta Licencia en un -medio habitualmente utilizado para el intercambio de programas, o -
    2. Acompañarlo con una oferta por escrito, válida durante -al menos tres años, de proporcionar a cualquier tercera parte una -copia completa en formato electrónico del código fuente correspondiente, -a un coste no mayor que el de realizar físicamente la distribución -del fuente, que será distribuido bajo las condiciones descritas -en los apartados 1 y 2 anteriores, en un medio habitualmente utilizado -para el intercambio de programas, o -
    3. Acompañarlo con la información que recibiste ofreciendo -distribuir el código fuente correspondiente. (Esta opción -se permite sólo para distribución no comercial y sólo -si usted recibió el programa como código objeto o en formato -ejecutable con tal oferta, de acuerdo con el apartado b anterior).
    -Por código fuente de un trabajo se entiende la forma preferida del -trabajo cuando se le hacen modificaciones. Para un trabajo ejecutable, -se entiende por código fuente completo todo el código fuente -para todos los módulos que contiene, más cualquier fichero -asociado de definición de interfaces, más los guiones utilizados -para controlar la compilación e instalación del ejecutable. -Como excepción especial el código fuente distribuido no necesita -incluir nada que sea distribuido normalmente (bien como fuente, bien en -forma binaria) con los componentes principales (compilador, kernel y similares) -del sistema operativo en el cual funciona el ejecutable, a no ser que el -propio componente acompañe al ejecutable. -

    Si la distribución del ejecutable o del código objeto -se hace mediante la oferta acceso para copiarlo de un cierto lugar, entonces -se considera la oferta de acceso para copiar el código fuente del -mismo lugar como distribución del código fuente, incluso -aunque terceras partes no estén forzadas a copiar el fuente junto -con el código objeto. -

  5. No puede copiar, modificar, sublicenciar o distribuir el Programa excepto -como prevé expresamente esta Licencia. Cualquier intento de copiar, -modificar sublicenciar o distribuir el Programa de otra forma es inválida, -y hará que cesen automáticamente los derechos que te proporciona -esta Licencia. En cualquier caso, las partes que hayan recibido copias -o derechos de usted bajo esta Licencia no cesarán en sus derechos -mientras esas partes continúen cumpliéndola. -
  6. No está obligado a aceptar esta licencia, ya que no la ha firmado. -Sin embargo, no hay hada más que le proporcione permiso para modificar -o distribuir el Programa o sus trabajos derivados. Estas acciones están -prohibidas por la ley si no acepta esta Licencia. Por lo tanto, si modifica -o distribuye el Programa (o cualquier trabajo basado en el Programa), está -indicando que acepta esta Licencia para poder hacerlo, y todos sus términos -y condiciones para copiar, distribuir o modificar el Programa o trabajos -basados en él. -
  7. Cada vez que redistribuya el Programa (o cualquier trabajo basado en -el Programa), el receptor recibe automáticamente una licencia del -licenciatario original para copiar, distribuir o modificar el Programa, -de forma sujeta a estos términos y condiciones. No puede imponer -al receptor ninguna restricción más sobre el ejercicio de -los derechos aquí garantizados. No es usted responsable de hacer -cumplir esta licencia por terceras partes. -
  8. Si como consecuencia de una resolución judicial o de una alegación -de infracción de patente o por cualquier otra razón (no limitada -a asuntos relacionados con patentes) se le imponen condiciones (ya sea -por mandato judicial, por acuerdo o por cualquier otra causa) que contradigan -las condiciones de esta Licencia, ello no le exime de cumplir las condiciones -de esta Licencia. Si no puede realizar distribuciones de forma que se satisfagan -simultáneamente sus obligaciones bajo esta licencia y cualquier -otra obligación pertinente entonces, como consecuencia, no puede -distribuir el Programa de ninguna forma. Por ejemplo, si una patente no -permite la redistribución libre de derechos de autor del Programa -por parte de todos aquellos que reciban copias directa o indirectamente -a través de usted, entonces la única forma en que podría -satisfacer tanto esa condición como esta Licencia sería evitar -completamente la distribución del Programa. -

    Si cualquier porción de este apartado se considera inválida -o imposible de cumplir bajo cualquier circunstancia particular ha de cumplirse -el resto y la sección por entero ha de cumplirse en cualquier otra -circunstancia. -

    No es el propósito de este apartado inducirle a infringir ninguna -reivindicación de patente ni de ningún otro derecho de propiedad -o impugnar la validez de ninguna de dichas reivindicaciones. Este apartado -tiene el único propósito de proteger la integridad del sistema -de distribución de software libre, que se realiza mediante prácticas -de licencia pública. Mucha gente ha hecho contribuciones generosas -a la gran variedad de software distribuido mediante ese sistema con la -confianza de que el sistema se aplicará consistentemente. Será -el autor/donante quien decida si quiere distribuir software mediante cualquier -otro sistema y una licencia no puede imponer esa elección. -

    Este apartado pretende dejar completamente claro lo que se cree que -es una consecuencia del resto de esta Licencia. -

  9. Si la distribución y/o uso de el Programa está restringida -en ciertos países, bien por patentes o por interfaces bajo copyright, -el tenedor del copyright que coloca este Programa bajo esta Licencia puede -añadir una limitación explícita de distribución -geográfica excluyendo esos países, de forma que la distribución -se permita sólo en o entre los países no excluidos de esta -manera. En ese caso, esta Licencia incorporará la limitación -como si estuviese escrita en el cuerpo de esta Licencia. -
  10. La Free Software Foundation puede publicar versiones revisadas y/o nuevas -de la Licencia Pública General de tiempo en tiempo. Dichas nuevas -versiones serán similares en espíritu a la presente versión, -pero pueden ser diferentes en detalles para considerar nuevos problemas -o situaciones. -

    Cada versión recibe un número de versión que la -distingue de otras. Si el Programa especifica un número de versión -de esta Licencia que se refiere a ella y a �cualquier versión -posterior�, tienes la opción de seguir los términos -y condiciones, bien de esa versión, bien de cualquier versión -posterior publicada por la Free Software Foundation. Si el Programa no -especifica un número de versión de esta Licencia, puedes -escoger cualquier versión publicada por la Free Software Foundation. -

  11. Si quiere incorporar partes del Programa en otros programas libres cuyas -condiciones de distribución son diferentes, escribe al autor para -pedirle permiso. Si el software tiene copyright de la Free Software Foundation, -escribe a la Free Software Foundation: algunas veces hacemos excepciones -en estos casos. Nuestra decisión estará guiada por el doble -objetivo de de preservar la libertad de todos los derivados de nuestro -software libre y promover el que se comparta y reutilice el software en -general.
+

FIN DE TÉRMINOS Y CONDICIONES

-

AUSENCIA DE GARANTÍA

- -
    -
  1. Como el programa se licencia libre de cargas, -no se ofrece ninguna garantía sobre el programa, en todas la extensión -permitida por la legislación aplicable. Excepto cuando se indique -de otra forma por escrito, los tenedores del copyright y/u otras partes -proporcionan el programa �tal cual�, sin garantía de -ninguna clase, bien expresa o implícita, con inclusión, pero -sin limitación a las garantías mercantiles implícitas -o a la conveniencia para un propósito particular. Cualquier riesgo -referente a la calidad y prestaciones del programa es asumido por usted. -Si se probase que el Programa es defectuoso, asume el coste de cualquier -servicio, reparación o corrección. -
  2. En ningún caso, salvo que lo requiera la legislación aplicable -o haya sido acordado por escrito, ningún tenedor del copyright ni -ninguna otra parte que modifique y/o redistribuya el Programa según -se permite en esta Licencia será responsable ante usted por daños, -incluyendo cualquier daño general, especial, incidental o resultante -producido por el uso o la imposibilidad de uso del Programa (con inclusión, -pero sin limitación a la pérdida de datos o a la generación -incorrecta de datos o a pérdidas sufridas por usted o por terceras -partes o a un fallo del Programa al funcionar en combinación con -cualquier otro programa), incluso si dicho tenedor u otra parte ha sido -advertido de la posibilidad de dichos daños.
- -

FIN DE TÉRMINOS Y CONDICIONES

- -

Apéndice: Cómo aplicar estos -términos a sus nuevos programas.

-

-Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso posible -para el público en general, la mejor forma de conseguirlo es convirtiéndolo -en software libre que cualquiera pueda redistribuir y cambiar bajo estos -términos.

-

Para hacerlo, añada los siguientes anuncios al programa. Lo más -seguro es añadirlos al principio de cada fichero fuente para transmitir -lo más efectivamente posible la ausencia de garantía. Además -cada fichero debería tener al menos la línea de �copyright� -y un indicador a dónde puede encontrarse el anuncio completo. -

<una línea para indicar el nombre -del programa y una rápida idea de qué hace.> -

Copyright (C) 19aa <nombre del autor> -

Este programa es software libre. Puede redistribuirlo y/o modificarlo -bajo los términos de la Licencia Pública General de GNU según -es publicada por la Free Software Foundation, bien de la versión -2 de dicha Licencia o bien (según su elección) de cualquier -versión posterior. -

Este programa se distribuye con la esperanza de que sea útil, -pero SIN NINGUNA GARANT�A, incluso sin la garantía MERCANTIL -implícita o sin garantizar la CONVENIENCIA PARA UN PROP�SITO -PARTICULAR. Véase la Licencia Pública General de GNU para -más detalles. -

Debería haber recibido una copia de la Licencia Pública -General junto con este programa. Si no ha sido así, escriba a la -Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU.

-

-Añada también información sobre cómo contactar -con usted mediante correo electrónico y postal.

-

Si el programa es interactivo, haga que muestre un pequeño anuncio -como el siguiente, cuando comienza a funcionar en modo interactivo: -

Gnomovision versión 69, Copyright -(C) 19aa nombre del autor -

Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para más -detalles escriba �show w�.

-

-Los comandos hipotéticos �show w� y �show c� -deberían mostrar las partes adecuadas de la Licencia Pública -General. Por supuesto, los comandos que use pueden llamarse de cualquier -otra manera. Podrían incluso ser pulsaciones del ratón o -elementos de un menú (lo que sea apropiado para su programa).

-

También deberías conseguir que su empleador (si trabaja -como programador) o tu Universidad (si es el caso) firme un �renuncia -de copyright� para el programa, si es necesario. A continuación -se ofrece un ejemplo, altere los nombres según sea conveniente: -

    -
  1. -Yoyodyne, Inc. mediante este documento renuncia -a cualquier interés de derechos de copyright con respecto al programa -Gnomovision (que hace pasadas a compiladores) escrito por Pepe Programador. -

    <firma de Pepito Grillo>, 20 de diciembre de 1996 -

    Pepito Grillo, Presidente de Asuntillos Varios.

-

-Esta Licencia Pública General no permite que incluya sus programas -en programas propietarios. Si su programa es una biblioteca de subrutinas, -puede considerar más útil el permitir el enlazado de aplicaciones -propietarias con la biblioteca. Si este es el caso, use la Licencia Pública -General de GNU para Bibliotecas en lugar de esta Licencia.

- - \ No newline at end of file +

+ Apéndice: Cómo aplicar estos + términos a sus nuevos programas. +

+

+ Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso + posible para el público en general, la mejor forma de conseguirlo + es convirtiéndolo en software libre que cualquiera pueda + redistribuir y cambiar bajo estos términos. +

+

+ Para hacerlo, añada los siguientes anuncios al programa. Lo + más seguro es añadirlos al principio de cada fichero fuente + para transmitir lo más efectivamente posible la ausencia de + garantía. Además cada fichero debería tener al menos + la línea de �copyright� y un indicador a dónde puede + encontrarse el anuncio completo. +

+
+ <una línea para indicar el nombre del programa y una + rápida idea de qué hace.> +

Copyright (C) 19aa <nombre del autor>

+

+ Este programa es software libre. Puede redistribuirlo y/o modificarlo + bajo los términos de la Licencia Pública General de GNU + según es publicada por la Free Software Foundation, bien de la + versión 2 de dicha Licencia o bien (según su + elección) de cualquier versión posterior. +

+

+ Este programa se distribuye con la esperanza de que sea útil, + pero SIN NINGUNA GARANT�A, incluso sin la garantía MERCANTIL + implícita o sin garantizar la CONVENIENCIA PARA UN PROP�SITO + PARTICULAR. Véase la Licencia Pública General de GNU para + más detalles. +

+

+ Debería haber recibido una copia de la Licencia Pública + General junto con este programa. Si no ha sido así, escriba a la + Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, + EEUU. +

+
+

+ Añada también información sobre cómo contactar + con usted mediante correo electrónico y postal. +

+

+ Si el programa es interactivo, haga que muestre un pequeño anuncio + como el siguiente, cuando comienza a funcionar en modo interactivo: +

+
+ Gnomovision versión 69, Copyright (C) 19aa nombre del autor +

+ Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para + más detalles escriba �show w�. +

+
+

+ Los comandos hipotéticos �show w� y �show c� deberían + mostrar las partes adecuadas de la Licencia Pública General. Por + supuesto, los comandos que use pueden llamarse de cualquier otra manera. + Podrían incluso ser pulsaciones del ratón o elementos de un + menú (lo que sea apropiado para su programa). +

+

+ También deberías conseguir que su empleador (si trabaja como + programador) o tu Universidad (si es el caso) firme un �renuncia de + copyright� para el programa, si es necesario. A continuación se + ofrece un ejemplo, altere los nombres según sea conveniente: +

+
    +
  1. + Yoyodyne, Inc. mediante este documento renuncia a cualquier + interés de derechos de copyright con respecto al programa + Gnomovision (que hace pasadas a compiladores) escrito por Pepe + Programador. +

    <firma de Pepito Grillo>, 20 de diciembre de 1996

    +

    Pepito Grillo, Presidente de Asuntillos Varios.

    +
  2. +
+

+ Esta Licencia Pública General no permite que incluya sus programas + en programas propietarios. Si su programa es una biblioteca de subrutinas, + puede considerar más útil el permitir el enlazado de + aplicaciones propietarias con la biblioteca. Si este es el caso, use la + Licencia Pública General de GNU para Bibliotecas en lugar de esta + Licencia. +

+ + diff --git a/pandora_console/general/license/pandora_info_fr.html b/pandora_console/general/license/pandora_info_fr.html index c0e83632b5..28ab89e3b2 100644 --- a/pandora_console/general/license/pandora_info_fr.html +++ b/pandora_console/general/license/pandora_info_fr.html @@ -1,437 +1,553 @@ - - Licence Publique Générale GNU - - -

Licence Publique Générale GNU

+ + Licence Publique Générale GNU + + +

Licence Publique Générale GNU

-

Benjamin Drieu, APRIL (bdrieu@april.org), Mélanie -Clément-Fontaine (melanie@amberlab.net), -Arnaud Fontaine (arnaud@crao.net), Lo�c Dachary -(loic@gnu.org), Frédéric Couchet (fcouchet@fsffrance.org). -

-

Advertiment

-

-This is an unofficial translation of the GNU General Public -License into French. It was not published by the Free Software -Foundation, and does not legally state the distribution terms -for software that uses the GNU GPL--only the original English -text of the GNU GPL does that. However, we hope that this -translation will help French speakers understand the GNU GPL -better. -

+

+ Benjamin Drieu, APRIL (bdrieu@april.org), Mélanie Clément-Fontaine (melanie@amberlab.net), Arnaud Fontaine (arnaud@crao.net), Lo�c Dachary (loic@gnu.org), + Frédéric Couchet (fcouchet@fsffrance.org). + +

+

Advertiment

+

+ This is an unofficial translation of the GNU General Public License into + French. It was not published by the Free Software Foundation, and does not + legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help French speakers understand the GNU + GPL better. +

-

-Ceci est une traduction non officielle de la GNU General Public -License en fran�ais. Elle n'a pas été publiée par la Free -Software Foundation, et ne détermine pas les termes de -distribution pour les logiciels qui utilisent la GNU GPL, seul -le texte anglais original de la GNU GPL déterminent ces -termes. Cependant, nous espérons que cette traduction aidera les -francophones à mieux comprendre la GNU GPL. -

+

+ Ceci est une traduction non officielle de la GNU General Public License en + fran�ais. Elle n'a pas été publiée par la Free + Software Foundation, et ne détermine pas les termes de distribution + pour les logiciels qui utilisent la GNU GPL, seul le texte anglais + original de la GNU GPL déterminent ces termes. Cependant, nous + espérons que cette traduction aidera les francophones à + mieux comprendre la GNU GPL. +

-

Licence Publique Générale GNU

-

Les licences de la plupart des logiciels sont -con�ues pour vous enlever toute liberté de les partager et de les -modifier.

-

A contrario, la Licence Publique Générale est destinée à garantir -votre liberté de partager et de modifier les logiciels libres, -et à assurer que ces logiciels soient libres pour tous leurs -utilisateurs.

-

La présente Licence Publique Générale s'applique à la -plupart des logiciels de la Free Software Foundation, ainsi -qu'à tout autre programme pour lequel ses auteurs s'engagent à -l'utiliser.

-

(Certains autres logiciels de la Free Software Foundation -sont couverts par la GNU Lesser General Public License à la place.)

-

Vous pouvez aussi l'appliquer aux programmes qui sont les v�tres.

-

Quand nous parlons de logiciels libres, nous parlons de -liberté, non de prix.

-

Nos licences publiques générales sont con�ues pour vous donner -l'assurance d'�tre libres de distribuer des copies des -logiciels libres (et de facturer ce service, si vous le -souhaitez), de recevoir le code source ou de pouvoir -l'obtenir si vous le souhaitez, de pouvoir modifier les -logiciels ou en utiliser des éléments dans de nouveaux -programmes libres et de savoir que vous pouvez le -faire.

-

Pour protéger vos droits, il nous est nécessaire d'imposer -des limitations qui interdisent à quiconque de vous refuser -ces droits ou de vous demander d'y renoncer.

-

Certaines responsabilités vous incombent en raison de ces -limitations si vous distribuez des copies de ces logiciels, ou -si vous les modifiez.

-

Par exemple, si vous distribuez des copies d'un tel -programme, à titre gratuit ou contre une rémunération, vous devez -accorder aux destinataires tous les droits dont vous disposez. -

-

Vous devez vous assurer qu'eux aussi re�oivent ou puissent -disposer du code source.

-

Et vous devez leur montrer les présentes conditions afin -qu'ils aient connaissance de leurs droits.

-

Nous protégeons vos droits en deux étapes : (1) nous sommes -titulaires des droits d'auteur du logiciel, et -(2) nous vous delivrons cette licence, qui vous donne -l'autorisation légale de copier, distribuer et/ou modifier -le logiciel.

-

En outre, pour la protection de chaque auteur ainsi que la n�tre, -nous voulons nous assurer que chacun comprenne que ce logiciel libre ne fait l'objet -d'aucune garantie.

-

Si le logiciel est modifié par quelqu'un d'autre puis -transmis à des tiers, nous voulons que les destinataires -soient mis au courant que ce qu'ils ont re�u n'est pas le logiciel d'origine, de sorte -que tout problème introduit par d'autres ne puisse entacher -la réputation de -l'auteur originel.

-

En définitive, un programme libre restera à la merci des -brevets de logiciels.

-

Nous souhaitons éviter le risque que les redistributeurs -d'un programme libre fassent des demandes individuelles de -licence de brevet, ceci ayant pour effet de rendre le programme -propriétaire. -

-

Pour éviter cela, nous établissons clairement que toute licence de brevet -doit �tre concédée de fa�on a ce que l'usage en soit libre pour tous -ou bien qu'aucune licence ne soit concédée.

-

Les termes exacts et les conditions de copie, distribution et -modification sont les suivants:

-

Conditions de copie, distribution -et modification de la Licence Publique Générale GNU.

-

0. La présente Licence s'applique à tout programme -ou tout autre ouvrage contenant un avis, apposé par le titulaire des -droits d'auteur, stipulant qu'il peut �tre distribué au titre -des conditions de la présente Licence Publique -Générale.

-

Ci-après, le "Programme" désigne l'un quelconque de ces -programmes ou ouvrages, et un "ouvrage fondé sur le Programme" -désigne soit le Programme, soit un ouvrage qui en dérive au -titre des lois sur le droit d'auteur: en d'autres termes, -un ouvrage contenant le Programme ou une partie de -ce dernier, soit à l'identique, soit avec des modifications et/ou -traduit dans un autre langage.

-

(Ci-après, le terme "modification" implique, sans s'y réduire, le terme traduction)

-

Chaque concessionaire sera désigné par "vous".

-

Les activités autres que la copie, la distribution et -la modification ne sont pas couvertes par la présente Licence -; elles sont hors de son champ d'application.

-

L'opération consistant à exécuter le Programme n'est soumise à aucune limitation -et les sorties du programme ne sont couvertes que si leur -contenu constitue un ouvrage fondé sur le Programme -(indépendamment du fait qu'il ait été réalisé par l'exécution -du Programme).

-

La validité de ce qui précède dépend de ce que fait le -Programme.

-

1. Vous pouvez copier et distribuer des copies à -l'identique du code source du Programme tel que vous l'avez -re�u, sur n'importe quel support, du moment que vous apposiez -sur chaque copie, de manière ad hoc et parfaitement -visible, l'avis de droit d'auteur adéquat et -une exonération de garantie ; que vous gardiez intacts tous les -avis faisant référence à la présente Licence et à l'absence de -toute garantie ; et que vous fournissiez à tout destinataire du -Programme autre que vous m�me un exemplaire de la présente -Licence en m�me temps que le Programme.

-

Vous pouvez faire payer l'acte physique de -transmission d'une copie, et vous pouvez, à votre discrétion, -proposer une garantie contre rémunération.

-

2. Vous pouvez modifier votre copie ou des copies du Programme -ou n'importe quelle partie de celui-ci, créant ainsi un ouvrage -fondé sur le Programme, et copier et distribuer de telles modifications ou ouvrage selon les -termes de l'Article 1 ci-dessus, à condition de vous conformer également -à chacune des obligations suivantes:

-

a) Vous devez munir les fichiers modifiés d'avis bien visibles -stipulants que vous avez modifié ces -fichiers, ainsi que la date de chaque modification;

-

b) Vous devez prendre les dispositions nécessaires pour que -tout ouvrage -que vous distribuez ou publiez, et qui, en totalité ou en partie, -contient ou est fondé sur le Programme - ou une partie -quelconque de ce dernier - soit concédé comme un tout, -à titre gratuit, à n'importe quel tiers, au titre des conditions -de la présente Licence.

-

c) Si le programme modifié lit habituellement des instructions -de fa�on interactive lorsqu'on l'exécute, vous devez, -quand il commence son exécution pour ladite -utilisation interactive de la manière la plus usuelle, faire -en sorte qu'il imprime ou affiche une annonce -comprenant un avis de droit d'auteur ad hoc, et un avis -stipulant qu'il n'y a pas de garantie (ou bien indiquant que -c'est vous qui fournissez la garantie), et que -les utilisateurs peuvent redistribuer le programme en respectant -les présentes obligations, et expliquant à l'utilisateur comment -voir une copie de la présente Licence.

-

(Exception : si le Programme est lui-m�me interactif -mais n'imprime pas habituellement une telle annonce, votre -ouvrage fondé sur le Programme n'est pas obligé -d'imprimer une annonce).

-

Ces obligations s'appliquent à l'ouvrage modifié -pris comme un tout. -

-

Si des éléments identifiables -de cet ouvrage ne sont pas fondées sur le Programme et peuvent -raisonnablement �tre considérées comme des ouvrages indépendants -distincts en eux m�mes, alors la présente Licence et -ses conditions ne -s'appliquent pas à ces éléments lorsque vous les distribuez -en tant qu'ouvrages distincts.

-

-Mais lorsque vous distribuez ces m�mes éléments comme partie -d'un tout, lequel constitue un ouvrage fondé sur le Programme, -la distribution de ce tout doit �tre soumise aux conditions de -la présente Licence, et les autorisations qu'elle octroie aux -autres concessionaires s'étendent à l'ensemble de l'ouvrage et -par conséquent à chaque et toute partie indifférement de qui -l'a écrite. -

-

Par conséquent, l'objet du présent article n'est pas de revendiquer des droits -ou de contester vos droits sur un ouvrage entièrement écrit par -vous; son objet est plut�t d'exercer le droit de contr�ler -la distribution d'ouvrages dérivés ou d'ouvrages collectifs fondés -sur le Programme. -

-

-De plus, la simple proximité du Programme avec un autre -ouvrage qui n'est pas fondé sur le Programme (ou un ouvrage -fondé sur le Programme) sur une partition d'un espace de -stockage ou un support de distribution ne place pas cet autre -ouvrage dans le champ d'application de la présente Licence. -

-

3. Vous pouvez copier et distribuer le Programme (ou un -ouvrage fondé sur lui, selon l'Article 2) sous forme de code -objet ou d'exécutable, selon les termes des Articles 1 et 2 -ci-dessus, à condition que vous accomplissiez l'un des points -suivants :

-

a) L'accompagner de l'intégralité du code source correspondant, -sous une forme lisible par un ordinateur, lequel doit �tre distribué -au titre -des termes des Articles 1 et 2 ci-dessus, sur un support -habituellement utilisé pour l'échange de logiciels; ou,

-

b) L'accompagner d'une proposition écrite, valable pendant -au moins trois ans, de fournir à tout tiers, à un tarif qui -ne soit pas supérieur à ce que vous co�te l'acte physique de -réaliser une distribution source, une copie intégrale du code -source correspondant sous une forme lisible par un -ordinateur, qui sera distribuée au titre des termes des -Articles 1 et 2 ci-dessus, sur un support habituellement -utilisé pour l'échange de logiciels; ou, -

-

c) L'accompagner des informations re�ues par vous concernant la proposition de distribution du code source correspondant. (Cette -solution n'est autorisée que dans le cas d'une distribution non-commerciale -et seulement si vous avez re�u le programme sous forme de code objet ou -d'éxécutable accompagné d'une telle proposition - en conformité avec le -sous-Article b ci-dessus.) -

-

Le code source d'un ouvrage désigne la forme favorite pour -travailler à des modifications de cet ouvrage. Pour un -ouvrage exécutable, le code source intégral désigne la -totalité du code source de la totalité des modules qu'il -contient, ainsi que les éventuels fichiers de définition des -interfaces qui y sont associés, ainsi que les scripts utilisés -pour contr�ler la compilation et l'installation de -l'exécutable. Cependant, par exception spéciale, le code -source distribué n'est pas censé inclure quoi que ce soit de -normalement distribué (que ce soit sous forme source ou -binaire) avec les composants principaux (compilateur, noyau, -et autre) du système d'exploitation sur lequel l'exécutable -tourne, à moins que ce composant lui-m�me n'accompagne -l'exécutable. -

-

-Si distribuer un exécutable ou un code objet consiste à -offrir un accès permettant leur copie depuis un -endroit particulier, alors l'offre d'un accès équivalent pour -copier le code source depuis le m�me endroit compte comme une -distribution du code source - m�me si les tiers ne sont pas -contraints de copier le source en m�me temps que le code -objet. -

-

4. Vous ne pouvez copier, modifier, concéder en sous-licence, ou distribuer -le Programme, sauf tel qu'expressément prévu par la présente Licence. -Toute tentative de copier, modifier, concéder en sous-licence, ou -distribuer le Programme d'une autre manière est réputée non valable, et met -immédiatement fin à vos droits au titre de la présente Licence. -Toutefois, les tiers ayant re�u de vous des copies, ou des droits, -au titre de la présente Licence ne verront pas leurs autorisations résiliées -aussi longtemps que ledits tiers se conforment pleinement à elle. -

-

5. Vous n'�tes pas obligé d'accepter la présente Licence étant donné que vous ne -l'avez pas signée. Cependant, rien d'autre -ne vous accorde l'autorisation de modifier ou -distribuer le Programme ou les ouvrages fondés sur lui. Ces actions sont -interdites par la loi si vous n'acceptez pas la présente Licence. -En conséquence, en modifiant ou -distribuant le Programme (ou un ouvrage quelconque fondé sur -le Programme), vous signifiez votre acceptation de la présente Licence en le faisant, -et de toutes ses conditions concernant la copie, la -distribution ou la modification du Programme ou d'ouvrages fondés -sur lui.

-

-6. Chaque fois que vous redistribuez le Programme (ou n'importe quel -ouvrage fondé sur le Programme), une licence est automatiquement -concédée au destinataire par le concédant originel de la licence, -l'autorisant à -copier, distribuer ou modifier le Programme, sous réserve -des présentes conditions. Vous ne pouvez imposer -une quelconque limitation supplémentaire à l'exercice des -droits octroyés au titre des présentes par le destinataire. Vous -n'avez pas la responsabilité d'imposer le respect de -la présente Licence à des tiers.

-

-7. Si, conséquement à une décision de justice ou l'allégation -d'une transgression de brevet ou pour toute autre raison (non limitée à un -probleme de brevet), des obligations vous sont imposées (que ce soit par jugement, -conciliation ou autre) qui contredisent les conditions de la présente Licence, elles -ne vous excusent pas des conditions de la présente Licence. Si vous ne pouvez -distribuer de manière à satisfaire simultanément vos obligations au titre -de la présente Licence et toute autre obligation pertinente, alors il en découle que vous ne pouvez pas du tout distribuer le Programme. Par exemple, -si une licence de brevet ne permettait pas une redistribution sans redevance du -Programme par tous ceux qui re�oivent une copie directement ou indirectement -par votre intermédiaire, alors la seule fa�on pour vous de satisfaire à la -fois à la licence du brevet et à la présente Licence serait de vous abstenir -totalement de toute distribution du Programme. -

-

Si une partie quelconque de cet article est tenue pour -nulle ou inopposable dans une circonstance particulière -quelconque, l'intention est que le reste de l'article -s'applique. La totalité de la section s'appliquera dans toutes les -autres circonstances.

-

Cet article n'a pas pour but de vous induire à transgresser un -quelconque brevet ou d'autres revendications à un droit de propriété ou -à contester la validité de la moindre de ces revendications ; cet article a pour -seul objectif de protéger l'intégrité du système de distribution -du logiciel libre, qui est mis en oeuvre par la pratique des licenses -publiques. De nombreuses personnes ont fait de généreuses contributions -au large spectre de logiciels distribués par ce système en se fiant à -l'application cohérente de ce système ; il appartient à chaque auteur/donateur -de décider si il ou elle veut distribuer du logiciel par l'intermédiaire -d'un quelconque autre système et un concessionaire ne peut imposer ce -choix. -

-

Cet article a pour but de rendre totalement limpide ce que l'on pense -�tre une conséquence du reste de la présente Licence.

-

8. Si la distribution et/ou l'utilisation du Programme est limitée -dans certains pays que ce soit par des brevets ou par des interfaces soumises -au droit d'auteur, le titulaire originel des droits d'auteur -qui décide de couvrir le Programme par la présente Licence peut ajouter -une limitation géographique de distribution explicite qui exclue ces pays afin -que la distribution soit permise seulement dans ou entre les pays qui ne sont -pas ainsi exclus. Dans ce cas, la présente Licence incorpore la limitation -comme si elle était écrite dans le corps de la présente Licence. -

-

9. La Free Software Foundation peut, de temps à autre, publier des -versions révisées et/ou nouvelles de la Licence Publique Générale. De telles -nouvelles versions seront similaires à la présente version dans l'esprit -mais pourront différer dans le détail pour prendre en compte -de nouvelles problématiques ou inquiétudes. -

-

Chaque version possède un numéro de version la distinguant. Si le Programme -précise le numéro de version de la présente Licence qui s'y applique -et "une version ultérieure quelconque", vous avez le choix -de suivre les -conditions de -la présente version ou de toute autre version ultérieure publiée par la -Free Software Foundation. Si le Programme ne spécifie aucun numéro de -version de la présente Licence, vous pouvez choisir une version quelconque -publiée par la Free Software Foundation à quelque moment que ce soit.

-

10. Si vous souhaitez incorporer des parties du Programme -dans d'autres programmes libres dont les conditions de -distribution sont différentes, écrivez à l'auteur pour lui en demander -l'autorisation. Pour les logiciels dont la Free Software Foundation est -titulaire des droits d'auteur, écrivez à la Free Software Foundation ; -nous faisons parfois des exceptions dans ce sens. Notre décision sera guidée -par le double objectif de préserver le statut libre de tous les dérivés de nos -logiciels libres et de promouvoir le partage et la réutilisation des logiciels -en général. -

-

ABSENCE DE GARANTIE

-

11. COMME LA LICENCE DU PROGRAMME EST CONCEDEE A TITRE GRATUIT, -AUCUNE GARANTIE NE S'APPLIQUE AU PROGRAMME, DANS LES LIMITES -AUTORISEES PAR LA LOI APPLICABLE. SAUF MENTION CONTRAIRE ECRITE, -LES TITULAIRES DU DROIT D'AUTEUR ET/OU LES AUTRES PARTIES FOURNISSENT -LE PROGRAMME "EN L'ETAT", SANS AUCUNE GARANTIE DE -QUELQUE NATURE QUE CE SOIT, EXPRESSE OU IMPLICITE, Y COMPRIS, MAIS -SANS Y ETRE LIMITE, LES GARANTIES IMPLICITES DE COMMERCIABILITE ET -DE LA CONFORMITE A UNE UTILISATION PARTICULIERE. VOUS -ASSUMEZ LA TOTALITE DES RISQUES LIES A LA QUALITE ET AUX PERFORMANCES DU PROGRAMME. -SI LE PROGRAMME SE REVELAIT DEFECTUEUX, LE COUT DE L'ENTRETIEN, -DES REPARATIONS OU DES CORRECTIONS NECESSAIRES -VOUS INCOMBENT INTEGRALEMENT.

-

12. EN AUCUN CAS, SAUF LORSQUE LA LOI APPLICABLE OU UNE CONVENTION ECRITE L'EXIGE, UN TITULAIRE DE DROIT D'AUTEUR QUEL QU'IL SOIT, OU TOUTE PARTIE QUI POURRAIT MODIFIER ET/OU REDISTRIBUER LE PROGRAMME COMME PERMIS CI-DESSUS, NE POURRAIT ETRE TENU POUR RESPONSABLE A VOTRE EGARD DES DOMMAGES, INCLUANT LES DOMMAGES GENERIQUES, SPECIFIQUES, SECONDAIRES OU CONSECUTIFS, RESULTANT DE L'UTILISATION OU DE L'INCAPACITE D'UTILISER LE PROGRAMME (Y COMPRIS, MAIS SANS Y ETRE LIMITE, LA PERTE DE DONNEES, OU LE FAIT QUE DES DONNEES SOIENT RENDUES IMPRECISES, OU LES PERTES EPROUVEES PAR VOUS OU PAR DES TIERS, OU LE FAIT QUE LE PROGRAMME ECHOUE A INTEROPERER AVEC UN AUTRE PROGRAMME QUEL QU'IL SOIT) MEME SI LE DIT TITULAIRE DU DROIT D'AUTEUR OU LE PARTIE CONCERNEE A ETE AVERTI DE L'EVENTUALITE DE TELS DOMMAGES. -

-

FIN DES CONDITIONS

-

Comment appliquer ces conditions à vos nouveaux programmes

-

Si vous développez un nouveau programme, et si vous voulez qu'il soit de la plus grande utilité possible pour le public, le meilleur moyen d'y parvenir est d'en faire un logiciel libre que chacun peut redistribuer et modifier au titre des présentes conditions.

-

Pour ce faire, munissez le programme des avis qui suivent. -Le plus s�r est de les ajouter au début de chaque fichier source -pour véhiculer le plus efficacement possible l'absence -de toute garantie; chaque fichier devrait aussi contenir au moins -la ligne "copyright" et une indication de l'endroit où se trouve l'avis -compl�t. -

-

[Une ligne donnant le nom du programme et une courte idée de ce qu'il fait.] -

-

-Copyright (C) [année] [nom de l'auteur] -

-

-Ce programme est un logiciel libre ; vous pouvez le -redistribuer et/ou le modifier au titre des clauses de la -Licence Publique Générale GNU, telle que publiée par la Free -Software Foundation ; soit la version 2 de la Licence, ou (à -votre discrétion) une version ultérieure quelconque. -

-

-Ce programme est distribué dans l'espoir qu'il sera utile, -mais SANS AUCUNE GARANTIE ; sans m�me une garantie implicite de -COMMERCIABILITE ou DE CONFORMITE A UNE UTILISATION -PARTICULIERE. Voir la Licence Publique -Générale GNU pour plus de détails. -

-

-Vous devriez avoir re�u un exemplaire de la Licence Publique -Générale GNU avec ce programme ; si ce n'est pas le cas, -écrivez à la Free Software Foundation Inc., 51 Franklin -Street, Fifth Floor, Boston, MA 02110-1301, USA.

-

Ajoutez aussi des informations sur la manière de vous contacter -par courrier électronique et courrier postal.

-

Si le programme est interactif, faites en sorte qu'il -affiche un court avis tel que celui-ci lorsqu'il démarre en -mode interactif : -

-

Gnomovision version 69, Copyright (C) année nom de l'auteur -Gnomovision n'est accompagné d'ABSOLUMENT AUCUNE GARANTIE ; pour plus de -détails tapez "show w". Ceci est un logiciel libre et vous �tes -invité à le redistribuer en respectant certaines obligations ; pour plus -de détails tapez "show c".

-

Les instructions hypothétiques "show w" et "show c" sont supposées montrer -les parties ad hoc de la Licence Publique Générale. Bien -entendu, les instructions que vous utilisez peuvent porter d'autres -noms que "show w" et "show c" ; elles peuvent m�me �tre des -clics de souris ou des éléments d'un menu ou tout ce qui convient à -votre programme.

-

Vous devriez aussi obtenir de votre employeur (si vous -travaillez en tant que développeur) ou de votre école, si c'est -le cas, qu'il (ou elle) signe une "renonciation aux droits -d'auteur" concernant le programme, si nécessaire. Voici un -exemple (changez les noms) : -

-

Yoyodyne, Inc., déclare par la présente renoncer à toute prétention -sur les droits d'auteur du programme "Gnomovision" (qui fait des -avances aux compilateurs) écrit par James Hacker. -

-

-[signature de Ty Coon], 1er avril 1989 -

-

-Ty Coon, President du Vice

-

La présente Licence Publique Générale n'autorise pas l'incorporation de votre -programme dans des programmes -propriétaires. Si votre programme est une bibliothèque de -sous-programmes, vous pouvez considérer plus utile -d'autoriser l'édition de liens d'applications propriétaires avec -la bibliothèque. Si c'est ce que vous voulez faire, utilisez la -GNU Lesser General Public License au lieu de la présente Licence. -

- - \ No newline at end of file +

Licence Publique Générale GNU

+

+ Les licences de la plupart des logiciels sont con�ues pour vous enlever + toute liberté de les partager et de les modifier. +

+

+ A contrario, la Licence Publique Générale est + destinée à garantir votre liberté de partager et de + modifier les logiciels libres, et à assurer que ces logiciels + soient libres pour tous leurs utilisateurs. +

+

+ La présente Licence Publique Générale s'applique + à la plupart des logiciels de la Free Software Foundation, ainsi + qu'à tout autre programme pour lequel ses auteurs s'engagent + à l'utiliser. +

+

+ (Certains autres logiciels de la Free Software Foundation sont couverts + par la GNU Lesser General Public License à la place.) +

+

Vous pouvez aussi l'appliquer aux programmes qui sont les v�tres.

+

+ Quand nous parlons de logiciels libres, nous parlons de liberté, + non de prix. +

+

+ Nos licences publiques générales sont con�ues pour vous + donner l'assurance d'�tre libres de distribuer des copies des logiciels + libres (et de facturer ce service, si vous le souhaitez), de recevoir le + code source ou de pouvoir l'obtenir si vous le souhaitez, de pouvoir + modifier les logiciels ou en utiliser des éléments dans de + nouveaux programmes libres et de savoir que vous pouvez le faire. +

+

+ Pour protéger vos droits, il nous est nécessaire d'imposer + des limitations qui interdisent à quiconque de vous refuser ces + droits ou de vous demander d'y renoncer. +

+

+ Certaines responsabilités vous incombent en raison de ces + limitations si vous distribuez des copies de ces logiciels, ou si vous les + modifiez. +

+

+ Par exemple, si vous distribuez des copies d'un tel programme, à + titre gratuit ou contre une rémunération, vous devez + accorder aux destinataires tous les droits dont vous disposez. +

+

+ Vous devez vous assurer qu'eux aussi re�oivent ou puissent disposer du + code source. +

+

+ Et vous devez leur montrer les présentes conditions afin qu'ils + aient connaissance de leurs droits. +

+

+ Nous protégeons vos droits en deux étapes : (1) nous sommes + titulaires des droits d'auteur du logiciel, et (2) nous vous delivrons + cette licence, qui vous donne l'autorisation légale de copier, + distribuer et/ou modifier le logiciel. +

+

+ En outre, pour la protection de chaque auteur ainsi que la n�tre, nous + voulons nous assurer que chacun comprenne que ce logiciel libre ne fait + l'objet d'aucune garantie. +

+

+ Si le logiciel est modifié par quelqu'un d'autre puis transmis + à des tiers, nous voulons que les destinataires soient mis au + courant que ce qu'ils ont re�u n'est pas le logiciel d'origine, de sorte + que tout problème introduit par d'autres ne puisse entacher la + réputation de l'auteur originel. +

+

+ En définitive, un programme libre restera à la merci des + brevets de logiciels. +

+

+ Nous souhaitons éviter le risque que les redistributeurs d'un + programme libre fassent des demandes individuelles de licence de brevet, + ceci ayant pour effet de rendre le programme propriétaire. +

+

+ Pour éviter cela, nous établissons clairement que toute + licence de brevet doit �tre concédée de fa�on a ce que + l'usage en soit libre pour tous ou bien qu'aucune licence ne soit + concédée. +

+

+ Les termes exacts et les conditions de copie, distribution et modification + sont les suivants: +

+

+ Conditions de copie, distribution et modification de la Licence Publique + Générale GNU. +

+

+ 0. La présente Licence s'applique à tout programme ou tout + autre ouvrage contenant un avis, apposé par le titulaire des droits + d'auteur, stipulant qu'il peut �tre distribué au titre des + conditions de la présente Licence Publique Générale. +

+

+ Ci-après, le "Programme" désigne l'un quelconque de ces + programmes ou ouvrages, et un "ouvrage fondé sur le Programme" + désigne soit le Programme, soit un ouvrage qui en dérive au + titre des lois sur le droit d'auteur: en d'autres termes, un ouvrage + contenant le Programme ou une partie de ce dernier, soit à + l'identique, soit avec des modifications et/ou traduit dans un autre + langage. +

+

+ (Ci-après, le terme "modification" implique, sans s'y + réduire, le terme traduction) +

+

Chaque concessionaire sera désigné par "vous".

+

+ Les activités autres que la copie, la distribution et la + modification ne sont pas couvertes par la présente Licence ; elles + sont hors de son champ d'application. +

+

+ L'opération consistant à exécuter le Programme n'est + soumise à aucune limitation et les sorties du programme ne sont + couvertes que si leur contenu constitue un ouvrage fondé sur le + Programme (indépendamment du fait qu'il ait été + réalisé par l'exécution du Programme). +

+

+ La validité de ce qui précède dépend de ce que + fait le Programme. +

+

+ 1. Vous pouvez copier et distribuer des copies à l'identique du + code source du Programme tel que vous l'avez re�u, sur n'importe quel + support, du moment que vous apposiez sur chaque copie, de manière + ad hoc et parfaitement visible, l'avis de droit d'auteur adéquat et + une exonération de garantie ; que vous gardiez intacts tous les + avis faisant référence à la présente Licence + et à l'absence de toute garantie ; et que vous fournissiez à + tout destinataire du Programme autre que vous m�me un exemplaire de la + présente Licence en m�me temps que le Programme. +

+

+ Vous pouvez faire payer l'acte physique de transmission d'une copie, et + vous pouvez, à votre discrétion, proposer une garantie + contre rémunération. +

+

+ 2. Vous pouvez modifier votre copie ou des copies du Programme ou + n'importe quelle partie de celui-ci, créant ainsi un ouvrage + fondé sur le Programme, et copier et distribuer de telles + modifications ou ouvrage selon les termes de l'Article 1 ci-dessus, + à condition de vous conformer également à chacune des + obligations suivantes: +

+

+ a) Vous devez munir les fichiers modifiés d'avis bien visibles + stipulants que vous avez modifié ces fichiers, ainsi que la date de + chaque modification; +

+

+ b) Vous devez prendre les dispositions nécessaires pour que tout + ouvrage que vous distribuez ou publiez, et qui, en totalité ou en + partie, contient ou est fondé sur le Programme - ou une partie + quelconque de ce dernier - soit concédé comme un tout, + à titre gratuit, à n'importe quel tiers, au titre des + conditions de la présente Licence. +

+

+ c) Si le programme modifié lit habituellement des instructions de + fa�on interactive lorsqu'on l'exécute, vous devez, quand il + commence son exécution pour ladite utilisation interactive de la + manière la plus usuelle, faire en sorte qu'il imprime ou affiche + une annonce comprenant un avis de droit d'auteur ad hoc, et un avis + stipulant qu'il n'y a pas de garantie (ou bien indiquant que c'est vous + qui fournissez la garantie), et que les utilisateurs peuvent redistribuer + le programme en respectant les présentes obligations, et expliquant + à l'utilisateur comment voir une copie de la présente + Licence. +

+

+ (Exception : si le Programme est lui-m�me interactif mais n'imprime pas + habituellement une telle annonce, votre ouvrage fondé sur le + Programme n'est pas obligé d'imprimer une annonce). +

+

+ Ces obligations s'appliquent à l'ouvrage modifié pris comme + un tout. +

+

+ Si des éléments identifiables de cet ouvrage ne sont pas + fondées sur le Programme et peuvent raisonnablement �tre + considérées comme des ouvrages indépendants distincts + en eux m�mes, alors la présente Licence et ses conditions ne + s'appliquent pas à ces éléments lorsque vous les + distribuez en tant qu'ouvrages distincts. +

+

+ Mais lorsque vous distribuez ces m�mes éléments comme partie + d'un tout, lequel constitue un ouvrage fondé sur le Programme, la + distribution de ce tout doit �tre soumise aux conditions de la + présente Licence, et les autorisations qu'elle octroie aux autres + concessionaires s'étendent à l'ensemble de l'ouvrage et par + conséquent à chaque et toute partie indifférement de + qui l'a écrite. +

+

+ Par conséquent, l'objet du présent article n'est pas de + revendiquer des droits ou de contester vos droits sur un ouvrage + entièrement écrit par vous; son objet est plut�t d'exercer + le droit de contr�ler la distribution d'ouvrages dérivés ou + d'ouvrages collectifs fondés sur le Programme. +

+

+ De plus, la simple proximité du Programme avec un autre ouvrage qui + n'est pas fondé sur le Programme (ou un ouvrage fondé sur le + Programme) sur une partition d'un espace de stockage ou un support de + distribution ne place pas cet autre ouvrage dans le champ d'application de + la présente Licence. +

+

+ 3. Vous pouvez copier et distribuer le Programme (ou un ouvrage + fondé sur lui, selon l'Article 2) sous forme de code objet ou + d'exécutable, selon les termes des Articles 1 et 2 ci-dessus, + à condition que vous accomplissiez l'un des points suivants : +

+

+ a) L'accompagner de l'intégralité du code source + correspondant, sous une forme lisible par un ordinateur, lequel doit �tre + distribué au titre des termes des Articles 1 et 2 ci-dessus, sur un + support habituellement utilisé pour l'échange de logiciels; + ou, +

+

+ b) L'accompagner d'une proposition écrite, valable pendant au moins + trois ans, de fournir à tout tiers, à un tarif qui ne soit + pas supérieur à ce que vous co�te l'acte physique de + réaliser une distribution source, une copie intégrale du + code source correspondant sous une forme lisible par un ordinateur, qui + sera distribuée au titre des termes des Articles 1 et 2 ci-dessus, + sur un support habituellement utilisé pour l'échange de + logiciels; ou, +

+

+ c) L'accompagner des informations re�ues par vous concernant la + proposition de distribution du code source correspondant. (Cette solution + n'est autorisée que dans le cas d'une distribution non-commerciale + et seulement si vous avez re�u le programme sous forme de code objet ou + d'éxécutable accompagné d'une telle proposition - en + conformité avec le sous-Article b ci-dessus.) +

+

+ Le code source d'un ouvrage désigne la forme favorite pour + travailler à des modifications de cet ouvrage. Pour un ouvrage + exécutable, le code source intégral désigne la + totalité du code source de la totalité des modules qu'il + contient, ainsi que les éventuels fichiers de définition des + interfaces qui y sont associés, ainsi que les scripts + utilisés pour contr�ler la compilation et l'installation de + l'exécutable. Cependant, par exception spéciale, le code + source distribué n'est pas censé inclure quoi que ce soit de + normalement distribué (que ce soit sous forme source ou binaire) + avec les composants principaux (compilateur, noyau, et autre) du + système d'exploitation sur lequel l'exécutable tourne, + à moins que ce composant lui-m�me n'accompagne l'exécutable. +

+

+ Si distribuer un exécutable ou un code objet consiste à + offrir un accès permettant leur copie depuis un endroit + particulier, alors l'offre d'un accès équivalent pour copier + le code source depuis le m�me endroit compte comme une distribution du + code source - m�me si les tiers ne sont pas contraints de copier le source + en m�me temps que le code objet. +

+

+ 4. Vous ne pouvez copier, modifier, concéder en sous-licence, ou + distribuer le Programme, sauf tel qu'expressément prévu par + la présente Licence. Toute tentative de copier, modifier, + concéder en sous-licence, ou distribuer le Programme d'une autre + manière est réputée non valable, et met + immédiatement fin à vos droits au titre de la + présente Licence. Toutefois, les tiers ayant re�u de vous des + copies, ou des droits, au titre de la présente Licence ne verront + pas leurs autorisations résiliées aussi longtemps que ledits + tiers se conforment pleinement à elle. +

+

+ 5. Vous n'�tes pas obligé d'accepter la présente Licence + étant donné que vous ne l'avez pas signée. Cependant, + rien d'autre ne vous accorde l'autorisation de modifier ou distribuer le + Programme ou les ouvrages fondés sur lui. Ces actions sont + interdites par la loi si vous n'acceptez pas la présente Licence. + En conséquence, en modifiant ou distribuant le Programme (ou un + ouvrage quelconque fondé sur le Programme), vous signifiez votre + acceptation de la présente Licence en le faisant, et de toutes ses + conditions concernant la copie, la distribution ou la modification du + Programme ou d'ouvrages fondés sur lui. +

+

+ 6. Chaque fois que vous redistribuez le Programme (ou n'importe quel + ouvrage fondé sur le Programme), une licence est automatiquement + concédée au destinataire par le concédant originel de + la licence, l'autorisant à copier, distribuer ou modifier le + Programme, sous réserve des présentes conditions. Vous ne + pouvez imposer une quelconque limitation supplémentaire à + l'exercice des droits octroyés au titre des présentes par le + destinataire. Vous n'avez pas la responsabilité d'imposer le + respect de la présente Licence à des tiers. +

+

+ 7. Si, conséquement à une décision de justice ou + l'allégation d'une transgression de brevet ou pour toute autre + raison (non limitée à un probleme de brevet), des + obligations vous sont imposées (que ce soit par jugement, + conciliation ou autre) qui contredisent les conditions de la + présente Licence, elles ne vous excusent pas des conditions de la + présente Licence. Si vous ne pouvez distribuer de manière + à satisfaire simultanément vos obligations au titre de la + présente Licence et toute autre obligation pertinente, alors il en + découle que vous ne pouvez pas du tout distribuer le Programme. Par + exemple, si une licence de brevet ne permettait pas une redistribution + sans redevance du Programme par tous ceux qui re�oivent une copie + directement ou indirectement par votre intermédiaire, alors la + seule fa�on pour vous de satisfaire à la fois à la licence + du brevet et à la présente Licence serait de vous abstenir + totalement de toute distribution du Programme. +

+

+ Si une partie quelconque de cet article est tenue pour nulle ou + inopposable dans une circonstance particulière quelconque, + l'intention est que le reste de l'article s'applique. La totalité + de la section s'appliquera dans toutes les autres circonstances. +

+

+ Cet article n'a pas pour but de vous induire à transgresser un + quelconque brevet ou d'autres revendications à un droit de + propriété ou à contester la validité de la + moindre de ces revendications ; cet article a pour seul objectif de + protéger l'intégrité du système de + distribution du logiciel libre, qui est mis en oeuvre par la pratique des + licenses publiques. De nombreuses personnes ont fait de + généreuses contributions au large spectre de logiciels + distribués par ce système en se fiant à l'application + cohérente de ce système ; il appartient à chaque + auteur/donateur de décider si il ou elle veut distribuer du + logiciel par l'intermédiaire d'un quelconque autre système + et un concessionaire ne peut imposer ce choix. +

+

+ Cet article a pour but de rendre totalement limpide ce que l'on pense �tre + une conséquence du reste de la présente Licence. +

+

+ 8. Si la distribution et/ou l'utilisation du Programme est limitée + dans certains pays que ce soit par des brevets ou par des interfaces + soumises au droit d'auteur, le titulaire originel des droits d'auteur qui + décide de couvrir le Programme par la présente Licence peut + ajouter une limitation géographique de distribution explicite qui + exclue ces pays afin que la distribution soit permise seulement dans ou + entre les pays qui ne sont pas ainsi exclus. Dans ce cas, la + présente Licence incorpore la limitation comme si elle était + écrite dans le corps de la présente Licence. +

+

+ 9. La Free Software Foundation peut, de temps à autre, publier des + versions révisées et/ou nouvelles de la Licence Publique + Générale. De telles nouvelles versions seront similaires + à la présente version dans l'esprit mais pourront + différer dans le détail pour prendre en compte de nouvelles + problématiques ou inquiétudes. +

+

+ Chaque version possède un numéro de version la distinguant. + Si le Programme précise le numéro de version de la + présente Licence qui s'y applique et "une version ultérieure + quelconque", vous avez le choix de suivre les conditions de la + présente version ou de toute autre version ultérieure + publiée par la Free Software Foundation. Si le Programme ne + spécifie aucun numéro de version de la présente + Licence, vous pouvez choisir une version quelconque publiée par la + Free Software Foundation à quelque moment que ce soit. +

+

+ 10. Si vous souhaitez incorporer des parties du Programme dans d'autres + programmes libres dont les conditions de distribution sont + différentes, écrivez à l'auteur pour lui en demander + l'autorisation. Pour les logiciels dont la Free Software Foundation est + titulaire des droits d'auteur, écrivez à la Free Software + Foundation ; nous faisons parfois des exceptions dans ce sens. Notre + décision sera guidée par le double objectif de + préserver le statut libre de tous les dérivés de nos + logiciels libres et de promouvoir le partage et la réutilisation + des logiciels en général. +

+

ABSENCE DE GARANTIE

+

+ 11. COMME LA LICENCE DU PROGRAMME EST CONCEDEE A TITRE GRATUIT, AUCUNE + GARANTIE NE S'APPLIQUE AU PROGRAMME, DANS LES LIMITES AUTORISEES PAR LA + LOI APPLICABLE. SAUF MENTION CONTRAIRE ECRITE, LES TITULAIRES DU DROIT + D'AUTEUR ET/OU LES AUTRES PARTIES FOURNISSENT LE PROGRAMME "EN L'ETAT", + SANS AUCUNE GARANTIE DE QUELQUE NATURE QUE CE SOIT, EXPRESSE OU IMPLICITE, + Y COMPRIS, MAIS SANS Y ETRE LIMITE, LES GARANTIES IMPLICITES DE + COMMERCIABILITE ET DE LA CONFORMITE A UNE UTILISATION PARTICULIERE. VOUS + ASSUMEZ LA TOTALITE DES RISQUES LIES A LA QUALITE ET AUX PERFORMANCES DU + PROGRAMME. SI LE PROGRAMME SE REVELAIT DEFECTUEUX, LE COUT DE L'ENTRETIEN, + DES REPARATIONS OU DES CORRECTIONS NECESSAIRES VOUS INCOMBENT + INTEGRALEMENT. +

+

+ 12. EN AUCUN CAS, SAUF LORSQUE LA LOI APPLICABLE OU UNE CONVENTION ECRITE + L'EXIGE, UN TITULAIRE DE DROIT D'AUTEUR QUEL QU'IL SOIT, OU TOUTE PARTIE + QUI POURRAIT MODIFIER ET/OU REDISTRIBUER LE PROGRAMME COMME PERMIS + CI-DESSUS, NE POURRAIT ETRE TENU POUR RESPONSABLE A VOTRE EGARD DES + DOMMAGES, INCLUANT LES DOMMAGES GENERIQUES, SPECIFIQUES, SECONDAIRES OU + CONSECUTIFS, RESULTANT DE L'UTILISATION OU DE L'INCAPACITE D'UTILISER LE + PROGRAMME (Y COMPRIS, MAIS SANS Y ETRE LIMITE, LA PERTE DE DONNEES, OU LE + FAIT QUE DES DONNEES SOIENT RENDUES IMPRECISES, OU LES PERTES EPROUVEES + PAR VOUS OU PAR DES TIERS, OU LE FAIT QUE LE PROGRAMME ECHOUE A + INTEROPERER AVEC UN AUTRE PROGRAMME QUEL QU'IL SOIT) MEME SI LE DIT + TITULAIRE DU DROIT D'AUTEUR OU LE PARTIE CONCERNEE A ETE AVERTI DE + L'EVENTUALITE DE TELS DOMMAGES. +

+

FIN DES CONDITIONS

+

Comment appliquer ces conditions à vos nouveaux programmes

+

+ Si vous développez un nouveau programme, et si vous voulez qu'il + soit de la plus grande utilité possible pour le public, le meilleur + moyen d'y parvenir est d'en faire un logiciel libre que chacun peut + redistribuer et modifier au titre des présentes conditions. +

+

+ Pour ce faire, munissez le programme des avis qui suivent. Le plus s�r est + de les ajouter au début de chaque fichier source pour + véhiculer le plus efficacement possible l'absence de toute + garantie; chaque fichier devrait aussi contenir au moins la ligne + "copyright" et une indication de l'endroit où se trouve l'avis + compl�t. +

+

+ [Une ligne donnant le nom du programme et une courte idée de ce + qu'il fait.] +

+

Copyright (C) [année] [nom de l'auteur]

+

+ Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le + modifier au titre des clauses de la Licence Publique + Générale GNU, telle que publiée par la Free Software + Foundation ; soit la version 2 de la Licence, ou (à votre + discrétion) une version ultérieure quelconque. +

+

+ Ce programme est distribué dans l'espoir qu'il sera utile, mais + SANS AUCUNE GARANTIE ; sans m�me une garantie implicite de COMMERCIABILITE + ou DE CONFORMITE A UNE UTILISATION PARTICULIERE. Voir la Licence Publique + Générale GNU pour plus de détails. +

+

+ Vous devriez avoir re�u un exemplaire de la Licence Publique + Générale GNU avec ce programme ; si ce n'est pas le cas, + écrivez à la Free Software Foundation Inc., 51 Franklin + Street, Fifth Floor, Boston, MA 02110-1301, USA. +

+

+ Ajoutez aussi des informations sur la manière de vous contacter par + courrier électronique et courrier postal. +

+

+ Si le programme est interactif, faites en sorte qu'il affiche un court + avis tel que celui-ci lorsqu'il démarre en mode interactif : +

+

+ Gnomovision version 69, Copyright (C) année nom de l'auteur + Gnomovision n'est accompagné d'ABSOLUMENT AUCUNE GARANTIE ; pour + plus de détails tapez "show w". Ceci est un logiciel libre et vous + �tes invité à le redistribuer en respectant certaines + obligations ; pour plus de détails tapez "show c". +

+

+ Les instructions hypothétiques "show w" et "show c" sont + supposées montrer les parties ad hoc de la Licence Publique + Générale. Bien entendu, les instructions que vous utilisez + peuvent porter d'autres noms que "show w" et "show c" ; elles peuvent m�me + �tre des clics de souris ou des éléments d'un menu ou tout + ce qui convient à votre programme. +

+

+ Vous devriez aussi obtenir de votre employeur (si vous travaillez en tant + que développeur) ou de votre école, si c'est le cas, qu'il + (ou elle) signe une "renonciation aux droits d'auteur" concernant le + programme, si nécessaire. Voici un exemple (changez les noms) : +

+

+ Yoyodyne, Inc., déclare par la présente renoncer à + toute prétention sur les droits d'auteur du programme "Gnomovision" + (qui fait des avances aux compilateurs) écrit par James Hacker. +

+

[signature de Ty Coon], 1er avril 1989

+

Ty Coon, President du Vice

+

+ La présente Licence Publique Générale n'autorise pas + l'incorporation de votre programme dans des programmes + propriétaires. Si votre programme est une bibliothèque de + sous-programmes, vous pouvez considérer plus utile d'autoriser + l'édition de liens d'applications propriétaires avec la + bibliothèque. Si c'est ce que vous voulez faire, utilisez la GNU + Lesser General Public License au lieu de la présente Licence. +

+ + diff --git a/pandora_console/general/license/pandora_info_it.html b/pandora_console/general/license/pandora_info_it.html index a28c18e0ee..f96cf46faa 100644 --- a/pandora_console/general/license/pandora_info_it.html +++ b/pandora_console/general/license/pandora_info_it.html @@ -1,279 +1,304 @@ - -Licenze GNU - - + + Licenze GNU + + +

Licenze GNU

-

Licenze GNU

+

Sommario

+ -

Sommario

+
- +

Introduzione

-
+

+ Tutto il software pubblicato dovrebbe essere software libero. + Perché sia libero, bisogna pubblicarlo con una licenza per il + software libero. Normalmente utilizziamo la + Licenza Pubblica Generica GNU (GNU GPL), ma talvolta + utilizziamo anche + altre licenze per software libero. Per il + software GNU utilizziamo solo licenze compatibili con la GNU GPL. +

-

Introduzione

+

+ La documentazione per il software libero dovrebbe essere documentazione + libera, in modo che si possa distribuire e migliorare assieme al software + che essa descrive. Per rendere libera la documentazione occorre + rilasciarla con una licenza di documentazione libera. Normalmente + utilizziamo la + Licenza per Documentazione Libera GNU (GNU FDL), ma + talvolta utilizziamo anche + altre licenze per la documentazione libera. +

-

-Tutto il software pubblicato dovrebbe essere software libero. Perché sia -libero, bisogna pubblicarlo con una licenza per il software libero. -Normalmente utilizziamo la Licenza -Pubblica Generica GNU (GNU GPL), ma talvolta utilizziamo anche altre licenze per software -libero. Per il software GNU utilizziamo solo licenze compatibili -con la GNU GPL. -

+

La Licenza Pubblica Generica GNU

-

-La documentazione per il software libero dovrebbe -essere documentazione -libera, in modo che si possa distribuire e migliorare assieme al -software che essa descrive. Per rendere libera la documentazione -occorre rilasciarla con una licenza di documentazione -libera. Normalmente utilizziamo -la Licenza per Documentazione Libera -GNU (GNU FDL), ma talvolta utilizziamo -anche altre licenze per la -documentazione libera. -

+

+ La Licenza Pubblica Generica GNU è spesso indicata brevemente come + GNU GPL; è usata dalla maggioranza dei programmi GNU, e da + più della metà di tutti i pacchetti di software libero. +

-

La Licenza Pubblica Generica GNU

+

+ Licenza Pubblica Generica Attenuata GNU +

-

-La Licenza Pubblica Generica GNU è spesso indicata brevemente come GNU -GPL; è usata dalla maggioranza dei programmi GNU, e da più della metà di -tutti i pacchetti di software libero. -

+

+ La Licenza Pubblica Generica Attenuata GNU è utilizzata da alcune + (non tutte) delle librerie GNU. Questa licenza era originariamente + chiamata la GPL per Librerie, ma in seguito le cambiammo nome + perché il vecchio nome ne incoraggiava un uso più frequente + del dovuto. +

-

Licenza Pubblica Generica Attenuata GNU

+

+ La Licenza per Documentazione Libera GNU +

-

-La Licenza Pubblica Generica Attenuata GNU è utilizzata da alcune (non -tutte) delle librerie GNU. Questa licenza era originariamente chiamata -la GPL per Librerie, ma in seguito le cambiammo nome perché il vecchio -nome ne incoraggiava un uso più frequente del dovuto. -

+

+ La licenza di Documentazione Libera è una forma di permesso + d'autore (copyleft) pensata per un manuale, libro di testo o altro + documento, in modo da garantire a chiunque l'effettiva libertà di + usarlo e distribuirlo, con o senza modifiche, commercialmente o meno. +

+

+ Copie letterali e distribuzione +

+

+ La nota standard di copyright per le pagine web GNU recita: + La copia letterale e la distribuzione di questo articolo nella sua + integrità sono permesse con qualsiasi mezzo, a condizione che + questa nota sia riprodotta. Si tenga presente questo commento di Eben Moglen: +

-

La Licenza per Documentazione Libera GNU

+

+ «Con la frase "copia letterale con qualsiasi mezzo" non intendiamo + richiedere il mantenimento di intestazioni, piè di pagina o altre + caratteristiche di formattazione. Si richiede tuttavia di mantenere link + web sia per i media ipertestuali sia per quelli non ipertestuali (in forma + di note o URL riportate letteralmente su media non HTML).» +

-

-La licenza di Documentazione Libera è una forma di permesso d'autore -(copyleft) pensata per un manuale, libro di testo o altro documento, in -modo da garantire a chiunque l'effettiva libertà di usarlo e -distribuirlo, con o senza modifiche, commercialmente o meno. -

+

+ Elenco di licenze per il software libero +

-

Copie letterali e distribuzione

-

-La nota standard di copyright per le pagine web GNU recita: La copia -letterale e la distribuzione di questo articolo nella sua integrità sono -permesse con qualsiasi mezzo, a condizione che questa nota sia -riprodotta. Si tenga presente questo commento di Eben Moglen: -

+
    +
  • + Elenco di licenze per il software libero -

    -«Con la frase "copia letterale con qualsiasi mezzo" non intendiamo -richiedere il mantenimento di intestazioni, piè di pagina o altre -caratteristiche di formattazione. Si richiede tuttavia di mantenere link -web sia per i media ipertestuali sia per quelli non ipertestuali (in -forma di note o URL riportate letteralmente su media non HTML).» -

    +

    + Se state pensando di scrivere una nuova licenza, vi preghiamo di + contattare la FSF scrivendo a + <licensing@fsf.org>. Il + proliferare di diverse licenze di software libero significa un aumento + di lavoro per gli utenti per la loro comprensione. Potremmo essere in + grado di aiutarvi a trovare una licenza esistente per software libero + che soddisfi le vostre esigenze. +

    -

    Elenco di licenze per il software libero

    +

    + Nel caso ciò non sia possibile, se effettivamente avete bisogno + di una nuova licenza con il nostro aiuto potete assicuravi che la + vostra licenza sia effettivamente una licenza per software libero, ed + evitare vari problemi pratici. +

    +
  • +
-
    -
  • - Elenco di licenze per il software libero +

    + Cos'è il permesso d'autore (copyleft)? +

    -

    Se state pensando di scrivere una nuova licenza, vi preghiamo di -contattare la FSF scrivendo a <licensing@fsf.org>. Il -proliferare di diverse licenze di software libero significa un aumento -di lavoro per gli utenti per la loro comprensione. Potremmo essere in -grado di aiutarvi a trovare una licenza esistente per software libero -che soddisfi le vostre esigenze. -

    +

    + Il permesso d'autore (copyleft) è un metodo + generico per rendere un programma libero ed imporre che tutte le modifiche + e versioni estese del programma siano anch'esse software libero. +

    -

    -Nel caso ciò non sia possibile, se effettivamente avete bisogno di una -nuova licenza con il nostro aiuto potete assicuravi che la vostra -licenza sia effettivamente una licenza per software libero, ed evitare -vari problemi pratici. -

    +

    + [NdT: si tratta di un gioco di parole, che qui viene reso con "permesso di + autore": copyright (diritto di autore) è formato dalle parola + "copy" (copia) e "right" (diritto, ma anche destra), opposto di "left" + (sinistra, ma anche lasciato).] +

    -
  • -
+

+ Il modo più semplice per rendere un programma libero è + dichiararlo di dominio pubblico, privo di copyright. [NdT: in Italia + questo concetto a rigore non esiste, perché l'autore non può + rinunciare alla paternità dell'opera; effetti simili si possono + ottenere con l'uso di una licenza permissiva, come la licenza di X del + MIT]. Ciò permette a chiunque di condividere il programma e i suoi + miglioramenti. Tuttavia permette anche a chi non vuol cooperare di + convertire il programma in software proprietario. Costoro possono infatti + apportare modifiche, che siano significative o meno, e distribuire il + risultato come prodotto proprietario. Chi riceve il programma nella forma + modificata non ha la libertà data dall'autore originario; + l'intermediario l'avrà rimossa. +

-

Cos'è il permesso d'autore (copyleft)?

+

+ Nel Progetto GNU, la nostra intenzione è dare a tutti gli + utenti la libertà di ridistribuire e modificare software GNU. Se + l'intermediario potesse rimuoverne la libertà, potremmo avere molti + utenti, ma costoro non avrebbero libertà. Così, invece di + rilasciare il software GNU come dominio pubblico, utilizziamo il permesso + d'autore. Il permesso d'autore (copyleft) significa che chiunque + distribuisca il software, con o senza modifiche, deve accompagnarlo con la + libertà di ulteriori copie o modifiche. Il permesso d'autore + garantisce che ogni utente sia libero. +

-

-Il permesso d'autore (copyleft) è un metodo generico -per rendere un programma libero ed imporre che tutte le modifiche e -versioni estese del programma siano anch'esse software libero. -

+

+ Il permesso d'autore costituisce anche un incentivo per altri + programmatori ad incrementare il software libero. Alcuni programmi liberi + importanti, come il compilatore GNU C++, esistono solo grazie a questo. +

-

-[NdT: si tratta di un gioco di parole, che qui viene reso con "permesso -di autore": copyright (diritto di autore) è formato dalle parola "copy" -(copia) e "right" (diritto, ma anche destra), opposto di "left" -(sinistra, ma anche lasciato).] -

+

+ Il permesso d'autore aiuta anche i programmatori che desiderano + contribuire con miglioramenti al software libero ad ottenerne il permesso. + Questi programmatori spesso lavorano per aziende o università che + farebbero quasi qualunque cosa per avere più denaro. Un + programmatore potrebbe voler cedere le sue modifiche alla comunità, + ma il suo superiore potrebbe volerne fare un prodotto software + proprietario. +

-

-Il modo più semplice per rendere un programma libero è dichiararlo di dominio -pubblico, privo di copyright. [NdT: in Italia questo concetto a -rigore non esiste, perché l'autore non può rinunciare alla paternità -dell'opera; effetti simili si possono ottenere con l'uso di una licenza -permissiva, come la licenza di X del MIT]. Ciò permette a chiunque di -condividere il programma e i suoi miglioramenti. Tuttavia permette anche -a chi non vuol cooperare di convertire il programma in software -proprietario. Costoro possono infatti apportare modifiche, che -siano significative o meno, e distribuire il risultato come prodotto -proprietario. Chi riceve il programma nella forma modificata non ha la -libertà data dall'autore originario; l'intermediario l'avrà rimossa. -

+

+ Quando spieghiamo ai datori di lavoro che è illegale distribuire la + versione migliorata se non come software libero, questi normalmente + decidono di rilasciarla come software libero piuttosto che buttarla via. +

-

-Nel Progetto GNU, la nostra -intenzione è dare a tutti gli utenti la libertà di -ridistribuire e modificare software GNU. Se l'intermediario potesse -rimuoverne la libertà, potremmo avere molti utenti, ma costoro non -avrebbero libertà. Così, invece di rilasciare il software GNU come -dominio pubblico, utilizziamo il permesso d'autore. Il permesso -d'autore (copyleft) significa che chiunque distribuisca il software, con -o senza modifiche, deve accompagnarlo con la libertà di ulteriori -copie o modifiche. Il permesso d'autore garantisce che ogni utente sia -libero. -

+

+ Nel rendere un programma copyleft, per prima cosa mettiamo in chiaro che + è soggetto a diritto d'autore; poi aggiungiamo le condizioni di + distribuzione, che sono uno strumento legale per dare a chiunque i diritti + d'uso, di modifica e ridistribuzione del codice del programma + ed ogni programma da esso derivato, ma solo se si lasciano + invariati i termini di distribuzione. Così, il codice e le + libertà divengono legalmente inseparabili. +

-

-Il permesso d'autore costituisce anche un incentivo per altri -programmatori ad incrementare il software libero. Alcuni programmi -liberi importanti, come il compilatore GNU C++, esistono solo grazie a -questo. -

+

+ Gli sviluppatori di software proprietario utilizzano il diritto d'autore + per togliere la libertà agli utenti. Noi lo utilizziamo per + garantire la loro libertà. Ecco perché invertiamo il + termine, trasformando "diritto d'autore" in "permesso d'autore" + ("copyright" in "copyleft"). +

-

-Il permesso d'autore aiuta anche i programmatori che desiderano -contribuire con miglioramenti al software libero ad ottenerne il -permesso. Questi programmatori spesso lavorano per aziende o università -che farebbero quasi qualunque cosa per avere più denaro. Un -programmatore potrebbe voler cedere le sue modifiche alla comunità, ma -il suo superiore potrebbe volerne fare un prodotto software -proprietario. -

+

+ Il permesso d'autore è un concetto generale; ci sono molti modi di + completare i dettagli. Nel Progetto GNU, le specifiche condizioni di + distribuzione che utilizziamo sono contenute nella Licenza Pubblica + Generica GNU, la Licenza Pubblica Generica Attenuata GNU e la Licenza per + Documentazione Libera GNU. +

-

-Quando spieghiamo ai datori di lavoro che è illegale distribuire la -versione migliorata se non come software libero, questi normalmente -decidono di rilasciarla come software libero piuttosto che buttarla via. -

+

+ La licenza appropriata è inclusa in molti manuali e in ogni + distribuzione di codice sorgente GNU. +

-

-Nel rendere un programma copyleft, per prima cosa mettiamo in chiaro che -è soggetto a diritto d'autore; poi aggiungiamo le condizioni di -distribuzione, che sono uno strumento legale per dare a chiunque i -diritti d'uso, di modifica e ridistribuzione del codice del programma -ed ogni programma da esso derivato, ma solo se si lasciano -invariati i termini di distribuzione. Così, il codice e le libertà -divengono legalmente inseparabili. -

+

+ La GNU GPL è progettata perché possiate applicarla + facilmente ai vostri programmi se siete i titolari dei relativi diritti. + Per far questo non dovete modificare la GNU GPL ma solo aggiungere nel + programma una nota che vi faccia riferimento. Vi preghiamo di tener + presente che se usate la GNU GPL dovete usare il testo integrale della + licenza. E' un tutto unico, versioni parziali non sono consentite (lo + stesso vale per la LGPL e la FDL). +

-

-Gli sviluppatori di software proprietario utilizzano il diritto d'autore -per togliere la libertà agli utenti. Noi lo utilizziamo per garantire la -loro libertà. Ecco perché invertiamo il termine, trasformando "diritto -d'autore" in "permesso d'autore" ("copyright" in "copyleft"). -

+

+ Usare gli stessi termini di distribuzione per molti programmi rende facile + copiare codice tra programmi diversi. Dato che tutti hanno gli stessi + termini di distribuzione, non c'è bisogno di preoccuparsi se i + termini siano compatibili. La GPL Attenuata include una clausola che + permette di trasformare i termini di distribuzione nella GPL ordinaria, in + modo che possiate copiare codice in un altro programma coperto dalla GPL. +

-

-Il permesso d'autore è un concetto generale; ci sono molti modi di -completare i dettagli. Nel Progetto GNU, le specifiche condizioni di -distribuzione che utilizziamo sono contenute nella Licenza Pubblica -Generica GNU, la Licenza Pubblica Generica Attenuata GNU e la Licenza -per Documentazione Libera GNU. -

+

+ Licenze per altri tipi di opere +

-

-La licenza appropriata è inclusa in molti manuali e in ogni -distribuzione di codice sorgente GNU. -

+

+ Noi crediamo che il software e la documentazione che si pubblicano debbano + essere software libero e documentazione libera. + Consigliamo di rendere ugualmente libera ogni genere di opera educativa e + di riferimento, utilizzando licenze di documentazione libera come la + Licenza per Documentazione Libera GNU (GNU FDL). +

-

-La GNU GPL è progettata perché possiate applicarla facilmente ai vostri -programmi se siete i titolari dei relativi diritti. Per far questo non -dovete modificare la GNU GPL ma solo aggiungere nel programma una nota -che vi faccia riferimento. Vi preghiamo di tener presente che se usate -la GNU GPL dovete usare il testo integrale della licenza. E' un tutto -unico, versioni parziali non sono consentite (lo stesso vale per la LGPL -e la FDL). -

+

+ Per saggi o pubblicazioni scientifiche, consigliamo la semplice licenza di + "copia letterale" utilizzata ad esempio per questa pagina Web. +

-

-Usare gli stessi termini di distribuzione per molti programmi rende -facile copiare codice tra programmi diversi. Dato che tutti hanno gli -stessi termini di distribuzione, non c'è bisogno di preoccuparsi se i -termini siano compatibili. La GPL Attenuata include una clausola che -permette di trasformare i termini di distribuzione nella GPL ordinaria, -in modo che possiate copiare codice in un altro programma coperto dalla -GPL. -

+

+ Non prendiamo posizione sull'idea che i lavori artistici o letterari + debbano essere liberi, ma se volete fare in modo che un vostro lavoro lo + sia vi consigliamo la + Free Art License (in + inglese). +

-

Licenze per altri tipi di opere

- -

-Noi crediamo che il software e la documentazione che si pubblicano -debbano essere software libero e -documentazione libera. Consigliamo di rendere ugualmente libera -ogni genere di opera educativa e di riferimento, utilizzando licenze di -documentazione libera come la Licenza per -Documentazione Libera GNU (GNU FDL). -

- -

-Per saggi o pubblicazioni scientifiche, consigliamo la semplice licenza -di "copia letterale" utilizzata ad esempio per questa pagina Web.

- -

-Non prendiamo posizione sull'idea che i lavori artistici o letterari -debbano essere liberi, ma se volete fare in modo che un vostro lavoro -lo sia vi consigliamo la Free -Art License (in inglese).

- - -

-Copyright (C) 1996, 1997, 1998, 1999, 2003, 2004, 2005 Free Software Foundation, Inc., -51 Franklin St, Fifth Floor, Boston, MA 02110, USA -
-La copia letterale e la distribuzione di questo articolo nella sua -integrità sono permesse con qualsiasi mezzo gratuitamente a -condizione che questa nota sia riprodotta. -

- - +

+ Copyright (C) 1996, 1997, 1998, 1999, 2003, 2004, 2005 Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA +
+ La copia letterale e la distribuzione di questo articolo nella sua + integrità sono permesse con qualsiasi mezzo gratuitamente a + condizione che questa nota sia riprodotta. +

+ diff --git a/pandora_console/general/license/pandora_info_ja.html b/pandora_console/general/license/pandora_info_ja.html index 3a6dcedffe..3db88f9eb5 100644 --- a/pandora_console/general/license/pandora_info_ja.html +++ b/pandora_console/general/license/pandora_info_ja.html @@ -1,436 +1,433 @@ - + - - -GNU 一般公衆利用許諾契約書 - GNU プロジェクト - フリーソフトウェア財団 (FSF) - - + + + + GNU 一般公衆利用許諾契約書 - GNU プロジェクト - フリーソフトウェア財団 + (FSF) + + + + 本訳は、http://www.opensource.jp/gpl/gpl.ja.html.euc-jpより転載している。 -本訳は、http://www.opensource.jp/gpl/gpl.ja.html.euc-jpより転載している。 +
-
+

GNU 一般公衆利用許諾契約書

-

GNU 一般公衆利用許諾契約書

+

もくじ

+ -

もくじ

- -
-

-

GNU 一般公衆利用許諾契約書

-

-バージョン 2、1991年6月
-日本語訳、2002年8月28日 -

- -
+    
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
 
 この利用許諾契約書を、一字一句そのままに複製し頒布することは許可する。
 しかし変更は認めない。
-
+
-
-This is an unofficial translation of the GNU General Public License -into Japanese. It was not published by the Free Software Foundation, -and does not legally state the distribution terms for software that -uses the GNU GPL--only the original English text of the GNU GPL does -that. However, we hope that this translation will help Japanese -speakers understand the GNU GPL better. -
+
+ This is an unofficial translation of the GNU General Public License into + Japanese. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help Japanese speakers understand the GNU + GPL better. +
-
-(訳: 以下はGNU General Public Licenseの非公式な日本語訳です。これはフ -リーソフトウェア財団(the Free Software Foundation)によって発表されたも -のではなく、GNU GPLを適用したソフトウェアの頒布条件を法的に有効な形で -述べたものではありません。頒布条件としてはGNU GPLの英語版テキストで指 -定されているもののみが有効です。しかしながら、私たちはこの翻訳が、日本 -語を使用する人々にとってGNU GPLをより良く理解する助けとなることを望ん -でいます。) -
+
+ (訳: 以下はGNU General Public Licenseの非公式な日本語訳です。これはフ + リーソフトウェア財団(the Free Software Foundation)によって発表されたも + のではなく、GNU GPLを適用したソフトウェアの頒布条件を法的に有効な形で + 述べたものではありません。頒布条件としてはGNU GPLの英語版テキストで指 + 定されているもののみが有効です。しかしながら、私たちはこの翻訳が、日本 + 語を使用する人々にとってGNU GPLをより良く理解する助けとなることを望ん + でいます。) +
-
-翻訳は 八田真行<mhatta@gnu.org>が行った。原文はhttp://www.gnu.org/licenses/gpl.html -である。誤訳の指摘や改善案を歓迎する。 -
+
+ 翻訳は 八田真行<mhatta@gnu.org>が行った。原文はhttp://www.gnu.org/licenses/gpl.html + である。誤訳の指摘や改善案を歓迎する。 +
-

はじめに

+

はじめに

-

-ソフトウェア向けライセンスの大半は、あなたがそのソフトウェアを共有した -り変更したりする自由を奪うように設計されています。対照的に、GNU 一般公 -衆利用許諾契約書は、あなたがフリーソフトウェアを共有したり変更したりす -る自由を保証する--すなわち、ソフトウェアがそのユーザすべてにとってフリー -であることを保証することを目的としています。この一般公衆利用許諾契約書 -はフリーソフトウェア財団のソフトウェアのほとんどに適用されており、また -GNU GPLを適用すると決めたフリーソフトウェア財団以外の作者によるプログ -ラムにも適用されています(いくつかのフリーソフトウェア財団のソフトウェ -アには、GNU GPLではなくGNU ライブラリ一般公衆利用許諾契約書が適用され -ています)。あなたもまた、ご自分のプログラムにGNU GPLを適用することが可 -能です。 +

+ ソフトウェア向けライセンスの大半は、あなたがそのソフトウェアを共有した + り変更したりする自由を奪うように設計されています。対照的に、GNU 一般公 + 衆利用許諾契約書は、あなたがフリーソフトウェアを共有したり変更したりす + る自由を保証する--すなわち、ソフトウェアがそのユーザすべてにとってフリー + であることを保証することを目的としています。この一般公衆利用許諾契約書 + はフリーソフトウェア財団のソフトウェアのほとんどに適用されており、また GNU + GPLを適用すると決めたフリーソフトウェア財団以外の作者によるプログ + ラムにも適用されています(いくつかのフリーソフトウェア財団のソフトウェ + アには、GNU GPLではなくGNU ライブラリ一般公衆利用許諾契約書が適用され + ています)。あなたもまた、ご自分のプログラムにGNU GPLを適用することが可 + 能です。 +

+

+ 私たちがフリーソフトウェアと言うとき、それは利用の自由について言及して + いるのであって、価格は問題にしていません。私たちの一般公衆利用許諾契約 + 書は、あなたがフリーソフトウェアの複製物を頒布する自由を保証するよう設 + 計されています(希望に応じてその種のサービスに手数料を課す自由も保証さ + れます)。また、あなたがソースコードを受け取るか、あるいは望めばそれを + 入手することが可能であるということ、あなたがソフトウェアを変更し、その + 一部を新たなフリーのプログラムで利用できるということ、そして、以上で述 + べたようなことができるということがあなたに知らされるということも保証さ + れます。 +

+

+ あなたの権利を守るため、私たちは誰かがあなたの有するこれらの権利を否定 + することや、これらの権利を放棄するよう要求することを禁止するという制限 + を加える必要があります。よって、あなたがソフトウェアの複製物を頒布した + りそれを変更したりする場合には、そういった制限のためにあなたにある種の + 責任が発生することになります。 +

+

+ 例えば、あなたがフリーなプログラムの複製物を頒布する場合、有料か無料に + 関わらず、あなたは自分が有する権利を全て受領者に与えなければなりません。 + また、あなたは彼らもソースコードを受け取るか手に入れることができるよう + 保証しなければなりません。そして、あなたは彼らに対して以下で述べる条件 + を示し、彼らに自らの持つ権利について知らしめるようにしなければなりませ + ん。 +

+

+ 私たちはあなたの権利を二段階の手順を踏んで保護します。(1) まずソフトウェ + アに対して著作権を主張し、そして (2) あなたに対して、ソフトウェアの複 + 製や頒布または改変についての法的な許可を与えるこの契約書を提示します。 +

+

+ また、各作者や私たちを保護するため、私たちはこのフリーソフトウェアには + 何の保証も無いということを誰もが確実に理解するようにし、またソフトウェ + アが誰か他人によって改変され、それが次々と頒布されていったとしても、そ + の受領者は彼らが手に入れたソフトウェアがオリジナルのバージョンでは無い + こと、そして原作者の名声は他人によって持ち込まれた可能性のある問題によっ + て影響されることがないということを周知させたいと思います。 +

+

+ 最後に、ソフトウェア特許がいかなるフリーのプログラムの存在にも不断の脅 + 威を投げかけていますが、私たちは、フリーなプログラムの再頒布者が個々に + 特許ライセンスを取得することによって、事実上プログラムを独占的にしてし + まうという危険を避けたいと思います。こういった事態を予防するため、私た + ちはいかなる特許も誰もが自由に利用できるようライセンスされるか、全くラ + イセンスされないかのどちらかでなければならないことを明確にしました。 +

-

-

-私たちがフリーソフトウェアと言うとき、それは利用の自由について言及して -いるのであって、価格は問題にしていません。私たちの一般公衆利用許諾契約 -書は、あなたがフリーソフトウェアの複製物を頒布する自由を保証するよう設 -計されています(希望に応じてその種のサービスに手数料を課す自由も保証さ -れます)。また、あなたがソースコードを受け取るか、あるいは望めばそれを -入手することが可能であるということ、あなたがソフトウェアを変更し、その -一部を新たなフリーのプログラムで利用できるということ、そして、以上で述 -べたようなことができるということがあなたに知らされるということも保証さ -れます。 +

+ (訳注: 本契約書で「独占的(proprietary)」とは、ソフトウェアの利用や再頒 + 布、改変が禁止されているか、許可を得ることが必要とされているか、あるい + は厳しい制限が課せられていて自由にそうすることが事実上できなくなってい + る状態のことを指す。詳しくはhttp://www.gnu.org/philosophy/categories.ja.html#ProprietarySoftware + を参照せよ。) +
-

-

-あなたの権利を守るため、私たちは誰かがあなたの有するこれらの権利を否定 -することや、これらの権利を放棄するよう要求することを禁止するという制限 -を加える必要があります。よって、あなたがソフトウェアの複製物を頒布した -りそれを変更したりする場合には、そういった制限のためにあなたにある種の -責任が発生することになります。 +

複製や頒布、改変についての正確な条件と制約を以下で述べていきます。

-

-

-例えば、あなたがフリーなプログラムの複製物を頒布する場合、有料か無料に -関わらず、あなたは自分が有する権利を全て受領者に与えなければなりません。 -また、あなたは彼らもソースコードを受け取るか手に入れることができるよう -保証しなければなりません。そして、あなたは彼らに対して以下で述べる条件 -を示し、彼らに自らの持つ権利について知らしめるようにしなければなりませ -ん。 +

複製、頒布、改変に関する条件と制約

-

-

-私たちはあなたの権利を二段階の手順を踏んで保護します。(1) まずソフトウェ -アに対して著作権を主張し、そして (2) あなたに対して、ソフトウェアの複 -製や頒布または改変についての法的な許可を与えるこの契約書を提示します。 +

+ 0. + この利用許諾契約書は、そのプログラム(またはその他の著作物)をこの一般公 + 衆利用許諾契約書の定める条件の下で頒布できる、という告知が著作権者によっ + て記載されたプログラムまたはその他の著作物全般に適用される。以下では、 + 「『プログラム』」とはそのようにしてこの契約書が適用されたプログラムや + 著作物全般を意味し、また「『プログラム』を基にした著作物」とは『プログ + ラム』やその他著作権法の下で派生物と見なされるもの全般を指す。すなわち、 + 『プログラム』かその一部を、全く同一のままか、改変を加えたか、あるいは + 他の言語に翻訳された形で含む著作物のことである(「改変」という語の本来 + の意味からはずれるが、以下では翻訳も改変の一種と見なす)。それぞれの契 + 約者は「あなた」と表現される。 +

+

+ 複製や頒布、改変以外の活動はこの契約書ではカバーされない。それらはこの + 契約書の対象外である。『プログラム』を実行する行為自体に制限はない。ま + た、そのような『プログラム』の出力結果は、その内容が『プログラム』を基 + にした著作物を構成する場合のみこの契約書によって保護される(『プログラ + ム』を実行したことによって作成されたということとは無関係である)。この + ような線引きの妥当性は、『プログラム』が何をするのかに依存する。 +

+

+ 1. + それぞれの複製物において適切な著作権表示と保証の否認声明(disclaimer of + warranty)を目立つよう適切に掲載し、またこの契約書および一切の保証の不 + 在に触れた告知すべてをそのまま残し、そしてこの契約書の複製物を『プログ + ラム』のいかなる受領者にも『プログラム』と共に頒布する限り、あなたは + 『プログラム』のソースコードの複製物を、あなたが受け取った通りの形で複 + 製または頒布することができる。媒体は問わない。 +

+

+ あなたは、物理的に複製物を譲渡するという行為に関して手数料を課しても良 + いし、希望によっては手数料を取って交換における保護の保証を提供しても良 + い。 +

+

+ 2. + あなたは自分の『プログラム』の複製物かその一部を改変して『プログラム』 + を基にした著作物を形成し、そのような改変点や著作物を上記第1節の定める + 条件の下で複製または頒布することができる。ただし、そのためには以下の条 + 件すべてを満たしていなければならない: +

+

+
    +
  • + a) + あなたがそれらのファイルを変更したということと変更した日時が良く + 分かるよう、改変されたファイルに告示しなければならない。 -

    -

    -また、各作者や私たちを保護するため、私たちはこのフリーソフトウェアには -何の保証も無いということを誰もが確実に理解するようにし、またソフトウェ -アが誰か他人によって改変され、それが次々と頒布されていったとしても、そ -の受領者は彼らが手に入れたソフトウェアがオリジナルのバージョンでは無い -こと、そして原作者の名声は他人によって持ち込まれた可能性のある問題によっ -て影響されることがないということを周知させたいと思います。 +

    +
  • +
  • + b) + 『プログラム』またはその一部を含む著作物、あるいは『プログラム』 + かその一部から派生した著作物を頒布あるいは発表する場合には、その + 全体をこの契約書の条件に従って第三者へ無償で利用許諾しなけれ + ばならない。 -

    -

    -最後に、ソフトウェア特許がいかなるフリーのプログラムの存在にも不断の脅 -威を投げかけていますが、私たちは、フリーなプログラムの再頒布者が個々に -特許ライセンスを取得することによって、事実上プログラムを独占的にしてし -まうという危険を避けたいと思います。こういった事態を予防するため、私た -ちはいかなる特許も誰もが自由に利用できるようライセンスされるか、全くラ -イセンスされないかのどちらかでなければならないことを明確にしました。 +

    +
  • +
  • + c) + 改変されたプログラムが、通常実行する際に対話的にコマンドを読むよ + うになっているならば、そのプログラムを最も一般的な方法で対話的に + 実行する際、適切な著作権表示、無保証であること(あるいはあなたが保 + 証を提供するということ)、ユーザがプログラムをこの契約書で述べた条 + 件の下で頒布することができるということ、そしてこの契約書の複製物 + を閲覧するにはどうしたらよいかというユーザへの説明を含む告知が印 + 刷されるか、あるいは画面に表示されるようにしなければならない(例外 + として、『プログラム』そのものは対話的であっても通常そのような告 + 知を印刷しない場合には、『プログラム』を基にしたあなたの著作物に + そのような告知を印刷させる必要はない)。 +
  • +
-

+ 以上の必要条件は全体としての改変された著作物に適用される。著作物の一部 + が『プログラム』から派生したものではないと確認でき、それら自身別の独立 + した著作物であると合理的に考えられるならば、あなたがそれらを別の著作物 + として分けて頒布する場合、そういった部分にはこの契約書とその条件は適用 + されない。しかし、あなたが同じ部分を『プログラム』を基にした著作物全体 + の一部として頒布するならば、全体としての頒布物は、この契約書が課す条件 + に従わなければならない。というのは、この契約書が他の契約者に与える許可 + は『プログラム』丸ごと全体に及び、誰が書いたかは関係なく各部分のすべて + を保護するからである。 +

+ よって、すべてあなたによって書かれた著作物に対し、権利を主張したりあな + たの権利に異議を申し立てることはこの節の意図するところではない。むしろ、 + その趣旨は『プログラム』を基にした派生物ないし集合著作物の頒布を管理す + る権利を行使するということにある。 +

+

+ また、『プログラム』を基にしていないその他の著作物を『プログラム』(あ + るいは『プログラム』を基にした著作物)と一緒に集めただけのものを一巻の + 保管装置ないし頒布媒体に収めても、その他の著作物までこの契約書が保護す + る対象になるということにはならない。 +

+

+ 3. + あなたは上記第1節および2節の条件に従い、『プログラム』(あるいは第2節に + おける派生物)をオブジェクトコードないし実行形式で複製または頒布するこ + とができる。ただし、その場合あなたは以下のうちどれか一つを実施しなけれ + ばならない: -

-(訳注: 本契約書で「独占的(proprietary)」とは、ソフトウェアの利用や再頒 -布、改変が禁止されているか、許可を得ることが必要とされているか、あるい -は厳しい制限が課せられていて自由にそうすることが事実上できなくなってい -る状態のことを指す。詳しくはhttp://www.gnu.org/philosophy/categories.ja.html#ProprietarySoftware -を参照せよ。) -
+ + +

+
    +
  • + a) + 著作物に、『プログラム』に対応した完全かつ機械で読み取り可能なソー + スコードを添付する。ただし、ソースコードは上記第1節および2節の条 + 件に従いソフトウェアの交換で習慣的に使われる媒体で頒布しなければ + ならない。あるいは、 +

    +
  • +
  • + b) + 著作物に、いかなる第三者に対しても、『プログラム』に対応した完全 + かつ機械で読み取り可能なソースコードを、頒布に要する物理的コスト + を上回らない程度の手数料と引き換えに提供する旨述べた少なくとも3年 + 間は有効な書面になった申し出を添える。ただし、ソースコードは上記 + 第1節および2節の条件に従いソフトウェアの交換で習慣的に使われる媒 + 体で頒布しなければならない。あるいは、 +

    +
  • +
  • + c) + 対応するソースコード頒布の申し出に際して、あなたが得た情報を一緒 + に引き渡す(この選択肢は、営利を目的としない頒布であって、かつあな + たが上記小節bで指定されているような申し出と共にオブジェクトコード + あるいは実行形式のプログラムしか入手していない場合に限り許可され る)。 +
  • +
-

-複製や頒布、改変についての正確な条件と制約を以下で述べていきます。 + 著作物のソースコードとは、それに対して改変を加える上で好ましいとされる + 著作物の形式を意味する。ある実行形式の著作物にとって完全なソースコード + とは、それが含むモジュールすべてのソースコード全部に加え、関連するイン + ターフェース定義ファイルのすべてとライブラリのコンパイルやインストール + を制御するために使われるスクリプトをも加えたものを意味する。しかし特別 + な例外として、そのコンポーネント自体が実行形式に付随するのでは無い限り、 + 頒布されるものの中に、実行形式が実行されるオペレーティングシステムの主 + 要なコンポーネント(コンパイラやカーネル等)と通常一緒に(ソースかバイナ + リ形式のどちらかで)頒布されるものを含んでいる必要はないとする。 +

+ 実行形式またはオブジェクトコードの頒布が、指定された場所からコピーする + ためのアクセス手段を提供することで為されるとして、その上でソースコード + も同等のアクセス手段によって同じ場所からコピーできるようになっているな + らば、第三者がオブジェクトコードと一緒にソースも強制的にコピーさせられ + るようになっていなくてもソースコード頒布の条件を満たしているものとする。 +

+

+ 4. + あなたは『プログラム』を、この契約書において明確に提示された行為を除き + 複製や改変、サブライセンス、あるいは頒布してはならない。他に『プログラ + ム』を複製や改変、サブライセンス、あるいは頒布する企てはすべて無効であ + り、この契約書の下でのあなたの権利を自動的に終結させることになろう。し + かし、複製物や権利をこの契約書に従ってあなたから得た人々に関しては、そ + のような人々がこの契約書に完全に従っている限り彼らのライセンスまで終結 + することはない。 +

+

+ 5. + あなたはこの契約書を受諾する必要は無い。というのは、あなたはこれに署名 + していないからである。しかし、この契約書以外にあなたに対して『プログラ + ム』やその派生物を改変または頒布する許可を与えるものは存在しない。これ + らの行為は、あなたがこの契約書を受け入れない限り法によって禁じられてい + る。そこで、『プログラム』(あるいは『プログラム』を基にした著作物全般) + を改変ないし頒布することにより、あなたは自分がそのような行為を行うため + にこの契約書を受諾したということ、そして『プログラム』とそれに基づく著 + 作物の複製や頒布、改変についてこの契約書が課す制約と条件をすべて受け入 + れたということを示したものと見なす。 +

+

+ 6. + あなたが『プログラム』(または『プログラム』を基にした著作物全般)を再頒 + 布するたびに、その受領者は元々のライセンス許可者から、この契約書で指定 + された条件と制約の下で『プログラム』を複製や頒布、あるいは改変する許可 + を自動的に得るものとする。あなたは、受領者がここで認められた権利を行使 + することに関してこれ以上他のいかなる制限も課してはならない。あなたには、 + 第三者がこの契約書に従うことを強制する責任はない。 +

+

+ 7. + 特許侵害あるいはその他の理由(特許関係に限らない)から、裁判所の判決ある + いは申し立ての結果としてあなたに(裁判所命令や契約などにより)このライセ + ンスの条件と矛盾する制約が課された場合でも、あなたがこの契約書の条 + 件を免除されるわけではない。もしこの契約書の下であなたに課せられた + 責任と他の関連する責任を同時に満たすような形で頒布できないならば、結果 + としてあなたは『プログラム』を頒布することが全くできないということであ + る。例えば特許ライセンスが、あなたから直接間接を問わずコピーを受け取っ + た人が誰でも『プログラム』を使用料無料で再頒布することを認めていない場 + 合、あなたがその制約とこの契約書を両方とも満たすには『プログラム』 + の頒布を完全に中止するしかないだろう。 +

+

+ この節の一部分が特定の状況の下で無効ないし実施不可能な場合でも、節の残 + りの部分は適用されるよう意図されている。その他の状況では節が全体として + 適用されるよう意図されている。 +

+

+ 特許やその他の財産権を侵害したり、そのような権利の主張の効力に異議を唱 + えたりするようあなたを誘惑することがこの節の目的ではない。この節には、 + 人々によってライセンス慣行として実現されてきた、フリーソフトウェア頒布 + のシステムの完全性を護るという目的しかない。多くの人々が、フリーソフト + ウェアの頒布システムが首尾一貫して適用されているという信頼に基づき、こ + のシステムを通じて頒布される多様なソフトウェアに寛大な貢献をしてきたの + は事実であるが、人がどのようなシステムを通じてソフトウェアを頒布したい + と思うかはあくまでも作者/寄与者次第であり、あなたが選択を押しつけるこ + とはできない。 +

+

+ この節は、この契約書のこの節以外の部分の一帰結になると考えられるケー + スを徹底的に明らかにすることを目的としている。 +

+

+ 8. + 『プログラム』の頒布や利用が、ある国においては特許または著作権が主張さ + れたインターフェースのいずれかによって制限されている場合、『プログラム』 + にこの契約書を適用した元の著作権者は、そういった国々を排除した明確 + な地理的頒布制限を加え、そこで排除されていない国の中やそれらの国々の間 + でのみ頒布が許可されるようにしても構わない。その場合、そのような制限は + この契約書本文で書かれているのと同様に見なされる。 +

+

+ 9. + フリーソフトウェア財団は、時によって改訂または新版の一般公衆利用許諾書 + を発表することができる。そのような新版は現在のバージョンとその精神にお + いては似たものになるだろうが、新たな問題や懸念を解決するため細部では異 + なる可能性がある。 +

+

+ それぞれのバージョンには、見分けが付くようにバージョン番号が振られてい + る。『プログラム』においてそれに適用されるこの契約書のバージョン番号が + 指定されていて、更に「それ以降のいかなるバージョン(any later version)」 + も適用して良いとなっていた場合、あなたは従う条件と制約として、指定のバー + ジョンか、フリーソフトウェア財団によって発行された指定のバージョン以降 + の版のどれか一つのどちらかを選ぶことが出来る。『プログラム』でライセン + スのバージョン番号が指定されていないならば、あなたは今までにフリーソフ + トウェア財団から発行されたバージョンの中から好きに選んで構わない。 +

+

+ 10. + もしあなたが『プログラム』の一部を、その頒布条件がこの契約書と異なる他 + のフリーなプログラムと統合したいならば、作者に連絡して許可を求めよ。フ + リーソフトウェア財団が著作権を保有するソフトウェアについては、フリーソ + フトウェア財団に連絡せよ。私たちは、このような場合のために特別な例外を + 設けることもある。私たちが決定を下すにあたっては、私たちのフリーソフト + ウェアの派生物すべてがフリーな状態に保たれるということと、一般的にソフ + トウェアの共有と再利用を促進するという二つの目標を規準に検討されるであ + ろう。 +

+

無保証について

-

+

+ 11. + + 『プログラム』は代価無しに利用が許可されるので、適切な法が認める限りに + おいて、『プログラム』に関するいかなる保証も存在しない。書面で別に述べ + る場合を除いて、著作権者、またはその他の団体は、『プログラム』を、表明 + されたか言外にかは問わず、商業的適性を保証するほのめかしやある特定の目 + 的への適合性(に限られない)を含む一切の保証無しに「あるがまま」で提供す + る。『プログラム』の質と性能に関するリスクのすべてはあなたに帰属する。 + 『プログラム』に欠陥があると判明した場合、あなたは必要な保守点検や補修、 + 修正に要するコストのすべてを引き受けることになる。 + +

+

+ 12. + + 適切な法か書面での同意によって命ぜられない限り、著作権者、または上記で + 許可されている通りに『プログラム』を改変または再頒布したその他の団体は、 + あなたに対して『プログラム』の利用ないし利用不能で生じた通常損害や特別 + 損害、偶発損害、間接損害(データの消失や不正確な処理、あなたか第三者が + 被った損失、あるいは『プログラム』が他のソフトウェアと一緒に動作しない + という不具合などを含むがそれらに限らない)に一切の責任を負わない。その + ような損害が生ずる可能性について彼らが忠告されていたとしても同様である。 + +

- -

複製、頒布、改変に関する条件と制約

- - -

- -0. -この利用許諾契約書は、そのプログラム(またはその他の著作物)をこの一般公 -衆利用許諾契約書の定める条件の下で頒布できる、という告知が著作権者によっ -て記載されたプログラムまたはその他の著作物全般に適用される。以下では、 -「『プログラム』」とはそのようにしてこの契約書が適用されたプログラムや -著作物全般を意味し、また「『プログラム』を基にした著作物」とは『プログ -ラム』やその他著作権法の下で派生物と見なされるもの全般を指す。すなわち、 -『プログラム』かその一部を、全く同一のままか、改変を加えたか、あるいは -他の言語に翻訳された形で含む著作物のことである(「改変」という語の本来 -の意味からはずれるが、以下では翻訳も改変の一種と見なす)。それぞれの契 -約者は「あなた」と表現される。 -

- -複製や頒布、改変以外の活動はこの契約書ではカバーされない。それらはこの -契約書の対象外である。『プログラム』を実行する行為自体に制限はない。ま -た、そのような『プログラム』の出力結果は、その内容が『プログラム』を基 -にした著作物を構成する場合のみこの契約書によって保護される(『プログラ -ム』を実行したことによって作成されたということとは無関係である)。この -ような線引きの妥当性は、『プログラム』が何をするのかに依存する。 -

- -1. -それぞれの複製物において適切な著作権表示と保証の否認声明(disclaimer of -warranty)を目立つよう適切に掲載し、またこの契約書および一切の保証の不 -在に触れた告知すべてをそのまま残し、そしてこの契約書の複製物を『プログ -ラム』のいかなる受領者にも『プログラム』と共に頒布する限り、あなたは -『プログラム』のソースコードの複製物を、あなたが受け取った通りの形で複 -製または頒布することができる。媒体は問わない。 -

- -あなたは、物理的に複製物を譲渡するという行為に関して手数料を課しても良 -いし、希望によっては手数料を取って交換における保護の保証を提供しても良 -い。 -

- -2. -あなたは自分の『プログラム』の複製物かその一部を改変して『プログラム』 -を基にした著作物を形成し、そのような改変点や著作物を上記第1節の定める -条件の下で複製または頒布することができる。ただし、そのためには以下の条 -件すべてを満たしていなければならない: -

- -

    - -
  • a) - あなたがそれらのファイルを変更したということと変更した日時が良く - 分かるよう、改変されたファイルに告示しなければならない。 - -

    -

  • b) - 『プログラム』またはその一部を含む著作物、あるいは『プログラム』 - かその一部から派生した著作物を頒布あるいは発表する場合には、その - 全体をこの契約書の条件に従って第三者へ無償で利用許諾しなけれ - ばならない。 - -

    -

  • c) - 改変されたプログラムが、通常実行する際に対話的にコマンドを読むよ - うになっているならば、そのプログラムを最も一般的な方法で対話的に - 実行する際、適切な著作権表示、無保証であること(あるいはあなたが保 - 証を提供するということ)、ユーザがプログラムをこの契約書で述べた条 - 件の下で頒布することができるということ、そしてこの契約書の複製物 - を閲覧するにはどうしたらよいかというユーザへの説明を含む告知が印 - 刷されるか、あるいは画面に表示されるようにしなければならない(例外 - として、『プログラム』そのものは対話的であっても通常そのような告 - 知を印刷しない場合には、『プログラム』を基にしたあなたの著作物に - そのような告知を印刷させる必要はない)。 -
- -以上の必要条件は全体としての改変された著作物に適用される。著作物の一部 -が『プログラム』から派生したものではないと確認でき、それら自身別の独立 -した著作物であると合理的に考えられるならば、あなたがそれらを別の著作物 -として分けて頒布する場合、そういった部分にはこの契約書とその条件は適用 -されない。しかし、あなたが同じ部分を『プログラム』を基にした著作物全体 -の一部として頒布するならば、全体としての頒布物は、この契約書が課す条件 -に従わなければならない。というのは、この契約書が他の契約者に与える許可 -は『プログラム』丸ごと全体に及び、誰が書いたかは関係なく各部分のすべて -を保護するからである。 -

- -よって、すべてあなたによって書かれた著作物に対し、権利を主張したりあな -たの権利に異議を申し立てることはこの節の意図するところではない。むしろ、 -その趣旨は『プログラム』を基にした派生物ないし集合著作物の頒布を管理す -る権利を行使するということにある。 -

- -また、『プログラム』を基にしていないその他の著作物を『プログラム』(あ -るいは『プログラム』を基にした著作物)と一緒に集めただけのものを一巻の -保管装置ないし頒布媒体に収めても、その他の著作物までこの契約書が保護す -る対象になるということにはならない。 -

- -3. -あなたは上記第1節および2節の条件に従い、『プログラム』(あるいは第2節に -おける派生物)をオブジェクトコードないし実行形式で複製または頒布するこ -とができる。ただし、その場合あなたは以下のうちどれか一つを実施しなけれ -ばならない: - - - -

    - -
  • a) - 著作物に、『プログラム』に対応した完全かつ機械で読み取り可能なソー - スコードを添付する。ただし、ソースコードは上記第1節および2節の条 - 件に従いソフトウェアの交換で習慣的に使われる媒体で頒布しなければ - ならない。あるいは、 -

    -

  • b) - 著作物に、いかなる第三者に対しても、『プログラム』に対応した完全 - かつ機械で読み取り可能なソースコードを、頒布に要する物理的コスト - を上回らない程度の手数料と引き換えに提供する旨述べた少なくとも3年 - 間は有効な書面になった申し出を添える。ただし、ソースコードは上記 - 第1節および2節の条件に従いソフトウェアの交換で習慣的に使われる媒 - 体で頒布しなければならない。あるいは、 -

    -

  • c) - 対応するソースコード頒布の申し出に際して、あなたが得た情報を一緒 - に引き渡す(この選択肢は、営利を目的としない頒布であって、かつあな - たが上記小節bで指定されているような申し出と共にオブジェクトコード - あるいは実行形式のプログラムしか入手していない場合に限り許可され - る)。 -
- -著作物のソースコードとは、それに対して改変を加える上で好ましいとされる -著作物の形式を意味する。ある実行形式の著作物にとって完全なソースコード -とは、それが含むモジュールすべてのソースコード全部に加え、関連するイン -ターフェース定義ファイルのすべてとライブラリのコンパイルやインストール -を制御するために使われるスクリプトをも加えたものを意味する。しかし特別 -な例外として、そのコンポーネント自体が実行形式に付随するのでは無い限り、 -頒布されるものの中に、実行形式が実行されるオペレーティングシステムの主 -要なコンポーネント(コンパイラやカーネル等)と通常一緒に(ソースかバイナ -リ形式のどちらかで)頒布されるものを含んでいる必要はないとする。 -

- -実行形式またはオブジェクトコードの頒布が、指定された場所からコピーする -ためのアクセス手段を提供することで為されるとして、その上でソースコード -も同等のアクセス手段によって同じ場所からコピーできるようになっているな -らば、第三者がオブジェクトコードと一緒にソースも強制的にコピーさせられ -るようになっていなくてもソースコード頒布の条件を満たしているものとする。 -

- -4. -あなたは『プログラム』を、この契約書において明確に提示された行為を除き -複製や改変、サブライセンス、あるいは頒布してはならない。他に『プログラ -ム』を複製や改変、サブライセンス、あるいは頒布する企てはすべて無効であ -り、この契約書の下でのあなたの権利を自動的に終結させることになろう。し -かし、複製物や権利をこの契約書に従ってあなたから得た人々に関しては、そ -のような人々がこの契約書に完全に従っている限り彼らのライセンスまで終結 -することはない。 -

- -5. -あなたはこの契約書を受諾する必要は無い。というのは、あなたはこれに署名 -していないからである。しかし、この契約書以外にあなたに対して『プログラ -ム』やその派生物を改変または頒布する許可を与えるものは存在しない。これ -らの行為は、あなたがこの契約書を受け入れない限り法によって禁じられてい -る。そこで、『プログラム』(あるいは『プログラム』を基にした著作物全般) -を改変ないし頒布することにより、あなたは自分がそのような行為を行うため -にこの契約書を受諾したということ、そして『プログラム』とそれに基づく著 -作物の複製や頒布、改変についてこの契約書が課す制約と条件をすべて受け入 -れたということを示したものと見なす。 -

- -6. -あなたが『プログラム』(または『プログラム』を基にした著作物全般)を再頒 -布するたびに、その受領者は元々のライセンス許可者から、この契約書で指定 -された条件と制約の下で『プログラム』を複製や頒布、あるいは改変する許可 -を自動的に得るものとする。あなたは、受領者がここで認められた権利を行使 -することに関してこれ以上他のいかなる制限も課してはならない。あなたには、 -第三者がこの契約書に従うことを強制する責任はない。 - -

- -7. -特許侵害あるいはその他の理由(特許関係に限らない)から、裁判所の判決ある -いは申し立ての結果としてあなたに(裁判所命令や契約などにより)このライセ -ンスの条件と矛盾する制約が課された場合でも、あなたがこの契約書の条 -件を免除されるわけではない。もしこの契約書の下であなたに課せられた -責任と他の関連する責任を同時に満たすような形で頒布できないならば、結果 -としてあなたは『プログラム』を頒布することが全くできないということであ -る。例えば特許ライセンスが、あなたから直接間接を問わずコピーを受け取っ -た人が誰でも『プログラム』を使用料無料で再頒布することを認めていない場 -合、あなたがその制約とこの契約書を両方とも満たすには『プログラム』 -の頒布を完全に中止するしかないだろう。 - -

- -この節の一部分が特定の状況の下で無効ないし実施不可能な場合でも、節の残 -りの部分は適用されるよう意図されている。その他の状況では節が全体として -適用されるよう意図されている。 - -

- -特許やその他の財産権を侵害したり、そのような権利の主張の効力に異議を唱 -えたりするようあなたを誘惑することがこの節の目的ではない。この節には、 -人々によってライセンス慣行として実現されてきた、フリーソフトウェア頒布 -のシステムの完全性を護るという目的しかない。多くの人々が、フリーソフト -ウェアの頒布システムが首尾一貫して適用されているという信頼に基づき、こ -のシステムを通じて頒布される多様なソフトウェアに寛大な貢献をしてきたの -は事実であるが、人がどのようなシステムを通じてソフトウェアを頒布したい -と思うかはあくまでも作者/寄与者次第であり、あなたが選択を押しつけるこ -とはできない。 - -

- -この節は、この契約書のこの節以外の部分の一帰結になると考えられるケー -スを徹底的に明らかにすることを目的としている。 - -

- -8. -『プログラム』の頒布や利用が、ある国においては特許または著作権が主張さ -れたインターフェースのいずれかによって制限されている場合、『プログラム』 -にこの契約書を適用した元の著作権者は、そういった国々を排除した明確 -な地理的頒布制限を加え、そこで排除されていない国の中やそれらの国々の間 -でのみ頒布が許可されるようにしても構わない。その場合、そのような制限は -この契約書本文で書かれているのと同様に見なされる。 - -

- -9. -フリーソフトウェア財団は、時によって改訂または新版の一般公衆利用許諾書 -を発表することができる。そのような新版は現在のバージョンとその精神にお -いては似たものになるだろうが、新たな問題や懸念を解決するため細部では異 -なる可能性がある。 - -

-それぞれのバージョンには、見分けが付くようにバージョン番号が振られてい -る。『プログラム』においてそれに適用されるこの契約書のバージョン番号が -指定されていて、更に「それ以降のいかなるバージョン(any later version)」 -も適用して良いとなっていた場合、あなたは従う条件と制約として、指定のバー -ジョンか、フリーソフトウェア財団によって発行された指定のバージョン以降 -の版のどれか一つのどちらかを選ぶことが出来る。『プログラム』でライセン -スのバージョン番号が指定されていないならば、あなたは今までにフリーソフ -トウェア財団から発行されたバージョンの中から好きに選んで構わない。 - -

- - -10. -もしあなたが『プログラム』の一部を、その頒布条件がこの契約書と異なる他 -のフリーなプログラムと統合したいならば、作者に連絡して許可を求めよ。フ -リーソフトウェア財団が著作権を保有するソフトウェアについては、フリーソ -フトウェア財団に連絡せよ。私たちは、このような場合のために特別な例外を -設けることもある。私たちが決定を下すにあたっては、私たちのフリーソフト -ウェアの派生物すべてがフリーな状態に保たれるということと、一般的にソフ -トウェアの共有と再利用を促進するという二つの目標を規準に検討されるであ -ろう。 - -

無保証について

- -

- -11. - -『プログラム』は代価無しに利用が許可されるので、適切な法が認める限りに -おいて、『プログラム』に関するいかなる保証も存在しない。書面で別に述べ -る場合を除いて、著作権者、またはその他の団体は、『プログラム』を、表明 -されたか言外にかは問わず、商業的適性を保証するほのめかしやある特定の目 -的への適合性(に限られない)を含む一切の保証無しに「あるがまま」で提供す -る。『プログラム』の質と性能に関するリスクのすべてはあなたに帰属する。 -『プログラム』に欠陥があると判明した場合、あなたは必要な保守点検や補修、 -修正に要するコストのすべてを引き受けることになる。 - - -

- -12. - -適切な法か書面での同意によって命ぜられない限り、著作権者、または上記で -許可されている通りに『プログラム』を改変または再頒布したその他の団体は、 -あなたに対して『プログラム』の利用ないし利用不能で生じた通常損害や特別 -損害、偶発損害、間接損害(データの消失や不正確な処理、あなたか第三者が -被った損失、あるいは『プログラム』が他のソフトウェアと一緒に動作しない -という不具合などを含むがそれらに限らない)に一切の責任を負わない。その -ような損害が生ずる可能性について彼らが忠告されていたとしても同様である。 - -

- -

条件と制約終わり

- +

条件と制約終わり

+ + diff --git a/pandora_console/general/license/pandora_info_pt_BR.html b/pandora_console/general/license/pandora_info_pt_BR.html index b4eb7552e4..246330f30e 100644 --- a/pandora_console/general/license/pandora_info_pt_BR.html +++ b/pandora_console/general/license/pandora_info_pt_BR.html @@ -1,424 +1,457 @@ - - -Licen�a Pública Geral GNU - - - -

LICEN�A P�BLICA GERAL GNU

-

Vers�o 2, junho de 1991

-

-This is an unofficial translation of the GNU General Public License -into Brazilian Portuguese. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL -- only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Brazilian Portuguese speakers understand the GNU GPL better. -

-

-Esta � uma tradu��o n�o-oficial da Licen�a P�blica Geral GNU ("GPL -GNU") para o portugu�s do Brasil. Ela n�o foi publicada pela Free -Software Foundation, e legalmente n�o afirma os termos de distribui��o -de software que utiliza a GPL GNU -- apenas o texto original da GPL -GNU, em ingl�s, faz isso. Contudo, esperamos que esta tradu��o ajude -aos que utilizam o portugu�s do Brasil a entender melhor a GPL GNU. -

-

Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA

-

-A qualquer pessoa � permitido copiar e distribuir c�pias desse -documento de licen�a, desde que sem qualquer altera��o. -

- -

Introdu��o

- -

As licen�as de muitos software s�o desenvolvidas para restringir sua -liberdade de compartilh�-lo e mud�-lo. Contr�ria a isso, a Licen�a -P�blica Geral GNU pretende garantir sua liberdade de compartilhar e -alterar software livres -- garantindo que o software ser� livre e -gratuito para os seus usu�rios. Esta Licen�a P�blica Geral aplica-se � -maioria dos software da Free Software Foundation e a qualquer outro -programa cujo autor decida aplic�-la. (Alguns outros software da FSF -s�o cobertos pela Licen�a P�blica Geral de Bibliotecas, no entanto.) -Voc� pode aplic�-la tamb�m aos seus programas.

- -

Quando nos referimos a software livre, estamos nos referindo a -liberdade e n�o a pre�o. Nossa Licen�a P�blica Geral foi desenvolvida -para garantir que voc� tenha a liberdade de distribuir c�pias de -software livre (e cobrar por isso, se quiser); que voc� receba o -c�digo-fonte ou tenha acesso a ele, se quiser; que voc� possa mudar o -software ou utilizar partes dele em novos programas livres e -gratuitos; e que voc� saiba que pode fazer tudo isso.

- -

Para proteger seus direitos, precisamos fazer restri��es que impe�am -a qualquer um negar estes direitos ou solicitar que voc� deles -abdique. Estas restri��es traduzem-se em certas responsabilidades para -voc�, se voc� for distribuir c�pias do software ou modific�-lo.

- -

Por exemplo, se voc� distribuir c�pias de um programa, gratuitamente -ou por alguma quantia, voc� tem que fornecer aos recebedores todos os -direitos que voc� possui. Voc� tem que garantir que eles tamb�m -recebam ou possam obter o c�digo-fonte. E voc� tem que mostrar-lhes -estes termos para que eles possam conhecer seus direitos.

- -

N�s protegemos seus direitos em dois passos: (1) com copyright do -software e (2) com a oferta desta licen�a, que lhe d� permiss�o legal -para copiar, distribuir e/ou modificar o software.

- -

Al�m disso, tanto para a prote��o do autor quanto a nossa, -gostar�amos de certificar-nos que todos entendam que n�o h� qualquer -garantia nestes software livres. Se o software � modificado por algu�m -mais e passado adiante, queremos que seus recebedores saibam que o que -eles obtiveram n�o � original, de forma que qualquer problema -introduzido por terceiros n�o interfira na reputa��o do autor -original.

- -

Finalmente, qualquer programa � amea�ado constantemente por patentes -de software. Queremos evitar o perigo de que distribuidores de -software livre obtenham patentes individuais, o que tem o efeito de -tornar o programa propriet�rio. Para prevenir isso, deixamos claro que -qualquer patente tem que ser licenciada para uso livre e gratuito por -qualquer pessoa, ou ent�o que nem necessite ser licenciada. -

- -

Os termos e condi��es precisas para c�pia, distribui��o e -modifica��o se encontram abaixo:

- -

LICEN�A P�BLICA GERAL GNU TERMOS E CONDI��ES PARA C�PIA, DISTRIBUI��O E MODIFICA��O

- -

-0.Esta licen�a se aplica a qualquer programa ou outro trabalho que -contenha um aviso colocado pelo detentor dos direitos autorais -informando que aquele pode ser distribu�do sob as condi��es desta -Licen�a P�blica Geral. O "Programa" abaixo refere-se a qualquer -programa ou trabalho, e "trabalho baseado no Programa" significa tanto -o Programa em si como quaisquer trabalhos derivados, de acordo com a -lei de direitos autorais: isto quer dizer um trabalho que contenha o -Programa ou parte dele, tanto originalmente ou com modifica��es, e/ou -tradu��o para outros idiomas. (Doravante o processo de tradu��o est� -inclu�do sem limites no termo "modifica��o".) Cada licenciado � -mencionado como "voc�".

-

-Atividades outras que a c�pia, a distribui��o e modifica��o n�o est�o -cobertas por esta Licen�a; elas est�o fora de seu escopo. O ato de -executar o Programa n�o � restringido e o resultado do Programa � -coberto apenas se seu conte�do contenha trabalhos baseados no Programa -(independentemente de terem sido gerados pela execu��o do -Programa). Se isso � verdadeiro depende do que o programa faz.

- -

-1.Voc� pode copiar e distribuir c�pias fi�is do c�digo-fonte do -Programa da mesma forma que voc� o recebeu, usando qualquer meio, -deste que voc� consp�cua e apropriadamente publique em cada c�pia um -aviso de direitos autorais e uma declara��o de inexist�ncia de -garantias; mantenha intactas todos os avisos que se referem a esta -Licen�a e � aus�ncia total de garantias; e forne�a a outros -recebedores do Programa uma c�pia desta Licen�a, junto com o Programa. -

-

-Voc� pode cobrar pelo ato f�sico de transferir uma c�pia e pode, -opcionalmente, oferecer garantia em troca de pagamento. -

-

-2. Voc� pode modificar sua c�pia ou c�pias do Programa, ou qualquer -parte dele, assim gerando um trabalho baseado no Programa, e copiar e -distribuir essas modifica��es ou trabalhos sob os temos da se��o 1 -acima, desde que voc� tamb�m se enquadre em todas estas condi��es:

-
-a) Voc� tem que fazer com que os arquivos modificados levem avisos - proeminentes afirmando que voc� alterou os arquivos, incluindo a - data de qualquer altera��o. -
- -
-b) Voc� tem que fazer com que quaisquer trabalhos que voc� - distribua ou publique, e que integralmente ou em partes contenham - ou sejam derivados do Programa ou de suas partes, sejam - licenciados, integralmente e sem custo algum para quaisquer - terceiros, sob os termos desta Licen�a. -
- -
-c) Se qualquer programa modificado normalmente l� comandos - interativamente quando executados, voc� tem que fazer com que, - quando iniciado tal uso interativo da forma mais simples, seja - impresso ou mostrado um an�ncio de que n�o h� qualquer garantia - (ou ent�o que voc� fornece a garantia) e que os usu�rios podem - redistribuir o programa sob estas condi��es, ainda informando os - usu�rios como consultar uma c�pia desta Licen�a. (Exce��o: se o - Programa em si � interativo mas normalmente n�o imprime estes - tipos de an�ncios, seu trabalho baseado no Programa n�o precisa - imprimir um an�ncio.) -
-

-Estas exig�ncias aplicam-se ao trabalho modificado como um todo. Se -se��es identific�veis de tal trabalho n�o s�o derivadas do Programa, e -podem ser razoavelmente consideradas trabalhos independentes e -separados por si s�, ent�o esta Licen�a, e seus termos, n�o se aplicam -a estas se��es quando voc� distribui-las como trabalhos em -separado. Mas quando voc� distribuir as mesmas se��es como parte de um -todo que � trabalho baseado no Programa, a distribui��o como um todo -tem que se enquadrar nos termos desta Licen�a, cujas permiss�es para -outros licenciados se estendem ao todo, portanto tamb�m para cada e -toda parte independente de quem a escreveu. -

-

-Desta forma, esta se��o n�o tem a inten��o de reclamar direitos os -contestar seus direitos sobre o trabalho escrito completamente por -voc�; ao inv�s disso, a inten��o � a de exercitar o direito de -controlar a distribui��o de trabalhos, derivados ou coletivos, -baseados no Programa. -

-

-Adicionalmente, a mera adi��o ao Programa de outro trabalho n�o -baseado no Programa (ou de trabalho baseado no Programa) em um volume -de armazenamento ou meio de distribui��o n�o faz o outro trabalho -parte do escopo desta Licen�a. -

-

3. Voc� pode copiar e distribuir o Programa (ou trabalho baseado -nele, conforme descrito na Se��o 2) em c�digo-objeto ou em forma -execut�vel sob os termos das Se��es 1 e 2 acima, desde que voc� -fa�a um dos seguintes: -

-
-a)O acompanhe com o c�digo-fonte completo e em forma acess�vel - por m�quinas, que tem que ser distribu�do sob os termos das Se��es - 1 e 2 acima e em meio normalmente utilizado para o interc�mbio de - software; ou, -
- -
-b) O acompanhe com uma oferta escrita, v�lida por pelo menos tr�s - anos, de fornecer a qualquer um, com um custo n�o superior ao - custo de distribui��o f�sica do material, uma c�pia do - c�digo-fonte completo e em forma acess�vel por m�quinas, que tem - que ser distribu�do sob os termos das Se��es 1 e 2 acima e em meio - normalmente utilizado para o interc�mbio de software; ou, -
- -
-

-c) O acompanhe com a informa��o que voc� recebeu em rela��o � - oferta de distribui��o do c�digo-fonte correspondente. (Esta - alternativa � permitida somente em distribui��o n�o comerciais, e - apenas se voc� recebeu o programa em forma de c�digo-objeto ou - execut�vel, com oferta de acordo com a Subse��o b acima.) -

-
-

-O c�digo-fonte de um trabalho corresponde � forma de trabalho -preferida para se fazer modifica��es. Para um trabalho em forma -execut�vel, o c�digo-fonte completo significa todo o c�digo-fonte de -todos os m�dulos que ele cont�m, mais quaisquer arquivos de defini��o -de "interface", mais os "scripts" utilizados para se controlar a -compila��o e a instala��o do execut�vel. Contudo, como exce��o -especial, o c�digo-fonte distribu�do n�o precisa incluir qualquer -componente normalmente distribu�do (tanto em forma original quanto -bin�ria) com os maiores componentes (o compilador, o "kernel" etc.) do -sistema operacional sob o qual o execut�vel funciona, a menos que o -componente em si acompanhe o execut�vel. -

-

-Se a distribui��o do execut�vel ou c�digo-objeto � feita atrav�s da -oferta de acesso a c�pias de algum lugar, ent�o ofertar o acesso -equivalente a c�pia, do mesmo lugar, do c�digo-fonte equivale � -distribui��o do c�digo-fonte, mesmo que terceiros n�o sejam compelidos -a copiar o c�digo-fonte com o c�digo-objeto. -

-

-4. Voc� n�o pode copiar, modificar, sub-licenciar ou distribuir o -Programa, exceto de acordo com as condi��es expressas nesta -Licen�a. Qualquer outra tentativa de c�pia, modifica��o, -sub-licenciamento ou distribui��o do Programa n�o � valida, e -cancelar� automaticamente os direitos que lhe foram fornecidos por -esta Licen�a. No entanto, terceiros que de voc� receberam c�pias ou -direitos, fornecidos sob os termos desta Licen�a, n�o ter�o suas -licen�as terminadas, desde que permane�am em total concord�ncia com -ela. -

-

-5. Voc� n�o � obrigado a aceitar esta Licen�a j� que n�o a -assinou. No entanto, nada mais o dar� permiss�o para modificar ou -distribuir o Programa ou trabalhos derivados deste. Estas a��es s�o -proibidas por lei, caso voc� n�o aceite esta Licen�a. Desta forma, ao -modificar ou distribuir o Programa (ou qualquer trabalho derivado do -Programa), voc� estar� indicando sua total aceita��o desta Licen�a -para faz�-los, e todos os seus termos e condi��es para copiar, -distribuir ou modificar o Programa, ou trabalhos baseados nele. -

-

-6. Cada vez que voc� redistribuir o Programa (ou qualquer trabalho -baseado nele), os recebedores adquirir�o automaticamente do -licenciador original uma licen�a para copiar, distribuir ou modificar -o Programa, sujeitos a estes termos e condi��es. Voc� n�o poder� impor -aos recebedores qualquer outra restri��o ao exerc�cio dos direitos -ent�o adquiridos. Voc� n�o � respons�vel em garantir a concord�ncia de -terceiros a esta Licen�a. -

-

-7. Se, em conseq��ncia de decis�es judiciais ou alega��es de -infringimento de patentes ou quaisquer outras raz�es (n�o limitadas a -assuntos relacionados a patentes), condi��es forem impostas a voc� -(por ordem judicial, acordos ou outras formas) e que contradigam as -condi��es desta Licen�a, elas n�o o livram das condi��es desta -Licen�a. Se voc� n�o puder distribuir de forma a satisfazer -simultaneamente suas obriga��es para com esta Licen�a e para com as -outras obriga��es pertinentes, ent�o como conseq��ncia voc� n�o poder� -distribuir o Programa. Por exemplo, se uma licen�a de patente n�o -permitir� a redistribui��o, livre de "royalties", do Programa, por -todos aqueles que receberem c�pias direta ou indiretamente de voc�, -ent�o a �nica forma de voc� satisfazer a ela e a esta Licen�a seria a -de desistir completamente de distribuir o Programa. -

-

-Se qualquer parte desta se��o for considerada inv�lida ou n�o -aplic�vel em qualquer circunst�ncia particular, o restante da se��o se -aplica, e a se��o como um todo se aplica em outras circunst�ncias. -

-

-O prop�sito desta se��o n�o � o de induzi-lo a infringir quaisquer -patentes ou reivindica��o de direitos de propriedade outros, ou a -contestar a validade de quaisquer dessas reivindica��es; esta se��o -tem como �nico prop�sito proteger a integridade dos sistemas de -distribui��o de software livres, o que � implementado pela pr�tica de -licen�as p�blicas. V�rias pessoas t�m contribu�do generosamente e em -grande escala para os software distribu�dos usando este sistema, na -certeza de que sua aplica��o � feita de forma consistente; fica a -crit�rio do autor/doador decidir se ele ou ela est� disposto a -distribuir software utilizando outro sistema, e um licenciado n�o pode -impor qualquer escolha. -

-

-Esta se��o destina-se a tornar bastante claro o que se acredita ser -conseq��ncia do restante desta Licen�a. -

-

-8. Se a distribui��o e/ou uso do Programa s�o restringidos em certos -pa�ses por patentes ou direitos autorais, o detentor dos direitos -autorais original, e que colocou o Programa sob esta Licen�a, pode -incluir uma limita��o geogr�fica de distribui��o, excluindo aqueles -pa�ses de forma a tornar a distribui��o permitida apenas naqueles ou -entre aqueles pa�ses ent�o n�o exclu�dos. Nestes casos, esta Licen�a -incorpora a limita��o como se a mesma constasse escrita nesta Licen�a. -

-

-9. A Free Software Foundation pode publicar vers�es revisadas e/ou -novas da Licen�a P�blica Geral de tempos em tempos. Estas novas -vers�es ser�o similares em esp�rito � vers�o atual, mas podem diferir -em detalhes que resolvem novos problemas ou situa��es. -

-

-A cada vers�o � dada um n�mero distinto. Se o Programa especifica um -n�mero de vers�o espec�fico desta Licen�a que se aplica a ele e a -"qualquer nova vers�o", voc� tem a op��o de aceitar os termos e -condi��es daquela vers�o ou de qualquer outra vers�o publicada pela -Free Software Foundation. Se o programa n�o especifica um n�mero de -vers�o desta Licen�a, voc� pode escolher qualquer vers�o j� publicada -pela Free Software Foundation. -

-

-10. Se voc� pretende incorporar partes do Programa em outros -programas livres cujas condi��es de distribui��o s�o diferentes, -escreva ao autor e solicite permiss�o. Para o software que a Free -Software Foundation det�m direitos autorais, escreva � Free Software -Foundation; �s vezes n�s permitimos exce��es a este caso. Nossa -decis�o ser� guiada pelos dois objetivos de preservar a condi��o de -liberdade de todas as deriva��es do nosso software livre, e de -promover o compartilhamento e reutiliza��o de software em aspectos -gerais. -

-

-AUS�NCIA DE GARANTIAS -

-

-11. UMA VEZ QUE O PROGRAMA � LICENCIADO SEM �NUS, N�O H� QUALQUER -GARANTIA PARA O PROGRAMA, NA EXTENS�O PERMITIDA PELAS LEIS -APLIC�VEIS. EXCETO QUANDO EXPRESSADO DE FORMA ESCRITA, OS DETENTORES -DOS DIREITOS AUTORAIS E/OU TERCEIROS DISPONIBILIZAM O PROGRAMA "NO -ESTADO", SEM QUALQUER TIPO DE GARANTIAS, EXPRESSAS OU IMPL�CITAS, -INCLUINDO, MAS N�O LIMITADO A, AS GARANTIAS IMPL�CITAS DE -COMERCIALIZA��O E AS DE ADEQUA��O A QUALQUER PROP�SITO. O RISCO TOTAL -COM A QUALIDADE E DESEMPENHO DO PROGRAMA � SEU. SE O PROGRAMA SE -MOSTRAR DEFEITUOSO, VOC� ASSUME OS CUSTOS DE TODAS AS MANUTEN��ES, -REPAROS E CORRE��ES. -

-

-12. EM NENHUMA OCASI�O, A MENOS QUE EXIGIDO PELAS LEIS APLIC�VEIS OU -ACORDO ESCRITO, OS DETENTORES DOS DIREITOS AUTORAIS, OU QUALQUER OUTRA -PARTE QUE POSSA MODIFICAR E/OU REDISTRIBUIR O PROGRAMA CONFORME -PERMITIDO ACIMA, SER�O RESPONSABILIZADOS POR VOC� POR DANOS, INCLUINDO -QUALQUER DANO EM GERAL, ESPECIAL, ACIDENTAL OU CONSEQ�ENTE, -RESULTANTES DO USO OU INCAPACIDADE DE USO DO PROGRAMA (INCLUINDO, MAS -N�O LIMITADO A, A PERDA DE DADOS OU DADOS TORNADOS INCORRETOS, OU -PERDAS SOFRIDAS POR VOC� OU POR OUTRAS PARTES, OU FALHAS DO PROGRAMA -AO OPERAR COM QUALQUER OUTRO PROGRAMA), MESMO QUE TAL DETENTOR OU -PARTE TENHAM SIDO AVISADOS DA POSSIBILIDADE DE TAIS DANOS. -

-

FIM DOS TERMOS E CONDI��ES

+ + + Licen�a Pública Geral GNU + + +

LICEN�A P�BLICA GERAL GNU

+

Vers�o 2, junho de 1991

+

+ This is an unofficial translation of the GNU General Public License into + Brazilian Portuguese. It was not published by the Free Software + Foundation, and does not legally state the distribution terms for software + that uses the GNU GPL -- only the original English text of the GNU GPL + does that. However, we hope that this translation will help Brazilian + Portuguese speakers understand the GNU GPL better. +

+

+ Esta � uma tradu��o n�o-oficial da Licen�a P�blica Geral GNU ("GPL GNU") + para o portugu�s do Brasil. Ela n�o foi publicada pela Free Software + Foundation, e legalmente n�o afirma os termos de distribui��o de software + que utiliza a GPL GNU -- apenas o texto original da GPL GNU, em ingl�s, + faz isso. Contudo, esperamos que esta tradu��o ajude aos que utilizam o + portugu�s do Brasil a entender melhor a GPL GNU. +

+

+ Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, + Cambridge, MA 02139, USA +

+

+ A qualquer pessoa � permitido copiar e distribuir c�pias desse documento + de licen�a, desde que sem qualquer altera��o. +

-

Como Aplicar Estes Termos aos Seus Novos Programas

- -

Se voc� desenvolver um novo programa, e quer que ele seja utilizado -amplamente pelo p�blico, a melhor forma de alcan�ar este objetivo � -torn�-lo software livre que qualquer um pode redistribuir e alterar, -sob estes termos. -

-

Para isso, anexe os seguintes avisos ao programa. � mais seguro -anex�-los logo no in�cio de cada arquivo-fonte para refor�arem mais -efetivamente a inexist�ncia de garantias; e cada arquivo deve possuir -pelo menos a linha de "copyright" e uma indica��o de onde o texto -completo se encontra. -

-

<uma linha que forne�a o nome do programa e uma id�ia do que ele faz.> - Copyright (C) <ano> <nome do autor> -

-

Este programa � software livre; voc� pode redistribu�-lo e/ou - modific�-lo sob os termos da Licen�a P�blica Geral GNU, conforme - publicada pela Free Software Foundation; tanto a vers�o 2 da - Licen�a como (a seu crit�rio) qualquer vers�o mais nova. -

-

Este programa � distribu�do na expectativa de ser �til, mas SEM - QUALQUER GARANTIA; sem mesmo a garantia impl�cita de - COMERCIALIZA��O ou de ADEQUA��O A QUALQUER PROP�SITO EM - PARTICULAR. Consulte a Licen�a P�blica Geral GNU para obter mais - detalhes. -

-

Voc� deve ter recebido uma c�pia da Licen�a P�blica Geral GNU - junto com este programa; se n�o, escreva para a Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - 02111-1307, USA. -

-

Inclua tamb�m informa��es sobre como contact�-lo eletronicamente e por carta.

-

Se o programa � interativo, fa�a-o mostrar um aviso breve como este, ao iniciar um modo interativo: -

-

Gnomovision vers�o 69, Copyright (C) ano nome do autor - O Gnomovision n�o possui QUALQUER GARANTIA; para obter mais - detalhes digite `show w'. Ele � software livre e voc� est� - convidado a redistribui-lo sob certas condi��es; digite `show c' - para obter detalhes. -

-

Os comandos hipot�ticos `show w' e `show c' devem mostrar as partes -apropriadas da Licen�a P�blica Geral. Claro, os comandos que voc� usar -podem ser ativados de outra forma que `show w' e `show c'; eles podem -at� ser cliques do mouse ou itens de um menu -- o que melhor se -adequar ao programa. -

-

Voc� tamb�m deve obter do seu empregador (se voc� trabalha como -programador) ou escola, se houver, uma "declara��o de aus�ncia de -direitos autorais" sobre o programa, se necess�rio. Aqui est� um -exemplo; altere os nomes: -

-

Yoyodyne, Inc., aqui declara a aus�ncia de quaisquer direitos - autorais sobre o programa `Gnomovision' (que executa interpreta��es - em compiladores) escrito por James Hacker. -

-

<assinatura de Ty Coon>, 1o. de abril de 1989 -

-

Ty Con, Vice-presidente - -

-

Esta Licen�a P�blica Geral n�o permite incorporar seu programa em -programas propriet�rios. Se seu programa � uma biblioteca de -sub-rotinas, voc� deve considerar mais �til permitir ligar aplica��es -propriet�rias com a biblioteca. Se isto � o que voc� deseja, use a -Licen�a P�blica Geral de Bibliotecas GNU, ao inv�s desta Licen�a. -

- \ No newline at end of file +

Introdu��o

+ +

+ As licen�as de muitos software s�o desenvolvidas para restringir sua + liberdade de compartilh�-lo e mud�-lo. Contr�ria a isso, a Licen�a P�blica + Geral GNU pretende garantir sua liberdade de compartilhar e alterar + software livres -- garantindo que o software ser� livre e gratuito para os + seus usu�rios. Esta Licen�a P�blica Geral aplica-se � maioria dos software + da Free Software Foundation e a qualquer outro programa cujo autor decida + aplic�-la. (Alguns outros software da FSF s�o cobertos pela Licen�a + P�blica Geral de Bibliotecas, no entanto.) Voc� pode aplic�-la tamb�m aos + seus programas. +

+ +

+ Quando nos referimos a software livre, estamos nos referindo a liberdade e + n�o a pre�o. Nossa Licen�a P�blica Geral foi desenvolvida para garantir + que voc� tenha a liberdade de distribuir c�pias de software livre (e + cobrar por isso, se quiser); que voc� receba o c�digo-fonte ou tenha + acesso a ele, se quiser; que voc� possa mudar o software ou utilizar + partes dele em novos programas livres e gratuitos; e que voc� saiba que + pode fazer tudo isso. +

+ +

+ Para proteger seus direitos, precisamos fazer restri��es que impe�am a + qualquer um negar estes direitos ou solicitar que voc� deles abdique. + Estas restri��es traduzem-se em certas responsabilidades para voc�, se + voc� for distribuir c�pias do software ou modific�-lo. +

+ +

+ Por exemplo, se voc� distribuir c�pias de um programa, gratuitamente ou + por alguma quantia, voc� tem que fornecer aos recebedores todos os + direitos que voc� possui. Voc� tem que garantir que eles tamb�m recebam ou + possam obter o c�digo-fonte. E voc� tem que mostrar-lhes estes termos para + que eles possam conhecer seus direitos. +

+ +

+ N�s protegemos seus direitos em dois passos: (1) com copyright do software + e (2) com a oferta desta licen�a, que lhe d� permiss�o legal para copiar, + distribuir e/ou modificar o software. +

+ +

+ Al�m disso, tanto para a prote��o do autor quanto a nossa, gostar�amos de + certificar-nos que todos entendam que n�o h� qualquer garantia nestes + software livres. Se o software � modificado por algu�m mais e passado + adiante, queremos que seus recebedores saibam que o que eles obtiveram n�o + � original, de forma que qualquer problema introduzido por terceiros n�o + interfira na reputa��o do autor original. +

+ +

+ Finalmente, qualquer programa � amea�ado constantemente por patentes de + software. Queremos evitar o perigo de que distribuidores de software livre + obtenham patentes individuais, o que tem o efeito de tornar o programa + propriet�rio. Para prevenir isso, deixamos claro que qualquer patente tem + que ser licenciada para uso livre e gratuito por qualquer pessoa, ou ent�o + que nem necessite ser licenciada. +

+ +

+ Os termos e condi��es precisas para c�pia, distribui��o e modifica��o se + encontram abaixo: +

+ +

+ LICEN�A P�BLICA GERAL GNU TERMOS E CONDI��ES PARA C�PIA, DISTRIBUI��O E + MODIFICA��O +

+ +

+ 0.Esta licen�a se aplica a qualquer programa ou outro + trabalho que contenha um aviso colocado pelo detentor dos direitos + autorais informando que aquele pode ser distribu�do sob as condi��es desta + Licen�a P�blica Geral. O "Programa" abaixo refere-se a qualquer programa + ou trabalho, e "trabalho baseado no Programa" significa tanto o Programa + em si como quaisquer trabalhos derivados, de acordo com a lei de direitos + autorais: isto quer dizer um trabalho que contenha o Programa ou parte + dele, tanto originalmente ou com modifica��es, e/ou tradu��o para outros + idiomas. (Doravante o processo de tradu��o est� inclu�do sem limites no + termo "modifica��o".) Cada licenciado � mencionado como "voc�". +

+

+ Atividades outras que a c�pia, a distribui��o e modifica��o n�o est�o + cobertas por esta Licen�a; elas est�o fora de seu escopo. O ato de + executar o Programa n�o � restringido e o resultado do Programa � coberto + apenas se seu conte�do contenha trabalhos baseados no Programa + (independentemente de terem sido gerados pela execu��o do Programa). Se + isso � verdadeiro depende do que o programa faz. +

+ +

+ 1.Voc� pode copiar e distribuir c�pias fi�is do + c�digo-fonte do Programa da mesma forma que voc� o recebeu, usando + qualquer meio, deste que voc� consp�cua e apropriadamente publique em cada + c�pia um aviso de direitos autorais e uma declara��o de inexist�ncia de + garantias; mantenha intactas todos os avisos que se referem a esta Licen�a + e � aus�ncia total de garantias; e forne�a a outros recebedores do + Programa uma c�pia desta Licen�a, junto com o Programa. +

+

+ Voc� pode cobrar pelo ato f�sico de transferir uma c�pia e pode, + opcionalmente, oferecer garantia em troca de pagamento. +

+

+ 2. Voc� pode modificar sua c�pia ou c�pias do Programa, + ou qualquer parte dele, assim gerando um trabalho baseado no Programa, e + copiar e distribuir essas modifica��es ou trabalhos sob os temos da se��o + 1 acima, desde que voc� tamb�m se enquadre em todas estas condi��es: +

+
+
+ a) Voc� tem que fazer com que os arquivos modificados + levem avisos proeminentes afirmando que voc� alterou os arquivos, + incluindo a data de qualquer altera��o. +
+
+ +
+
+ b) Voc� tem que fazer com que quaisquer trabalhos que + voc� distribua ou publique, e que integralmente ou em partes contenham + ou sejam derivados do Programa ou de suas partes, sejam licenciados, + integralmente e sem custo algum para quaisquer terceiros, sob os termos + desta Licen�a. +
+
+ +
+
+ c) Se qualquer programa modificado normalmente l� + comandos interativamente quando executados, voc� tem que fazer com que, + quando iniciado tal uso interativo da forma mais simples, seja impresso + ou mostrado um an�ncio de que n�o h� qualquer garantia (ou ent�o que + voc� fornece a garantia) e que os usu�rios podem redistribuir o programa + sob estas condi��es, ainda informando os usu�rios como consultar uma + c�pia desta Licen�a. (Exce��o: se o Programa em si � interativo mas + normalmente n�o imprime estes tipos de an�ncios, seu trabalho baseado no + Programa n�o precisa imprimir um an�ncio.) +
+
+

+ Estas exig�ncias aplicam-se ao trabalho modificado como um todo. Se se��es + identific�veis de tal trabalho n�o s�o derivadas do Programa, e podem ser + razoavelmente consideradas trabalhos independentes e separados por si s�, + ent�o esta Licen�a, e seus termos, n�o se aplicam a estas se��es quando + voc� distribui-las como trabalhos em separado. Mas quando voc� distribuir + as mesmas se��es como parte de um todo que � trabalho baseado no Programa, + a distribui��o como um todo tem que se enquadrar nos termos desta Licen�a, + cujas permiss�es para outros licenciados se estendem ao todo, portanto + tamb�m para cada e toda parte independente de quem a escreveu. +

+

+ Desta forma, esta se��o n�o tem a inten��o de reclamar direitos os + contestar seus direitos sobre o trabalho escrito completamente por voc�; + ao inv�s disso, a inten��o � a de exercitar o direito de controlar a + distribui��o de trabalhos, derivados ou coletivos, baseados no Programa. +

+

+ Adicionalmente, a mera adi��o ao Programa de outro trabalho n�o baseado no + Programa (ou de trabalho baseado no Programa) em um volume de + armazenamento ou meio de distribui��o n�o faz o outro trabalho parte do + escopo desta Licen�a. +

+

+ 3. Voc� pode copiar e distribuir o Programa (ou trabalho + baseado nele, conforme descrito na Se��o 2) em c�digo-objeto ou em forma + execut�vel sob os termos das Se��es 1 e 2 acima, desde que voc� fa�a um + dos seguintes: +

+
+
+ a)O acompanhe com o c�digo-fonte completo e em forma + acess�vel por m�quinas, que tem que ser distribu�do sob os termos das + Se��es 1 e 2 acima e em meio normalmente utilizado para o interc�mbio de + software; ou, +
+
+ +
+
+ b) O acompanhe com uma oferta escrita, v�lida por pelo + menos tr�s anos, de fornecer a qualquer um, com um custo n�o superior ao + custo de distribui��o f�sica do material, uma c�pia do c�digo-fonte + completo e em forma acess�vel por m�quinas, que tem que ser distribu�do + sob os termos das Se��es 1 e 2 acima e em meio normalmente utilizado + para o interc�mbio de software; ou, +
+
+ +
+
+

+ c) O acompanhe com a informa��o que voc� recebeu em + rela��o � oferta de distribui��o do c�digo-fonte correspondente. (Esta + alternativa � permitida somente em distribui��o n�o comerciais, e + apenas se voc� recebeu o programa em forma de c�digo-objeto ou + execut�vel, com oferta de acordo com a Subse��o b acima.) +

+
+
+

+ O c�digo-fonte de um trabalho corresponde � forma de trabalho preferida + para se fazer modifica��es. Para um trabalho em forma execut�vel, o + c�digo-fonte completo significa todo o c�digo-fonte de todos os m�dulos + que ele cont�m, mais quaisquer arquivos de defini��o de "interface", mais + os "scripts" utilizados para se controlar a compila��o e a instala��o do + execut�vel. Contudo, como exce��o especial, o c�digo-fonte distribu�do n�o + precisa incluir qualquer componente normalmente distribu�do (tanto em + forma original quanto bin�ria) com os maiores componentes (o compilador, o + "kernel" etc.) do sistema operacional sob o qual o execut�vel funciona, a + menos que o componente em si acompanhe o execut�vel. +

+

+ Se a distribui��o do execut�vel ou c�digo-objeto � feita atrav�s da oferta + de acesso a c�pias de algum lugar, ent�o ofertar o acesso equivalente a + c�pia, do mesmo lugar, do c�digo-fonte equivale � distribui��o do + c�digo-fonte, mesmo que terceiros n�o sejam compelidos a copiar o + c�digo-fonte com o c�digo-objeto. +

+

+ 4. Voc� n�o pode copiar, modificar, sub-licenciar ou + distribuir o Programa, exceto de acordo com as condi��es expressas nesta + Licen�a. Qualquer outra tentativa de c�pia, modifica��o, sub-licenciamento + ou distribui��o do Programa n�o � valida, e cancelar� automaticamente os + direitos que lhe foram fornecidos por esta Licen�a. No entanto, terceiros + que de voc� receberam c�pias ou direitos, fornecidos sob os termos desta + Licen�a, n�o ter�o suas licen�as terminadas, desde que permane�am em total + concord�ncia com ela. +

+

+ 5. Voc� n�o � obrigado a aceitar esta Licen�a j� que n�o + a assinou. No entanto, nada mais o dar� permiss�o para modificar ou + distribuir o Programa ou trabalhos derivados deste. Estas a��es s�o + proibidas por lei, caso voc� n�o aceite esta Licen�a. Desta forma, ao + modificar ou distribuir o Programa (ou qualquer trabalho derivado do + Programa), voc� estar� indicando sua total aceita��o desta Licen�a para + faz�-los, e todos os seus termos e condi��es para copiar, distribuir ou + modificar o Programa, ou trabalhos baseados nele. +

+

+ 6. Cada vez que voc� redistribuir o Programa (ou qualquer + trabalho baseado nele), os recebedores adquirir�o automaticamente do + licenciador original uma licen�a para copiar, distribuir ou modificar o + Programa, sujeitos a estes termos e condi��es. Voc� n�o poder� impor aos + recebedores qualquer outra restri��o ao exerc�cio dos direitos ent�o + adquiridos. Voc� n�o � respons�vel em garantir a concord�ncia de terceiros + a esta Licen�a. +

+

+ 7. Se, em conseq��ncia de decis�es judiciais ou alega��es + de infringimento de patentes ou quaisquer outras raz�es (n�o limitadas a + assuntos relacionados a patentes), condi��es forem impostas a voc� (por + ordem judicial, acordos ou outras formas) e que contradigam as condi��es + desta Licen�a, elas n�o o livram das condi��es desta Licen�a. Se voc� n�o + puder distribuir de forma a satisfazer simultaneamente suas obriga��es + para com esta Licen�a e para com as outras obriga��es pertinentes, ent�o + como conseq��ncia voc� n�o poder� distribuir o Programa. Por exemplo, se + uma licen�a de patente n�o permitir� a redistribui��o, livre de + "royalties", do Programa, por todos aqueles que receberem c�pias direta ou + indiretamente de voc�, ent�o a �nica forma de voc� satisfazer a ela e a + esta Licen�a seria a de desistir completamente de distribuir o Programa. +

+

+ Se qualquer parte desta se��o for considerada inv�lida ou n�o aplic�vel em + qualquer circunst�ncia particular, o restante da se��o se aplica, e a + se��o como um todo se aplica em outras circunst�ncias. +

+

+ O prop�sito desta se��o n�o � o de induzi-lo a infringir quaisquer + patentes ou reivindica��o de direitos de propriedade outros, ou a + contestar a validade de quaisquer dessas reivindica��es; esta se��o tem + como �nico prop�sito proteger a integridade dos sistemas de distribui��o + de software livres, o que � implementado pela pr�tica de licen�as + p�blicas. V�rias pessoas t�m contribu�do generosamente e em grande escala + para os software distribu�dos usando este sistema, na certeza de que sua + aplica��o � feita de forma consistente; fica a crit�rio do autor/doador + decidir se ele ou ela est� disposto a distribuir software utilizando outro + sistema, e um licenciado n�o pode impor qualquer escolha. +

+

+ Esta se��o destina-se a tornar bastante claro o que se acredita ser + conseq��ncia do restante desta Licen�a. +

+

+ 8. Se a distribui��o e/ou uso do Programa s�o + restringidos em certos pa�ses por patentes ou direitos autorais, o + detentor dos direitos autorais original, e que colocou o Programa sob esta + Licen�a, pode incluir uma limita��o geogr�fica de distribui��o, excluindo + aqueles pa�ses de forma a tornar a distribui��o permitida apenas naqueles + ou entre aqueles pa�ses ent�o n�o exclu�dos. Nestes casos, esta Licen�a + incorpora a limita��o como se a mesma constasse escrita nesta Licen�a. +

+

+ 9. A Free Software Foundation pode publicar vers�es + revisadas e/ou novas da Licen�a P�blica Geral de tempos em tempos. Estas + novas vers�es ser�o similares em esp�rito � vers�o atual, mas podem + diferir em detalhes que resolvem novos problemas ou situa��es. +

+

+ A cada vers�o � dada um n�mero distinto. Se o Programa especifica um + n�mero de vers�o espec�fico desta Licen�a que se aplica a ele e a + "qualquer nova vers�o", voc� tem a op��o de aceitar os termos e condi��es + daquela vers�o ou de qualquer outra vers�o publicada pela Free Software + Foundation. Se o programa n�o especifica um n�mero de vers�o desta + Licen�a, voc� pode escolher qualquer vers�o j� publicada pela Free + Software Foundation. +

+

+ 10. Se voc� pretende incorporar partes do Programa em + outros programas livres cujas condi��es de distribui��o s�o diferentes, + escreva ao autor e solicite permiss�o. Para o software que a Free Software + Foundation det�m direitos autorais, escreva � Free Software Foundation; �s + vezes n�s permitimos exce��es a este caso. Nossa decis�o ser� guiada pelos + dois objetivos de preservar a condi��o de liberdade de todas as deriva��es + do nosso software livre, e de promover o compartilhamento e reutiliza��o + de software em aspectos gerais. +

+

AUS�NCIA DE GARANTIAS

+

+ 11. UMA VEZ QUE O PROGRAMA � LICENCIADO SEM �NUS, N�O H� + QUALQUER GARANTIA PARA O PROGRAMA, NA EXTENS�O PERMITIDA PELAS LEIS + APLIC�VEIS. EXCETO QUANDO EXPRESSADO DE FORMA ESCRITA, OS DETENTORES DOS + DIREITOS AUTORAIS E/OU TERCEIROS DISPONIBILIZAM O PROGRAMA "NO ESTADO", + SEM QUALQUER TIPO DE GARANTIAS, EXPRESSAS OU IMPL�CITAS, INCLUINDO, MAS + N�O LIMITADO A, AS GARANTIAS IMPL�CITAS DE COMERCIALIZA��O E AS DE + ADEQUA��O A QUALQUER PROP�SITO. O RISCO TOTAL COM A QUALIDADE E DESEMPENHO + DO PROGRAMA � SEU. SE O PROGRAMA SE MOSTRAR DEFEITUOSO, VOC� ASSUME OS + CUSTOS DE TODAS AS MANUTEN��ES, REPAROS E CORRE��ES. +

+

+ 12. EM NENHUMA OCASI�O, A MENOS QUE EXIGIDO PELAS LEIS + APLIC�VEIS OU ACORDO ESCRITO, OS DETENTORES DOS DIREITOS AUTORAIS, OU + QUALQUER OUTRA PARTE QUE POSSA MODIFICAR E/OU REDISTRIBUIR O PROGRAMA + CONFORME PERMITIDO ACIMA, SER�O RESPONSABILIZADOS POR VOC� POR DANOS, + INCLUINDO QUALQUER DANO EM GERAL, ESPECIAL, ACIDENTAL OU CONSEQ�ENTE, + RESULTANTES DO USO OU INCAPACIDADE DE USO DO PROGRAMA (INCLUINDO, MAS N�O + LIMITADO A, A PERDA DE DADOS OU DADOS TORNADOS INCORRETOS, OU PERDAS + SOFRIDAS POR VOC� OU POR OUTRAS PARTES, OU FALHAS DO PROGRAMA AO OPERAR + COM QUALQUER OUTRO PROGRAMA), MESMO QUE TAL DETENTOR OU PARTE TENHAM SIDO + AVISADOS DA POSSIBILIDADE DE TAIS DANOS. +

+

FIM DOS TERMOS E CONDI��ES

+ +

Como Aplicar Estes Termos aos Seus Novos Programas

+ +

+ Se voc� desenvolver um novo programa, e quer que ele seja utilizado + amplamente pelo p�blico, a melhor forma de alcan�ar este objetivo � + torn�-lo software livre que qualquer um pode redistribuir e alterar, sob + estes termos. +

+

+ Para isso, anexe os seguintes avisos ao programa. � mais seguro anex�-los + logo no in�cio de cada arquivo-fonte para refor�arem mais efetivamente a + inexist�ncia de garantias; e cada arquivo deve possuir pelo menos a linha + de "copyright" e uma indica��o de onde o texto completo se encontra. +

+

+ <uma linha que forne�a o nome do programa e uma id�ia do que ele + faz.> Copyright (C) <ano> <nome do autor> +

+

+ Este programa � software livre; voc� pode redistribu�-lo e/ou modific�-lo + sob os termos da Licen�a P�blica Geral GNU, conforme publicada pela Free + Software Foundation; tanto a vers�o 2 da Licen�a como (a seu crit�rio) + qualquer vers�o mais nova. +

+

+ Este programa � distribu�do na expectativa de ser �til, mas SEM QUALQUER + GARANTIA; sem mesmo a garantia impl�cita de COMERCIALIZA��O ou de + ADEQUA��O A QUALQUER PROP�SITO EM PARTICULAR. Consulte a Licen�a P�blica + Geral GNU para obter mais detalhes. +

+

+ Voc� deve ter recebido uma c�pia da Licen�a P�blica Geral GNU junto com + este programa; se n�o, escreva para a Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307, USA. +

+

+ Inclua tamb�m informa��es sobre como contact�-lo eletronicamente e por + carta. +

+

+ Se o programa � interativo, fa�a-o mostrar um aviso breve como este, ao + iniciar um modo interativo: +

+

+ Gnomovision vers�o 69, Copyright (C) ano nome do autor O Gnomovision n�o + possui QUALQUER GARANTIA; para obter mais detalhes digite `show w'. Ele � + software livre e voc� est� convidado a redistribui-lo sob certas + condi��es; digite `show c' para obter detalhes. +

+

+ Os comandos hipot�ticos `show w' e `show c' devem mostrar as partes + apropriadas da Licen�a P�blica Geral. Claro, os comandos que voc� usar + podem ser ativados de outra forma que `show w' e `show c'; eles podem at� + ser cliques do mouse ou itens de um menu -- o que melhor se adequar ao + programa. +

+

+ Voc� tamb�m deve obter do seu empregador (se voc� trabalha como + programador) ou escola, se houver, uma "declara��o de aus�ncia de direitos + autorais" sobre o programa, se necess�rio. Aqui est� um exemplo; altere os + nomes: +

+

+ Yoyodyne, Inc., aqui declara a aus�ncia de quaisquer direitos autorais + sobre o programa `Gnomovision' (que executa interpreta��es em + compiladores) escrito por James Hacker. +

+

<assinatura de Ty Coon>, 1o. de abril de 1989

+

Ty Con, Vice-presidente

+

+ Esta Licen�a P�blica Geral n�o permite incorporar seu programa em + programas propriet�rios. Se seu programa � uma biblioteca de sub-rotinas, + voc� deve considerar mais �til permitir ligar aplica��es propriet�rias com + a biblioteca. Se isto � o que voc� deseja, use a Licen�a P�blica Geral de + Bibliotecas GNU, ao inv�s desta Licen�a. +

+ + diff --git a/pandora_console/godmode/reporting/visual_console_builder.editor.js b/pandora_console/godmode/reporting/visual_console_builder.editor.js index bc573e1b92..1ab1916927 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.editor.js +++ b/pandora_console/godmode/reporting/visual_console_builder.editor.js @@ -26,4228 +26,5308 @@ var parents = {}; var obj_js_user_lines = null; - var SIZE_GRID = 16; //Const the size (for width and height) of grid. var img_handler_start; var img_handler_end; function toggle_advance_options_palette(close) { - if ($("#advance_options").css('display') == 'none') { - $("#advance_options").css('display', ''); - } - else { - $("#advance_options").css('display', 'none'); - } + if ($("#advance_options").css("display") == "none") { + $("#advance_options").css("display", ""); + } else { + $("#advance_options").css("display", "none"); + } - if (close == false) { - $("#advance_options").css('display', 'none'); - } + if (close == false) { + $("#advance_options").css("display", "none"); + } } // Main function, execute in event documentReady function visual_map_main() { - img_handler_start = "images/dot_red.png"; - img_handler_end = "images/dot_green.png"; - get_image_url(img_handler_start).done(function (data) { - img_handler_start = data; - }); - get_image_url(img_handler_end).done(function (data) { - img_handler_end = data; - }); + img_handler_start = "images/dot_red.png"; + img_handler_end = "images/dot_green.png"; + get_image_url(img_handler_start).done(function(data) { + img_handler_start = data; + }); + get_image_url(img_handler_end).done(function(data) { + img_handler_end = data; + }); - //Get the list of posible parents - parents = Base64.decode($("input[name='parents_load']").val()); - parents = eval("(" + parents + ")"); + //Get the list of posible parents + parents = Base64.decode($("input[name='parents_load']").val()); + parents = eval("(" + parents + ")"); - eventsBackground(); - eventsItems(); + eventsBackground(); + eventsItems(); - //Fixed to wait the load of images. - $(window).on('load', function() { - $('#module').change(function(){ - var txt = $("#module").val(); - if(selectedItem == 'simple_value' || creationItem == 'simple_value'){ - $.ajax({ - async:false, - type: "POST", - url: "ajax.php", - data: {"page" : "general/check_image_module", - "get_image" : txt, - }, - success: function(data) { - if(data == 0){ - $("#data_image_check").html('Off'); - $('#data_image_container').css('display','none'); - $('#data_image_check').css('display','none'); - $('#data_image_check_label').css('display','none'); - $('.block_tinymce').remove(); - $('#process_value_row').css('display','table-row'); - if($('#process_value').val() != '0'){ - $('#period_row').css('display','table-row'); - } - } - else{ - $('#data_image_container').css('display','inline'); - $('#data_image_check').css('display','inline'); - $('#data_image_check_label').css('display','inline'); - $("#data_image_check").html('On'); - $('#process_value_row').css('display','none'); - $('#period_row').css('display','none'); - $('#text-label_ifr').contents().find('#tinymce').html('_VALUE_'); - $('.block_tinymce').remove(); - $('#label_row').append('
'); - } - } - }); - } - }); - - - // Begin - Background label color changer - - $( "#text-label_ifr" ).contents().find( "body" ).bind('mousewheel', function(e){ - e.preventDefault(); - - if($( "#text-label_ifr" ).contents().find( "body" ).css('background-color') == 'rgb(211, 211, 211)'){ - $( "#text-label_ifr" ).contents().find( "body" ).css('background-color','white'); - } - else{ - $( "#text-label_ifr" ).contents().find( "body" ).css('background-color','lightgray'); - } + //Fixed to wait the load of images. + $(window).on("load", function() { + $("#module").change(function() { + var txt = $("#module").val(); + if (selectedItem == "simple_value" || creationItem == "simple_value") { + $.ajax({ + async: false, + type: "POST", + url: "ajax.php", + data: { page: "general/check_image_module", get_image: txt }, + success: function(data) { + if (data == 0) { + $("#data_image_check").html("Off"); + $("#data_image_container").css("display", "none"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $(".block_tinymce").remove(); + $("#process_value_row").css("display", "table-row"); + if ($("#process_value").val() != "0") { + $("#period_row").css("display", "table-row"); + } + } else { + $("#data_image_container").css("display", "inline"); + $("#data_image_check").css("display", "inline"); + $("#data_image_check_label").css("display", "inline"); + $("#data_image_check").html("On"); + $("#process_value_row").css("display", "none"); + $("#period_row").css("display", "none"); + $("#text-label_ifr") + .contents() + .find("#tinymce") + .html("_VALUE_"); + $(".block_tinymce").remove(); + $("#label_row").append( + '
' + ); + } + } + }); + } }); - - // End - Background label color changer - - $('#radiobtn0001').click(function(){ - $("#custom_graph option[value=0]").prop("selected", true); - }); - - $('.labelpos').click(function(event) { - if($("#hidden-metaconsole").val() == 1){ - $("#labelposup img").attr('src','../../images/label_up.png'); - $("#labelposdown img").attr('src','../../images/label_down.png'); - $("#labelposleft img").attr('src','../../images/label_left.png'); - $("#labelposright img").attr('src','../../images/label_right.png'); - $('.labelpos').attr('sel','no'); - $("#"+$(this).attr('id')+" img").attr('src','../../images/label_'+$(this).attr('id').replace('labelpos','')+'_2.png'); - $("#"+$(this).attr('id')).attr('sel','yes'); - } - else{ - $("#labelposup img").attr('src','images/label_up.png'); - $("#labelposdown img").attr('src','images/label_down.png'); - $("#labelposleft img").attr('src','images/label_left.png'); - $("#labelposright img").attr('src','images/label_right.png'); - $('.labelpos').attr('sel','no'); - $("#"+$(this).attr('id')+" img").attr('src','images/label_'+$(this).attr('id').replace('labelpos','')+'_2.png'); - $("#"+$(this).attr('id')).attr('sel','yes'); - } - - }); - bindColorRangeEvents(); + // Begin - Background label color changer - draw_lines(lines, 'background', true); + $("#text-label_ifr") + .contents() + .find("body") + .bind("mousewheel", function(e) { + e.preventDefault(); - draw_user_lines("", 0, 0, 0 , 0, 0, true); + if ( + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color") == "rgb(211, 211, 211)" + ) { + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color", "white"); + } else { + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color", "lightgray"); + } + }); - //~ center_labels(); - }); + // End - Background label color changer - obj_js_user_lines = new jsGraphics("background"); + $("#radiobtn0001").click(function() { + $("#custom_graph option[value=0]").prop("selected", true); + }); - $("input[name='radio_choice']").on('change', function() { - var radio_value = $("input[name='radio_choice']:checked").val(); + $(".labelpos").click(function(event) { + if ($("#hidden-metaconsole").val() == 1) { + $("#labelposup img").attr("src", "../../images/label_up.png"); + $("#labelposdown img").attr("src", "../../images/label_down.png"); + $("#labelposleft img").attr("src", "../../images/label_left.png"); + $("#labelposright img").attr("src", "../../images/label_right.png"); + $(".labelpos").attr("sel", "no"); + $("#" + $(this).attr("id") + " img").attr( + "src", + "../../images/label_" + + $(this) + .attr("id") + .replace("labelpos", "") + + "_2.png" + ); + $("#" + $(this).attr("id")).attr("sel", "yes"); + } else { + $("#labelposup img").attr("src", "images/label_up.png"); + $("#labelposdown img").attr("src", "images/label_down.png"); + $("#labelposleft img").attr("src", "images/label_left.png"); + $("#labelposright img").attr("src", "images/label_right.png"); + $(".labelpos").attr("sel", "no"); + $("#" + $(this).attr("id") + " img").attr( + "src", + "images/label_" + + $(this) + .attr("id") + .replace("labelpos", "") + + "_2.png" + ); + $("#" + $(this).attr("id")).attr("sel", "yes"); + } + }); - if ((creationItem == 'module_graph') || (selectedItem == 'module_graph')) { - if (radio_value == "module_graph") { - $("#custom_graph_row").css('display', 'none'); - $("#agent_row").css('display', ''); - $("#module_row").css('display', ''); - $("#type_graph").css('display', ''); - } - else { - $("#custom_graph_row").css('display', ''); - $("#agent_row").css('display', 'none'); - $("#module_row").css('display', 'none'); - $("#type_graph").css('display', 'none'); - } - } - }); + bindColorRangeEvents(); - //Resize the view to adapt the screen size. - if ($("#main").length) { - //Console - $("#frame_view").height($("#main").height() - 75); - } - else { - //Metaconsole - $("#frame_view").height($("#page").height() - 75); - } + draw_lines(lines, "background", true); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + + //~ center_labels(); + }); + + obj_js_user_lines = new jsGraphics("background"); + + $("input[name='radio_choice']").on("change", function() { + var radio_value = $("input[name='radio_choice']:checked").val(); + + if (creationItem == "module_graph" || selectedItem == "module_graph") { + if (radio_value == "module_graph") { + $("#custom_graph_row").css("display", "none"); + $("#agent_row").css("display", ""); + $("#module_row").css("display", ""); + $("#type_graph").css("display", ""); + } else { + $("#custom_graph_row").css("display", ""); + $("#agent_row").css("display", "none"); + $("#module_row").css("display", "none"); + $("#type_graph").css("display", "none"); + } + } + }); + + //Resize the view to adapt the screen size. + if ($("#main").length) { + //Console + $("#frame_view").height($("#main").height() - 75); + } else { + //Metaconsole + $("#frame_view").height($("#page").height() - 75); + } } function cancel_button_palette_callback() { - if (is_opened_palette) { - toggle_item_palette(); - } + if (is_opened_palette) { + toggle_item_palette(); + } } function get_url_ajax() { - if (is_metaconsole()) { - return "../../ajax.php"; - } - else { - return "ajax.php"; - } + if (is_metaconsole()) { + return "../../ajax.php"; + } else { + return "ajax.php"; + } } var metaconsole = null; function is_metaconsole() { - if (metaconsole === null) - metaconsole = $("input[name='metaconsole']").val(); + if (metaconsole === null) metaconsole = $("input[name='metaconsole']").val(); - if (metaconsole != 0) - return true; - else - return false; + if (metaconsole != 0) return true; + else return false; } function update_button_palette_callback() { + var values = {}; - var values = {}; + values = readFields(); - values = readFields(); + // TODO VALIDATE DATA + switch (selectedItem) { + case "background": + if (values["width"] < 1024 || values["height"] < 768) { + alert("Min allowed size is 1024x768"); + return false; + } - // TODO VALIDATE DATA - switch (selectedItem) { - case 'background': - if(values['width'] < 1024 || values['height'] < 768){ - alert('Min allowed size is 1024x768'); - return false; - } + if (values["width"] == 0 && values["height"] == 0) { + values["width"] = $("#hidden-background_original_width").val(); + values["height"] = $("#hidden-background_original_height").val(); + } + $("#background").css("width", values["width"]); + $("#background").css("height", values["height"]); - if(values['width'] == 0 && values['height'] == 0) { - values['width'] = - $("#hidden-background_original_width").val(); - values['height'] = - $("#hidden-background_original_height").val(); - } - $("#background").css('width', values['width']); - $("#background").css('height', values['height']); + var image = values["background"]; + $("#background_img").attr("src", "images/spinner.gif"); + set_image("background", null, image); - var image = values['background']; - $("#background_img").attr('src', "images/spinner.gif"); - set_image("background", null, image); + idElement = 0; + break; + case "box_item": + if ($("input[name=width_box]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height_box]").val() == "") { + alert("Undefined height"); + return false; + } - idElement = 0; - break; - case 'box_item': - if($('input[name=width_box]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height_box]').val() == ''){ - alert('Undefined height'); - return false; - } + $("#" + idItem + " div").css("background-color", values["fill_color"]); + $("#" + idItem + " div").css("border-color", values["border_color"]); + $("#" + idItem + " div").css( + "border-width", + values["border_width"] + "px" + ); - $("#" + idItem + " div").css('background-color', values['fill_color']); - $("#" + idItem + " div").css('border-color', values['border_color']); - $("#" + idItem + " div").css('border-width', values['border_width'] + "px"); + if (values["height_box"] == 0 || values["width_box"] == 0) { + $("#" + idItem + " div").css("width", "300px"); + $("#" + idItem + " div").css("height", "180px"); + } else { + $("#" + idItem + " div").css("height", values["height_box"] + "px"); + $("#" + idItem + " div").css("width", values["width_box"] + "px"); + } + break; + case "group_item": + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" && + values["show_statistics"] == false + ) { + alert("Undefined image"); + return false; + } - if(values['height_box']==0 || values['width_box']==0){ - $("#" + idItem + " div").css('width', "300px"); - $("#" + idItem + " div").css('height', "180px"); - } - else{ - $("#" + idItem + " div").css('height', values['height_box'] + "px"); - $("#" + idItem + " div").css('width', values['width_box'] + "px"); - } - break; - case 'group_item': - if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined image'); - return false; - } + $("#text_" + idItem).html(values["label"]); - $("#text_" + idItem).html(values['label']); + if (values["show_statistics"] == 1) { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png") + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png") + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png"); + } - if(values['show_statistics'] == 1){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } + $("#" + idItem).append($image); + } - $('#'+idItem).append($image); - } + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ); + } - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['image'] != '' && values['image'] != 'none'){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } + $("#" + idItem).append($image); + } - $('#'+idItem).append($image); - } + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + $("#image_" + idItem).remove(); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + } + break; + case "static_graph": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" + ) { + alert("Undefined image"); + return false; + } - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - $("#image_" + idItem).remove(); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - } - break; - case 'static_graph': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - if(((values['image'] == '' || values['image'] == 'none') && (values['label'] == ''))){ - alert('Undefined image'); - return false; - } + $("#text_" + idItem).html(values["label"]); - $("#text_" + idItem).html(values['label']); + if (values["show_statistics"] == 1) { + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ); + } + $("#" + idItem).append($image); + } - if(values['show_statistics'] == 1){ - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['image'] != '' && values['image'] != 'none'){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } - $('#'+idItem).append($image); - } + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + $("#image_" + idItem).remove(); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + } + break; + case "percentile_bar": + case "percentile_item": + if ($("input[name=width_percentile]").val() == "") { + alert("Undefined width"); + return false; + } - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - $("#image_" + idItem).remove(); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - } - break; - case 'percentile_bar': - case 'percentile_item': - if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); - return false; - } + if ($("input[name=height_percentile]").val() == "") { + alert("Undefined height"); + return false; + } - if($('input[name=height_percentile]').val() == ''){ - alert('Undefined height'); - return false; - } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); + if (values["type_percentile"] == "bubble") { + setPercentileBubble(idItem, values); + } else if (values["type_percentile"] == "circular_progress_bar") { + setPercentileCircular(idItem, values); + } else if ( + values["type_percentile"] == "interior_circular_progress_bar" + ) { + setPercentileInteriorCircular(idItem, values); + } else { + setPercentileBar(idItem, values); + } - if (values['type_percentile'] == 'bubble') { - setPercentileBubble(idItem, values); - } - else if (values['type_percentile'] == 'circular_progress_bar') { - setPercentileCircular(idItem, values); - } - else if (values['type_percentile'] == 'interior_circular_progress_bar') { - setPercentileInteriorCircular(idItem, values); - } - else { - setPercentileBar(idItem, values); - } + break; + case "module_graph": + if ($("#dir_items").html() == "horizontal") { + if ( + parseInt($("#text-left").val()) + + parseInt( + $("input[name=height_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("width")) || + parseInt($("#text-left").val()) + + parseInt( + $("input[name=width_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("width")) + ) { + alert( + $("#count_items").html() + + " joined graph items are wider than background" + ); + return false; + } + } - break; - case 'module_graph': - if($('#dir_items').html() == 'horizontal'){ - if(parseInt($('#text-left').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width')) - || parseInt($('#text-left').val()) + (parseInt($('input[name=width_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width'))){ - - alert($('#count_items').html()+' joined graph items are wider than background'); - return false; - - } - } - - if($('#dir_items').html() == 'vertical'){ - if(parseInt($('#text-top').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('height'))){ - alert($('#count_items').html()+' joined graph items are higher than background'); - return false; - - } - } - - if($('input[name=width_module_graph]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height_module_graph]').val() == ''){ - alert('Undefined height'); - return false; - } - if($('#custom_graph_row').css('display') != 'none' && $("#custom_graph option:selected").html() == 'None'){ - alert('Undefined graph'); - return false; - } - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - setModuleGraph(idItem); - break; - case 'bars_graph': - if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); - return false; - } + if ($("#dir_items").html() == "vertical") { + if ( + parseInt($("#text-top").val()) + + parseInt( + $("input[name=height_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("height")) + ) { + alert( + $("#count_items").html() + + " joined graph items are higher than background" + ); + return false; + } + } - if($('input[name=bars_graph_height]').val() == ''){ - alert('Undefined height'); - return false; - } - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - - setBarsGraph(idItem, values); - break; - - case 'clock': - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - setClock(idItem, values); - break; - - case 'auto_sla_graph': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); + if ($("input[name=width_module_graph]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height_module_graph]").val() == "") { + alert("Undefined height"); + return false; + } + if ( + $("#custom_graph_row").css("display") != "none" && + $("#custom_graph option:selected").html() == "None" + ) { + alert("Undefined graph"); + return false; + } - setEventsBar(idItem, values); - break; - case 'donut_graph': - $("#image_" + idItem).attr("src", "images/spinner.gif"); + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + setModuleGraph(idItem); + break; + case "bars_graph": + if ($("input[name=width_percentile]").val() == "") { + alert("Undefined width"); + return false; + } - setDonutsGraph(idItem, values); - break; - case 'simple_value': - $("#" + idItem).html(values['label']); - - if($("#data_image_check").html() == "On"){ - $("#text_" + idItem).html(''); - $("#" + idItem).html(''); - } - else{ - $("#text_" + idItem).html( - '
'+values["label"]+'
' - ) - $("#" + idItem).html( - '
'+values["label"]+'
' - ) - } - break; - case 'label': - $("#text_" + idItem).html(values['label']); - break; - case 'icon': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - if(values['image'] == '' || values['image'] == 'none'){ - alert('Undefined image'); - return false; - } - $("#image_" + idItem).attr('src', "images/spinner.gif"); - if ((values['width'] == 0) || (values['height'] == 0)) { - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - var image = values['image'] + ".png"; - set_image("image", idItem, image); - break; - default: - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - //Maybe save in any Enterprise item. - if (typeof(enterprise_update_button_palette_callback) == 'function') { - enterprise_update_button_palette_callback(values); - } + if ($("input[name=bars_graph_height]").val() == "") { + alert("Undefined height"); + return false; + } - break; - - } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); - updateDB(selectedItem, idItem , values); + setBarsGraph(idItem, values); + break; - toggle_item_palette(); - - if(values['label_position']=='left'){ - $("#" + idItem + ' table').css('float','left'); - $("#" + idItem + ' img').css('float','right'); - $("#" + idItem + ' img').css('margin-left',''); - $("#" + idItem + ' table').css('height',$("#" + idItem+ ' img').css('height')); - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' img').css('margin-top',(parseInt($("#" + idItem).css('height'))/2)-(parseInt($("#" + idItem + " img").css('height'))/2)+'px'); - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='right'){ - $("#" + idItem + ' table').css('float','right'); - $("#" + idItem + ' img').css('float','left'); - $("#" + idItem + ' img').css('margin-left',''); - $("#" + idItem + ' table').css('height',$("#" + idItem+ ' img').css('height')); - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' img').css('margin-top',(parseInt($("#" + idItem).css('height'))/2)-(parseInt($("#" + idItem + " img").css('height'))/2)+'px'); - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='down'){ - $("#" + idItem + ' table').css('float',''); - $("#" + idItem + ' img').css('float',''); - var tempoimg = $('#' + idItem + ' table').clone(); - $('#' + idItem + ' table').remove(); - $('#' + idItem).append(tempoimg); - $("#" + idItem + ' table').css('height',''); - if (selectedItem != 'simple_value') { - $("#" + idItem + ' table').css('width','70'); - $("#" + idItem + ' span').css('width','70'); - } - else { - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' table').css('text-align','center'); - $("#" + idItem + ' span').css('width',''); - } - $("#" + idItem + ' img').css('margin-top',''); - - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='up'){ - $("#" + idItem + ' table').css('float',''); - $("#" + idItem + ' img').css('float',''); - var tempoimg = $('#' + idItem + ' img').clone(); - $('#' + idItem + ' img').remove(); - $('#' + idItem).append(tempoimg); - $("#" + idItem + ' table').css('height',''); - if (selectedItem != 'simple_value') { - $("#" + idItem + ' table').css('width','70'); - $("#" + idItem + ' span').css('width','70'); - } - else { - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' table').css('text-align','center'); - $("#" + idItem + ' span').css('width',''); - } - $("#" + idItem + ' img').css('margin-top',''); + case "clock": + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + setClock(idItem, values); + break; - $("#" + idItem + ' > p').remove(); - } + case "auto_sla_graph": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + + setEventsBar(idItem, values); + break; + case "donut_graph": + $("#image_" + idItem).attr("src", "images/spinner.gif"); + + setDonutsGraph(idItem, values); + break; + case "simple_value": + $("#" + idItem).html(values["label"]); + + if ($("#data_image_check").html() == "On") { + $("#text_" + idItem).html( + '' + ); + $("#" + idItem).html( + '' + ); + } else { + $("#text_" + idItem).html( + '
' + + values["label"] + + "
" + ); + $("#" + idItem).html( + '
' + + values["label"] + + "
" + ); + } + break; + case "label": + $("#text_" + idItem).html(values["label"]); + break; + case "icon": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + if (values["image"] == "" || values["image"] == "none") { + alert("Undefined image"); + return false; + } + $("#image_" + idItem).attr("src", "images/spinner.gif"); + if (values["width"] == 0 || values["height"] == 0) { + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + var image = values["image"] + ".png"; + set_image("image", idItem, image); + break; + default: + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + //Maybe save in any Enterprise item. + if (typeof enterprise_update_button_palette_callback == "function") { + enterprise_update_button_palette_callback(values); + } + + break; + } + + updateDB(selectedItem, idItem, values); + + toggle_item_palette(); + + if (values["label_position"] == "left") { + $("#" + idItem + " table").css("float", "left"); + $("#" + idItem + " img").css("float", "right"); + $("#" + idItem + " img").css("margin-left", ""); + $("#" + idItem + " table").css( + "height", + $("#" + idItem + " img").css("height") + ); + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " img").css( + "margin-top", + parseInt($("#" + idItem).css("height")) / 2 - + parseInt($("#" + idItem + " img").css("height")) / 2 + + "px" + ); + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "right") { + $("#" + idItem + " table").css("float", "right"); + $("#" + idItem + " img").css("float", "left"); + $("#" + idItem + " img").css("margin-left", ""); + $("#" + idItem + " table").css( + "height", + $("#" + idItem + " img").css("height") + ); + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " img").css( + "margin-top", + parseInt($("#" + idItem).css("height")) / 2 - + parseInt($("#" + idItem + " img").css("height")) / 2 + + "px" + ); + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "down") { + $("#" + idItem + " table").css("float", ""); + $("#" + idItem + " img").css("float", ""); + var tempoimg = $("#" + idItem + " table").clone(); + $("#" + idItem + " table").remove(); + $("#" + idItem).append(tempoimg); + $("#" + idItem + " table").css("height", ""); + if (selectedItem != "simple_value") { + $("#" + idItem + " table").css("width", "70"); + $("#" + idItem + " span").css("width", "70"); + } else { + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " table").css("text-align", "center"); + $("#" + idItem + " span").css("width", ""); + } + $("#" + idItem + " img").css("margin-top", ""); + + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "up") { + $("#" + idItem + " table").css("float", ""); + $("#" + idItem + " img").css("float", ""); + var tempoimg = $("#" + idItem + " img").clone(); + $("#" + idItem + " img").remove(); + $("#" + idItem).append(tempoimg); + $("#" + idItem + " table").css("height", ""); + if (selectedItem != "simple_value") { + $("#" + idItem + " table").css("width", "70"); + $("#" + idItem + " span").css("width", "70"); + } else { + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " table").css("text-align", "center"); + $("#" + idItem + " span").css("width", ""); + } + $("#" + idItem + " img").css("margin-top", ""); + + $("#" + idItem + " > p").remove(); + } } function readFields() { - - $("#text-label_ifr").contents().find("p").css('overflow','hidden'); - metaconsole = $("input[name='metaconsole']").val(); - var values = {}; - values['label'] = $("input[name=label]").val(); - var text = tinymce.get('text-label').getContent(); - values['label'] = text; + $("#text-label_ifr") + .contents() + .find("p") + .css("overflow", "hidden"); + metaconsole = $("input[name='metaconsole']").val(); + var values = {}; + values["label"] = $("input[name=label]").val(); + var text = tinymce.get("text-label").getContent(); + values["label"] = text; - if ($("input[name=percentile_label]").val().length > 0) { - values['percentile_label_color'] = $("input[name=percentile_label_color]").val(); - values['label'] = "" + $("input[name=percentile_label]").val() + ""; - } + if ($("input[name=percentile_label]").val().length > 0) { + values["percentile_label_color"] = $( + "input[name=percentile_label_color]" + ).val(); + values["label"] = + "" + + $("input[name=percentile_label]").val() + + ""; + } - values['line-height'] = $("#text-label_ifr").contents().find("p").css('line-height'); - values['type_graph'] = $("select[name=type_graph]").val(); - values['image'] = $("select[name=image]").val(); - values['background_color'] = $("select[name=background_color]").val(); - values['left'] = $("input[name=left]").val(); - values['top'] = $("input[name=top]").val(); - values['agent'] = $("input[name=agent]").val(); - values['id_agent'] = $("input[name=id_agent]").val(); - values['agent_string'] = $("input[name=agent_string]").val(); - values['id_agent_string'] = $("input[name=id_agent_string]").val(); - values['module'] = $("select[name=module]").val(); - values['process_simple_value'] = $("select[name=process_value]").val(); - values['background'] = $("#background_image").val(); - values['period'] = undefined != $("#hidden-period").val() ? $("#hidden-period").val() : $("#period").val(); - values['width'] = $("input[name=width]").val(); - values['width_data_image'] = $("#data_image_width").val(); - if(selectedItem == 'simple_value' || creationItem == 'simple_value'){ - if(values['width_data_image'] != 0){ - values['width'] = values['width_data_image']; - } - } - values['height'] = $("input[name=height]").val(); - values['bars_graph_type'] = $("select[name=bars_graph_type]").val(); - values['parent'] = $("select[name=parent]").val(); - values['map_linked'] = $("select[name=map_linked]").val(); - values['linked_map_node_id'] = $("input[name=linked_map_node_id]").val(); - values['linked_map_status_calculation_type'] = $("select[name=linked_map_status_calculation_type]").val(); - values['map_linked_weight'] = $("input[name=map_linked_weight]").val(); - values['linked_map_status_service_critical'] = $("input[name=linked_map_status_service_critical]").val(); - values['linked_map_status_service_warning'] = $("input[name=linked_map_status_service_warning]").val(); - values['element_group'] = $("select[name=element_group]").val(); - values['width_percentile'] = $("input[name=width_percentile]").val(); - values['bars_graph_height'] = $("input[name=bars_graph_height]").val(); - values['max_percentile'] = parseInt($("input[name=max_percentile]").val()); - values['width_module_graph'] = $("input[name=width_module_graph]").val(); - values['height_module_graph'] = $("input[name=height_module_graph]").val(); - values['event_max_time_row'] = $("select[name=event_max_time_row]").val(); - values['type_percentile'] = $("select[name=type_percentile]").val(); - values['percentile_color'] = $("input[name=percentile_color]").val(); - values['percentile_label'] = $("input[name=percentile_label]").val(); - values['value_show'] = $("select[name=value_show]").val(); - - values['enable_link'] = $("input[name=enable_link]").is(':checked') ? 1 : 0; - values['id_group'] = $("select[name=group]").val(); - values['id_custom_graph'] = $("#custom_graph option:selected").val(); - values['width_box'] = parseInt( - $("input[name='width_box']").val()); - values['height_box'] = parseInt( - $("input[name='height_box']").val()); - values['border_color'] = $("input[name='border_color']").val(); - values['resume_color'] = $("input[name='resume_color']").val(); - values['grid_color'] = $("input[name='grid_color']").val(); - values['border_width'] = parseInt( - $("input[name='border_width']").val()); - values['fill_color'] = $("input[name='fill_color']").val(); - values['line_width'] = parseInt( - $("input[name='line_width']").val()); - values['line_color'] = $("input[name='line_color']").val(); - values['label_position'] = $(".labelpos[sel=yes]").attr('position'); - values['show_statistics'] = $("input[name=show_statistics]").is(':checked') ? 1 : 0; - values['show_on_top'] = $("input[name=show_on_top]").is(':checked') ? 1 : 0; - values['time_format'] = $("select[name=time_format]").val(); - values['timezone'] = $("select[name=timezone]").val(); - values['clock_animation'] = $("select[name=clock_animation]").val(); - values['show_last_value'] = $("select[name=last_value]").val(); - - // Color Cloud values - if (selectedItem == "color_cloud" || creationItem == "color_cloud") { - var diameter = $("input[name=diameter]").val(); - values["diameter"] = values["width"] = values["height"] = diameter; - var defaultColor = $("input[name=default_color]").val(); - values["default_color"] = defaultColor; + values["line-height"] = $("#text-label_ifr") + .contents() + .find("p") + .css("line-height"); + values["type_graph"] = $("select[name=type_graph]").val(); + values["image"] = $("select[name=image]").val(); + values["background_color"] = $("select[name=background_color]").val(); + values["left"] = $("input[name=left]").val(); + values["top"] = $("input[name=top]").val(); + values["agent"] = $("input[name=agent]").val(); + values["id_agent"] = $("input[name=id_agent]").val(); + values["agent_string"] = $("input[name=agent_string]").val(); + values["id_agent_string"] = $("input[name=id_agent_string]").val(); + values["module"] = $("select[name=module]").val(); + values["process_simple_value"] = $("select[name=process_value]").val(); + values["background"] = $("#background_image").val(); + values["period"] = + undefined != $("#hidden-period").val() + ? $("#hidden-period").val() + : $("#period").val(); + values["width"] = $("input[name=width]").val(); + values["width_data_image"] = $("#data_image_width").val(); + if (selectedItem == "simple_value" || creationItem == "simple_value") { + if (values["width_data_image"] != 0) { + values["width"] = values["width_data_image"]; + } + } + values["height"] = $("input[name=height]").val(); + values["bars_graph_type"] = $("select[name=bars_graph_type]").val(); + values["parent"] = $("select[name=parent]").val(); + values["map_linked"] = $("select[name=map_linked]").val(); + values["linked_map_node_id"] = $("input[name=linked_map_node_id]").val(); + values["linked_map_status_calculation_type"] = $( + "select[name=linked_map_status_calculation_type]" + ).val(); + values["map_linked_weight"] = $("input[name=map_linked_weight]").val(); + values["linked_map_status_service_critical"] = $( + "input[name=linked_map_status_service_critical]" + ).val(); + values["linked_map_status_service_warning"] = $( + "input[name=linked_map_status_service_warning]" + ).val(); + values["element_group"] = $("select[name=element_group]").val(); + values["width_percentile"] = $("input[name=width_percentile]").val(); + values["bars_graph_height"] = $("input[name=bars_graph_height]").val(); + values["max_percentile"] = parseInt($("input[name=max_percentile]").val()); + values["width_module_graph"] = $("input[name=width_module_graph]").val(); + values["height_module_graph"] = $("input[name=height_module_graph]").val(); + values["event_max_time_row"] = $("select[name=event_max_time_row]").val(); + values["type_percentile"] = $("select[name=type_percentile]").val(); + values["percentile_color"] = $("input[name=percentile_color]").val(); + values["percentile_label"] = $("input[name=percentile_label]").val(); + values["value_show"] = $("select[name=value_show]").val(); - // Ranges - $('input[name="color_range_from_values[]"]').each(function (index, element) { - values["color_range_from_values[" + index + "]"] = $(element).val(); - }); - $('input[name="color_range_to_values[]"]').each(function (index, element) { - values["color_range_to_values[" + index + "]"] = $(element).val(); - }); - $('input[name="color_range_color_values[]"]').each(function (index, element) { - values["color_range_colors[" + index + "]"] = $(element).val(); - }); - } + values["enable_link"] = $("input[name=enable_link]").is(":checked") ? 1 : 0; + values["id_group"] = $("select[name=group]").val(); + values["id_custom_graph"] = $("#custom_graph option:selected").val(); + values["width_box"] = parseInt($("input[name='width_box']").val()); + values["height_box"] = parseInt($("input[name='height_box']").val()); + values["border_color"] = $("input[name='border_color']").val(); + values["resume_color"] = $("input[name='resume_color']").val(); + values["grid_color"] = $("input[name='grid_color']").val(); + values["border_width"] = parseInt($("input[name='border_width']").val()); + values["fill_color"] = $("input[name='fill_color']").val(); + values["line_width"] = parseInt($("input[name='line_width']").val()); + values["line_color"] = $("input[name='line_color']").val(); + values["label_position"] = $(".labelpos[sel=yes]").attr("position"); + values["show_statistics"] = $("input[name=show_statistics]").is(":checked") + ? 1 + : 0; + values["show_on_top"] = $("input[name=show_on_top]").is(":checked") ? 1 : 0; + values["time_format"] = $("select[name=time_format]").val(); + values["timezone"] = $("select[name=timezone]").val(); + values["clock_animation"] = $("select[name=clock_animation]").val(); + values["show_last_value"] = $("select[name=last_value]").val(); - if (is_metaconsole()) { - values['metaconsole'] = 1; - values['id_agent'] = $("#hidden-agent").val(); - values['server_name'] = $("#id_server_name").val(); - values['server_id'] = $("input[name='id_server_metaconsole']").val(); - } - else { - values['metaconsole'] = 0; - } + // Color Cloud values + if (selectedItem == "color_cloud" || creationItem == "color_cloud") { + var diameter = $("input[name=diameter]").val(); + values["diameter"] = values["width"] = values["height"] = diameter; + var defaultColor = $("input[name=default_color]").val(); + values["default_color"] = defaultColor; - if (typeof(enterprise_readFields) == 'function') { - //The parameter is a object and the function can change or add - //attributes. - enterprise_readFields(values); - } + // Ranges + $('input[name="color_range_from_values[]"]').each(function(index, element) { + values["color_range_from_values[" + index + "]"] = $(element).val(); + }); + $('input[name="color_range_to_values[]"]').each(function(index, element) { + values["color_range_to_values[" + index + "]"] = $(element).val(); + }); + $('input[name="color_range_color_values[]"]').each(function( + index, + element + ) { + values["color_range_colors[" + index + "]"] = $(element).val(); + }); + } - return values; + if (is_metaconsole()) { + values["metaconsole"] = 1; + values["id_agent"] = $("#hidden-agent").val(); + values["server_name"] = $("#id_server_name").val(); + values["server_id"] = $("input[name='id_server_metaconsole']").val(); + } else { + values["metaconsole"] = 0; + } + + if (typeof enterprise_readFields == "function") { + //The parameter is a object and the function can change or add + //attributes. + enterprise_readFields(values); + } + + return values; } function create_button_palette_callback() { - var values = readFields(); + var values = readFields(); - //VALIDATE DATA - var validate = true; - switch (creationItem) { - case 'box_item': - if (($("input[name='width_box']").val() == '')) { - alert('Undefined width'); - validate = false; - } - if (($("input[name='height_box']").val() == '')) { - alert('Undefined height'); - validate = false; - } - break; - case 'group_item': - if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined images'); - validate = false; - } - break; - case 'static_graph': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['height'] == '')) { - alert('Undefined height'); - validate = false; - } - if((values['image'] == '' || values['image'] == 'none') && (values['label']) == false){ - alert('Undefined image'); - validate = false; - } - + //VALIDATE DATA + var validate = true; + switch (creationItem) { + case "box_item": + if ($("input[name='width_box']").val() == "") { + alert("Undefined width"); + validate = false; + } + if ($("input[name='height_box']").val() == "") { + alert("Undefined height"); + validate = false; + } + break; + case "group_item": + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" && + values["show_statistics"] == false + ) { + alert("Undefined images"); + validate = false; + } + break; + case "static_graph": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height"] == "") { + alert("Undefined height"); + validate = false; + } + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == false + ) { + alert("Undefined image"); + validate = false; + } - break; - case 'auto_sla_graph': - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - break; - case 'donut_graph': - if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - break; - case 'label': - if ((values['label'] == '')) { - alert($("#message_alert_no_label").html()); - validate = false; - } - break; - case 'icon': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['height'] == '')) { - alert('Undefined height'); - validate = false; - } - if ((values['image'] == '' || values['image'] == 'none')) { - alert($("#message_alert_no_image").html()); - validate = false; - } - break; - case 'percentile_bar': - case 'percentile_item': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['max_percentile'] == '')) { - alert($("#message_alert_no_max_percentile").html()); - validate = false; - } - if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); - validate = false; - } - break; - case 'module_graph': - if (values['width_module_graph'] == '') { - alert('Undefined width'); - validate = false; - } - if (values['height_module_graph'] == '') { - alert('Undefined height'); - validate = false; - } - if (values['id_custom_graph'] == 0) { - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['period'] == 0)) { - alert($("#message_alert_no_period").html()); - validate = false; - } - } - break; - case 'bars_graph': - if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); - validate = false; - } - if ((values['bars_graph_height'] == '')) { - alert($("#message_alert_no_bars_graph_height").html()); - validate = false; - } - break; - case 'simple_value': - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - break; - default: - //Maybe save in any Enterprise item. - if (typeof(enterprise_create_button_palette_callback) == 'function') { - validate = enterprise_create_button_palette_callback(values); - } - break; - } + break; + case "auto_sla_graph": + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + break; + case "donut_graph": + if (values["agent_string"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + break; + case "label": + if (values["label"] == "") { + alert($("#message_alert_no_label").html()); + validate = false; + } + break; + case "icon": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height"] == "") { + alert("Undefined height"); + validate = false; + } + if (values["image"] == "" || values["image"] == "none") { + alert($("#message_alert_no_image").html()); + validate = false; + } + break; + case "percentile_bar": + case "percentile_item": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["max_percentile"] == "") { + alert($("#message_alert_no_max_percentile").html()); + validate = false; + } + if (values["width_percentile"] == "") { + alert($("#message_alert_no_width_percentile").html()); + validate = false; + } + break; + case "module_graph": + if (values["width_module_graph"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height_module_graph"] == "") { + alert("Undefined height"); + validate = false; + } + if (values["id_custom_graph"] == 0) { + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["period"] == 0) { + alert($("#message_alert_no_period").html()); + validate = false; + } + } + break; + case "bars_graph": + if (values["agent_string"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["width_percentile"] == "") { + alert($("#message_alert_no_width_percentile").html()); + validate = false; + } + if (values["bars_graph_height"] == "") { + alert($("#message_alert_no_bars_graph_height").html()); + validate = false; + } + break; + case "simple_value": + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + break; + default: + //Maybe save in any Enterprise item. + if (typeof enterprise_create_button_palette_callback == "function") { + validate = enterprise_create_button_palette_callback(values); + } + break; + } - if (validate) { - switch (creationItem) { - case 'line_item': - create_line('step_1', values); - break; - default: - - insertDB(creationItem, values); - break; - } + if (validate) { + switch (creationItem) { + case "line_item": + create_line("step_1", values); + break; + default: + insertDB(creationItem, values); + break; + } - - toggle_item_palette(); - } + toggle_item_palette(); + } } function delete_user_line(idElement) { - var found = null; + var found = null; - jQuery.each(user_lines, function(iterator, user_line) { - if (user_line['id'] == idElement) { - found = iterator; - return; - } - }); + jQuery.each(user_lines, function(iterator, user_line) { + if (user_line["id"] == idElement) { + found = iterator; + return; + } + }); - if (found != null) { - user_lines.splice(found, 1); - } + if (found != null) { + user_lines.splice(found, 1); + } } function update_user_line(type, idElement, top, left) { - jQuery.each(user_lines, function(iterator, user_line) { + jQuery.each(user_lines, function(iterator, user_line) { + if (user_line["id"] != idElement) return; - if (user_line['id'] != idElement) - return; + switch (type) { + // -- line_item -- + case "handler_start": + // --------------- - switch (type) { - // -- line_item -- - case 'handler_start': - // --------------- + user_lines[iterator]["start_x"] = left; + user_lines[iterator]["start_y"] = top; - user_lines[iterator]['start_x'] = left; - user_lines[iterator]['start_y'] = top; + break; + // -- line_item -- + case "handler_end": + // --------------- - break; - // -- line_item -- - case 'handler_end': - // --------------- + user_lines[iterator]["end_x"] = left; + user_lines[iterator]["end_y"] = top; - user_lines[iterator]['end_x'] = left; - user_lines[iterator]['end_y'] = top; - - break; - } - }); + break; + } + }); } -function draw_user_lines(color, thickness, start_x, start_y , end_x, - end_y, only_defined_lines) { +function draw_user_lines( + color, + thickness, + start_x, + start_y, + end_x, + end_y, + only_defined_lines +) { + obj_js_user_lines.clear(); + // Draw the previous lines + for (iterator = 0; iterator < user_lines.length; iterator++) { + obj_js_user_lines.setStroke(user_lines[iterator]["line_width"]); + obj_js_user_lines.setColor(user_lines[iterator]["line_color"]); + obj_js_user_lines.drawLine( + parseInt(user_lines[iterator]["start_x"]), + parseInt(user_lines[iterator]["start_y"]), + parseInt(user_lines[iterator]["end_x"]), + parseInt(user_lines[iterator]["end_y"]) + ); + } - obj_js_user_lines.clear(); + if (typeof only_defined_lines == "undefined") { + only_defined_lines = false; + } - // Draw the previous lines - for (iterator = 0; iterator < user_lines.length; iterator++) { + if (!only_defined_lines) { + obj_js_user_lines.setStroke(thickness); + obj_js_user_lines.setColor(color); + obj_js_user_lines.drawLine(start_x, start_y, end_x, end_y); + } - obj_js_user_lines.setStroke(user_lines[iterator]['line_width']); - obj_js_user_lines.setColor(user_lines[iterator]['line_color']); - obj_js_user_lines.drawLine( - parseInt(user_lines[iterator]['start_x']), - parseInt(user_lines[iterator]['start_y']), - parseInt(user_lines[iterator]['end_x']), - parseInt(user_lines[iterator]['end_y'])); - } - - - if (typeof(only_defined_lines) == "undefined") { - only_defined_lines = false; - } - - if (!only_defined_lines) { - obj_js_user_lines.setStroke(thickness); - obj_js_user_lines.setColor(color); - obj_js_user_lines.drawLine(start_x, start_y, end_x, end_y); - } - - obj_js_user_lines.paint(); + obj_js_user_lines.paint(); } function create_line(step, values) { + $(".item").unbind("click"); + $(".item").unbind("dblclick"); + $(".item").unbind("dragstop"); + $(".item").unbind("dragstart"); - $('.item').unbind('click'); - $('.item').unbind('dblclick'); - $('.item').unbind('dragstop'); - $('.item').unbind('dragstart'); + $("#background").unbind("click"); + $("#background").unbind("dblclick"); - $('#background').unbind('click'); - $('#background').unbind('dblclick'); + switch (step) { + case "step_1": + $("#background *").css("cursor", "crosshair"); - switch (step) { - case 'step_1': - $("#background *").css("cursor", "crosshair"); + $("#background *").on("mousemove", function(e) { + $("#div_step_1").css({ + left: e.offsetX, + top: e.offsetY + }); + $("#div_step_1").show(); + // 2 for the black border of background + values["line_start_x"] = e.offsetX; + values["line_start_y"] = e.offsetY; + }); - $("#background *") - .on('mousemove', function(e) { + $("#background *").on("click", function(e) { + create_line("step_2", values); + }); - $('#div_step_1').css({ - left: e.offsetX, - top: e.offsetY - }); - $('#div_step_1').show(); + break; + case "step_2": + $("#div_step_1").hide(); + $("#background *").off("mousemove"); + $("#background *").off("click"); - // 2 for the black border of background - values['line_start_x'] = e.offsetX; - values['line_start_y'] = e.offsetY; + $("#background *").on("mousemove", function(e) { + $("#div_step_2").css({ + left: e.offsetX, + top: e.offsetY + }); + $("#div_step_2").show(); - }); + // 2 for the black border of background + values["line_end_x"] = e.offsetX; + values["line_end_y"] = e.offsetY; + draw_user_lines( + values["line_color"], + values["line_width"], + values["line_start_x"], + values["line_start_y"], + values["line_end_x"], + values["line_end_y"] + ); + }); - $("#background *") - .on('click', function(e) { - create_line('step_2', values); - }); + $("#background *").on("click", function(e) { + create_line("step_3", values); + }); + break; + case "step_3": + $("#div_step_2").hide(); + $("#background *").off("mousemove"); + $("#background *").off("click"); - break; - case 'step_2': - $('#div_step_1').hide(); - $("#background *").off('mousemove'); - $("#background *").off('click'); + $("#background *").css("cursor", ""); + insertDB("line_item", values); - $("#background *") - .on('mousemove', function(e) { - - $('#div_step_2').css({ - left: e.offsetX, - top: e.offsetY - }); - $('#div_step_2').show(); - - // 2 for the black border of background - values['line_end_x'] = e.offsetX; - values['line_end_y'] = e.offsetY; - - draw_user_lines( - values['line_color'], - values['line_width'], - values['line_start_x'], - values['line_start_y'], - values['line_end_x'], - values['line_end_y']); - }); - - $("#background *") - .on('click', function(e) { - create_line('step_3', values); - }); - break; - case 'step_3': - $('#div_step_2').hide(); - $("#background *").off('mousemove'); - $("#background *").off('click'); - - $("#background *").css("cursor", ""); - - insertDB("line_item", values); - - eventsItems(); - eventsBackground(); - break; - } + eventsItems(); + eventsBackground(); + break; + } } function toggle_item_palette() { - var item = null; + var item = null; - if (is_opened_palette) { - is_opened_palette = false; + if (is_opened_palette) { + is_opened_palette = false; - activeToolboxButton('static_graph', true); - activeToolboxButton('module_graph', true); - activeToolboxButton('bars_graph', true); - activeToolboxButton('simple_value', true); - activeToolboxButton('label', true); - activeToolboxButton('icon', true); - activeToolboxButton('clock', true); - activeToolboxButton('percentile_item', true); - activeToolboxButton('group_item', true); - activeToolboxButton('box_item', true); - activeToolboxButton('line_item', true); - activeToolboxButton('auto_sla_graph', true); - activeToolboxButton('donut_graph', true); - activeToolboxButton('color_cloud', true); + activeToolboxButton("static_graph", true); + activeToolboxButton("module_graph", true); + activeToolboxButton("bars_graph", true); + activeToolboxButton("simple_value", true); + activeToolboxButton("label", true); + activeToolboxButton("icon", true); + activeToolboxButton("clock", true); + activeToolboxButton("percentile_item", true); + activeToolboxButton("group_item", true); + activeToolboxButton("box_item", true); + activeToolboxButton("line_item", true); + activeToolboxButton("auto_sla_graph", true); + activeToolboxButton("donut_graph", true); + activeToolboxButton("color_cloud", true); - if (typeof(enterprise_activeToolboxButton) == 'function') { - enterprise_activeToolboxButton(true); - } + if (typeof enterprise_activeToolboxButton == "function") { + enterprise_activeToolboxButton(true); + } - $(".item").draggable("enable"); - $("#background").resizable('enable'); - $("#properties_panel").hide("fast"); + $(".item").draggable("enable"); + $("#background").resizable("enable"); + $("#properties_panel").hide("fast"); - toggle_advance_options_palette(false); - } - else { - is_opened_palette = true; + toggle_advance_options_palette(false); + } else { + is_opened_palette = true; - $(".item").draggable("disable"); - $("#background").resizable('disable'); + $(".item").draggable("disable"); + $("#background").resizable("disable"); - activeToolboxButton('static_graph', false); - activeToolboxButton('module_graph', false); - activeToolboxButton('bars_graph', false); - activeToolboxButton('auto_sla_graph', false); - activeToolboxButton('donut_graph', false); - activeToolboxButton('simple_value', false); - activeToolboxButton('label', false); - activeToolboxButton('icon', false); - activeToolboxButton('clock', false); - activeToolboxButton('percentile_item', false); - activeToolboxButton('group_item', false); - activeToolboxButton('box_item', false); - activeToolboxButton('line_item', false); - activeToolboxButton('color_cloud', false); + activeToolboxButton("static_graph", false); + activeToolboxButton("module_graph", false); + activeToolboxButton("bars_graph", false); + activeToolboxButton("auto_sla_graph", false); + activeToolboxButton("donut_graph", false); + activeToolboxButton("simple_value", false); + activeToolboxButton("label", false); + activeToolboxButton("icon", false); + activeToolboxButton("clock", false); + activeToolboxButton("percentile_item", false); + activeToolboxButton("group_item", false); + activeToolboxButton("box_item", false); + activeToolboxButton("line_item", false); + activeToolboxButton("color_cloud", false); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', false); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', false); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", false); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", false); - if (typeof(enterprise_activeToolboxButton) == 'function') { - enterprise_activeToolboxButton(false); - } + if (typeof enterprise_activeToolboxButton == "function") { + enterprise_activeToolboxButton(false); + } - if (creationItem != null) { - //Create a item + if (creationItem != null) { + //Create a item - activeToolboxButton(creationItem, true); - item = creationItem; - $("#button_update_row").css('display', 'none'); - $("#button_create_row").css('display', ''); - cleanFields(item); - unselectAll(); - } - else if (selectedItem != null) { - //Edit a item + activeToolboxButton(creationItem, true); + item = creationItem; + $("#button_update_row").css("display", "none"); + $("#button_create_row").css("display", ""); + cleanFields(item); + unselectAll(); + } else if (selectedItem != null) { + //Edit a item - item = selectedItem; - toolbuttonActive = item; + item = selectedItem; + toolbuttonActive = item; - switch (item) { - case 'handler_start': - case 'handler_end': - activeToolboxButton('line_item', true); - break; - default: - activeToolboxButton(toolbuttonActive, true); - break; - } + switch (item) { + case "handler_start": + case "handler_end": + activeToolboxButton("line_item", true); + break; + default: + activeToolboxButton(toolbuttonActive, true); + break; + } + $("#button_create_row").css("display", "none"); + $("#button_update_row").css("display", ""); + cleanFields(); - $("#button_create_row").css('display', 'none'); - $("#button_update_row").css('display', ''); - cleanFields(); + loadFieldsFromDB(item); + } - loadFieldsFromDB(item); - } + hiddenFields(item); - hiddenFields(item); - - $("#show_on_top_row").css('display', 'table-row'); - $("#show_on_top." + item).css('display', 'block'); + $("#show_on_top_row").css("display", "table-row"); + $("#show_on_top." + item).css("display", "block"); - $("#properties_panel").show("fast"); - - $( ".lineheighttd").remove(); - //$('.mceToolbarEndButton').before( - // '' - //); - $('.mceToolbarEndButton').before( - '' - ); - - $('.lineheight').click(function(){ - $( "#text-label_ifr" ).contents().find( "p" ).attr( "data-mce-style","line-height:"+$(this).val()+";"); - $( "#text-label_ifr" ).contents().find( "p" ).css("line-height",$(this).val()); - $( "#text-label_ifr" ).contents().find( "span" ).attr( "data-mce-style","line-height:"+$(this).val()+";"); - $( "#text-label_ifr" ).contents().find( "span" ).css("line-height",$(this).val()); - - }); - - $( "#text-label_ifr" ).contents().find( "p" ).css("line-height",$('#lineheight').val()); - $( "#text-label_ifr" ).contents().find( "span" ).css("line-height",$('#lineheight').val()); - $( "#text-label_ifr" ).contents().find( "body" ).css("background","lightgray"); - - } - - if(creationItem != 'simple_value'){ - $("#data_image_check").html('Off'); - $("#data_image_check").css('display','none'); - $("#data_image_check_label").css('display','none'); - $("#data_image_container").css('display','none'); - $('.block_tinymce').remove(); - } + $("#properties_panel").show("fast"); + + $(".lineheighttd").remove(); + //$('.mceToolbarEndButton').before( + // '' + //); + $(".mceToolbarEndButton").before( + '' + ); + + $(".lineheight").click(function() { + $("#text-label_ifr") + .contents() + .find("p") + .attr("data-mce-style", "line-height:" + $(this).val() + ";"); + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height", $(this).val()); + $("#text-label_ifr") + .contents() + .find("span") + .attr("data-mce-style", "line-height:" + $(this).val() + ";"); + $("#text-label_ifr") + .contents() + .find("span") + .css("line-height", $(this).val()); + }); + + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height", $("#lineheight").val()); + $("#text-label_ifr") + .contents() + .find("span") + .css("line-height", $("#lineheight").val()); + $("#text-label_ifr") + .contents() + .find("body") + .css("background", "lightgray"); + } + + if (creationItem != "simple_value") { + $("#data_image_check").html("Off"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $("#data_image_container").css("display", "none"); + $(".block_tinymce").remove(); + } } function fill_parent_select(id_item) { - //Populate the parent widget - $("#parent option") - .filter(function() { if ($(this).attr('value') != 0) return true; }) - .remove(); - jQuery.each(parents, function(key, value) { - if (value == undefined) { - return; - } - if (id_item == key) { - return; //continue - } + //Populate the parent widget + $("#parent option") + .filter(function() { + if ($(this).attr("value") != 0) return true; + }) + .remove(); + jQuery.each(parents, function(key, value) { + if (value == undefined) { + return; + } + if (id_item == key) { + return; //continue + } - $("#parent").append($('')); - }); + $("#parent").append( + $('") + ); + }); } function loadFieldsFromDB(item) { - $("#loading_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#loading_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - parameter = Array(); - parameter.push ({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "load"}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - parameter.push ({name: "type", value: item}); - parameter.push ({name: "id_element", value: idItem}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "load" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: item }); + parameter.push({ name: "id_element", value: idItem }); - set_label = false; + set_label = false; - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - var moduleId = 0; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var moduleId = 0; - fill_parent_select(idItem); - - jQuery.each(data, function(key, val) { - if (key == 'event_max_time_row') - $("select[name=event_max_time_row]").val(val); - if (key == 'background') - $("#background_image").val(val); - if (key == 'width') $("input[name=width]").val(val); - if (key == 'height') - $("input[name=height]").val(val); + fill_parent_select(idItem); - if (key == 'label') { - tinymce.get('text-label') - .setContent(""); - $("input[name=label]").val(""); + jQuery.each(data, function(key, val) { + if (key == "event_max_time_row") + $("select[name=event_max_time_row]").val(val); + if (key == "background") $("#background_image").val(val); + if (key == "width") $("input[name=width]").val(val); + if (key == "height") $("input[name=height]").val(val); - tinymce.get('text-label').setContent(val); - $("input[name=label]").val(val); - } - - $('#lineheight').val($("#text-label_ifr").contents().find("p").css('line-height')); + if (key == "label") { + tinymce.get("text-label").setContent(""); + $("input[name=label]").val(""); - if (key == 'enable_link') { - if (val == "1") { - $("input[name=enable_link]") - .prop("checked", true); - } - else { - $("input[name=enable_link]") - .prop("checked", false); - } - } - - if (key == 'show_statistics') { - if (val == "1") { - $("input[name=show_statistics]") - .prop("checked", true); - } - else { - $("input[name=show_statistics]") - .prop("checked", false); - } - } - - if (key == 'show_on_top') { - if (val == "1") { - $("input[name=show_on_top]") - .prop("checked", true); - } - else { - $("input[name=show_on_top]") - .prop("checked", false); - } - } - - if (key == 'type_graph') { - $("select[name=type_graph]").val(val); - } - - if (key == 'label_position') { - if($("#hidden-metaconsole").val() == 1){ - $('#labelposup'+" img").attr('src','../../images/label_up.png'); - $('#labelposdown'+" img").attr('src','../../images/label_down.png'); - $('#labelposleft'+" img").attr('src','../../images/label_left.png'); - $('#labelposright'+" img").attr('src','../../images/label_right.png'); - $('.labelpos').attr('sel','no'); - $('#labelpos'+val+" img").attr('src','../../images/label_'+$('#labelpos'+val).attr('id').replace('labelpos','')+'_2.png'); - $('#labelpos'+val).attr('sel','yes'); - } - else{ - $('#labelposup'+" img").attr('src','images/label_up.png'); - $('#labelposdown'+" img").attr('src','images/label_down.png'); - $('#labelposleft'+" img").attr('src','images/label_left.png'); - $('#labelposright'+" img").attr('src','images/label_right.png'); - $('.labelpos').attr('sel','no'); - $('#labelpos'+val+" img").attr('src','images/label_'+$('#labelpos'+val).attr('id').replace('labelpos','')+'_2.png'); - $('#labelpos'+val).attr('sel','yes'); - } - } - - if (key == 'image') { - //Load image preview - $("select[name=image]").val(val); - $("select[name=background_color]").val(val); - showPreview(val); - } + tinymce.get("text-label").setContent(val); + $("input[name=label]").val(val); + } - if (key == 'pos_x') $("input[name=left]").val(val); - if (key == 'pos_y') $("input[name=top]").val(val); - if (key == 'agent_name') { - $("input[name=agent]").val(val); - $("input[name=agent_string]").val(val); - //Reload no-sincrone the select of modules - } - - if (key == 'id_agent') { - $("input[name=id_agent]").val(val); - } - if (key == 'id_agent_string') { - $("input[name=id_agent_string]").val(val); - } - if (key == 'modules_html') { - $("select[name=module]").empty().html(val); - $("select[name=module]").val(moduleId); - } - if (key == 'id_agente_modulo') { - moduleId = val; - $("select[name=module]").val(val); - } - if (key == 'process_value') - $("select[name=process_value]").val(val); - if (key == 'period') { - var anySelected = false; - var periodId = $('#hidden-period').attr('class'); - $('#' + periodId + '_select option') - .each(function() { + $("#lineheight").val( + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height") + ); - if($(this).val() == val) { - $(this).prop('selected', true); - $(this).trigger('change'); - anySelected = true; - } - }); - if (anySelected == false) { - $('#' + periodId + '_select option') - .eq(0).prop('selected', true); - $('#' + periodId + '_units option') - .eq(0).prop('selected', true); - $('#hidden-period').val(val); - $('#text-' + periodId + '_text').val(val); - adjustTextUnits(periodId); - $('#' + periodId + '_default').hide(); - $('#' + periodId + '_manual').show(); - } - } - if (key == 'width') - $("input[name=width]").val(val); - if (key == 'height') - $("input[name=height]").val(val); - if (key == 'parent_item') - $("select[name=parent]").val(val); - if (key == 'linked_layout_status_type') - $("select[name=linked_map_status_calculation_type]").val(val).change(); - if (key == 'id_layout_linked') { - if (val != 0) { - if (data['linked_layout_node_id'] == null) { - $("select[name=map_linked]").val(val).change(); - } else { - var $option = $("select[name=map_linked] > option[data-node-id=" + data['linked_layout_node_id'] + "][value=" + val + "]"); - if ($option.length === 0) $option = $("select[name=map_linked] > option[value=" + val + "]"); - $option.prop("selected", true).parent().change(); - } - } - } - if (key == 'linked_layout_node_id') - $("input[name=linked_map_node_id]").val(val); - if (key == 'id_layout_linked_weight') - $("input[name=map_linked_weight]").val(val); - if (key == 'linked_layout_status_as_service_critical') - $("input[name=linked_map_status_service_critical]").val(val); - if (key == 'linked_layout_status_as_service_warning') - $("input[name=linked_map_status_service_warning]").val(val); - if (key == 'element_group') - $("select[name=element_group]").val(val); - if (key == 'width_percentile') - $("input[name=width_percentile]").val(val); - if (key == 'bars_graph_height') - $("input[name=bars_graph_height]").val(val); - if (key == 'max_percentile') - $("input[name=max_percentile]").val(val); - if (key == 'width_module_graph') - $("input[name=width_module_graph]").val(val); - if (key == 'height_module_graph') - $("input[name=height_module_graph]").val(val); - if (key == 'bars_graph_type') - $("select[name=bars_graph_type]").val(val); - if (key == 'type_percentile') - $("select[name=type_percentile]").val(val); - if (key == 'percentile_label') - $("input[name=percentile_label]").val(val); - if (key == 'percentile_color') { - $("input[name=percentile_color]").val(val); - $("#percentile_item_row_5 .ColorPickerDivSample") - .css('background-color', val); - } - if (key == 'percentile_label_color') { - $("input[name=percentile_label_color]").val(val); - $("#percentile_item_row_6 .ColorPickerDivSample") - .css('background-color', val); - } - - if (key == 'show_last_value') { - $("select[name=last_value]").val(val); - } - - if (key == 'clock_animation') - $("select[name=clock_animation]").val(val); - if (key == 'time_format') - $("select[name=time_format]").val(val); - if (key == 'timezone') { - var zone = val.split("/"); - $("select[name=zone]").val(zone[0]); - - $.ajax({ - type: "POST", - url: "ajax.php", - data: "page=godmode/setup/setup&select_timezone=1&zone=" + zone[0], - dataType: "json", - success: function(data) { - $("#timezone").empty(); - jQuery.each (data, function (id, value) { - timezone = value; - var timezone_country = timezone.replace (/^.*\//g, ""); - $("select[name='timezone']").append($("" + ) + ); - var anyText = $("#any_text").html(); //Trick for catch the translate text. - $("#module") - .empty() - .append($('')); - - //Code for the graphs - $("input[name='radio_choice'][value='module_graph']") - .prop('checked', true); - $("input[name='radio_choice']").trigger('change'); - - //Select none custom graph - $("#custom_graph option[value=0]") - .prop('selected', true); + //Code for the graphs + $("input[name='radio_choice'][value='module_graph']").prop("checked", true); + $("input[name='radio_choice']").trigger("change"); + //Select none custom graph + $("#custom_graph option[value=0]").prop("selected", true); } function set_static_graph_status(idElement, image, status) { - $("#image_" + idElement).attr('src', "images/spinner.gif"); + $("#image_" + idElement).attr("src", "images/spinner.gif"); - if (typeof(status) == 'undefined') { - var parameter = Array(); - parameter.push ({ - name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({ - name: "get_element_status", - value: "1"}); - parameter.push ({ - name: "id_element", - value: idElement}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); + if (typeof status == "undefined") { + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ + name: "get_element_status", + value: "1" + }); + parameter.push({ + name: "id_element", + value: idElement + }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - if (is_metaconsole()) { - parameter.push ({name: "metaconsole", value: 1}); - } - else { - parameter.push ({name: "metaconsole", value: 0}); - } + if (is_metaconsole()) { + parameter.push({ name: "metaconsole", value: 1 }); + } else { + parameter.push({ name: "metaconsole", value: 0 }); + } - $('#hidden-status_' + idElement).val(3); - jQuery.ajax ({ - type: 'POST', - url: get_url_ajax(), - data: parameter, - success: function (data) { - set_static_graph_status(idElement, image, data); - if(data['show_statistics'] == 1){ - if($('#'+idElement+' table').css('float') == 'right' || $('#'+idElement+ ' table').css('float') == 'left'){ - $('#'+idElement+ ' img').css('margin-top', parseInt($('#'+idElement).css('height'))/2 - parseInt($('#'+idElement+ ' img').css('height'))/2); - } - else{ - $('#'+idElement+ ' img').css('margin-left', parseInt($('#'+idElement).css('width'))/2 - parseInt($('#'+idElement+ ' img').css('width'))/2); - } - } - } - }); + $("#hidden-status_" + idElement).val(3); + jQuery.ajax({ + type: "POST", + url: get_url_ajax(), + data: parameter, + success: function(data) { + set_static_graph_status(idElement, image, data); + if (data["show_statistics"] == 1) { + if ( + $("#" + idElement + " table").css("float") == "right" || + $("#" + idElement + " table").css("float") == "left" + ) { + $("#" + idElement + " img").css( + "margin-top", + parseInt($("#" + idElement).css("height")) / 2 - + parseInt($("#" + idElement + " img").css("height")) / 2 + ); + } else { + $("#" + idElement + " img").css( + "margin-left", + parseInt($("#" + idElement).css("width")) / 2 - + parseInt($("#" + idElement + " img").css("width")) / 2 + ); + } + } + } + }); - return; - } + return; + } - switch (status) { - case '1': - //Critical (BAD) - suffix = "_bad.png"; - break; - case '4': - //Critical (ALERT) - suffix = "_bad.png"; - break; - case '0': - //Normal (OK) - suffix = "_ok.png"; - break; - case '2': - //Warning - suffix = "_warning.png"; - break; - case '3': - default: - //Unknown - suffix = ".png"; - break; - } - set_image("image", idElement, image + suffix); + switch (status) { + case "1": + //Critical (BAD) + suffix = "_bad.png"; + break; + case "4": + //Critical (ALERT) + suffix = "_bad.png"; + break; + case "0": + //Normal (OK) + suffix = "_ok.png"; + break; + case "2": + //Warning + suffix = "_warning.png"; + break; + case "3": + default: + //Unknown + suffix = ".png"; + break; + } + set_image("image", idElement, image + suffix); } function set_image(type, idElement, image) { - - if(image == 'show_statistics_bad.png' || image == 'show_statistics_ok.png' || image == 'show_statistics_warning.png' || image == 'show_statistics.png'){ - item = "#image_" + idElement; - img_src = "images/console/signes/group_status.png"; - } - else{ - - if (type == "image") { - item = "#image_" + idElement; - img_src = "images/console/icons/" + image; - } - else if (type == "background") { - item = "#background_img"; - img_src = "images/console/background/" + image; - } - - } - - - var params = []; - params.push("get_image_path=1"); - params.push("img_src=" + img_src); - params.push("page=include/ajax/skins.ajax"); - params.push("only_src=1"); - params.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: get_url_ajax(), - success: function (data) { - $(item).attr('src', data); - - if(image == 'show_statistics_bad.png' || image == 'show_statistics_ok.png' || image == 'show_statistics_warning.png' || image == 'show_statistics.png'){ - $(item).attr('width', 520); - $(item).attr('height', 80); - } - - } - }); + if ( + image == "show_statistics_bad.png" || + image == "show_statistics_ok.png" || + image == "show_statistics_warning.png" || + image == "show_statistics.png" + ) { + item = "#image_" + idElement; + img_src = "images/console/signes/group_status.png"; + } else { + if (type == "image") { + item = "#image_" + idElement; + img_src = "images/console/icons/" + image; + } else if (type == "background") { + item = "#background_img"; + img_src = "images/console/background/" + image; + } + } + + var params = []; + params.push("get_image_path=1"); + params.push("img_src=" + img_src); + params.push("page=include/ajax/skins.ajax"); + params.push("only_src=1"); + params.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: get_url_ajax(), + success: function(data) { + $(item).attr("src", data); + + if ( + image == "show_statistics_bad.png" || + image == "show_statistics_ok.png" || + image == "show_statistics_warning.png" || + image == "show_statistics.png" + ) { + $(item).attr("width", 520); + $(item).attr("height", 80); + } + } + }); } function setBarsGraph(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - width_percentile = values['width_percentile']; - bars_graph_height = values['bars_graph_height']; + width_percentile = values["width_percentile"]; + bars_graph_height = values["bars_graph_height"]; - parameter = Array(); - - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "id_agent", value: values['id_agent_string']}); - parameter.push ({name: "module", value: values['module']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/barras.png'); - - if (values['width_percentile'] == "0" && values["bars_graph_height"] == "0") { - // Image size - } - else{ - $("#" + id_data + " img").css('width', width_percentile + 'px'); - $("#" + id_data + " img").css('height', bars_graph_height + 'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left', parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + parameter = Array(); + + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "id_agent", value: values["id_agent_string"] }); + parameter.push({ name: "module", value: values["module"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/barras.png" + ); + + if ( + values["width_percentile"] == "0" && + values["bars_graph_height"] == "0" + ) { + // Image size + } else { + $("#" + id_data + " img").css("width", width_percentile + "px"); + $("#" + id_data + " img").css("height", bars_graph_height + "px"); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setClock(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - parameter = Array(); - - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "time_format", value: values['time_format']}); - parameter.push ({name: "timezone", value: values['timezone']}); - parameter.push ({name: "clock_animation", value: values['clock_animation']}); - parameter.push ({name: "label", value: values['label']}); - parameter.push ({name: "width", value: values['width_percentile']}); - parameter.push ({name: "always_on_top", value: values['always_on_top']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/clock.png'); - } - else{ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/digital-clock.png'); - } - - if (values['width_percentile'] == 0) { - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").css('width', 200 + 'px'); - $("#" + id_data + " img").css('height', 240 + 'px'); - } - else{ - $("#" + id_data + " img").css('width', 200 + 'px'); - - if(values['time_format'] == 'time'){ - $("#" + id_data + " img").css('height', 71 + 'px'); - } - else{ - $("#" + id_data + " img").css('height', 91 + 'px'); - } - - } - - } - else{ - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").css('width', values['width_percentile'] + 'px'); - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])+40 + 'px'); - } - else{ - $("#" + id_data + " img").css('width', values['width_percentile'] + 'px'); - - if(values['time_format'] == 'time'){ - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])/3.9+20 + 'px'); - } - else{ - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])/3.9+40 + 'px'); - } - } - - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left', parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + parameter = Array(); + + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "time_format", value: values["time_format"] }); + parameter.push({ name: "timezone", value: values["timezone"] }); + parameter.push({ name: "clock_animation", value: values["clock_animation"] }); + parameter.push({ name: "label", value: values["label"] }); + parameter.push({ name: "width", value: values["width_percentile"] }); + parameter.push({ name: "always_on_top", value: values["always_on_top"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/clock.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/digital-clock.png" + ); + } + + if (values["width_percentile"] == 0) { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").css("width", 200 + "px"); + $("#" + id_data + " img").css("height", 240 + "px"); + } else { + $("#" + id_data + " img").css("width", 200 + "px"); + + if (values["time_format"] == "time") { + $("#" + id_data + " img").css("height", 71 + "px"); + } else { + $("#" + id_data + " img").css("height", 91 + "px"); + } + } + } else { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").css( + "width", + values["width_percentile"] + "px" + ); + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) + 40 + "px" + ); + } else { + $("#" + id_data + " img").css( + "width", + values["width_percentile"] + "px" + ); + + if (values["time_format"] == "time") { + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) / 3.9 + 20 + "px" + ); + } else { + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) / 3.9 + 40 + "px" + ); + } + } + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setModuleGraph(id_data) { - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_layout_data"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_layout_data" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - id_agente_modulo = data['id_agente_modulo']; - id_custom_graph = data['id_custom_graph']; - label = data['label']; - height = (data['height']); - width = (data['width']); - period = data['period']; - background_color = data['image']; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + id_agente_modulo = data["id_agente_modulo"]; + id_custom_graph = data["id_custom_graph"]; + label = data["label"]; + height = data["height"]; + width = data["width"]; + period = data["period"]; + background_color = data["image"]; - if (is_metaconsole()) { - id_metaconsole = data['id_metaconsole']; - } + if (is_metaconsole()) { + id_metaconsole = data["id_metaconsole"]; + } - //Cleaned array - parameter = Array(); + //Cleaned array + parameter = Array(); - parameter.push ({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_image_sparse"}); - parameter.push ({name: "id_agent_module", value: id_agente_modulo}); - parameter.push ({name: "id_custom_graph", value: id_custom_graph}); - if (is_metaconsole()) { - parameter.push ({name: "id_metaconsole", value: id_metaconsole}); - } - parameter.push ({name: "type", value: 'module_graph'}); - parameter.push ({name: "height", value: height}); - parameter.push ({name: "width", value: width}); - parameter.push ({name: "period", value: period}); - parameter.push ({name: "background_color", value: background_color}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) - { - - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } - - if (data['no_data'] == true) { - $('#' + id_data).html(data['url']); - } - else { - if($("#module_row").css('display')!='none'){ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module_graph.png'); - if($('#text-width_module_graph').val() == 0 || $('#text-height_module_graph').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_module_graph').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height_module_graph').val()+'px'); - } - }else{ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/custom_graph.png'); - if($('#text-width_module_graph').val() == 0 || $('#text-height_module_graph').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_module_graph').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height_module_graph').val()+'px'); - } - } - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - } - }); - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_image_sparse" }); + parameter.push({ name: "id_agent_module", value: id_agente_modulo }); + parameter.push({ name: "id_custom_graph", value: id_custom_graph }); + if (is_metaconsole()) { + parameter.push({ name: "id_metaconsole", value: id_metaconsole }); + } + parameter.push({ name: "type", value: "module_graph" }); + parameter.push({ name: "height", value: height }); + parameter.push({ name: "width", value: width }); + parameter.push({ name: "period", value: period }); + parameter.push({ name: "background_color", value: background_color }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } + if (data["no_data"] == true) { + $("#" + id_data).html(data["url"]); + } else { + if ($("#module_row").css("display") != "none") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module_graph.png" + ); + if ( + $("#text-width_module_graph").val() == 0 || + $("#text-height_module_graph").val() == 0 + ) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_module_graph").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-height_module_graph").val() + "px" + ); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/custom_graph.png" + ); + if ( + $("#text-width_module_graph").val() == 0 || + $("#text-height_module_graph").val() == 0 + ) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_module_graph").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-height_module_graph").val() + "px" + ); + } + } + } + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); + } + }); } -function setModuleValue(id_data, process_simple_value, period, width_data_image) { - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "period", value: period}); - parameter.push ({name: "width", value: width_data_image}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - if (process_simple_value != undefined) { - parameter.push ({name: "process_simple_value", value: process_simple_value}); - } - - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - var currentValue = $("#text_" + id_data).html(); - - $("#text_" + id_data).html(currentValue); - } - }); +function setModuleValue( + id_data, + process_simple_value, + period, + width_data_image +) { + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "period", value: period }); + parameter.push({ name: "width", value: width_data_image }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + if (process_simple_value != undefined) { + parameter.push({ + name: "process_simple_value", + value: process_simple_value + }); + } + + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var currentValue = $("#text_" + id_data).html(); + + $("#text_" + id_data).html(currentValue); + } + }); } function setPercentileBar(id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - var img = url_hack_metaconsole + 'include/graphs/fgraph.php?graph_type=progressbar&height=15&' + - 'width=' + width_percentile + '&mode=1&progress=' + percentile + - '&value_text=' + value_text + '&colorRGB=' + colorRGB; + var img = + url_hack_metaconsole + + "include/graphs/fgraph.php?graph_type=progressbar&height=15&" + + "width=" + + width_percentile + + "&mode=1&progress=" + + percentile + + "&value_text=" + + value_text + + "&colorRGB=" + + colorRGB; - $("#"+ id_data).attr('src', img); - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/percentil.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - } - - $("#" + id_data + " img").css('height', '30px'); - - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - - } - }); + $("#" + id_data).attr("src", img); + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/percentil.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + } + + $("#" + id_data + " img").css("height", "30px"); + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } -function setPercentileCircular (id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); +function setPercentileCircular(id_data, values) { + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/circular-progress-bar.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/circular-progress-bar.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } -function setPercentileInteriorCircular (id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); +function setPercentileInteriorCircular(id_data, values) { + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/circular-progress-bar-interior.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + + "images/console/signes/circular-progress-bar-interior.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setEventsBar(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - parameter = Array(); + parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_events"}); - parameter.push ({name: "id_agent", value: values['id_agent']}); - parameter.push ({name: "id_agent_module", value: values['module']}); - if (is_metaconsole()) { - parameter.push ({name: "id_metaconsole", value: values['server_id']}); - } - parameter.push ({name: "period", value: values['event_max_time_row']}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['no_data'] == true) { - if (values['width'] == "0" || values['height'] == "0") { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - $("#" + id_data + " img").css('width', values['width'] + 'px'); - $("#" + id_data + " img").css('height', values['height'] + 'px'); - } - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - - if($('#text-width').val() == 0 || $('#text-height').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height').val()+'px'); - } - } - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_events" }); + parameter.push({ name: "id_agent", value: values["id_agent"] }); + parameter.push({ name: "id_agent_module", value: values["module"] }); + if (is_metaconsole()) { + parameter.push({ name: "id_metaconsole", value: values["server_id"] }); + } + parameter.push({ name: "period", value: values["event_max_time_row"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["no_data"] == true) { + if (values["width"] == "0" || values["height"] == "0") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + $("#" + id_data + " img").css("width", values["width"] + "px"); + $("#" + id_data + " img").css("height", values["height"] + "px"); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + + if ($("#text-width").val() == 0 || $("#text-height").val() == 0) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css("width", $("#text-width").val() + "px"); + $("#" + id_data + " img").css( + "height", + $("#text-height").val() + "px" + ); + } + } + } + }); } -function setDonutsGraph (id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } +function setDonutsGraph(id_data, values) { + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - width_percentile = values['width_percentile']; + width_percentile = values["width_percentile"]; - parameter = Array(); + parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "id_agent", value: values['id_agent_string']}); - parameter.push ({name: "module", value: values['module']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['no_data'] == true) { - if (values['width'] == "0") { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/wrong_donut_graph.png'); - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/wrong_donut_graph.png'); - $("#" + id_data + " img").css('width', width_percentile + 'px'); - $("#" + id_data + " img").css('height', width_percentile + 'px'); - } - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/donut-graph.png'); - - if($('#text-width_percentile').val() == 0){ - // Image size - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - } - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "id_agent", value: values["id_agent_string"] }); + parameter.push({ name: "module", value: values["module"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["no_data"] == true) { + if (values["width"] == "0") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/wrong_donut_graph.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/wrong_donut_graph.png" + ); + $("#" + id_data + " img").css("width", width_percentile + "px"); + $("#" + id_data + " img").css("height", width_percentile + "px"); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/donut-graph.png" + ); + + if ($("#text-width_percentile").val() == 0) { + // Image size + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + } + } + }); } function setPercentileBubble(id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') - unit_text = data['unit_text']; - colorRGB = data['colorRGB']; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") + unit_text = data["unit_text"]; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - var img = url_hack_metaconsole + 'include/graphs/fgraph.php?graph_type=progressbubble&height=' + width_percentile + '&' + - 'width=' + width_percentile + '&mode=1&progress=' + percentile + - '&value_text=' + value_text + '&colorRGB=' + colorRGB; + var img = + url_hack_metaconsole + + "include/graphs/fgraph.php?graph_type=progressbubble&height=" + + width_percentile + + "&" + + "width=" + + width_percentile + + "&mode=1&progress=" + + percentile + + "&value_text=" + + value_text + + "&colorRGB=" + + colorRGB; - $("#image_" + id_data).attr('src', img); - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/percentil_bubble.png'); - - - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - } - }); + $("#image_" + id_data).attr("src", img); + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/percentil_bubble.png" + ); + + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } -function setColorCloud (visualConsoleId, dataId, $container) { - $container = $container || $("#" + dataId + ".item.color_cloud"); - if ($container.length === 0) return; +function setColorCloud(visualConsoleId, dataId, $container) { + $container = $container || $("#" + dataId + ".item.color_cloud"); + if ($container.length === 0) return; - var $spinner = $container.children("img"); - var $svg = $container.children("svg"); + var $spinner = $container.children("img"); + var $svg = $container.children("svg"); - if ($svg.length === 0) { - $svg = $(""); - $container.append($svg); - } - - if ($spinner.length > 0) $svg.hide(); + if ($svg.length === 0) { + $svg = $(""); + $container.append($svg); + } - jQuery - .post( - get_url_ajax(), - { - "page": "include/ajax/visual_console_builder.ajax", - "action": "get_color_cloud", - "id_visual_console": visualConsoleId, - "id_element": dataId - }, - null, - "html" - ) - .done(function (data) { - var $newSvg = $(data); - // Check if $newSvg contains a svg - if ($newSvg.is("svg")) $svg.replaceWith($newSvg); - }) - .always(function () { - if ($spinner.length > 0) $spinner.remove(); - $svg.show(); - }); + if ($spinner.length > 0) $svg.hide(); + + jQuery + .post( + get_url_ajax(), + { + page: "include/ajax/visual_console_builder.ajax", + action: "get_color_cloud", + id_visual_console: visualConsoleId, + id_element: dataId + }, + null, + "html" + ) + .done(function(data) { + var $newSvg = $(data); + // Check if $newSvg contains a svg + if ($newSvg.is("svg")) $svg.replaceWith($newSvg); + }) + .always(function() { + if ($spinner.length > 0) $spinner.remove(); + $svg.show(); + }); } function get_image_url(img_src) { - var img_url= null; - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/skins.ajax"}); - parameter.push ({name: "get_image_path", value: true}); - parameter.push ({name: "img_src", value: img_src}); - parameter.push ({name: "only_src", value: true}); + var img_url = null; + var parameter = Array(); + parameter.push({ name: "page", value: "include/ajax/skins.ajax" }); + parameter.push({ name: "get_image_path", value: true }); + parameter.push({ name: "img_src", value: img_src }); + parameter.push({ name: "only_src", value: true }); - return $.ajax ({ - type: 'GET', - url: get_url_ajax(), - cache: false, - data: parameter - }); + return $.ajax({ + type: "GET", + url: get_url_ajax(), + cache: false, + data: parameter + }); } function set_color_line_status(lines, id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_color_line"}); - parameter.push ({name: "id_element", value: id_data}); + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_color_line" }); + parameter.push({ name: "id_element", value: id_data }); - var color = null; + var color = null; - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - color = data['color_line']; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + color = data["color_line"]; - var line = { - "id": id_data, - "node_begin": values['parent'], - "node_end": id_data, - "color": color }; + var line = { + id: id_data, + node_begin: values["parent"], + node_end: id_data, + color: color + }; - lines.push(line); - - refresh_lines(lines, 'background', true); - } - }); + lines.push(line); + refresh_lines(lines, "background", true); + } + }); } function createItem(type, values, id_data) { - var sizeStyle = ''; - var imageSize = ''; - var item = null; + var sizeStyle = ""; + var imageSize = ""; + var item = null; - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - switch (type) { - case 'box_item': - - if(values['width_box'] == 0 || values['height_box'] == 0){ - item = $('
' - + '
' - + '
' - + '
' - + '' - ); - } - else{ - item = $('
' - + '
' - + '
' - + '
' - + '' - ); - } - - - break; - case 'group_item': - - class_type = "group_item"; - + switch (type) { + case "box_item": + if (values["width_box"] == 0 || values["height_box"] == 0) { + item = $( + '
' + + "
' + + "
" + + "
" + + '' + ); + } else { + item = $( + '
' + + "
' + + "
" + + "
" + + '' + ); + } - img_src = "images/spinner.gif"; + break; + case "group_item": + class_type = "group_item"; - item = $('
') - .attr('id', id_data) - .attr('class', 'item ' + class_type) - .css('text-align', 'left') - .css('position', 'absolute') - .css('display', 'inline-block') - .css('top', values['top'] + 'px') - .css('left', values['left'] + 'px'); - - - - if(values['show_statistics'] != 1){ - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png') - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png') - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png'); - - } - } - else{ - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src); - - } - } - - - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - // Do none - if(values['image'] != '' && values['image'] != 'none'){ - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - - var $input = $('') - .attr('id', 'hidden-status_' + id_data) - .attr('type', 'hidden') - .attr('value', -1) - .attr('name', 'status_' + id_data); + img_src = "images/spinner.gif"; - if(values['label_position'] == 'up'){ - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append('
'+values['label']+'
') - .append($input); - } - else{ - item - .append('
'+values['label']+'
') - .append($image) - .append($input); - } - - } - else if(values['label_position'] == 'down'){ - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append('
'+values['label']+'
') - .append($input); - - } - else{ - item - .append($image) - .append('
'+values['label']+'
') - .append($input); - } - - } - else if(values['label_position'] == 'left'){ - - if(values['height'] == 0){ - item - .append('
'+values['label']+'
'); - } - else{ - item - .append('
'+values['label']+'
') - } - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append($input); - } - else{ - item - .append($image) - .append($input); - } - - - } - else if(values['label_position'] == 'right'){ - if(values['height'] == 0){ - item - .append('
'+values['label']+'
'); - } - else{ - item - .append('
'+values['label']+'
') - } - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append($input); - } - else{ - item - .append($image) - .append($input); - } - - } - - if(values['show_statistics'] != 1){ - set_static_graph_status(id_data, values['image']); - } - else{ - set_static_graph_status(id_data, 'show_statistics'); - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - - if(values['image'] != '' && values['image'] != 'none'){ - // Do none - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } + item = $("
") + .attr("id", id_data) + .attr("class", "item " + class_type) + .css("text-align", "left") + .css("position", "absolute") + .css("display", "inline-block") + .css("top", values["top"] + "px") + .css("left", values["left"] + "px"); - break; - - case 'static_graph': - class_type = "static_graph"; + if (values["show_statistics"] != 1) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png") + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png") + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png"); + } + } else { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src); + } + } - img_src = "images/spinner.gif"; + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + // Do none + if (values["image"] != "" && values["image"] != "none") { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } - item = $('
') - .attr('id', id_data) - .attr('class', 'item ' + class_type) - .css('text-align', 'left') - .css('position', 'absolute') - .css('display', 'inline-block') - .css('top', values['top'] + 'px') - .css('left', values['left'] + 'px'); - - - - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src); - - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - // Do none - if(values['image'] != '' && values['image'] != 'none'){ - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - - - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - // else{ - // $('#image_'+id_data).css('width', values['width']+'px'); - // $('#image_'+id_data).css('height', values['height']+'px'); - // } -/* + var $input = $("") + .attr("id", "hidden-status_" + id_data) + .attr("type", "hidden") + .attr("value", -1) + .attr("name", "status_" + id_data); + + if (values["label_position"] == "up") { + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } else { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($image) + .append($input); + } + } else if (values["label_position"] == "down") { + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } else { + item + .append($image) + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } + } else if (values["label_position"] == "left") { + if (values["height"] == 0) { + item.append( + '
' + + values["label"] + + "
" + ); + } else { + item.append( + '
' + + values["label"] + + "
" + ); + } + + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item.append($input); + } else { + item.append($image).append($input); + } + } else if (values["label_position"] == "right") { + if (values["height"] == 0) { + item.append( + '
' + + values["label"] + + "
" + ); + } else { + item.append( + '
' + + values["label"] + + "
" + ); + } + + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item.append($input); + } else { + item.append($image).append($input); + } + } + + if (values["show_statistics"] != 1) { + set_static_graph_status(id_data, values["image"]); + } else { + set_static_graph_status(id_data, "show_statistics"); + } + + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + // Do none + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } + + break; + + case "static_graph": + class_type = "static_graph"; + + img_src = "images/spinner.gif"; + + item = $("
") + .attr("id", id_data) + .attr("class", "item " + class_type) + .css("text-align", "left") + .css("position", "absolute") + .css("display", "inline-block") + .css("top", values["top"] + "px") + .css("left", values["left"] + "px"); + + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src); + } + + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + // Do none + if (values["image"] != "" && values["image"] != "none") { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } + // else{ + // $('#image_'+id_data).css('width', values['width']+'px'); + // $('#image_'+id_data).css('height', values['height']+'px'); + // } + /* var $span = $('') .attr('id', 'text_' + id_data) .attr('class', 'text') .append(values['label']); */ - var $input = $('') - .attr('id', 'hidden-status_' + id_data) - .attr('type', 'hidden') - .attr('value', -1) - .attr('name', 'status_' + id_data); + var $input = $("") + .attr("id", "hidden-status_" + id_data) + .attr("type", "hidden") + .attr("value", -1) + .attr("name", "status_" + id_data); - if(values['label_position'] == 'up'){ - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append('
'+values['label']+'
') - .append($input); - } - else{ - item - .append('
'+values['label']+'
') - .append($image) - .append($image) - .append($input); - } - - } - else if(values['label_position'] == 'down'){ - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append('
'+values['label']+'
') - .append($input); - - } - else{ - item - .append($image) - .append($image) - .append('
'+values['label']+'
') - .append($input); - } - - } - else if(values['label_position'] == 'left'){ - - if(values['height'] == 0){ - item - .append('
'+values['label']+'
'); - } - else{ - item - .append('
'+values['label']+'
') - } - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append($input); - } - else{ - item - .append($image) - .append($image) - .append($input); - } - - - } - else if(values['label_position'] == 'right'){ - if(values['height'] == 0){ - item - .append('
'+values['label']+'
'); - } - else{ - item - .append('
'+values['label']+'
') - } - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append($input); - } - else{ - item - .append($image) - .append($image) - .append($input); - } - - - - } - - if(values['show_statistics'] != 1){ - set_static_graph_status(id_data, values['image']); - } - else{ - set_static_graph_status(id_data, 'show_statistics'); - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - - if(values['image'] != '' && values['image'] != 'none'){ - // Do none - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } + if (values["label_position"] == "up") { + if (values["image"] == "" || values["image"] == "none") { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } else { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($image) + .append($image) + .append($input); + } + } else if (values["label_position"] == "down") { + if (values["image"] == "" || values["image"] == "none") { + item + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } else { + item + .append($image) + .append($image) + .append( + '
' + + values["label"] + + "
" + ) + .append($input); + } + } else if (values["label_position"] == "left") { + if (values["height"] == 0) { + item.append( + '
' + + values["label"] + + "
" + ); + } else { + item.append( + '
' + + values["label"] + + "
" + ); + } - break; - case 'auto_sla_graph': - var sizeStyle = ''; - var imageSize = ''; - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); + if (values["image"] == "" || values["image"] == "none") { + item.append($input); + } else { + item + .append($image) + .append($image) + .append($input); + } + } else if (values["label_position"] == "right") { + if (values["height"] == 0) { + item.append( + '
' + + values["label"] + + "
" + ); + } else { + item.append( + '
' + + values["label"] + + "
" + ); + } - setEventsBar(id_data, values); - break; - case 'donut_graph': - var sizeStyle = ''; - var imageSize = ''; - item = $('
' + - '' + - '
' - ); + if (values["image"] == "" || values["image"] == "none") { + item.append($input); + } else { + item + .append($image) + .append($image) + .append($input); + } + } - setDonutsGraph(id_data, values); - break; - case 'percentile_bar': - case 'percentile_item': - var sizeStyle = ''; - var imageSize = ''; + if (values["show_statistics"] != 1) { + set_static_graph_status(id_data, values["image"]); + } else { + set_static_graph_status(id_data, "show_statistics"); + } - if (values['type_percentile'] == 'percentile') { - - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - - setPercentileBar(id_data, values); - } - else if (values['type_percentile'] == 'circular_progress_bar') { - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - - setPercentileCircular(id_data, values); - } - else if (values['type_percentile'] == 'interior_circular_progress_bar') { - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - - } - - setPercentileInteriorCircular(id_data, values); - } - else { - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - setPercentileBubble(id_data, values); - } - break; - case 'module_graph': - sizeStyle = ''; - imageSize = ''; + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + // Do none + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } + break; + case "auto_sla_graph": + var sizeStyle = ""; + var imageSize = ""; + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); - - setModuleGraph(id_data); - break; - case 'bars_graph': - sizeStyle = ''; - imageSize = ''; + setEventsBar(id_data, values); + break; + case "donut_graph": + var sizeStyle = ""; + var imageSize = ""; + item = $( + '
' + + '' + + "
" + ); - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } + setDonutsGraph(id_data, values); + break; + case "percentile_bar": + case "percentile_item": + var sizeStyle = ""; + var imageSize = ""; - - setBarsGraph(id_data, values); - break; - case 'clock': - sizeStyle = ''; - imageSize = ''; + if (values["type_percentile"] == "percentile") { + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } - if(values['label_position'] == 'up'){ - item = $('
' + - '
' + values['label'] + '
' + - '' + - '
' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
' + - '' + - '
' + values['label'] + '
' + - '
' - ); - } - - setClock(id_data, values); - - break; - case 'simple_value': - sizeStyle = ''; - imageSize = ''; - if($('#data_image_check').html() == 'On'){ - values['label'] = ''; - - } - item = $('
' + - ' ' + values['label'] + ' ' + '
' - ); - break; - case 'label': - item = $('
' + - '' + - values['label'] + - '' + - '
' - ); - break; - case 'icon': - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalWidth'] > 150){ - sizeStyle = 'width: ' + '70' + 'px; height: ' + '70' + 'px;'; - imageSize = 'width="' + '70' + '" height="' + '70' + '"'; - } - } - else { - sizeStyle = 'width: ' + values['width'] + 'px; height: ' + values['height'] + 'px;'; - imageSize = 'width="' + values['width'] + '" height="' + values['height'] + '"'; - } + setPercentileBar(id_data, values); + } else if (values["type_percentile"] == "circular_progress_bar") { + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } - item = $('
' + - '
' + - '
' - ); - var image = values['image'] + ".png"; - set_image("image", id_data, image); - break; - case 'color_cloud': - var diameter = values["diameter"] || values["width"] || 100; + setPercentileCircular(id_data, values); + } else if ( + values["type_percentile"] == "interior_circular_progress_bar" + ) { + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } - item = $('
' + - '' + - '
' - ); - setColorCloud(id_visual_console, id_data, item); - break; - default: - //Maybe create in any Enterprise item. - if (typeof(enterprise_createItem) == 'function') { - if (values['image'] == "") { - values['image'] = 'visualmap.services'; - } - temp_item = enterprise_createItem(type, values, id_data); - if (temp_item != false) { - item = temp_item; - } - $('#'+id_data).css({'width':'','height':''}); - } - break; - } + setPercentileInteriorCircular(id_data, values); + } else { + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } + setPercentileBubble(id_data, values); + } + break; + case "module_graph": + sizeStyle = ""; + imageSize = ""; - $("#background").append(item); + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } - if (values['parent'] != 0) { - var line = {"id": id_data, - "node_begin": values['parent'], - "node_end": id_data, - "color": '#cccccc' }; + setModuleGraph(id_data); + break; + case "bars_graph": + sizeStyle = ""; + imageSize = ""; - lines.push(line); + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } - set_color_line_status(lines, id_data, values); + setBarsGraph(id_data, values); + break; + case "clock": + sizeStyle = ""; + imageSize = ""; - refresh_lines(lines, 'background', true); - } - - - if(values['label_position'] == 'right'){ - $('#text_'+id_data).css({'display':'block','float':'right'}); - } - else if(values['label_position'] == 'left'){ - $('#text_'+id_data).css({'display':'block','float':'left'}); - } - - if(values['show_on_top'] == 1){ - $("#" + id_data).css('z-index', '10'); - } - - if(values['show_on_top'] == 0){ - $("#" + id_data).css('z-index', '5'); - } - + if (values["label_position"] == "up") { + item = $( + '
' + + '
' + + values["label"] + + "
" + + '' + + "
" + ); + } else if (values["label_position"] == "down") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "left") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } else if (values["label_position"] == "right") { + item = $( + '
' + + '' + + '
' + + values["label"] + + "
" + + "
" + ); + } + + setClock(id_data, values); + + break; + case "simple_value": + sizeStyle = ""; + imageSize = ""; + if ($("#data_image_check").html() == "On") { + values["label"] = + ''; + } + item = $( + '
' + + ' ' + + values["label"] + + " " + + "
" + ); + break; + case "label": + item = $( + '
" + + '' + + values["label"] + + "" + + "
" + ); + break; + case "icon": + if (values["width"] == 0 || values["height"] == 0) { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalWidth"] > 150 + ) { + sizeStyle = "width: " + "70" + "px; height: " + "70" + "px;"; + imageSize = 'width="' + "70" + '" height="' + "70" + '"'; + } + } else { + sizeStyle = + "width: " + + values["width"] + + "px; height: " + + values["height"] + + "px;"; + imageSize = + 'width="' + values["width"] + '" height="' + values["height"] + '"'; + } + + item = $( + '
' + + '
" + + "
" + ); + var image = values["image"] + ".png"; + set_image("image", id_data, image); + break; + case "color_cloud": + var diameter = values["diameter"] || values["width"] || 100; + + item = $( + '
' + + '' + + "
" + ); + setColorCloud(id_visual_console, id_data, item); + break; + default: + //Maybe create in any Enterprise item. + if (typeof enterprise_createItem == "function") { + if (values["image"] == "") { + values["image"] = "visualmap.services"; + } + temp_item = enterprise_createItem(type, values, id_data); + if (temp_item != false) { + item = temp_item; + } + $("#" + id_data).css({ width: "", height: "" }); + } + break; + } + + $("#background").append(item); + + if (values["parent"] != 0) { + var line = { + id: id_data, + node_begin: values["parent"], + node_end: id_data, + color: "#cccccc" + }; + + lines.push(line); + + set_color_line_status(lines, id_data, values); + + refresh_lines(lines, "background", true); + } + + if (values["label_position"] == "right") { + $("#text_" + id_data).css({ display: "block", float: "right" }); + } else if (values["label_position"] == "left") { + $("#text_" + id_data).css({ display: "block", float: "left" }); + } + + if (values["show_on_top"] == 1) { + $("#" + id_data).css("z-index", "10"); + } + + if (values["show_on_top"] == 0) { + $("#" + id_data).css("z-index", "5"); + } } function addItemSelectParents(id_data, text) { - parents[id_data] = text; - //$("#parent").append($('')); + parents[id_data] = text; + //$("#parent").append($('')); } function insertDB(type, values) { - - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - $("#saving_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#saving_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - var id = null; + var id = null; - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "insert"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "type", value: type}); - jQuery.each(values, function(key, val) { - parameter.push ({name: key, value: val}); - }); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "insert" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: type }); + jQuery.each(values, function(key, val) { + parameter.push({ name: key, value: val }); + }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - id = data['id_data']; - var image_to_show = $('#preview > img')[0]; - if((type === 'group_item') || (type === 'icon') || (type === 'static_graph' && typeof(image_to_show) !== 'undefined')){ - values['naturalWidth'] = image_to_show.naturalWidth; - values['naturalHeight'] = image_to_show.naturalHeight; - } - createItem(type, values, id); - addItemSelectParents(id, data['text']); - //Reload all events for the item and new item. - eventsItems(); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + id = data["id_data"]; + var image_to_show = $("#preview > img")[0]; + if ( + type === "group_item" || + type === "icon" || + (type === "static_graph" && typeof image_to_show !== "undefined") + ) { + values["naturalWidth"] = image_to_show.naturalWidth; + values["naturalHeight"] = image_to_show.naturalHeight; + } + createItem(type, values, id); + addItemSelectParents(id, data["text"]); + //Reload all events for the item and new item. + eventsItems(); - switch (type) { - case 'line_item': - var line = { - "id": id, - "start_x": values['line_start_x'], - "start_y": values['line_start_y'], - "end_x": values['line_end_x'], - "end_y": values['line_end_y'], - "line_width": values['line_width'], - "line_color": values['line_color']}; + switch (type) { + case "line_item": + var line = { + id: id, + start_x: values["line_start_x"], + start_y: values["line_start_y"], + end_x: values["line_end_x"], + end_y: values["line_end_y"], + line_width: values["line_width"], + line_color: values["line_color"] + }; - user_lines.push(line); + user_lines.push(line); - // Draw handlers - radious_handle = 6; + // Draw handlers + radious_handle = 6; - // Draw handler start - item = $('
' + + // Draw handler start + item = $( + '
' + + '' + + "
" + ); + $("#background").append(item); - '' + + // Draw handler stop + item = $( + '
' + + '' + + "
" + ); + $("#background").append(item); + break; + } - '
' - ); - $("#background").append(item); - - // Draw handler stop - item = $('
' + - - '' + - - '
' - ); - $("#background").append(item); - break; - } - - $("#saving_in_progress_dialog").dialog("close"); - //Reload all events for the item and new item. - eventsItems(); - } - else { - //TODO - } - } - }); + $("#saving_in_progress_dialog").dialog("close"); + //Reload all events for the item and new item. + eventsItems(); + } else { + //TODO + } + } + }); } -function updateDB_visual(type, idElement , values, event, top, left) { - metaconsole = $("input[name='metaconsole']").val(); +function updateDB_visual(type, idElement, values, event, top, left) { + metaconsole = $("input[name='metaconsole']").val(); - radious_handle = 6; + radious_handle = 6; - switch (type) { - case 'handler_start': - $("#handler_start_" + idElement) - .css('top', (top - radious_handle) + 'px'); - $("#handler_start_" + idElement) - .css('left', left + 'px'); - break; - case 'handler_end': + switch (type) { + case "handler_start": + $("#handler_start_" + idElement).css("top", top - radious_handle + "px"); + $("#handler_start_" + idElement).css("left", left + "px"); + break; + case "handler_end": + $("#handler_end_" + idElement).css("top", top - radious_handle + "px"); + $("#handler_end_" + idElement).css("left", left + "px"); + break; + case "group_item": + case "static_graph": + if ( + event != "resizestop" && + event != "show_grid" && + event != "dragstop" + ) { + if (values["show_statistics"] != 1) { + set_static_graph_status(idElement, values["image"]); + } + } + $("#" + idElement).css("left", left + "px"); + $("#" + idElement).css("top", top + "px"); + break; + case "percentile_item": + case "simple_value": + case "label": + case "icon": + case "module_graph": + case "bars_graph": + case "clock": + case "auto_sla_graph": + case "donut_graph": + if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + $("#" + idElement) + .css("top", "0px") + .css("top", top + "px"); + $("#" + idElement) + .css("left", "0px") + .css("left", left + "px"); + } else { + $("#" + idElement) + .css("top", "0px") + .css("top", top + "px"); + $("#" + idElement) + .css("left", "0px") + .css("left", left + "px"); + } - $("#handler_end_" + idElement).css('top', (top - radious_handle) + 'px'); - $("#handler_end_" + idElement).css('left', (left) + 'px'); - break; - case 'group_item': - case 'static_graph': - if ((event != 'resizestop') && (event != 'show_grid') - && (event != 'dragstop')) { - if(values['show_statistics'] != 1){ - set_static_graph_status(idElement, values['image']); - } - } - $("#" + idElement).css('left', left + 'px'); - $("#" + idElement).css('top', top + 'px'); - break; - case 'percentile_item': - case 'simple_value': - case 'label': - case 'icon': - case 'module_graph': - case 'bars_graph': - case 'clock': - case 'auto_sla_graph': - case 'donut_graph': - if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - $("#" + idElement).css('top', '0px').css('top', top + 'px'); - $("#" + idElement).css('left', '0px').css('left', left + 'px'); - } - else{ - $("#" + idElement).css('top', '0px').css('top', top + 'px'); - $("#" + idElement).css('left', '0px').css('left', left + 'px'); - } + //Update the lines + end_foreach = false; + found = false; + jQuery.each(lines, function(i, line) { + if (end_foreach) { + return; + } - //Update the lines - end_foreach = false; - found = false; - jQuery.each(lines, function(i, line) { - if (end_foreach) { - return; - } + if (lines[i]["node_end"] == idElement) { + found = true; + if (values["parent"] == 0) { + //Erased the line + lines.splice(i, 1); + end_foreach = true; + } else { + if ( + typeof values["mov_left"] == "undefined" && + typeof values["mov_top"] == "undefined" && + typeof values["absolute_left"] == "undefined" && + typeof values["absolute_top"] == "undefined" + ) { + lines[i]["node_begin"] = values["parent"]; + } + } + } + }); - if (lines[i]['node_end'] == idElement) { - found = true; - if (values['parent'] == 0) { - //Erased the line - lines.splice(i, 1); - end_foreach = true; - } - else { - if ((typeof(values['mov_left']) == 'undefined') && - (typeof(values['mov_top']) == 'undefined') && - (typeof(values['absolute_left']) == 'undefined') && - (typeof(values['absolute_top']) == 'undefined')) { - lines[i]['node_begin'] = values['parent']; - } - } - } - }); - - if (typeof(values['parent']) != 'undefined' && values['parent'] > 0 ) { - if (!found) { - set_color_line_status(lines, idElement, values); - } - } - - break; - case 'color_cloud': - var diameter = values["diameter"]; - var $container = $("#" + idElement + ".item.color_cloud"); - if ($container.children("img").length === 0) { - $container.append( - '' - ); - } - setColorCloud(id_visual_console, idElement, $container); - break; - case 'background': - if(values['width'] == '0' || values['height'] == '0'){ - $("#background").css('width', $("#hidden-background_width").val() + 'px'); - $("#background").css('height', $("#hidden-background_height").val() + 'px'); - } - else { - $("#background").css('width', values['width'] + 'px'); - $("#background").css('height', values['height'] + 'px'); - } - break; - case 'service': - refresh_lines(lines, 'background', true); - break; - } - - refresh_lines(lines, 'background', true); - draw_user_lines("", 0, 0, 0 , 0, 0, true); - - if(values['show_on_top'] == 1){ - $("#" + idElement).css('z-index',10); - } - - if(values['show_on_top'] == 0){ - $("#" + idElement).css('z-index',5); - } + if (typeof values["parent"] != "undefined" && values["parent"] > 0) { + if (!found) { + set_color_line_status(lines, idElement, values); + } + } + break; + case "color_cloud": + var diameter = values["diameter"]; + var $container = $("#" + idElement + ".item.color_cloud"); + if ($container.children("img").length === 0) { + $container.append( + '' + ); + } + setColorCloud(id_visual_console, idElement, $container); + break; + case "background": + if (values["width"] == "0" || values["height"] == "0") { + $("#background").css( + "width", + $("#hidden-background_width").val() + "px" + ); + $("#background").css( + "height", + $("#hidden-background_height").val() + "px" + ); + } else { + $("#background").css("width", values["width"] + "px"); + $("#background").css("height", values["height"] + "px"); + } + break; + case "service": + refresh_lines(lines, "background", true); + break; + } + + refresh_lines(lines, "background", true); + draw_user_lines("", 0, 0, 0, 0, 0, true); + + if (values["show_on_top"] == 1) { + $("#" + idElement).css("z-index", 10); + } + + if (values["show_on_top"] == 0) { + $("#" + idElement).css("z-index", 5); + } } -function updateDB(type, idElement , values, event) { - metaconsole = $("input[name='metaconsole']").val(); +function updateDB(type, idElement, values, event) { + metaconsole = $("input[name='metaconsole']").val(); - var top = typeof(values.top) != 'undefined' ? values.top : 0; - var left = typeof(values.left) != 'undefined' ? values.left : 0; + var top = typeof values.top != "undefined" ? values.top : 0; + var left = typeof values.left != "undefined" ? values.left : 0; - action = "update"; + action = "update"; - //Check if the event parameter in function is passed in the call. - if (event != null) { - switch (event) { - case 'show_grid': - case 'resizestop': - //Force to move action when resize a background, for to avoid - //lost the label. - case 'dragstop': + //Check if the event parameter in function is passed in the call. + if (event != null) { + switch (event) { + case "show_grid": + case "resizestop": + //Force to move action when resize a background, for to avoid + //lost the label. + case "dragstop": + switch (type) { + case "handler_start": + idElement = idElement.replace("handler_start_", ""); + break; + case "handler_end": + idElement = idElement.replace("handler_end_", ""); + break; + } - switch (type) { - case 'handler_start': - idElement = idElement.replace("handler_start_", ""); - break; - case 'handler_end': - idElement = idElement.replace("handler_end_", ""); - break; - } + action = "move"; + break; + } + } - action = "move"; - break; - } - } + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: action }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: type }); + parameter.push({ name: "id_element", value: idElement }); - parameter = Array(); - parameter.push({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push({name: "action", value: action}); - parameter.push({name: "id_visual_console", - value: id_visual_console}); - parameter.push({name: "type", value: type}); - parameter.push({name: "id_element", value: idElement}); + jQuery.each(values, function(key, val) { + parameter.push({ name: key, value: val }); + }); - jQuery.each(values, function(key, val) { - parameter.push({name: key, value: val}); - }); + switch (type) { + // -- line_item -- + case "handler_start": + // --------------- - switch (type) { - // -- line_item -- - case 'handler_start': - // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_start_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_start_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_start_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_start_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + //Added the radious of image point of handler + top = top + 6; + left = left + 6; - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + update_user_line(type, idElement, top, left); + break; + // -- line_item -- + case "handler_end": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_end_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_end_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } - update_user_line(type, idElement, top, left); - break; - // -- line_item -- - case 'handler_end': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_end_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_end_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + //Added the radious of image point of handler + top = top + 6; + left = left + 6; - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + update_user_line(type, idElement, top, left); + break; + default: + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } + break; + } - update_user_line(type, idElement, top, left); - break; - default: - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } - break; - } + if (typeof top != "undefined" && typeof left != "undefined") { + if ( + typeof values["top"] == "undefined" && + typeof values["left"] == "undefined" + ) { + parameter.push({ name: "top", value: top }); + parameter.push({ name: "left", value: left }); + } else { + values["top"] = top; + values["left"] = left; + } + } - if ((typeof(top) != 'undefined') && (typeof(left) != 'undefined')) { - if ((typeof(values['top']) == 'undefined') && - (typeof(values['left']) == 'undefined')) { - parameter.push ({name: 'top', value: top}); - parameter.push ({name: 'left', value: left}); - } - else { - values['top'] = top; - values['left'] = left; - } - } + success_update = false; + if (!autosave) { + list_actions_pending_save.push(parameter); + //At the moment for to show correctly. + updateDB_visual(type, idElement, values, event, top, left); + } else { + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + if (data["new_line"]) { + var line = { + id: idElement, + node_begin: values["parent"], + node_end: idElement, + color: "#cccccc" + }; - success_update = false; - if (!autosave) { - list_actions_pending_save.push(parameter); - //At the moment for to show correctly. - updateDB_visual(type, idElement , values, event, top, left); - } - else { - - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - if (data['new_line']) { - var line = {"id": idElement, - "node_begin": values['parent'], - "node_end": idElement, - "color": '#cccccc' }; - - lines.push(line); - } - updateDB_visual(type, idElement , values, event, top, left); - } - } - }); - } + lines.push(line); + } + updateDB_visual(type, idElement, values, event, top, left); + } + } + }); + } } function copyDB(idItem) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "copy"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "id_element", value: idItem}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "copy" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "id_element", value: idItem }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - values = data['values']; - type = data['type']; - id = data['id_data']; - - if((type === 'group_item') || (type === 'icon') || (type === 'static_graph')){ - values['naturalWidth'] = $('#image_'+idItem).prop('naturalWidth'); - values['naturalHeight'] = $('#image_'+idItem).prop('naturalHeight'); - } - - createItem(type, values, id); - addItemSelectParents(id, data['text']); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + values = data["values"]; + type = data["type"]; + id = data["id_data"]; - //Reload all events for the item and new item. - eventsItems(); - } - else { - //TODO - } - } - }); + if ( + type === "group_item" || + type === "icon" || + type === "static_graph" + ) { + values["naturalWidth"] = $("#image_" + idItem).prop("naturalWidth"); + values["naturalHeight"] = $("#image_" + idItem).prop("naturalHeight"); + } + + createItem(type, values, id); + addItemSelectParents(id, data["text"]); + + //Reload all events for the item and new item. + eventsItems(); + } else { + //TODO + } + } + }); } function deleteDB(idElement) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - $("#delete_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#delete_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "delete"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "id_element", value: idElement}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "delete" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "id_element", value: idElement }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) - { - if (data['correct']) { - $("#parent > option[value=" + idElement + "]").remove(); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + $("#parent > option[value=" + idElement + "]").remove(); + jQuery.each(lines, function(i, line) { + if (typeof line == "undefined") { + return; //Continue + } - jQuery.each(lines, function(i, line) { - if (typeof(line) == 'undefined') { - return; //Continue - } + if (line["id"] == idElement || line["node_begin"] == idElement) { + lines.splice(i, 1); + } + }); - if ((line['id'] == idElement) - || (line['node_begin'] == idElement)) { + if ( + $("#handler_start_" + idElement).length || + $("#handler_end_" + idElement).length + ) { + // Line item - lines.splice(i, 1); - } - }); + $("#handler_start_" + idElement).remove(); + $("#handler_end_" + idElement).remove(); - if ($("#handler_start_" + idElement).length || - $("#handler_end_" + idElement).length) { + delete_user_line(idElement); + } - // Line item + refresh_lines(lines, "background", true); - $("#handler_start_" + idElement).remove(); - $("#handler_end_" + idElement).remove(); + draw_user_lines("", 0, 0, 0, 0, 0, true); - delete_user_line(idElement); - } + $("#" + idElement).remove(); + activeToolboxButton("delete_item", false); - - refresh_lines(lines, 'background', true); - - draw_user_lines("", 0, 0, 0 , 0, 0, true); - - $('#' + idElement).remove(); - activeToolboxButton('delete_item', false); - - $("#delete_in_progress_dialog").dialog("close"); - } - else { - //TODO - } - } - }); + $("#delete_in_progress_dialog").dialog("close"); + } else { + //TODO + } + } + }); } function activeToolboxButton(id, active) { - if ($("input." + id + "[name=button_toolbox2]").length == 0) { - return; - } + if ($("input." + id + "[name=button_toolbox2]").length == 0) { + return; + } - if (active) { - $("input." + id + "[name=button_toolbox2]") - .removeAttr('disabled'); - } - else { - $("input." + id + "[name=button_toolbox2]") - .attr('disabled', true); - } + if (active) { + $("input." + id + "[name=button_toolbox2]").removeAttr("disabled"); + } else { + $("input." + id + "[name=button_toolbox2]").attr("disabled", true); + } } function click_delete_item_callback() { - if(selectedItems == null){ - activeToolboxButton('edit_item', false); - deleteDB(idItem); - idItem = 0; - selectedItem = null; - } - else{ - idItem = 0; - selectedItem = null; - selectedItems.forEach( function(valor, indice, array) { - deleteDB(valor); - }); - } + if (selectedItems == null) { + activeToolboxButton("edit_item", false); + deleteDB(idItem); + idItem = 0; + selectedItem = null; + } else { + idItem = 0; + selectedItem = null; + selectedItems.forEach(function(valor, indice, array) { + deleteDB(valor); + }); + } } /** @@ -4255,1190 +5335,1272 @@ function click_delete_item_callback() { * drop. */ function eventsItems(drag) { - if (typeof(drag) == 'undefined') { - drag = false; - } + if (typeof drag == "undefined") { + drag = false; + } - $('.item').unbind('click'); - $('.item').unbind('dragstop'); - $('.item').unbind('dragstart'); + $(".item").unbind("click"); + $(".item").unbind("dragstop"); + $(".item").unbind("dragstart"); - //$(".item").resizable(); //Disable but run in ff and in the waste (aka micro$oft IE) show ungly borders + //$(".item").resizable(); //Disable but run in ff and in the waste (aka micro$oft IE) show ungly borders - $('.item').bind('click', function(event, ui) { - - event.stopPropagation(); - if (!is_opened_palette) { - var divParent = $(event.target); - while (!$(divParent).hasClass("item")) { - divParent = $(divParent).parent(); - } - unselectAll(); - $(divParent).attr('withborder','true'); - $(divParent).css('border', '1px blue dotted'); - $(divParent).css('left', '-=1px'); - $(divParent).css('top', '-=1px'); - - if ($(divParent).hasClass('box_item')) { - creationItem = null; - selectedItem = 'box_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('static_graph')) { - creationItem = null; - selectedItem = 'static_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('auto_sla_graph')) { - creationItem = null; - selectedItem = 'auto_sla_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('donut_graph')) { - creationItem = null; - selectedItem = 'donut_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('group_item')) { - creationItem = null; - selectedItem = 'group_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('percentile_item')) { - creationItem = null; - selectedItem = 'percentile_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('module_graph')) { - creationItem = null; - selectedItem = 'module_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('bars_graph')) { - creationItem = null; - selectedItem = 'bars_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('simple_value')) { - creationItem = null; - selectedItem = 'simple_value'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('label')) { - creationItem = null; - selectedItem = 'label'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('icon')) { - creationItem = null; - selectedItem = 'icon'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('clock')) { - creationItem = null; - selectedItem = 'clock'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('color_cloud')) { - creationItem = null; - selectedItem = 'color_cloud'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('handler_start')) { - idItem = $(divParent).attr('id') - .replace("handler_start_", ""); - creationItem = null; - selectedItem = 'handler_start'; - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('handler_end')) { - idItem = $(divParent).attr('id') - .replace("handler_end_", ""); - creationItem = null; - selectedItem = 'handler_end'; - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } + $(".item").bind("click", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette) { + var divParent = $(event.target); + while (!$(divParent).hasClass("item")) { + divParent = $(divParent).parent(); + } + unselectAll(); + $(divParent).attr("withborder", "true"); + $(divParent).css("border", "1px blue dotted"); + $(divParent).css("left", "-=1px"); + $(divParent).css("top", "-=1px"); - //Maybe receive a click event any Enterprise item. - if (typeof(enterprise_click_item_callback) == 'function') { - enterprise_click_item_callback(divParent); - } - } - - - - if(!event.ctrlKey){ - firstItem = event.currentTarget.id; - selectedItems = null; - selectedItems = Array(); - selectedItems.push(event.currentTarget.id); + if ($(divParent).hasClass("box_item")) { + creationItem = null; + selectedItem = "box_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("static_graph")) { + creationItem = null; + selectedItem = "static_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("auto_sla_graph")) { + creationItem = null; + selectedItem = "auto_sla_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("donut_graph")) { + creationItem = null; + selectedItem = "donut_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("group_item")) { + creationItem = null; + selectedItem = "group_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("percentile_item")) { + creationItem = null; + selectedItem = "percentile_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("module_graph")) { + creationItem = null; + selectedItem = "module_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("bars_graph")) { + creationItem = null; + selectedItem = "bars_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("simple_value")) { + creationItem = null; + selectedItem = "simple_value"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("label")) { + creationItem = null; + selectedItem = "label"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("icon")) { + creationItem = null; + selectedItem = "icon"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("clock")) { + creationItem = null; + selectedItem = "clock"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("color_cloud")) { + creationItem = null; + selectedItem = "color_cloud"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("handler_start")) { + idItem = $(divParent) + .attr("id") + .replace("handler_start_", ""); + creationItem = null; + selectedItem = "handler_start"; + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("handler_end")) { + idItem = $(divParent) + .attr("id") + .replace("handler_end_", ""); + creationItem = null; + selectedItem = "handler_end"; + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } - } - else{ - - selectedItem = null; - - unselectAll(); - - if(selectedItems.indexOf(event.currentTarget.id) > -1){ - - $('#'+event.currentTarget.id).css('left', '+=1'); - $('#'+event.currentTarget.id).css('top', '+=1'); - $('#'+event.currentTarget.id).css('border', ''); - $('#'+event.currentTarget.id).attr('withborder') == 'false'; - - - selectedItems.splice(selectedItems.indexOf(event.currentTarget.id),1); - } - else{ - $('#'+event.currentTarget.id).css('left', '-=1'); - $('#'+event.currentTarget.id).css('top', '-=1'); - $('#'+event.currentTarget.id).css('border', '1px dotted rgb(0, 0, 255)'); - $('#'+event.currentTarget.id).attr('withborder') == 'true'; - - - selectedItems.push(event.currentTarget.id); - } - - - selectedItems.forEach( function(valor, indice, array) { - if(selectedItems.indexOf(valor) > -1 && $('#'+valor).css('border') != '1px dotted rgb(0, 0, 255)'){ - // $('#'+valor).css('left', '-=1'); - // $('#'+valor).css('top', '-=1'); - $('#'+valor).css('border', '1px dotted rgb(0, 0, 255)'); - $('#'+valor).attr('withborder') == 'true'; - } - }); - - $('#'+firstItem).css('left', '-=1'); - $('#'+firstItem).css('top', '-=1'); - - firstItem = null; - - } - - - - - }); + //Maybe receive a click event any Enterprise item. + if (typeof enterprise_click_item_callback == "function") { + enterprise_click_item_callback(divParent); + } + } - //Double click in the item - $('.item').bind('dblclick', function(event, ui) { + if (!event.ctrlKey) { + firstItem = event.currentTarget.id; + selectedItems = null; + selectedItems = Array(); + selectedItems.push(event.currentTarget.id); + } else { + selectedItem = null; - event.stopPropagation(); - if ((!is_opened_palette) && (autosave)) { - toggle_item_palette(); - } - - if(selectedItem == 'simple_value'){ - $('#data_image_width').val(event.currentTarget.clientWidth); - - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_image_from_module"}); - parameter.push ({name: "id_element", value: idItem}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); + unselectAll(); - jQuery.ajax({ - url: "ajax.php", - data: parameter, - type: "POST", - dataType: "json", - success: function(data) { - if(!data['correct']){ - $("#data_image_check").html('Off'); - $('#data_image_container').css('display','none'); - $('#data_image_check').css('display','none'); - $('#data_image_check_label').css('display','none'); - $('.block_tinymce').remove(); - $('#process_value_row').css('display','table-row'); - if($('#process_value').val() != '0'){ - $('#period_row').css('display','table-row'); - } - } - else{ - $('#data_image_container').css('display','inline'); - $('#data_image_check').css('display','inline'); - $('#data_image_check_label').css('display','inline'); - $("#data_image_check").html('On'); - $('#process_value_row').css('display','none'); - $('#period_row').css('display','none'); - $('#text-label_ifr').contents().find('#tinymce').html('_VALUE_'); - $('.block_tinymce').remove(); - $('#label_row').append('
'); - } - } - }); - } - else{ - $("#data_image_check").css('display','none'); - $("#data_image_check_label").css('display','none'); - $('#data_image_container').css('display','none'); - } - - }); + if (selectedItems.indexOf(event.currentTarget.id) > -1) { + $("#" + event.currentTarget.id).css("left", "+=1"); + $("#" + event.currentTarget.id).css("top", "+=1"); + $("#" + event.currentTarget.id).css("border", ""); + $("#" + event.currentTarget.id).attr("withborder") == "false"; - //Set the limit of draggable in the div with id "background" and set drag - //by default is false. - $(".item").draggable({containment: "#background", grid: drag}); + selectedItems.splice(selectedItems.indexOf(event.currentTarget.id), 1); + } else { + $("#" + event.currentTarget.id).css("left", "-=1"); + $("#" + event.currentTarget.id).css("top", "-=1"); + $("#" + event.currentTarget.id).css( + "border", + "1px dotted rgb(0, 0, 255)" + ); + $("#" + event.currentTarget.id).attr("withborder") == "true"; - $('.item').bind('dragstart', function(event, ui) { - - if(selectedItems == null || selectedItems.length < 2){ - event.stopPropagation(); - if (!is_opened_palette) { - unselectAll(); - $(event.target).css('border', '1px blue dotted'); + selectedItems.push(event.currentTarget.id); + } - selectedItem = null; - if ($(event.target).hasClass('box_item')) { - selectedItem = 'box_item'; - } - if ($(event.target).hasClass('static_graph')) { - selectedItem = 'static_graph'; - } - if ($(event.target).hasClass('auto_sla_graph')) { - selectedItem = 'auto_sla_graph'; - } - if ($(event.target).hasClass('donut_graph')) { - selectedItem = 'donut_graph'; - } - if ($(event.target).hasClass('group_item')) { - selectedItem = 'group_item'; - } - if ($(event.target).hasClass('percentile_item')) { - selectedItem = 'percentile_item'; - } - if ($(event.target).hasClass('module_graph')) { - selectedItem = 'module_graph'; - } - if ($(event.target).hasClass('bars_graph')) { - selectedItem = 'bars_graph'; - } - if ($(event.target).hasClass('simple_value')) { - selectedItem = 'simple_value'; - } - if ($(event.target).hasClass('label')) { - selectedItem = 'label'; - } - if ($(event.target).hasClass('icon')) { - selectedItem = 'icon'; - } - if ($(event.target).hasClass('clock')) { - selectedItem = 'clock'; - } - if ($(event.target).hasClass('color_cloud')) { - selectedItem = 'color_cloud'; - } - if ($(event.target).hasClass('handler_start')) { - selectedItem = 'handler_start'; - } - if ($(event.target).hasClass('handler_end')) { - selectedItem = 'handler_end'; - } + selectedItems.forEach(function(valor, indice, array) { + if ( + selectedItems.indexOf(valor) > -1 && + $("#" + valor).css("border") != "1px dotted rgb(0, 0, 255)" + ) { + // $('#'+valor).css('left', '-=1'); + // $('#'+valor).css('top', '-=1'); + $("#" + valor).css("border", "1px dotted rgb(0, 0, 255)"); + $("#" + valor).attr("withborder") == "true"; + } + }); - if (selectedItem == null) { - //Maybe receive a click event any Enterprise item. - if (typeof(enterprise_dragstart_item_callback) == 'function') { - selectedItem = enterprise_dragstart_item_callback(event); - } - } + $("#" + firstItem).css("left", "-=1"); + $("#" + firstItem).css("top", "-=1"); - if (selectedItem != null) { - creationItem = null; + firstItem = null; + } + }); - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - idItem = $(event.target).attr('id') - .replace("handler_start_", ""); - break; - // -- line_item -- - case 'handler_end': - // --------------- - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - break; - default: - idItem = $(event.target).attr('id'); - - break; - } - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - } - } - } - else{ - multiDragStart(event); - - } - }); + //Double click in the item + $(".item").bind("dblclick", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette && autosave) { + toggle_item_palette(); + } - $('.item').bind('dragstop', function(event, ui) { - if(selectedItems == null || selectedItems.length < 2){ - event.stopPropagation(); + if (selectedItem == "simple_value") { + $("#data_image_width").val(event.currentTarget.clientWidth); - var values = {}; - values['mov_left'] = ui.position.left; - values['mov_top'] = ui.position.top; + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_image_from_module" }); + parameter.push({ name: "id_element", value: idItem }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - updateDB(selectedItem, idItem, values, 'dragstop'); - } - else{ - multidragStop(event); - } - }); + jQuery.ajax({ + url: "ajax.php", + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (!data["correct"]) { + $("#data_image_check").html("Off"); + $("#data_image_container").css("display", "none"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $(".block_tinymce").remove(); + $("#process_value_row").css("display", "table-row"); + if ($("#process_value").val() != "0") { + $("#period_row").css("display", "table-row"); + } + } else { + $("#data_image_container").css("display", "inline"); + $("#data_image_check").css("display", "inline"); + $("#data_image_check_label").css("display", "inline"); + $("#data_image_check").html("On"); + $("#process_value_row").css("display", "none"); + $("#period_row").css("display", "none"); + $("#text-label_ifr") + .contents() + .find("#tinymce") + .html("_VALUE_"); + $(".block_tinymce").remove(); + $("#label_row").append( + '
' + ); + } + } + }); + } else { + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $("#data_image_container").css("display", "none"); + } + }); - $('.item').bind('drag', function(event, ui) { - if(selectedItems == null || selectedItems.length < 2){ - if ($(event.target).hasClass('handler_start')) { - selectedItem = 'handler_start'; - } - if ($(event.target).hasClass('handler_end')) { - selectedItem = 'handler_end'; - } + //Set the limit of draggable in the div with id "background" and set drag + //by default is false. + $(".item").draggable({ containment: "#background", grid: drag }); - var values = {}; - values['mov_left'] = ui.position.left; - values['mov_top'] = ui.position.top; + $(".item").bind("dragstart", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + event.stopPropagation(); + if (!is_opened_palette) { + unselectAll(); + $(event.target).css("border", "1px blue dotted"); - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - idElement = $(event.target).attr('id') - .replace("handler_start_", ""); - break; - // -- line_item -- - case 'handler_end': - // --------------- - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - break; - } + selectedItem = null; + if ($(event.target).hasClass("box_item")) { + selectedItem = "box_item"; + } + if ($(event.target).hasClass("static_graph")) { + selectedItem = "static_graph"; + } + if ($(event.target).hasClass("auto_sla_graph")) { + selectedItem = "auto_sla_graph"; + } + if ($(event.target).hasClass("donut_graph")) { + selectedItem = "donut_graph"; + } + if ($(event.target).hasClass("group_item")) { + selectedItem = "group_item"; + } + if ($(event.target).hasClass("percentile_item")) { + selectedItem = "percentile_item"; + } + if ($(event.target).hasClass("module_graph")) { + selectedItem = "module_graph"; + } + if ($(event.target).hasClass("bars_graph")) { + selectedItem = "bars_graph"; + } + if ($(event.target).hasClass("simple_value")) { + selectedItem = "simple_value"; + } + if ($(event.target).hasClass("label")) { + selectedItem = "label"; + } + if ($(event.target).hasClass("icon")) { + selectedItem = "icon"; + } + if ($(event.target).hasClass("clock")) { + selectedItem = "clock"; + } + if ($(event.target).hasClass("color_cloud")) { + selectedItem = "color_cloud"; + } + if ($(event.target).hasClass("handler_start")) { + selectedItem = "handler_start"; + } + if ($(event.target).hasClass("handler_end")) { + selectedItem = "handler_end"; + } - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - var top = parseInt($("#handler_start_" + idElement) - .css('top').replace('px', '')); - var left = parseInt($("#handler_start_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - var top = values['absolute_top']; - var left = values['absolute_left']; - } + if (selectedItem == null) { + //Maybe receive a click event any Enterprise item. + if (typeof enterprise_dragstart_item_callback == "function") { + selectedItem = enterprise_dragstart_item_callback(event); + } + } - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + if (selectedItem != null) { + creationItem = null; - update_user_line('handler_start', idElement, top, left); + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idItem = $(event.target) + .attr("id") + .replace("handler_start_", ""); + break; + // -- line_item -- + case "handler_end": + // --------------- + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + break; + default: + idItem = $(event.target).attr("id"); - draw_user_lines("", 0, 0, 0 , 0, 0, true); - break; - // -- line_item -- - case 'handler_end': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_end_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_end_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + break; + } + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + } + } + } else { + multiDragStart(event); + } + }); - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + $(".item").bind("dragstop", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + event.stopPropagation(); - update_user_line('handler_end', idElement, top, left); + var values = {}; + values["mov_left"] = ui.position.left; + values["mov_top"] = ui.position.top; - draw_user_lines("", 0, 0, 0 , 0, 0, true); - break; - } - } - }); + updateDB(selectedItem, idItem, values, "dragstop"); + } else { + multidragStop(event); + } + }); + + $(".item").bind("drag", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + if ($(event.target).hasClass("handler_start")) { + selectedItem = "handler_start"; + } + if ($(event.target).hasClass("handler_end")) { + selectedItem = "handler_end"; + } + + var values = {}; + values["mov_left"] = ui.position.left; + values["mov_top"] = ui.position.top; + + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idElement = $(event.target) + .attr("id") + .replace("handler_start_", ""); + break; + // -- line_item -- + case "handler_end": + // --------------- + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + break; + } + + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + var top = parseInt( + $("#handler_start_" + idElement) + .css("top") + .replace("px", "") + ); + var left = parseInt( + $("#handler_start_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + var top = values["absolute_top"]; + var left = values["absolute_left"]; + } + + //Added the radious of image point of handler + top = top + 6; + left = left + 6; + + update_user_line("handler_start", idElement, top, left); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + break; + // -- line_item -- + case "handler_end": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_end_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_end_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } + + //Added the radious of image point of handler + top = top + 6; + left = left + 6; + + update_user_line("handler_end", idElement, top, left); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + break; + } + } + }); } /** * Events for the background (click, resize and doubleclick). */ function eventsBackground() { - $("#background").resizable(); + $("#background").resizable(); - $('#background').bind('resizestart', function(event, ui) { - if (!is_opened_palette) { - $("#background").css('border', '2px red solid'); - } - }); + $("#background").bind("resizestart", function(event, ui) { + if (!is_opened_palette) { + $("#background").css("border", "2px red solid"); + } + }); - $('#background').bind('resizestop', function(event, ui) { - if (!is_opened_palette) { - unselectAll(); - - var launch_message = false; - var dont_resize = false; - var values = {}; - var actual_width = $('#background').css('width').replace('px', ''); - var actual_height = $('#background').css('height').replace('px', ''); - - if (actual_width < 1024) { - actual_width = 1024; - $('#background').css('width', 1024); - launch_message = true; - dont_resize = true; - } - if (actual_height < 768) { - actual_height = 768; - $('#background').css('height', 768); - launch_message = true; - dont_resize = true; - } - - values['width'] = actual_width; - values['height'] = actual_height; - - if (!dont_resize) { - updateDB('background', 0, values, 'resizestop'); - - width = ui.size['width']; - height = ui.size['height']; + $("#background").bind("resizestop", function(event, ui) { + if (!is_opened_palette) { + unselectAll(); - original_width = ui.originalSize['width']; - original_height = ui.originalSize['height']; - - move_elements_resize(original_width, original_height, width, height); + var launch_message = false; + var dont_resize = false; + var values = {}; + var actual_width = $("#background") + .css("width") + .replace("px", ""); + var actual_height = $("#background") + .css("height") + .replace("px", ""); - $('#background_grid').css('width', width); - $('#background_grid').css('height', height); - } - else{ - updateDB('background', 0, values, 'resizestop'); - } - if (launch_message) - alert($('#hidden-message_size').val()); - } - }); + if (actual_width < 1024) { + actual_width = 1024; + $("#background").css("width", 1024); + launch_message = true; + dont_resize = true; + } + if (actual_height < 768) { + actual_height = 768; + $("#background").css("height", 768); + launch_message = true; + dont_resize = true; + } - // Event click for background - $("#background").click(function(event) { - selectedItems = null; - selectedItems = Array(); - event.stopPropagation(); - if (!is_opened_palette) { - unselectAll(); - $("#background").css('border', '1px blue dotted'); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', true); + values["width"] = actual_width; + values["height"] = actual_height; - idItem = 0; - creationItem = null; - selectedItem = 'background'; - } - }); + if (!dont_resize) { + updateDB("background", 0, values, "resizestop"); - $('#background').bind('dblclick', function(event, ui) { - event.stopPropagation(); - if ((!is_opened_palette) && (autosave)) { - toggle_item_palette(); - } - $("#show_on_top_row").css('display', 'none'); - $("#show_on_top." + item).css('display', ''); - }); + width = ui.size["width"]; + height = ui.size["height"]; + + original_width = ui.originalSize["width"]; + original_height = ui.originalSize["height"]; + + move_elements_resize(original_width, original_height, width, height); + + $("#background_grid").css("width", width); + $("#background_grid").css("height", height); + } else { + updateDB("background", 0, values, "resizestop"); + } + if (launch_message) alert($("#hidden-message_size").val()); + } + }); + + // Event click for background + $("#background").click(function(event) { + selectedItems = null; + selectedItems = Array(); + event.stopPropagation(); + if (!is_opened_palette) { + unselectAll(); + $("#background").css("border", "1px blue dotted"); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", true); + + idItem = 0; + creationItem = null; + selectedItem = "background"; + } + }); + + $("#background").bind("dblclick", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette && autosave) { + toggle_item_palette(); + } + $("#show_on_top_row").css("display", "none"); + $("#show_on_top." + item).css("display", ""); + }); } function move_elements_resize(original_width, original_height, width, height) { - jQuery.each($(".item"), function(key, value) { - item = value; - idItem = $(item).attr('id'); - classItem = $(item).attr('class').replace('item', '') - .replace('ui-draggable', '').replace('ui-draggable-disabled', '') - .replace(/^\s+/g,'').replace(/\s+$/g,''); + jQuery.each($(".item"), function(key, value) { + item = value; + idItem = $(item).attr("id"); + classItem = $(item) + .attr("class") + .replace("item", "") + .replace("ui-draggable", "") + .replace("ui-draggable-disabled", "") + .replace(/^\s+/g, "") + .replace(/\s+$/g, ""); - old_height = parseInt($(item).css('top').replace('px', '')); - old_width = parseInt($(item).css('left').replace('px', '')); + old_height = parseInt( + $(item) + .css("top") + .replace("px", "") + ); + old_width = parseInt( + $(item) + .css("left") + .replace("px", "") + ); - ratio_width = width / original_width; - ratio_height = height / original_height; + ratio_width = width / original_width; + ratio_height = height / original_height; - new_height = old_height * ratio_height; - new_width = old_width * ratio_width; + new_height = old_height * ratio_height; + new_width = old_width * ratio_width; - var values = {}; + var values = {}; - values['absolute_left'] = new_width; - values['absolute_top'] = new_height; + values["absolute_left"] = new_width; + values["absolute_top"] = new_height; - updateDB(classItem, idItem, values, "resizestop"); - }); + updateDB(classItem, idItem, values, "resizestop"); + }); } function unselectAll() { - $("#background").css('border', '1px lightgray solid'); - $(".item").each(function(){ - $(this).css('border', ''); - if($(this).attr('withborder') == 'true'){ - $(this).css('top', '+=1'); - $(this).css('left', '+=1'); - $(this).attr('withborder', 'false'); - } - - }); - selectedItem = null; + $("#background").css("border", "1px lightgray solid"); + $(".item").each(function() { + $(this).css("border", ""); + if ($(this).attr("withborder") == "true") { + $(this).css("top", "+=1"); + $(this).css("left", "+=1"); + $(this).attr("withborder", "false"); + } + }); + selectedItem = null; } function click_button_toolbox(id) { - switch (id) { - case 'static_graph': - toolbuttonActive = creationItem = 'static_graph'; - toggle_item_palette(); - break; - case 'percentile_bar': - case 'percentile_item': - toolbuttonActive = creationItem = 'percentile_item'; - toggle_item_palette(); - break; - case 'module_graph': - toolbuttonActive = creationItem = 'module_graph'; - toggle_item_palette(); - break; - case 'bars_graph': - toolbuttonActive = creationItem = 'bars_graph'; - toggle_item_palette(); - break; - case 'auto_sla_graph': - toolbuttonActive = creationItem = 'auto_sla_graph'; - toggle_item_palette(); - break; - case 'donut_graph': - toolbuttonActive = creationItem = 'donut_graph'; - toggle_item_palette(); - break; - case 'simple_value': - toolbuttonActive = creationItem = 'simple_value'; - toggle_item_palette(); - $("#period_row." + id).css('display', 'none'); - break; - case 'label': - $("#data_image_width").val(100); - toolbuttonActive = creationItem = 'label'; - toggle_item_palette(); - break; - case 'icon': - toolbuttonActive = creationItem = 'icon'; - toggle_item_palette(); - break; - case 'clock': - toolbuttonActive = creationItem = 'clock'; - toggle_item_palette(); - break; - case 'group_item': - toolbuttonActive = creationItem = 'group_item'; - toggle_item_palette(); - break; - case 'box_item': - toolbuttonActive = creationItem = 'box_item'; - toggle_item_palette(); - break; - case 'line_item': - toolbuttonActive = creationItem = 'line_item'; - toggle_item_palette(); - break; - case 'color_cloud': - toolbuttonActive = creationItem = 'color_cloud'; - toggle_item_palette(); - break; - case 'copy_item': - click_copy_item_callback(); - break; - case 'edit_item': - toggle_item_palette(); - break; - case 'delete_item': - click_delete_item_callback(); - break; - case 'show_grid': - showGrid(); - break; - case 'auto_save': - if (autosave) { - activeToolboxButton('save_visualmap', true); - autosave = false; + switch (id) { + case "static_graph": + toolbuttonActive = creationItem = "static_graph"; + toggle_item_palette(); + break; + case "percentile_bar": + case "percentile_item": + toolbuttonActive = creationItem = "percentile_item"; + toggle_item_palette(); + break; + case "module_graph": + toolbuttonActive = creationItem = "module_graph"; + toggle_item_palette(); + break; + case "bars_graph": + toolbuttonActive = creationItem = "bars_graph"; + toggle_item_palette(); + break; + case "auto_sla_graph": + toolbuttonActive = creationItem = "auto_sla_graph"; + toggle_item_palette(); + break; + case "donut_graph": + toolbuttonActive = creationItem = "donut_graph"; + toggle_item_palette(); + break; + case "simple_value": + toolbuttonActive = creationItem = "simple_value"; + toggle_item_palette(); + $("#period_row." + id).css("display", "none"); + break; + case "label": + $("#data_image_width").val(100); + toolbuttonActive = creationItem = "label"; + toggle_item_palette(); + break; + case "icon": + toolbuttonActive = creationItem = "icon"; + toggle_item_palette(); + break; + case "clock": + toolbuttonActive = creationItem = "clock"; + toggle_item_palette(); + break; + case "group_item": + toolbuttonActive = creationItem = "group_item"; + toggle_item_palette(); + break; + case "box_item": + toolbuttonActive = creationItem = "box_item"; + toggle_item_palette(); + break; + case "line_item": + toolbuttonActive = creationItem = "line_item"; + toggle_item_palette(); + break; + case "color_cloud": + toolbuttonActive = creationItem = "color_cloud"; + toggle_item_palette(); + break; + case "copy_item": + click_copy_item_callback(); + break; + case "edit_item": + toggle_item_palette(); + break; + case "delete_item": + click_delete_item_callback(); + break; + case "show_grid": + showGrid(); + break; + case "auto_save": + if (autosave) { + activeToolboxButton("save_visualmap", true); + autosave = false; - //Disable all toolbox buttons. - //Because when it is not autosave only trace the movements - //the other actions need to contant with the apache server. - //And it is necesary to re-code more parts of code to change - //this method. - activeToolboxButton('static_graph', false); - activeToolboxButton('percentile_item', false); - activeToolboxButton('module_graph', false); - activeToolboxButton('bars_graph', false); - activeToolboxButton('simple_value', false); - activeToolboxButton('label', false); - activeToolboxButton('icon', false); - activeToolboxButton('clock', false); - activeToolboxButton('service', false); - activeToolboxButton('group_item', false); - activeToolboxButton('auto_sla_graph', false); - activeToolboxButton('donut_graph', false); - activeToolboxButton('color_cloud', false); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', false); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', false); - } - else { - activeToolboxButton('save', false); - autosave = true; + //Disable all toolbox buttons. + //Because when it is not autosave only trace the movements + //the other actions need to contant with the apache server. + //And it is necesary to re-code more parts of code to change + //this method. + activeToolboxButton("static_graph", false); + activeToolboxButton("percentile_item", false); + activeToolboxButton("module_graph", false); + activeToolboxButton("bars_graph", false); + activeToolboxButton("simple_value", false); + activeToolboxButton("label", false); + activeToolboxButton("icon", false); + activeToolboxButton("clock", false); + activeToolboxButton("service", false); + activeToolboxButton("group_item", false); + activeToolboxButton("auto_sla_graph", false); + activeToolboxButton("donut_graph", false); + activeToolboxButton("color_cloud", false); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", false); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", false); + } else { + activeToolboxButton("save", false); + autosave = true; - //Reactive the buttons. + //Reactive the buttons. - if ((selectedItem != 'background') && (selectedItem != null)) { - activeToolboxButton('delete_item', true); - } - if (selectedItem == 'background') { - activeToolboxButton('show_grid', true); - } - if (selectedItem != null) { - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - } + if (selectedItem != "background" && selectedItem != null) { + activeToolboxButton("delete_item", true); + } + if (selectedItem == "background") { + activeToolboxButton("show_grid", true); + } + if (selectedItem != null) { + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + } - activeToolboxButton('static_graph', true); - activeToolboxButton('percentile_item', true); - activeToolboxButton('module_graph', true); - activeToolboxButton('bars_graph', true); - activeToolboxButton('simple_value', true); - activeToolboxButton('label', true); - activeToolboxButton('icon', true); - activeToolboxButton('clock', true); - activeToolboxButton('group_item', true); - activeToolboxButton('auto_sla_graph', true); - activeToolboxButton('donut_graph', true); - activeToolboxButton('color_cloud', true); - } - break; - case 'save_visualmap': - $("#saving_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + activeToolboxButton("static_graph", true); + activeToolboxButton("percentile_item", true); + activeToolboxButton("module_graph", true); + activeToolboxButton("bars_graph", true); + activeToolboxButton("simple_value", true); + activeToolboxButton("label", true); + activeToolboxButton("icon", true); + activeToolboxButton("clock", true); + activeToolboxButton("group_item", true); + activeToolboxButton("auto_sla_graph", true); + activeToolboxButton("donut_graph", true); + activeToolboxButton("color_cloud", true); + } + break; + case "save_visualmap": + $("#saving_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - var status = true; - activeToolboxButton('save', false); - jQuery.each(list_actions_pending_save, function(key, action_pending_save) { - jQuery.ajax ({ - type: 'POST', - url: action="ajax.php", - data: action_pending_save, - dataType: 'json', - success: function (data) { - if (data == '0') { - status = false; - } + var status = true; + activeToolboxButton("save", false); + jQuery.each(list_actions_pending_save, function( + key, + action_pending_save + ) { + jQuery.ajax({ + type: "POST", + url: (action = "ajax.php"), + data: action_pending_save, + dataType: "json", + success: function(data) { + if (data == "0") { + status = false; + } - $("#saving_in_progress_dialog").dialog("close"); + $("#saving_in_progress_dialog").dialog("close"); - if (status) { - alert($('#hack_translation_correct_save').html()); - } - else { - alert($('#hack_translation_incorrect_save').html()); - } - activeToolboxButton('save', true); - } - }); - }); + if (status) { + alert($("#hack_translation_correct_save").html()); + } else { + alert($("#hack_translation_incorrect_save").html()); + } + activeToolboxButton("save", true); + } + }); + }); - - break; - default: - //Maybe click in any Enterprise button in toolbox. - if (typeof(enterprise_click_button_toolbox) == 'function') { - enterprise_click_button_toolbox(id); - } - break; - } - $('.ColorPickerDivSample').css('background-color',"black"); + break; + default: + //Maybe click in any Enterprise button in toolbox. + if (typeof enterprise_click_button_toolbox == "function") { + enterprise_click_button_toolbox(id); + } + break; + } + $(".ColorPickerDivSample").css("background-color", "black"); } function showPreview(image) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - switch (toolbuttonActive) { - case 'group_item': - case 'static_graph': - showPreviewStaticGraph(image); - break; - case 'icon': - showPreviewIcon(image); - break; - case 'service': - if (image && image.length > 0) showPreviewIcon(image); - break; - } + switch (toolbuttonActive) { + case "group_item": + case "static_graph": + showPreviewStaticGraph(image); + break; + case "icon": + showPreviewIcon(image); + break; + case "service": + if (image && image.length > 0) showPreviewIcon(image); + break; + } } function showPreviewStaticGraph(staticGraph) { - metaconsole = $("input[name='metaconsole']").val(); - var $spinner = $(""); - $spinner.prop("src", "images/spinner.gif"); + metaconsole = $("input[name='metaconsole']").val(); + var $spinner = $(""); + $spinner.prop("src", "images/spinner.gif"); - if (is_metaconsole()) { - $spinner.prop("src", "../../images/spinner.gif"); - } + if (is_metaconsole()) { + $spinner.prop("src", "../../images/spinner.gif"); + } - // If no image configured do not show anything - if (staticGraph === null) return; + // If no image configured do not show anything + if (staticGraph === null) return; - $("#preview") - .empty() - .css('text-align', 'right') - .append($spinner); + $("#preview") + .empty() + .css("text-align", "right") + .append($spinner); - if(staticGraph == '' || staticGraph == 'none'){ - - if (is_metaconsole()) { - $spinner.prop("src", "../../images/image_problem_area.png"); - } - else{ - $spinner.prop("src", "images/image_problem_area.png"); - } - $('#preview > img').css({'max-width':'100px','max-height':'100px'}); - } - else{ - imgBase = "images/console/icons/" + staticGraph; + if (staticGraph == "" || staticGraph == "none") { + if (is_metaconsole()) { + $spinner.prop("src", "../../images/image_problem_area.png"); + } else { + $spinner.prop("src", "images/image_problem_area.png"); + } + $("#preview > img").css({ "max-width": "100px", "max-height": "100px" }); + } else { + imgBase = "images/console/icons/" + staticGraph; - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "get_image_path_status", value: "1"}); - parameter.push ({name: "img_src", value: imgBase }); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "get_image_path_status", value: "1" }); + parameter.push({ name: "img_src", value: imgBase }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - jQuery.ajax ({ - type: 'POST', - url: get_url_ajax(), - data: parameter, - dataType: 'json', - error: function (xhr, textStatus, errorThrown) { - $("#preview").empty(); - }, - success: function (data) { - $("#preview").empty(); + jQuery.ajax({ + type: "POST", + url: get_url_ajax(), + data: parameter, + dataType: "json", + error: function(xhr, textStatus, errorThrown) { + $("#preview").empty(); + }, + success: function(data) { + $("#preview").empty(); - jQuery.each(data, function(i, line) { - $("#preview").append(line); - $('#preview > img').css({'max-width':'70px','max-height':'70px'}); - }); - } - }); - - } + jQuery.each(data, function(i, line) { + $("#preview").append(line); + $("#preview > img").css({ + "max-width": "70px", + "max-height": "70px" + }); + }); + } + }); + } } function showPreviewIcon(icon) { - var metaconsole = $("input[name='metaconsole']").val(); - var $spinner = $(""); - $spinner.prop("src", "images/spinner.gif"); + var metaconsole = $("input[name='metaconsole']").val(); + var $spinner = $(""); + $spinner.prop("src", "images/spinner.gif"); - if (is_metaconsole()) { - $spinner.prop("src", "../../images/spinner.gif"); - } + if (is_metaconsole()) { + $spinner.prop("src", "../../images/spinner.gif"); + } - $("#preview") - .empty() - .css('text-align', 'left') - .append($spinner); + $("#preview") + .empty() + .css("text-align", "left") + .append($spinner); + if (icon == "" || icon == "none") { + if (is_metaconsole()) { + $spinner.prop("src", "../../images/image_problem_area.png"); + } else { + $spinner.prop("src", "images/image_problem_area.png"); + } + $("#preview > img").css({ "max-width": "100px", "max-height": "100px" }); + } else { + imgBase = "images/console/icons/" + icon; - if (icon == '' || icon == 'none') { - if (is_metaconsole()) { - $spinner.prop("src", "../../images/image_problem_area.png"); - } - else{ - $spinner.prop("src", "images/image_problem_area.png"); - } - $('#preview > img').css({'max-width':'100px','max-height':'100px'}); - } - else{ - imgBase = "images/console/icons/" + icon; - - var params = []; - params.push("get_image_path=1"); - params.push("img_src=" + imgBase + ".png"); - params.push("page=include/ajax/skins.ajax"); - params.push ({ - name: "id_visual_console", - value: id_visual_console - }); - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: get_url_ajax(), - error: function (xhr, textStatus, errorThrown) { - $("#preview").empty(); - }, - success: function (data) { - $("#preview") - .empty() - .append(data); - $('#preview > img').css({'max-width':'70px','max-height':'70px'}); - } - }); - } + var params = []; + params.push("get_image_path=1"); + params.push("img_src=" + imgBase + ".png"); + params.push("page=include/ajax/skins.ajax"); + params.push({ + name: "id_visual_console", + value: id_visual_console + }); + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: get_url_ajax(), + error: function(xhr, textStatus, errorThrown) { + $("#preview").empty(); + }, + success: function(data) { + $("#preview") + .empty() + .append(data); + $("#preview > img").css({ "max-width": "70px", "max-height": "70px" }); + } + }); + } } function click_copy_item_callback() { - copyDB(idItem); + copyDB(idItem); } function showGrid() { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } - - var display = $("#background_grid").css('display'); - - if (display == 'none') { - $("#background_grid").css('display', ''); - $("#background_img").css('opacity', '0.55'); - $("#background_img").css('filter', 'alpha(opacity=55)'); - $("#background_grid").css('background', - 'url("' + url_hack_metaconsole + 'images/console/background/white_boxed.jpg")'); + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - //Snap to grid all elements. - jQuery.each($(".item"), function(key, value) { - item = value; - idItem = $(item).attr('id'); - classItem = $(item).attr('class').replace('item', '') - .replace('ui-draggable', '').replace('ui-draggable-disabled', '') - .replace(/^\s+/g,'').replace(/\s+$/g,''); + var display = $("#background_grid").css("display"); - pos_y = parseInt($(item).css('top').replace('px', '')); - pos_x = parseInt($(item).css('left').replace('px', '')); + if (display == "none") { + $("#background_grid").css("display", ""); + $("#background_img").css("opacity", "0.55"); + $("#background_img").css("filter", "alpha(opacity=55)"); + $("#background_grid").css( + "background", + 'url("' + + url_hack_metaconsole + + 'images/console/background/white_boxed.jpg")' + ); - pos_y = Math.floor(pos_y / SIZE_GRID) * SIZE_GRID; - pos_x = Math.floor(pos_x / SIZE_GRID) * SIZE_GRID; + //Snap to grid all elements. + jQuery.each($(".item"), function(key, value) { + item = value; + idItem = $(item).attr("id"); + classItem = $(item) + .attr("class") + .replace("item", "") + .replace("ui-draggable", "") + .replace("ui-draggable-disabled", "") + .replace(/^\s+/g, "") + .replace(/\s+$/g, ""); - var values = {}; + pos_y = parseInt( + $(item) + .css("top") + .replace("px", "") + ); + pos_x = parseInt( + $(item) + .css("left") + .replace("px", "") + ); - values['absolute_left'] = pos_x; - values['absolute_top'] = pos_y; - - updateDB(classItem, idItem, values, 'show_grid'); - }); + pos_y = Math.floor(pos_y / SIZE_GRID) * SIZE_GRID; + pos_x = Math.floor(pos_x / SIZE_GRID) * SIZE_GRID; - eventsItems([SIZE_GRID, SIZE_GRID]); - } - else { - $("#background_grid").css('display', 'none'); - $("#background_img").css('opacity', '1'); - $("#background_img").css('filter', 'alpha(opacity=100)'); + var values = {}; - eventsItems(); - } + values["absolute_left"] = pos_x; + values["absolute_top"] = pos_y; + + updateDB(classItem, idItem, values, "show_grid"); + }); + + eventsItems([SIZE_GRID, SIZE_GRID]); + } else { + $("#background_grid").css("display", "none"); + $("#background_img").css("opacity", "1"); + $("#background_img").css("filter", "alpha(opacity=100)"); + + eventsItems(); + } } -function multiDragStart(event){ - multiDragMouse(event); - +function multiDragStart(event) { + multiDragMouse(event); } -function multidragStop(event){ - $('#background').off("mousemove"); - values = []; - selectedItems.forEach( function(valor, indice, array) { - $('#'+valor).css('left','+=1'); - $('#'+valor).css('top','+=1'); - classItem = $('#'+valor).attr('class').replace(/item|ui-draggable|ui-draggable-dragging|-dragging/g, '').trim(); - values['mov_left'] = parseInt($('#'+valor).css('left')); - values['mov_top'] = parseInt($('#'+valor).css('top')); - updateDB(classItem, valor, values,'dragstop'); - }); - +function multidragStop(event) { + $("#background").off("mousemove"); + values = []; + selectedItems.forEach(function(valor, indice, array) { + $("#" + valor).css("left", "+=1"); + $("#" + valor).css("top", "+=1"); + classItem = $("#" + valor) + .attr("class") + .replace(/item|ui-draggable|ui-draggable-dragging|-dragging/g, "") + .trim(); + values["mov_left"] = parseInt($("#" + valor).css("left")); + values["mov_top"] = parseInt($("#" + valor).css("top")); + updateDB(classItem, valor, values, "dragstop"); + }); } +function multiDragMouse(eventDrag) { + var preX = []; + var preY = []; + selectedItems.forEach(function(valor, indice, array) { + preX[indice] = $("#" + valor).css("left"); + preY[indice] = $("#" + valor).css("top"); + }); -function multiDragMouse(eventDrag){ - var preX = []; - var preY = []; - - selectedItems.forEach( function(valor, indice, array) { - preX[indice] = $('#'+valor).css('left'); - preY[indice] = $('#'+valor).css('top'); - }); - - $('#background').on('mousemove',function(event){ - var moveDiffX = event.clientX - eventDrag.clientX; - var moveDiffY = event.clientY - eventDrag.clientY; - selectedItems.forEach( function(valor, indice, array) { - if(!(parseInt($('#'+valor).css('left')) < 0 && parseInt(moveDiffX)+parseInt(preX[indice]) < 0) && - !(parseInt($('#'+valor).css('left')) + parseInt($('#'+valor).css('width')) > parseInt($('#background').css('width')) && parseInt(moveDiffX+preX[indice]) > 0)){ - $('#'+valor).css('left',parseInt(moveDiffX)+parseInt(preX[indice])+'px'); - } - if(!(parseInt($('#'+valor).css('top')) < 0 && parseInt(moveDiffY)+parseInt(preY[indice]) < 0) && - !(parseInt($('#'+valor).css('top')) + parseInt($('#'+valor).css('height')) > parseInt($('#background').css('height')) && parseInt(moveDiffY+preY[indice]) > 0)){ - $('#'+valor).css('top',parseInt(moveDiffY)+parseInt(preY[indice])+'px'); - } - }); - }); + $("#background").on("mousemove", function(event) { + var moveDiffX = event.clientX - eventDrag.clientX; + var moveDiffY = event.clientY - eventDrag.clientY; + selectedItems.forEach(function(valor, indice, array) { + if ( + !( + parseInt($("#" + valor).css("left")) < 0 && + parseInt(moveDiffX) + parseInt(preX[indice]) < 0 + ) && + !( + parseInt($("#" + valor).css("left")) + + parseInt($("#" + valor).css("width")) > + parseInt($("#background").css("width")) && + parseInt(moveDiffX + preX[indice]) > 0 + ) + ) { + $("#" + valor).css( + "left", + parseInt(moveDiffX) + parseInt(preX[indice]) + "px" + ); + } + if ( + !( + parseInt($("#" + valor).css("top")) < 0 && + parseInt(moveDiffY) + parseInt(preY[indice]) < 0 + ) && + !( + parseInt($("#" + valor).css("top")) + + parseInt($("#" + valor).css("height")) > + parseInt($("#background").css("height")) && + parseInt(moveDiffY + preY[indice]) > 0 + ) + ) { + $("#" + valor).css( + "top", + parseInt(moveDiffY) + parseInt(preY[indice]) + "px" + ); + } + }); + }); } -function linkedMapStatusCalculationTypeChanged ($linkedMapStatusCalcRow, value) { - if ($linkedMapStatusCalcRow.length === 0) return; +function linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value) { + if ($linkedMapStatusCalcRow.length === 0) return; - switch (value) { - case "weight": - // Show weight input - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .show() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - break; - case "service": - // Show critical and warning values - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .show() - .siblings("#linked_map_status_service_warning_row") - .show(); - break; - default: - // Hide inputs - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - break; - } + switch (value) { + case "weight": + // Show weight input + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .show() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + break; + case "service": + // Show critical and warning values + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .show() + .siblings("#linked_map_status_service_warning_row") + .show(); + break; + default: + // Hide inputs + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + break; + } } -function linkedMapChanged ($linkedMapRow, value) { - if ($linkedMapRow.length === 0) return; +function linkedMapChanged($linkedMapRow, value) { + if ($linkedMapRow.length === 0) return; - if (value === 0) { - $linkedMapRow - .siblings("#linked_map_status_calculation_row") - .hide() - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - } else { - var $linkedMapStatusCalcRow = $linkedMapRow.siblings("#linked_map_status_calculation_row"); - var calcType = $linkedMapStatusCalcRow.find("select").val(); - $linkedMapStatusCalcRow.show(); - linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, calcType); - } + if (value === 0) { + $linkedMapRow + .siblings("#linked_map_status_calculation_row") + .hide() + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + } else { + var $linkedMapStatusCalcRow = $linkedMapRow.siblings( + "#linked_map_status_calculation_row" + ); + var calcType = $linkedMapStatusCalcRow.find("select").val(); + $linkedMapStatusCalcRow.show(); + linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, calcType); + } } -function onLinkedMapChange (event) { - var $linkedMapRow = $(event.target).parent().parent(); - var value = Number.parseInt(event.target.value); - linkedMapChanged($linkedMapRow, value); +function onLinkedMapChange(event) { + var $linkedMapRow = $(event.target) + .parent() + .parent(); + var value = Number.parseInt(event.target.value); + linkedMapChanged($linkedMapRow, value); } -function onLinkedMapStatusCalculationTypeChange (event) { - var $linkedMapStatusCalcRow = $(event.target).parent().parent(); - var value = event.target.value || "default"; - linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value); +function onLinkedMapStatusCalculationTypeChange(event) { + var $linkedMapStatusCalcRow = $(event.target) + .parent() + .parent(); + var value = event.target.value || "default"; + linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value); } -function validateColorRange (values) { - return ( - (values["from_value"].length > 0 || values["to_value"].length > 0) && - values["color"].length > 0 && - !Number.isNaN(Number.parseFloat(values["from_value"])) && - !Number.isNaN(Number.parseFloat(values["to_value"])) - ) +function validateColorRange(values) { + return ( + (values["from_value"].length > 0 || values["to_value"].length > 0) && + values["color"].length > 0 && + !Number.isNaN(Number.parseFloat(values["from_value"])) && + !Number.isNaN(Number.parseFloat(values["to_value"])) + ); } -function getColorRangeTable ($colorRangeCreationTable, values) { - var $colorRangeTable = $colorRangeCreationTable.clone(); - $colorRangeTable.attr("id", "").removeClass("color-range-creation"); +function getColorRangeTable($colorRangeCreationTable, values) { + var $colorRangeTable = $colorRangeCreationTable.clone(); + $colorRangeTable.attr("id", "").removeClass("color-range-creation"); - // ref inputs - var $fromValueInput = $colorRangeTable.find('input[name="from_value_new"]'); - var $toValueInput = $colorRangeTable.find('input[name="to_value_new"]'); - var $colorInput = $colorRangeTable.find('input[name="color_new"]'); + // ref inputs + var $fromValueInput = $colorRangeTable.find('input[name="from_value_new"]'); + var $toValueInput = $colorRangeTable.find('input[name="to_value_new"]'); + var $colorInput = $colorRangeTable.find('input[name="color_new"]'); - // Override input values - if (values != null) { - if (values["from_value"] != null) { - $fromValueInput.val(values["from_value"]); - } - if (values["to_value"] != null) { - $toValueInput.val(values["to_value"]); - } - if (values["color"] != null) { - $colorInput.val(values["color"]); - } - } + // Override input values + if (values != null) { + if (values["from_value"] != null) { + $fromValueInput.val(values["from_value"]); + } + if (values["to_value"] != null) { + $toValueInput.val(values["to_value"]); + } + if (values["color"] != null) { + $colorInput.val(values["color"]); + } + } - // Change the name of the new inputs (and clear the id attr) - $fromValueInput.attr("name", "color_range_from_values[]").attr("id", ""); - $toValueInput.attr("name", "color_range_to_values[]").attr("id", ""); - $colorInput.attr("name", "color_range_color_values[]").attr("id", ""); + // Change the name of the new inputs (and clear the id attr) + $fromValueInput.attr("name", "color_range_from_values[]").attr("id", ""); + $toValueInput.attr("name", "color_range_to_values[]").attr("id", ""); + $colorInput.attr("name", "color_range_color_values[]").attr("id", ""); - // Change the add button - $colorRangeAddBtn = $colorRangeTable.find("a.color-range-add"); - if ($colorRangeAddBtn.length > 0) { - $colorRangeAddBtn - .removeClass("color-range-add") - .addClass("color-range-delete") - .click(function (e) { - e.preventDefault(); - e.stopPropagation(); - $colorRangeTable.remove(); - }); - - // Change img - $colorRangeAddImg = $colorRangeAddBtn.children("img"); - if ($colorRangeAddImg.length > 0) { - var src = $("#hidden-metaconsole").val() == 1 - ? "../../images/delete.png" - : "images/delete.png"; - $colorRangeAddImg.prop("src", src); - } - } + // Change the add button + $colorRangeAddBtn = $colorRangeTable.find("a.color-range-add"); + if ($colorRangeAddBtn.length > 0) { + $colorRangeAddBtn + .removeClass("color-range-add") + .addClass("color-range-delete") + .click(function(e) { + e.preventDefault(); + e.stopPropagation(); + $colorRangeTable.remove(); + }); - return $colorRangeTable; + // Change img + $colorRangeAddImg = $colorRangeAddBtn.children("img"); + if ($colorRangeAddImg.length > 0) { + var src = + $("#hidden-metaconsole").val() == 1 + ? "../../images/delete.png" + : "images/delete.png"; + $colorRangeAddImg.prop("src", src); + } + } + + return $colorRangeTable; } -function handleColorRangeCreation (event) { - event.preventDefault(); - event.stopPropagation(); +function handleColorRangeCreation(event) { + event.preventDefault(); + event.stopPropagation(); - var $creationBtn = $(event.target); - var $colorRangeCreationTable = $creationBtn.parents("table.color-range-creation"); + var $creationBtn = $(event.target); + var $colorRangeCreationTable = $creationBtn.parents( + "table.color-range-creation" + ); - // ref inputs - var $fromValueInput = $colorRangeCreationTable.find('input[name="from_value_new"]'); - var $toValueInput = $colorRangeCreationTable.find('input[name="to_value_new"]'); - var $colorInput = $colorRangeCreationTable.find('input[name="color_new"]'); + // ref inputs + var $fromValueInput = $colorRangeCreationTable.find( + 'input[name="from_value_new"]' + ); + var $toValueInput = $colorRangeCreationTable.find( + 'input[name="to_value_new"]' + ); + var $colorInput = $colorRangeCreationTable.find('input[name="color_new"]'); - // TODO: Show info about validation - var values = { - "from_value": $fromValueInput.val(), - "to_value": $toValueInput.val(), - "color": $colorInput.val() - } - if (!validateColorRange(values)) return; + // TODO: Show info about validation + var values = { + from_value: $fromValueInput.val(), + to_value: $toValueInput.val(), + color: $colorInput.val() + }; + if (!validateColorRange(values)) return; - var $newColorRangeTable = getColorRangeTable($colorRangeCreationTable); - - // Clear creation inputs - $fromValueInput.val(""); - $toValueInput.val(""); - $colorInput.val("#FFFFFF"); + var $newColorRangeTable = getColorRangeTable($colorRangeCreationTable); - // Add the new table - $newColorRangeTable.insertBefore($colorRangeCreationTable); + // Clear creation inputs + $fromValueInput.val(""); + $toValueInput.val(""); + $colorInput.val("#FFFFFF"); + + // Add the new table + $newColorRangeTable.insertBefore($colorRangeCreationTable); } -function bindColorRangeEvents () { - $("a.color-range-add").click(handleColorRangeCreation); +function bindColorRangeEvents() { + $("a.color-range-add").click(handleColorRangeCreation); } diff --git a/pandora_console/include/graphs/flot/pandora.flot.js b/pandora_console/include/graphs/flot/pandora.flot.js index e69fb155e0..0460b55c99 100644 --- a/pandora_console/include/graphs/flot/pandora.flot.js +++ b/pandora_console/include/graphs/flot/pandora.flot.js @@ -1,272 +1,329 @@ +function pandoraFlotPie( + graph_id, + values, + labels, + nseries, + width, + font_size, + water_mark, + separator, + legend_position, + height, + colors, + hide_labels +) { + var labels = labels.split(separator); + var data = values.split(separator); -function pandoraFlotPie(graph_id, values, labels, nseries, width, font_size, water_mark, separator, legend_position, height, colors, hide_labels) { - var labels = labels.split(separator); - var data = values.split(separator); + if (colors != "") { + colors = colors.split(separator); + } - if (colors != '') { - colors = colors.split(separator); - } + var pieRadius = 0.9; - var pieRadius = 0.9; + var color = null; + for (var i = 0; i < nseries; i++) { + if (colors != "") { + color = colors[i]; + } + data[i] = { label: labels[i], data: parseFloat(data[i]), color: color }; + } - var color = null; - for (var i = 0; i < nseries; i++) { - if (colors != '') { - color = colors[i]; - } - data[i] = { label: labels[i], data: parseFloat(data[i]), color: color} - } + var show_legend = true; + if (legend_position == "hidden") { + show_legend = false; + } - var show_legend = true; - if (legend_position == 'hidden') { - show_legend = false; - } + var conf_pie = { + series: { + pie: { + show: true, + radius: pieRadius + } + }, + legend: { + show: show_legend + }, + grid: { + hoverable: true, + clickable: true + } + }; - var conf_pie = { - series: { - pie: { - show: true, - radius: pieRadius - } - }, - legend: { - show: show_legend - }, - grid: { - hoverable: true, - clickable: true - } - }; + if (hide_labels != false && hide_labels != 0) { + conf_pie.series.pie.label = { + show: true, + radius: 2 / 3, + formatter: labelFormatter, + threshold: 0.1 + }; + } else { + conf_pie.series.pie.label = { + show: false + }; + } - if(hide_labels != false && hide_labels != 0){ - conf_pie.series.pie.label = { - show: true, - radius: 2/3, - formatter: labelFormatter, - threshold: 0.1 - } - } - else{ - conf_pie.series.pie.label = { - show:false - } - } + switch (legend_position) { + case "bottom": + conf_pie.legend.position = "se"; + break; + case "right": + case "inner": + conf_pie.legend.container = $("#" + graph_id + "_legend"); + default: + //TODO FOR TOP OR LEFT OR RIGHT + break; + } - switch (legend_position) { - case 'bottom': - conf_pie.legend.position = "se"; - break; - case 'right': - case 'inner': - conf_pie.legend.container = $('#'+graph_id+"_legend"); - default: - //TODO FOR TOP OR LEFT OR RIGHT - break; - } + var plot = $.plot($("#" + graph_id), data, conf_pie); - var plot = $.plot($('#'+graph_id), data, conf_pie); + var legends = $("#" + graph_id + " .legendLabel"); + legends.css("font-size", font_size + "pt"); - var legends = $('#'+graph_id+' .legendLabel'); - legends.css('font-size', font_size+'pt'); + // Events + $("#" + graph_id).bind("plothover", pieHover); + $("#" + graph_id).bind("plotclick", pieClick); + $("#" + graph_id).bind("mouseout", resetInteractivity); + $("#" + graph_id).css("margin-left", "auto"); + $("#" + graph_id).css("margin-right", "auto"); - // Events - $('#' + graph_id).bind('plothover', pieHover); - $('#' + graph_id).bind('plotclick', pieClick); - $('#' + graph_id).bind('mouseout',resetInteractivity); - $('#' + graph_id).css('margin-left', 'auto'); - $('#' + graph_id).css('margin-right', 'auto'); + function pieHover(event, pos, obj) { + if (!obj) return; - function pieHover(event, pos, obj) { - if (!obj) return; + index = obj.seriesIndex; + legends.css("color", "#3F3F3D"); + legends.eq(index).css("color", ""); + } - index = obj.seriesIndex; - legends.css('color', '#3F3F3D'); - legends.eq(index).css('color', ''); - } + function labelFormatter(label, series) { + return ( + '
' + + label + + "
" + + series.percent.toFixed(2) + + "%
" + ); + } - function labelFormatter(label, series) { - return '
' + - label + '
' + series.percent.toFixed(2) + '%
'; - } + // Reset styles + function resetInteractivity() { + legends.css("color", "#3F3F3D"); + } - // Reset styles - function resetInteractivity() { - legends.css('color', '#3F3F3D'); - } - - if (water_mark) { - set_watermark(graph_id, plot,$('#watermark_image_' + graph_id).attr('src')); - } + if (water_mark) { + set_watermark( + graph_id, + plot, + $("#watermark_image_" + graph_id).attr("src") + ); + } } -function pandoraFlotPieCustom(graph_id, values, labels, width, - font_size, font, water_mark, separator, legend_position, height, - colors,legend,background_color) { - - font = font.split("/").pop().split(".").shift(); - var labels = labels.split(separator); - var legend = legend.split(separator); - var data = values.split(separator); - var no_data = 0; - if (colors != '') { - colors = colors.split(separator); - } - var colors_data = ['#FC4444','#FFA631','#FAD403','#5BB6E5','#F2919D','#80BA27']; - var color = null; - for (var i = 0; i < data.length; i++) { - if (colors != '') { - color = colors[i]; - } - var datos = data[i]; - data[i] = { label: labels[i], data: parseFloat(data[i]), color: color }; - if (!datos) - no_data++; - - } - - var label_conf; - var show_legend = true; - - if((width <= 450)) { - show_legend = false; - label_conf = { - show: false - }; - } - else { - label_conf = { - show: true, - radius: 0.75, - formatter: function(label, series) { - return '
' + - series.percent.toFixed(2) + '%
'; - }, - background: { - opacity: 0.5, - color: '' - } - }; +function pandoraFlotPieCustom( + graph_id, + values, + labels, + width, + font_size, + font, + water_mark, + separator, + legend_position, + height, + colors, + legend, + background_color +) { + font = font + .split("/") + .pop() + .split(".") + .shift(); + var labels = labels.split(separator); + var legend = legend.split(separator); + var data = values.split(separator); + var no_data = 0; + if (colors != "") { + colors = colors.split(separator); + } + var colors_data = [ + "#FC4444", + "#FFA631", + "#FAD403", + "#5BB6E5", + "#F2919D", + "#80BA27" + ]; + var color = null; + for (var i = 0; i < data.length; i++) { + if (colors != "") { + color = colors[i]; + } + var datos = data[i]; + data[i] = { label: labels[i], data: parseFloat(data[i]), color: color }; + if (!datos) no_data++; + } - } + var label_conf; + var show_legend = true; - var conf_pie = { - series: { - pie: { - show: true, - radius: 3/4, - innerRadius: 0.4 - //label: label_conf - } - }, - legend: { - show: show_legend, - }, - grid: { - hoverable: true, - clickable: true - } - }; - if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { - conf_pie.series.pie.label = {show: false}; - } - - var plot = $.plot($('#'+graph_id), data, conf_pie); - if (no_data == data.length) { - $('#'+graph_id+' .overlay').remove(); - $('#'+graph_id+' .base').remove(); - $('#'+graph_id).prepend(""); - - } - var legends = $('#'+graph_id+' .legendLabel'); - var j = 0; - legends.each(function () { - //$(this).css('width', $(this).width()); - $(this).css('font-size', font_size+'pt'); - $(this).removeClass("legendLabel"); - $(this).addClass(font); - $(this).text(legend[j]); - j++; - }); - - if ($('input[name="custom_graph"]').val()) { - $('.legend>div').css('right',($('.legend>div').height()*-1)); - $('.legend>table').css('right',($('.legend>div').height()*-1)); - } - //$('.legend>table').css('border',"1px solid #E2E2E2"); - - if(background_color == 'transparent') { - $('.legend>table').css('background-color',""); - $('.legend>div').css('background-color',""); - $('.legend>table').css('color',"#aaa"); - } else if (background_color == 'white') { - $('.legend>table').css('background-color',"white"); - $('.legend>table').css('color',"black"); - } else if (background_color == 'black') { - $('.legend>table').css('background-color',"black"); - $('.legend>table').css('color',"#aaa"); - } - - $('.legend').hover(function() { - return false; - }); - - var pielegends = $('#'+graph_id+' .pieLabelBackground'); - pielegends.each(function () { - $(this).css('transform', "rotate(-35deg)").css('color', 'black'); - }); - var labelpielegends = $('#'+graph_id+' .pieLabel'); - labelpielegends.each(function () { - $(this).css('transform', "rotate(-35deg)").css('color', 'black'); - }); - - // Events - $('#' + graph_id).bind('plothover', pieHover); - $('#' + graph_id).bind('plotclick', Clickpie); - $('#' + graph_id).bind('mouseout', resetInteractivity); - $('#' + graph_id).css('margin-left', 'auto'); - $('#' + graph_id).css('margin-right', 'auto'); - - function pieHover(event, pos, obj) { - if (!obj) return; - - index = obj.seriesIndex; - legends.css('color', '#3F3F3D'); - legends.eq(index).css('color', ''); - } - - function Clickpie(event, pos, obj) { - if (!obj) return; - percent = parseFloat(obj.series.percent).toFixed(2); - valor = parseFloat(obj.series.data[0][1]); - - if (valor > 1000000){ - value = Math.round((valor / 1000000)*100)/100; - value = value + "M"; - }else{ if (valor > 1000) { - value = Math.round((valor / 1000)*100)/100; - value = value + "K"; - } - else - value = valor; - } - - alert(''+obj.series.label+': '+ value +' ('+percent+'%)'); - } - - // Reset styles - function resetInteractivity() { - legends.each(function () { - // fix the widths so they don't jump around - $(this).css('color', '#3F3F3D'); - }); - } - - if (water_mark) { - set_watermark(graph_id, plot, - $('#watermark_image_' + graph_id).attr('src')); - } -/* + if (width <= 450) { + show_legend = false; + label_conf = { + show: false + }; + } else { + label_conf = { + show: true, + radius: 0.75, + formatter: function(label, series) { + return ( + '
' + + series.percent.toFixed(2) + + "%
" + ); + }, + background: { + opacity: 0.5, + color: "" + } + }; + } + + var conf_pie = { + series: { + pie: { + show: true, + radius: 3 / 4, + innerRadius: 0.4 + //label: label_conf + } + }, + legend: { + show: show_legend + }, + grid: { + hoverable: true, + clickable: true + } + }; + if ( + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) + ) { + conf_pie.series.pie.label = { show: false }; + } + + var plot = $.plot($("#" + graph_id), data, conf_pie); + if (no_data == data.length) { + $("#" + graph_id + " .overlay").remove(); + $("#" + graph_id + " .base").remove(); + $("#" + graph_id).prepend( + "" + ); + } + var legends = $("#" + graph_id + " .legendLabel"); + var j = 0; + legends.each(function() { + //$(this).css('width', $(this).width()); + $(this).css("font-size", font_size + "pt"); + $(this).removeClass("legendLabel"); + $(this).addClass(font); + $(this).text(legend[j]); + j++; + }); + + if ($('input[name="custom_graph"]').val()) { + $(".legend>div").css("right", $(".legend>div").height() * -1); + $(".legend>table").css("right", $(".legend>div").height() * -1); + } + //$('.legend>table').css('border',"1px solid #E2E2E2"); + + if (background_color == "transparent") { + $(".legend>table").css("background-color", ""); + $(".legend>div").css("background-color", ""); + $(".legend>table").css("color", "#aaa"); + } else if (background_color == "white") { + $(".legend>table").css("background-color", "white"); + $(".legend>table").css("color", "black"); + } else if (background_color == "black") { + $(".legend>table").css("background-color", "black"); + $(".legend>table").css("color", "#aaa"); + } + + $(".legend").hover(function() { + return false; + }); + + var pielegends = $("#" + graph_id + " .pieLabelBackground"); + pielegends.each(function() { + $(this) + .css("transform", "rotate(-35deg)") + .css("color", "black"); + }); + var labelpielegends = $("#" + graph_id + " .pieLabel"); + labelpielegends.each(function() { + $(this) + .css("transform", "rotate(-35deg)") + .css("color", "black"); + }); + + // Events + $("#" + graph_id).bind("plothover", pieHover); + $("#" + graph_id).bind("plotclick", Clickpie); + $("#" + graph_id).bind("mouseout", resetInteractivity); + $("#" + graph_id).css("margin-left", "auto"); + $("#" + graph_id).css("margin-right", "auto"); + + function pieHover(event, pos, obj) { + if (!obj) return; + + index = obj.seriesIndex; + legends.css("color", "#3F3F3D"); + legends.eq(index).css("color", ""); + } + + function Clickpie(event, pos, obj) { + if (!obj) return; + percent = parseFloat(obj.series.percent).toFixed(2); + valor = parseFloat(obj.series.data[0][1]); + + if (valor > 1000000) { + value = Math.round((valor / 1000000) * 100) / 100; + value = value + "M"; + } else { + if (valor > 1000) { + value = Math.round((valor / 1000) * 100) / 100; + value = value + "K"; + } else value = valor; + } + + alert("" + obj.series.label + ": " + value + " (" + percent + "%)"); + } + + // Reset styles + function resetInteractivity() { + legends.each(function() { + // fix the widths so they don't jump around + $(this).css("color", "#3F3F3D"); + }); + } + + if (water_mark) { + set_watermark( + graph_id, + plot, + $("#watermark_image_" + graph_id).attr("src") + ); + } + /* window.onresize = function(event) { $.plot($('#' + graph_id), data, conf_pie); if (no_data == data.length) { @@ -304,1362 +361,1793 @@ function pandoraFlotPieCustom(graph_id, values, labels, width, */ } -function pandoraFlotHBars(graph_id, values, labels, water_mark, - maxvalue, water_mark, separator, separator2, font, font_size, - background_color, tick_color, min, max) { +function pandoraFlotHBars( + graph_id, + values, + labels, + water_mark, + maxvalue, + water_mark, + separator, + separator2, + font, + font_size, + background_color, + tick_color, + min, + max +) { + var colors_data = [ + "#FC4444", + "#FFA631", + "#FAD403", + "#5BB6E5", + "#F2919D", + "#80BA27" + ]; + values = values.split(separator2); + font = font + .split("/") + .pop() + .split(".") + .shift(); + var datas = new Array(); + for (i = 0; i < values.length; i++) { + var serie = values[i].split(separator); - var colors_data = ['#FC4444','#FFA631','#FAD403','#5BB6E5','#F2919D','#80BA27']; - values = values.split(separator2); - font = font.split("/").pop().split(".").shift(); - var datas = new Array(); - for (i = 0; i < values.length; i++) { - var serie = values[i].split(separator); + var aux = new Array(); + for (j = 0; j < serie.length; j++) { + var aux2 = parseFloat(serie[j]); + aux.push([aux2, j]); + datas.push({ + data: [[aux2, j]], + color: colors_data[j] + }); + } + } + var labels_total = new Array(); + labels = labels.split(separator); + i = 0; + for (i = 0; i < labels.length; i++) { + labels_total.push([i, labels[i]]); + } - var aux = new Array(); - for (j = 0; j < serie.length; j++) { - var aux2 = parseFloat(serie[j]); - aux.push([aux2, j]); - datas.push( { - data: [[aux2, j]], - color: colors_data[j] - }); - }; - } + var stack = 0, + bars = true, + lines = false, + steps = false; + var k = 0; + var options = { + series: { + bars: { + show: true, + barWidth: 0.75, + align: "center", + lineWidth: 1, + fill: 1, + horizontal: true + } + }, + grid: { + hoverable: true, + borderWidth: 1, + tickColor: tick_color, + borderColor: "#C1C1C1", + backgroundColor: { colors: [background_color, background_color] } + }, + xaxis: { + color: tick_color, + axisLabelUseCanvas: true, + axisLabelFontSizePixels: font_size, + axisLabelFontFamily: font + "Font", + tickFormatter: xFormatter + }, + yaxis: { + font: { + size: font_size + 2, + color: "rgb(84, 84, 84)", + family: font + "Font" + }, + ticks: yFormatter + }, + legend: { + show: false + } + }; - var labels_total=new Array(); - labels = labels.split(separator); - i = 0; - for (i = 0; i < labels.length; i++) { - labels_total.push([i, labels[i]]); - } + // Fixed to avoid the graphs with all 0 datas + // the X axis show negative part instead to + // show the axis only the positive part. + if (maxvalue == 0) { + options["yaxis"]["min"] = 0; + // Fixed the values with a lot of decimals in the situation + // with all 0 values. + options["yaxis"]["tickDecimals"] = 0; + } - var stack = 0, bars = true, lines = false, steps = false; - var k=0; - var options = { - series: { - bars: { - show: true, - barWidth: 0.75, - align: "center", - lineWidth: 1, - fill: 1, - horizontal: true, - } - }, - grid: { - hoverable: true, - borderWidth: 1, - tickColor: tick_color, - borderColor: '#C1C1C1', - backgroundColor: { colors: [background_color, background_color] } - }, - xaxis: { - color: tick_color, - axisLabelUseCanvas: true, - axisLabelFontSizePixels: font_size, - axisLabelFontFamily: font+'Font', - tickFormatter: xFormatter, - }, - yaxis: { - font: { - size: font_size + 2, - color: 'rgb(84, 84, 84)', - family: font+'Font' - }, - ticks: yFormatter, - }, - legend: { - show: false - } - }; + if (max) { + options["xaxis"]["max"] = max; + } + if (min) { + options["xaxis"]["min"] = min; + } - // Fixed to avoid the graphs with all 0 datas - // the X axis show negative part instead to - // show the axis only the positive part. - if (maxvalue == 0) { - options['yaxis']['min'] = 0; - // Fixed the values with a lot of decimals in the situation - // with all 0 values. - options['yaxis']['tickDecimals'] = 0; - } + var plot = $.plot($("#" + graph_id), datas, options); - if (max) { - options['xaxis']['max'] = max; - } - if (min) { - options['xaxis']['min'] = min; - } + $("#" + graph_id).HUseTooltip(); + $("#" + graph_id).css("margin-left", "auto"); + $("#" + graph_id).css("margin-right", "auto"); + //~ $('#' + graph_id).find('div.legend-tooltip').tooltip({ track: true }); - var plot = $.plot($('#' + graph_id), datas, options ); + function yFormatter(v, axis) { + format = new Array(); + for (i = 0; i < labels_total.length; i++) { + var label = labels_total[i][1]; + // var shortLabel = reduceText(label, 25); + var title = label; + var margin_top = 0; + if (label.length > 30) { + label = reduceText(label, 30); + } + var div_attributes = + 'style="font-size:' + + font_size + + "pt !important;" + + " margin: 0; max-width: 150px;" + + "margin-right:5px"; + +"margin-left: -1.5em"; + +"text-align: right"; - $('#' + graph_id).HUseTooltip(); - $('#' + graph_id).css("margin-left","auto"); - $('#' + graph_id).css("margin-right","auto"); - //~ $('#' + graph_id).find('div.legend-tooltip').tooltip({ track: true }); + if (label.indexOf("
") != -1) { + div_attributes += "min-height: 2.5em;"; + } - function yFormatter(v, axis) { - format = new Array(); - for (i = 0; i < labels_total.length; i++) { - var label = labels_total[i][1]; - // var shortLabel = reduceText(label, 25); - var title = label; - var margin_top = 0; - if(label.length > 30){ - label = reduceText(label, 30); - } - var div_attributes = 'style="font-size:'+font_size+'pt !important;' - + ' margin: 0; max-width: 150px;' - + 'margin-right:5px'; - + 'margin-left: -1.5em'; - + 'text-align: right'; + div_attributes += '" title="' + title + '" style="overflow: hidden;"'; - if (label.indexOf("
") != -1) { - div_attributes += "min-height: 2.5em;"; - } + format.push([i, "
" + label + "
"]); + } + return format; + } - div_attributes += '" title="'+title+'" style="overflow: hidden;"'; + function xFormatter(v, axis) { + label = parseFloat(v); + text = label.toLocaleString(); + if (label >= 1000000) text = text.substring(0, 4) + "M"; + else if (label >= 100000) text = text.substring(0, 3) + "K"; + else if (label >= 1000) text = text.substring(0, 2) + "K"; - format.push([i,'
' - + label - + '
']); - } - return format; - } + return ( + '
' + + text + + "
" + ); + } - function xFormatter(v, axis) { - label = parseFloat(v); - text = label.toLocaleString(); - if ( label >= 1000000) - text = text.substring(0,4) + "M"; - else if (label >= 100000) - text = text.substring(0,3) + "K"; - else if (label >= 1000) - text = text.substring(0,2) + "K"; - - return '
'+text+'
'; - } - - if (water_mark) { - set_watermark(graph_id, plot, $('#watermark_image_'+graph_id).attr('src')); - } + if (water_mark) { + set_watermark( + graph_id, + plot, + $("#watermark_image_" + graph_id).attr("src") + ); + } } -var previousPoint = null, previousLabel = null; +var previousPoint = null, + previousLabel = null; -$.fn.HUseTooltip = function () { - $(this).bind("plothover", function (event, pos, item) { - if (item) { - if ((previousLabel != item.series.label) || (previousPoint != item.seriesIndex)) { - previousPoint = item.seriesIndex; - previousLabel = item.series.label; - $("#tooltip").remove(); +$.fn.HUseTooltip = function() { + $(this).bind("plothover", function(event, pos, item) { + if (item) { + if ( + previousLabel != item.series.label || + previousPoint != item.seriesIndex + ) { + previousPoint = item.seriesIndex; + previousLabel = item.series.label; + $("#tooltip").remove(); - var x = item.datapoint[0]; - var y = item.datapoint[1]; + var x = item.datapoint[0]; + var y = item.datapoint[1]; - var color = item.series.color; - showTooltip(pos.pageX, - pos.pageY, - color, - "" + x + ""); - } - } else { - $("#tooltip").remove(); - previousPoint = null; - } - }); + var color = item.series.color; + showTooltip(pos.pageX, pos.pageY, color, "" + x + ""); + } + } else { + $("#tooltip").remove(); + previousPoint = null; + } + }); }; -$.fn.VUseTooltip = function () { - $(this).bind("plothover", function (event, pos, item) { - if (item) { - if ((previousLabel != item.series.label) || (previousPoint != item.seriesIndex)) { - previousPoint = item.seriesIndex; - previousLabel = item.series.label; - - $("#tooltip").remove(); +$.fn.VUseTooltip = function() { + $(this).bind("plothover", function(event, pos, item) { + if (item) { + if ( + previousLabel != item.series.label || + previousPoint != item.seriesIndex + ) { + previousPoint = item.seriesIndex; + previousLabel = item.series.label; - var x = item.datapoint[0]; - var y = item.datapoint[1]; - - var color = item.series.color; - showTooltip(pos.pageX, - pos.pageY, - color, - "" + y + ""); - } - } else { - $("#tooltip").remove(); - previousPoint = null; - } - }); + $("#tooltip").remove(); + + var x = item.datapoint[0]; + var y = item.datapoint[1]; + + var color = item.series.color; + showTooltip(pos.pageX, pos.pageY, color, "" + y + ""); + } + } else { + $("#tooltip").remove(); + previousPoint = null; + } + }); }; function showTooltip(x, y, color, contents) { - $('
' + contents + '
').css({ - position: 'absolute', - display: 'none', - top: y, - left: x, - border: '2px solid ' + color, - padding: '3px', - 'font-size': '9px', - 'border-radius': '5px', - 'background-color': '#fff', - 'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif', - opacity: 0.9 - }).appendTo("body").fadeIn(200); + $('
' + contents + "
") + .css({ + position: "absolute", + display: "none", + top: y, + left: x, + border: "2px solid " + color, + padding: "3px", + "font-size": "9px", + "border-radius": "5px", + "background-color": "#fff", + "font-family": "Verdana, Arial, Helvetica, Tahoma, sans-serif", + opacity: 0.9 + }) + .appendTo("body") + .fadeIn(200); } -function pandoraFlotVBars(graph_id, values, labels, labels_long, legend, colors, water_mark, maxvalue, water_mark, separator, separator2, font, font_size , from_ux, from_wux, background_color, tick_color) { - values = values.split(separator2); - legend = legend.split(separator); - font = font.split("/").pop().split(".").shift(); - labels_long = labels_long.length > 0 ? labels_long.split(separator) : 0; - colors = colors.length > 0 ? colors.split(separator) : []; - - var colors_data = colors.length > 0 - ? colors - : ['#FFA631','#FC4444','#FAD403','#5BB6E5','#F2919D','#80BA27']; - var datas = new Array(); - - for (i = 0; i < values.length; i++) { - var serie = values[i].split(separator); - - var aux = new Array(); - for (j = 0; j < serie.length; j++) { - var aux2 = parseFloat(serie[j]); - aux.push([aux2, j]); - if (from_ux) { - datas.push( { - data: [[j, aux2]], - color: colors_data[j] - }); - } - else { - datas.push( { - data: [[j, aux2]], - color: colors_data[0] - }); - } - }; - } - - var labels_total=new Array(); - labels = labels.split(separator); - i = 0; - for (i = 0; i < labels.length; i++) { - labels_total.push([i, labels[i]]); - } - - var stack = 0, bars = true, lines = false, steps = false; - - var options = { - series: { - bars: { - show: true, - lineWidth: 1, - fill: 1, - align: "center", - barWidth: 1 - } - }, - xaxis: { - color:tick_color, - axisLabelUseCanvas: true, - axisLabelFontSizePixels: font_size, - axisLabelFontFamily: font+'Font', - axisLabelPadding: 0, - ticks: xFormatter, - labelWidth: 130, - labelHeight: 50, - }, - yaxis: { - color:tick_color, - axisLabelUseCanvas: true, - axisLabelFontSizePixels: font_size, - axisLabelFontFamily: font+'Font', - axisLabelPadding: 100, - autoscaleMargin: 0.02, - tickFormatter: function (v, axis) { - label = parseFloat(v); - text = label.toLocaleString(); - if ( label >= 1000000) - text = text.substring(0,4) + "M"; - else if (label >= 100000) - text = text.substring(0,3) + "K"; - else if (label >= 1000) - text = text.substring(0,2) + "K"; - - return '
'+text+'
'; - } - }, - legend: { - noColumns: 100, - labelBoxBorderColor: "", - margin: 100, - container: true, - sorted: false - }, - grid: { - hoverable: true, - borderWidth: 1, - tickColor: tick_color, - borderColor: '#C1C1C1', - backgroundColor: { colors: [background_color, background_color] } - } - }; - - if(from_wux){ - options.series.bars.barWidth = 0.5; - options.grid.aboveData = true; - options.grid.borderWidth = 0; - options.grid.markings = [ { xaxis: { from: -0.25, to: -0.25 }, color: "#000" }, - { yaxis: { from: 0, to: 0 }, color: "#000" }]; - options.grid.markingsLineWidth = 0.3; - - options.xaxis.tickLength = 0; - options.yaxis.tickLength = 0; - } - - if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) - options.xaxis.labelWidth = 100; - - var plot = $.plot($('#'+graph_id),datas, options ); - $('#' + graph_id).VUseTooltip(); - $('#' + graph_id).css("margin-left","auto"); - $('#' + graph_id).css("margin-right","auto"); - - if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) - $('#'+graph_id+' .xAxis .tickLabel') - .find('div') - .css('top', '+0px') - .css('left', '-20px'); - // Format functions - function xFormatter(v, axis) { - var format = new Array(); - for (i = 0; i < labels_total.length; i++) { - var label = labels_total[i][1]; - var shortLabel = reduceText(label, 28); - if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) - shortLabel = reduceText(label, 18); - var title = ''; - if (label !== shortLabel) { - title = label; - label = shortLabel; - } - - format.push([i, - '
' - + label - + '
']); - } - return format; - } - - function yFormatter(v, axis) { - return '
'+v+'
'; - } - - function lFormatter(v, axis) { - return '
'+v+'
'; - } - - if (water_mark) { - set_watermark(graph_id, plot, $('#watermark_image_'+graph_id).attr('src')); - } -} - -function pandoraFlotSlicebar(graph_id, values, datacolor, labels, legend, acumulate_data, intervaltick, - font, font_size, separator, separator2, id_agent, full_legend, not_interactive, show_date) { - - values = values.split(separator2); - labels = labels.split(separator); - legend = legend.split(separator); - acumulate_data = acumulate_data.split(separator); - datacolor = datacolor.split(separator); - - if (full_legend != false) { - full_legend = full_legend.split(separator); - } - - var font_size = parseInt(font_size); - var font = font.split("/").pop().split(".").shift(); - // Check possible adapt_keys on classes - check_adaptions(graph_id); - - var datas = new Array(); - - for (i=0;i 0 ? labels_long.split(separator) : 0; + colors = colors.length > 0 ? colors.split(separator) : []; - //XXXXXX colocar - var force_integer = 0; + var colors_data = + colors.length > 0 + ? colors + : ["#FFA631", "#FC4444", "#FAD403", "#5BB6E5", "#F2919D", "#80BA27"]; + var datas = new Array(); - if(typeof type === 'undefined' || type == ''){ - type = params.type_graph; - } + for (i = 0; i < values.length; i++) { + var serie = values[i].split(separator); - //for threshold - var threshold = true; - var thresholded = false; - var yellow_threshold = parseFloat (data_module_graph.w_min); - var red_threshold = parseFloat (data_module_graph.c_min); - var yellow_up = parseFloat (data_module_graph.w_max); - var red_up = parseFloat (data_module_graph.c_max); - var yellow_inverse = parseInt (data_module_graph.w_inv); - var red_inverse = parseInt (data_module_graph.c_inv); + var aux = new Array(); + for (j = 0; j < serie.length; j++) { + var aux2 = parseFloat(serie[j]); + aux.push([aux2, j]); + if (from_ux) { + datas.push({ + data: [[j, aux2]], + color: colors_data[j] + }); + } else { + datas.push({ + data: [[j, aux2]], + color: colors_data[0] + }); + } + } + } - //XXXXX - var markins_graph = true; + var labels_total = new Array(); + labels = labels.split(separator); + i = 0; + for (i = 0; i < labels.length; i++) { + labels_total.push([i, labels[i]]); + } - // If threshold and up are the same, that critical or warning is disabled - if (yellow_threshold == yellow_up){ - yellow_inverse = false; - } + var stack = 0, + bars = true, + lines = false, + steps = false; - if (red_threshold == red_up){ - red_inverse = false; - } + var options = { + series: { + bars: { + show: true, + lineWidth: 1, + fill: 1, + align: "center", + barWidth: 1 + } + }, + xaxis: { + color: tick_color, + axisLabelUseCanvas: true, + axisLabelFontSizePixels: font_size, + axisLabelFontFamily: font + "Font", + axisLabelPadding: 0, + ticks: xFormatter, + labelWidth: 130, + labelHeight: 50 + }, + yaxis: { + color: tick_color, + axisLabelUseCanvas: true, + axisLabelFontSizePixels: font_size, + axisLabelFontFamily: font + "Font", + axisLabelPadding: 100, + autoscaleMargin: 0.02, + tickFormatter: function(v, axis) { + label = parseFloat(v); + text = label.toLocaleString(); + if (label >= 1000000) text = text.substring(0, 4) + "M"; + else if (label >= 100000) text = text.substring(0, 3) + "K"; + else if (label >= 1000) text = text.substring(0, 2) + "K"; - //Array with points to be painted - var threshold_data = new Array(); - //Array with some interesting points - var extremes = new Array (); + return ( + '
' + + text + + "
" + ); + } + }, + legend: { + noColumns: 100, + labelBoxBorderColor: "", + margin: 100, + container: true, + sorted: false + }, + grid: { + hoverable: true, + borderWidth: 1, + tickColor: tick_color, + borderColor: "#C1C1C1", + backgroundColor: { colors: [background_color, background_color] } + } + }; - var yellow_only_min = ((yellow_up == 0) && (yellow_threshold != 0)); - var red_only_min = ((red_up == 0) && (red_threshold != 0)); + if (from_wux) { + options.series.bars.barWidth = 0.5; + options.grid.aboveData = true; + options.grid.borderWidth = 0; + options.grid.markings = [ + { xaxis: { from: -0.25, to: -0.25 }, color: "#000" }, + { yaxis: { from: 0, to: 0 }, color: "#000" } + ]; + options.grid.markingsLineWidth = 0.3; - //color - var warning = 'yellow'; - var critical = 'red'; + options.xaxis.tickLength = 0; + options.yaxis.tickLength = 0; + } - if (threshold) { - // Warning interval. Change extremes depends on critical interval - if (yellow_inverse && red_inverse) { - if (red_only_min && yellow_only_min) { - // C: |-------- | - // W: |········==== | - if (yellow_threshold > red_threshold) { - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: { - show: true, - align: "left", - barWidth: yellow_threshold - red_threshold, - lineWidth: 0, - horizontal: true, - fillColor: { - colors: [ - { - opacity: 0.1 - }, - { - opacity: 0.1 - } - ] - } - }, - highlightColor: 'rgba(254, 255, 198, 0)' - }); + if ( + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) + ) + options.xaxis.labelWidth = 100; - extremes['warning_normal_fdown_1'] = red_threshold; - extremes['warning_normal_fdown_2'] = yellow_threshold; - } - } else if (!red_only_min && yellow_only_min) { - // C: |-------- ------| - // W: |········===· | - if (yellow_threshold > red_up) { - yellow_threshold = red_up; - } - if (yellow_threshold > red_threshold) { - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_threshold - red_threshold, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = red_threshold; - extremes['warning_normal_fdown_2'] = yellow_threshold; - } - } else if (red_only_min && !yellow_only_min) { - // C: |------- | - // W: |·······==== ===| - if (red_threshold < yellow_threshold) { - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_threshold - red_threshold, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = red_threshold; - extremes['warning_normal_fdown_2'] = yellow_threshold; - } + var plot = $.plot($("#" + graph_id), datas, options); + $("#" + graph_id).VUseTooltip(); + $("#" + graph_id).css("margin-left", "auto"); + $("#" + graph_id).css("margin-right", "auto"); - if (yellow_up < red_threshold) { - yellow_up = red_threshold; - } - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = yellow_up; - } else { - if (yellow_threshold > red_threshold) { - // C: |-------- ------| - // W: |········===· ···| - if (yellow_threshold > red_up) { - yellow_threshold = red_up; - } - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_threshold - red_threshold, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = red_threshold; - extremes['warning_normal_fdown_2'] = yellow_threshold; - } - if (yellow_up < red_up) { - // C: |-------- ---| - // W: |····· ·======···| - if (yellow_up < red_threshold) { - yellow_up = red_up; - } - threshold_data.push({ - id: 'warning_normal_fup', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: red_up - yellow_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fup_1'] = red_up; - extremes['warning_normal_fup_2'] = yellow_up; - } - // If warning is under critical completely do not paint anything yellow - // C: |-------- -----| - // W: |···· ···| - } - } else if (yellow_inverse && !red_inverse) { - if (red_only_min && yellow_only_min) { - // C: | -----| - // W: |============··· | - if (yellow_threshold > red_threshold) { - yellow_threshold = red_threshold; - } - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = yellow_threshold; + if ( + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) + ) + $("#" + graph_id + " .xAxis .tickLabel") + .find("div") + .css("top", "+0px") + .css("left", "-20px"); + // Format functions + function xFormatter(v, axis) { + var format = new Array(); + for (i = 0; i < labels_total.length; i++) { + var label = labels_total[i][1]; + var shortLabel = reduceText(label, 28); + if ( + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) + ) + shortLabel = reduceText(label, 18); + var title = ""; + if (label !== shortLabel) { + title = label; + label = shortLabel; + } - } else if (!red_only_min && yellow_only_min) { - // C: | ---- | - // W: |======····=== | + format.push([ + i, + '
' + + label + + "
" + ]); + } + return format; + } - if (yellow_threshold > red_up) { - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_threshold - red_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = red_up; - extremes['warning_normal_fdown_2'] = yellow_threshold; - } + function yFormatter(v, axis) { + return ( + '
' + + v + + "
" + ); + } - if (yellow_threshold > red_threshold) { - yellow_threshold = red_threshold; - } - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = yellow_threshold; + function lFormatter(v, axis) { + return ( + '
' + v + "
" + ); + } - } else if (red_only_min && !yellow_only_min) { - if (yellow_threshold < red_threshold) { - // C: | -----| - // W: |======= ===·····| - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = yellow_threshold; + if (water_mark) { + set_watermark( + graph_id, + plot, + $("#watermark_image_" + graph_id).attr("src") + ); + } +} - if (red_threshold > yellow_up) { - threshold_data.push({ - id: 'warning_normal_fup', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: red_threshold - yellow_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fup_1'] = yellow_up; - extremes['warning_normal_fup_2'] = red_threshold; - } - } else { - // C: | ------------| - // W: |=====·· ········| - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = red_threshold; - } - } else { - if (yellow_threshold > red_up) { - // C: | ----- | - // W: |====·····=== ===| - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, red_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = red_threshold; +function pandoraFlotSlicebar( + graph_id, + values, + datacolor, + labels, + legend, + acumulate_data, + intervaltick, + font, + font_size, + separator, + separator2, + id_agent, + full_legend, + not_interactive, + show_date +) { + values = values.split(separator2); + labels = labels.split(separator); + legend = legend.split(separator); + acumulate_data = acumulate_data.split(separator); + datacolor = datacolor.split(separator); - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, red_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_threshold - red_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = red_up; - extremes['warning_normal_fdown_2'] = yellow_threshold; + if (full_legend != false) { + full_legend = full_legend.split(separator); + } - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = yellow_up; - } else if (red_threshold > yellow_up){ - // C: | ----- | - // W: |=== ===·····==| - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = yellow_threshold; + var font_size = parseInt(font_size); + var font = font + .split("/") + .pop() + .split(".") + .shift(); + // Check possible adapt_keys on classes + check_adaptions(graph_id); - threshold_data.push({ - id: 'warning_normal_fup', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: red_threshold - yellow_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fup_1'] = yellow_up; - extremes['warning_normal_fup_2'] = red_threshold; + var datas = new Array(); - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, red_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = red_up; - } else { - // C: | -------- | - // W: |==· ···=======| - if (yellow_threshold > red_threshold) { - yellow_threshold = red_threshold; - } - if (yellow_up < red_up) { - yellow_up = red_up; - } + for (i = 0; i < values.length; i++) { + var serie = values[i].split(separator); - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_down', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_down'] = yellow_threshold; + var aux = new Array(); + $.each(serie, function(i, v) { + aux.push([v, i]); + }); - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, yellow_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = yellow_up; - } - } - } else if (!yellow_inverse && red_inverse) { - if (yellow_only_min && red_only_min) { - // C: |----- | - // W: | ··============| - if (yellow_threshold < red_threshold) { - yellow_threshold = red_threshold; - } - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = yellow_threshold; - } else if (!yellow_only_min && red_only_min) { - // C: |----- | - // W: | ··======== | - if (yellow_threshold < red_threshold) { - yellow_threshold = red_threshold; - } - if (yellow_up > red_threshold) { - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (yellow_up - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = yellow_up; - } - } else if (yellow_only_min && !red_only_min) { - // C: |----- ------| - // W: | ··======······| - if (yellow_threshold < red_threshold) { - yellow_threshold = red_threshold; - } - if (yellow_threshold < red_up) { - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (red_up - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = red_up; - } - // If warning is under critical completely do not paint anything yellow - // C: |-------- -----| - // W: | ···| - } else { - if (red_up > yellow_threshold && red_threshold < yellow_up) { - // C: |----- ------| - // W: | ··======· | - if (yellow_threshold < red_threshold) { - yellow_threshold = red_threshold; - } - if (yellow_up > red_up) { - yellow_up = red_up; - } + datas.push({ + data: aux, + bars: { + show: true, + fill: 1, + fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] }, + lineWidth: 0, + horizontal: true, + steps: false, + barWidth: 24 * 60 * 60 * 600 + }, + color: datacolor[i] + }); + } - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (yellow_up - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = yellow_up; - } - } - } - // If warning is under critical completely do not paint anything yellow - // C: |-------- -----| or // C: |-------- -----| - // W: | ···· | // W: | ·· | - else { - if (red_only_min && yellow_only_min) { - if (yellow_threshold < red_threshold) { - // C: | ---------| - // W: | =====·········| - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (red_threshold - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = red_threshold; - } - } else if (red_only_min && !yellow_only_min) { - // C: | ---------| - // W: | =====··· | - if (yellow_up > red_threshold) { - yellow_up = red_threshold; - } - if (yellow_threshold < red_threshold) { - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (yellow_up - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = yellow_up; - } - } else if (!red_only_min && yellow_only_min) { - // C: | ------- | - // W: | ==·······=====| - if (yellow_threshold < red_threshold) { - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: red_threshold - yellow_threshold, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = yellow_threshold; - extremes['warning_normal_fdown_2'] = red_threshold; - } + var regex = /visual_console/; + var match = regex.exec(window.location.href); - if (yellow_threshold < red_up) { - yellow_threshold = red_up; - } + var options = { + series: { + stack: true, + bars: { + align: "center" + } + }, + grid: { + borderWidth: 1, + borderColor: "#C1C1C1", + tickColor: "#fff" + }, + xaxes: [ + { + show: show_date, + tickFormatter: xFormatter, + color: "", + tickSize: intervaltick, + tickLength: 0, + font: { + size: font_size + 2, + family: font + "Font" + } + } + ], + yaxes: [ + { + show: false, + tickLength: 0 + } + ], + legend: { + show: false + } + }; - threshold_data.push({ // barWidth will be correct on draw time - id: 'warning_up', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_up'] = yellow_threshold; + if (match == null && not_interactive == 0) { + options.grid["hoverable"] = true; + options.grid["clickable"] = true; + } else { + options.grid["hoverable"] = false; + options.grid["clickable"] = false; + } - } else { - if (red_threshold > yellow_threshold && red_up < yellow_up ) { - // C: | ------ | - // W: | ==······==== | - threshold_data.push({ - id: 'warning_normal_fdown', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: red_threshold - yellow_threshold, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fdown_1'] = yellow_threshold; - extremes['warning_normal_fdown_2'] = red_threshold; + $.plot($("#" + graph_id), datas, options); - threshold_data.push({ - id: 'warning_normal_fup', - data: [[max_x, red_up]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: yellow_up - red_up, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_fup_1'] = red_up; - extremes['warning_normal_fup_2'] = yellow_up; - } else if (red_threshold < yellow_threshold && red_up > yellow_up) { - // If warning is under critical completely do not paint anything yellow - // C: | -------- | - // W: | ···· | - } else { - // C: | -------- | or // C: | ------ | - // W: | ==·· | // W: | ···==== | - if ((yellow_up > red_threshold) && (yellow_up < red_up)) { - yellow_up = red_threshold; - } - if ((yellow_threshold < red_up) && (yellow_threshold > red_threshold)) { - yellow_threshold = red_up; - } - threshold_data.push({ - id: 'warning_normal', - data: [[max_x, yellow_threshold]], - label: null, - color: warning, - bars: {show: true, align: "left", barWidth: (yellow_up - yellow_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 255, 198, 0)' - }); - extremes['warning_normal_1'] = yellow_threshold; - extremes['warning_normal_2'] = yellow_up; - } - } - } + if (match == null) { + // Events + $("#" + graph_id).bind("plothover", function(event, pos, item) { + if (item) { + var from = legend[item.seriesIndex]; + var to = legend[item.seriesIndex + 1]; - // Critical interval - if (red_inverse) { - if (!red_only_min) { - threshold_data.push({ // barWidth will be correct on draw time - id: 'critical_up', - data: [[max_x, red_up]], - label: null, - color: critical, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 236, 234, 0)' - }); - extremes['critical_normal_1'] = red_threshold; - extremes['critical_normal_2'] = red_up; - } - threshold_data.push({ // barWidth will be correct on draw time - id: 'critical_down', - data: [[max_x, red_threshold]], - label: null, - color: critical, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 236, 234, 0)' - }); - extremes['critical_normal_3'] = red_threshold; - extremes['critical_normal_4'] = red_threshold; - } else { - if (red_up == 0 && red_threshold != 0) { - threshold_data.push({ // barWidth will be correct on draw time - id: 'critical_up', - data: [[max_x, red_threshold]], - label: null, - color: critical, - bars: {show: true, align: "left", barWidth: 1, lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 236, 234, 0)' - }); - extremes['critical_normal_1'] = red_threshold; - extremes['critical_normal_2'] = red_up; - } else { - threshold_data.push({ - id: 'critical_normal', - data: [[max_x, red_threshold]], - label: null, - color: critical, - bars: {show: true, align: "left", barWidth: (red_up - red_threshold), lineWidth: 0, horizontal: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.1 } ] }}, - highlightColor: 'rgba(254, 236, 234, 0)' - }); - extremes['critical_normal_1'] = red_threshold; - extremes['critical_normal_2'] = red_up; - } - } - } + if (to == undefined) { + to = ">"; + } - switch (type) { - case 'line': - case 2: - stacked = null; - filled_s = false; - break; - case 3: - stacked = 'stack'; - filled_s = false; - break; - default: - case 'area': - case 0: - stacked = null; - filled_s = 0.3; - break; - case 1: - stacked = 'stack'; - filled_s = 0.3; - break; - } + $("#extra_" + graph_id).text(from + "-" + to); + var extra_height = parseInt( + $("#extra_" + graph_id) + .css("height") + .split("px")[0] + ); + var extra_width = parseInt( + $("#extra_" + graph_id) + .css("width") + .split("px")[0] + ); + $("#extra_" + graph_id).css("left", pos.pageX - extra_width / 4 + "px"); + //$('#extra_'+graph_id).css('top',plot.offset().top-extra_height-5+'px'); + $("#extra_" + graph_id).show(); + } + }); - var datas = new Array(); - var data_base = new Array(); - var lineWidth = $('#hidden-line_width_graph').val() || 1; + $("#" + graph_id).bind("plotclick", function(event, pos, item) { + if (item) { + //from time + var from = legend[item.seriesIndex]; + //to time + var to = legend[item.seriesIndex + 1]; + //current date + var dateObj = new Date(); - i=0; - $.each(values, function (index, value) { - if (typeof value.data !== "undefined") { - if(index.search("alert") >= 0){ - fill_color = '#ff7f00'; - } - else if(index.search("event") >= 0){ - fill_color = '#ff0000'; - } - else{ - fill_color = 'green'; - } + if (full_legend != "") { + newdate = full_legend[item.seriesIndex]; + newdate2 = full_legend[item.seriesIndex + 1]; + } else { + var month = dateObj.getUTCMonth() + 1; //months from 1-12 + var day = dateObj.getUTCDate(); + var year = dateObj.getUTCFullYear(); + newdate = year + "/" + month + "/" + day; + } - switch (series_type[index]) { - case 'area': - line_show = true; - points_show = false; // XXX - false - filled = filled_s; - steps_chart = false; - radius = false; - fill_points = fill_color; - break; - case 'percentil': - case 'line': - default: - line_show = true; - points_show = false; - filled = false; - steps_chart = false; - radius = false; - fill_points = fill_color; - break; - case 'points': - line_show = false; - points_show = true; - filled = false; - steps_chart = false; - radius = 1.5; - fill_points = fill_color; - break; - case 'unknown': - case 'boolean': - line_show = true; - points_show = false; - filled = filled_s; - steps_chart = true; - radius = false; - fill_points = fill_color; - break; - } + if (!to) { + to = "23:59"; + } - if(series_type[index] != 'boolean'){ - if(value.slice_data){ - update_legend[index] = value.slice_data; - } - } + if (full_legend != "") { + if (newdate2 == undefined) { + window.location = + "index.php?sec=eventos&sec2=operation/events/events&id_agent=" + + id_agent + + "&date_from=" + + newdate + + "&time_from=" + + from + + "&status=-1"; + } else { + window.location = + "index.php?sec=eventos&sec2=operation/events/events&id_agent=" + + id_agent + + "&date_from=" + + newdate + + "&time_from=" + + from + + "&date_to=" + + newdate2 + + "&time_to=" + + to + + "&status=-1"; + } + } else { + window.location = + "index.php?sec=eventos&sec2=operation/events/events&id_agent=" + + id_agent + + "&date_from=" + + newdate + + "&time_from=" + + from + + "&date_to=" + + newdate + + "&time_to=" + + to + + "&status=-1"; + } + } + }); - //in graph stacked unset percentil - if( ! ( (type == 1) && ( /percentil/.test(index) ) == true ) && - ! ( (type == 3) && ( /percentil/.test(index) ) == true ) ){ - data_base.push({ - id: 'serie_' + i, - data: value.data, - label: index, - color: color[index]['color'], - lines: { - show: line_show, - fill: filled, - lineWidth: lineWidth, - steps: steps_chart - }, - points: { - show: points_show, - radius: 3, - fillColor: fill_points - }, - legend: legend.index - }); - } - } - i++; - }); + $("#" + graph_id).bind("mouseout", resetInteractivity); + } - // The first execution, the graph data is the base data - datas = data_base; + // Reset interactivity styles + function resetInteractivity() { + $("#extra_" + graph_id).hide(); + } - var number_ticks = 8; - if(vconsole){ - number_ticks = 5; - } + // Format functions + function xFormatter(v, axis) { + v = new Date(1000 * v); + date_format = + (v.getHours() < 10 ? "0" : "") + + v.getHours() + + ":" + + (v.getMinutes() < 10 ? "0" : "") + + v.getMinutes(); + return date_format; + } +} - var maxticks = date_array['period'] / 3600 / number_ticks; +function pandoraFlotArea( + graph_id, + values, + legend, + series_type, + color, + water_mark, + date_array, + data_module_graph, + params, + events_array +) { + //diferents vars + var unit = params.unit ? params.unit : ""; + var homeurl = params.homeurl; + var font_size = parseInt(params.font_size); + var font = params.font + .split("/") + .pop() + .split(".") + .shift(); + var width = params.width; + var height = params.height; + var vconsole = params.vconsole; + var dashboard = params.dashboard; + var menu = params.menu; + var min_x = date_array["start_date"] * 1000; + var max_x = date_array["final_date"] * 1000; + var type = parseInt(params.stacked); + var show_legend = params.show_legend; + var image_treshold = params.image_treshold; + var short_data = params.short_data; + var grid_color = params.grid_color; + var background_color = params.backgroundColor; + var legend_color = params.legend_color; + var update_legend = {}; - var options = { - series: { - stack: stacked, - shadowSize: 0.1 - }, - crosshair: { - mode: 'xy', - color: 'grey' - }, - selection: { - mode: 'xy', - color: '#777' - }, - export: { - export_data: true, - labels_long: legend, - homeurl: homeurl - }, - grid: { - hoverable: true, - clickable: true, - borderWidth:1, - borderColor: '#C1C1C1', - backgroundColor: background_color, - color: grid_color, - autoHighlight: true - }, - xaxis: { - min: min_x, - max: max_x, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - } - }, - xaxes: [{ - mode: "time", - timezone: "browser", - localTimezone: true, - //tickSize: [maxticks, 'hour'] - }], - yaxis: { - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font', - variant: "small-caps" - }, - }, - yaxes: [{ - tickFormatter: yFormatter, - position: 'left' - }], - legend: { - position: 'se', - container: $('#legend_' + graph_id), - labelFormatter: lFormatter - } - }; + //XXXXXX colocar + var force_integer = 0; - if (vconsole) { - options.grid['hoverable'] = false; - options.grid['clickable'] = false; - options.crosshair = false; - options.selection = false; - } + if (typeof type === "undefined" || type == "") { + type = params.type_graph; + } - var stack = 0, - bars = true, - lines = false, - steps = false; + //for threshold + var threshold = true; + var thresholded = false; + var yellow_threshold = parseFloat(data_module_graph.w_min); + var red_threshold = parseFloat(data_module_graph.c_min); + var yellow_up = parseFloat(data_module_graph.w_max); + var red_up = parseFloat(data_module_graph.c_max); + var yellow_inverse = parseInt(data_module_graph.w_inv); + var red_inverse = parseInt(data_module_graph.c_inv); - var plot = $.plot($('#' + graph_id), datas, options); + //XXXXX + var markins_graph = true; - // Re-calculate the graph height with the legend height - if (dashboard || vconsole) { - $acum = 0; - if(dashboard) $acum = 35; - var hDiff = $('#'+graph_id).height() - $('#legend_'+graph_id).height() - $acum; - if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ){ - } - else { - $('#'+graph_id).css('height', hDiff); - } - } + // If threshold and up are the same, that critical or warning is disabled + if (yellow_threshold == yellow_up) { + yellow_inverse = false; + } - /* + if (red_threshold == red_up) { + red_inverse = false; + } + + //Array with points to be painted + var threshold_data = new Array(); + //Array with some interesting points + var extremes = new Array(); + + var yellow_only_min = yellow_up == 0 && yellow_threshold != 0; + var red_only_min = red_up == 0 && red_threshold != 0; + + //color + var warning = "yellow"; + var critical = "red"; + + if (threshold) { + // Warning interval. Change extremes depends on critical interval + if (yellow_inverse && red_inverse) { + if (red_only_min && yellow_only_min) { + // C: |-------- | + // W: |········==== | + if (yellow_threshold > red_threshold) { + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { + colors: [ + { + opacity: 0.1 + }, + { + opacity: 0.1 + } + ] + } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + + extremes["warning_normal_fdown_1"] = red_threshold; + extremes["warning_normal_fdown_2"] = yellow_threshold; + } + } else if (!red_only_min && yellow_only_min) { + // C: |-------- ------| + // W: |········===· | + if (yellow_threshold > red_up) { + yellow_threshold = red_up; + } + if (yellow_threshold > red_threshold) { + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = red_threshold; + extremes["warning_normal_fdown_2"] = yellow_threshold; + } + } else if (red_only_min && !yellow_only_min) { + // C: |------- | + // W: |·······==== ===| + if (red_threshold < yellow_threshold) { + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = red_threshold; + extremes["warning_normal_fdown_2"] = yellow_threshold; + } + + if (yellow_up < red_threshold) { + yellow_up = red_threshold; + } + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = yellow_up; + } else { + if (yellow_threshold > red_threshold) { + // C: |-------- ------| + // W: |········===· ···| + if (yellow_threshold > red_up) { + yellow_threshold = red_up; + } + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = red_threshold; + extremes["warning_normal_fdown_2"] = yellow_threshold; + } + if (yellow_up < red_up) { + // C: |-------- ---| + // W: |····· ·======···| + if (yellow_up < red_threshold) { + yellow_up = red_up; + } + threshold_data.push({ + id: "warning_normal_fup", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_up - yellow_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fup_1"] = red_up; + extremes["warning_normal_fup_2"] = yellow_up; + } + // If warning is under critical completely do not paint anything yellow + // C: |-------- -----| + // W: |···· ···| + } + } else if (yellow_inverse && !red_inverse) { + if (red_only_min && yellow_only_min) { + // C: | -----| + // W: |============··· | + if (yellow_threshold > red_threshold) { + yellow_threshold = red_threshold; + } + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = yellow_threshold; + } else if (!red_only_min && yellow_only_min) { + // C: | ---- | + // W: |======····=== | + + if (yellow_threshold > red_up) { + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = red_up; + extremes["warning_normal_fdown_2"] = yellow_threshold; + } + + if (yellow_threshold > red_threshold) { + yellow_threshold = red_threshold; + } + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = yellow_threshold; + } else if (red_only_min && !yellow_only_min) { + if (yellow_threshold < red_threshold) { + // C: | -----| + // W: |======= ===·····| + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = yellow_threshold; + + if (red_threshold > yellow_up) { + threshold_data.push({ + id: "warning_normal_fup", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_threshold - yellow_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fup_1"] = yellow_up; + extremes["warning_normal_fup_2"] = red_threshold; + } + } else { + // C: | ------------| + // W: |=====·· ········| + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = red_threshold; + } + } else { + if (yellow_threshold > red_up) { + // C: | ----- | + // W: |====·····=== ===| + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, red_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = red_threshold; + + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, red_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_threshold - red_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = red_up; + extremes["warning_normal_fdown_2"] = yellow_threshold; + + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = yellow_up; + } else if (red_threshold > yellow_up) { + // C: | ----- | + // W: |=== ===·····==| + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = yellow_threshold; + + threshold_data.push({ + id: "warning_normal_fup", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_threshold - yellow_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fup_1"] = yellow_up; + extremes["warning_normal_fup_2"] = red_threshold; + + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, red_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = red_up; + } else { + // C: | -------- | + // W: |==· ···=======| + if (yellow_threshold > red_threshold) { + yellow_threshold = red_threshold; + } + if (yellow_up < red_up) { + yellow_up = red_up; + } + + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_down", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_down"] = yellow_threshold; + + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, yellow_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = yellow_up; + } + } + } else if (!yellow_inverse && red_inverse) { + if (yellow_only_min && red_only_min) { + // C: |----- | + // W: | ··============| + if (yellow_threshold < red_threshold) { + yellow_threshold = red_threshold; + } + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = yellow_threshold; + } else if (!yellow_only_min && red_only_min) { + // C: |----- | + // W: | ··======== | + if (yellow_threshold < red_threshold) { + yellow_threshold = red_threshold; + } + if (yellow_up > red_threshold) { + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_up - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = yellow_up; + } + } else if (yellow_only_min && !red_only_min) { + // C: |----- ------| + // W: | ··======······| + if (yellow_threshold < red_threshold) { + yellow_threshold = red_threshold; + } + if (yellow_threshold < red_up) { + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_up - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = red_up; + } + // If warning is under critical completely do not paint anything yellow + // C: |-------- -----| + // W: | ···| + } else { + if (red_up > yellow_threshold && red_threshold < yellow_up) { + // C: |----- ------| + // W: | ··======· | + if (yellow_threshold < red_threshold) { + yellow_threshold = red_threshold; + } + if (yellow_up > red_up) { + yellow_up = red_up; + } + + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_up - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = yellow_up; + } + } + } + // If warning is under critical completely do not paint anything yellow + // C: |-------- -----| or // C: |-------- -----| + // W: | ···· | // W: | ·· | + else { + if (red_only_min && yellow_only_min) { + if (yellow_threshold < red_threshold) { + // C: | ---------| + // W: | =====·········| + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_threshold - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = red_threshold; + } + } else if (red_only_min && !yellow_only_min) { + // C: | ---------| + // W: | =====··· | + if (yellow_up > red_threshold) { + yellow_up = red_threshold; + } + if (yellow_threshold < red_threshold) { + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_up - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = yellow_up; + } + } else if (!red_only_min && yellow_only_min) { + // C: | ------- | + // W: | ==·······=====| + if (yellow_threshold < red_threshold) { + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_threshold - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = yellow_threshold; + extremes["warning_normal_fdown_2"] = red_threshold; + } + + if (yellow_threshold < red_up) { + yellow_threshold = red_up; + } + + threshold_data.push({ + // barWidth will be correct on draw time + id: "warning_up", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_up"] = yellow_threshold; + } else { + if (red_threshold > yellow_threshold && red_up < yellow_up) { + // C: | ------ | + // W: | ==······==== | + threshold_data.push({ + id: "warning_normal_fdown", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: red_threshold - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fdown_1"] = yellow_threshold; + extremes["warning_normal_fdown_2"] = red_threshold; + + threshold_data.push({ + id: "warning_normal_fup", + data: [[max_x, red_up]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_up - red_up, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_fup_1"] = red_up; + extremes["warning_normal_fup_2"] = yellow_up; + } else if (red_threshold < yellow_threshold && red_up > yellow_up) { + // If warning is under critical completely do not paint anything yellow + // C: | -------- | + // W: | ···· | + } else { + // C: | -------- | or // C: | ------ | + // W: | ==·· | // W: | ···==== | + if (yellow_up > red_threshold && yellow_up < red_up) { + yellow_up = red_threshold; + } + if (yellow_threshold < red_up && yellow_threshold > red_threshold) { + yellow_threshold = red_up; + } + threshold_data.push({ + id: "warning_normal", + data: [[max_x, yellow_threshold]], + label: null, + color: warning, + bars: { + show: true, + align: "left", + barWidth: yellow_up - yellow_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 255, 198, 0)" + }); + extremes["warning_normal_1"] = yellow_threshold; + extremes["warning_normal_2"] = yellow_up; + } + } + } + + // Critical interval + if (red_inverse) { + if (!red_only_min) { + threshold_data.push({ + // barWidth will be correct on draw time + id: "critical_up", + data: [[max_x, red_up]], + label: null, + color: critical, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 236, 234, 0)" + }); + extremes["critical_normal_1"] = red_threshold; + extremes["critical_normal_2"] = red_up; + } + threshold_data.push({ + // barWidth will be correct on draw time + id: "critical_down", + data: [[max_x, red_threshold]], + label: null, + color: critical, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 236, 234, 0)" + }); + extremes["critical_normal_3"] = red_threshold; + extremes["critical_normal_4"] = red_threshold; + } else { + if (red_up == 0 && red_threshold != 0) { + threshold_data.push({ + // barWidth will be correct on draw time + id: "critical_up", + data: [[max_x, red_threshold]], + label: null, + color: critical, + bars: { + show: true, + align: "left", + barWidth: 1, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 236, 234, 0)" + }); + extremes["critical_normal_1"] = red_threshold; + extremes["critical_normal_2"] = red_up; + } else { + threshold_data.push({ + id: "critical_normal", + data: [[max_x, red_threshold]], + label: null, + color: critical, + bars: { + show: true, + align: "left", + barWidth: red_up - red_threshold, + lineWidth: 0, + horizontal: true, + fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] } + }, + highlightColor: "rgba(254, 236, 234, 0)" + }); + extremes["critical_normal_1"] = red_threshold; + extremes["critical_normal_2"] = red_up; + } + } + } + + switch (type) { + case "line": + case 2: + stacked = null; + filled_s = false; + break; + case 3: + stacked = "stack"; + filled_s = false; + break; + default: + case "area": + case 0: + stacked = null; + filled_s = 0.3; + break; + case 1: + stacked = "stack"; + filled_s = 0.3; + break; + } + + var datas = new Array(); + var data_base = new Array(); + var lineWidth = $("#hidden-line_width_graph").val() || 1; + + i = 0; + $.each(values, function(index, value) { + if (typeof value.data !== "undefined") { + if (index.search("alert") >= 0) { + fill_color = "#ff7f00"; + } else if (index.search("event") >= 0) { + fill_color = "#ff0000"; + } else { + fill_color = "green"; + } + + switch (series_type[index]) { + case "area": + line_show = true; + points_show = false; // XXX - false + filled = filled_s; + steps_chart = false; + radius = false; + fill_points = fill_color; + break; + case "percentil": + case "line": + default: + line_show = true; + points_show = false; + filled = false; + steps_chart = false; + radius = false; + fill_points = fill_color; + break; + case "points": + line_show = false; + points_show = true; + filled = false; + steps_chart = false; + radius = 1.5; + fill_points = fill_color; + break; + case "unknown": + case "boolean": + line_show = true; + points_show = false; + filled = filled_s; + steps_chart = true; + radius = false; + fill_points = fill_color; + break; + } + + if (series_type[index] != "boolean") { + if (value.slice_data) { + update_legend[index] = value.slice_data; + } + } + + //in graph stacked unset percentil + if ( + !(type == 1 && /percentil/.test(index) == true) && + !(type == 3 && /percentil/.test(index) == true) + ) { + data_base.push({ + id: "serie_" + i, + data: value.data, + label: index, + color: color[index]["color"], + lines: { + show: line_show, + fill: filled, + lineWidth: lineWidth, + steps: steps_chart + }, + points: { + show: points_show, + radius: 3, + fillColor: fill_points + }, + legend: legend.index + }); + } + } + i++; + }); + + // The first execution, the graph data is the base data + datas = data_base; + + var number_ticks = 8; + if (vconsole) { + number_ticks = 5; + } + + var maxticks = date_array["period"] / 3600 / number_ticks; + + var options = { + series: { + stack: stacked, + shadowSize: 0.1 + }, + crosshair: { + mode: "xy", + color: "grey" + }, + selection: { + mode: "xy", + color: "#777" + }, + export: { + export_data: true, + labels_long: legend, + homeurl: homeurl + }, + grid: { + hoverable: true, + clickable: true, + borderWidth: 1, + borderColor: "#C1C1C1", + backgroundColor: background_color, + color: grid_color, + autoHighlight: true + }, + xaxis: { + min: min_x, + max: max_x, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + xaxes: [ + { + mode: "time", + timezone: "browser", + localTimezone: true + //tickSize: [maxticks, 'hour'] + } + ], + yaxis: { + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font", + variant: "small-caps" + } + }, + yaxes: [ + { + tickFormatter: yFormatter, + position: "left" + } + ], + legend: { + position: "se", + container: $("#legend_" + graph_id), + labelFormatter: lFormatter + } + }; + + if (vconsole) { + options.grid["hoverable"] = false; + options.grid["clickable"] = false; + options.crosshair = false; + options.selection = false; + } + + var stack = 0, + bars = true, + lines = false, + steps = false; + + var plot = $.plot($("#" + graph_id), datas, options); + + // Re-calculate the graph height with the legend height + if (dashboard || vconsole) { + $acum = 0; + if (dashboard) $acum = 35; + var hDiff = + $("#" + graph_id).height() - $("#legend_" + graph_id).height() - $acum; + if ( + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) + ) { + } else { + $("#" + graph_id).css("height", hDiff); + } + } + + /* //XXXREvisar esto if (vconsole) { var myCanvas = plot.getCanvas(); @@ -1670,1085 +2158,1231 @@ function pandoraFlotArea( graph_id, values, legend, } */ - // Adjust the overview plot to the width and position of the main plot - adjust_left_width_canvas(graph_id, 'overview_'+graph_id); - update_left_width_canvas(graph_id); - - // Adjust overview when main chart is resized - $('#'+graph_id).resize(function(){ - update_left_width_canvas(graph_id); - }); - - // Adjust linked graph to the width and position of the main plot - // Miniplot - if (!vconsole) { - var overview = $.plot($('#overview_'+graph_id),datas, { - series: { - stack: stacked, - shadowSize: 0.1 - }, - crosshair: { - mode: 'xy' - }, - selection: { - mode: 'xy', - color: '#777' - }, - export: { - export_data: true, - labels_long: legend, - homeurl: homeurl - }, - grid: { - hoverable: true, - clickable: true, - borderWidth:1, - borderColor: '#C1C1C1', - tickColor: background_color, - color: grid_color, - autoHighlight: true - }, - xaxis: { - min: date_array.start_date * 1000, - max: date_array.final_date * 1000, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - } - }, - xaxes: [{ - mode: "time", - timezone: "browser", - localTimezone: true, - //tickSize: [maxticks, 'hour'] - }], - yaxis: { - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - }, - }, - yaxes: [{ - tickFormatter: yFormatter, - position: 'left' - }], - legend: { - position: 'se', - container: $('#legend_' + graph_id), - labelFormatter: lFormatter - } - }); - } - - // Adjust overview when main chart is resized - $('#overview_'+graph_id).resize(function(){ - update_left_width_canvas(graph_id); - }); - - var max_draw = []; - max_draw['max'] = plot.getAxes().yaxis.max; - max_draw['min'] = plot.getAxes().yaxis.min; - - // Connection between plot and miniplot - $('#' + graph_id).bind('plotselected', function (event, ranges) { - // do the zooming if exist menu to undo it - if (menu == 0) { - return; - } - - dataInSelection = ranges.xaxis.to - ranges.xaxis.from; - - var maxticks_zoom = dataInSelection / 3600000 / number_ticks; - if(maxticks_zoom < 0.001){ - maxticks_zoom = dataInSelection / 60000 / number_ticks; - if(maxticks_zoom < 0.001){ - maxticks_zoom = 0; - } - } - - if(thresholded){ - var y_recal = axis_thresholded( - threshold_data, - plot.getAxes().yaxis.min, - plot.getAxes().yaxis.max, - red_threshold, extremes, - red_up - ); - } - else{ - var y_recal = ranges.yaxis; - } - - if (thresholded) { - data_base_treshold = add_threshold ( - data_base, - threshold_data, - ranges.yaxis.from, - y_recal.max, - red_threshold, - extremes, - red_up, - markins_graph - ); - - plot = $.plot($('#' + graph_id), data_base_treshold, - $.extend(true, {}, options, { - grid: { - borderWidth: 1, - hoverable: true, - autoHighlight: true - }, - xaxis: { - min: ranges.xaxis.from, - max: ranges.xaxis.to, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - } - }, - xaxes: [{ - mode: "time", - timezone: "browser", - localTimezone: true, - tickSize: [maxticks_zoom, 'hour'] - }], - yaxis:{ - min: ranges.yaxis.from, - max: y_recal.max, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - }, - }, - yaxes: [{ - tickFormatter: yFormatter, - position: 'left' - }], - legend: { - show: true - } - })); - } - else{ - plot = $.plot($('#' + graph_id), data_base, - $.extend(true, {}, options, { - grid: { - borderWidth: 1, - hoverable: true, - autoHighlight: true - }, - xaxis: { - min: ranges.xaxis.from, - max: ranges.xaxis.to, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - } - }, - xaxes: [{ - mode: "time", - timezone: "browser", - localTimezone: true, - tickSize: [maxticks_zoom, 'hour'] - }], - yaxis:{ - min: ranges.yaxis.from, - max: ranges.yaxis.to, - font: { - size: font_size + 2, - color: legend_color, - family: font+'Font' - }, - }, - yaxes: [{ - tickFormatter: yFormatter, - position: 'left' - }], - legend: { - show: true - } - })); - } - - $('#menu_cancelzoom_' + graph_id).attr('src', homeurl + 'images/zoom_cross_grey.png'); - - max_draw['max'] = ranges.yaxis.to; - max_draw['min'] = ranges.yaxis.from; - - // don't fire event on the overview to prevent eternal loop - overview.setSelection(ranges, true); - }); - - $('#overview_' + graph_id) - .bind('plotselected', function (event, ranges) { - plot.setSelection(ranges); - }); - - var updateLegendTimeout = null; - var latestPosition = null; - var currentPlot = null; - var currentRanges = null; - - // Update legend with the data of the plot in the mouse position - function updateLegend() { - updateLegendTimeout = null; - var pos = latestPosition; - var axes = currentPlot.getAxes(); - if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || - pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) { - return; - } - - $('#timestamp_'+graph_id).show(); - - var d = new Date(pos.x); - var monthNames = [ - "Jan", "Feb", "Mar", - "Apr", "May", "Jun", - "Jul", "Aug", "Sep", - "Oct", "Nov", "Dec" - ]; - - date_format = (d.getDate() <10?'0':'') + d.getDate() + " " + - monthNames[d.getMonth()] + " " + - d.getFullYear() + "\n" + - (d.getHours()<10?'0':'') + d.getHours() + ":" + - (d.getMinutes()<10?'0':'') + d.getMinutes() + ":" + - (d.getSeconds()<10?'0':'') + d.getSeconds(); - - $('#timestamp_'+graph_id).text(date_format); - - var timesize = $('#timestamp_'+graph_id).width(); - - dataset = currentPlot.getData(); - - var timenewpos = dataset[0].xaxis.p2c(pos.x)+$('.yAxis>div').eq(0).width(); - var canvaslimit = $('#'+graph_id).width(); - - $('#timestamp_'+graph_id) - .css('top', currentPlot.getPlotOffset().top - - $('#timestamp_'+graph_id).height() + - $('#legend_' + graph_id).height()); - - $('#timestamp_'+graph_id).css('color', legend_color); - $('#timestamp_'+graph_id).css('font-size', font_size + 2+'px'); - $('#timestamp_'+graph_id).css('font-family', font + 'Font'); - - if (timesize+timenewpos > canvaslimit) { - $('#timestamp_'+graph_id).css('left', timenewpos - timesize); - } - else { - $('#timestamp_'+graph_id).css('left', timenewpos); - } - - var dataset = currentPlot.getData(); - var i = 0; - for (k = 0; k < dataset.length; k++) { - // k is the real series counter - // i is the series counter without thresholds - var series = dataset[k]; - if (series.label == null) { - continue; - } - - // find the nearest points, x-wise - for (j = 0; j < series.data.length; ++j){ - if (series.data[j][0] > pos.x) { - break; - } - - if(series.data[j]){ - var y = series.data[j][1]; - var x = Math.round(series.data[j][0]) -1; - } - } - - y_array = format_unit_yaxes(y); - - y = y_array['y']; - how_bigger = y_array['unit']; - - var data_legend = []; - - // The graphs of points type and unknown graphs will dont be updated - if (series_type[dataset[k]["label"]] != 'points' && - series_type[dataset[k]["label"]] != 'unknown' && - series_type[dataset[k]["label"]] != 'percentil' - ) { - if(Object.keys(update_legend).length == 0){ - var label_aux = legend[series.label]; - - $('#legend_' + graph_id + ' .legendLabel') - .eq(i).html(label_aux + ' value = ' + - (short_data ? number_format(y, 0, "", short_data) : parseFloat(y)) + - how_bigger + ' ' + unit - ); - } - else{ - $.each(update_legend, function (index, value) { - if(!value[x]){ - x = x +1; - } - if(value[x].min){ - min_y_array = format_unit_yaxes(value[x].min); - min_y = min_y_array['y']; - min_bigger = min_y_array['unit']; - } - else{ - min_y = 0; - min_bigger = ""; - } - - if(value[x].max){ - max_y_array = format_unit_yaxes(value[x].max); - max_y = max_y_array['y']; - max_bigger = max_y_array['unit']; - } - else{ - max_y = 0; - max_bigger = ""; - } - - if(value[x].avg){ - avg_y_array = format_unit_yaxes(value[x].avg); - avg_y = avg_y_array['y']; - avg_bigger = avg_y_array['unit']; - } - else{ - avg_y = 0; - avg_bigger = ""; - } - - data_legend[index] = - ' Min: ' + (short_data ? number_format(min_y, 0, "", short_data) : parseFloat(min_y)) + min_bigger - + ' Max: ' + (short_data ? number_format(max_y, 0, "", short_data) : parseFloat(max_y)) + max_bigger - + ' Avg: ' + (short_data ? number_format(avg_y, 0, "", short_data) : parseFloat(avg_y)) + avg_bigger; - }); - - var label_aux = legend[series.label].split(":")[0] + data_legend[series.label]; - $('#legend_' + graph_id + ' .legendLabel').eq(i).html(label_aux); - } - } - - $('#legend_' + graph_id + ' .legendLabel').eq(i).css('color', legend_color); - $('#legend_' + graph_id + ' .legendLabel').eq(i).css('font-size', font_size + 2 +'px'); - $('#legend_' + graph_id + ' .legendLabel').eq(i).css('font-family', font + 'Font'); - - i++; - } - } - - // Events - $('#overview_' + graph_id).bind('plothover', function (event, pos, item) { - plot.setCrosshair({ x: pos.x, y: pos.y }); - currentPlot = plot; - latestPosition = pos; - if (!updateLegendTimeout) { - updateLegendTimeout = setTimeout(updateLegend, 50); - } - }); - - $('#' + graph_id).bind('plothover', function (event, pos, item) { - overview.setCrosshair({ x: pos.x, y: pos.y }); - currentPlot = plot; - latestPosition = pos; - if (!updateLegendTimeout) { - updateLegendTimeout = setTimeout(updateLegend, 50); - } - }); - - $('#' + graph_id).bind("plotclick", function (event, pos, item) { - plot.unhighlight(); - if(item && item.series.label != '' && item.series.label != null && - ( (item.series.label.search("alert") >= 0) || - (item.series.label.search("event") >= 0) ) - ){ - plot.unhighlight(); - - $('#extra_'+graph_id).css('width', '170px'); - $('#extra_'+graph_id).css('height', '60px'); - - var dataset = plot.getData(); - var extra_info = 'No info to show'; - var extra_show = false; - var extra_height = $('#extra_'+graph_id).height(); - var extra_width = parseInt($('#extra_'+graph_id) - .css('width') - .split('px')[0]); - var events_data = new Array(); - var offset_graph = plot.getPlotOffset(); - var offset_relative = plot.offset(); - var width_graph = plot.width(); - var height_legend = $('#legend_' + graph_id).height(); - var coord_x = pos.pageX - offset_relative.left + offset_graph.left; - var coord_y = offset_graph.top + height_legend + extra_height; - - if(coord_x + extra_width > width_graph){ - coord_x = coord_x - extra_width; - } - - var coord_y = offset_graph.top + height_legend + extra_height; - - $('#extra_'+graph_id).css('left',coord_x); - $('#extra_'+graph_id).css('top', coord_y ); - - if( (item.series.label.search("alert") >= 0) || - (item.series.label.search("event") >= 0) ){ - - $.each(events_array, function (i, v) { - $.each(v, function (index, value) { - if(value.utimestamp == item.datapoint[0]/1000 || - value.utimestamp == (item.datapoint[0]/1000) - 1){ - events_data = value; - } - }); - }); - - if(events_data.event_type.search("alert") >= 0){ - $extra_color = '#FFA631'; - } - else if(events_data.event_type.search("critical") >= 0){ - $extra_color = '#FC4444'; - } - else if(events_data.event_type.search("warning") >= 0){ - $extra_color = '#FAD403'; - } - else if(events_data.event_type.search("unknown") >= 0){ - $extra_color = '#3BA0FF'; - } - else if(events_data.event_type.search("normal") >= 0){ - $extra_color = '#80BA27'; - } - else{ - $extra_color = '#ffffff'; - } - - $('#extra_'+graph_id).css('background-color',$extra_color); - - extra_info = ''+events_data.evento+':'; - extra_info += '

Time: '+events_data.timestamp; - extra_show = true; - } - - if (extra_show) { - $('#extra_'+graph_id).html(extra_info); - $('#extra_'+graph_id).css('display',''); - } - plot.highlight(item.series, item.datapoint); - } - else { - $('#extra_'+graph_id).html(''); - $('#extra_'+graph_id).css('display','none'); - } - }); - - if(!vconsole){ - $('#'+graph_id) - .bind('mouseout', resetInteractivity); - $('#overview_'+graph_id) - .bind('mouseout', resetInteractivity); - } - - if(image_treshold){ - if(!thresholded){ - // Recalculate the y axis - var y_recal = axis_thresholded( - threshold_data, - plot.getAxes().yaxis.min, - plot.getAxes().yaxis.max, - red_threshold, extremes, - red_up - ); - } - else{ - var y_recal = plot.getAxes().yaxis.max - } - - datas_treshold = add_threshold ( - data_base, - threshold_data, - plot.getAxes().yaxis.min, - y_recal.max, - red_threshold, - extremes, - red_up, - markins_graph - ); - - plot = $.plot($('#' + graph_id), datas_treshold, - $.extend(true, {}, options, { - yaxis: { - max: y_recal.max, - }, - xaxis: { - min: plot.getAxes().xaxis.min, - max: plot.getAxes().xaxis.max - } - })); - - thresholded = true; - } - - // Reset interactivity styles - function resetInteractivity() { - $('#timestamp_'+graph_id).hide(); - dataset = plot.getData(); - for (i = 0; i < dataset.length; ++i) { - var series = dataset[i]; - var label_aux = legend[series.label]; - $('#legend_' + graph_id + ' .legendLabel') - .eq(i).html(label_aux); - } - $('#legend_' + graph_id + ' .legendLabel') - .css('color', legend_color); - $('#legend_' + graph_id + ' .legendLabel') - .css('font-size', font_size + 2 +'px'); - $('#legend_' + graph_id + ' .legendLabel') - .css('font-family', font + 'Font'); - - plot.clearCrosshair(); - overview.clearCrosshair(); - } - - function yFormatter(v, axis) { - if (short_data) { - var formatted = number_format(v, force_integer, "", short_data); - } - else { - // It is an integer - if(v - Math.floor(v) == 0){ - var formatted = number_format(v, force_integer, "", 2); - } else { - var formatted = v; - } - } - - // Get only two decimals - formatted = round_with_decimals(formatted, 100); - return formatted; - } - - function lFormatter(v, item) { - return ''+legend[v]+''; - } - - $('#overview_' + graph_id).css('display', 'none'); - - if (menu) { - var parent_height; - $('#menu_overview_' + graph_id).click(function() { - $('#overview_' + graph_id).toggle(); - }); - - $("#menu_export_csv_"+graph_id).click(function (e) { - e.preventDefault(); - plot.exportDataCSV(); - var es_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; - if(es_firefox){ - $("#dialog").css('visibility', 'visible').dialog(); - } - delete data_base[0].threshold; - plot = $.plot($('#' + graph_id), data_base, - $.extend(true, {}, options, { - legend: { show: true } - })); - }); - - $('#menu_threshold_' + graph_id).click(function() { - datas = new Array(); - if (thresholded) { - $.each(data_base, function() { - datas.push(this); - }); - - delete data_base[0].threshold; - - plot = $.plot($('#' + graph_id), data_base, - $.extend(true, {}, options, { - yaxis: { - min: max_draw['min'], - max: max_draw['max'] - }, - xaxis: { - min: plot.getAxes().xaxis.min, - max: plot.getAxes().xaxis.max - } - })); - thresholded = false; - } - else { - if(!thresholded){ - // Recalculate the y axis - var y_recal = axis_thresholded( - threshold_data, - plot.getAxes().yaxis.min, - plot.getAxes().yaxis.max, - red_threshold, extremes, - red_up - ); - } - else{ - var y_recal = plot.getAxes().yaxis.max - } - - datas_treshold = add_threshold ( - data_base, - threshold_data, - plot.getAxes().yaxis.min, - y_recal.max, - red_threshold, - extremes, - red_up, - markins_graph - ); - - plot = $.plot($('#' + graph_id), datas_treshold, - $.extend(true, {}, options, { - yaxis: { - min: max_draw['min'], - max: y_recal.max - }, - xaxis: { - min: plot.getAxes().xaxis.min, - max: plot.getAxes().xaxis.max - } - })); - - thresholded = true; - } - - }); - - $('#menu_cancelzoom_' + graph_id).click(function() { - // cancel the zooming - delete data_base[0].threshold; - plot = $.plot($('#' + graph_id), data_base, - $.extend(true, {}, options, { - legend: { show: true } - })); - $('#menu_cancelzoom_' + graph_id) - .attr('src', homeurl + 'images/zoom_cross.disabled.png'); - overview.clearSelection(); - currentRanges = null; - thresholded = false; - max_draw = []; - }); - - // Adjust the menu image on top of the plot - // If there is no legend we increase top-padding to make space to the menu - if (legend.length == 0) { - $('#menu_' + graph_id).parent().css('padding-top', - $('#menu_' + graph_id).css('height')); - } - - // Add bottom margin in the legend - // Estimated height of 24 (works fine with this data in all browsers) - menu_height = 24; - $('#legend_'+graph_id).css('margin-bottom', '10px'); - parent_height = parseInt($('#menu_'+graph_id).parent().css('height').split('px')[0]); - adjust_menu(graph_id, plot, parent_height, width, show_legend); - } - - if (!dashboard) { - if (water_mark){ - set_watermark(graph_id, plot, $('#watermark_image_'+graph_id).attr('src')); - } - //adjust_menu(graph_id, plot, parent_height, width, show_legend); - } + // Adjust the overview plot to the width and position of the main plot + adjust_left_width_canvas(graph_id, "overview_" + graph_id); + update_left_width_canvas(graph_id); + + // Adjust overview when main chart is resized + $("#" + graph_id).resize(function() { + update_left_width_canvas(graph_id); + }); + + // Adjust linked graph to the width and position of the main plot + // Miniplot + if (!vconsole) { + var overview = $.plot($("#overview_" + graph_id), datas, { + series: { + stack: stacked, + shadowSize: 0.1 + }, + crosshair: { + mode: "xy" + }, + selection: { + mode: "xy", + color: "#777" + }, + export: { + export_data: true, + labels_long: legend, + homeurl: homeurl + }, + grid: { + hoverable: true, + clickable: true, + borderWidth: 1, + borderColor: "#C1C1C1", + tickColor: background_color, + color: grid_color, + autoHighlight: true + }, + xaxis: { + min: date_array.start_date * 1000, + max: date_array.final_date * 1000, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + xaxes: [ + { + mode: "time", + timezone: "browser", + localTimezone: true + //tickSize: [maxticks, 'hour'] + } + ], + yaxis: { + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + yaxes: [ + { + tickFormatter: yFormatter, + position: "left" + } + ], + legend: { + position: "se", + container: $("#legend_" + graph_id), + labelFormatter: lFormatter + } + }); + } + + // Adjust overview when main chart is resized + $("#overview_" + graph_id).resize(function() { + update_left_width_canvas(graph_id); + }); + + var max_draw = []; + max_draw["max"] = plot.getAxes().yaxis.max; + max_draw["min"] = plot.getAxes().yaxis.min; + + // Connection between plot and miniplot + $("#" + graph_id).bind("plotselected", function(event, ranges) { + // do the zooming if exist menu to undo it + if (menu == 0) { + return; + } + + dataInSelection = ranges.xaxis.to - ranges.xaxis.from; + + var maxticks_zoom = dataInSelection / 3600000 / number_ticks; + if (maxticks_zoom < 0.001) { + maxticks_zoom = dataInSelection / 60000 / number_ticks; + if (maxticks_zoom < 0.001) { + maxticks_zoom = 0; + } + } + + if (thresholded) { + var y_recal = axis_thresholded( + threshold_data, + plot.getAxes().yaxis.min, + plot.getAxes().yaxis.max, + red_threshold, + extremes, + red_up + ); + } else { + var y_recal = ranges.yaxis; + } + + if (thresholded) { + data_base_treshold = add_threshold( + data_base, + threshold_data, + ranges.yaxis.from, + y_recal.max, + red_threshold, + extremes, + red_up, + markins_graph + ); + + plot = $.plot( + $("#" + graph_id), + data_base_treshold, + $.extend(true, {}, options, { + grid: { + borderWidth: 1, + hoverable: true, + autoHighlight: true + }, + xaxis: { + min: ranges.xaxis.from, + max: ranges.xaxis.to, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + xaxes: [ + { + mode: "time", + timezone: "browser", + localTimezone: true, + tickSize: [maxticks_zoom, "hour"] + } + ], + yaxis: { + min: ranges.yaxis.from, + max: y_recal.max, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + yaxes: [ + { + tickFormatter: yFormatter, + position: "left" + } + ], + legend: { + show: true + } + }) + ); + } else { + plot = $.plot( + $("#" + graph_id), + data_base, + $.extend(true, {}, options, { + grid: { + borderWidth: 1, + hoverable: true, + autoHighlight: true + }, + xaxis: { + min: ranges.xaxis.from, + max: ranges.xaxis.to, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + xaxes: [ + { + mode: "time", + timezone: "browser", + localTimezone: true, + tickSize: [maxticks_zoom, "hour"] + } + ], + yaxis: { + min: ranges.yaxis.from, + max: ranges.yaxis.to, + font: { + size: font_size + 2, + color: legend_color, + family: font + "Font" + } + }, + yaxes: [ + { + tickFormatter: yFormatter, + position: "left" + } + ], + legend: { + show: true + } + }) + ); + } + + $("#menu_cancelzoom_" + graph_id).attr( + "src", + homeurl + "images/zoom_cross_grey.png" + ); + + max_draw["max"] = ranges.yaxis.to; + max_draw["min"] = ranges.yaxis.from; + + // don't fire event on the overview to prevent eternal loop + overview.setSelection(ranges, true); + }); + + $("#overview_" + graph_id).bind("plotselected", function(event, ranges) { + plot.setSelection(ranges); + }); + + var updateLegendTimeout = null; + var latestPosition = null; + var currentPlot = null; + var currentRanges = null; + + // Update legend with the data of the plot in the mouse position + function updateLegend() { + updateLegendTimeout = null; + var pos = latestPosition; + var axes = currentPlot.getAxes(); + if ( + pos.x < axes.xaxis.min || + pos.x > axes.xaxis.max || + pos.y < axes.yaxis.min || + pos.y > axes.yaxis.max + ) { + return; + } + + $("#timestamp_" + graph_id).show(); + + var d = new Date(pos.x); + var monthNames = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ]; + + date_format = + (d.getDate() < 10 ? "0" : "") + + d.getDate() + + " " + + monthNames[d.getMonth()] + + " " + + d.getFullYear() + + "\n" + + (d.getHours() < 10 ? "0" : "") + + d.getHours() + + ":" + + (d.getMinutes() < 10 ? "0" : "") + + d.getMinutes() + + ":" + + (d.getSeconds() < 10 ? "0" : "") + + d.getSeconds(); + + $("#timestamp_" + graph_id).text(date_format); + + var timesize = $("#timestamp_" + graph_id).width(); + + dataset = currentPlot.getData(); + + var timenewpos = + dataset[0].xaxis.p2c(pos.x) + + $(".yAxis>div") + .eq(0) + .width(); + var canvaslimit = $("#" + graph_id).width(); + + $("#timestamp_" + graph_id).css( + "top", + currentPlot.getPlotOffset().top - + $("#timestamp_" + graph_id).height() + + $("#legend_" + graph_id).height() + ); + + $("#timestamp_" + graph_id).css("color", legend_color); + $("#timestamp_" + graph_id).css("font-size", font_size + 2 + "px"); + $("#timestamp_" + graph_id).css("font-family", font + "Font"); + + if (timesize + timenewpos > canvaslimit) { + $("#timestamp_" + graph_id).css("left", timenewpos - timesize); + } else { + $("#timestamp_" + graph_id).css("left", timenewpos); + } + + var dataset = currentPlot.getData(); + var i = 0; + for (k = 0; k < dataset.length; k++) { + // k is the real series counter + // i is the series counter without thresholds + var series = dataset[k]; + if (series.label == null) { + continue; + } + + // find the nearest points, x-wise + for (j = 0; j < series.data.length; ++j) { + if (series.data[j][0] > pos.x) { + break; + } + + if (series.data[j]) { + var y = series.data[j][1]; + var x = Math.round(series.data[j][0]) - 1; + } + } + + y_array = format_unit_yaxes(y); + + y = y_array["y"]; + how_bigger = y_array["unit"]; + + var data_legend = []; + + // The graphs of points type and unknown graphs will dont be updated + if ( + series_type[dataset[k]["label"]] != "points" && + series_type[dataset[k]["label"]] != "unknown" && + series_type[dataset[k]["label"]] != "percentil" + ) { + if (Object.keys(update_legend).length == 0) { + var label_aux = legend[series.label]; + + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .html( + label_aux + + " value = " + + (short_data + ? number_format(y, 0, "", short_data) + : parseFloat(y)) + + how_bigger + + " " + + unit + ); + } else { + $.each(update_legend, function(index, value) { + if (!value[x]) { + x = x + 1; + } + if (value[x].min) { + min_y_array = format_unit_yaxes(value[x].min); + min_y = min_y_array["y"]; + min_bigger = min_y_array["unit"]; + } else { + min_y = 0; + min_bigger = ""; + } + + if (value[x].max) { + max_y_array = format_unit_yaxes(value[x].max); + max_y = max_y_array["y"]; + max_bigger = max_y_array["unit"]; + } else { + max_y = 0; + max_bigger = ""; + } + + if (value[x].avg) { + avg_y_array = format_unit_yaxes(value[x].avg); + avg_y = avg_y_array["y"]; + avg_bigger = avg_y_array["unit"]; + } else { + avg_y = 0; + avg_bigger = ""; + } + + data_legend[index] = + " Min: " + + (short_data + ? number_format(min_y, 0, "", short_data) + : parseFloat(min_y)) + + min_bigger + + " Max: " + + (short_data + ? number_format(max_y, 0, "", short_data) + : parseFloat(max_y)) + + max_bigger + + " Avg: " + + (short_data + ? number_format(avg_y, 0, "", short_data) + : parseFloat(avg_y)) + + avg_bigger; + }); + + var label_aux = + legend[series.label].split(":")[0] + data_legend[series.label]; + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .html(label_aux); + } + } + + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .css("color", legend_color); + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .css("font-size", font_size + 2 + "px"); + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .css("font-family", font + "Font"); + + i++; + } + } + + // Events + $("#overview_" + graph_id).bind("plothover", function(event, pos, item) { + plot.setCrosshair({ x: pos.x, y: pos.y }); + currentPlot = plot; + latestPosition = pos; + if (!updateLegendTimeout) { + updateLegendTimeout = setTimeout(updateLegend, 50); + } + }); + + $("#" + graph_id).bind("plothover", function(event, pos, item) { + overview.setCrosshair({ x: pos.x, y: pos.y }); + currentPlot = plot; + latestPosition = pos; + if (!updateLegendTimeout) { + updateLegendTimeout = setTimeout(updateLegend, 50); + } + }); + + $("#" + graph_id).bind("plotclick", function(event, pos, item) { + plot.unhighlight(); + if ( + item && + item.series.label != "" && + item.series.label != null && + (item.series.label.search("alert") >= 0 || + item.series.label.search("event") >= 0) + ) { + plot.unhighlight(); + + $("#extra_" + graph_id).css("width", "170px"); + $("#extra_" + graph_id).css("height", "60px"); + + var dataset = plot.getData(); + var extra_info = "No info to show"; + var extra_show = false; + var extra_height = $("#extra_" + graph_id).height(); + var extra_width = parseInt( + $("#extra_" + graph_id) + .css("width") + .split("px")[0] + ); + var events_data = new Array(); + var offset_graph = plot.getPlotOffset(); + var offset_relative = plot.offset(); + var width_graph = plot.width(); + var height_legend = $("#legend_" + graph_id).height(); + var coord_x = pos.pageX - offset_relative.left + offset_graph.left; + var coord_y = offset_graph.top + height_legend + extra_height; + + if (coord_x + extra_width > width_graph) { + coord_x = coord_x - extra_width; + } + + var coord_y = offset_graph.top + height_legend + extra_height; + + $("#extra_" + graph_id).css("left", coord_x); + $("#extra_" + graph_id).css("top", coord_y); + + if ( + item.series.label.search("alert") >= 0 || + item.series.label.search("event") >= 0 + ) { + $.each(events_array, function(i, v) { + $.each(v, function(index, value) { + if ( + value.utimestamp == item.datapoint[0] / 1000 || + value.utimestamp == item.datapoint[0] / 1000 - 1 + ) { + events_data = value; + } + }); + }); + + if (events_data.event_type.search("alert") >= 0) { + $extra_color = "#FFA631"; + } else if (events_data.event_type.search("critical") >= 0) { + $extra_color = "#FC4444"; + } else if (events_data.event_type.search("warning") >= 0) { + $extra_color = "#FAD403"; + } else if (events_data.event_type.search("unknown") >= 0) { + $extra_color = "#3BA0FF"; + } else if (events_data.event_type.search("normal") >= 0) { + $extra_color = "#80BA27"; + } else { + $extra_color = "#ffffff"; + } + + $("#extra_" + graph_id).css("background-color", $extra_color); + + extra_info = "" + events_data.evento + ":"; + extra_info += + '

Time: ' + + events_data.timestamp; + extra_show = true; + } + + if (extra_show) { + $("#extra_" + graph_id).html(extra_info); + $("#extra_" + graph_id).css("display", ""); + } + plot.highlight(item.series, item.datapoint); + } else { + $("#extra_" + graph_id).html(""); + $("#extra_" + graph_id).css("display", "none"); + } + }); + + if (!vconsole) { + $("#" + graph_id).bind("mouseout", resetInteractivity); + $("#overview_" + graph_id).bind("mouseout", resetInteractivity); + } + + if (image_treshold) { + if (!thresholded) { + // Recalculate the y axis + var y_recal = axis_thresholded( + threshold_data, + plot.getAxes().yaxis.min, + plot.getAxes().yaxis.max, + red_threshold, + extremes, + red_up + ); + } else { + var y_recal = plot.getAxes().yaxis.max; + } + + datas_treshold = add_threshold( + data_base, + threshold_data, + plot.getAxes().yaxis.min, + y_recal.max, + red_threshold, + extremes, + red_up, + markins_graph + ); + + plot = $.plot( + $("#" + graph_id), + datas_treshold, + $.extend(true, {}, options, { + yaxis: { + max: y_recal.max + }, + xaxis: { + min: plot.getAxes().xaxis.min, + max: plot.getAxes().xaxis.max + } + }) + ); + + thresholded = true; + } + + // Reset interactivity styles + function resetInteractivity() { + $("#timestamp_" + graph_id).hide(); + dataset = plot.getData(); + for (i = 0; i < dataset.length; ++i) { + var series = dataset[i]; + var label_aux = legend[series.label]; + $("#legend_" + graph_id + " .legendLabel") + .eq(i) + .html(label_aux); + } + $("#legend_" + graph_id + " .legendLabel").css("color", legend_color); + $("#legend_" + graph_id + " .legendLabel").css( + "font-size", + font_size + 2 + "px" + ); + $("#legend_" + graph_id + " .legendLabel").css( + "font-family", + font + "Font" + ); + + plot.clearCrosshair(); + overview.clearCrosshair(); + } + + function yFormatter(v, axis) { + if (short_data) { + var formatted = number_format(v, force_integer, "", short_data); + } else { + // It is an integer + if (v - Math.floor(v) == 0) { + var formatted = number_format(v, force_integer, "", 2); + } else { + var formatted = v; + } + } + + // Get only two decimals + formatted = round_with_decimals(formatted, 100); + return formatted; + } + + function lFormatter(v, item) { + return '' + legend[v] + ""; + } + + $("#overview_" + graph_id).css("display", "none"); + + if (menu) { + var parent_height; + $("#menu_overview_" + graph_id).click(function() { + $("#overview_" + graph_id).toggle(); + }); + + $("#menu_export_csv_" + graph_id).click(function(e) { + e.preventDefault(); + plot.exportDataCSV(); + var es_firefox = + navigator.userAgent.toLowerCase().indexOf("firefox") > -1; + if (es_firefox) { + $("#dialog") + .css("visibility", "visible") + .dialog(); + } + delete data_base[0].threshold; + plot = $.plot( + $("#" + graph_id), + data_base, + $.extend(true, {}, options, { + legend: { show: true } + }) + ); + }); + + $("#menu_threshold_" + graph_id).click(function() { + datas = new Array(); + if (thresholded) { + $.each(data_base, function() { + datas.push(this); + }); + + delete data_base[0].threshold; + + plot = $.plot( + $("#" + graph_id), + data_base, + $.extend(true, {}, options, { + yaxis: { + min: max_draw["min"], + max: max_draw["max"] + }, + xaxis: { + min: plot.getAxes().xaxis.min, + max: plot.getAxes().xaxis.max + } + }) + ); + thresholded = false; + } else { + if (!thresholded) { + // Recalculate the y axis + var y_recal = axis_thresholded( + threshold_data, + plot.getAxes().yaxis.min, + plot.getAxes().yaxis.max, + red_threshold, + extremes, + red_up + ); + } else { + var y_recal = plot.getAxes().yaxis.max; + } + + datas_treshold = add_threshold( + data_base, + threshold_data, + plot.getAxes().yaxis.min, + y_recal.max, + red_threshold, + extremes, + red_up, + markins_graph + ); + + plot = $.plot( + $("#" + graph_id), + datas_treshold, + $.extend(true, {}, options, { + yaxis: { + min: max_draw["min"], + max: y_recal.max + }, + xaxis: { + min: plot.getAxes().xaxis.min, + max: plot.getAxes().xaxis.max + } + }) + ); + + thresholded = true; + } + }); + + $("#menu_cancelzoom_" + graph_id).click(function() { + // cancel the zooming + delete data_base[0].threshold; + plot = $.plot( + $("#" + graph_id), + data_base, + $.extend(true, {}, options, { + legend: { show: true } + }) + ); + $("#menu_cancelzoom_" + graph_id).attr( + "src", + homeurl + "images/zoom_cross.disabled.png" + ); + overview.clearSelection(); + currentRanges = null; + thresholded = false; + max_draw = []; + }); + + // Adjust the menu image on top of the plot + // If there is no legend we increase top-padding to make space to the menu + if (legend.length == 0) { + $("#menu_" + graph_id) + .parent() + .css("padding-top", $("#menu_" + graph_id).css("height")); + } + + // Add bottom margin in the legend + // Estimated height of 24 (works fine with this data in all browsers) + menu_height = 24; + $("#legend_" + graph_id).css("margin-bottom", "10px"); + parent_height = parseInt( + $("#menu_" + graph_id) + .parent() + .css("height") + .split("px")[0] + ); + adjust_menu(graph_id, plot, parent_height, width, show_legend); + } + + if (!dashboard) { + if (water_mark) { + set_watermark( + graph_id, + plot, + $("#watermark_image_" + graph_id).attr("src") + ); + } + //adjust_menu(graph_id, plot, parent_height, width, show_legend); + } } -function format_unit_yaxes(y){ - var how_bigger = []; +function format_unit_yaxes(y) { + var how_bigger = []; - if (y > 1000000) { - how_bigger['unit'] = "M"; - how_bigger['y'] = y / 1000000; - } - else if (y > 1000) { - how_bigger['unit'] = "K"; - how_bigger['y'] = y / 1000; - } - else if(y < -1000000) { - how_bigger['unit'] = "M"; - how_bigger['y'] = y / 1000000; - } - else if (y < -1000) { - how_bigger['unit'] = "K"; - how_bigger['y'] = y / 1000; - } - else{ - how_bigger['unit'] = ""; - how_bigger['y'] = y; - } + if (y > 1000000) { + how_bigger["unit"] = "M"; + how_bigger["y"] = y / 1000000; + } else if (y > 1000) { + how_bigger["unit"] = "K"; + how_bigger["y"] = y / 1000; + } else if (y < -1000000) { + how_bigger["unit"] = "M"; + how_bigger["y"] = y / 1000000; + } else if (y < -1000) { + how_bigger["unit"] = "K"; + how_bigger["y"] = y / 1000; + } else { + how_bigger["unit"] = ""; + how_bigger["y"] = y; + } - return how_bigger; + return how_bigger; } function adjust_menu(graph_id, plot, parent_height, width, show_legend) { - if ($('#'+graph_id+' .xAxis .tickLabel').eq(0).css('width') != undefined) { - left_ticks_width = $('#'+graph_id+' .xAxis .tickLabel').eq(0).css('width').split('px')[0]; - } - else { - left_ticks_width = 0; - } + if ( + $("#" + graph_id + " .xAxis .tickLabel") + .eq(0) + .css("width") != undefined + ) { + left_ticks_width = $("#" + graph_id + " .xAxis .tickLabel") + .eq(0) + .css("width") + .split("px")[0]; + } else { + left_ticks_width = 0; + } - var parent_height_new = 0; + var parent_height_new = 0; - if(show_legend){ - var legend_height = parseInt($('#legend_'+graph_id).css('height').split('px')[0]) + parseInt($('#legend_'+graph_id).css('margin-top').split('px')[0]); - } - else{ - var legend_height = 0; - } + if (show_legend) { + var legend_height = + parseInt( + $("#legend_" + graph_id) + .css("height") + .split("px")[0] + ) + + parseInt( + $("#legend_" + graph_id) + .css("margin-top") + .split("px")[0] + ); + } else { + var legend_height = 0; + } - var menu_height = '25'; + var menu_height = "25"; - if ($('#menu_'+graph_id).height() != undefined && $('#menu_'+graph_id).height() > 20) { - menu_height = $('#menu_'+graph_id).height(); - } + if ( + $("#menu_" + graph_id).height() != undefined && + $("#menu_" + graph_id).height() > 20 + ) { + menu_height = $("#menu_" + graph_id).height(); + } - offset = $('#' + graph_id)[0].offsetTop; + offset = $("#" + graph_id)[0].offsetTop; - $('#menu_' + graph_id).css('top', ((offset) + 'px')); + $("#menu_" + graph_id).css("top", offset + "px"); - $('#menu_' + graph_id).show(); + $("#menu_" + graph_id).show(); } function set_watermark(graph_id, plot, watermark_src) { - var img = new Image(); + var img = new Image(); - img.src = watermark_src; - var context = plot.getCanvas().getContext('2d'); + img.src = watermark_src; + var context = plot.getCanvas().getContext("2d"); - // Once it's loaded draw the image on the canvas. - img.addEventListener('load', function () { - // Now resize the image: x, y, w, h. - var down_ticks_height = 0; - if ($('#'+graph_id+' .yAxis .tickLabel').eq(0).css('height') != undefined) { - down_ticks_height = $('#'+graph_id+' .yAxis .tickLabel').eq(0).css('height').split('px')[0]; - } + // Once it's loaded draw the image on the canvas. + img.addEventListener( + "load", + function() { + // Now resize the image: x, y, w, h. + var down_ticks_height = 0; + if ( + $("#" + graph_id + " .yAxis .tickLabel") + .eq(0) + .css("height") != undefined + ) { + down_ticks_height = $("#" + graph_id + " .yAxis .tickLabel") + .eq(0) + .css("height") + .split("px")[0]; + } - var left_pos = parseInt(context.canvas.width) - $('#watermark_image_'+graph_id)[0].width - 30; - var top_pos = 7; - //var top_pos = parseInt(context.canvas.height - down_ticks_height - 10) - $('#watermark_image_'+graph_id)[0].height; - //var left_pos = 380; - context.drawImage(this, left_pos, top_pos); - - }, false); + var left_pos = + parseInt(context.canvas.width) - + $("#watermark_image_" + graph_id)[0].width - + 30; + var top_pos = 7; + //var top_pos = parseInt(context.canvas.height - down_ticks_height - 10) - $('#watermark_image_'+graph_id)[0].height; + //var left_pos = 380; + context.drawImage(this, left_pos, top_pos); + }, + false + ); } -function get_event_details (event_ids) { - table = ''; - if (typeof(event_ids) != "undefined") { - var inputs = []; - var table; - inputs.push ("get_events_details=1"); - inputs.push ("event_ids="+event_ids); - inputs.push ("page=include/ajax/events"); +function get_event_details(event_ids) { + table = ""; + if (typeof event_ids != "undefined") { + var inputs = []; + var table; + inputs.push("get_events_details=1"); + inputs.push("event_ids=" + event_ids); + inputs.push("page=include/ajax/events"); - // Autologin - if ($('#hidden-loginhash').val() != undefined) { - inputs.push ("loginhash=" + $('#hidden-loginhash').val()); - inputs.push ("loginhash_data=" + $('#hidden-loginhash_data').val()); - inputs.push ("loginhash_user=" + $('#hidden-loginhash_user').val()); - } + // Autologin + if ($("#hidden-loginhash").val() != undefined) { + inputs.push("loginhash=" + $("#hidden-loginhash").val()); + inputs.push("loginhash_data=" + $("#hidden-loginhash_data").val()); + inputs.push("loginhash_user=" + $("#hidden-loginhash_user").val()); + } - jQuery.ajax ({ - data: inputs.join ("&"), - type: 'GET', - url: action="../../ajax.php", - timeout: 10000, - dataType: 'html', - async: false, - success: function (data) { - table = data; - //forced_title_callback(); - } - }); - } + jQuery.ajax({ + data: inputs.join("&"), + type: "GET", + url: (action = "../../ajax.php"), + timeout: 10000, + dataType: "html", + async: false, + success: function(data) { + table = data; + //forced_title_callback(); + } + }); + } - return table; + return table; } //Ajusta la grafica pequenña con el desplazamiento del eje y function adjust_left_width_canvas(adapter_id, adapted_id) { - var adapter_left_margin = $('#'+adapter_id+' .yAxis .tickLabel').width(); - var adapted_pix = $('#'+adapted_id).width(); - var new_adapted_width = adapted_pix - adapter_left_margin; - $('#'+adapted_id).width(new_adapted_width); - $('#'+adapted_id).css('margin-left', adapter_left_margin); + var adapter_left_margin = $("#" + adapter_id + " .yAxis .tickLabel").width(); + var adapted_pix = $("#" + adapted_id).width(); + var new_adapted_width = adapted_pix - adapter_left_margin; + $("#" + adapted_id).width(new_adapted_width); + $("#" + adapted_id).css("margin-left", adapter_left_margin); } //Ajusta el ancho de la grafica pequeña con respecto a la grande function update_left_width_canvas(graph_id) { - $('#overview_'+graph_id).width($('#'+graph_id).width()); - $('#overview_'+graph_id).css('margin-left', $('#'+graph_id+' .yAxis .tickLabel').width()); + $("#overview_" + graph_id).width($("#" + graph_id).width()); + $("#overview_" + graph_id).css( + "margin-left", + $("#" + graph_id + " .yAxis .tickLabel").width() + ); } function check_adaptions(graph_id) { - var classes = $('#'+graph_id).attr('class').split(' '); - $.each(classes, function(i,v) { - // If has a class starting with adapted, we adapt it - if (v.split('_')[0] == 'adapted') { - var adapter_id = $('.adapter_'+v.split('_')[1]).attr('id'); - adjust_left_width_canvas(adapter_id, graph_id); - } - }); + var classes = $("#" + graph_id) + .attr("class") + .split(" "); + $.each(classes, function(i, v) { + // If has a class starting with adapted, we adapt it + if (v.split("_")[0] == "adapted") { + var adapter_id = $(".adapter_" + v.split("_")[1]).attr("id"); + adjust_left_width_canvas(adapter_id, graph_id); + } + }); } function number_format(number, force_integer, unit, short_data) { - if (force_integer) { - if (Math.round(number) != number) { - return ''; - } - } - else { - short_data ++; - decimals = pad(1, short_data, 0); - number = Math.round(number * decimals) / decimals; - } + if (force_integer) { + if (Math.round(number) != number) { + return ""; + } + } else { + short_data++; + decimals = pad(1, short_data, 0); + number = Math.round(number * decimals) / decimals; + } - var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; - var pos = 0; - while (1) { - if (number >= 1000) { //as long as the number can be divided by 1000 - pos++; //Position in array starting with 0 - number = number / 1000; - } - else if (number <= -1000) { - pos++; - number = number / 1000; - } - else { - break; - } - } + var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; + var pos = 0; + while (1) { + if (number >= 1000) { + //as long as the number can be divided by 1000 + pos++; //Position in array starting with 0 + number = number / 1000; + } else if (number <= -1000) { + pos++; + number = number / 1000; + } else { + break; + } + } - return number + ' ' + shorts[pos] + unit; + return number + " " + shorts[pos] + unit; } function pad(input, length, padding) { - var str = input + ""; - return (length <= str.length) ? str : pad(str+padding, length, padding); + var str = input + ""; + return length <= str.length ? str : pad(str + padding, length, padding); } // Recalculate the threshold data depends on warning and critical -function axis_thresholded (threshold_data, y_min, y_max, red_threshold, extremes, red_up) { - var y = { - min: 0, - max: 0 - }; +function axis_thresholded( + threshold_data, + y_min, + y_max, + red_threshold, + extremes, + red_up +) { + var y = { + min: 0, + max: 0 + }; - // Default values - var yaxis_resize = { - up: null, - normal_up: 0, - normal_down: 0, - down: null - }; - // Resize the y axis to display all intervals - $.each(threshold_data, function() { - if (/_up/.test(this.id)){ - yaxis_resize['up'] = this.data[0][1]; - } - if (/_down/.test(this.id)){ - if (/critical/.test(this.id)) { - yaxis_resize['down'] = red_threshold; - } else { - yaxis_resize['down'] = extremes[this.id]; - } - } - if (/_normal/.test(this.id)){ - var end; - if (/critical/.test(this.id)) { - end = red_up; - } else { - end = extremes[this.id + '_2']; - } - if (yaxis_resize['normal_up'] < end) yaxis_resize['normal_up'] = end; - if (yaxis_resize['normal_down'] > this.data[0][1]) yaxis_resize['normal_down'] = this.data[0][1]; - } - }); + // Default values + var yaxis_resize = { + up: null, + normal_up: 0, + normal_down: 0, + down: null + }; + // Resize the y axis to display all intervals + $.each(threshold_data, function() { + if (/_up/.test(this.id)) { + yaxis_resize["up"] = this.data[0][1]; + } + if (/_down/.test(this.id)) { + if (/critical/.test(this.id)) { + yaxis_resize["down"] = red_threshold; + } else { + yaxis_resize["down"] = extremes[this.id]; + } + } + if (/_normal/.test(this.id)) { + var end; + if (/critical/.test(this.id)) { + end = red_up; + } else { + end = extremes[this.id + "_2"]; + } + if (yaxis_resize["normal_up"] < end) yaxis_resize["normal_up"] = end; + if (yaxis_resize["normal_down"] > this.data[0][1]) + yaxis_resize["normal_down"] = this.data[0][1]; + } + }); - // If you need to display a up or a down bar, display 10% of data height - var margin_up_or_down = (y_max - y_min)*0.10; + // If you need to display a up or a down bar, display 10% of data height + var margin_up_or_down = (y_max - y_min) * 0.1; - // Calculate the new axis - y['max'] = yaxis_resize['normal_up'] > y_max ? yaxis_resize['normal_up'] : y_max; - y['min'] = yaxis_resize['normal_down'] > y_min ? yaxis_resize['normal_down'] : y_min; - if (yaxis_resize['up'] !== null) { - y['max'] = (yaxis_resize['up'] + margin_up_or_down) < y_max - ? y_max - : yaxis_resize['up'] + margin_up_or_down; - } - if (yaxis_resize['down'] !== null) { - y['min'] = (yaxis_resize['down'] - margin_up_or_down) < y_min - ? yaxis_resize['up'] + margin_up_or_down - : y_min; - } + // Calculate the new axis + y["max"] = + yaxis_resize["normal_up"] > y_max ? yaxis_resize["normal_up"] : y_max; + y["min"] = + yaxis_resize["normal_down"] > y_min ? yaxis_resize["normal_down"] : y_min; + if (yaxis_resize["up"] !== null) { + y["max"] = + yaxis_resize["up"] + margin_up_or_down < y_max + ? y_max + : yaxis_resize["up"] + margin_up_or_down; + } + if (yaxis_resize["down"] !== null) { + y["min"] = + yaxis_resize["down"] - margin_up_or_down < y_min + ? yaxis_resize["up"] + margin_up_or_down + : y_min; + } - return y; + return y; } //add treshold -function add_threshold (data_base, threshold_data, y_min, y_max, - red_threshold, extremes, red_up, markins_graph) { - var datas = new Array (); +function add_threshold( + data_base, + threshold_data, + y_min, + y_max, + red_threshold, + extremes, + red_up, + markins_graph +) { + var datas = new Array(); - $.each(data_base, function() { - datas.push(this); - }); + $.each(data_base, function() { + datas.push(this); + }); - var threshold_array = []; + var threshold_array = []; - // Resize the threshold data - $.each(threshold_data, function(index, value) { - threshold_array[index] = []; + // Resize the threshold data + $.each(threshold_data, function(index, value) { + threshold_array[index] = []; - if (/_up/.test(this.id)){ - this.bars.barWidth = y_max - this.data[0][1]; + if (/_up/.test(this.id)) { + this.bars.barWidth = y_max - this.data[0][1]; - if (/critical/.test(this.id)){ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = y_max; - threshold_array[index]['color'] = "red"; - } - else{ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = y_max; - threshold_array[index]['color'] = "yellow"; - } + if (/critical/.test(this.id)) { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = y_max; + threshold_array[index]["color"] = "red"; + } else { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = y_max; + threshold_array[index]["color"] = "yellow"; + } - if(y_min > this.data[0][1]){ - this.bars.barWidth = this.bars.barWidth - (y_min - this.data[0][1]); - this.data[0][1] = y_min; - } - } + if (y_min > this.data[0][1]) { + this.bars.barWidth = this.bars.barWidth - (y_min - this.data[0][1]); + this.data[0][1] = y_min; + } + } - if (/_down/.test(this.id)){ - var end; - if (/critical/.test(this.id)) { - end = red_threshold; - } else { - end = extremes[this.id]; - } + if (/_down/.test(this.id)) { + var end; + if (/critical/.test(this.id)) { + end = red_threshold; + } else { + end = extremes[this.id]; + } - this.bars.barWidth = end - y_min; - this.data[0][1] = y_min; + this.bars.barWidth = end - y_min; + this.data[0][1] = y_min; - if (/critical/.test(this.id)){ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.bars.barWidth; - threshold_array[index]['color'] = "red"; - } - else{ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.bars.barWidth; - threshold_array[index]['color'] = "yellow"; - } - } + if (/critical/.test(this.id)) { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.bars.barWidth; + threshold_array[index]["color"] = "red"; + } else { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.bars.barWidth; + threshold_array[index]["color"] = "yellow"; + } + } - if (/_normal/.test(this.id)){ - var end; - if (/critical/.test(this.id)) { - end = red_up; - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = end; - threshold_array[index]['color'] = "red"; - } else { - var first = extremes[this.id + '_1']; - var second = extremes[this.id + '_2']; - if(first > second){ - end = first; - } - else{ - end = second; - } - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = end; - threshold_array[index]['color'] = "yellow"; - } + if (/_normal/.test(this.id)) { + var end; + if (/critical/.test(this.id)) { + end = red_up; + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = end; + threshold_array[index]["color"] = "red"; + } else { + var first = extremes[this.id + "_1"]; + var second = extremes[this.id + "_2"]; + if (first > second) { + end = first; + } else { + end = second; + } + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = end; + threshold_array[index]["color"] = "yellow"; + } + if (this.data[0][1] < y_min) { + this.bars.barWidth = end - y_min; + this.data[0][1] = y_min; + end = this.bars.barWidth + this.data[0][1]; - if (this.data[0][1] < y_min) { - this.bars.barWidth = end - y_min; - this.data[0][1] = y_min; - end = this.bars.barWidth + this.data[0][1]; + if (/critical/.test(this.id)) { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.data[0][1] + this.bars.barWidth; + threshold_array[index]["color"] = "red"; + } else { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.data[0][1] + this.bars.barWidth; + threshold_array[index]["color"] = "yellow"; + } + } - if (/critical/.test(this.id)){ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.data[0][1] + this.bars.barWidth; - threshold_array[index]['color'] = "red"; - } - else{ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.data[0][1] + this.bars.barWidth; - threshold_array[index]['color'] = "yellow"; - } + if (end > y_max) { + this.bars.barWidth = y_max - this.data[0][1]; - } + if (/critical/.test(this.id)) { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.data[0][1] + this.bars.barWidth; + threshold_array[index]["color"] = "red"; + } else { + threshold_array[index]["min"] = this.data[0][1]; + threshold_array[index]["max"] = this.data[0][1] + this.bars.barWidth; + threshold_array[index]["color"] = "yellow"; + } + } + } - if (end > y_max) { - this.bars.barWidth = y_max - this.data[0][1]; + if (markins_graph && this.bars.barWidth > 0) { + datas.push(this); + } + }); - if (/critical/.test(this.id)){ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.data[0][1] + this.bars.barWidth; - threshold_array[index]['color'] = "red"; - } - else{ - threshold_array[index]['min'] = this.data[0][1]; - threshold_array[index]['max'] = this.data[0][1] + this.bars.barWidth; - threshold_array[index]['color'] = "yellow"; - } + var extreme_treshold_array = []; + var i = 0; + var flag = true; - } - } + $.each(threshold_array, function(index, value) { + flag = true; + extreme_treshold_array[i] = { + below: value["max"], + color: value["color"] + }; + i++; + $.each(threshold_array, function(i, v) { + if (value["min"] == v["max"]) { + return (flag = false); + } + }); + if (flag) { + extreme_treshold_array[i] = { + below: value["min"], + color: datas[0].color + }; + i++; + } + }); - if(markins_graph && this.bars.barWidth > 0){ - datas.push(this); - } - }); + datas[0].threshold = extreme_treshold_array; - var extreme_treshold_array = []; - var i = 0; - var flag = true; - - $.each(threshold_array, function(index, value) { - flag = true; - extreme_treshold_array[i] = { - 'below': value['max'], - 'color': value['color'], - } - i++; - $.each(threshold_array, function(i, v) { - if(value['min'] == v['max']){ - return flag = false; - } - }); - if(flag){ - extreme_treshold_array[i] = { - 'below': value['min'], - 'color': datas[0].color, - } - i++; - } - }); - - datas[0].threshold = extreme_treshold_array; - - return datas; + return datas; } -function reduceText (text, maxLength) { - if(!text) return text; - if (text.length <= maxLength) return text - var firstSlideEnd = parseInt((maxLength - 3)/1.6); - var str_cut = text.substr(0, firstSlideEnd); - return str_cut + '...
' + text.substr(-firstSlideEnd - 3); +function reduceText(text, maxLength) { + if (!text) return text; + if (text.length <= maxLength) return text; + var firstSlideEnd = parseInt((maxLength - 3) / 1.6); + var str_cut = text.substr(0, firstSlideEnd); + return str_cut + "...
" + text.substr(-firstSlideEnd - 3); } diff --git a/pandora_console/include/graphs/pandora.d3.js b/pandora_console/include/graphs/pandora.d3.js index f33a3b5e68..40dcd34ac1 100644 --- a/pandora_console/include/graphs/pandora.d3.js +++ b/pandora_console/include/graphs/pandora.d3.js @@ -12,7 +12,6 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // The recipient is the selector of the html element // The elements is an array with the names of the wheel elements // The matrix must be a 2 dimensional array with a row and a column for each element @@ -21,246 +20,297 @@ // matrix = [[0, 0, 2], // a[a => a, a => b, a => c] // [5, 0, 1], // b[b => a, b => b, b => c] // [2, 3, 0]]; // c[c => a, c => b, c => c] -function chordDiagram (recipient, elements, matrix, unit, width) { +function chordDiagram(recipient, elements, matrix, unit, width) { + d3.chart = d3.chart || {}; + d3.chart.chordWheel = function(options) { + // Default values + var width = 700; + var margin = 150; + var padding = 0.02; - d3.chart = d3.chart || {}; - d3.chart.chordWheel = function(options) { - - // Default values - var width = 700; - var margin = 150; - var padding = 0.02; + function chart(selection) { + selection.each(function(data) { + var matrix = data.matrix; + var elements = data.elements; + var radius = width / 2 - margin; - function chart(selection) { - selection.each(function(data) { + // create the layout + var chord = d3.layout + .chord() + .padding(padding) + .sortSubgroups(d3.descending); - var matrix = data.matrix; - var elements = data.elements; - var radius = width / 2 - margin; + // Select the svg element, if it exists. + var svg = d3 + .select(this) + .selectAll("svg") + .data([data]); - // create the layout - var chord = d3.layout.chord() - .padding(padding) - .sortSubgroups(d3.descending); + // Otherwise, create the skeletal chart. + var gEnter = svg + .enter() + .append("svg:svg") + .attr("width", width) + .attr("height", width) + .attr("class", "dependencyWheel") + .append("g") + .attr("transform", "translate(" + width / 2 + "," + width / 2 + ")"); - // Select the svg element, if it exists. - var svg = d3.select(this).selectAll("svg").data([data]); + var arc = d3.svg + .arc() + .innerRadius(radius) + .outerRadius(radius + 20); - // Otherwise, create the skeletal chart. - var gEnter = svg.enter().append("svg:svg") - .attr("width", width) - .attr("height", width) - .attr("class", "dependencyWheel") - .append("g") - .attr("transform", "translate(" + (width / 2) + "," + (width / 2) + ")"); + var fill = function(d) { + return "hsl(" + parseInt((d.index / 26) * 360, 10) + ",80%,70%)"; + }; - var arc = d3.svg.arc() - .innerRadius(radius) - .outerRadius(radius + 20); + // Returns an event handler for fading a given chord group. + var fade = function(opacity) { + return function(g, i) { + svg + .selectAll(".chord") + .filter(function(d) { + return d.source.index != i && d.target.index != i; + }) + .transition() + .style("opacity", opacity); + var groups = []; + svg.selectAll(".chord").filter(function(d) { + if (d.source.index == i) { + groups.push(d.target.index); + } + if (d.target.index == i) { + groups.push(d.source.index); + } + }); + groups.push(i); + var length = groups.length; + svg + .selectAll(".group") + .filter(function(d) { + for (var i = 0; i < length; i++) { + if (groups[i] == d.index) return false; + } + return true; + }) + .transition() + .style("opacity", opacity); + }; + }; - var fill = function(d) { - return "hsl(" + parseInt((d.index / 26) * 360, 10) + ",80%,70%)"; - }; + chord.matrix(matrix); - // Returns an event handler for fading a given chord group. - var fade = function(opacity) { - return function(g, i) { - svg.selectAll(".chord") - .filter(function(d) { - return d.source.index != i && d.target.index != i; - }) - .transition() - .style("opacity", opacity); - var groups = []; - svg.selectAll(".chord") - .filter(function(d) { - if (d.source.index == i) { - groups.push(d.target.index); - } - if (d.target.index == i) { - groups.push(d.source.index); - } - }); - groups.push(i); - var length = groups.length; - svg.selectAll('.group') - .filter(function(d) { - for (var i = 0; i < length; i++) { - if(groups[i] == d.index) return false; - } - return true; - }) - .transition() - .style("opacity", opacity); - }; - }; + var rootGroup = chord.groups()[0]; + var rotation = + (-(rootGroup.endAngle - rootGroup.startAngle) / 2) * (180 / Math.PI); - chord.matrix(matrix); + var g = gEnter + .selectAll("g.group") + .data(chord.groups) + .enter() + .append("svg:g") + .attr("class", "group") + .attr("transform", function(d) { + return "rotate(" + rotation + ")"; + }); - var rootGroup = chord.groups()[0]; - var rotation = - (rootGroup.endAngle - rootGroup.startAngle) / 2 * (180 / Math.PI); + g.append("svg:path") + .style("fill", fill) + .style("stroke", fill) + .attr("d", arc) + .on("mouseover", fade(0.1)) + .on("mouseout", fade(1)); - var g = gEnter.selectAll("g.group") - .data(chord.groups) - .enter().append("svg:g") - .attr("class", "group") - .attr("transform", function(d) { - return "rotate(" + rotation + ")"; - }); + g.append("svg:text") + .each(function(d) { + d.angle = (d.startAngle + d.endAngle) / 2; + }) + .attr("dy", ".35em") + .attr("text-anchor", function(d) { + return d.angle > Math.PI ? "end" : null; + }) + .attr("transform", function(d) { + return ( + "rotate(" + + ((d.angle * 180) / Math.PI - 90) + + ")" + + "translate(" + + (radius + 26) + + ")" + + (d.angle > Math.PI ? "rotate(180)" : "") + ); + }) + .text(function(d) { + return elements[d.index]; + }); - g.append("svg:path") - .style("fill", fill) - .style("stroke", fill) - .attr("d", arc) - .on("mouseover", fade(0.1)) - .on("mouseout", fade(1)); + gEnter + .selectAll("path.chord") + .data(chord.chords) + .enter() + .append("svg:path") + .attr("class", "chord") + .style("stroke", function(d) { + return d3.rgb(fill(d.source)).darker(); + }) + .style("fill", function(d) { + return fill(d.source); + }) + .attr("d", d3.svg.chord().radius(radius)) + .attr("transform", function(d) { + return "rotate(" + rotation + ")"; + }) + .style("opacity", 1); - g.append("svg:text") - .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; }) - .attr("dy", ".35em") - .attr("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; }) - .attr("transform", function(d) { - return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" + - "translate(" + (radius + 26) + ")" + - (d.angle > Math.PI ? "rotate(180)" : ""); - }) - .text(function(d) { return elements[d.index]; }); + // Add an elaborate mouseover title for each chord. + gEnter + .selectAll("path.chord") + .on("mouseover", over_user) + .on("mouseout", out_user) + .on("mousemove", move_tooltip); - gEnter.selectAll("path.chord") - .data(chord.chords) - .enter().append("svg:path") - .attr("class", "chord") - .style("stroke", function(d) { return d3.rgb(fill(d.source)).darker(); }) - .style("fill", function(d) { return fill(d.source); }) - .attr("d", d3.svg.chord().radius(radius)) - .attr("transform", function(d) { - return "rotate(" + rotation + ")"; - }) - .style("opacity", 1); + function move_tooltip(d) { + x = d3.event.pageX + 10; + y = d3.event.pageY + 10; - // Add an elaborate mouseover title for each chord. - gEnter.selectAll("path.chord") - .on("mouseover", over_user) - .on("mouseout", out_user) - .on("mousemove", move_tooltip); + $("#tooltip").css("left", x + "px"); + $("#tooltip").css("top", y + "px"); + } - function move_tooltip(d) { - x = d3.event.pageX + 10; - y = d3.event.pageY + 10; - - $("#tooltip").css('left', x + 'px'); - $("#tooltip").css('top', y + 'px'); - } - - function over_user(d) { - id = d.id; - - $("#" + id).css('border', '1px solid black'); - $("#" + id).css('z-index', '1'); - - show_tooltip(d); - } - - function out_user(d) { - id = d.id; - - $("#" + id).css('border', ''); - $("#" + id).css('z-index', ''); - - hide_tooltip(); - } + function over_user(d) { + id = d.id; - function create_tooltip(d, x, y) { - if ($("#tooltip").length == 0) { - $(recipient) - .append($("
") - .attr('id', 'tooltip') - .html( - elements[d.source.index] - + " → " - + elements[d.target.index] - + ": " + d.source.value.toFixed(2) + " " + unit + "" - + "
" - + elements[d.target.index] - + " → " - + elements[d.source.index] - + ": " + d.target.value.toFixed(2) + " " + unit + "" - )); - } - else { - $("#tooltip").html( - elements[d.source.index] - + " → " - + elements[d.target.index] - + ": " + d.source.value.toFixed(2) + " " + unit + "" - + "
" - + elements[d.target.index] - + " → " - + elements[d.source.index] - + ": " + d.target.value.toFixed(2) + " " + unit + "" - ); - } - - $("#tooltip").attr('style', 'background: #fff;' + - 'position: absolute;' + - 'display: inline-block;' + - 'width: auto;' + - 'max-width: 500px;' + - 'text-align: left;' + - 'padding: 10px 10px 10px 10px;' + - 'z-index: 2;' + - "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - 'left: ' + x + 'px;' + - 'top: ' + y + 'px;'); - } - - function show_tooltip(d) { - x = d3.event.pageX + 10; - y = d3.event.pageY + 10; - - create_tooltip(d, x, y); - } - - function hide_tooltip() { - $("#tooltip").hide(); - } - }); - } + $("#" + id).css("border", "1px solid black"); + $("#" + id).css("z-index", "1"); - chart.width = function(value) { - if (!arguments.length) return width; - width = value; - return chart; - }; + show_tooltip(d); + } - chart.margin = function(value) { - if (!arguments.length) return margin; - margin = value; - return chart; - }; + function out_user(d) { + id = d.id; - chart.padding = function(value) { - if (!arguments.length) return padding; - padding = value; - return chart; - }; + $("#" + id).css("border", ""); + $("#" + id).css("z-index", ""); - return chart; - }; + hide_tooltip(); + } - var chart = d3.chart.chordWheel() - .width(width) - .margin(150) - .padding(.02); + function create_tooltip(d, x, y) { + if ($("#tooltip").length == 0) { + $(recipient).append( + $("
") + .attr("id", "tooltip") + .html( + elements[d.source.index] + + " → " + + elements[d.target.index] + + ": " + + d.source.value.toFixed(2) + + " " + + unit + + "" + + "
" + + elements[d.target.index] + + " → " + + elements[d.source.index] + + ": " + + d.target.value.toFixed(2) + + " " + + unit + + "" + ) + ); + } else { + $("#tooltip").html( + elements[d.source.index] + + " → " + + elements[d.target.index] + + ": " + + d.source.value.toFixed(2) + + " " + + unit + + "" + + "
" + + elements[d.target.index] + + " → " + + elements[d.source.index] + + ": " + + d.target.value.toFixed(2) + + " " + + unit + + "" + ); + } - d3.select(recipient) - .datum({ - elements: elements, - matrix: matrix - }) - .call(chart); + $("#tooltip").attr( + "style", + "background: #fff;" + + "position: absolute;" + + "display: inline-block;" + + "width: auto;" + + "max-width: 500px;" + + "text-align: left;" + + "padding: 10px 10px 10px 10px;" + + "z-index: 2;" + + "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "left: " + + x + + "px;" + + "top: " + + y + + "px;" + ); + } + + function show_tooltip(d) { + x = d3.event.pageX + 10; + y = d3.event.pageY + 10; + + create_tooltip(d, x, y); + } + + function hide_tooltip() { + $("#tooltip").hide(); + } + }); + } + + chart.width = function(value) { + if (!arguments.length) return width; + width = value; + return chart; + }; + + chart.margin = function(value) { + if (!arguments.length) return margin; + margin = value; + return chart; + }; + + chart.padding = function(value) { + if (!arguments.length) return padding; + padding = value; + return chart; + }; + + return chart; + }; + + var chart = d3.chart + .chordWheel() + .width(width) + .margin(150) + .padding(0.02); + + d3.select(recipient) + .datum({ + elements: elements, + matrix: matrix + }) + .call(chart); } // The recipient is the selector of the html element @@ -299,2086 +349,2398 @@ function chordDiagram (recipient, elements, matrix, unit, width) { // ] // }; function treeMap(recipient, data, width, height) { + //var isIE = BrowserDetect.browser == 'Explorer'; + var isIE = true; + var chartWidth = width; + var chartHeight = height; + if (width === "auto") { + chartWidth = $(recipient).innerWidth(); + } + if (height === "auto") { + chartHeight = $(recipient).innerHeight(); + } + var xscale = d3.scale.linear().range([0, chartWidth]); + var yscale = d3.scale.linear().range([0, chartHeight]); + var color = d3.scale.category10(); + var headerHeight = 20; + var headerColor = "#555555"; + var transitionDuration = 500; + var root; + var node; - //var isIE = BrowserDetect.browser == 'Explorer'; - var isIE = true; - var chartWidth = width; - var chartHeight = height; - if (width === 'auto') { - chartWidth = $(recipient).innerWidth(); - } - if (height === 'auto') { - chartHeight = $(recipient).innerHeight(); - } - var xscale = d3.scale.linear().range([0, chartWidth]); - var yscale = d3.scale.linear().range([0, chartHeight]); - var color = d3.scale.category10(); - var headerHeight = 20; - var headerColor = "#555555"; - var transitionDuration = 500; - var root; - var node; + var treemap = d3.layout + .treemap() + .round(false) + .size([chartWidth, chartHeight]) + .sticky(true) + .value(function(d) { + return d.value; + }); - var treemap = d3.layout.treemap() - .round(false) - .size([chartWidth, chartHeight]) - .sticky(true) - .value(function(d) { - return d.value; - }); + var chart = d3 + .select(recipient) + .append("svg:svg") + .attr("width", chartWidth) + .attr("height", chartHeight) + .append("svg:g"); - var chart = d3.select(recipient) - .append("svg:svg") - .attr("width", chartWidth) - .attr("height", chartHeight) - .append("svg:g"); + node = root = data; + var nodes = treemap.nodes(root); - node = root = data; - var nodes = treemap.nodes(root); + var children = nodes.filter(function(d) { + return !d.children; + }); + var parents = nodes.filter(function(d) { + return d.children; + }); - var children = nodes.filter(function(d) { - return !d.children; - }); - var parents = nodes.filter(function(d) { - return d.children; - }); + // create parent cells + var parentCells = chart.selectAll("g.cell.parent").data(parents, function(d) { + return d.id; + }); + var parentEnterTransition = parentCells + .enter() + .append("g") + .attr("class", "cell parent") + .on("click", function(d) { + zoom(d); + }) + .append("svg") + .attr("class", "clip") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", headerHeight); + parentEnterTransition + .append("rect") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", headerHeight) + .style("fill", headerColor); + parentEnterTransition + .append("text") + .attr("class", "label") + .attr("fill", "white") + .attr("transform", "translate(3, 13)") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", headerHeight) + .text(function(d) { + return d.name; + }); + // update transition + var parentUpdateTransition = parentCells + .transition() + .duration(transitionDuration); + parentUpdateTransition.select(".cell").attr("transform", function(d) { + return "translate(" + d.dx + "," + d.y + ")"; + }); + parentUpdateTransition + .select("rect") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", headerHeight) + .style("fill", headerColor); + parentUpdateTransition + .select(".label") + .attr("transform", "translate(3, 13)") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", headerHeight) + .text(function(d) { + return d.name; + }); + // remove transition + parentCells.exit().remove(); - // create parent cells - var parentCells = chart.selectAll("g.cell.parent") - .data(parents, function(d) { - return d.id; - }); - var parentEnterTransition = parentCells.enter() - .append("g") - .attr("class", "cell parent") - .on("click", function(d) { - zoom(d); - }) - .append("svg") - .attr("class", "clip") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", headerHeight); - parentEnterTransition.append("rect") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", headerHeight) - .style("fill", headerColor); - parentEnterTransition.append('text') - .attr("class", "label") - .attr("fill", "white") - .attr("transform", "translate(3, 13)") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", headerHeight) - .text(function(d) { - return d.name; - }); - // update transition - var parentUpdateTransition = parentCells.transition().duration(transitionDuration); - parentUpdateTransition.select(".cell") - .attr("transform", function(d) { - return "translate(" + d.dx + "," + d.y + ")"; - }); - parentUpdateTransition.select("rect") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", headerHeight) - .style("fill", headerColor); - parentUpdateTransition.select(".label") - .attr("transform", "translate(3, 13)") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", headerHeight) - .text(function(d) { - return d.name; - }); - // remove transition - parentCells.exit() - .remove(); + // create children cells + var childrenCells = chart + .selectAll("g.cell.child") + .data(children, function(d) { + return d.id; + }); - // create children cells - var childrenCells = chart.selectAll("g.cell.child") - .data(children, function(d) { - return d.id; - }); + // enter transition + var childEnterTransition = childrenCells + .enter() + .append("g") + .attr("class", "cell child") + .on("click", function(d) { + zoom(node === d.parent ? root : d.parent); + }) + .on("mouseover", over_user) + .on("mouseout", out_user) + .on("mousemove", move_tooltip) + .append("svg") + .attr("class", "clip"); - // enter transition - var childEnterTransition = childrenCells.enter() - .append("g") - .attr("class", "cell child") - .on("click", function(d) { - zoom(node === d.parent ? root : d.parent); - }) - .on("mouseover", over_user) - .on("mouseout", out_user) - .on("mousemove", move_tooltip) - .append("svg") - .attr("class", "clip"); + childEnterTransition + .append("rect") + .classed("background", true) + .style("fill", function(d) { + return color(d.name); + }); - childEnterTransition.append("rect") - .classed("background", true) - .style("fill", function(d) { - return color(d.name); - }); + childEnterTransition + .append("text") + .attr("class", "label") + .attr("x", function(d) { + return d.dx / 2; + }) + .attr("y", function(d) { + return d.dy / 2; + }) + .attr("dy", ".35em") + .attr("text-anchor", "middle") + .style("display", "none") + .text(function(d) { + return d.name; + }); - childEnterTransition.append('text') - .attr("class", "label") - .attr('x', function(d) { - return d.dx / 2; - }) - .attr('y', function(d) { - return d.dy / 2; - }) - .attr("dy", ".35em") - .attr("text-anchor", "middle") - .style("display", "none") - .text(function(d) { - return d.name; - }); + // update transition + var childUpdateTransition = childrenCells + .transition() + .duration(transitionDuration); - // update transition - var childUpdateTransition = childrenCells.transition().duration(transitionDuration); + childUpdateTransition.select(".cell").attr("transform", function(d) { + return "translate(" + d.x + "," + d.y + ")"; + }); - childUpdateTransition.select(".cell") - .attr("transform", function(d) { - return "translate(" + d.x + "," + d.y + ")"; - }); + childUpdateTransition + .select("rect") + .attr("width", function(d) { + return Math.max(0.01, d.dx); + }) + .attr("height", function(d) { + return d.dy; + }); - childUpdateTransition.select("rect") - .attr("width", function(d) { - return Math.max(0.01, d.dx); - }) - .attr("height", function(d) { - return d.dy; - }); + childUpdateTransition + .select(".label") + .attr("x", function(d) { + return d.dx / 2; + }) + .attr("y", function(d) { + return d.dy / 2; + }) + .attr("dy", ".35em") + .attr("text-anchor", "middle") + .style("display", "none") + .text(function(d) { + return d.name; + }); - childUpdateTransition.select(".label") - .attr('x', function(d) { - return d.dx / 2; - }) - .attr('y', function(d) { - return d.dy / 2; - }) - .attr("dy", ".35em") - .attr("text-anchor", "middle") - .style("display", "none") - .text(function(d) { - return d.name; - }); + // exit transition + childrenCells.exit().remove(); - // exit transition - childrenCells.exit() - .remove(); + d3.select("select").on("change", function() { + treemap.value(this.value == "size" ? size : count).nodes(root); + zoom(node); + }); - d3.select("select").on("change", function() { - treemap.value(this.value == "size" ? size : count) - .nodes(root); - zoom(node); - }); + zoom(node); - zoom(node); + function size(d) { + return d.size; + } - function size(d) { - return d.size; - } + function count(d) { + return 1; + } - function count(d) { - return 1; - } + //and another one + function textHeight(d) { + var ky = chartHeight / d.dy; + yscale.domain([d.y, d.y + d.dy]); + return (ky * d.dy) / headerHeight; + } - //and another one - function textHeight(d) { - var ky = chartHeight / d.dy; - yscale.domain([d.y, d.y + d.dy]); - return (ky * d.dy) / headerHeight; - } + function getRGBComponents(color) { + var r = color.substring(1, 3); + var g = color.substring(3, 5); + var b = color.substring(5, 7); + return { + R: parseInt(r, 16), + G: parseInt(g, 16), + B: parseInt(b, 16) + }; + } - function getRGBComponents (color) { - var r = color.substring(1, 3); - var g = color.substring(3, 5); - var b = color.substring(5, 7); - return { - R: parseInt(r, 16), - G: parseInt(g, 16), - B: parseInt(b, 16) - }; - } + function idealTextColor(bgColor) { + var nThreshold = 105; + var components = getRGBComponents(bgColor); + var bgDelta = + components.R * 0.299 + components.G * 0.587 + components.B * 0.114; + return 255 - bgDelta < nThreshold ? "#000000" : "#ffffff"; + } - function idealTextColor (bgColor) { - var nThreshold = 105; - var components = getRGBComponents(bgColor); - var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114); - return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff"; - } - - function zoom(d) { - treemap - .padding([headerHeight / (chartHeight / d.dy), 0, 0, 0]) - .nodes(d); + function zoom(d) { + treemap.padding([headerHeight / (chartHeight / d.dy), 0, 0, 0]).nodes(d); - // moving the next two lines above treemap layout messes up padding of zoom result - var kx = chartWidth / d.dx; - var ky = chartHeight / d.dy; - var level = d; + // moving the next two lines above treemap layout messes up padding of zoom result + var kx = chartWidth / d.dx; + var ky = chartHeight / d.dy; + var level = d; - xscale.domain([d.x, d.x + d.dx]); - yscale.domain([d.y, d.y + d.dy]); + xscale.domain([d.x, d.x + d.dx]); + yscale.domain([d.y, d.y + d.dy]); - if (node != level) { - chart.selectAll(".cell.child .label") - .style("display", "none"); - } + if (node != level) { + chart.selectAll(".cell.child .label").style("display", "none"); + } - var zoomTransition = chart.selectAll("g.cell").transition().duration(transitionDuration) - .attr("transform", function(d) { - return "translate(" + xscale(d.x) + "," + yscale(d.y) + ")"; - }) - .each("start", function() { - d3.select(this).select("label") - .style("display", "none"); - }) - .each("end", function(d, i) { - if (!i && (level !== self.root)) { - chart.selectAll(".cell.child") - .filter(function(d) { - return d.parent === self.node; // only get the children for selected group - }) - .select(".label") - .style("display", "") - .style("color", function(d) { - return idealTextColor(color(d.parent.name)); - }); - } - }); + var zoomTransition = chart + .selectAll("g.cell") + .transition() + .duration(transitionDuration) + .attr("transform", function(d) { + return "translate(" + xscale(d.x) + "," + yscale(d.y) + ")"; + }) + .each("start", function() { + d3.select(this) + .select("label") + .style("display", "none"); + }) + .each("end", function(d, i) { + if (!i && level !== self.root) { + chart + .selectAll(".cell.child") + .filter(function(d) { + return d.parent === self.node; // only get the children for selected group + }) + .select(".label") + .style("display", "") + .style("color", function(d) { + return idealTextColor(color(d.parent.name)); + }); + } + }); - zoomTransition.select(".clip") - .attr("width", function(d) { - return Math.max(0.01, (kx * d.dx)); - }) - .attr("height", function(d) { - return d.children ? headerHeight : Math.max(0.01, (ky * d.dy)); - }); + zoomTransition + .select(".clip") + .attr("width", function(d) { + return Math.max(0.01, kx * d.dx); + }) + .attr("height", function(d) { + return d.children ? headerHeight : Math.max(0.01, ky * d.dy); + }); - zoomTransition.select(".label") - .attr("width", function(d) { - return Math.max(0.01, (kx * d.dx)); - }) - .attr("height", function(d) { - return d.children ? headerHeight : Math.max(0.01, (ky * d.dy)); - }) - .text(function(d) { - return d.name; - }); + zoomTransition + .select(".label") + .attr("width", function(d) { + return Math.max(0.01, kx * d.dx); + }) + .attr("height", function(d) { + return d.children ? headerHeight : Math.max(0.01, ky * d.dy); + }) + .text(function(d) { + return d.name; + }); - zoomTransition.select(".child .label") - .attr("x", function(d) { - return kx * d.dx / 2; - }) - .attr("y", function(d) { - return ky * d.dy / 2; - }); + zoomTransition + .select(".child .label") + .attr("x", function(d) { + return (kx * d.dx) / 2; + }) + .attr("y", function(d) { + return (ky * d.dy) / 2; + }); - zoomTransition.select("rect") - .attr("width", function(d) { - return Math.max(0.01, (kx * d.dx)); - }) - .attr("height", function(d) { - return d.children ? headerHeight : Math.max(0.01, (ky * d.dy)); - }); + zoomTransition + .select("rect") + .attr("width", function(d) { + return Math.max(0.01, kx * d.dx); + }) + .attr("height", function(d) { + return d.children ? headerHeight : Math.max(0.01, ky * d.dy); + }); - node = d; + node = d; - if (d3.event) { - d3.event.stopPropagation(); - } - } + if (d3.event) { + d3.event.stopPropagation(); + } + } + function position() { + this.style("left", function(d) { + return d.x + "px"; + }) + .style("top", function(d) { + return d.y + "px"; + }) + .style("width", function(d) { + return Math.max(0, d.dx - 1) + "px"; + }) + .style("height", function(d) { + return Math.max(0, d.dy - 1) + "px"; + }); + } - function position() { - this.style("left", function(d) { return d.x + "px"; }) - .style("top", function(d) { return d.y + "px"; }) - .style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; }) - .style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; }); - } - - function move_tooltip(d) { - x = d3.event.pageX + 10; - y = d3.event.pageY + 10; - - $("#tooltip").css('left', x + 'px'); - $("#tooltip").css('top', y + 'px'); - } - - function over_user(d) { - id = d.id; - - $("#" + id).css('border', '1px solid black'); - $("#" + id).css('z-index', '1'); - - show_tooltip(d); - } - - function out_user(d) { - id = d.id; - - $("#" + id).css('border', ''); - $("#" + id).css('z-index', ''); - - hide_tooltip(); - } + function move_tooltip(d) { + x = d3.event.pageX + 10; + y = d3.event.pageY + 10; - function create_tooltip(d, x, y) { - if ($("#tooltip").length == 0) { - $(recipient) - .append($("
") - .attr('id', 'tooltip') - .html(d.tooltip_content)); - } - else { - $("#tooltip").html(d.tooltip_content); - } - - $("#tooltip").attr('style', 'background: #fff;' + - 'position: absolute;' + - 'display: block;' + - 'width: 200px;' + - 'text-align: left;' + - 'padding: 10px 10px 10px 10px;' + - 'z-index: 2;' + - "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - 'left: ' + x + 'px;' + - 'top: ' + y + 'px;'); - } - - function show_tooltip(d) { - x = d3.event.pageX + 10; - y = d3.event.pageY + 10; - - create_tooltip(d, x, y); - } - - function hide_tooltip() { - $("#tooltip").hide(); - } + $("#tooltip").css("left", x + "px"); + $("#tooltip").css("top", y + "px"); + } + + function over_user(d) { + id = d.id; + + $("#" + id).css("border", "1px solid black"); + $("#" + id).css("z-index", "1"); + + show_tooltip(d); + } + + function out_user(d) { + id = d.id; + + $("#" + id).css("border", ""); + $("#" + id).css("z-index", ""); + + hide_tooltip(); + } + + function create_tooltip(d, x, y) { + if ($("#tooltip").length == 0) { + $(recipient).append( + $("
") + .attr("id", "tooltip") + .html(d.tooltip_content) + ); + } else { + $("#tooltip").html(d.tooltip_content); + } + + $("#tooltip").attr( + "style", + "background: #fff;" + + "position: absolute;" + + "display: block;" + + "width: 200px;" + + "text-align: left;" + + "padding: 10px 10px 10px 10px;" + + "z-index: 2;" + + "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "left: " + + x + + "px;" + + "top: " + + y + + "px;" + ); + } + + function show_tooltip(d) { + x = d3.event.pageX + 10; + y = d3.event.pageY + 10; + + create_tooltip(d, x, y); + } + + function hide_tooltip() { + $("#tooltip").hide(); + } } - // A sunburst is similar to a treemap, except it uses a radial layout. // The root node of the tree is at the center, with leaves on the circumference. // The area (or angle, depending on implementation) of each arc corresponds to its value. // Sunburst design by John Stasko. Data courtesy Jeff Heer. // http://bl.ocks.org/mbostock/4348373 -function sunburst (recipient, data, width, height) { +function sunburst(recipient, data, width, height) { + if (width === "auto") { + width = $(recipient).innerWidth(); + } + if (height === "auto") { + height = width; + } + // var width = 960, + // height = 700; + var radius = Math.min(width, height) / 2; - if (width === 'auto') { - width = $(recipient).innerWidth(); - } - if (height === 'auto') { - height = width; - } - // var width = 960, - // height = 700; - var radius = Math.min(width, height) / 2; + var x = d3.scale.linear().range([0, 2 * Math.PI]); - var x = d3.scale.linear() - .range([0, 2 * Math.PI]); + var y = d3.scale.sqrt().range([0, radius]); - var y = d3.scale.sqrt() - .range([0, radius]); + var color = d3.scale.category20c(); - var color = d3.scale.category20c(); + var svg = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height); - var svg = d3.select(recipient).append("svg") - .attr("width", width) - .attr("height", height); + var partition = d3.layout.partition().value(function(d) { + return d.size; + }); - var partition = d3.layout.partition() - .value(function(d) { return d.size; }); + var arc = d3.svg + .arc() + .startAngle(function(d) { + return Math.max(0, Math.min(2 * Math.PI, x(d.x))); + }) + .endAngle(function(d) { + return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); + }) + .innerRadius(function(d) { + return Math.max(0, y(d.y)); + }) + .outerRadius(function(d) { + return Math.max(0, y(d.y + d.dy)); + }); - var arc = d3.svg.arc() - .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); }) - .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); }) - .innerRadius(function(d) { return Math.max(0, y(d.y)); }) - .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); }); + var g = svg + .selectAll("g") + .data(partition.nodes(data)) + .enter() + .append("g") + .attr( + "transform", + "translate(" + width / 2 + "," + (height / 2 + 10) + ")" + ); - var g = svg.selectAll("g") - .data(partition.nodes(data)) - .enter().append("g") - .attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")"); + var path = g + .append("path") + .attr("d", arc) + .style("fill", function(d) { + return d.color + ? d3.rgb(d.color) + : color((d.children ? d : d.parent).name); + }) + .style("cursor", "pointer") + .on("click", click) + .on("mouseover", over_user) + .on("mouseout", out_user) + .on("mousemove", move_tooltip); - var path = g.append("path") - .attr("d", arc) - .style("fill", function(d) { return d.color ? d3.rgb(d.color) : color((d.children ? d : d.parent).name); }) - .style("cursor", "pointer") - .on("click", click) - .on("mouseover", over_user) - .on("mouseout", out_user) - .on("mousemove", move_tooltip); + function computeTextRotation(d) { + var ang = ((x(d.x + d.dx / 2) - Math.PI / 2) / Math.PI) * 180; + return ang > 90 ? 180 + ang : ang; + } - function computeTextRotation(d) { - var ang = (x(d.x + d.dx / 2) - Math.PI / 2) / Math.PI * 180; - return (ang > 90) ? 180 + ang : ang; - } + var text = g + .append("text") + .attr("transform", function(d) { + return ( + "translate(" + + arc.centroid(d) + + ")rotate(" + + computeTextRotation(d) + + ")" + ); + }) + .attr("x", function(d) { + return computeTextRotation(d) > 180 ? -40 : -30; + }) + .attr("dx", "6") // margin + .attr("dy", ".35em") // vertical-align + .attr("opacity", function(d) { + if (typeof d.show_name != "undefined" && d.show_name) return 1; + else return 0; + }) + .text(function(d) { + return d.name; + }) + .style("font-size", "10px") + // Makes svg elements invisible to events + .style("pointer-events", "none"); - var text = g.append("text") - .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + computeTextRotation(d) + ")"; }) - .attr("x", function (d) { return computeTextRotation(d) > 180 ? -40 : -30; }) - .attr("dx", "6") // margin - .attr("dy", ".35em") // vertical-align - .attr("opacity", function(d) { - if (typeof d.show_name != "undefined" && d.show_name) - return 1; - else - return 0; - }) - .text(function(d) { - return d.name; - }) - .style("font-size", "10px") - // Makes svg elements invisible to events - .style("pointer-events", "none"); + function click(d) { + if (typeof d.link != "undefined") { + window.location.href = d.link; + } else { + // fade out all text elements + text.transition().attr("opacity", 0); - function click(d) { - if (typeof d.link != "undefined") { - window.location.href = d.link; - } - else { - // fade out all text elements - text.transition().attr("opacity", 0); + path + .transition() + .duration(750) + .attrTween("d", arcTween(d)) + .each("end", function(e, i) { + // check if the animated element's data e lies within the visible angle span given in d + if ( + typeof e.type != "undefined" && + (e.type == "group" || + (e.type == "agent" && + (d.type == "group" || + d.type == "agent" || + d.type == "module_group" || + d.type == "module")) || + ((e.type == "module_group" || e.type == "module") && + (d.type == "agent" || d.type == "module_group"))) && + e.x >= d.x && + e.x < d.x + d.dx + ) { + // get a selection of the associated text element + var arcText = d3.select(this.parentNode).select("text"); + // fade in the text element and recalculate positions + arcText + .attr("transform", function(d) { + return ( + "translate(" + + arc.centroid(d) + + ")rotate(" + + computeTextRotation(d) + + ")" + ); + }) + .attr("x", function(d) { + return computeTextRotation(d) > 180 ? -40 : -30; + }) + .transition() + .duration(250) + .attr("opacity", 1); + } + }); + } + } - path.transition() - .duration(750) - .attrTween("d", arcTween(d)) - .each("end", function(e, i) { - // check if the animated element's data e lies within the visible angle span given in d - if ((typeof e.type != 'undefined' - && (e.type == "group" - || ( e.type == "agent" && (d.type == "group" || d.type == "agent" || d.type == "module_group" || d.type == "module") ) - || ( (e.type == "module_group" || e.type == "module") && (d.type == "agent" || d.type == "module_group") ) )) - && e.x >= d.x && e.x < (d.x + d.dx)) { - // get a selection of the associated text element - var arcText = d3.select(this.parentNode).select("text"); - // fade in the text element and recalculate positions - arcText - .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + computeTextRotation(d) + ")"; }) - .attr("x", function (d) { return computeTextRotation(d) > 180 ? -40 : -30; }) - .transition().duration(250) - .attr("opacity", 1); - } - }); - } - } + d3.select(self.frameElement).style("height", height + "px"); - d3.select(self.frameElement).style("height", height + "px"); + // Interpolate the scales! + function arcTween(d) { + var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]), + yd = d3.interpolate(y.domain(), [d.y, 1]), + yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]); + return function(d, i) { + return i + ? function(t) { + return arc(d); + } + : function(t) { + x.domain(xd(t)); + y.domain(yd(t)).range(yr(t)); + return arc(d); + }; + }; + } - // Interpolate the scales! - function arcTween(d) { - var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]), - yd = d3.interpolate(y.domain(), [d.y, 1]), - yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]); - return function(d, i) { - return i - ? function(t) { return arc(d); } - : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); }; - }; - } + function move_tooltip(d) { + var x = d3.event.pageX + 10; + var y = d3.event.pageY + 10; - function move_tooltip(d) { - var x = d3.event.pageX + 10; - var y = d3.event.pageY + 10; - - $("#tooltip").css('left', x + 'px'); - $("#tooltip").css('top', y + 'px'); - } - - function over_user(d) { - id = d.id; - - $("#" + id).css('border', '1px solid black'); - $("#" + id).css('z-index', '1'); - - show_tooltip(d); - } - - function out_user(d) { - id = d.id; - - $("#" + id).css('border', ''); - $("#" + id).css('z-index', ''); - - hide_tooltip(); - } + $("#tooltip").css("left", x + "px"); + $("#tooltip").css("top", y + "px"); + } - function create_tooltip(d, x, y) { - var tooltip = (typeof d.tooltip_content != 'undefined') ? d.tooltip_content : d.name; + function over_user(d) { + id = d.id; - if ($("#tooltip").length == 0) { - $(recipient) - .append($("
") - .attr('id', 'tooltip') - .html(tooltip)); - } - else { - $("#tooltip").html(tooltip); - } - - $("#tooltip").attr('style', 'background: #fff;' + - 'position: absolute;' + - 'display: block;' + - 'width: 200px;' + - 'text-align: left;' + - 'padding: 10px 10px 10px 10px;' + - 'z-index: 2;' + - "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + - 'left: ' + x + 'px;' + - 'top: ' + y + 'px;'); - } - - function show_tooltip(d) { - var x = d3.event.pageX + 10; - var y = d3.event.pageY + 10; - - create_tooltip(d, x, y); - } - - function hide_tooltip() { - $("#tooltip").hide(); - } + $("#" + id).css("border", "1px solid black"); + $("#" + id).css("z-index", "1"); + + show_tooltip(d); + } + + function out_user(d) { + id = d.id; + + $("#" + id).css("border", ""); + $("#" + id).css("z-index", ""); + + hide_tooltip(); + } + + function create_tooltip(d, x, y) { + var tooltip = + typeof d.tooltip_content != "undefined" ? d.tooltip_content : d.name; + + if ($("#tooltip").length == 0) { + $(recipient).append( + $("
") + .attr("id", "tooltip") + .html(tooltip) + ); + } else { + $("#tooltip").html(tooltip); + } + + $("#tooltip").attr( + "style", + "background: #fff;" + + "position: absolute;" + + "display: block;" + + "width: 200px;" + + "text-align: left;" + + "padding: 10px 10px 10px 10px;" + + "z-index: 2;" + + "-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);" + + "left: " + + x + + "px;" + + "top: " + + y + + "px;" + ); + } + + function show_tooltip(d) { + var x = d3.event.pageX + 10; + var y = d3.event.pageY + 10; + + create_tooltip(d, x, y); + } + + function hide_tooltip() { + $("#tooltip").hide(); + } } -function createGauge(name, etiqueta, value, min, max, min_warning,max_warning,warning_inverse,min_critical,max_critical,critical_inverse,font_size, height, font) -{ - var gauges; +function createGauge( + name, + etiqueta, + value, + min, + max, + min_warning, + max_warning, + warning_inverse, + min_critical, + max_critical, + critical_inverse, + font_size, + height, + font +) { + var gauges; - var config = - { - size: height, - label: etiqueta, - min: undefined != min ? min : 0, - max: undefined != max ? max : 100, - font_size: font_size - } - - if (value == null) { - config.majorTicks = 1; - config.minorTicks = 1; - value = false; - } - else { - config.minorTicks = 10; - } + var config = { + size: height, + label: etiqueta, + min: undefined != min ? min : 0, + max: undefined != max ? max : 100, + font_size: font_size + }; - save_min_critical = min_critical; - save_max_critical = max_critical; - save_min_warning = min_warning; - save_max_warning = max_warning; - - if (max_warning < config.min) { - config.min = max_warning; - } - if (min_warning < config.min) { - config.min = min_warning; - } - if (max_critical < config.min) { - config.min = max_critical; - } - if (min_critical < config.min) { - config.min = min_critical; - } + if (value == null) { + config.majorTicks = 1; + config.minorTicks = 1; + value = false; + } else { + config.minorTicks = 10; + } - if (max_warning > config.max) { - config.max = max_warning; - } - if (min_warning > config.max) { - config.max = min_warning; - } - if (max_critical > config.max) { - config.max = max_critical; - } - if (min_critical > config.max) { - config.max = min_critical; - } - - if(config.max < value){ - config.max = value; - } + save_min_critical = min_critical; + save_max_critical = max_critical; + save_min_warning = min_warning; + save_max_warning = max_warning; - if(config.min > value){ - config.min = value; - } - - if (critical_inverse == 1) { - if (max_critical == 0) { - max_critical = min_critical; - min_critical = config.min; - } - else { - max_critical = save_min_critical; - min_critical = config.min; - max_critical2 = config.max; - min_critical2 = save_max_critical; - } - } - else { - if ((min_critical > max_critical) && (max_critical == 0)) { - max_critical = config.max; - } - } + if (max_warning < config.min) { + config.min = max_warning; + } + if (min_warning < config.min) { + config.min = min_warning; + } + if (max_critical < config.min) { + config.min = max_critical; + } + if (min_critical < config.min) { + config.min = min_critical; + } - if (warning_inverse == 1) { - if (max_warning == 0) { - max_warning = min_warning; - min_warning = config.min; - } - else{ - max_warning = save_min_warning; - min_warning = config.min; - max_warning2 = config.max; - min_warning2 = save_max_warning; - } - - } - else { - if ((min_warning > max_warning) && (max_warning == 0)) { - max_warning = config.max; - } - } + if (max_warning > config.max) { + config.max = max_warning; + } + if (min_warning > config.max) { + config.max = min_warning; + } + if (max_critical > config.max) { + config.max = max_critical; + } + if (min_critical > config.max) { + config.max = min_critical; + } - if (value !== false) { - if(typeof max_warning2 !== 'undefined'){ - if ( min_warning >= 0 && ( min_warning != max_warning ) ) { - config.yellowZones = [{ from: min_warning, to: max_warning },{ from: min_warning2, to: max_warning2 }]; - } - } - else{ - if ( min_warning >= 0 && ( min_warning != max_warning ) ) { - config.yellowZones = [{ from: min_warning, to: max_warning }]; - } - } + if (config.max < value) { + config.max = value; + } - if(typeof max_critical2 !== 'undefined'){ - if ( min_critical >= 0 && ( min_critical != max_critical ) ) { - config.redZones = [{ from: min_critical, to: max_critical},{from: min_critical2, to: max_critical2 }]; - } - } - else { - if ( min_critical >= 0 && ( min_critical != max_critical ) ) { - config.redZones = [{ from: min_critical, to: max_critical }]; - } - } - } + if (config.min > value) { + config.min = value; + } - var range = config.max - config.min; - - gauges = new Gauge(name, config, font); - gauges.render(); - gauges.redraw(value); - $(".gauge>text").each(function() { - label = $(this).text(); - - if (!isNaN(label)){ - label = parseFloat(label); - text = label.toLocaleString(); - if ( label >= 1000000) - text = text.substring(0,4) + "M"; - else if (label >= 100000) - text = text.substring(0,3) + "K"; - else if (label >= 10000) - text = text.substring(0,3) + "K"; - - $(this).text(text); - } - }); - $(".pointerContainer>text").each(function() { - label = $(this).text(); - - if (!isNaN(label)){ - label = parseFloat(label); - text = label.toLocaleString(); - if ( label >= 10000000) - text = text.substring(0,4) + "M"; - else if ( label >= 1000000) - text = text.substring(0,4) + "M"; - else if (label >= 100000) - text = text.substring(0,3) + "K"; - else if (label >= 10000) - text = text.substring(0,3) + "K"; - $(this).text(text); - } - }); - config = false; - max_warning2 = false; - min_warning2 = false; + if (critical_inverse == 1) { + if (max_critical == 0) { + max_critical = min_critical; + min_critical = config.min; + } else { + max_critical = save_min_critical; + min_critical = config.min; + max_critical2 = config.max; + min_critical2 = save_max_critical; + } + } else { + if (min_critical > max_critical && max_critical == 0) { + max_critical = config.max; + } + } + + if (warning_inverse == 1) { + if (max_warning == 0) { + max_warning = min_warning; + min_warning = config.min; + } else { + max_warning = save_min_warning; + min_warning = config.min; + max_warning2 = config.max; + min_warning2 = save_max_warning; + } + } else { + if (min_warning > max_warning && max_warning == 0) { + max_warning = config.max; + } + } + + if (value !== false) { + if (typeof max_warning2 !== "undefined") { + if (min_warning >= 0 && min_warning != max_warning) { + config.yellowZones = [ + { from: min_warning, to: max_warning }, + { from: min_warning2, to: max_warning2 } + ]; + } + } else { + if (min_warning >= 0 && min_warning != max_warning) { + config.yellowZones = [{ from: min_warning, to: max_warning }]; + } + } + + if (typeof max_critical2 !== "undefined") { + if (min_critical >= 0 && min_critical != max_critical) { + config.redZones = [ + { from: min_critical, to: max_critical }, + { from: min_critical2, to: max_critical2 } + ]; + } + } else { + if (min_critical >= 0 && min_critical != max_critical) { + config.redZones = [{ from: min_critical, to: max_critical }]; + } + } + } + + var range = config.max - config.min; + + gauges = new Gauge(name, config, font); + gauges.render(); + gauges.redraw(value); + $(".gauge>text").each(function() { + label = $(this).text(); + + if (!isNaN(label)) { + label = parseFloat(label); + text = label.toLocaleString(); + if (label >= 1000000) text = text.substring(0, 4) + "M"; + else if (label >= 100000) text = text.substring(0, 3) + "K"; + else if (label >= 10000) text = text.substring(0, 3) + "K"; + + $(this).text(text); + } + }); + $(".pointerContainer>text").each(function() { + label = $(this).text(); + + if (!isNaN(label)) { + label = parseFloat(label); + text = label.toLocaleString(); + if (label >= 10000000) text = text.substring(0, 4) + "M"; + else if (label >= 1000000) text = text.substring(0, 4) + "M"; + else if (label >= 100000) text = text.substring(0, 3) + "K"; + else if (label >= 10000) text = text.substring(0, 3) + "K"; + $(this).text(text); + } + }); + config = false; + max_warning2 = false; + min_warning2 = false; } function createGauges(data, width, height, font_size, no_data_image, font) { - var nombre,label,minimun_warning,maximun_warning,minimun_critical,maximun_critical, - mininum,maxinum,valor; + var nombre, + label, + minimun_warning, + maximun_warning, + minimun_critical, + maximun_critical, + mininum, + maxinum, + valor; - for (key in data) { - nombre = data[key].gauge; + for (key in data) { + nombre = data[key].gauge; - label = data[key].label; + label = data[key].label; - label = label.replace(/ /g,' '); - label = label.replace(/\(/g,'\('); - label = label.replace(/\)/g,'\)'); + label = label.replace(/ /g, " "); + label = label.replace(/\(/g, "("); + label = label.replace(/\)/g, ")"); - label = label.replace(/(/g,'\('); - label = label.replace(/)/g,'\)'); + label = label.replace(/(/g, "("); + label = label.replace(/)/g, ")"); - minimun_warning = round_with_decimals(parseFloat( data[key].min_warning )); - maximun_warning = round_with_decimals(parseFloat( data[key].max_warning )); - minimun_critical = round_with_decimals(parseFloat( data[key].min_critical )); - maximun_critical = round_with_decimals(parseFloat( data[key].max_critical )); + minimun_warning = round_with_decimals(parseFloat(data[key].min_warning)); + maximun_warning = round_with_decimals(parseFloat(data[key].max_warning)); + minimun_critical = round_with_decimals(parseFloat(data[key].min_critical)); + maximun_critical = round_with_decimals(parseFloat(data[key].max_critical)); - mininum = round_with_decimals(parseFloat(data[key].min)); - maxinum = round_with_decimals(parseFloat(data[key].max)); + mininum = round_with_decimals(parseFloat(data[key].min)); + maxinum = round_with_decimals(parseFloat(data[key].max)); - critical_inverse = parseInt(data[key].critical_inverse); - warning_inverse = parseInt(data[key].warning_inverse); + critical_inverse = parseInt(data[key].critical_inverse); + warning_inverse = parseInt(data[key].warning_inverse); - valor = round_with_decimals(data[key].value); + valor = round_with_decimals(data[key].value); - - if (isNaN(valor)) - valor = null; - createGauge(nombre, label, valor, mininum, maxinum, - minimun_warning, maximun_warning, warning_inverse, minimun_critical, - maximun_critical, critical_inverse, font_size, height, font); - - } + if (isNaN(valor)) valor = null; + createGauge( + nombre, + label, + valor, + mininum, + maxinum, + minimun_warning, + maximun_warning, + warning_inverse, + minimun_critical, + maximun_critical, + critical_inverse, + font_size, + height, + font + ); + } } -function Gauge(placeholderName, configuration, font) -{ +function Gauge(placeholderName, configuration, font) { + var font = font + .split("/") + .pop() + .split(".") + .shift(); + this.placeholderName = placeholderName; - var font = font.split("/").pop().split(".").shift(); - this.placeholderName = placeholderName; - - var self = this; // for internal d3 functions - - this.configure = function(configuration) - { - this.config = configuration; - - this.config.size = this.config.size * 0.9; - this.config.font_size = this.config.font_size; - - this.config.raduis = this.config.size * 0.97 / 2; - this.config.cx = this.config.size / 2; - this.config.cy = this.config.size / 2; - - this.config.min = undefined != configuration.min ? configuration.min : 0; - this.config.max = undefined != configuration.max ? configuration.max : 100; - this.config.range = this.config.max - this.config.min; - - this.config.majorTicks = configuration.majorTicks || 5; - this.config.minorTicks = configuration.minorTicks || 2; - - this.config.greenColor = configuration.greenColor || "#109618"; - this.config.yellowColor = configuration.yellowColor || "#FF9900"; - this.config.redColor = configuration.redColor || "#DC3912"; - - this.config.transitionDuration = configuration.transitionDuration || 500; - } + var self = this; // for internal d3 functions - this.render = function() - { - this.body = d3.select("#" + this.placeholderName) - .append("svg:svg") - .attr("class", "gauge") - .attr("width", this.config.size) - .attr("height", this.config.size); - - this.body.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", this.config.raduis) - .style("fill", "#ccc") - .style("stroke", "#000") - .style("stroke-width", "0.5px"); - - this.body.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", 0.9 * this.config.raduis) - .style("fill", "#fff") - .style("stroke", "#e0e0e0") - .style("stroke-width", "2px"); - - for (var index in this.config.greenZones) - { - this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor); - } - - for (var index in this.config.yellowZones) - { - this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor); - } - - for (var index in this.config.redZones) - { - this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor); - } - - if (undefined != this.config.label) - { - var fontSize = Math.round(this.config.size / 9); - this.body.append("svg:text") - .attr("x", this.config.cx) - .attr("y", this.config.cy / 2 + fontSize / 2) - .attr("dy", fontSize / 2) - .attr("text-anchor", "middle") - .attr("class", font) - .text(this.config.label) - .style("font-size", this.config.font_size+"pt") - .style("fill", "#333") - .style("stroke-width", "0px"); - } - - var fontSize = Math.round(this.config.size / 16); - var majorDelta = this.config.range / (this.config.majorTicks - 1); - for (var major = this.config.min; major <= this.config.max; major += majorDelta) - { - var minorDelta = majorDelta / this.config.minorTicks; - for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta) - { - var point1 = this.valueToPoint(minor, 0.75); - var point2 = this.valueToPoint(minor, 0.85); - - this.body.append("svg:line") - .attr("x1", point1.x) - .attr("y1", point1.y) - .attr("x2", point2.x) - .attr("y2", point2.y) - .style("stroke", "#666") - .style("stroke-width", "1px"); - } - - var point1 = this.valueToPoint(major, 0.7); - var point2 = this.valueToPoint(major, 0.85); - - this.body.append("svg:line") - .attr("x1", point1.x) - .attr("y1", point1.y) - .attr("x2", point2.x) - .attr("y2", point2.y) - .style("stroke", "#333") - .style("stroke-width", "2px"); - - if (major == this.config.min || major == this.config.max) - { - var point = this.valueToPoint(major, 0.63); - - this.body.append("svg:text") - .attr("x", point.x) - .attr("y", point.y) - .attr("dy", fontSize / 3) - .attr("text-anchor", major == this.config.min ? "start" : "end") - .text(major) - .style("font-size", this.config.font_size+"pt") - .style("fill", "#333") - .style("stroke-width", "0px"); - } - } - - var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer"); - - var midValue = (this.config.min + this.config.max) / 2; - - var pointerPath = this.buildPointerPath(midValue); - - var pointerLine = d3.svg.line() - .x(function(d) { return d.x }) - .y(function(d) { return d.y }) - .interpolate("basis"); - - pointerContainer.selectAll("path") - .data([pointerPath]) - .enter() - .append("svg:path") - .attr("d", pointerLine) - .style("fill", "#dc3912") - .style("stroke", "#c63310") - .style("fill-opacity", 0.7) - - pointerContainer.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", 0.12 * this.config.raduis) - .style("fill", "#4684EE") - .style("stroke", "#666") - .style("opacity", 1); - - var fontSize = Math.round(this.config.size / 10); - pointerContainer.selectAll("text") - .data([midValue]) - .enter() - .append("svg:text") - .attr("x", this.config.cx) - .attr("y", this.config.size - this.config.cy / 4 - fontSize) - .attr("dy", fontSize / 2) - .attr("text-anchor", "middle") - .style("font-size", this.config.font_size+"pt") - .style("fill", "#000") - .style("stroke-width", "0px"); - - this.redraw(this.config.min, 0); - } - - this.buildPointerPath = function(value) - { - var delta = this.config.range / 13; - - var head = valueToPoint(value, 0.85); - var head1 = valueToPoint(value - delta, 0.12); - var head2 = valueToPoint(value + delta, 0.12); - - var tailValue = value - (this.config.range * (1/(270/360)) / 2); - var tail = valueToPoint(tailValue, 0.28); - var tail1 = valueToPoint(tailValue - delta, 0.12); - var tail2 = valueToPoint(tailValue + delta, 0.12); - - return [head, head1, tail2, tail, tail1, head2, head]; - - function valueToPoint(value, factor) - { - var point = self.valueToPoint(value, factor); - point.x -= self.config.cx; - point.y -= self.config.cy; - return point; - } - } - - this.drawBand = function(start, end, color) - { - if (start === undefined) return; - if (end === undefined) return; - if (0 >= end - start) return; + this.configure = function(configuration) { + this.config = configuration; - this.body.append("svg:path") - .style("fill", color) - .attr("d", d3.svg.arc() - .startAngle(this.valueToRadians(start)) - .endAngle(this.valueToRadians(end)) - .innerRadius(Math.round(0.65 * this.config.raduis)) - .outerRadius(Math.round(0.85 * this.config.raduis))) - .attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" }); - } + this.config.size = this.config.size * 0.9; + this.config.font_size = this.config.font_size; - this.redraw = function(value, transitionDuration) - { - var pointerContainer = this.body.select(".pointerContainer"); + this.config.raduis = (this.config.size * 0.97) / 2; + this.config.cx = this.config.size / 2; + this.config.cy = this.config.size / 2; - pointerContainer.selectAll("text").text(round_with_decimals(value)); + this.config.min = undefined != configuration.min ? configuration.min : 0; + this.config.max = undefined != configuration.max ? configuration.max : 100; + this.config.range = this.config.max - this.config.min; - var pointer = pointerContainer.selectAll("path"); - pointer.transition() - .duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration) - //.delay(0) - //.ease("linear") - //.attr("transform", function(d) - .attrTween("transform", function() - { - var pointerValue = value; - if (value > self.config.max) pointerValue = self.config.max + 0.02*self.config.range; - else if (value < self.config.min) pointerValue = self.config.min - 0.02*self.config.range; - var targetRotation = (self.valueToDegrees(pointerValue) - 90); - var currentRotation = self._currentRotation || targetRotation; - self._currentRotation = targetRotation; + this.config.majorTicks = configuration.majorTicks || 5; + this.config.minorTicks = configuration.minorTicks || 2; - return function(step) - { - var rotation = currentRotation + (targetRotation-currentRotation)*step; - return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation + ")"; - } - }); - } - - this.valueToDegrees = function(value) - { - // thanks @closealert - //return value / this.config.range * 270 - 45; - return value / this.config.range * 270 - (this.config.min / this.config.range * 270 + 45); - } - - this.valueToRadians = function(value) - { - return this.valueToDegrees(value) * Math.PI / 180; - } - - this.valueToPoint = function(value, factor) - { - return { x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)), - y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value)) }; - } - - // initialization - this.configure(configuration); + this.config.greenColor = configuration.greenColor || "#109618"; + this.config.yellowColor = configuration.yellowColor || "#FF9900"; + this.config.redColor = configuration.redColor || "#DC3912"; + + this.config.transitionDuration = configuration.transitionDuration || 500; + }; + + this.render = function() { + this.body = d3 + .select("#" + this.placeholderName) + .append("svg:svg") + .attr("class", "gauge") + .attr("width", this.config.size) + .attr("height", this.config.size); + + this.body + .append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", this.config.raduis) + .style("fill", "#ccc") + .style("stroke", "#000") + .style("stroke-width", "0.5px"); + + this.body + .append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", 0.9 * this.config.raduis) + .style("fill", "#fff") + .style("stroke", "#e0e0e0") + .style("stroke-width", "2px"); + + for (var index in this.config.greenZones) { + this.drawBand( + this.config.greenZones[index].from, + this.config.greenZones[index].to, + self.config.greenColor + ); + } + + for (var index in this.config.yellowZones) { + this.drawBand( + this.config.yellowZones[index].from, + this.config.yellowZones[index].to, + self.config.yellowColor + ); + } + + for (var index in this.config.redZones) { + this.drawBand( + this.config.redZones[index].from, + this.config.redZones[index].to, + self.config.redColor + ); + } + + if (undefined != this.config.label) { + var fontSize = Math.round(this.config.size / 9); + this.body + .append("svg:text") + .attr("x", this.config.cx) + .attr("y", this.config.cy / 2 + fontSize / 2) + .attr("dy", fontSize / 2) + .attr("text-anchor", "middle") + .attr("class", font) + .text(this.config.label) + .style("font-size", this.config.font_size + "pt") + .style("fill", "#333") + .style("stroke-width", "0px"); + } + + var fontSize = Math.round(this.config.size / 16); + var majorDelta = this.config.range / (this.config.majorTicks - 1); + for ( + var major = this.config.min; + major <= this.config.max; + major += majorDelta + ) { + var minorDelta = majorDelta / this.config.minorTicks; + for ( + var minor = major + minorDelta; + minor < Math.min(major + majorDelta, this.config.max); + minor += minorDelta + ) { + var point1 = this.valueToPoint(minor, 0.75); + var point2 = this.valueToPoint(minor, 0.85); + + this.body + .append("svg:line") + .attr("x1", point1.x) + .attr("y1", point1.y) + .attr("x2", point2.x) + .attr("y2", point2.y) + .style("stroke", "#666") + .style("stroke-width", "1px"); + } + + var point1 = this.valueToPoint(major, 0.7); + var point2 = this.valueToPoint(major, 0.85); + + this.body + .append("svg:line") + .attr("x1", point1.x) + .attr("y1", point1.y) + .attr("x2", point2.x) + .attr("y2", point2.y) + .style("stroke", "#333") + .style("stroke-width", "2px"); + + if (major == this.config.min || major == this.config.max) { + var point = this.valueToPoint(major, 0.63); + + this.body + .append("svg:text") + .attr("x", point.x) + .attr("y", point.y) + .attr("dy", fontSize / 3) + .attr("text-anchor", major == this.config.min ? "start" : "end") + .text(major) + .style("font-size", this.config.font_size + "pt") + .style("fill", "#333") + .style("stroke-width", "0px"); + } + } + + var pointerContainer = this.body + .append("svg:g") + .attr("class", "pointerContainer"); + + var midValue = (this.config.min + this.config.max) / 2; + + var pointerPath = this.buildPointerPath(midValue); + + var pointerLine = d3.svg + .line() + .x(function(d) { + return d.x; + }) + .y(function(d) { + return d.y; + }) + .interpolate("basis"); + + pointerContainer + .selectAll("path") + .data([pointerPath]) + .enter() + .append("svg:path") + .attr("d", pointerLine) + .style("fill", "#dc3912") + .style("stroke", "#c63310") + .style("fill-opacity", 0.7); + + pointerContainer + .append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", 0.12 * this.config.raduis) + .style("fill", "#4684EE") + .style("stroke", "#666") + .style("opacity", 1); + + var fontSize = Math.round(this.config.size / 10); + pointerContainer + .selectAll("text") + .data([midValue]) + .enter() + .append("svg:text") + .attr("x", this.config.cx) + .attr("y", this.config.size - this.config.cy / 4 - fontSize) + .attr("dy", fontSize / 2) + .attr("text-anchor", "middle") + .style("font-size", this.config.font_size + "pt") + .style("fill", "#000") + .style("stroke-width", "0px"); + + this.redraw(this.config.min, 0); + }; + + this.buildPointerPath = function(value) { + var delta = this.config.range / 13; + + var head = valueToPoint(value, 0.85); + var head1 = valueToPoint(value - delta, 0.12); + var head2 = valueToPoint(value + delta, 0.12); + + var tailValue = value - (this.config.range * (1 / (270 / 360))) / 2; + var tail = valueToPoint(tailValue, 0.28); + var tail1 = valueToPoint(tailValue - delta, 0.12); + var tail2 = valueToPoint(tailValue + delta, 0.12); + + return [head, head1, tail2, tail, tail1, head2, head]; + + function valueToPoint(value, factor) { + var point = self.valueToPoint(value, factor); + point.x -= self.config.cx; + point.y -= self.config.cy; + return point; + } + }; + + this.drawBand = function(start, end, color) { + if (start === undefined) return; + if (end === undefined) return; + if (0 >= end - start) return; + + this.body + .append("svg:path") + .style("fill", color) + .attr( + "d", + d3.svg + .arc() + .startAngle(this.valueToRadians(start)) + .endAngle(this.valueToRadians(end)) + .innerRadius(Math.round(0.65 * this.config.raduis)) + .outerRadius(Math.round(0.85 * this.config.raduis)) + ) + .attr("transform", function() { + return ( + "translate(" + + self.config.cx + + ", " + + self.config.cy + + ") rotate(270)" + ); + }); + }; + + this.redraw = function(value, transitionDuration) { + var pointerContainer = this.body.select(".pointerContainer"); + + pointerContainer.selectAll("text").text(round_with_decimals(value)); + + var pointer = pointerContainer.selectAll("path"); + pointer + .transition() + .duration( + undefined != transitionDuration + ? transitionDuration + : this.config.transitionDuration + ) + //.delay(0) + //.ease("linear") + //.attr("transform", function(d) + .attrTween("transform", function() { + var pointerValue = value; + if (value > self.config.max) + pointerValue = self.config.max + 0.02 * self.config.range; + else if (value < self.config.min) + pointerValue = self.config.min - 0.02 * self.config.range; + var targetRotation = self.valueToDegrees(pointerValue) - 90; + var currentRotation = self._currentRotation || targetRotation; + self._currentRotation = targetRotation; + + return function(step) { + var rotation = + currentRotation + (targetRotation - currentRotation) * step; + return ( + "translate(" + + self.config.cx + + ", " + + self.config.cy + + ") rotate(" + + rotation + + ")" + ); + }; + }); + }; + + this.valueToDegrees = function(value) { + // thanks @closealert + //return value / this.config.range * 270 - 45; + return ( + (value / this.config.range) * 270 - + ((this.config.min / this.config.range) * 270 + 45) + ); + }; + + this.valueToRadians = function(value) { + return (this.valueToDegrees(value) * Math.PI) / 180; + }; + + this.valueToPoint = function(value, factor) { + return { + x: + this.config.cx - + this.config.raduis * factor * Math.cos(this.valueToRadians(value)), + y: + this.config.cy - + this.config.raduis * factor * Math.sin(this.valueToRadians(value)) + }; + }; + + // initialization + this.configure(configuration); } -function print_phases_donut (recipient, phases) { - var svg = d3.select(recipient) - .append("svg") - .attr("width", 800) - .attr("height", 500) - .append("g"); +function print_phases_donut(recipient, phases) { + var svg = d3 + .select(recipient) + .append("svg") + .attr("width", 800) + .attr("height", 500) + .append("g"); - svg.append("g") - .attr("class", "slices"); - svg.append("g") - .attr("class", "labels"); - svg.append("g") - .attr("class", "lines"); + svg.append("g").attr("class", "slices"); + svg.append("g").attr("class", "labels"); + svg.append("g").attr("class", "lines"); - var width = 550, - height = 300, - radius = Math.min(width, height) / 2; + var width = 550, + height = 300, + radius = Math.min(width, height) / 2; - var pie = d3.layout.pie() - .sort(null) - .value(function(d) { - return parseFloat(d.label2); - }); + var pie = d3.layout + .pie() + .sort(null) + .value(function(d) { + return parseFloat(d.label2); + }); - var arc = d3.svg.arc() - .outerRadius(radius * 0.8) - .innerRadius(radius * 0.4); + var arc = d3.svg + .arc() + .outerRadius(radius * 0.8) + .innerRadius(radius * 0.4); - var outerArc = d3.svg.arc() - .innerRadius(radius * 0.9) - .outerRadius(radius * 0.9); + var outerArc = d3.svg + .arc() + .innerRadius(radius * 0.9) + .outerRadius(radius * 0.9); - width = 800; - height = 500; - svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + width = 800; + height = 500; + svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); - var key = function(d){ return d.data.label; }; + var key = function(d) { + return d.data.label; + }; - function phasesData (){ - return phases.map(function(phase){ - return { label: phase_name(phase, 1), label2: phase_name(phase, 2), value: phase.status } - }); - } + function phasesData() { + return phases.map(function(phase) { + return { + label: phase_name(phase, 1), + label2: phase_name(phase, 2), + value: phase.status + }; + }); + } - function phase_name (phase, index) { - if (index == 1) { - return phase.phase_name; - } - else { - return phase.phase_time; - } - } + function phase_name(phase, index) { + if (index == 1) { + return phase.phase_name; + } else { + return phase.phase_time; + } + } - print_phases(phasesData()); + print_phases(phasesData()); - function print_phases(data) { - /* ------- PIE SLICES -------*/ - var slice = svg.select(".slices").selectAll("path.slice") - .data(pie(data), key); + function print_phases(data) { + /* ------- PIE SLICES -------*/ + var slice = svg + .select(".slices") + .selectAll("path.slice") + .data(pie(data), key); - slice.enter() - .insert("path") - .style("fill", function(d) { - if (d.data.value == 0) { - return "#80BA27"; - } - else { - return "#FC4444"; - } - }) - .attr("class", "slice"); + slice + .enter() + .insert("path") + .style("fill", function(d) { + if (d.data.value == 0) { + return "#80BA27"; + } else { + return "#FC4444"; + } + }) + .attr("class", "slice"); - slice - .transition().duration(0) - .attrTween("d", function(d) { - this._current = this._current || d; - var interpolate = d3.interpolate(this._current, d); - this._current = interpolate(0); - return function(t) { - return arc(interpolate(t)); - }; - }); + slice + .transition() + .duration(0) + .attrTween("d", function(d) { + this._current = this._current || d; + var interpolate = d3.interpolate(this._current, d); + this._current = interpolate(0); + return function(t) { + return arc(interpolate(t)); + }; + }); - slice.exit() - .remove(); + slice.exit().remove(); - /* ------- TEXT LABELS -------*/ - var text = svg.select(".labels").selectAll("text") - .data(pie(data), key); + /* ------- TEXT LABELS -------*/ + var text = svg + .select(".labels") + .selectAll("text") + .data(pie(data), key); - text.enter() - .append("text") - .append("tspan") - .attr("dy", ".1em") - .text(function(d) { - return d.data.label; - }) - .style("font-family", "Verdana") - .style("font-size", "15px") - .append("tspan") - .attr("dy", "1.2em") - .attr("dx", "-2.8em") - .text(function(d) { - return d.data.label2 + "ms"; - }) - .style("font-family", "Verdana") - .style("font-size", "15px"); - - function midAngle(d){ - return d.startAngle + (d.endAngle - d.startAngle)/2; - } + text + .enter() + .append("text") + .append("tspan") + .attr("dy", ".1em") + .text(function(d) { + return d.data.label; + }) + .style("font-family", "Verdana") + .style("font-size", "15px") + .append("tspan") + .attr("dy", "1.2em") + .attr("dx", "-2.8em") + .text(function(d) { + return d.data.label2 + "ms"; + }) + .style("font-family", "Verdana") + .style("font-size", "15px"); - var ex = 1; - var sum = 0; - text.transition().duration(0) - .attrTween("transform", function(d) { - this._current = this._current || d; - var interpolate = d3.interpolate(this._current, d); - this._current = interpolate(0); - return function(t) { - var d2 = interpolate(t); + function midAngle(d) { + return d.startAngle + (d.endAngle - d.startAngle) / 2; + } - //fix for labels of a very small portion increase the - //height of the label so that they do not overlap - if( ( d2.endAngle - d2.startAngle ) < 0.1){ - var pos = outerArc.centroid(d2); - if (ex%2==0){ - pos[0] = 150; - } - else{ - pos[0] = -150; - sum++; - } - pos[1] = pos[1] - (35*sum); - ex++; - } - else{ - var pos = outerArc.centroid(d2); - pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1); - } + var ex = 1; + var sum = 0; + text + .transition() + .duration(0) + .attrTween("transform", function(d) { + this._current = this._current || d; + var interpolate = d3.interpolate(this._current, d); + this._current = interpolate(0); + return function(t) { + var d2 = interpolate(t); - return "translate("+ pos +")"; - }; - }) - .styleTween("text-anchor", function(d){ - this._current = this._current || d; - var interpolate = d3.interpolate(this._current, d); - this._current = interpolate(0); - return function(t) { - var d2 = interpolate(t); + //fix for labels of a very small portion increase the + //height of the label so that they do not overlap + if (d2.endAngle - d2.startAngle < 0.1) { + var pos = outerArc.centroid(d2); + if (ex % 2 == 0) { + pos[0] = 150; + } else { + pos[0] = -150; + sum++; + } + pos[1] = pos[1] - 35 * sum; + ex++; + } else { + var pos = outerArc.centroid(d2); + pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1); + } - //fix for labels of a very small portion increase the - //height of the label so that they do not overlap - if( ( d2.endAngle - d2.startAngle ) < 0.1){ - if (ex%2==0){ - return "start"; - } - else{ - return "end"; - } - } - return midAngle(d2) < Math.PI ? "start":"end"; - }; - }); + return "translate(" + pos + ")"; + }; + }) + .styleTween("text-anchor", function(d) { + this._current = this._current || d; + var interpolate = d3.interpolate(this._current, d); + this._current = interpolate(0); + return function(t) { + var d2 = interpolate(t); - text.exit() - .remove(); + //fix for labels of a very small portion increase the + //height of the label so that they do not overlap + if (d2.endAngle - d2.startAngle < 0.1) { + if (ex % 2 == 0) { + return "start"; + } else { + return "end"; + } + } + return midAngle(d2) < Math.PI ? "start" : "end"; + }; + }); - /* ------- SLICE TO TEXT POLYLINES -------*/ - var polyline = svg.select(".lines").selectAll("polyline") - .data(pie(data), key); + text.exit().remove(); - polyline.enter() - .append("polyline"); + /* ------- SLICE TO TEXT POLYLINES -------*/ + var polyline = svg + .select(".lines") + .selectAll("polyline") + .data(pie(data), key); - var ex2 = 1; - var sum2 = 0; - polyline.transition().duration(0) - .attrTween("points", function(d){ - this._current = this._current || d; - var interpolate = d3.interpolate(this._current, d); - this._current = interpolate(0); - return function(t) { - var d2 = interpolate(t); + polyline.enter().append("polyline"); - //fix for labels of a very small portion increase the - //height of the label so that they do not overlap - if( ( d2.endAngle - d2.startAngle ) < 0.1){ - var pos = outerArc.centroid(d2); - if (ex2%2==0){ - pos[0] = 150 * 0.95; - } - else{ - pos[0] = -150 * 0.95; - sum2++; - } - pos[1] = pos[1] - (30*sum2); - ex2++; - } - else{ - var pos = outerArc.centroid(d2); - pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1); - } - return [arc.centroid(d2), outerArc.centroid(d2), pos]; - }; - }) - .style("stroke", "black") - .style("opacity", ".3") - .style("stroke-width", "2px") - .style("fill", "none"); + var ex2 = 1; + var sum2 = 0; + polyline + .transition() + .duration(0) + .attrTween("points", function(d) { + this._current = this._current || d; + var interpolate = d3.interpolate(this._current, d); + this._current = interpolate(0); + return function(t) { + var d2 = interpolate(t); - polyline.exit() - .remove(); - } + //fix for labels of a very small portion increase the + //height of the label so that they do not overlap + if (d2.endAngle - d2.startAngle < 0.1) { + var pos = outerArc.centroid(d2); + if (ex2 % 2 == 0) { + pos[0] = 150 * 0.95; + } else { + pos[0] = -150 * 0.95; + sum2++; + } + pos[1] = pos[1] - 30 * sum2; + ex2++; + } else { + var pos = outerArc.centroid(d2); + pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1); + } + return [arc.centroid(d2), outerArc.centroid(d2), pos]; + }; + }) + .style("stroke", "black") + .style("opacity", ".3") + .style("stroke-width", "2px") + .style("fill", "none"); + + polyline.exit().remove(); + } } -function progress_bar_d3 (recipient, percentile, width, height, color, unit, label, label_color) { - var startPercent = 0; - var endPercent = parseInt(percentile) / 100; - var count = Math.abs((endPercent - startPercent) / 0.01); - var step = endPercent < startPercent ? -0.01 : 0.01; +function progress_bar_d3( + recipient, + percentile, + width, + height, + color, + unit, + label, + label_color +) { + var startPercent = 0; + var endPercent = parseInt(percentile) / 100; + var count = Math.abs((endPercent - startPercent) / 0.01); + var step = endPercent < startPercent ? -0.01 : 0.01; - var circle = d3.select(recipient) - .append("svg") - .attr("width", width) - .attr("height", height); + var circle = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height); - var progress_back = circle.append('rect') - .attr('fill', '#000000') - .attr('fill-opacity', 0.5) - .attr('height', 20) - .attr('width', width) - .attr('rx', 10) - .attr('ry', 10) - .attr('x', 0); + var progress_back = circle + .append("rect") + .attr("fill", "#000000") + .attr("fill-opacity", 0.5) + .attr("height", 20) + .attr("width", width) + .attr("rx", 10) + .attr("ry", 10) + .attr("x", 0); - var progress_front = circle.append('rect') - .attr('fill', color) - .attr('fill-opacity', 1) - .attr('height', 20) - .attr('width', 0) - .attr('rx', 10) - .attr('ry', 10) - .attr('x', 0); + var progress_front = circle + .append("rect") + .attr("fill", color) + .attr("fill-opacity", 1) + .attr("height", 20) + .attr("width", 0) + .attr("rx", 10) + .attr("ry", 10) + .attr("x", 0); - var labelText = circle.append("text") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", 20) - .html(label) - .attr('dy', '15') - .attr('text-anchor', 'middle'); + var labelText = circle + .append("text") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", 20) + .html(label) + .attr("dy", "15") + .attr("text-anchor", "middle"); - var numberText = circle.append("text") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', '#FFFFFF') - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", 14) - .attr('text-anchor', 'middle') - .attr('dy', '-10'); + var numberText = circle + .append("text") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", "#FFFFFF") + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", 14) + .attr("text-anchor", "middle") + .attr("dy", "-10"); - function updateProgress(bar_progress) { - var percent_value = Number(bar_progress * 100); - numberText.text(percent_value.toFixed() + " " + unit); - progress_front.attr('width', (width * bar_progress)); - } + function updateProgress(bar_progress) { + var percent_value = Number(bar_progress * 100); + numberText.text(percent_value.toFixed() + " " + unit); + progress_front.attr("width", width * bar_progress); + } - var bar_progress = startPercent; + var bar_progress = startPercent; - (function loops() { - updateProgress(bar_progress); + (function loops() { + updateProgress(bar_progress); - if (count > 0) { - count--; - bar_progress += step; - setTimeout(loops, 30); - } - })(); + if (count > 0) { + count--; + bar_progress += step; + setTimeout(loops, 30); + } + })(); } -function progress_bubble_d3 (recipient, percentile, width, height, color, unit, label, label_color) { - var startPercent = 0; - var endPercent = parseInt(percentile) / 100; - var count = Math.abs((endPercent - startPercent) / 0.01); - var step = endPercent < startPercent ? -0.01 : 0.01; +function progress_bubble_d3( + recipient, + percentile, + width, + height, + color, + unit, + label, + label_color +) { + var startPercent = 0; + var endPercent = parseInt(percentile) / 100; + var count = Math.abs((endPercent - startPercent) / 0.01); + var step = endPercent < startPercent ? -0.01 : 0.01; - var numberSize = 0; - var textSize = 0; - var unitSize = 0; - var yPosText = 0; - var yPosNumber = 0; - if (width >= 500) { - numberSize = 100; - textSize = 50; - unitSize = 50; - yPosNumber = '15'; - yPosText = '-100'; - } - else if (width >= 400) { - numberSize = 80; - textSize = 40; - unitSize = 40; - yPosNumber = '15'; - yPosText = '-80'; - } - else if (width >= 300) { - numberSize = 60; - textSize = 30; - unitSize = 30; - yPosNumber = '15'; - yPosText = '-45'; - } - else if (width >= 200) { - numberSize = 40; - textSize = 20; - unitSize = 20; - yPosNumber = '50'; - yPosText = '-30'; - } - else if (width >= 100) { - numberSize = 20; - textSize = 10; - unitSize = 10; - yPosNumber = '5'; - yPosText = '-20'; - } - else { - numberSize = 10; - textSize = 8; - unitSize = 8; - yPosNumber = '5'; - yPosText = '-10'; - } + var numberSize = 0; + var textSize = 0; + var unitSize = 0; + var yPosText = 0; + var yPosNumber = 0; + if (width >= 500) { + numberSize = 100; + textSize = 50; + unitSize = 50; + yPosNumber = "15"; + yPosText = "-100"; + } else if (width >= 400) { + numberSize = 80; + textSize = 40; + unitSize = 40; + yPosNumber = "15"; + yPosText = "-80"; + } else if (width >= 300) { + numberSize = 60; + textSize = 30; + unitSize = 30; + yPosNumber = "15"; + yPosText = "-45"; + } else if (width >= 200) { + numberSize = 40; + textSize = 20; + unitSize = 20; + yPosNumber = "50"; + yPosText = "-30"; + } else if (width >= 100) { + numberSize = 20; + textSize = 10; + unitSize = 10; + yPosNumber = "5"; + yPosText = "-20"; + } else { + numberSize = 10; + textSize = 8; + unitSize = 8; + yPosNumber = "5"; + yPosText = "-10"; + } - var circle = d3.select(recipient) - .append("svg") - .attr("width", width) - .attr("height", height); + var circle = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height); - var progress_back = circle.append('circle') - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', '#000000') - .attr('fill-opacity', 0) - .attr('r', width/2); + var progress_back = circle + .append("circle") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", "#000000") + .attr("fill-opacity", 0) + .attr("r", width / 2); - var progress_front = circle.append('circle') - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', color) - .attr('fill-opacity', 1) - .attr('r', 0); + var progress_front = circle + .append("circle") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", color) + .attr("fill-opacity", 1) + .attr("r", 0); - var labelText = circle.append("text") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", textSize) - .html(label) - .attr('dy', -(width/3)) - .attr('text-anchor', 'middle'); + var labelText = circle + .append("text") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", textSize) + .html(label) + .attr("dy", -(width / 3)) + .attr("text-anchor", "middle"); - var numberText = circle.append("text") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", numberSize) - .attr('text-anchor', 'middle') - .attr('dy', width/3); + var numberText = circle + .append("text") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", numberSize) + .attr("text-anchor", "middle") + .attr("dy", width / 3); - function updateProgress(bar_progress) { - var percent_value = Number(bar_progress * 100); - numberText.text(percent_value.toFixed() + " " + unit); - progress_front.attr('r', ((width/2) * bar_progress)); - } + function updateProgress(bar_progress) { + var percent_value = Number(bar_progress * 100); + numberText.text(percent_value.toFixed() + " " + unit); + progress_front.attr("r", (width / 2) * bar_progress); + } - var bar_progress = startPercent; + var bar_progress = startPercent; - (function loops() { - updateProgress(bar_progress); + (function loops() { + updateProgress(bar_progress); - if (count > 0) { - count--; - bar_progress += step; - setTimeout(loops, 30); - } - })(); + if (count > 0) { + count--; + bar_progress += step; + setTimeout(loops, 30); + } + })(); } -function print_circular_progress_bar (recipient, percentile, width, height, color, unit, label, label_color) { - var twoPi = Math.PI * 2; - var radius = (width / 2); - var border = 20; - var startPercent = 0; - var endPercent = parseInt(percentile) / 100; - var count = Math.abs((endPercent - startPercent) / 0.01); - var step = endPercent < startPercent ? -0.01 : 0.01; +function print_circular_progress_bar( + recipient, + percentile, + width, + height, + color, + unit, + label, + label_color +) { + var twoPi = Math.PI * 2; + var radius = width / 2; + var border = 20; + var startPercent = 0; + var endPercent = parseInt(percentile) / 100; + var count = Math.abs((endPercent - startPercent) / 0.01); + var step = endPercent < startPercent ? -0.01 : 0.01; - var numberSize = 0; - var textSize = 0; - var unitSize = 0; - var yPosText = 0; - var yPosUnit = 0; - var yPosNumber = 0; - if (width >= 500) { - numberSize = 100; - textSize = 50; - unitSize = 50; - yPosNumber = '15'; - yPosText = '-100'; - yPosUnit = '100'; - } - else if (width >= 400) { - numberSize = 80; - textSize = 40; - unitSize = 40; - yPosNumber = '15'; - yPosText = '-80'; - yPosUnit = '80'; - } - else if (width >= 300) { - numberSize = 60; - textSize = 30; - unitSize = 30; - yPosNumber = '15'; - yPosText = '-45'; - yPosUnit = '60'; - } - else if (width >= 200) { - numberSize = 40; - textSize = 20; - unitSize = 20; - yPosNumber = '10'; - yPosText = '-30'; - yPosUnit = '40'; - } - else if (width >= 100) { - numberSize = 20; - textSize = 10; - unitSize = 10; - yPosNumber = '5'; - yPosText = '-15'; - yPosUnit = '20'; - } - else { - numberSize = 8; - textSize = 4; - unitSize = 4; - yPosNumber = '2'; - yPosText = '-5'; - yPosUnit = '5'; - } + var numberSize = 0; + var textSize = 0; + var unitSize = 0; + var yPosText = 0; + var yPosUnit = 0; + var yPosNumber = 0; + if (width >= 500) { + numberSize = 100; + textSize = 50; + unitSize = 50; + yPosNumber = "15"; + yPosText = "-100"; + yPosUnit = "100"; + } else if (width >= 400) { + numberSize = 80; + textSize = 40; + unitSize = 40; + yPosNumber = "15"; + yPosText = "-80"; + yPosUnit = "80"; + } else if (width >= 300) { + numberSize = 60; + textSize = 30; + unitSize = 30; + yPosNumber = "15"; + yPosText = "-45"; + yPosUnit = "60"; + } else if (width >= 200) { + numberSize = 40; + textSize = 20; + unitSize = 20; + yPosNumber = "10"; + yPosText = "-30"; + yPosUnit = "40"; + } else if (width >= 100) { + numberSize = 20; + textSize = 10; + unitSize = 10; + yPosNumber = "5"; + yPosText = "-15"; + yPosUnit = "20"; + } else { + numberSize = 8; + textSize = 4; + unitSize = 4; + yPosNumber = "2"; + yPosText = "-5"; + yPosUnit = "5"; + } - var arc = d3.svg.arc() - .startAngle(0) - .innerRadius(radius) - .outerRadius(radius - border); + var arc = d3.svg + .arc() + .startAngle(0) + .innerRadius(radius) + .outerRadius(radius - border); - var circle = d3.select(recipient) - .append("svg") - .attr("width", width) - .attr("height", height) - .append("g") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")"); + var circle = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")"); - var meter = circle.append("g") - .attr('class', 'progress-meter'); + var meter = circle.append("g").attr("class", "progress-meter"); - meter.append("path") - .attr('fill', '#000000') - .attr('fill-opacity', 0.5) - .attr('d', arc.endAngle(twoPi)); + meter + .append("path") + .attr("fill", "#000000") + .attr("fill-opacity", 0.5) + .attr("d", arc.endAngle(twoPi)); - var foreground = circle.append("path") - .attr('fill', color) - .attr('fill-opacity', 1) - .attr('stroke', color) - .attr('stroke-opacity', 1); - - var front = circle.append("path") - .attr('fill', color) - .attr('fill-opacity', 1); + var foreground = circle + .append("path") + .attr("fill", color) + .attr("fill-opacity", 1) + .attr("stroke", color) + .attr("stroke-opacity", 1); - var labelText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", textSize) - .html(label) - .attr('text-anchor', 'middle') - .attr('dy', yPosText); + var front = circle + .append("path") + .attr("fill", color) + .attr("fill-opacity", 1); - var numberText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", numberSize) - .attr('text-anchor', 'middle') - .attr('dy', yPosNumber); + var labelText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", textSize) + .html(label) + .attr("text-anchor", "middle") + .attr("dy", yPosText); - var percentText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", unitSize) - .text(unit) - .attr('text-anchor', 'middle') - .attr('dy', yPosUnit); + var numberText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", numberSize) + .attr("text-anchor", "middle") + .attr("dy", yPosNumber); - function updateProgress(progress) { - foreground.attr('d', arc.endAngle(twoPi * progress)); - front.attr('d', arc.endAngle(twoPi * progress)); - var percent_value = Number(progress * 100); - numberText.text(percent_value.toFixed()); - } + var percentText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", unitSize) + .text(unit) + .attr("text-anchor", "middle") + .attr("dy", yPosUnit); - var progress = startPercent; + function updateProgress(progress) { + foreground.attr("d", arc.endAngle(twoPi * progress)); + front.attr("d", arc.endAngle(twoPi * progress)); + var percent_value = Number(progress * 100); + numberText.text(percent_value.toFixed()); + } - (function loops() { - updateProgress(progress); + var progress = startPercent; - if (count > 0) { - count--; - progress += step; - setTimeout(loops, 30); - } - })(); + (function loops() { + updateProgress(progress); + + if (count > 0) { + count--; + progress += step; + setTimeout(loops, 30); + } + })(); } -function print_interior_circular_progress_bar (recipient, percentile, width, height, color, unit, label, label_color) { - var twoPi = Math.PI * 2; - var radius = (width / 2) - 20; - var radius2 = (width / 2); - var border = 20; - var startPercent = 0; - var endPercent = parseInt(percentile) / 100; - var count = Math.abs((endPercent - startPercent) / 0.01); - var step = endPercent < startPercent ? -0.01 : 0.01; +function print_interior_circular_progress_bar( + recipient, + percentile, + width, + height, + color, + unit, + label, + label_color +) { + var twoPi = Math.PI * 2; + var radius = width / 2 - 20; + var radius2 = width / 2; + var border = 20; + var startPercent = 0; + var endPercent = parseInt(percentile) / 100; + var count = Math.abs((endPercent - startPercent) / 0.01); + var step = endPercent < startPercent ? -0.01 : 0.01; - var numberSize = 0; - var textSize = 0; - var unitSize = 0; - var yPosText = 0; - var yPosUnit = 0; - var yPosNumber = 0; - if (width >= 500) { - numberSize = 100; - textSize = 50; - unitSize = 50; - yPosNumber = '15'; - yPosText = '-100'; - yPosUnit = '100'; - } - else if (width >= 400) { - numberSize = 80; - textSize = 40; - unitSize = 40; - yPosNumber = '15'; - yPosText = '-80'; - yPosUnit = '80'; - } - else if (width >= 300) { - numberSize = 60; - textSize = 30; - unitSize = 30; - yPosNumber = '15'; - yPosText = '-45'; - yPosUnit = '60'; - } - else if (width >= 200) { - numberSize = 40; - textSize = 20; - unitSize = 20; - yPosNumber = '10'; - yPosText = '-30'; - yPosUnit = '40'; - } - else if (width >= 100) { - numberSize = 20; - textSize = 10; - unitSize = 10; - yPosNumber = '5'; - yPosText = '-15'; - yPosUnit = '20'; - } - else { - numberSize = 8; - textSize = 4; - unitSize = 4; - yPosNumber = '2'; - yPosText = '-5'; - yPosUnit = '5'; - } + var numberSize = 0; + var textSize = 0; + var unitSize = 0; + var yPosText = 0; + var yPosUnit = 0; + var yPosNumber = 0; + if (width >= 500) { + numberSize = 100; + textSize = 50; + unitSize = 50; + yPosNumber = "15"; + yPosText = "-100"; + yPosUnit = "100"; + } else if (width >= 400) { + numberSize = 80; + textSize = 40; + unitSize = 40; + yPosNumber = "15"; + yPosText = "-80"; + yPosUnit = "80"; + } else if (width >= 300) { + numberSize = 60; + textSize = 30; + unitSize = 30; + yPosNumber = "15"; + yPosText = "-45"; + yPosUnit = "60"; + } else if (width >= 200) { + numberSize = 40; + textSize = 20; + unitSize = 20; + yPosNumber = "10"; + yPosText = "-30"; + yPosUnit = "40"; + } else if (width >= 100) { + numberSize = 20; + textSize = 10; + unitSize = 10; + yPosNumber = "5"; + yPosText = "-15"; + yPosUnit = "20"; + } else { + numberSize = 8; + textSize = 4; + unitSize = 4; + yPosNumber = "2"; + yPosText = "-5"; + yPosUnit = "5"; + } - var arc = d3.svg.arc() - .startAngle(0) - .innerRadius(radius) - .outerRadius(radius - border); + var arc = d3.svg + .arc() + .startAngle(0) + .innerRadius(radius) + .outerRadius(radius - border); - var arc2 = d3.svg.arc() - .startAngle(0) - .innerRadius(radius2) - .outerRadius(radius2 - border); + var arc2 = d3.svg + .arc() + .startAngle(0) + .innerRadius(radius2) + .outerRadius(radius2 - border); - var circle = d3.select(recipient) - .append("svg") - .attr("width", width) - .attr("height", height) - .append("g") - .attr("transform", "translate(" + (width/2) + ", " + (height/2) + ")"); + var circle = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + ", " + height / 2 + ")"); - var meter = circle.append("g") - .attr('class', 'progress-meter'); + var meter = circle.append("g").attr("class", "progress-meter"); - meter.append("path") - .attr('fill', '#000000') - .attr('fill-opacity', 0.5) - .attr('d', arc.endAngle(twoPi)); + meter + .append("path") + .attr("fill", "#000000") + .attr("fill-opacity", 0.5) + .attr("d", arc.endAngle(twoPi)); - var meter = circle.append("g") - .attr('class', 'progress-meter'); + var meter = circle.append("g").attr("class", "progress-meter"); - meter.append("path") - .attr('fill', color) - .attr('fill-opacity', 1) - .attr('d', arc2.endAngle(twoPi)); + meter + .append("path") + .attr("fill", color) + .attr("fill-opacity", 1) + .attr("d", arc2.endAngle(twoPi)); - var foreground = circle.append("path") - .attr('fill', color) - .attr('fill-opacity', 1) - .attr('stroke', color) - .attr('stroke-opacity', 1); - - var front = circle.append("path") - .attr('fill', color) - .attr('fill-opacity', 1); + var foreground = circle + .append("path") + .attr("fill", color) + .attr("fill-opacity", 1) + .attr("stroke", color) + .attr("stroke-opacity", 1); - var labelText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", textSize) - .html(label) - .attr('text-anchor', 'middle') - .attr('dy', yPosText); + var front = circle + .append("path") + .attr("fill", color) + .attr("fill-opacity", 1); - var numberText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", numberSize) - .attr('text-anchor', 'middle') - .attr('dy', yPosNumber); + var labelText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", textSize) + .html(label) + .attr("text-anchor", "middle") + .attr("dy", yPosText); - var percentText = circle.append("text") - .attr('fill', label_color) - .style("font-family", "arial") - .style("font-weight", "bold") - .style("font-size", unitSize) - .text(unit) - .attr('text-anchor', 'middle') - .attr('dy', yPosUnit); + var numberText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", numberSize) + .attr("text-anchor", "middle") + .attr("dy", yPosNumber); - function updateProgress(progress) { - foreground.attr('d', arc.endAngle(twoPi * progress)); - front.attr('d', arc.endAngle(twoPi * progress)); - var percent_value = Number(progress * 100); - numberText.text(percent_value.toFixed()); - } + var percentText = circle + .append("text") + .attr("fill", label_color) + .style("font-family", "arial") + .style("font-weight", "bold") + .style("font-size", unitSize) + .text(unit) + .attr("text-anchor", "middle") + .attr("dy", yPosUnit); - var progress = startPercent; + function updateProgress(progress) { + foreground.attr("d", arc.endAngle(twoPi * progress)); + front.attr("d", arc.endAngle(twoPi * progress)); + var percent_value = Number(progress * 100); + numberText.text(percent_value.toFixed()); + } - (function loops() { - updateProgress(progress); + var progress = startPercent; - if (count > 0) { - count--; - progress += step; - setTimeout(loops, 30); - } - })(); + (function loops() { + updateProgress(progress); + + if (count > 0) { + count--; + progress += step; + setTimeout(loops, 30); + } + })(); } -function print_donut_graph (recipient, width, height, module_data, resume_color) { - var svg = d3.select(recipient) - .append("svg") - .attr("width", width) - .attr("height", height) - .append("g"); +function print_donut_graph( + recipient, + width, + height, + module_data, + resume_color +) { + var svg = d3 + .select(recipient) + .append("svg") + .attr("width", width) + .attr("height", height) + .append("g"); - svg.append("g") - .attr("class", "slices"); + svg.append("g").attr("class", "slices"); - var radius = 120; - var increment_y = 60; - var increment_y_padding = 25; - var decrement_x_padding = 150; - if (width >= 500) { - radius = 180; - increment_y = 60; - increment_y_padding = 20; - decrement_x_padding = 40; - } - else if (width >= 400) { - radius = 140; - increment_y = 40; - increment_y_padding = 20; - decrement_x_padding = 40; - } - else if (width >= 300) { - radius = 100; - increment_y = 40; - increment_y_padding = 15; - decrement_x_padding = 40; - } - else if (width >= 200) { - radius = 50; - increment_y = 40; - increment_y_padding = 15; - decrement_x_padding = 25; - } - else if (width >= 100) { - radius = 20; - increment_y = 20; - increment_y_padding = 8; - decrement_x_padding = 25; - } - else { - radius = 10; - increment_y = 10; - increment_y_padding = 3; - decrement_x_padding = 5; - } + var radius = 120; + var increment_y = 60; + var increment_y_padding = 25; + var decrement_x_padding = 150; + if (width >= 500) { + radius = 180; + increment_y = 60; + increment_y_padding = 20; + decrement_x_padding = 40; + } else if (width >= 400) { + radius = 140; + increment_y = 40; + increment_y_padding = 20; + decrement_x_padding = 40; + } else if (width >= 300) { + radius = 100; + increment_y = 40; + increment_y_padding = 15; + decrement_x_padding = 40; + } else if (width >= 200) { + radius = 50; + increment_y = 40; + increment_y_padding = 15; + decrement_x_padding = 25; + } else if (width >= 100) { + radius = 20; + increment_y = 20; + increment_y_padding = 8; + decrement_x_padding = 25; + } else { + radius = 10; + increment_y = 10; + increment_y_padding = 3; + decrement_x_padding = 5; + } - var arc = d3.svg.arc() - .outerRadius(radius * 0.8) - .innerRadius(radius * 0.4); + var arc = d3.svg + .arc() + .outerRadius(radius * 0.8) + .innerRadius(radius * 0.4); - var key = function(d){ return d.data.label; }; + var key = function(d) { + return d.data.label; + }; - var pie = d3.layout.pie() - .sort(null) - .value(function(d) { - return parseFloat(d.percent); - }); + var pie = d3.layout + .pie() + .sort(null) + .value(function(d) { + return parseFloat(d.percent); + }); - jQuery.each(module_data, function (key, m_d) { - svg.append("g") - .append("rect") - .attr("transform", "translate(" + (((width / 2) - (radius + decrement_x_padding))) + "," + (((height / 2) - radius) - increment_y) + ")") - .attr('fill', m_d.color) - .attr('x', -20) - .attr('y', -10) - .attr('width', 20) - .attr('height', 10); + jQuery.each(module_data, function(key, m_d) { + svg + .append("g") + .append("rect") + .attr( + "transform", + "translate(" + + (width / 2 - (radius + decrement_x_padding)) + + "," + + (height / 2 - radius - increment_y) + + ")" + ) + .attr("fill", m_d.color) + .attr("x", -20) + .attr("y", -10) + .attr("width", 20) + .attr("height", 10); - svg.append("g") - .append("text") - .attr('fill', resume_color) - .attr("transform", "translate(" + (((width / 2) - (radius + decrement_x_padding)) + 10) + "," + (((height / 2) - radius) - increment_y) + ")") - .text(m_d.tag_name) - .style("font-family", "smallfontFont") - .style("font-size", "7pt"); - - increment_y -= increment_y_padding; - }); + svg + .append("g") + .append("text") + .attr("fill", resume_color) + .attr( + "transform", + "translate(" + + (width / 2 - (radius + decrement_x_padding) + 10) + + "," + + (height / 2 - radius - increment_y) + + ")" + ) + .text(m_d.tag_name) + .style("font-family", "smallfontFont") + .style("font-size", "7pt"); - function donutData (){ - return module_data.map(function(m_data){ - return { label: m_data.tag_name, percent: m_data.percent, color : m_data.color} - }); - } + increment_y -= increment_y_padding; + }); - print_phases(donutData()); + function donutData() { + return module_data.map(function(m_data) { + return { + label: m_data.tag_name, + percent: m_data.percent, + color: m_data.color + }; + }); + } - function print_phases(data) { - var slice = svg.select(".slices").selectAll("path.slice") - .data(pie(data), key); + print_phases(donutData()); - slice.enter() - .insert("path") - .style("fill", function(d) { - return d.data.color; - }) - .attr("class", "slice") - .attr("transform", "translate(" + width / 2 + "," + (height - radius) + ")"); + function print_phases(data) { + var slice = svg + .select(".slices") + .selectAll("path.slice") + .data(pie(data), key); - slice.transition() - .duration(0) - .attrTween("d", function(d) { - this._current = this._current || d; - var interpolate = d3.interpolate(this._current, d); - this._current = interpolate(0); - return function(t) { - return arc(interpolate(t)); - }; - }); - - slice.exit().remove(); - } + slice + .enter() + .insert("path") + .style("fill", function(d) { + return d.data.color; + }) + .attr("class", "slice") + .attr( + "transform", + "translate(" + width / 2 + "," + (height - radius) + ")" + ); + + slice + .transition() + .duration(0) + .attrTween("d", function(d) { + this._current = this._current || d; + var interpolate = d3.interpolate(this._current, d); + this._current = interpolate(0); + return function(t) { + return arc(interpolate(t)); + }; + }); + + slice.exit().remove(); + } } -function printClockAnalogic1 (time_format, timezone, clock_animation,width,height,id_element,color) { - - if(width != 0){ - width = width-20; - height = width-20; - } - - - if(width == 0){ - width = 180; - height = 180; - } - -var radians = 0.0174532925, - clockRadius = width/2, - margin = 10, - width = (clockRadius+margin)*2, - height = (clockRadius+margin)*2, - hourHandLength = 2*clockRadius/3, +function printClockAnalogic1( + time_format, + timezone, + clock_animation, + width, + height, + id_element, + color +) { + if (width != 0) { + width = width - 20; + height = width - 20; + } + + if (width == 0) { + width = 180; + height = 180; + } + + var radians = 0.0174532925, + clockRadius = width / 2, + margin = 10, + width = (clockRadius + margin) * 2, + height = (clockRadius + margin) * 2, + hourHandLength = (2 * clockRadius) / 3, minuteHandLength = clockRadius, - secondHandLength = clockRadius-12, + secondHandLength = clockRadius - 12, secondHandBalance = 30, secondTickStart = clockRadius; - secondTickLength = -10, - hourTickStart = clockRadius, - hourTickLength = -18, - secondLabelRadius = clockRadius + 16, - secondLabelYOffset = 5, - hourLabelRadius = clockRadius - 40, - hourLabelYOffset = 7; + (secondTickLength = -10), + (hourTickStart = clockRadius), + (hourTickLength = -18), + (secondLabelRadius = clockRadius + 16), + (secondLabelYOffset = 5), + (hourLabelRadius = clockRadius - 40), + (hourLabelYOffset = 7); -var hourScale = d3.scale.linear() - .range([0,330]) - .domain([0,11]); + var hourScale = d3.scale + .linear() + .range([0, 330]) + .domain([0, 11]); -var minuteScale = secondScale = d3.scale.linear() - .range([0,354]) - .domain([0,59]); + var minuteScale = (secondScale = d3.scale + .linear() + .range([0, 354]) + .domain([0, 59])); -var handData = [ - { - type:'hour', - value:0, - length:-hourHandLength, - scale:hourScale - }, - { - type:'minute', - value:0, - length:-minuteHandLength, - scale:minuteScale - }, - { - type:'second', - value:0, - length:-secondHandLength, - scale:secondScale, - balance:secondHandBalance - } -]; + var handData = [ + { + type: "hour", + value: 0, + length: -hourHandLength, + scale: hourScale + }, + { + type: "minute", + value: 0, + length: -minuteHandLength, + scale: minuteScale + }, + { + type: "second", + value: 0, + length: -secondHandLength, + scale: secondScale, + balance: secondHandBalance + } + ]; -function drawClock(){ //create all the clock elements - updateData(timezone); //draw them in the correct starting position - var svg = d3.select("#clock_"+id_element).append("svg") - .attr("width", width) - .attr("height", height); + function drawClock() { + //create all the clock elements + updateData(timezone); //draw them in the correct starting position + var svg = d3 + .select("#clock_" + id_element) + .append("svg") + .attr("width", width) + .attr("height", height); - var face = svg.append('g') - .attr('id','clock-face') - .attr('transform','translate(' + (clockRadius + margin) + ',' + (clockRadius + margin) + ')'); + var face = svg + .append("g") + .attr("id", "clock-face") + .attr( + "transform", + "translate(" + + (clockRadius + margin) + + "," + + (clockRadius + margin) + + ")" + ); - //add marks for seconds - face.selectAll('.second-tick') - .data(d3.range(0,60)).enter() - .append('line') - .attr('class', 'second-tick') - .attr('x1',0) - .attr('x2',0) - .attr('y1',secondTickStart) - .attr('y2',secondTickStart + secondTickLength) - .attr('stroke',color) - .attr('transform',function(d){ - return 'rotate(' + secondScale(d) + ')'; - }); - //and labels + //add marks for seconds + face + .selectAll(".second-tick") + .data(d3.range(0, 60)) + .enter() + .append("line") + .attr("class", "second-tick") + .attr("x1", 0) + .attr("x2", 0) + .attr("y1", secondTickStart) + .attr("y2", secondTickStart + secondTickLength) + .attr("stroke", color) + .attr("transform", function(d) { + return "rotate(" + secondScale(d) + ")"; + }); + //and labels - // face.selectAll('.second-label') - // .data(d3.range(5,61,5)) - // .enter() - // .append('text') - // .attr('class', 'second-label') - // .attr('text-anchor','middle') - // .attr('x',function(d){ - // return secondLabelRadius*Math.sin(secondScale(d)*radians); - // }) - // .attr('y',function(d){ - // return -secondLabelRadius*Math.cos(secondScale(d)*radians) + secondLabelYOffset; - // }) - // .text(function(d){ - // return d; - // }); + // face.selectAll('.second-label') + // .data(d3.range(5,61,5)) + // .enter() + // .append('text') + // .attr('class', 'second-label') + // .attr('text-anchor','middle') + // .attr('x',function(d){ + // return secondLabelRadius*Math.sin(secondScale(d)*radians); + // }) + // .attr('y',function(d){ + // return -secondLabelRadius*Math.cos(secondScale(d)*radians) + secondLabelYOffset; + // }) + // .text(function(d){ + // return d; + // }); - //... and hours - face.selectAll('.hour-tick') - .data(d3.range(0,12)).enter() - .append('line') - .attr('class', 'hour-tick') - .attr('x1',0) - .attr('x2',0) - .attr('y1',hourTickStart) - .attr('y2',hourTickStart + hourTickLength) - .attr('stroke',color) - .attr('transform',function(d){ - return 'rotate(' + hourScale(d) + ')'; - }); + //... and hours + face + .selectAll(".hour-tick") + .data(d3.range(0, 12)) + .enter() + .append("line") + .attr("class", "hour-tick") + .attr("x1", 0) + .attr("x2", 0) + .attr("y1", hourTickStart) + .attr("y2", hourTickStart + hourTickLength) + .attr("stroke", color) + .attr("transform", function(d) { + return "rotate(" + hourScale(d) + ")"; + }); - face.selectAll('.hour-label') - .data(d3.range(3,13,3)) - .enter() - .append('text') - .attr('class', 'hour-label') - .attr('text-anchor','middle') - .attr('stroke',color) - .attr('x',function(d){ - return hourLabelRadius*Math.sin(hourScale(d)*radians); - }) - .attr('y',function(d){ - return -hourLabelRadius*Math.cos(hourScale(d)*radians) + hourLabelYOffset; - }) - .text(function(d){ - return d; - }); + face + .selectAll(".hour-label") + .data(d3.range(3, 13, 3)) + .enter() + .append("text") + .attr("class", "hour-label") + .attr("text-anchor", "middle") + .attr("stroke", color) + .attr("x", function(d) { + return hourLabelRadius * Math.sin(hourScale(d) * radians); + }) + .attr("y", function(d) { + return ( + -hourLabelRadius * Math.cos(hourScale(d) * radians) + hourLabelYOffset + ); + }) + .text(function(d) { + return d; + }); + var hands = face.append("g").attr("id", "clock-hands"); - var hands = face.append('g').attr('id','clock-hands'); + face + .append("g") + .attr("id", "face-overlay") + .append("circle") + .attr("class", "hands-cover") + .attr("stroke", color) + .attr("x", 0) + .attr("y", 0) + .attr("r", clockRadius / 20); - face.append('g').attr('id','face-overlay') - .append('circle').attr('class','hands-cover') - .attr('stroke',color) - .attr('x',0) - .attr('y',0) - .attr('r',clockRadius/20); + hands + .selectAll("line") + .data(handData) + .enter() + .append("line") + .attr("stroke", color) + .attr("class", function(d) { + return d.type + "-hand"; + }) + .attr("x1", 0) + .attr("y1", function(d) { + return d.balance ? d.balance : 0; + }) + .attr("x2", 0) + .attr("y2", function(d) { + return d.length; + }) + .attr("transform", function(d) { + return "rotate(" + d.scale(d.value) + ")"; + }); + } - hands.selectAll('line') - .data(handData) - .enter() - .append('line') - .attr('stroke',color) - .attr('class', function(d){ - return d.type + '-hand'; - }) - .attr('x1',0) - .attr('y1',function(d){ - return d.balance ? d.balance : 0; - }) - .attr('x2',0) - .attr('y2',function(d){ - return d.length; - }) - .attr('transform',function(d){ - return 'rotate('+ d.scale(d.value) +')'; - }); -} + function moveHands() { + d3.select("#clock_" + id_element + " #clock-hands") + .selectAll("line") + .data(handData) + .transition() + .attr("transform", function(d) { + return "rotate(" + d.scale(d.value) + ")"; + }); + } -function moveHands(){ - d3.select("#clock_"+id_element+' #clock-hands').selectAll('line') - .data(handData) - .transition() - .attr('transform',function(d){ - return 'rotate('+ d.scale(d.value) +')'; - }); -} - -function updateData(tz){ - - var d = new Date(); - var dt = d.getTime(); + function updateData(tz) { + var d = new Date(); + var dt = d.getTime(); os = d.getTimezoneOffset(); - tz = parseInt(tz) + parseInt(os * 60); - var t = new Date((dt + (tz * 1000))); - - handData[0].value = (t.getHours() % 12) + t.getMinutes()/60 ; - handData[1].value = t.getMinutes(); - handData[2].value = t.getSeconds(); + tz = parseInt(tz) + parseInt(os * 60); + var t = new Date(dt + tz * 1000); + + handData[0].value = (t.getHours() % 12) + t.getMinutes() / 60; + handData[1].value = t.getMinutes(); + handData[2].value = t.getSeconds(); + } + + drawClock(); + + setInterval(function() { + updateData(timezone); + moveHands(); + }, 1000); + + d3.select(self.frameElement).style("height", height + "px"); + + $("#clock_" + id_element).css("margin-top", "0"); } -drawClock(); +function printClockDigital1( + time_format, + timezone, + clock_animation, + width, + height, + id_element, + color +) { + var svgUnderlay = d3.select("#clock_" + id_element + " svg"), + svgOverlay = d3.select("#clock_" + id_element), + svg = d3.selectAll("#clock_" + id_element + " svg"); -setInterval(function(){ - updateData(timezone); - moveHands(); -}, 1000); + svgUnderlay.attr("id", "underlay_" + id_element); + svgOverlay.attr("id", "overlay_" + id_element); -d3.select(self.frameElement).style("height", height + "px"); - -$('#clock_'+id_element).css('margin-top','0'); - -} - -function printClockDigital1 (time_format, timezone, clock_animation,width,height,id_element,color) { - -var svgUnderlay = d3.select("#clock_"+id_element+" svg"), - svgOverlay = d3.select("#clock_"+id_element), - svg = d3.selectAll("#clock_"+id_element+" svg"); - -svgUnderlay.attr("id", "underlay_"+id_element); -svgOverlay.attr("id", "overlay_"+id_element); - -var digit = svg.selectAll(".digit"), + var digit = svg.selectAll(".digit"), separator = svg.selectAll(".separator circle"); -var digitPattern = [ - [1,0,1,1,0,1,1,1,1,1], - [1,0,0,0,1,1,1,0,1,1], - [1,1,1,1,1,0,0,1,1,1], - [0,0,1,1,1,1,1,0,1,1], - [1,0,1,0,0,0,1,0,1,0], - [1,1,0,1,1,1,1,1,1,1], - [1,0,1,1,0,1,1,0,1,1] -]; + var digitPattern = [ + [1, 0, 1, 1, 0, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 0, 1, 1], + [1, 0, 1, 0, 0, 0, 1, 0, 1, 0], + [1, 1, 0, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 1, 1, 0, 1, 1, 0, 1, 1] + ]; -(function tick() { - - var tz = timezone; - var d = new Date(); - var dt = d.getTime(); - os = d.getTimezoneOffset(); - tz = parseInt(tz) + parseInt(os * 60); - var t = new Date((dt + (tz * 1000))); + (function tick() { + var tz = timezone; + var d = new Date(); + var dt = d.getTime(); + os = d.getTimezoneOffset(); + tz = parseInt(tz) + parseInt(os * 60); + var t = new Date(dt + tz * 1000); - var now = new Date, + var now = new Date(), hours = t.getHours(), minutes = t.getMinutes(), seconds = t.getSeconds(); - digit = digit.data([hours / 10 | 0, hours % 10, minutes / 10 | 0, minutes % 10, seconds / 10 | 0, seconds % 10]); - digit.select("path:nth-child(1)").classed("lit", function(d) { return digitPattern[0][d]; }); - digit.select("path:nth-child(2)").classed("lit", function(d) { return digitPattern[1][d]; }); - digit.select("path:nth-child(3)").classed("lit", function(d) { return digitPattern[2][d]; }); - digit.select("path:nth-child(4)").classed("lit", function(d) { return digitPattern[3][d]; }); - digit.select("path:nth-child(5)").classed("lit", function(d) { return digitPattern[4][d]; }); - digit.select("path:nth-child(6)").classed("lit", function(d) { return digitPattern[5][d]; }); - digit.select("path:nth-child(7)").classed("lit", function(d) { return digitPattern[6][d]; }); - separator.classed("lit", 1); + digit = digit.data([ + (hours / 10) | 0, + hours % 10, + (minutes / 10) | 0, + minutes % 10, + (seconds / 10) | 0, + seconds % 10 + ]); + digit.select("path:nth-child(1)").classed("lit", function(d) { + return digitPattern[0][d]; + }); + digit.select("path:nth-child(2)").classed("lit", function(d) { + return digitPattern[1][d]; + }); + digit.select("path:nth-child(3)").classed("lit", function(d) { + return digitPattern[2][d]; + }); + digit.select("path:nth-child(4)").classed("lit", function(d) { + return digitPattern[3][d]; + }); + digit.select("path:nth-child(5)").classed("lit", function(d) { + return digitPattern[4][d]; + }); + digit.select("path:nth-child(6)").classed("lit", function(d) { + return digitPattern[5][d]; + }); + digit.select("path:nth-child(7)").classed("lit", function(d) { + return digitPattern[6][d]; + }); + separator.classed("lit", 1); - setTimeout(tick, 1000 - now % 1000); -})(); - + setTimeout(tick, 1000 - (now % 1000)); + })(); } diff --git a/pandora_console/include/javascript/clippy.js b/pandora_console/include/javascript/clippy.js index f7624e3638..044825cb08 100644 --- a/pandora_console/include/javascript/clippy.js +++ b/pandora_console/include/javascript/clippy.js @@ -1,8 +1,8 @@ function clippy_set_help(help_section) { - document.cookie = 'clippy=' + help_section; + document.cookie = "clippy=" + help_section; } function clippy_go_link_show_help(link, help_section) { - document.cookie = 'clippy=' + help_section; - window.location.href = link; -} \ No newline at end of file + document.cookie = "clippy=" + help_section; + window.location.href = link; +} diff --git a/pandora_console/include/javascript/encode_decode_base64.js b/pandora_console/include/javascript/encode_decode_base64.js index d5992ebb38..71432daa75 100644 --- a/pandora_console/include/javascript/encode_decode_base64.js +++ b/pandora_console/include/javascript/encode_decode_base64.js @@ -1,147 +1,136 @@ -/** +/** * Javascript functions for encoding /decoding in base 64 codification */ /** -* -* Base64 encode / decode -* http://www.webtoolkit.info/ -* -**/ + * + * Base64 encode / decode + * http://www.webtoolkit.info/ + * + **/ var Base64 = { + // private property + _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", - // private property - _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + // public method for encoding + encode: function(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; - // public method for encoding - encode : function (input) { - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; + input = Base64._utf8_encode(input); - input = Base64._utf8_encode(input); + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); - while (i < input.length) { + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; + output = + output + + this._keyStr.charAt(enc1) + + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + + this._keyStr.charAt(enc4); + } - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } + return output; + }, - output = output + - this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + - this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + // public method for decoding + decode: function(input) { + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; - } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - return output; - }, + while (i < input.length) { + enc1 = this._keyStr.indexOf(input.charAt(i++)); + enc2 = this._keyStr.indexOf(input.charAt(i++)); + enc3 = this._keyStr.indexOf(input.charAt(i++)); + enc4 = this._keyStr.indexOf(input.charAt(i++)); - // public method for decoding - decode : function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + output = output + String.fromCharCode(chr1); - while (i < input.length) { + if (enc3 != 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 != 64) { + output = output + String.fromCharCode(chr3); + } + } - enc1 = this._keyStr.indexOf(input.charAt(i++)); - enc2 = this._keyStr.indexOf(input.charAt(i++)); - enc3 = this._keyStr.indexOf(input.charAt(i++)); - enc4 = this._keyStr.indexOf(input.charAt(i++)); + output = Base64._utf8_decode(output); - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; + return output; + }, - output = output + String.fromCharCode(chr1); + // private method for UTF-8 encoding + _utf8_encode: function(string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); - } + for (var n = 0; n < string.length; n++) { + var c = string.charCodeAt(n); - } + if (c < 128) { + utftext += String.fromCharCode(c); + } else if (c > 127 && c < 2048) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + } - output = Base64._utf8_decode(output); + return utftext; + }, - return output; + // private method for UTF-8 decoding + _utf8_decode: function(utftext) { + var string = ""; + var i = 0; + var c = (c1 = c2 = 0); - }, + while (i < utftext.length) { + c = utftext.charCodeAt(i); - // private method for UTF-8 encoding - _utf8_encode : function (string) { - string = string.replace(/\r\n/g,"\n"); - var utftext = ""; - - for (var n = 0; n < string.length; n++) { - - var c = string.charCodeAt(n); - - if (c < 128) { - utftext += String.fromCharCode(c); - } - else if((c > 127) && (c < 2048)) { - utftext += String.fromCharCode((c >> 6) | 192); - utftext += String.fromCharCode((c & 63) | 128); - } - else { - utftext += String.fromCharCode((c >> 12) | 224); - utftext += String.fromCharCode(((c >> 6) & 63) | 128); - utftext += String.fromCharCode((c & 63) | 128); - } - - } - - return utftext; - }, - - // private method for UTF-8 decoding - _utf8_decode : function (utftext) { - var string = ""; - var i = 0; - var c = c1 = c2 = 0; - - while ( i < utftext.length ) { - - c = utftext.charCodeAt(i); - - if (c < 128) { - string += String.fromCharCode(c); - i++; - } - else if((c > 191) && (c < 224)) { - c2 = utftext.charCodeAt(i+1); - string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } - else { - c2 = utftext.charCodeAt(i+1); - c3 = utftext.charCodeAt(i+2); - string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - - } - - return string; - } - -} + if (c < 128) { + string += String.fromCharCode(c); + i++; + } else if (c > 191 && c < 224) { + c2 = utftext.charCodeAt(i + 1); + string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = utftext.charCodeAt(i + 1); + c3 = utftext.charCodeAt(i + 2); + string += String.fromCharCode( + ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) + ); + i += 3; + } + } + return string; + } +}; diff --git a/pandora_console/include/javascript/fixed-bottom-box.js b/pandora_console/include/javascript/fixed-bottom-box.js index 7fc622e498..7ea5b803b3 100644 --- a/pandora_console/include/javascript/fixed-bottom-box.js +++ b/pandora_console/include/javascript/fixed-bottom-box.js @@ -6,345 +6,334 @@ // This module has an Universal Module Definition pattern and its scope is private -(function (name, factory) { - // AMD - if (typeof define === 'function' && define.amd) { - define(['jquery'], factory); - } - // Node (CommonJS) - else if (typeof exports === 'object') { - module.exports = factory(require('jquery')); - } - // Assign to the jQuery namespace - else { - (this.jQuery || this.$)[name] = factory(this.jQuery || this.$); - } -} ('fixedBottomBox', function ($) { - // jQuery required - if (typeof $ === 'undefined') - return; - // Module definition - return fixedBottomBox = function (params) { - var self = new Object(); - - self._rendered = false; - - self.isRendered = function (state) { - if (typeof state === 'boolean') - self._rendered = state; - - return self._rendered; - } - - params = params || {}; - self._debug = params.debug || false; - self._target = params.target || 'body'; - self._opened = params.opened || false; - self._head = params.head || ''; - self._content = params.content || ''; - self._animationDuration = params.animationDuration || 200; - - self._width = params.width || 300; - self._height = params.height || 400; - - self.setWidth = function (width) { - if (typeof width !== 'number' || width <= 0) - throw new TypeError('Invalid width'); - self._width = width; - - if (typeof self._box !== 'undefined') { - self._box.head.css('width', width + 'px'); - self._box.content.css('width', width + 'px'); - } - - return self; - } - - self.getWidth = function (width) { - return self._width; - } - - self.setHeight = function (height) { - if (typeof height !== 'number' || height <= 0) - throw new TypeError('Invalid height'); - self._heigth = height; - - var headHeight = self._box.head.height() || 30; - - if (typeof self._box !== 'undefined') { - self._box.content.css('max-height', (height - headHeight) + 'px'); - } - - return self; - } - - self.getHeight = function (height) { - return self._height; - } - - self.resize = function (width, height) { - try { - self.setWidth(width); - self.setHeight(height); - self.emit('resized', { width: width, height: height }); - } - catch (error) { - if (self._debug) - console.error(error); - } - - return self; - } - - self.render = function (head, content) { - self._createBox(head, content); - - return self; - } - - self._renderHead = function (head) { - head = head || self._head; - - var headBody = $('
'); - headBody - .addClass('fixed-bottom-box-head-body') - .click(function(event) { - self.toggle(); - }); - var headClose = $(''); - headClose - .addClass('fixed-bottom-box-head-close') - .click(function(event) { - self.close(); - }); - - self._box.head = $('
'); - self._box.head - .addClass('fixed-bottom-box-head') - .append(headClose, headBody); - self._box.append(self._box.head); - - self.emit('head-rendered', { headRef: self._box.head, headContent: head }); - } - - self._renderContent = function (content) { - content = content || self._content; - - self._box.content = $('
'); - self._box.content - .addClass('fixed-bottom-box-content') - .append(content); - self._box.append(self._box.content); - - self.emit('content-rendered', { contentRef: self._box.content, content: content }); - } - - self._createBox = function (head, content) { - head = head || self._head; - content = content || self._content; - - if (self.isRendered()) - self._destroyBox(); - - try { - self._box = $('
'); - self._box - .addClass('fixed-bottom-box') - .css('position', 'fixed') - .css('bottom', '0px') - .css('right', '20px'); - - self._renderHead(head); - self._renderContent(content); - - self.resize(self._width, self._height); - - if (!self.isOpen()) - self._box.content.hide(); - - $(self._target).append(self._box); - - self.isRendered(true); - - self.emit('rendered', { boxRef: self._box, headContent: head, content: content }); - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self._destroyBox = function () { - try { - if (self.isRendered()) { - self._box.hide(); - - self._box.content.remove(); - delete self._box.content; - - self._box.head.remove(); - delete self._box.head; - - self._box.remove(); - delete self._box; - - self.isRendered(false); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - - self.isOpen = function (state) { - if (typeof state === 'boolean') - self._opened = state; - - return self._opened; - } - - self.setHead = function (head) { - if (typeof head === 'undefined' || head.length <= 0) - throw new TypeError('Invalid head'); - self._head = head; - - return self; - } - - self.setContent = function (content) { - if (typeof content === 'undefined' || content.length <= 0) - throw new TypeError('Invalid content'); - self._content = content; - - return self; - } - - self.open = function () { - try { - if (!self.isOpen()) { - self._box.content.slideDown(self._animationDuration, function() { - self.isOpen(true); - $(this) - .removeClass('fixed-bottom-box-hided') - .addClass('fixed-bottom-box-opened'); - self.emit('open', { ref: self }); - }); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self.hide = function () { - try { - if (self.isOpen()) { - - self._box.content.slideUp(self._animationDuration, function() { - self.isOpen(false); - $(this) - .removeClass('fixed-bottom-box-opened') - .addClass('fixed-bottom-box-hided'); - self.emit('hide', { ref: self }); - }); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self.toggle = function () { - if (self.isOpen()) - self.hide(); - else - self.open(); - } - - self.close = function () { - try { - self._head = ''; - self._content = ''; - self.isOpen(false); - self._destroyBox(); - - self.emit('close', {}); - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - - //-- Event handlers --// - - // Populate the observers - var eventsList = ['open', 'hide', 'close', 'rendered', 'head-rendered', 'content-rendered', 'resized']; - self._observers = {} - eventsList.forEach(function(eventName) { - self._observers[eventName] = []; - }); - - self.emit = function (eventName, payload) { - if (typeof eventName === 'undefined' || eventName.length <= 0) - throw new TypeError('Invalid event name'); - if (typeof self._observers[eventName] === 'undefined') - throw new TypeError('The introduced event does not exists'); - payload = payload || {}; - - var observers = self._observers[eventName]; - - observers.forEach(function(callback) { - if (typeof callback === 'function') - callback(payload); - }); - } - - self.on = function (eventName, callback) { - if (typeof eventName === 'undefined' || eventName.length <= 0) - throw new TypeError('Invalid event name'); - if (typeof callback === 'function') - throw new TypeError('The callback should be a function'); - - var res = false; - if (typeof self._observers[eventName] !== 'undefined') { - var length = self._observers[eventName].push(callback); - res = length - 1; - } - - return res; - } - - // Should receive - self.onOpen = function (callback) { - self.on('open', callback); - } - // Should receive - self.onHide = function (callback) { - self.on('hide', callback); - } - // Should receive - self.onClose = function (callback) { - self.on('close', callback); - } - // Should receive - self.onHeadRender = function (callback) { - self.on('head-rendered', callback); - } - // Should receive - self.onContentRender = function (callback) { - self.on('content-rendered', callback); - } - // Should receive - self.onResize = function (callback) { - self.on('resized', callback); - } - - return self; - } -})); \ No newline at end of file +(function(name, factory) { + // AMD + if (typeof define === "function" && define.amd) { + define(["jquery"], factory); + } + // Node (CommonJS) + else if (typeof exports === "object") { + module.exports = factory(require("jquery")); + } + // Assign to the jQuery namespace + else { + (this.jQuery || this.$)[name] = factory(this.jQuery || this.$); + } +})("fixedBottomBox", function($) { + // jQuery required + if (typeof $ === "undefined") return; + // Module definition + return (fixedBottomBox = function(params) { + var self = new Object(); + + self._rendered = false; + + self.isRendered = function(state) { + if (typeof state === "boolean") self._rendered = state; + + return self._rendered; + }; + + params = params || {}; + self._debug = params.debug || false; + self._target = params.target || "body"; + self._opened = params.opened || false; + self._head = params.head || ""; + self._content = params.content || ""; + self._animationDuration = params.animationDuration || 200; + + self._width = params.width || 300; + self._height = params.height || 400; + + self.setWidth = function(width) { + if (typeof width !== "number" || width <= 0) + throw new TypeError("Invalid width"); + self._width = width; + + if (typeof self._box !== "undefined") { + self._box.head.css("width", width + "px"); + self._box.content.css("width", width + "px"); + } + + return self; + }; + + self.getWidth = function(width) { + return self._width; + }; + + self.setHeight = function(height) { + if (typeof height !== "number" || height <= 0) + throw new TypeError("Invalid height"); + self._heigth = height; + + var headHeight = self._box.head.height() || 30; + + if (typeof self._box !== "undefined") { + self._box.content.css("max-height", height - headHeight + "px"); + } + + return self; + }; + + self.getHeight = function(height) { + return self._height; + }; + + self.resize = function(width, height) { + try { + self.setWidth(width); + self.setHeight(height); + self.emit("resized", { width: width, height: height }); + } catch (error) { + if (self._debug) console.error(error); + } + + return self; + }; + + self.render = function(head, content) { + self._createBox(head, content); + + return self; + }; + + self._renderHead = function(head) { + head = head || self._head; + + var headBody = $("
"); + headBody.addClass("fixed-bottom-box-head-body").click(function(event) { + self.toggle(); + }); + var headClose = $(""); + headClose.addClass("fixed-bottom-box-head-close").click(function(event) { + self.close(); + }); + + self._box.head = $("
"); + self._box.head + .addClass("fixed-bottom-box-head") + .append(headClose, headBody); + self._box.append(self._box.head); + + self.emit("head-rendered", { + headRef: self._box.head, + headContent: head + }); + }; + + self._renderContent = function(content) { + content = content || self._content; + + self._box.content = $("
"); + self._box.content.addClass("fixed-bottom-box-content").append(content); + self._box.append(self._box.content); + + self.emit("content-rendered", { + contentRef: self._box.content, + content: content + }); + }; + + self._createBox = function(head, content) { + head = head || self._head; + content = content || self._content; + + if (self.isRendered()) self._destroyBox(); + + try { + self._box = $("
"); + self._box + .addClass("fixed-bottom-box") + .css("position", "fixed") + .css("bottom", "0px") + .css("right", "20px"); + + self._renderHead(head); + self._renderContent(content); + + self.resize(self._width, self._height); + + if (!self.isOpen()) self._box.content.hide(); + + $(self._target).append(self._box); + + self.isRendered(true); + + self.emit("rendered", { + boxRef: self._box, + headContent: head, + content: content + }); + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self._destroyBox = function() { + try { + if (self.isRendered()) { + self._box.hide(); + + self._box.content.remove(); + delete self._box.content; + + self._box.head.remove(); + delete self._box.head; + + self._box.remove(); + delete self._box; + + self.isRendered(false); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.isOpen = function(state) { + if (typeof state === "boolean") self._opened = state; + + return self._opened; + }; + + self.setHead = function(head) { + if (typeof head === "undefined" || head.length <= 0) + throw new TypeError("Invalid head"); + self._head = head; + + return self; + }; + + self.setContent = function(content) { + if (typeof content === "undefined" || content.length <= 0) + throw new TypeError("Invalid content"); + self._content = content; + + return self; + }; + + self.open = function() { + try { + if (!self.isOpen()) { + self._box.content.slideDown(self._animationDuration, function() { + self.isOpen(true); + $(this) + .removeClass("fixed-bottom-box-hided") + .addClass("fixed-bottom-box-opened"); + self.emit("open", { ref: self }); + }); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.hide = function() { + try { + if (self.isOpen()) { + self._box.content.slideUp(self._animationDuration, function() { + self.isOpen(false); + $(this) + .removeClass("fixed-bottom-box-opened") + .addClass("fixed-bottom-box-hided"); + self.emit("hide", { ref: self }); + }); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.toggle = function() { + if (self.isOpen()) self.hide(); + else self.open(); + }; + + self.close = function() { + try { + self._head = ""; + self._content = ""; + self.isOpen(false); + self._destroyBox(); + + self.emit("close", {}); + } catch (error) { + if (self._debug) console.error(error); + } + }; + + //-- Event handlers --// + + // Populate the observers + var eventsList = [ + "open", + "hide", + "close", + "rendered", + "head-rendered", + "content-rendered", + "resized" + ]; + self._observers = {}; + eventsList.forEach(function(eventName) { + self._observers[eventName] = []; + }); + + self.emit = function(eventName, payload) { + if (typeof eventName === "undefined" || eventName.length <= 0) + throw new TypeError("Invalid event name"); + if (typeof self._observers[eventName] === "undefined") + throw new TypeError("The introduced event does not exists"); + payload = payload || {}; + + var observers = self._observers[eventName]; + + observers.forEach(function(callback) { + if (typeof callback === "function") callback(payload); + }); + }; + + self.on = function(eventName, callback) { + if (typeof eventName === "undefined" || eventName.length <= 0) + throw new TypeError("Invalid event name"); + if (typeof callback === "function") + throw new TypeError("The callback should be a function"); + + var res = false; + if (typeof self._observers[eventName] !== "undefined") { + var length = self._observers[eventName].push(callback); + res = length - 1; + } + + return res; + }; + + // Should receive + self.onOpen = function(callback) { + self.on("open", callback); + }; + // Should receive + self.onHide = function(callback) { + self.on("hide", callback); + }; + // Should receive + self.onClose = function(callback) { + self.on("close", callback); + }; + // Should receive + self.onHeadRender = function(callback) { + self.on("head-rendered", callback); + }; + // Should receive + self.onContentRender = function(callback) { + self.on("content-rendered", callback); + }; + // Should receive + self.onResize = function(callback) { + self.on("resized", callback); + }; + + return self; + }); +}); diff --git a/pandora_console/include/javascript/functions_pandora_networkmap.js b/pandora_console/include/javascript/functions_pandora_networkmap.js index 8871950f3e..4c9f5b61b7 100644 --- a/pandora_console/include/javascript/functions_pandora_networkmap.js +++ b/pandora_console/include/javascript/functions_pandora_networkmap.js @@ -1,1070 +1,1157 @@ - function draw_minimap() { - //Clean the canvas - context_minimap.clearRect(0, 0, minimap_w, minimap_h); + //Clean the canvas + context_minimap.clearRect(0, 0, minimap_w, minimap_h); - context_minimap.beginPath(); - context_minimap.globalAlpha = 0.8; - context_minimap.fillStyle = "#ddd"; - context_minimap.fillRect(0, 0, minimap_w, minimap_h); + context_minimap.beginPath(); + context_minimap.globalAlpha = 0.8; + context_minimap.fillStyle = "#ddd"; + context_minimap.fillRect(0, 0, minimap_w, minimap_h); - var relation_min_nodes = minimap_relation; - var relation_minimap_w = 2; - var relation_minimap_h = 2; - if (graph.nodes.length > 100) { - relation_min_nodes = 0.01; - relation_minimap_w = (graph.nodes.length / 100) * 2.5; - relation_minimap_h = 1.5; - } + var relation_min_nodes = minimap_relation; + var relation_minimap_w = 2; + var relation_minimap_h = 2; + if (graph.nodes.length > 100) { + relation_min_nodes = 0.01; + relation_minimap_w = (graph.nodes.length / 100) * 2.5; + relation_minimap_h = 1.5; + } - //Draw the items and lines - jQuery.each(graph.nodes, function (key, value) { - if (typeof (value) == 'undefined') return; + //Draw the items and lines + jQuery.each(graph.nodes, function(key, value) { + if (typeof value == "undefined") return; - context_minimap.beginPath(); - //Paint the item - if (graph.nodes.length > 100) { - center_orig_x = (value.x + value.image_width / 4) * relation_min_nodes + minimap_w / relation_minimap_w; - center_orig_y = (value.y + value.image_height / 4) * relation_min_nodes + minimap_h / relation_minimap_h; - } - else { - center_orig_x = (value.x + value.image_width / 2) * relation_min_nodes; - center_orig_y = (value.y + value.image_height / 2) * relation_min_nodes; - } + context_minimap.beginPath(); + //Paint the item + if (graph.nodes.length > 100) { + center_orig_x = + (value.x + value.image_width / 4) * relation_min_nodes + + minimap_w / relation_minimap_w; + center_orig_y = + (value.y + value.image_height / 4) * relation_min_nodes + + minimap_h / relation_minimap_h; + } else { + center_orig_x = (value.x + value.image_width / 2) * relation_min_nodes; + center_orig_y = (value.y + value.image_height / 2) * relation_min_nodes; + } - context_minimap.arc(center_orig_x, - center_orig_y, 2, 0, Math.PI * 2, false); - //Check if the pandora point - if (value.id_agent == -1) { - context_minimap.fillStyle = "#364D1F"; - } - else { - context_minimap.fillStyle = "#000"; - } - context_minimap.fill(); - }); + context_minimap.arc(center_orig_x, center_orig_y, 2, 0, Math.PI * 2, false); + //Check if the pandora point + if (value.id_agent == -1) { + context_minimap.fillStyle = "#364D1F"; + } else { + context_minimap.fillStyle = "#000"; + } + context_minimap.fill(); + }); - if (graph.nodes.length > 100) { - //Draw the rect of viewport - context_minimap.beginPath(); - context_minimap.strokeStyle = "#3f3f3f"; - context_minimap.strokeRect( - (-translation[0] / scale) * relation_min_nodes + minimap_w / relation_minimap_w, - (-translation[1] / scale) * relation_min_nodes + minimap_h / relation_minimap_h, - width_svg * relation_min_nodes / scale, - height_svg * relation_min_nodes / scale); - } - else { - //Draw the rect of viewport - context_minimap.beginPath(); - context_minimap.strokeStyle = "#f00"; - context_minimap.strokeRect( - (-translation[0] / scale) * relation_min_nodes, - (-translation[1] / scale) * relation_min_nodes, - width_svg * relation_min_nodes / scale, - height_svg * relation_min_nodes / scale); - } + if (graph.nodes.length > 100) { + //Draw the rect of viewport + context_minimap.beginPath(); + context_minimap.strokeStyle = "#3f3f3f"; + context_minimap.strokeRect( + (-translation[0] / scale) * relation_min_nodes + + minimap_w / relation_minimap_w, + (-translation[1] / scale) * relation_min_nodes + + minimap_h / relation_minimap_h, + (width_svg * relation_min_nodes) / scale, + (height_svg * relation_min_nodes) / scale + ); + } else { + //Draw the rect of viewport + context_minimap.beginPath(); + context_minimap.strokeStyle = "#f00"; + context_minimap.strokeRect( + (-translation[0] / scale) * relation_min_nodes, + (-translation[1] / scale) * relation_min_nodes, + (width_svg * relation_min_nodes) / scale, + (height_svg * relation_min_nodes) / scale + ); + } - context_minimap.beginPath(); - context_minimap.strokeStyle = "#82B92E"; - context_minimap.strokeRect( - (networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) * minimap_relation, - (networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) * minimap_relation, - holding_area_dimensions[0] * minimap_relation, - holding_area_dimensions[1] * minimap_relation) + context_minimap.beginPath(); + context_minimap.strokeStyle = "#82B92E"; + context_minimap.strokeRect( + (networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) * + minimap_relation, + (networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) * + minimap_relation, + holding_area_dimensions[0] * minimap_relation, + holding_area_dimensions[1] * minimap_relation + ); - context_minimap.globalAlpha = 1; + context_minimap.globalAlpha = 1; } function inner_minimap_box(param_x, param_y) { - if ((param_x + translation[0] * minimap_relation >= 0) - && (param_x + translation[0] * minimap_relation <= width_svg * minimap_relation) - && (param_y + translation[1] * minimap_relation >= 0) - && (param_y + translation[1] * minimap_relation <= height_svg * minimap_relation)) { - return true; - } + if ( + param_x + translation[0] * minimap_relation >= 0 && + param_x + translation[0] * minimap_relation <= + width_svg * minimap_relation && + param_y + translation[1] * minimap_relation >= 0 && + param_y + translation[1] * minimap_relation <= height_svg * minimap_relation + ) { + return true; + } - return false; + return false; } function set_center(id, event) { - pos_x = (width_svg / 2) - (translation[0] / scale); - pos_y = (height_svg / 2) - (translation[1] / scale); + pos_x = width_svg / 2 - translation[0] / scale; + pos_y = height_svg / 2 - translation[1] / scale; - var params = []; - params.push("set_center=1"); - params.push("id=" + id); - params.push("x=" + pos_x); - params.push("y=" + pos_y); - params.push("scale=" + scale); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - } - } - }); + var params = []; + params.push("set_center=1"); + params.push("id=" + id); + params.push("x=" + pos_x); + params.push("y=" + pos_y); + params.push("scale=" + scale); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + } + } + }); } function get_relations(node_param) { - var return_links = []; - var links_id_db = []; - - jQuery.each(graph.links, function (i, link_each) { - if (node_param.id == link_each.source.id || node_param.id == link_each.target.id) { - if(links_id_db.length > 0){ - if(links_id_db.indexOf(link_each.id_db) == -1){ - return_links.push(link_each); - links_id_db.push(link_each.id_db); - } - } else { - return_links.push(link_each); - links_id_db.push(link_each.id_db); - } - } - }); - - return return_links; + var return_links = []; + var links_id_db = []; + + jQuery.each(graph.links, function(i, link_each) { + if ( + node_param.id == link_each.source.id || + node_param.id == link_each.target.id + ) { + if (links_id_db.length > 0) { + if (links_id_db.indexOf(link_each.id_db) == -1) { + return_links.push(link_each); + links_id_db.push(link_each.id_db); + } + } else { + return_links.push(link_each); + links_id_db.push(link_each.id_db); + } + } + }); + + return return_links; } -function delete_link(source_id, source_module_id, target_id, target_module_id, id_link) { - if (enterprise_installed) { - var params = []; - params.push("delete_link=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("source_id=" + source_id); - params.push("source_module_id=" + source_module_id); - params.push("target_id=" + target_id); - params.push("target_module_id=" + target_module_id); - params.push("id_link=" + id_link); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - var found = -1; - jQuery.each(graph.links, function (i, element) { - if (element.id_db == id_link) { - found = i; - } - }); - if (found != -1) { - graph.links.splice(found, 1); - } +function delete_link( + source_id, + source_module_id, + target_id, + target_module_id, + id_link +) { + if (enterprise_installed) { + var params = []; + params.push("delete_link=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("source_id=" + source_id); + params.push("source_module_id=" + source_module_id); + params.push("target_id=" + target_id); + params.push("target_module_id=" + target_module_id); + params.push("id_link=" + id_link); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + var found = -1; + jQuery.each(graph.links, function(i, element) { + if (element.id_db == id_link) { + found = i; + } + }); + if (found != -1) { + graph.links.splice(found, 1); + } - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - $("#dialog_node_edit").dialog("close"); - } - }); - } + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + $("#dialog_node_edit").dialog("close"); + } + }); + } } function update_fictional_node(id_db_node) { - if (enterprise_installed) { - var name = $("input[name='edit_name_fictional_node']").val(); - var networkmap_to_link = $("#edit_networkmap_to_link").val(); + if (enterprise_installed) { + var name = $("input[name='edit_name_fictional_node']").val(); + var networkmap_to_link = $("#edit_networkmap_to_link").val(); - var params = []; - params.push("update_fictional_node=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("node_id=" + id_db_node); - params.push("name=" + name); - params.push("networkmap_to_link=" + networkmap_to_link); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_fictional_node=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("node_id=" + id_db_node); + params.push("name=" + name); + params.push("networkmap_to_link=" + networkmap_to_link); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_edit").dialog("close"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_edit").dialog("close"); - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i].text = name; - graph.nodes[i].networkmap_id = networkmap_to_link; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i].text = name; + graph.nodes[i].networkmap_id = networkmap_to_link; - $("#id_node_" + i + networkmap_id + " title").html(name); - $("#id_node_" + i + networkmap_id + " tspan").html(ellipsize(name, 30)); - } - }); + $("#id_node_" + i + networkmap_id + " title").html(name); + $("#id_node_" + i + networkmap_id + " tspan").html( + ellipsize(name, 30) + ); + } + }); - draw_elements_graph(); - set_positions_graph(); - } - } - }); - } + draw_elements_graph(); + set_positions_graph(); + } + } + }); + } } function update_node_name(id_db_node) { - if (enterprise_installed) { - var name = $("input[name='edit_name_node']").val(); + if (enterprise_installed) { + var name = $("input[name='edit_name_node']").val(); - var params = []; - params.push("update_node_name=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("node_id=" + id_db_node); - params.push("name=" + name); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_node_name=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("node_id=" + id_db_node); + params.push("name=" + name); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_edit").dialog("close"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_edit").dialog("close"); - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i]['text'] = data['text']; - graph.nodes[i]['raw_text'] = data['raw_text']; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i]["text"] = data["text"]; + graph.nodes[i]["raw_text"] = data["raw_text"]; - $("#id_node_" + i + networkmap_id + " title").html(data['raw_text']); - $("#id_node_" + i + networkmap_id + " tspan").html(ellipsize(data['raw_text'], 30)); - } - }); + $("#id_node_" + i + networkmap_id + " title").html( + data["raw_text"] + ); + $("#id_node_" + i + networkmap_id + " tspan").html( + ellipsize(data["raw_text"], 30) + ); + } + }); - draw_elements_graph(); - set_positions_graph(); - } - } - }); - } + draw_elements_graph(); + set_positions_graph(); + } + } + }); + } } function change_shape(id_db_node) { - if (enterprise_installed) { - var shape = $("select[name='shape']").val(); + if (enterprise_installed) { + var shape = $("select[name='shape']").val(); - var params = []; - params.push("change_shape=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("id=" + id_db_node); - params.push("shape=" + shape); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("change_shape=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("id=" + id_db_node); + params.push("shape=" + shape); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - $("#shape_icon_correct").css("display", "none"); - $("#shape_icon_fail").css("display", "none"); - $("#shape_icon_in_progress").css("display", ""); + $("#shape_icon_correct").css("display", "none"); + $("#shape_icon_fail").css("display", "none"); + $("#shape_icon_in_progress").css("display", ""); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $("#shape_icon_in_progress").css("display", "none"); - if (data['correct']) { - $("#shape_icon_correct").css("display", ""); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#shape_icon_in_progress").css("display", "none"); + if (data["correct"]) { + $("#shape_icon_correct").css("display", ""); - count = graph.nodes.length; + count = graph.nodes.length; - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i].shape = shape; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i].shape = shape; - $("#id_node_" + element.id + networkmap_id + " rect").remove(); - $("#id_node_" + element.id + networkmap_id + " circle").remove(); - $("#id_node_" + element.id + networkmap_id + " image").remove(); + $("#id_node_" + element.id + networkmap_id + " rect").remove(); + $("#id_node_" + element.id + networkmap_id + " circle").remove(); + $("#id_node_" + element.id + networkmap_id + " image").remove(); - if (shape == 'circle') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("circle", "title") - .attr("r", node_radius) - .attr("class", "node_shape node_shape_circle") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + if (shape == "circle") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("circle", "title") + .attr("r", node_radius) + .attr("class", "node_shape node_shape_circle") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } else if (shape == "square") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("rect", "title") + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("class", "node_shape node_shape_square") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } else if (shape == "rhombus") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("rect", "title") + .attr("transform", "") + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5) + .attr("class", "node_shape node_shape_rhombus") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - } - else if (shape == 'square') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("rect", "title") - .attr("width", node_radius * 2) - .attr("height", node_radius * 2) - .attr("class", "node_shape node_shape_square") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } + } - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - } - else if (shape == 'rhombus') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("rect", "title") - .attr("transform", - "") - .attr("width", node_radius * 1.5) - .attr("height", node_radius * 1.5) - .attr("class", "node_shape node_shape_rhombus") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - } - - } - - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); - } - }); - } - else { - $("#shape_icon_fail").css("display", ""); - } - } - }); - } + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); + } + }); + } else { + $("#shape_icon_fail").css("display", ""); + } + } + }); + } } function update_link(row_index, id_link) { - var interface_source = parseInt( - $("select[name='interface_source_" + row_index + "']") - .val() - ); + var interface_source = parseInt( + $("select[name='interface_source_" + row_index + "']").val() + ); - var text_source_interface = ""; - if (interface_source != 0) { - text_source_interface = $("select[name='interface_source_" + - row_index + "'] option:selected").text(); - } + var text_source_interface = ""; + if (interface_source != 0) { + text_source_interface = $( + "select[name='interface_source_" + row_index + "'] option:selected" + ).text(); + } - var interface_target = parseInt( - $("select[name='interface_target_" + row_index + "']") - .val() - ); + var interface_target = parseInt( + $("select[name='interface_target_" + row_index + "']").val() + ); - var text_target_interface = ""; - if (interface_target != 0) { - text_target_interface = $("select[name='interface_target_" + - row_index + "'] option:selected").text(); - } + var text_target_interface = ""; + if (interface_target != 0) { + text_target_interface = $( + "select[name='interface_target_" + row_index + "'] option:selected" + ).text(); + } - $(".edit_icon_progress_" + row_index).css("display", ""); - $(".edit_icon_" + row_index).css("display", "none"); + $(".edit_icon_progress_" + row_index).css("display", ""); + $(".edit_icon_" + row_index).css("display", "none"); - var params = []; - params.push("update_link=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("id_link=" + id_link); - params.push("interface_source=" + interface_source); - params.push("interface_target=" + interface_target); - params.push("source_text=" + text_source_interface); - params.push("target_text=" + text_target_interface); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_link=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("id_link=" + id_link); + params.push("interface_source=" + interface_source); + params.push("interface_target=" + interface_target); + params.push("source_text=" + text_source_interface); + params.push("target_text=" + text_target_interface); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $(".edit_icon_progress_" + row_index).css("display", "none"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $(".edit_icon_progress_" + row_index).css("display", "none"); - if (data['correct']) { - $(".edit_icon_correct_" + row_index).css("display", ""); + if (data["correct"]) { + $(".edit_icon_correct_" + row_index).css("display", ""); - $("select[name='interface_source_" + row_index + "'] option[value='" + interface_source + "']") - .prop("selected", true); - $("select[name='interface_target_" + row_index + "'] option[value='" + interface_target + "']") - .prop("selected", true); + $( + "select[name='interface_source_" + + row_index + + "'] option[value='" + + interface_source + + "']" + ).prop("selected", true); + $( + "select[name='interface_target_" + + row_index + + "'] option[value='" + + interface_target + + "']" + ).prop("selected", true); - var id = ""; - var index = -1; - $.each(graph.links, function (j, link) { - if (link['id_db'] == id_link) { - index = j; - id = String(id_link); - } - }); + var id = ""; + var index = -1; + $.each(graph.links, function(j, link) { + if (link["id_db"] == id_link) { + index = j; + id = String(id_link); + } + }); - delete_link_from_id(index); + delete_link_from_id(index); - var temp_link = {}; - temp_link["status_start"] = "0"; - temp_link["status_end"] = "0"; - - temp_link["id_db"] = String(data['id_db_link']); - - if (data['type_source'] == 1) { - temp_link["arrow_start"] = "module"; - temp_link["id_module_start"] = interface_source; - temp_link["status_start"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link["arrow_start"] = ""; - temp_link["id_agent_start"] = interface_source; - temp_link["id_module_start"] = 0; - } - if (data['type_target'] == 1) { - temp_link["arrow_end"] = "module"; - temp_link["id_module_end"] = interface_target; - temp_link["status_end"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link["arrow_end"] = ""; - temp_link["id_agent_end"] = interface_target; - temp_link["id_module_end"] = 0; - } - - temp_link["text_start"] = data["text_start"]; - temp_link["text_end"] = data["text_end"]; + var temp_link = {}; + temp_link["status_start"] = "0"; + temp_link["status_end"] = "0"; - $.each(graph.nodes, function (k, node) { - if (node['id_agent'] == data['id_db_target']) { - temp_link["target"] = graph.nodes[k]; - } - if (node['id_agent'] == data['id_db_source']) { - temp_link["source"] = graph.nodes[k]; - } - }); + temp_link["id_db"] = String(data["id_db_link"]); - add_new_link(temp_link); + if (data["type_source"] == 1) { + temp_link["arrow_start"] = "module"; + temp_link["id_module_start"] = interface_source; + temp_link["status_start"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_start"] = ""; + temp_link["id_agent_start"] = interface_source; + temp_link["id_module_start"] = 0; + } + if (data["type_target"] == 1) { + temp_link["arrow_end"] = "module"; + temp_link["id_module_end"] = interface_target; + temp_link["status_end"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_end"] = ""; + temp_link["id_agent_end"] = interface_target; + temp_link["id_module_end"] = 0; + } - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + temp_link["text_start"] = data["text_start"]; + temp_link["text_end"] = data["text_end"]; - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + $.each(graph.nodes, function(k, node) { + if (node["id_agent"] == data["id_db_target"]) { + temp_link["target"] = graph.nodes[k]; + } + if (node["id_agent"] == data["id_db_source"]) { + temp_link["source"] = graph.nodes[k]; + } + }); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + add_new_link(temp_link); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - else { - $(".edit_icon_fail_" + row_index).css("display", ""); - } - } - }); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); + + force + .nodes(graph.nodes) + .links(graph.links) + .start(); + + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); + + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } else { + $(".edit_icon_fail_" + row_index).css("display", ""); + } + } + }); } function delete_link_from_id(index) { - graph.links.splice(index, 1); + graph.links.splice(index, 1); } function add_new_link(new_link) { - graph.links.push(new_link); + graph.links.push(new_link); } -function move_to_networkmap (node) { - var params = []; - params.push("get_networkmap_from_fictional=1"); - params.push("id=" + node.id_db); - params.push("id_map=" + node.map_id); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); +function move_to_networkmap(node) { + var params = []; + params.push("get_networkmap_from_fictional=1"); + params.push("id=" + node.id_db); + params.push("id_map=" + node.map_id); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax ({ - data: params.join ("&"), - dataType: 'json', - type: 'POST', - url: action="ajax.php", - success: function (data) { - if (data['correct']) { - window.location="index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + data['id_networkmap']; - } - else { - edit_node(node, true); - } - } - }); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + window.location = + "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + + data["id_networkmap"]; + } else { + edit_node(node, true); + } + } + }); } - function edit_node(data_node, dblClick) { - if (enterprise_installed) { - var flag_edit_node = true; - var edit_node = null + if (enterprise_installed) { + var flag_edit_node = true; + var edit_node = null; - //Only select one node - var selection = d3.selectAll('.node_selected'); + //Only select one node + var selection = d3.selectAll(".node_selected"); - if (selection[0].length == 1) { - edit_node = selection[0].pop(); - } - else if (selection[0].length > 1) { - edit_node = selection[0].pop(); - } - else if (dblClick) { - edit_node = d3.select("#id_node_" + data_node['id'] + networkmap_id); - edit_node = edit_node[0][0]; - } - else { - flag_edit_node = false; - } + if (selection[0].length == 1) { + edit_node = selection[0].pop(); + } else if (selection[0].length > 1) { + edit_node = selection[0].pop(); + } else if (dblClick) { + edit_node = d3.select("#id_node_" + data_node["id"] + networkmap_id); + edit_node = edit_node[0][0]; + } else { + flag_edit_node = false; + } - if (flag_edit_node) { - d3.selectAll('.node_selected') - .classed("node_selected", false); - d3.select(edit_node) - .classed("node_selected", true); + if (flag_edit_node) { + d3.selectAll(".node_selected").classed("node_selected", false); + d3.select(edit_node).classed("node_selected", true); - id = d3.select(edit_node).attr("id").replace("id_node_", ""); - id_networkmap_lenght = networkmap_id.toString().length; - id_node_length = id.length - id_networkmap_lenght; - id = id.substring(0, id_node_length); - node_selected = graph.nodes[id]; + id = d3 + .select(edit_node) + .attr("id") + .replace("id_node_", ""); + id_networkmap_lenght = networkmap_id.toString().length; + id_node_length = id.length - id_networkmap_lenght; + id = id.substring(0, id_node_length); + node_selected = graph.nodes[id]; - selected_links = get_relations(node_selected); + selected_links = get_relations(node_selected); - $("select[name='shape'] option[value='" + node_selected.shape + "']") - .prop("selected", true); - $("select[name='shape']").attr("onchange", - "javascript: change_shape(" + node_selected.id_db + ");"); - $("#node_options-fictional_node_update_button-1 input") - .attr("onclick", "update_fictional_node(" + node_selected.id_db + ");"); + $( + "select[name='shape'] option[value='" + node_selected.shape + "']" + ).prop("selected", true); + $("select[name='shape']").attr( + "onchange", + "javascript: change_shape(" + node_selected.id_db + ");" + ); + $("#node_options-fictional_node_update_button-1 input").attr( + "onclick", + "update_fictional_node(" + node_selected.id_db + ");" + ); - $("#node_options-node_name-2 input") - .attr("onclick", "update_node_name(" + node_selected.id_db + ");"); + $("#node_options-node_name-2 input").attr( + "onclick", + "update_node_name(" + node_selected.id_db + ");" + ); - var params = []; - params.push("get_agent_info=1"); - params.push("id_agent=" + node_selected["id_agent"]); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("get_agent_info=1"); + params.push("id_agent=" + node_selected["id_agent"]); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $("#node_details-0-1").html('' + data['alias'] + ''); - - var addresses = ""; - if (data['adressess'] instanceof Array) { - for (var i; i < data['adressess'].length; i++) { - addresses += data['adressess'][i] + "
"; - } - } else { - for (address in data['adressess']) { - addresses += address + "
"; - } - } - $("#node_details-1-1").html(addresses); - $("#node_details-2-1").html(data["os"]); - $("#node_details-3-1").html(data["group"]); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#node_details-0-1").html( + '' + + data["alias"] + + "" + ); - $('[aria-describedby=dialog_node_edit]').css({ 'top': '200px' }); - $('#foot').css({ 'top': parseInt($("[aria-describedby=dialog_node_edit]").css('height') + $("[aria-describedby=dialog_node_edit]").css('top')), 'position': 'relative' }); + var addresses = ""; + if (data["adressess"] instanceof Array) { + for (var i; i < data["adressess"].length; i++) { + addresses += data["adressess"][i] + "
"; + } + } else { + for (address in data["adressess"]) { + addresses += address + "
"; + } + } + $("#node_details-1-1").html(addresses); + $("#node_details-2-1").html(data["os"]); + $("#node_details-3-1").html(data["group"]); - get_interface_data_to_table(node_selected, selected_links); - } - }); + $("[aria-describedby=dialog_node_edit]").css({ top: "200px" }); + $("#foot").css({ + top: parseInt( + $("[aria-describedby=dialog_node_edit]").css("height") + + $("[aria-describedby=dialog_node_edit]").css("top") + ), + position: "relative" + }); - $("#dialog_node_edit") - .dialog("option", "title", - dialog_node_edit_title.replace("%s", ellipsize(node_selected['text'], 40))); // It doesn't eval the possible XSS so it's ok - $("#dialog_node_edit").dialog("open"); + get_interface_data_to_table(node_selected, selected_links); + } + }); - if (node_selected.id_agent == undefined || node_selected.id_agent == -2) { - //Fictional node - $("#node_options-fictional_node_name") - .css("display", ""); - $("input[name='edit_name_fictional_node']") - .val(node_selected.text); // It doesn't eval the possible XSS so it's ok - $("#node_options-fictional_node_networkmap_link") - .css("display", ""); - $("#edit_networkmap_to_link") - .val(node_selected.networkmap_id); - $("#node_options-fictional_node_update_button") - .css("display", ""); - $("#node_options-node_name") - .css("display", "none"); - $("#node_options-node_update_button") - .css("display", "none"); - } - else { - $("input[name='edit_name_node']") - .val(node_selected.text); // It doesn't eval the possible XSS so it's ok - $("#node_options-fictional_node_name") - .css("display", "none"); - $("#node_options-fictional_node_networkmap_link") - .css("display", "none"); - $("#node_options-fictional_node_update_button") - .css("display", "none"); - $("#node_options-node_name") - .css("display", ""); - } + $("#dialog_node_edit").dialog( + "option", + "title", + dialog_node_edit_title.replace( + "%s", + ellipsize(node_selected["text"], 40) + ) + ); // It doesn't eval the possible XSS so it's ok + $("#dialog_node_edit").dialog("open"); - //Clean - $("#relations_table .relation_link_row").remove(); - //Show the no relations - $("#relations_table-loading").css('display', 'none'); - $("#relations_table-no_relations").css('display', ''); - } - } + if (node_selected.id_agent == undefined || node_selected.id_agent == -2) { + //Fictional node + $("#node_options-fictional_node_name").css("display", ""); + $("input[name='edit_name_fictional_node']").val(node_selected.text); // It doesn't eval the possible XSS so it's ok + $("#node_options-fictional_node_networkmap_link").css("display", ""); + $("#edit_networkmap_to_link").val(node_selected.networkmap_id); + $("#node_options-fictional_node_update_button").css("display", ""); + $("#node_options-node_name").css("display", "none"); + $("#node_options-node_update_button").css("display", "none"); + } else { + $("input[name='edit_name_node']").val(node_selected.text); // It doesn't eval the possible XSS so it's ok + $("#node_options-fictional_node_name").css("display", "none"); + $("#node_options-fictional_node_networkmap_link").css( + "display", + "none" + ); + $("#node_options-fictional_node_update_button").css("display", "none"); + $("#node_options-node_name").css("display", ""); + } + + //Clean + $("#relations_table .relation_link_row").remove(); + //Show the no relations + $("#relations_table-loading").css("display", "none"); + $("#relations_table-no_relations").css("display", ""); + } + } } function get_interface_data_to_table(node_selected, selected_links) { - $("#interface_information").find("tr:gt(0)").remove(); + $("#interface_information") + .find("tr:gt(0)") + .remove(); - var params = []; - params.push("get_interface_info=1"); - params.push("id_agent=" + node_selected["id_agent"]); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data.length == 0) { - $("#interface_information").find('tbody') - .append($('').html("

It has no interface to display

")); - } - else { - jQuery.each(data, function (j, interface) { - if (interface['graph'] == "") { - var interf_graph = "--"; - } - else { - var interf_graph = interface['graph']; - } - $("#interface_information").find('tbody') - .append($('') - .append($('') - .html(interface['name']) - ) - .append($('') - .html(interface['status']) - ) - .append($('') - .html(interf_graph) - ) - .append($('') - .html(interface['ip']) - ) - .append($('') - .html(interface['mac']) - ) - ); - }); - } - load_interfaces(selected_links); - } - }); + var params = []; + params.push("get_interface_info=1"); + params.push("id_agent=" + node_selected["id_agent"]); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data.length == 0) { + $("#interface_information") + .find("tbody") + .append( + $("").html( + '

It has no interface to display

' + ) + ); + } else { + jQuery.each(data, function(j, interface) { + if (interface["graph"] == "") { + var interf_graph = "--"; + } else { + var interf_graph = interface["graph"]; + } + $("#interface_information") + .find("tbody") + .append( + $("") + .append($("").html(interface["name"])) + .append($("").html(interface["status"])) + .append($("").html(interf_graph)) + .append($("").html(interface["ip"])) + .append($("").html(interface["mac"])) + ); + }); + } + load_interfaces(selected_links); + } + }); } function load_interfaces(selected_links) { - //Clean - $("#relations_table .relation_link_row").remove(); - //Show the no relations - $("#relations_table-loading").css('display', 'none'); - $("#relations_table-no_relations").css('display', ''); + //Clean + $("#relations_table .relation_link_row").remove(); + //Show the no relations + $("#relations_table-loading").css("display", "none"); + $("#relations_table-no_relations").css("display", ""); - jQuery.each(selected_links, function (i, link_each) { - $("#relations_table-no_relations").css('display', 'none'); - $("#relations_table-loading").css('display', ''); + jQuery.each(selected_links, function(i, link_each) { + $("#relations_table-no_relations").css("display", "none"); + $("#relations_table-loading").css("display", ""); - var template_relation_row = $("#relations_table-template_row") - .clone(); + var template_relation_row = $("#relations_table-template_row").clone(); - $(template_relation_row).css('display', ''); - $(template_relation_row).attr('class', 'relation_link_row'); + $(template_relation_row).css("display", ""); + $(template_relation_row).attr("class", "relation_link_row"); - $("select[name='interface_source']", template_relation_row) - .attr('name', "interface_source_" + i) - .attr('id', "interface_source_" + i); - $("select[name='interface_target']", template_relation_row) - .attr('name', "interface_target_" + i) - .attr('id', "interface_target_" + i); - $(".edit_icon_progress", template_relation_row) - .attr('class', "edit_icon_progress_" + i); - $(".edit_icon", template_relation_row) - .attr('class', "edit_icon_" + i); - $(".edit_icon_correct", template_relation_row) - .attr('class', "edit_icon_correct_" + i); - $(".edit_icon_fail", template_relation_row) - .attr('class', "edit_icon_fail_" + i); - $(".edit_icon_link", template_relation_row) - .attr('class', "edit_icon_link_" + i) - .click(function () { - update_link(i, link_each.id_db); - } - ); + $("select[name='interface_source']", template_relation_row) + .attr("name", "interface_source_" + i) + .attr("id", "interface_source_" + i); + $("select[name='interface_target']", template_relation_row) + .attr("name", "interface_target_" + i) + .attr("id", "interface_target_" + i); + $(".edit_icon_progress", template_relation_row).attr( + "class", + "edit_icon_progress_" + i + ); + $(".edit_icon", template_relation_row).attr("class", "edit_icon_" + i); + $(".edit_icon_correct", template_relation_row).attr( + "class", + "edit_icon_correct_" + i + ); + $(".edit_icon_fail", template_relation_row).attr( + "class", + "edit_icon_fail_" + i + ); + $(".edit_icon_link", template_relation_row) + .attr("class", "edit_icon_link_" + i) + .click(function() { + update_link(i, link_each.id_db); + }); - var params3 = []; - params3.push("get_intefaces=1"); - params3.push("id_agent_target=" + link_each.target.id_agent); - params3.push("id_agent_source=" + link_each.source.id_agent); - params3.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params3 = []; + params3.push("get_intefaces=1"); + params3.push("id_agent_target=" + link_each.target.id_agent); + params3.push("id_agent_source=" + link_each.source.id_agent); + params3.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params3.join("&"), - dataType: 'json', - type: 'POST', - async: true, - cache: false, - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("select[name='interface_target_" + i + "']", template_relation_row).empty(); - $("select[name='interface_target_" + i + "']", template_relation_row).append(''); + jQuery.ajax({ + data: params3.join("&"), + dataType: "json", + type: "POST", + async: true, + cache: false, + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).empty(); + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).append( + '' + ); - $("select[name='interface_source_" + i + "']", template_relation_row).empty(); - $("select[name='interface_source_" + i + "']", template_relation_row).append(''); - jQuery.each(data['target_interfaces'], function (j, interface) { - $("select[name='interface_target_" + i + "']", template_relation_row) - .append($("' + ); + jQuery.each(data["target_interfaces"], function(j, interface) { + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).append( + $("' + ); + jQuery.each(data.interfaces_parent, function(i, interface) { + $("#interface_target_select").append( + '" + ); + }); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - var parent_name = data_parent.text; - var child_name = child_data.text; - $('#label-node_source_interface').text(child_name); - $('#label-node_target_interface').text(parent_name); + $("#interface_source_select").empty(); + $("#interface_source_select").append( + '' + ); + jQuery.each(data.interfaces_child, function(i, interface) { + $("#interface_source_select").append( + '" + ); + }); - $("#interface_target_select").empty(); - $('#interface_target_select').append(''); - jQuery.each(data.interfaces_parent, function (i, interface) { - $('#interface_target_select').append(''); - }); - - $("#interface_source_select").empty(); - $('#interface_source_select').append(''); - jQuery.each(data.interfaces_child, function (i, interface) { - $('#interface_source_select').append(''); - }); - - $('#dialog_interface_link').dialog("open"); - } - }); - }); + $("#dialog_interface_link").dialog("open"); + } + }); + }); } function add_interface_link_js() { - cancel_set_parent_interface(); - $('#dialog_interface_link').dialog("close"); + cancel_set_parent_interface(); + $("#dialog_interface_link").dialog("close"); - source_value = $('#interface_source_select').val(); - source_text = $('#interface_source_select').find('option:selected').text(); - target_value = $('#interface_target_select').val(); - target_text = $('#interface_target_select').find('option:selected').text(); + source_value = $("#interface_source_select").val(); + source_text = $("#interface_source_select") + .find("option:selected") + .text(); + target_value = $("#interface_target_select").val(); + target_text = $("#interface_target_select") + .find("option:selected") + .text(); - var params = []; - params.push("add_interface_relation=1"); - params.push("id=" + networkmap_id); - params.push("source_value=" + source_value); - params.push("target_value=" + target_value); - params.push("source_text=" + source_text); - params.push("target_text=" + target_text); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("add_interface_relation=1"); + params.push("id=" + networkmap_id); + params.push("source_value=" + source_value); + params.push("target_value=" + target_value); + params.push("source_text=" + source_text); + params.push("target_text=" + target_text); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - var temp_link = {}; - temp_link['status_start'] = "0"; - temp_link['status_end'] = "0"; - - temp_link['id_db'] = data['id_db_link']; - - if (data['type_source'] == 1) { - temp_link['arrow_start'] = "module"; - temp_link['id_module_start'] = source_value; - temp_link["status_start"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link['arrow_start'] = ""; - temp_link['id_agent_start'] = source_value; - temp_link['id_module_start'] = 0; - } - if (data['type_target'] == 1) { - temp_link['arrow_end'] = "module"; - temp_link['id_module_end'] = target_value; - temp_link["status_end"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link['arrow_end'] = ""; - temp_link['id_agent_end'] = target_value; - temp_link['id_module_end'] = 0; - } + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + var temp_link = {}; + temp_link["status_start"] = "0"; + temp_link["status_end"] = "0"; - temp_link['text_start'] = data['text_start']; - temp_link['text_end'] = data['text_end']; + temp_link["id_db"] = data["id_db_link"]; - jQuery.each(graph.nodes, function (j, node) { - if (node['id_agent'] == data['id_db_target']) { - temp_link['target'] = graph.nodes[j]; - } - if (node['id_agent'] == data['id_db_source']) { - temp_link['source'] = graph.nodes[j]; - } - }); - - graph.links.push(temp_link); - - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - } - }); + if (data["type_source"] == 1) { + temp_link["arrow_start"] = "module"; + temp_link["id_module_start"] = source_value; + temp_link["status_start"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_start"] = ""; + temp_link["id_agent_start"] = source_value; + temp_link["id_module_start"] = 0; + } + if (data["type_target"] == 1) { + temp_link["arrow_end"] = "module"; + temp_link["id_module_end"] = target_value; + temp_link["status_end"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_end"] = ""; + temp_link["id_agent_end"] = target_value; + temp_link["id_module_end"] = 0; + } + + temp_link["text_start"] = data["text_start"]; + temp_link["text_end"] = data["text_end"]; + + jQuery.each(graph.nodes, function(j, node) { + if (node["id_agent"] == data["id_db_target"]) { + temp_link["target"] = graph.nodes[j]; + } + if (node["id_agent"] == data["id_db_source"]) { + temp_link["source"] = graph.nodes[j]; + } + }); + + graph.links.push(temp_link); + + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + } + }); } function refresh_holding_area() { - holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); - holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); + holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); + holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); - var pos_x = parseInt(holding_pos_x) + parseInt(node_radius); - var pos_y = parseInt(holding_pos_y) + parseInt(node_radius); - if (enterprise_installed) { - $('#holding_spinner_' + networkmap_id).css("display", ""); - var params = []; - params.push("refresh_holding_area=1"); - params.push("id=" + networkmap_id); - params.push("x=" + pos_x); - params.push("y=" + pos_y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - window.holding_area = data['holding_area']; + var pos_x = parseInt(holding_pos_x) + parseInt(node_radius); + var pos_y = parseInt(holding_pos_y) + parseInt(node_radius); + if (enterprise_installed) { + $("#holding_spinner_" + networkmap_id).css("display", ""); + var params = []; + params.push("refresh_holding_area=1"); + params.push("id=" + networkmap_id); + params.push("x=" + pos_x); + params.push("y=" + pos_y); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + window.holding_area = data["holding_area"]; - jQuery.each(holding_area.nodes, function (i, node) { - var temp_node = {}; + jQuery.each(holding_area.nodes, function(i, node) { + var temp_node = {}; - temp_node['id'] = graph.nodes.length; - holding_area.nodes[i]['id'] = temp_node['id']; + temp_node["id"] = graph.nodes.length; + holding_area.nodes[i]["id"] = temp_node["id"]; - temp_node['id_db'] = node['id_db']; - temp_node['id_agent'] = node['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = node['x']; - temp_node['y'] = node['y']; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['state'] = 'holding_area'; - temp_node['type'] = 0; - temp_node['color'] = node['color']; - temp_node['shape'] = node['shape']; - temp_node['text'] = node['text']; - temp_node['image_url'] = node['image_url']; - temp_node['image_width'] = node['image_width']; - temp_node['image_height'] = node['image_width']; - temp_node['deleted'] = false; + temp_node["id_db"] = node["id_db"]; + temp_node["id_agent"] = node["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = node["x"]; + temp_node["y"] = node["y"]; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["state"] = "holding_area"; + temp_node["type"] = 0; + temp_node["color"] = node["color"]; + temp_node["shape"] = node["shape"]; + temp_node["text"] = node["text"]; + temp_node["image_url"] = node["image_url"]; + temp_node["image_width"] = node["image_width"]; + temp_node["image_height"] = node["image_width"]; + temp_node["deleted"] = false; - graph.nodes.push(temp_node); - }); + graph.nodes.push(temp_node); + }); - jQuery.each(graph.links, function (j, g_link) { + jQuery.each(graph.links, function(j, g_link) { + for (var i = 0; i < holding_area.links.length; i++) { + if (g_link["id_db"] == holding_area.links[i]["id_db"]) { + holding_area.links.splice(i, 1); + } + } + }); - for (var i = 0; i < holding_area.links.length; i++) { - if (g_link['id_db'] == holding_area.links[i]['id_db']) { - holding_area.links.splice(i, 1); - } - } + jQuery.each(holding_area.links, function(i, link) { + var temp_link = {}; + temp_link["id_db"] = link["id_db"]; + temp_link["arrow_start"] = link["arrow_start"]; + temp_link["arrow_end"] = link["arrow_end"]; + temp_link["status_start"] = link["status_start"]; + temp_link["status_end"] = link["status_end"]; + temp_link["id_module_start"] = link["id_module_start"]; + temp_link["id_module_end"] = link["id_module_end"]; + temp_link["text_start"] = link["text_start"]; + temp_link["text_end"] = link["text_end"]; - }); + //Re-hook the links to nodes + jQuery.each(graph.nodes, function(j, node) { + if (node["id_agent"] == link["id_agent_end"]) { + temp_link["target"] = graph.nodes[j]; + } + if (node["id_agent"] == link["id_agent_start"]) { + temp_link["source"] = graph.nodes[j]; + } + }); - jQuery.each(holding_area.links, function (i, link) { - var temp_link = {}; - temp_link['id_db'] = link['id_db']; - temp_link['arrow_start'] = link['arrow_start']; - temp_link['arrow_end'] = link['arrow_end']; - temp_link['status_start'] = link['status_start']; - temp_link['status_end'] = link['status_end']; - temp_link['id_module_start'] = link['id_module_start']; - temp_link['id_module_end'] = link['id_module_end']; - temp_link['text_start'] = link['text_start']; - temp_link['text_end'] = link['text_end']; + graph.links.push(temp_link); + }); - //Re-hook the links to nodes - jQuery.each(graph.nodes, function (j, node) { - if (node['id_agent'] == link['id_agent_end']) { - temp_link['target'] = graph.nodes[j]; - } - if (node['id_agent'] == link['id_agent_start']) { - temp_link['source'] = graph.nodes[j]; - } - }); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - graph.links.push(temp_link); - }); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); - - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - - $('#holding_spinner_' + networkmap_id).css("display", "none"); - } - }, - error: function () { - $('#holding_spinner_' + networkmap_id).css("display", "none"); - } - }); - } + $("#holding_spinner_" + networkmap_id).css("display", "none"); + } + }, + error: function() { + $("#holding_spinner_" + networkmap_id).css("display", "none"); + } + }); + } } -function restart_map () { - $("
").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [ - { - text: ok_button, - click: function () { - $(this).dialog("close"); - proceed_to_restart_map(); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); - } - } - ] - }); +function restart_map() { + $( + "
" + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + proceed_to_restart_map(); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_confirm_text = "
"; - dialog_confirm_text = dialog_confirm_text + "
"; - dialog_confirm_text = dialog_confirm_text + "

" + warning_message + "

"; - dialog_confirm_text = dialog_confirm_text + "

" + message_to_confirm + "

"; - dialog_confirm_text = dialog_confirm_text + "
"; - - $('#restart_map_confirm').html(dialog_confirm_text); - $('#restart_map_confirm').dialog('open'); + var dialog_confirm_text = "
"; + dialog_confirm_text = + dialog_confirm_text + + "
"; + dialog_confirm_text = + dialog_confirm_text + + "

" + + warning_message + + "

"; + dialog_confirm_text = + dialog_confirm_text + + "

" + + message_to_confirm + + "

"; + dialog_confirm_text = dialog_confirm_text + "
"; + + $("#restart_map_confirm").html(dialog_confirm_text); + $("#restart_map_confirm").dialog("open"); } -function proceed_to_restart_map () { - $("
").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 450, - buttons: [ - { - text: ok_button, - click: function () { - $(this).dialog("close"); - var new_elements = []; - new_elements[0] = $("#text-name").val(); - new_elements[1] = $("#id_group").val(); - new_elements[2] = $("#text-node_radius").val(); - new_elements[3] = $("#textarea_description").val(); - new_elements[4] = $("input[name=source]:checked").val(); - if (new_elements[4] == 'group') { - new_elements[5] = $("#checkbox-dont_show_subgroups").is(':checked'); - } - else if (new_elements[4] == 'recon_task') { - new_elements[5] = $("#recon_task_id").val(); - } - else { - new_elements[5] = $("#text-ip_mask").val(); - } - new_elements[6] = $("#method").val(); - new_elements[7] = $("#text-pos_x").val(); - new_elements[8] = $("#text-pos_y").val(); - new_elements[9] = $("#text-scale_z").val(); - new_elements[10] = $("#text-node_sep").val(); - new_elements[11] = $("#text-mindist").val(); - new_elements[12] = $("#text-rank_sep").val(); - new_elements[13] = $("#text-kval").val(); - reset_map_from_form(new_elements); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); - } - } - ] - }); +function proceed_to_restart_map() { + $( + "
" + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 450, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + var new_elements = []; + new_elements[0] = $("#text-name").val(); + new_elements[1] = $("#id_group").val(); + new_elements[2] = $("#text-node_radius").val(); + new_elements[3] = $("#textarea_description").val(); + new_elements[4] = $("input[name=source]:checked").val(); + if (new_elements[4] == "group") { + new_elements[5] = $("#checkbox-dont_show_subgroups").is(":checked"); + } else if (new_elements[4] == "recon_task") { + new_elements[5] = $("#recon_task_id").val(); + } else { + new_elements[5] = $("#text-ip_mask").val(); + } + new_elements[6] = $("#method").val(); + new_elements[7] = $("#text-pos_x").val(); + new_elements[8] = $("#text-pos_y").val(); + new_elements[9] = $("#text-scale_z").val(); + new_elements[10] = $("#text-node_sep").val(); + new_elements[11] = $("#text-mindist").val(); + new_elements[12] = $("#text-rank_sep").val(); + new_elements[13] = $("#text-kval").val(); + reset_map_from_form(new_elements); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var params = []; - params.push("get_reset_map_form=1"); - params.push("map_id=" + networkmap_id); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'html', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $('#restart_map_form').html(data); - $('#restart_map_form').dialog('open'); - } - }); + var params = []; + params.push("get_reset_map_form=1"); + params.push("map_id=" + networkmap_id); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "html", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#restart_map_form").html(data); + $("#restart_map_form").dialog("open"); + } + }); } -function reset_map_from_form (new_elements) { - var params = []; - params.push("reset_map=1"); - params.push("map_id=" + networkmap_id); - params.push("elems[]=" + new_elements) - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (!data['error']) { - window.location = "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + networkmap_id; - } - } - }); +function reset_map_from_form(new_elements) { + var params = []; + params.push("reset_map=1"); + params.push("map_id=" + networkmap_id); + params.push("elems[]=" + new_elements); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (!data["error"]) { + window.location = + "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + + networkmap_id; + } + } + }); } function set_parent(parent_data) { - if (enterprise_installed) { - var selection = d3.selectAll('.node_children'); + if (enterprise_installed) { + var selection = d3.selectAll(".node_children"); - count = selection.size(); + count = selection.size(); - selection - .each(function (child_data) { - //Check if exist the link as - // repeat: - // old link: node1 (parent) - node2 (child) - // new link: node1 (parent) - node2 (child) - // - // swapped: - // old link: node1 (child) - node2 (parent) - // new link: node2 (child) - node1 (parent) + selection.each(function(child_data) { + //Check if exist the link as + // repeat: + // old link: node1 (parent) - node2 (child) + // new link: node1 (parent) - node2 (child) + // + // swapped: + // old link: node1 (child) - node2 (parent) + // new link: node2 (child) - node1 (parent) - var repeat = false; - jQuery.each(graph.links, function (i, link_item) { + var repeat = false; + jQuery.each(graph.links, function(i, link_item) { + if ( + link_item.source_id_db == child_data.id_db && + link_item.target_id_db == parent_data.id_db + ) { + repeat = true; + } - if ((link_item.source_id_db == child_data.id_db) && - (link_item.target_id_db == parent_data.id_db)) { + if ( + link_item.source_id_db == parent_data.id_db && + link_item.target_id_db == child_data.id_db + ) { + repeat = true; + } + }); - repeat = true; - } + if (repeat) { + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); - if ((link_item.source_id_db == parent_data.id_db) && - (link_item.target_id_db == child_data.id_db)) { + cancel_set_parent(); + cancel_set_parent_interface(); + } - repeat = true; - } + return; //Break + } - }); + var params = []; + params.push("set_relationship=1"); + params.push("id=" + networkmap_id); + params.push("child=" + child_data.id_db); + params.push("parent=" + parent_data.id_db); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + //Add the relationship and paint + item = {}; + item["arrow_start"] = ""; + item["arrow_end"] = ""; + item["status_start"] = ""; + item["status_end"] = ""; + item["text_start"] = ""; + item["text_end"] = ""; + item["id_module_start"] = 0; + item["id_module_end"] = 0; + item["id_db"] = data["id"]; + item["source_id_db"] = child_data.id_db; + item["target_id_db"] = parent_data.id; + item["id_agent_start"] = graph.nodes[child_data.id]["id_agent"]; + item["id_agent_end"] = graph.nodes[parent_data.id]["id_agent"]; + item["target"] = graph.nodes[parent_data.id]; + item["source"] = graph.nodes[child_data.id]; - if (repeat) { - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); + graph.links.push(item); + } + //update_networkmap(); + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); - cancel_set_parent(); - cancel_set_parent_interface(); - } - - return; //Break - } - - var params = []; - params.push("set_relationship=1"); - params.push("id=" + networkmap_id); - params.push("child=" + child_data.id_db); - params.push("parent=" + parent_data.id_db); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - //Add the relationship and paint - item = {}; - item['arrow_start'] = ''; - item['arrow_end'] = ''; - item['status_start'] = ''; - item['status_end'] = ''; - item['text_start'] = ''; - item['text_end'] = ''; - item['id_module_start'] = 0; - item['id_module_end'] = 0; - item['id_db'] = data['id']; - item['source_id_db'] = child_data.id_db; - item['target_id_db'] = parent_data.id; - item['id_agent_start'] = graph.nodes[child_data.id]['id_agent']; - item['id_agent_end'] = graph.nodes[parent_data.id]['id_agent']; - item['target'] = graph.nodes[parent_data.id]; - item['source'] = graph.nodes[child_data.id]; - - graph.links.push(item); - } - //update_networkmap(); - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); - - cancel_set_parent(); - cancel_set_parent_interface(); - } - } - }); - } - ); - } + cancel_set_parent(); + cancel_set_parent_interface(); + } + } + }); + }); + } } function cancel_set_parent_interface() { - var selection = d3.selectAll('.node_children'); + var selection = d3.selectAll(".node_children"); - selection - .each(function (d) { - d3.select("#id_node_" + d.id + networkmap_id) - .classed("node_selected", true) - .classed("node_children", false); - } - ); + selection.each(function(d) { + d3.select("#id_node_" + d.id + networkmap_id) + .classed("node_selected", true) + .classed("node_children", false); + }); - flag_setting_interface_link_running = false; + flag_setting_interface_link_running = false; } function cancel_set_parent() { - var selection = d3.selectAll('.node_children'); + var selection = d3.selectAll(".node_children"); - selection - .each(function (d) { - d3.select("#id_node_" + d.id + networkmap_id) - .classed("node_selected", true) - .classed("node_children", false); - } - ); + selection.each(function(d) { + d3.select("#id_node_" + d.id + networkmap_id) + .classed("node_selected", true) + .classed("node_children", false); + }); - flag_setting_relationship_running = false; + flag_setting_relationship_running = false; } //////////////////////////////////////////////////////////////////////// // OWN CODE FOR TO DRAG //////////////////////////////////////////////////////////////////////// function init_drag_and_drop() { - window.dragables = svg.selectAll(".dragable_node"); + window.dragables = svg.selectAll(".dragable_node"); - window.drag_start = [0, 0]; - window.drag_end = [0, 0]; - window.drag = d3.behavior.drag() - .on("dragstart", function () { - if (d3.event.sourceEvent.button == 2) - return; + window.drag_start = [0, 0]; + window.drag_end = [0, 0]; + window.drag = d3.behavior + .drag() + .on("dragstart", function() { + if (d3.event.sourceEvent.button == 2) return; - mouse_coords = d3.mouse(this); - drag_start[0] = drag_end[0] = mouse_coords[0]; - drag_start[1] = drag_end[1] = mouse_coords[1]; + mouse_coords = d3.mouse(this); + drag_start[0] = drag_end[0] = mouse_coords[0]; + drag_start[1] = drag_end[1] = mouse_coords[1]; - flag_drag_running = true; + flag_drag_running = true; - d3.event.sourceEvent.stopPropagation(); - }) - .on("dragend", function (d, i) { - if (d3.event.sourceEvent.button == 2) - return; + d3.event.sourceEvent.stopPropagation(); + }) + .on("dragend", function(d, i) { + if (d3.event.sourceEvent.button == 2) return; - flag_drag_running = false; + flag_drag_running = false; - var selection = d3.selectAll('.node_selected'); + var selection = d3.selectAll(".node_selected"); - if (enterprise_installed) { - holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); - holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); - delete d.raw_text; - selection - .each(function (d) { - var params = []; - params.push("update_node=1"); - params.push("node=" + JSON.stringify(d)); - params.push("x=" + holding_pos_x); - params.push("y=" + holding_pos_y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (d.state == 'holding_area') { - //It is out the holding area - if (data['state'] == "") { - //Remove the style of nodes and links - //in holding area - d3.select("#id_node_" + d.id + networkmap_id) - .classed("holding_area", false); - d3.select(".source_" + d.id + networkmap_id) - .classed("holding_area_link", false); - d3.select(".target_" + d.id + networkmap_id) - .classed("holding_area_link", false); - graph.nodes[d.id].state = ""; - } - } - } - }); - }); - } - else { - var params = []; - params.push("update_node_alert=1"); - params.push("map_id=" + networkmap_id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#open_version_dialog").dialog(); - } - } - }); - } + if (enterprise_installed) { + holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); + holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); + delete d.raw_text; + selection.each(function(d) { + var params = []; + params.push("update_node=1"); + params.push("node=" + JSON.stringify(d)); + params.push("x=" + holding_pos_x); + params.push("y=" + holding_pos_y); + params.push( + "page=enterprise/operation/agentes/pandora_networkmap.view" + ); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (d.state == "holding_area") { + //It is out the holding area + if (data["state"] == "") { + //Remove the style of nodes and links + //in holding area + d3.select("#id_node_" + d.id + networkmap_id).classed( + "holding_area", + false + ); + d3.select(".source_" + d.id + networkmap_id).classed( + "holding_area_link", + false + ); + d3.select(".target_" + d.id + networkmap_id).classed( + "holding_area_link", + false + ); + graph.nodes[d.id].state = ""; + } + } + } + }); + }); + } else { + var params = []; + params.push("update_node_alert=1"); + params.push("map_id=" + networkmap_id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#open_version_dialog").dialog(); + } + } + }); + } - d3.event.sourceEvent.stopPropagation(); - }) - .on("drag", function (d, i) { - if (d3.event.sourceEvent.button == 2) - return; + d3.event.sourceEvent.stopPropagation(); + }) + .on("drag", function(d, i) { + if (d3.event.sourceEvent.button == 2) return; - mouse_coords = d3.mouse(this); + mouse_coords = d3.mouse(this); - delta = [0, 0]; - delta[0] = mouse_coords[0] - drag_end[0]; - delta[1] = mouse_coords[1] - drag_end[1]; + delta = [0, 0]; + delta[0] = mouse_coords[0] - drag_end[0]; + delta[1] = mouse_coords[1] - drag_end[1]; - drag_end[0] = mouse_coords[0]; - drag_end[1] = mouse_coords[1]; + drag_end[0] = mouse_coords[0]; + drag_end[1] = mouse_coords[1]; - var selection = d3.selectAll('.node_selected'); + var selection = d3.selectAll(".node_selected"); - selection - .each(function (d) { - graph.nodes[d.id].x = d.x + delta[0]; - graph.nodes[d.id].y = d.y + delta[1]; - graph.nodes[d.id].px = d.px + delta[0]; - graph.nodes[d.id].py = d.py + delta[1]; - }); + selection.each(function(d) { + graph.nodes[d.id].x = d.x + delta[0]; + graph.nodes[d.id].y = d.y + delta[1]; + graph.nodes[d.id].px = d.px + delta[0]; + graph.nodes[d.id].py = d.py + delta[1]; + }); - draw_elements_graph(); - set_positions_graph(); + draw_elements_graph(); + set_positions_graph(); - d3.event.sourceEvent.stopPropagation(); - }); - dragables.call(drag); + d3.event.sourceEvent.stopPropagation(); + }); + dragables.call(drag); } function add_fictional_node() { - var name = $("input[name='name_fictional_node']").val(); - var networkmap_to_link = $("#networkmap_to_link").val(); + var name = $("input[name='name_fictional_node']").val(); + var networkmap_to_link = $("#networkmap_to_link").val(); - var x = (click_menu_position_svg[0] - translation[0]) / scale; - var y = (click_menu_position_svg[1] - translation[1]) / scale; + var x = (click_menu_position_svg[0] - translation[0]) / scale; + var y = (click_menu_position_svg[1] - translation[1]) / scale; - if (enterprise_installed) { - var params = []; - params.push("create_fictional_point=1"); - params.push("id=" + networkmap_id); - params.push("name=" + name); - params.push("networkmap=" + networkmap_to_link); - params.push("color=" + module_color_status[0]['color']); - params.push("radious=" + node_radius); - params.push("shape=circle"); - params.push("x=" + x); - params.push("y=" + y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_add").dialog("close"); + if (enterprise_installed) { + var params = []; + params.push("create_fictional_point=1"); + params.push("id=" + networkmap_id); + params.push("name=" + name); + params.push("networkmap=" + networkmap_to_link); + params.push("color=" + module_color_status[0]["color"]); + params.push("radious=" + node_radius); + params.push("shape=circle"); + params.push("x=" + x); + params.push("y=" + y); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_add").dialog("close"); - var temp_node = {}; - temp_node['id'] = graph.nodes.length; - temp_node['id_db'] = data['id_node']; - temp_node['id_agent'] = data['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = x; - temp_node['y'] = y; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['type'] = 3; - temp_node['color'] = data['color']; - temp_node['shape'] = data['shape']; - temp_node['text'] = data['text']; - temp_node['image_url'] = ""; - temp_node['image_width'] = 0; - temp_node['image_height'] = 0; - temp_node['networkmap_id'] = networkmap_to_link; + var temp_node = {}; + temp_node["id"] = graph.nodes.length; + temp_node["id_db"] = data["id_node"]; + temp_node["id_agent"] = data["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = x; + temp_node["y"] = y; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["type"] = 3; + temp_node["color"] = data["color"]; + temp_node["shape"] = data["shape"]; + temp_node["text"] = data["text"]; + temp_node["image_url"] = ""; + temp_node["image_width"] = 0; + temp_node["image_height"] = 0; + temp_node["networkmap_id"] = networkmap_to_link; - graph.nodes.push(temp_node); + graph.nodes.push(temp_node); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - } - }); - } - else { - $("#dialog_node_add").dialog("close"); + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + } + }); + } else { + $("#dialog_node_add").dialog("close"); - var temp_node = {}; - temp_node['id'] = graph.nodes.length; - temp_node['id_db'] = data['id_node']; - temp_node['id_agent'] = data['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = x; - temp_node['y'] = y; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['type'] = 3; - temp_node['color'] = data['color']; - temp_node['shape'] = data['shape']; - temp_node['text'] = data['text']; - temp_node['image_url'] = ""; - temp_node['image_width'] = 0; - temp_node['image_height'] = 0; - temp_node['networkmap_id'] = networkmap_to_link; + var temp_node = {}; + temp_node["id"] = graph.nodes.length; + temp_node["id_db"] = data["id_node"]; + temp_node["id_agent"] = data["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = x; + temp_node["y"] = y; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["type"] = 3; + temp_node["color"] = data["color"]; + temp_node["shape"] = data["shape"]; + temp_node["text"] = data["text"]; + temp_node["image_url"] = ""; + temp_node["image_width"] = 0; + temp_node["image_height"] = 0; + temp_node["networkmap_id"] = networkmap_to_link; - graph.nodes.push(temp_node); + graph.nodes.push(temp_node); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } } function init_graph(parameter_object) { - window.width_svg = $("#networkconsole_" + networkmap_id).width(); - if ($("#main").height()) { - window.height_svg = $("#main").height(); - } - else { - //Set the height in the pure view (fullscreen). - window.height_svg = $(window).height() - - $("#menu_tab_frame_view").height() - - 20; // 20 of margin - } + window.width_svg = $("#networkconsole_" + networkmap_id).width(); + if ($("#main").height()) { + window.height_svg = $("#main").height(); + } else { + //Set the height in the pure view (fullscreen). + window.height_svg = + $(window).height() - $("#menu_tab_frame_view").height() - 20; // 20 of margin + } - window.refresh_period = 5 * 1000; //milliseconds - if (typeof (parameter_object.refresh_period) != "undefined") { - window.refresh_period = parameter_object.refresh_period; - } - window.scale_minimap = 4.2; - window.translation = [0, 0]; - window.scale = z_dash || 0.5; - window.node_radius = 40; - if (typeof (parameter_object.node_radius) != "undefined") { - window.node_radius = parameter_object.node_radius; - } - window.interface_radius = 3; - window.disabled_drag_zoom = false; - window.key_multiple_selection = 17; //CTRL key - window.flag_multiple_selection = false; - window.flag_multiple_selection_running = false; - window.selection_rectangle = [0, 0, 0, 0]; - window.flag_drag_running = false; - window.in_a_node = false; - window.enterprise_installed = false; - window.flag_setting_relationship_running = false; - window.flag_setting_interface_link_running = false; + window.refresh_period = 5 * 1000; //milliseconds + if (typeof parameter_object.refresh_period != "undefined") { + window.refresh_period = parameter_object.refresh_period; + } + window.scale_minimap = 4.2; + window.translation = [0, 0]; + window.scale = z_dash || 0.5; + window.node_radius = 40; + if (typeof parameter_object.node_radius != "undefined") { + window.node_radius = parameter_object.node_radius; + } + window.interface_radius = 3; + window.disabled_drag_zoom = false; + window.key_multiple_selection = 17; //CTRL key + window.flag_multiple_selection = false; + window.flag_multiple_selection_running = false; + window.selection_rectangle = [0, 0, 0, 0]; + window.flag_drag_running = false; + window.in_a_node = false; + window.enterprise_installed = false; + window.flag_setting_relationship_running = false; + window.flag_setting_interface_link_running = false; - window.minimap_w = 0; - window.minimap_h = 0; - window.show_minimap = false; - window.show_labels = true; - window.context_minimap; + window.minimap_w = 0; + window.minimap_h = 0; + window.show_minimap = false; + window.show_labels = true; + window.context_minimap; - window.holding_area_dimensions = [200, 200]; - if (typeof (parameter_object.holding_area_dimensions) != "undefined") { - window.holding_area_dimensions = parameter_object.holding_area_dimensions; - } + window.holding_area_dimensions = [200, 200]; + if (typeof parameter_object.holding_area_dimensions != "undefined") { + window.holding_area_dimensions = parameter_object.holding_area_dimensions; + } - window.graph = null; - if (typeof (parameter_object.graph) != "undefined") { - window.graph = parameter_object.graph; - } + window.graph = null; + if (typeof parameter_object.graph != "undefined") { + window.graph = parameter_object.graph; + } - window.networkmap_center = []; - if (typeof (parameter_object.networkmap_center) != "undefined") { - window.networkmap_center = parameter_object.networkmap_center; - } + window.networkmap_center = []; + if (typeof parameter_object.networkmap_center != "undefined") { + window.networkmap_center = parameter_object.networkmap_center; + } - if (typeof (networkmap_center[0]) == "undefined") { - networkmap_center = [0, 0]; - } + if (typeof networkmap_center[0] == "undefined") { + networkmap_center = [0, 0]; + } - translation[0] = (width_svg / 2) - networkmap_center[0]; - translation[1] = (height_svg / 2) - networkmap_center[1]; + translation[0] = width_svg / 2 - networkmap_center[0]; + translation[1] = height_svg / 2 - networkmap_center[1]; - translation[0] = translation[0] * scale; - translation[1] = translation[1] * scale; + translation[0] = translation[0] * scale; + translation[1] = translation[1] * scale; - window.enterprise_installed = ''; - if (typeof (parameter_object.enterprise_installed) != "undefined") { - window.enterprise_installed = parameter_object.enterprise_installed; - } + window.enterprise_installed = ""; + if (typeof parameter_object.enterprise_installed != "undefined") { + window.enterprise_installed = parameter_object.enterprise_installed; + } - window.networkmap_dimensions = []; - if (typeof (parameter_object.networkmap_dimensions) != "undefined") { - window.networkmap_dimensions = parameter_object.networkmap_dimensions; - } - window.max = Math.max(networkmap_dimensions[0], networkmap_dimensions[1]); - window.min = Math.min(width_svg / scale_minimap, - height_svg / scale_minimap); + window.networkmap_dimensions = []; + if (typeof parameter_object.networkmap_dimensions != "undefined") { + window.networkmap_dimensions = parameter_object.networkmap_dimensions; + } + window.max = Math.max(networkmap_dimensions[0], networkmap_dimensions[1]); + window.min = Math.min(width_svg / scale_minimap, height_svg / scale_minimap); - window.minimap_relation = min / max; - minimap_w = networkmap_dimensions[0] * minimap_relation; - minimap_h = networkmap_dimensions[1] * minimap_relation; + window.minimap_relation = min / max; + minimap_w = networkmap_dimensions[0] * minimap_relation; + minimap_h = networkmap_dimensions[1] * minimap_relation; - $("#minimap_" + networkmap_id).attr('width', minimap_w); - $("#minimap_" + networkmap_id).attr('height', minimap_h); + $("#minimap_" + networkmap_id).attr("width", minimap_w); + $("#minimap_" + networkmap_id).attr("height", minimap_h); - window.canvas_minimap = $("#minimap_" + networkmap_id); - window.context_minimap = canvas_minimap[0].getContext('2d'); - window.minimap_drag = false; + window.canvas_minimap = $("#minimap_" + networkmap_id); + window.context_minimap = canvas_minimap[0].getContext("2d"); + window.minimap_drag = false; - window.url_background_grid = ''; - if (typeof (parameter_object.url_background_grid) != "undefined") { - // GRID - window.url_background_grid = ""; - } + window.url_background_grid = ""; + if (typeof parameter_object.url_background_grid != "undefined") { + // GRID + window.url_background_grid = ""; + } - var rect_center_x = graph.nodes[0].x; - var rect_center_y = graph.nodes[0].y; + var rect_center_x = graph.nodes[0].x; + var rect_center_y = graph.nodes[0].y; - //For to catch the keyevent for the ctrl key - d3.select(document) - .on("keydown", function () { - if (d3.event.keyCode == key_multiple_selection) { - flag_multiple_selection = true; - disabled_drag_zoom = true; - } - }) - .on("keyup", function () { - if (d3.event.keyCode == key_multiple_selection) { - flag_multiple_selection = false; - disabled_drag_zoom = false; - flag_multiple_selection_running = false; + //For to catch the keyevent for the ctrl key + d3.select(document) + .on("keydown", function() { + if (d3.event.keyCode == key_multiple_selection) { + flag_multiple_selection = true; + disabled_drag_zoom = true; + } + }) + .on("keyup", function() { + if (d3.event.keyCode == key_multiple_selection) { + flag_multiple_selection = false; + disabled_drag_zoom = false; + flag_multiple_selection_running = false; - d3.select("#selection_rectangle") - .style("display", "none"); - } - }); + d3.select("#selection_rectangle").style("display", "none"); + } + }); - window.force = d3.layout.force() - .charge(10) - .linkDistance(0) - .size([width_svg, height_svg]); + window.force = d3.layout + .force() + .charge(10) + .linkDistance(0) + .size([width_svg, height_svg]); - if (x_offs != null) { - translation[0] = translation[0] + x_offs; - } - if (y_offs != null) { - translation[1] = translation[1] + y_offs; - } - if (z_dash != null) { - scale = z_dash; - } + if (x_offs != null) { + translation[0] = translation[0] + x_offs; + } + if (y_offs != null) { + translation[1] = translation[1] + y_offs; + } + if (z_dash != null) { + scale = z_dash; + } - window.zoom_obj = d3.behavior.zoom(); - zoom_obj.scaleExtent([0.05, 1]) - .on("zoom", zoom) - .translate(translation) - .scale(scale); + window.zoom_obj = d3.behavior.zoom(); + zoom_obj + .scaleExtent([0.05, 1]) + .on("zoom", zoom) + .translate(translation) + .scale(scale); - window.svg = d3.select("#networkconsole_" + networkmap_id) - .append("svg") - .attr("id", "dinamic_networkmap_svg_" + networkmap_id) - .attr("width", width_svg) - .attr("height", height_svg) - .call(zoom_obj) - .on("mousedown", function () { - if (flag_multiple_selection) { - flag_multiple_selection_running = true; + window.svg = d3 + .select("#networkconsole_" + networkmap_id) + .append("svg") + .attr("id", "dinamic_networkmap_svg_" + networkmap_id) + .attr("width", width_svg) + .attr("height", height_svg) + .call(zoom_obj) + .on("mousedown", function() { + if (flag_multiple_selection) { + flag_multiple_selection_running = true; - mouse_coords = d3.mouse(this); + mouse_coords = d3.mouse(this); - selection_rectangle[0] = mouse_coords[0]; - selection_rectangle[1] = mouse_coords[1]; - selection_rectangle[2] = mouse_coords[0]; - selection_rectangle[3] = mouse_coords[1]; + selection_rectangle[0] = mouse_coords[0]; + selection_rectangle[1] = mouse_coords[1]; + selection_rectangle[2] = mouse_coords[0]; + selection_rectangle[3] = mouse_coords[1]; - d3.select("#selection_rectangle") - .style("display", "") - .attr("x", selection_rectangle[0]) - .attr("y", selection_rectangle[1]) - .attr("width", selection_rectangle[2] - selection_rectangle[0]) - .attr("height", selection_rectangle[3] - selection_rectangle[1]); - } - else { - clear_selection(); - } - }) - .on("mouseup", function () { - flag_multiple_selection_running = false; - d3.select("#selection_rectangle") - .style("display", "none"); - }) - .on("mousemove", function () { - if (flag_multiple_selection_running) { + d3.select("#selection_rectangle") + .style("display", "") + .attr("x", selection_rectangle[0]) + .attr("y", selection_rectangle[1]) + .attr("width", selection_rectangle[2] - selection_rectangle[0]) + .attr("height", selection_rectangle[3] - selection_rectangle[1]); + } else { + clear_selection(); + } + }) + .on("mouseup", function() { + flag_multiple_selection_running = false; + d3.select("#selection_rectangle").style("display", "none"); + }) + .on("mousemove", function() { + if (flag_multiple_selection_running) { + mouse_coords = d3.mouse(this); - mouse_coords = d3.mouse(this); + selection_rectangle[2] = mouse_coords[0]; + selection_rectangle[3] = mouse_coords[1]; - selection_rectangle[2] = mouse_coords[0]; - selection_rectangle[3] = mouse_coords[1]; + x = selection_rectangle[0]; + width = selection_rectangle[2] - selection_rectangle[0]; + if (width < 0) { + x = selection_rectangle[2]; + width = selection_rectangle[0] - selection_rectangle[2]; + } - x = selection_rectangle[0]; - width = selection_rectangle[2] - selection_rectangle[0]; - if (width < 0) { - x = selection_rectangle[2]; - width = selection_rectangle[0] - selection_rectangle[2]; - } + y = selection_rectangle[1]; + height = selection_rectangle[3] - selection_rectangle[1]; + if (height < 0) { + y = selection_rectangle[3]; + height = selection_rectangle[1] - selection_rectangle[3]; + } - y = selection_rectangle[1]; - height = selection_rectangle[3] - selection_rectangle[1]; - if (height < 0) { - y = selection_rectangle[3]; - height = selection_rectangle[1] - selection_rectangle[3]; - } + d3.select("#selection_rectangle") + .attr("x", x) + .attr("y", y) + .attr("width", width) + .attr("height", height); - d3.select("#selection_rectangle") - .attr("x", x) - .attr("y", y) - .attr("width", width) - .attr("height", height); + sel_rec_x1 = x; + sel_rec_x2 = x + width; + sel_rec_y1 = y; + sel_rec_y2 = y + height; - sel_rec_x1 = x; - sel_rec_x2 = x + width; - sel_rec_y1 = y; - sel_rec_y2 = y + height; + d3.selectAll(".node").each(function(data, i) { + item_x1 = (data.x - node_radius / 2) * scale + translation[0]; + item_x2 = (data.x + node_radius / 2) * scale + translation[0]; + item_y1 = (data.y - node_radius / 2) * scale + translation[1]; + item_y2 = (data.y + node_radius / 2) * scale + translation[1]; - d3.selectAll('.node').each(function (data, i) { + if ( + !d3.select(this).classed("node_selected") && + // inner circle inside selection frame + item_x1 >= sel_rec_x1 && + item_x2 <= sel_rec_x2 && + item_y1 >= sel_rec_y1 && + item_y1 <= sel_rec_y2 + ) { + d3.select("#id_node_" + data.id + networkmap_id).classed( + "node_selected", + true + ); + } + }); + } + }) + .on("contextmenu", function(d) { + show_menu("background", d); + }); - item_x1 = ((data.x - (node_radius / 2)) * scale + translation[0]); - item_x2 = ((data.x + (node_radius / 2)) * scale + translation[0]); - item_y1 = ((data.y - (node_radius / 2)) * scale + translation[1]); - item_y2 = ((data.y + (node_radius / 2)) * scale + translation[1]); + window.defs = svg.append("defs"); + defs + .selectAll("defs") + .data(module_color_status) + .enter() + .append("marker") + .attr("id", function(d) { + return "interface_start_" + d.status_code; + }) + .attr("refX", 0) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", node_radius / 2.3 - interface_radius / 2.3) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", function(d) { + return "fill: " + d.color + ";"; + }); - if ( - !d3.select(this).classed("node_selected") && - // inner circle inside selection frame - item_x1 >= sel_rec_x1 && - item_x2 <= sel_rec_x2 && - item_y1 >= sel_rec_y1 && - item_y1 <= sel_rec_y2 - ) { + defs + .selectAll("defs") + .data(module_color_status) + .enter() + .append("marker") + .attr("id", function(d) { + return "interface_end_" + d.status_code; + }) + .attr("refX", node_radius / 2.3 + interface_radius / 2.3) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", interface_radius) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", function(d) { + return "fill: " + d.color + ";"; + }); - d3.select("#id_node_" + data.id + networkmap_id) - .classed("node_selected", true); - } - }); - } - }) - .on("contextmenu", function (d) { show_menu("background", d); }); + defs + .append("marker") + .attr("id", "interface_start") + .attr("refX", 0) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", node_radius / 2 - interface_radius / 2) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", "fill:" + module_color_status_unknown + ";"); + defs + .append("marker") + .attr("id", "interface_end") + .attr("refX", node_radius / 2 + interface_radius / 2) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", interface_radius) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", "fill:" + module_color_status_unknown + ";"); - window.defs = svg.append("defs"); - defs.selectAll("defs") - .data(module_color_status) - .enter() - .append("marker") - .attr("id", function (d) { return "interface_start_" + d.status_code; }) - .attr("refX", 0) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", (node_radius / 2.3) - (interface_radius / 2.3)) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", function (d) { - return "fill: " + d.color + ";"; - }); + //Added pattern for the background grid + svg + .append("pattern") + .attr("id", "background_grid") + .attr("height", 24) + .attr("width", 25) + .attr("patternUnits", "userSpaceOnUse") + .append("image") + .attr("y", 0) + .attr("x", 0) + .attr("xlink:href", url_background_grid) + .attr("height", 24) + .attr("width", 25); - defs.selectAll("defs") - .data(module_color_status) - .enter() - .append("marker") - .attr("id", function (d) { return "interface_end_" + d.status_code; }) - .attr("refX", (node_radius / 2.3) + (interface_radius / 2.3)) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", interface_radius) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", function (d) { - return "fill: " + d.color + ";"; - }); + window.layer_graph = svg + .append("g") + .attr("id", "layer_graph_" + networkmap_id) + .attr("transform", "translate(" + translation + ")scale(" + scale + ")"); - defs.append("marker") - .attr("id", "interface_start") - .attr("refX", 0) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", (node_radius / 2) - (interface_radius / 2)) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", "fill:" + module_color_status_unknown + ";"); + if (enterprise_installed) { + window.layer_graph + .append("rect") + .attr("id", "holding_area_" + networkmap_id) + .attr("width", holding_area_dimensions[0]) + .attr("height", holding_area_dimensions[1]) + .attr( + "x", + networkmap_dimensions[0] + node_radius - holding_area_dimensions[0] + ) + .attr( + "y", + networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] + ) + .attr( + "style", + "fill: #e6e6e6; " + + "fill-opacity: 0.75; " + + "stroke: #dedede; " + + "stroke-width: 1; " + + "stroke-miterlimit: 4; " + + "stroke-opacity: 0.75; " + + "stroke-dasharray: none; " + + "stroke-dashoffset: 0" + ); - defs.append("marker") - .attr("id", "interface_end") - .attr("refX", (node_radius / 2) + (interface_radius / 2)) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", interface_radius) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", "fill:" + module_color_status_unknown + ";"); + window.layer_graph + .append("text") + .append("tspan") + .attr("xml:space", "preserve") + .attr( + "style", + "font-size: 32px; " + + "font-style: normal; " + + "font-weight: normal; " + + "text-align: start; " + + "line-height: 125%; " + + "letter-spacing: 0px; " + + "word-spacing: 0px; " + + "text-anchor: start; " + + "fill: #000000; " + + "fill-opacity: 1; " + + "stroke: none; " + + "font-family: Verdana" + ) + .attr( + "x", + networkmap_dimensions[0] + node_radius - holding_area_dimensions[0] + ) + .attr( + "y", + networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] - 10 + ) + .text(holding_area_title); + } - //Added pattern for the background grid - svg.append("pattern") - .attr("id", "background_grid") - .attr("height", 24) - .attr("width", 25) - .attr("patternUnits", "userSpaceOnUse") - .append("image") - .attr("y", 0) - .attr("x", 0) - .attr("xlink:href", url_background_grid) - .attr("height", 24) - .attr("width", 25); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - window.layer_graph = svg - .append("g") - .attr("id", "layer_graph_" + networkmap_id) - .attr("transform", - "translate(" + translation + ")scale(" + scale + ")"); + window.layer_selection_rectangle = svg + .append("g") + .attr("id", "layer_selection_rectangle"); - if (enterprise_installed) { - window.layer_graph.append("rect") - .attr("id", "holding_area_" + networkmap_id) - .attr("width", holding_area_dimensions[0]) - .attr("height", holding_area_dimensions[1]) - .attr("x", - networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) - .attr("y", - networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) - .attr("style", "fill: #e6e6e6; " + - "fill-opacity: 0.75; " + - "stroke: #dedede; " + - "stroke-width: 1; " + - "stroke-miterlimit: 4; " + - "stroke-opacity: 0.75; " + - "stroke-dasharray: none; " + - "stroke-dashoffset: 0"); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.layer_graph.append("text") - .append("tspan") - .attr("xml:space", "preserve") - .attr("style", "font-size: 32px; " + - "font-style: normal; " + - "font-weight: normal; " + - "text-align: start; " + - "line-height: 125%; " + - "letter-spacing: 0px; " + - "word-spacing: 0px; " + - "text-anchor: start; " + - "fill: #000000; " + - "fill-opacity: 1; " + - "stroke: none; " + - "font-family: Verdana") - .attr("x", networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) - .attr("y", networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] - 10) - .text(holding_area_title); - } + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + draw_elements_graph(); + set_positions_graph(); - window.layer_selection_rectangle = svg - .append("g") - .attr("id", "layer_selection_rectangle"); + layer_selection_rectangle + .append("rect") + .attr("width", 666) + .attr("height", 666) + .attr("x", 0) + .attr("y", 0) + .attr("id", "selection_rectangle") + .attr( + "style", + "display: none; fill:#e6e6e6; " + + "fill-opacity:0.46153846; " + + "stroke:#e6e6e6; " + + "stroke-width:1; " + + "stroke-miterlimit:4; " + + "stroke-opacity:1; " + + "stroke-dasharray:none;" + ); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + $("#dialog_node_edit").dialog({ + autoOpen: false, + width: 650 + }); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + $("#dialog_interface_link").dialog({ + autoOpen: false, + width: 650 + }); - draw_elements_graph(); - set_positions_graph(); - - layer_selection_rectangle - .append("rect") - .attr("width", 666) - .attr("height", 666) - .attr("x", 0) - .attr("y", 0) - .attr("id", "selection_rectangle") - .attr("style", "display: none; fill:#e6e6e6; " + - "fill-opacity:0.46153846; " + - "stroke:#e6e6e6; " + - "stroke-width:1; " + - "stroke-miterlimit:4; " + - "stroke-opacity:1; " + - "stroke-dasharray:none;"); - - $("#dialog_node_edit").dialog({ - autoOpen: false, - width: 650 - }); - - $("#dialog_interface_link").dialog({ - autoOpen: false, - width: 650 - }); - - $("#dialog_node_add").dialog({ - autoOpen: false, - width: 650 - }); + $("#dialog_node_add").dialog({ + autoOpen: false, + width: 650 + }); } function myMouseoverCircleFunction(node_id) { - var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); + var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); - over = circle.classed("node_over"); + over = circle.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - circle.classed("node_over", !over); + circle.classed("node_over", !over); - circle.transition().duration(400) - .attr("r", node_radius + 10); + circle + .transition() + .duration(400) + .attr("r", node_radius + 10); } function myMouseoutCircleFunction(node_id) { - var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); + var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); - over = circle.classed("node_over"); + over = circle.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - circle.classed("node_over", !over); + circle.classed("node_over", !over); - circle.transition().duration(400) - .attr("r", node_radius); + circle + .transition() + .duration(400) + .attr("r", node_radius); } function myMouseoverSquareFunction(node_id) { - var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = square.classed("node_over"); + over = square.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - square.classed("node_over", !over); + square.classed("node_over", !over); - square.transition().duration(400) - .attr("width", (node_radius * 2) + 10) - .attr("height", (node_radius * 2) + 10) - .attr("transform", "translate(" + (-5) + "," + (-5) + ")"); + square + .transition() + .duration(400) + .attr("width", node_radius * 2 + 10) + .attr("height", node_radius * 2 + 10) + .attr("transform", "translate(" + -5 + "," + -5 + ")"); } function myMouseoutSquareFunction(node_id) { - var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = square.classed("node_over"); + over = square.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - square.classed("node_over", !over); + square.classed("node_over", !over); - square.transition().duration(400) - .attr("width", (node_radius * 2)) - .attr("height", (node_radius * 2)) - .attr("transform", "translate(" + 0 + "," + 0 + ")"); + square + .transition() + .duration(400) + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("transform", "translate(" + 0 + "," + 0 + ")"); } function myMouseoverRhombusFunction(node_id) { - var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = rhombus.classed("node_over"); + over = rhombus.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - rhombus.classed("node_over", !over); + rhombus.classed("node_over", !over); - rhombus.transition().duration(400) - .attr("width", (node_radius * 1.5) + 10) - .attr("height", (node_radius * 1.5) + 10); + rhombus + .transition() + .duration(400) + .attr("width", node_radius * 1.5 + 10) + .attr("height", node_radius * 1.5 + 10); } function myMouseoutRhombusFunction(node_id) { - var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = rhombus.classed("node_over"); + over = rhombus.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - rhombus.classed("node_over", !over); + rhombus.classed("node_over", !over); - rhombus.transition().duration(400) - .attr("width", (node_radius * 1.5)) - .attr("height", (node_radius * 1.5)); + rhombus + .transition() + .duration(400) + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5); } function draw_elements_graph() { - link = link.data(force.links().filter(function(d, i) { - if (d['deleted']) { - return false; - } - else { - return true; - } - }), - function (d) { - return d.source.id + networkmap_id + "-" + d.target.id + networkmap_id + Math.random(); - }); - + link = link.data( + force.links().filter(function(d, i) { + if (d["deleted"]) { + return false; + } else { + return true; + } + }), + function(d) { + return ( + d.source.id + + networkmap_id + + "-" + + d.target.id + + networkmap_id + + Math.random() + ); + } + ); - link_temp = link.enter() - .append("g") - .attr("id", function (d) { - return "link_id_" + d.id_db + networkmap_id; - }) - .attr("class", function (d) { - var holding_area_text = ""; - if ((d.source.state == 'holding_area') || - (d.target.state == 'holding_area')) { + link_temp = link + .enter() + .append("g") + .attr("id", function(d) { + return "link_id_" + d.id_db + networkmap_id; + }) + .attr("class", function(d) { + var holding_area_text = ""; + if ( + d.source.state == "holding_area" || + d.target.state == "holding_area" + ) { + holding_area_text = " holding_area_link "; + } - holding_area_text = " holding_area_link "; - } + return ( + "link " + + "source_" + + d.source.id + + networkmap_id + + " " + + "target_" + + d.target.id + + networkmap_id + + " " + + holding_area_text + + "id_module_start_" + + d.id_module_start + + " " + + "id_module_end_" + + d.id_module_end + ); + }); - return "link " + - "source_" + d.source.id + networkmap_id + " " + - "target_" + d.target.id + networkmap_id + " " + - holding_area_text + - "id_module_start_" + d.id_module_start + " " + - "id_module_end_" + d.id_module_end; - }); + link.exit().remove(); - link.exit().remove(); + link_temp + .append("path") + .attr("id", function(d) { + return "link_id_text_" + d.id_db + networkmap_id; + }) + .attr("class", function(d) { + var holding_area_text = ""; + if ( + d.source.state == "holding_area" || + d.target.state == "holding_area" + ) { + holding_area_text = " holding_area_link "; + } - link_temp.append("path") - .attr("id", function (d) { - return "link_id_text_" + d.id_db + networkmap_id; - }) - .attr("class", function (d) { - var holding_area_text = ""; - if ((d.source.state == 'holding_area') || - (d.target.state == 'holding_area')) { + return ( + "link " + + "source_" + + d.source.id + + networkmap_id + + " " + + "target_" + + d.target.id + + networkmap_id + + " " + + holding_area_text + + "id_module_start_" + + d.id_module_start + + " " + + "id_module_end_" + + d.id_module_end + ); + }) + .attr("stroke", function(d) { + if (d.link_color === undefined) { + return "#999"; + } else { + return d.link_color; + } + }) + .attr("stroke-width", 3) + .attr("d", null) + .attr("marker-start", function(d) { + if (d.arrow_start == "") { + return ""; + } else if (d.arrow_start == "module") { + if (typeof module_color_status[d.status_start] == "undefined") + return "url(#interface_start)"; + else return "url(#interface_start_" + d.status_start + ")"; + } + }) + .attr("marker-end", function(d) { + if (d.arrow_end == "") { + return ""; + } else if (d.arrow_end == "module") { + if (typeof module_color_status[d.status_end] == "undefined") + return "url(#interface_end)"; + else return "url(#interface_end_" + d.status_end + ")"; + } + }) + .on("mouseover", function(d) { + d3.select(this).classed("link_over", true); + }) + .on("mouseout", function(d) { + d3.select(this).classed("link_over", false); + }); - holding_area_text = " holding_area_link "; - } + //Add the reverse line for the end marker, it is invisible + link_temp + .append("path") + .attr("id", function(d) { + return "link_reverse_id_" + d.id_db + networkmap_id; + }) + .attr("stroke-width", 0) + .attr("d", null) + .attr("class", function(d) { + return "link_reverse"; + }); - return "link " + - "source_" + d.source.id + networkmap_id + " " + - "target_" + d.target.id + networkmap_id + " " + - holding_area_text + - "id_module_start_" + d.id_module_start + " " + - "id_module_end_" + d.id_module_end; - }) - .attr("stroke", function (d) { - if(d.link_color === undefined) { - return "#999"; - } else { - return d.link_color; - } - }) - .attr("stroke-width", 3) - .attr("d", null) - .attr('marker-start', function (d) { - if (d.arrow_start == "") { - return ""; - } - else if (d.arrow_start == "module") { - if (typeof (module_color_status[d.status_start]) == "undefined") - return "url(#interface_start)"; - else - return "url(#interface_start_" + d.status_start + ")"; - } - }) - .attr('marker-end', function (d) { - if (d.arrow_end == "") { - return ""; - } - else if (d.arrow_end == "module") { - if (typeof (module_color_status[d.status_end]) == "undefined") - return "url(#interface_end)"; - else - return "url(#interface_end_" + d.status_end + ")"; - } - }) - .on("mouseover", function (d) { - d3.select(this) - .classed("link_over", true); - }) - .on("mouseout", function (d) { - d3.select(this) - .classed("link_over", false); - }); + link_temp + .append("text") + .attr("xml:space", "preserve") + .append("textPath") + .attr("xlink:href", function(d) { + if (d.source.x < d.target.x) { + return "#link_id_text_" + d.id_db + networkmap_id; + } else { + return "#link_reverse_id_" + d.id_db + networkmap_id; + } + }) + .attr("startOffset", function(d) { + if (d.source.x < d.target.x) { + return "0%"; + } else { + return "85%"; + } + }) + .attr("text-anchor", function(d) { + if (d.source.x < d.target.x) { + return ""; + } else { + return "end"; + } + }) + .append("tspan") + .attr( + "style", + "font-size: 12px; " + + "font-style:normal; " + + "font-weight:normal; " + + "line-height: 100%; " + + "letter-spacing:0px; " + + "word-spacing:0px; " + + "fill:#000000; " + + "fill-opacity:1; " + + "stroke:none; " + + "text-align:start; " + ) + .text(function(d) { + var text_link = ""; + if (d.text_start) { + text_link = d.text_start; + } - //Add the reverse line for the end marker, it is invisible - link_temp.append("path") - .attr("id", function (d) { - return "link_reverse_id_" + d.id_db + networkmap_id; - }) - .attr("stroke-width", 0) - .attr("d", null) - .attr("class", function (d) { - return "link_reverse"; - }); + return Array(25).join(" ") + text_link; + }); - link_temp.append("text") - .attr("xml:space", "preserve") - .append("textPath") - .attr("xlink:href", function (d) { - if (d.source.x < d.target.x) { - return "#link_id_text_" + d.id_db + networkmap_id; - } - else { - return "#link_reverse_id_" + d.id_db + networkmap_id; - } - }) - .attr("startOffset", function (d) { - if (d.source.x < d.target.x) { - return "0%"; - } - else { - return "85%"; - } - }) - .attr("text-anchor", function (d) { - if (d.source.x < d.target.x) { - return ""; - } - else { - return "end"; - } - }) - .append("tspan") - .attr("style", "font-size: 12px; " + - "font-style:normal; " + - "font-weight:normal; " + - "line-height: 100%; " + - "letter-spacing:0px; " + - "word-spacing:0px; " + - "fill:#000000; " + - "fill-opacity:1; " + - "stroke:none; " + - "text-align:start; ") - .text(function (d) { - var text_link = ""; - if (d.text_start) { - text_link = d.text_start; - } + link_temp + .append("text") + .attr("xml:space", "preserve") + .append("textPath") + .attr("xlink:href", function(d) { + if (d.source.x < d.target.x) { + return "#link_id_text_" + d.id_db + networkmap_id; + } else { + return "#link_reverse_id_" + d.id_db + networkmap_id; + } + }) + .attr("startOffset", function(d) { + if (d.source.x < d.target.x) { + return "85%"; + } else { + return "0%"; + } + }) + .attr("text-anchor", function(d) { + if (d.source.x < d.target.x) { + return "end"; + } else { + return ""; + } + }) + .append("tspan") + .attr( + "style", + "font-size: 12px; " + + "font-style:normal; " + + "font-weight:normal; " + + "line-height: 100%; " + + "letter-spacing:0px; " + + "word-spacing:0px; " + + "fill:#000000; " + + "fill-opacity:1; " + + "stroke:none; " + + "text-align:end; " + ) + .text(function(d) { + var text_link = ""; + if (d.text_end) { + text_link = d.text_end; + } - return (Array(25).join(" ")) + text_link; - }); + return Array(25).join(" ") + text_link; + }); - link_temp.append("text") - .attr("xml:space", "preserve") - .append("textPath") - .attr("xlink:href", function (d) { - if (d.source.x < d.target.x) { - return "#link_id_text_" + d.id_db + networkmap_id; - } - else { - return "#link_reverse_id_" + d.id_db + networkmap_id; - } - }) - .attr("startOffset", function (d) { - if (d.source.x < d.target.x) { - return "85%"; - } - else { - return "0%"; - } - }) - .attr("text-anchor", function (d) { - if (d.source.x < d.target.x) { - return "end"; - } - else { - return ""; - } - }) - .append("tspan") - .attr("style", "font-size: 12px; " + - "font-style:normal; " + - "font-weight:normal; " + - "line-height: 100%; " + - "letter-spacing:0px; " + - "word-spacing:0px; " + - "fill:#000000; " + - "fill-opacity:1; " + - "stroke:none; " + - "text-align:end; ") - .text(function (d) { - var text_link = ""; - if (d.text_end) { - text_link = d.text_end; - } + node = node.data( + force.nodes().filter(function(d, i) { + if (d["deleted"]) { + return false; + } else { + return true; + } + }), + function(d) { + return d.id; + } + ); - return (Array(25).join(" ")) + text_link; - }); + node_temp = node + .enter() + .append("g") + .attr("id", function(d) { + return "id_node_" + d.id + networkmap_id; + }) + .attr("class", function(d) { + if (d.state == "holding_area") return "node holding_area"; + else return "node"; + }); - node = node.data(force.nodes().filter(function(d, i) { - if (d['deleted']) { - return false; - } - else { - return true; - } - }), function (d) { return d.id; }); + node.exit().remove(); - node_temp = node.enter() - .append("g") - .attr("id", function (d) { - return "id_node_" + d.id + networkmap_id; - }) - .attr("class", function (d) { - if (d.state == 'holding_area') - return "node holding_area"; - else - return "node"; - }); + //Shape circle + node_temp + .filter(function(d) { + if (d.shape == "circle") { + return true; + } else return false; + }) + .append("circle") + .attr("r", node_radius) + .attr("class", "node_shape node_shape_circle") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node.exit().remove(); + node_temp + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return is_central_node(d) ? $("#hidden-center_logo").val() : d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - //Shape circle - node_temp.filter(function (d) { - if (d.shape == 'circle') { return true; } - else return false; - }) - .append("circle") - .attr("r", node_radius) - .attr("class", "node_shape node_shape_circle") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + //Shape square + node_temp + .filter(function(d) { + if (d.shape == "square") { + return true; + } else return false; + }) + .append("rect") + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("class", "node_shape node_shape_square") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .filter(function(d) { + if (d.shape == "square") { + return true; + } else return false; + }) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node_temp.append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return is_central_node(d) - ? $("#hidden-center_logo").val() - : d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + //Shape rhombus + node_temp + .filter(function(d) { + if (d.shape == "rhombus") { + return true; + } else return false; + }) + .append("rect") + .attr("transform", "") + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5) + .attr("class", "node_shape node_shape_rhombus") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .filter(function(d) { + if (d.shape == "rhombus") { + return true; + } else return false; + }) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - //Shape square - node_temp.filter(function (d) { - if (d.shape == 'square') { return true; } - else return false; - }) - .append("rect") - .attr("width", node_radius * 2) - .attr("height", node_radius * 2) - .attr("class", "node_shape node_shape_square") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + var font_size = node_radius / 1.5; - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .append("text") + .attr("class", "node_text") + .attr("id", "node_text_" + networkmap_id) + .attr( + "style", + "font-style:normal; font-weight:normal; line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;" + ) + .attr("x", function(d) { + return d.x; + }) + .attr("y", function(d) { + return d.y + node_radius + 12; + }) + .append("tspan") + .attr( + "style", + "font-size: " + + font_size + + "px !important; font-family:Verdana; text-align:center; text-anchor:middle; fill:#000000" + ) + .text(function(d) { + return ellipsize(get_node_name_ov(d), 30); + }) + .classed("dragable_node", true) //own dragable + .on("click", selected_node) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node_temp.filter(function (d) { - if (d.shape == 'square') { return true; } - else return false; - }) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + node_temp.append("title").text(function(d) { + return get_node_name_ov(d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - //Shape rhombus - node_temp.filter(function (d) { - if (d.shape == 'rhombus') { return true; } - else return false; - }) - .append("rect") - .attr("transform", - "") - .attr("width", node_radius * 1.5) - .attr("height", node_radius * 1.5) - .attr("class", "node_shape node_shape_rhombus") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - node_temp.filter(function (d) { - if (d.shape == 'rhombus') { return true; } - else return false; - }) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - var font_size = (node_radius / 1.5); - - node_temp.append("text") - .attr("class", "node_text") - .attr("id", "node_text_" + networkmap_id) - .attr("style", "font-style:normal; font-weight:normal; line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;") - .attr("x", function (d) { - return d.x; - }) - .attr("y", function (d) { - return d.y + node_radius + 12; - }) - .append("tspan") - .attr("style", "font-size: " + font_size + "px !important; font-family:Verdana; text-align:center; text-anchor:middle; fill:#000000") - .text(function (d) { - return ellipsize(get_node_name_ov(d), 30); - }) - .classed('dragable_node', true) //own dragable - .on("click", selected_node) - .on("contextmenu", function (d) { show_menu("node", d); }); - - node_temp.append("title") - .text(function (d) { return get_node_name_ov(d) }); - - node.exit().remove(); + node.exit().remove(); } -function is_central_node (data) { - return (data.type == 0 && data.id_agent == 0); +function is_central_node(data) { + return data.type == 0 && data.id_agent == 0; } -function get_node_name_ov (data) { - // Node central name should be the product name - return (is_central_node(data)) - ? $("#hidden-product_name").val() - : data.text; +function get_node_name_ov(data) { + // Node central name should be the product name + return is_central_node(data) ? $("#hidden-product_name").val() : data.text; } function choose_group_for_show_agents() { - if (enterprise_installed) { - group = $("#group_for_show_agents option:selected").val(); + if (enterprise_installed) { + group = $("#group_for_show_agents option:selected").val(); - $("#agents_filter_group").attr('disabled', true); - $("#spinner_group").css('display', ''); - if (group == -1) { - $("#agents_filter_group").html(''); - $("#spinner_group").css('display', 'none'); - } - else { - $("#group_for_show_agents").attr('disabled', true); + $("#agents_filter_group").attr("disabled", true); + $("#spinner_group").css("display", ""); + if (group == -1) { + $("#agents_filter_group").html( + '" + ); + $("#spinner_group").css("display", "none"); + } else { + $("#group_for_show_agents").attr("disabled", true); - var params = []; - params.push("get_agents_in_group=1"); - params.push("id=" + networkmap_id); - params.push("group=" + group); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#agents_filter_group").html(''); - jQuery.each(data['agents'], function (id, name) { - if (typeof (name) == 'undefined') return; + var params = []; + params.push("get_agents_in_group=1"); + params.push("id=" + networkmap_id); + params.push("group=" + group); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#agents_filter_group").html(""); + jQuery.each(data["agents"], function(id, name) { + if (typeof name == "undefined") return; - $("#agents_filter_group").append(''); - }); + $("#agents_filter_group").append( + '" + ); + }); - $("#agents_filter_group").removeAttr('disabled'); - $("#group_for_show_agents").removeAttr('disabled'); - $("#spinner_group").css('display', 'none'); - $("input[name=add_agent_group_button]").removeAttr('disabled'); - } - else { - $("#group_for_show_agents").removeAttr('disabled'); - $("#agents_filter_group").html(''); - $("#spinner_group").css('display', 'none'); function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + $("#agents_filter_group").removeAttr("disabled"); + $("#group_for_show_agents").removeAttr("disabled"); + $("#spinner_group").css("display", "none"); + $("input[name=add_agent_group_button]").removeAttr("disabled"); + } else { + $("#group_for_show_agents").removeAttr("disabled"); + $("#agents_filter_group").html( + '" + ); + $("#spinner_group").css("display", "none"); + function show_networkmap_node(id_agent_param, refresh_state) { + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { - function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + $(window).resize(function() { + function show_networkmap_node(id_agent_param, refresh_state) { + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { + $(window).resize(function() { + pos_scroll = Math.floor( + $("#content_node_info").width() / 2 + ); - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); + dirty_popup = true; + check_popup_modification(); + }); + } + pos_scroll = Math.floor($("#content_node_info").width() / 2); - dirty_popup = true; - check_popup_modification(); - }); - } - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); - - dirty_popup = true; - check_popup_modification(); - }); - } - } - } - }); - } - } + dirty_popup = true; + check_popup_modification(); + }); + } + } + } + }); + } + } } //////////////////////////////////////////////////////////////////////// @@ -3915,372 +4205,391 @@ var offset_y = 0; var module_inner = null; function get_status_node() { - var params = []; - params.push("get_status_node=1"); - params.push("id=" + id_agent); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - color_status_node = data['status_agent']; - dirty_popup = true; - } - } - }); + var params = []; + params.push("get_status_node=1"); + params.push("id=" + id_agent); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + color_status_node = data["status_agent"]; + dirty_popup = true; + } + } + }); } function get_status_module() { - jQuery.each(modules, function (id, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(id, module) { + if (typeof module == "undefined") return; - - var params = []; - params.push("get_status_module=1"); - params.push("id=" + id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - modules[data['id']].status_color = data['status_color']; - dirty_popup = true; - } - } - }); - - - }); + var params = []; + params.push("get_status_module=1"); + params.push("id=" + id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + modules[data["id"]].status_color = data["status_color"]; + dirty_popup = true; + } + } + }); + }); } function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { + $(window).resize(function() { + pos_scroll = Math.floor($("#content_node_info").width() / 2); - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); - - dirty_popup = true; - check_popup_modification(); - }); + dirty_popup = true; + check_popup_modification(); + }); } function show_tooltip_content(id) { - var params = []; - params.push("get_tooltip_content=1"); - params.push("id=" + id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - $("#tooltip").html(data['content']); - } - } - }); + var params = []; + params.push("get_tooltip_content=1"); + params.push("id=" + id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#tooltip").html(data["content"]); + } + } + }); } function show_tooltip(id, x, y) { - $("#tooltip").css('top', y + 'px'); - $("#tooltip").css('left', x + 'px'); + $("#tooltip").css("top", y + "px"); + $("#tooltip").css("left", x + "px"); - var params1 = []; - params1.push("get_image_path=1"); - params1.push("img_src=" + "images/spinner.gif"); - params1.push("page=include/ajax/skins.ajax"); - jQuery.ajax({ - data: params1.join("&"), - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - $("#tooltip").html(data); - $("#tooltip").css('display', ''); + var params1 = []; + params1.push("get_image_path=1"); + params1.push("img_src=" + "images/spinner.gif"); + params1.push("page=include/ajax/skins.ajax"); + jQuery.ajax({ + data: params1.join("&"), + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + $("#tooltip").html(data); + $("#tooltip").css("display", ""); - show_tooltip_content(id); - } - }); + show_tooltip_content(id); + } + }); } function hide_tooltip() { - $("#tooltip").css('display', 'none'); + $("#tooltip").css("display", "none"); } function inner_module(x, y) { - var return_var = null; + var return_var = null; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if ((x >= module.pos_x) && (x < (module.pos_x + SIZE_MODULE)) && - (y >= module.pos_y) && (y < (module.pos_y + SIZE_MODULE))) { + if ( + x >= module.pos_x && + x < module.pos_x + SIZE_MODULE && + y >= module.pos_y && + y < module.pos_y + SIZE_MODULE + ) { + return_var = key; + } + }); - return_var = key; - } - }); - - return return_var; + return return_var; } function check_popup_modification() { - if (dirty_popup) { - draw_popup(); - dirty_popup = false; - } + if (dirty_popup) { + draw_popup(); + dirty_popup = false; + } } function draw_popup() { - //Calculate the size - count_no_snmp = module_count - count_snmp_modules; + //Calculate the size + count_no_snmp = module_count - count_snmp_modules; - if (count_no_snmp > count_snmp_modules) { - box_height = Math.ceil(count_no_snmp / 2) * VERTICAL_SPACE_MODULES - + VERTICAL_SPACING_BETWEEN_MODULES; - } - else { - box_height = Math.ceil(count_snmp_modules / 2) * VERTICAL_SPACE_MODULES - + VERTICAL_SPACING_BETWEEN_MODULES; - } + if (count_no_snmp > count_snmp_modules) { + box_height = + Math.ceil(count_no_snmp / 2) * VERTICAL_SPACE_MODULES + + VERTICAL_SPACING_BETWEEN_MODULES; + } else { + box_height = + Math.ceil(count_snmp_modules / 2) * VERTICAL_SPACE_MODULES + + VERTICAL_SPACING_BETWEEN_MODULES; + } - //Draw the agent box. - // 2 columns of HORIZONTAL_SPACE_MODULES px for each modules - // + 15 * 2 half each snmp module - box_width = HORIZONTAL_SPACE_MODULES * 2 + SIZE_MODULE; + //Draw the agent box. + // 2 columns of HORIZONTAL_SPACE_MODULES px for each modules + // + 15 * 2 half each snmp module + box_width = HORIZONTAL_SPACE_MODULES * 2 + SIZE_MODULE; + //Resize the canvas if the box is bigger before of paint. + if (box_height + 50 != $("#node_info").attr("height")) { + node_info_height = box_height + 50; + $("#node_info").attr("height", node_info_height); + //$("#node_info").attr("width", node_info_width); + } - //Resize the canvas if the box is bigger before of paint. - if ((box_height + 50) != $("#node_info").attr("height")) { - node_info_height = box_height + 50; - $("#node_info").attr("height", node_info_height); - //$("#node_info").attr("width", node_info_width); - } + if (box_width + 400 != $("#node_info").attr("width")) { + node_info_width = box_width + 400; + $("#node_info").attr("width", node_info_width); + } - if ((box_width + 400) != $("#node_info").attr("width")) { - node_info_width = box_width + 400; - $("#node_info").attr("width", node_info_width); - } + //Clean the canvas + context_popup.clearRect(0, 0, node_info_width, node_info_height); + context_popup.beginPath(); //Erase lines? - //Clean the canvas - context_popup.clearRect(0, 0, node_info_width, node_info_height); - context_popup.beginPath(); //Erase lines? + pos_x = (node_info_width - box_width) / 2 + offset_x; + context_popup.beginPath(); + context_popup.rect( + pos_x, + VERTICAL_SPACING_BETWEEN_MODULES + offset_y, + box_width, + box_height + ); + context_popup.fillStyle = "#ccc"; + context_popup.fill(); + //Draw the global status of agent into the box's border color. + context_popup.lineWidth = BORDER_SIZE_AGENT_BOX; + context_popup.strokeStyle = color_status_node; + context_popup.stroke(); - pos_x = (node_info_width - box_width) / 2 + offset_x; - - context_popup.beginPath(); - context_popup.rect(pos_x, VERTICAL_SPACING_BETWEEN_MODULES + offset_y, box_width, box_height); - context_popup.fillStyle = "#ccc"; - context_popup.fill(); - - //Draw the global status of agent into the box's border color. - context_popup.lineWidth = BORDER_SIZE_AGENT_BOX; - context_popup.strokeStyle = color_status_node; - context_popup.stroke(); - - if (mode_show == 'all') { - draw_snmp_modules(); - draw_modules(); - } - else if (mode_show == 'status_module') { - draw_snmp_modules(); - } + if (mode_show == "all") { + draw_snmp_modules(); + draw_modules(); + } else if (mode_show == "status_module") { + draw_snmp_modules(); + } } function draw_snmp_modules() { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - count = 0; - reset_column = true; + count = 0; + reset_column = true; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if (module.type != 18) return; + if (module.type != 18) return; - if (count < (count_snmp_modules / 2)) { - module_pos_x = pos_x - 15; - text_align = 'right'; - margin_text = 5; - } - else { - if (reset_column) { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - reset_column = false; - } - module_pos_x = pos_x + box_width - 15; - text_align = 'left'; - margin_text = SIZE_MODULE - 5; - } - count++; + if (count < count_snmp_modules / 2) { + module_pos_x = pos_x - 15; + text_align = "right"; + margin_text = 5; + } else { + if (reset_column) { + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + reset_column = false; + } + module_pos_x = pos_x + box_width - 15; + text_align = "left"; + margin_text = SIZE_MODULE - 5; + } + count++; - context_popup.beginPath(); - context_popup.rect(module_pos_x, module_pos_y + offset_y, - SIZE_MODULE, SIZE_MODULE); - context_popup.fillStyle = module.status_color; - context_popup.fill(); - context_popup.lineWidth = 1; - context_popup.strokeStyle = "#000"; - context_popup.stroke(); + context_popup.beginPath(); + context_popup.rect( + module_pos_x, + module_pos_y + offset_y, + SIZE_MODULE, + SIZE_MODULE + ); + context_popup.fillStyle = module.status_color; + context_popup.fill(); + context_popup.lineWidth = 1; + context_popup.strokeStyle = "#000"; + context_popup.stroke(); - modules[key].pos_x = module_pos_x; - modules[key].pos_y = module_pos_y + offset_y; + modules[key].pos_x = module_pos_x; + modules[key].pos_y = module_pos_y + offset_y; - context_popup.fillStyle = "rgb(0,0,0)"; - context_popup.font = 'bold 10px sans-serif'; - context_popup.textBaseline = 'middle'; - context_popup.textAlign = text_align; - dimensions = context_popup.measureText(module.text); - text_pos_x = module_pos_x + margin_text; - text_pos_y = module_pos_y + 40 + offset_y; - context_popup.fillText(module.text, text_pos_x, text_pos_y); + context_popup.fillStyle = "rgb(0,0,0)"; + context_popup.font = "bold 10px sans-serif"; + context_popup.textBaseline = "middle"; + context_popup.textAlign = text_align; + dimensions = context_popup.measureText(module.text); + text_pos_x = module_pos_x + margin_text; + text_pos_y = module_pos_y + 40 + offset_y; + context_popup.fillText(module.text, text_pos_x, text_pos_y); - module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; - }); + module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; + }); } function draw_modules() { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - count = 0; - reset_column = true; + count = 0; + reset_column = true; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if (module.type == 18) return; + if (module.type == 18) return; - if (count < (count_no_snmp / 2)) { - module_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; - text_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES / 2); - } - else { - if (reset_column) { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - reset_column = false; - } - module_pos_x = pos_x + (box_width - HORIZONTAL_SPACE_MODULES) - + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; - text_pos_x = pos_x + (box_width - HORIZONTAL_SPACE_MODULES) + - (HORIZONTAL_SPACE_MODULES / 2) - } - count++; + if (count < count_no_snmp / 2) { + module_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; + text_pos_x = pos_x + HORIZONTAL_SPACE_MODULES / 2; + } else { + if (reset_column) { + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + reset_column = false; + } + module_pos_x = + pos_x + + (box_width - HORIZONTAL_SPACE_MODULES) + + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; + text_pos_x = + pos_x + + (box_width - HORIZONTAL_SPACE_MODULES) + + HORIZONTAL_SPACE_MODULES / 2; + } + count++; - context_popup.beginPath(); - center_orig_x = module_pos_x + (SIZE_MODULE / 2); - center_orig_y = module_pos_y + offset_y + (SIZE_MODULE / 2); - radius = SIZE_MODULE / 2; - context_popup.arc(center_orig_x, center_orig_y, radius, 0, Math.PI * 2, false); - //context_popup.rect(module_pos_x, module_pos_y + offset_y, SIZE_MODULE, SIZE_MODULE); - context_popup.fillStyle = module.status_color; - context_popup.fill(); - context_popup.lineWidth = 1; - context_popup.strokeStyle = "#000"; - context_popup.stroke(); + context_popup.beginPath(); + center_orig_x = module_pos_x + SIZE_MODULE / 2; + center_orig_y = module_pos_y + offset_y + SIZE_MODULE / 2; + radius = SIZE_MODULE / 2; + context_popup.arc( + center_orig_x, + center_orig_y, + radius, + 0, + Math.PI * 2, + false + ); + //context_popup.rect(module_pos_x, module_pos_y + offset_y, SIZE_MODULE, SIZE_MODULE); + context_popup.fillStyle = module.status_color; + context_popup.fill(); + context_popup.lineWidth = 1; + context_popup.strokeStyle = "#000"; + context_popup.stroke(); + modules[key].pos_x = module_pos_x; + modules[key].pos_y = module_pos_y + offset_y; - modules[key].pos_x = module_pos_x; - modules[key].pos_y = module_pos_y + offset_y; + context_popup.fillStyle = "rgb(0,0,0)"; + context_popup.font = "bold 10px sans-serif"; + context_popup.textBaseline = "middle"; + context_popup.textAlign = "center"; + dimensions = context_popup.measureText(module.short_text); - context_popup.fillStyle = "rgb(0,0,0)"; - context_popup.font = 'bold 10px sans-serif'; - context_popup.textBaseline = 'middle'; - context_popup.textAlign = 'center'; - dimensions = context_popup.measureText(module.short_text); + text_pos_y = module_pos_y + 40 + offset_y; + context_popup.fillText(module.short_text, text_pos_x, text_pos_y); - text_pos_y = module_pos_y + 40 + offset_y; - context_popup.fillText(module.short_text, text_pos_x, text_pos_y); + module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; + }); - module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; - }); - - paint_tooltip_module_one_time = false; + paint_tooltip_module_one_time = false; } function update_fictional_node_popup(id) { - name = $("#text-fictional_name").val(); - shape = $("#fictional_shape option:selected").val(); - networmap = $("#networmaps_enterprise option:selected").val(); - radious = $("#fictional_radious").val(); - color = $("#fictional_color").val(); + name = $("#text-fictional_name").val(); + shape = $("#fictional_shape option:selected").val(); + networmap = $("#networmaps_enterprise option:selected").val(); + radious = $("#fictional_radious").val(); + color = $("#fictional_color").val(); - window.close(); + window.close(); - window.opener.update_fictional_node(id, name, shape, networmap, radious, color); + window.opener.update_fictional_node( + id, + name, + shape, + networmap, + radious, + color + ); } diff --git a/pandora_console/include/javascript/openlayers.pandora.js b/pandora_console/include/javascript/openlayers.pandora.js index 32b7282440..ae06463d95 100755 --- a/pandora_console/include/javascript/openlayers.pandora.js +++ b/pandora_console/include/javascript/openlayers.pandora.js @@ -13,508 +13,570 @@ // GNU General Public License for more details. var map; // Map global var object is use in multiple places. -var statusShow = 'all'; +var statusShow = "all"; //The name of layer hierachy because in PHP change the text name into language of user. -var storeLayerNameHierachy = ''; +var storeLayerNameHierachy = ""; function js_refreshParentLines(layerName) { - if (typeof(layerName) == 'undefined') { - layerName = storeLayerNameHierachy; - } - else { - storeLayerNameHierachy = layerName; - } - - listFeaturesWithParents = Array(); - - jQuery.each(map.getLayersByClass("OpenLayers.Layer.Vector"), function (i, layer) { - visible = layer.visibility; - - jQuery.each(layer.features, function (i, feature) { - if (feature.data.type == "point_agent_info") { - id_parent = feature.data.id_parent; - long_lat = feature.data.long_lat; - id = feature.data.id; - status = feature.data.status; - - listFeaturesWithParents[id] = { - 'id': id, - 'id_parent': id_parent, - 'long_lat': long_lat, - 'status': status, - 'visible': visible}; - } - }); - }); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - layer.destroyFeatures(); - - jQuery.each(listFeaturesWithParents, function (i, feature) { - //INI "break" of foreach posibilites - if (typeof(feature) == 'undefined') return; - if (feature.id_parent == 0) return; - if (typeof(listFeaturesWithParents[feature.id_parent]) == 'undefined') return; //The agent have parent but this parent is not in the map. - if ((!feature.visible) - || (!listFeaturesWithParents[feature.id_parent].visible)) return; - if ((isHideFeatureByStatus(feature.status)) - || (isHideFeatureByStatus(listFeaturesWithParents[feature.id_parent].status))) return; - //END "break" of foreach posibilites - - points = new Array(); - - points[0] = new OpenLayers.Geometry.Point(feature.long_lat.lon, feature.long_lat.lat); - points[1] = new OpenLayers.Geometry.Point(listFeaturesWithParents[feature.id_parent].long_lat.lon, listFeaturesWithParents[feature.id_parent].long_lat.lat); - - var line = new OpenLayers.Feature.Vector( - new OpenLayers.Geometry.LineString(points), - null, - { strokeWidth: 2, fillOpacity: 0.2, fillColor: 'red', strokeDashstyle: "dash", strokeColor: 'red'}); - - layer.addFeatures(line); - }); + if (typeof layerName == "undefined") { + layerName = storeLayerNameHierachy; + } else { + storeLayerNameHierachy = layerName; + } + + listFeaturesWithParents = Array(); + + jQuery.each(map.getLayersByClass("OpenLayers.Layer.Vector"), function( + i, + layer + ) { + visible = layer.visibility; + + jQuery.each(layer.features, function(i, feature) { + if (feature.data.type == "point_agent_info") { + id_parent = feature.data.id_parent; + long_lat = feature.data.long_lat; + id = feature.data.id; + status = feature.data.status; + + listFeaturesWithParents[id] = { + id: id, + id_parent: id_parent, + long_lat: long_lat, + status: status, + visible: visible + }; + } + }); + }); + + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + layer.destroyFeatures(); + + jQuery.each(listFeaturesWithParents, function(i, feature) { + //INI "break" of foreach posibilites + if (typeof feature == "undefined") return; + if (feature.id_parent == 0) return; + if (typeof listFeaturesWithParents[feature.id_parent] == "undefined") + return; //The agent have parent but this parent is not in the map. + if (!feature.visible || !listFeaturesWithParents[feature.id_parent].visible) + return; + if ( + isHideFeatureByStatus(feature.status) || + isHideFeatureByStatus(listFeaturesWithParents[feature.id_parent].status) + ) + return; + //END "break" of foreach posibilites + + points = new Array(); + + points[0] = new OpenLayers.Geometry.Point( + feature.long_lat.lon, + feature.long_lat.lat + ); + points[1] = new OpenLayers.Geometry.Point( + listFeaturesWithParents[feature.id_parent].long_lat.lon, + listFeaturesWithParents[feature.id_parent].long_lat.lat + ); + + var line = new OpenLayers.Feature.Vector( + new OpenLayers.Geometry.LineString(points), + null, + { + strokeWidth: 2, + fillOpacity: 0.2, + fillColor: "red", + strokeDashstyle: "dash", + strokeColor: "red" + } + ); + + layer.addFeatures(line); + }); } /** * Inicialize the map in the browser and the object map. - * + * * @param string id_div The id of div to draw the map. * @param integer initial_zoom The initial zoom to show the map. * @param float center_latitude The coord of latitude for center. * @param float center_longitude The coord of longitude for center. * @param array objBaseLayers The array of baselayers with number index, and the baselayer is another asociative array that content 'type', 'name' and 'url'. * @param array arrayControls The array of enabled controls, the controls is: 'Navigation', 'MousePosition', 'OverviewMap', 'PanZoom', 'PanZoomBar', 'ScaleLine', 'Scale' - * + * * @return None */ -function js_printMap(id_div, initial_zoom, center_latitude, center_longitude, objBaseLayers, arrayControls) { - controlsList = []; - - for (var controlIndex in arrayControls) { - if (isInt(controlIndex)) { - switch (arrayControls[controlIndex]) { - case 'Navigation': - controlsList.push(new OpenLayers.Control.Navigation()); - break; - case 'MousePosition': - controlsList.push(new OpenLayers.Control.MousePosition()); - break; - case 'OverviewMap': - controlsList.push(new OpenLayers.Control.OverviewMap()); - break; - case 'PanZoom': - controlsList.push(new OpenLayers.Control.PanZoom()); - break; - case 'PanZoomBar': - controlsList.push(new OpenLayers.Control.PanZoomBar()); - break; - case 'ScaleLine': - controlsList.push(new OpenLayers.Control.ScaleLine()); - break; - case 'Scale': - controlsList.push(new OpenLayers.Control.Scale()); - break; - case 'layerSwitcher': - controlsList.push(new OpenLayers.Control.LayerSwitcher()); - break; - } - } - } - - - var option = { - controls: controlsList, - projection: new OpenLayers.Projection("EPSG:900913"), - displayProjection: new OpenLayers.Projection("EPSG:4326"), - units: "m", - numZoomLevels: 18, - maxResolution: 156543.0339, - maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)}; - - map = new OpenLayers.Map(id_div, option); - map.events.Event - var baseLayer = null; - - map.events.on({"zoomend": EventZoomEnd}); - map.events.on({"mouseup": EventZoomEnd}); +function js_printMap( + id_div, + initial_zoom, + center_latitude, + center_longitude, + objBaseLayers, + arrayControls +) { + controlsList = []; - //Define the maps layer - for (var baselayerIndex in objBaseLayers) { - if (isInt(baselayerIndex)) { - switch (objBaseLayers[baselayerIndex]['type']) { - case 'OSM': - baseLayer = null; - baseLayer = new OpenLayers.Layer.OSM( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - { - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'Gmap': - switch (objBaseLayers[baselayerIndex]['gmap_type']) { - case 'G_PHYSICAL_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_PHYSICAL_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'G_HYBRID_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_HYBRID_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'G_SATELLITE_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_SATELLITE_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - default: - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - } - break; - case 'Static_Image': - baseLayer = null; - baseLayer = new OpenLayers.Layer.Image( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - new OpenLayers.Bounds(objBaseLayers[baselayerIndex]['bb_left'], - objBaseLayers[baselayerIndex]['bb_bottom'], - objBaseLayers[baselayerIndex]['bb_right'], - objBaseLayers[baselayerIndex]['bb_top'] - ), - new OpenLayers.Size(objBaseLayers[baselayerIndex]['image_width'], objBaseLayers[baselayerIndex]['image_height']), - { - projection: new OpenLayers.Projection("EPSG:4326"), - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'] - } - ); - map.addLayer(baseLayer); - break; - case 'WMS': - // http:///geoserver/wms - // ?bbox=-130,24,-66,50 - // &styles=population - // &Format=application/openlayers - // &request=GetMap - // &layers=topp:states - // &width=550 - // &height=250 - // &srs=EPSG:4326 - var layer = new OpenLayers.Layer.WMS( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - { - layers: objBaseLayers[baselayerIndex]['layers'], - format: "image/png" - }, - { - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'] - } - ); - map.addLayer(layer); - break; - } - } - } - - var lonLat = new OpenLayers.LonLat(center_longitude, center_latitude) - .transform(map.displayProjection, map.getProjectionObject()); - - map.setCenter (lonLat, initial_zoom); - + for (var controlIndex in arrayControls) { + if (isInt(controlIndex)) { + switch (arrayControls[controlIndex]) { + case "Navigation": + controlsList.push(new OpenLayers.Control.Navigation()); + break; + case "MousePosition": + controlsList.push(new OpenLayers.Control.MousePosition()); + break; + case "OverviewMap": + controlsList.push(new OpenLayers.Control.OverviewMap()); + break; + case "PanZoom": + controlsList.push(new OpenLayers.Control.PanZoom()); + break; + case "PanZoomBar": + controlsList.push(new OpenLayers.Control.PanZoomBar()); + break; + case "ScaleLine": + controlsList.push(new OpenLayers.Control.ScaleLine()); + break; + case "Scale": + controlsList.push(new OpenLayers.Control.Scale()); + break; + case "layerSwitcher": + controlsList.push(new OpenLayers.Control.LayerSwitcher()); + break; + } + } + } + + var option = { + controls: controlsList, + projection: new OpenLayers.Projection("EPSG:900913"), + displayProjection: new OpenLayers.Projection("EPSG:4326"), + units: "m", + numZoomLevels: 18, + maxResolution: 156543.0339, + maxExtent: new OpenLayers.Bounds( + -20037508, + -20037508, + 20037508, + 20037508.34 + ) + }; + + map = new OpenLayers.Map(id_div, option); + map.events.Event; + var baseLayer = null; + + map.events.on({ zoomend: EventZoomEnd }); + map.events.on({ mouseup: EventZoomEnd }); + + //Define the maps layer + for (var baselayerIndex in objBaseLayers) { + if (isInt(baselayerIndex)) { + switch (objBaseLayers[baselayerIndex]["type"]) { + case "OSM": + baseLayer = null; + baseLayer = new OpenLayers.Layer.OSM( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + { + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "Gmap": + switch (objBaseLayers[baselayerIndex]["gmap_type"]) { + case "G_PHYSICAL_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_PHYSICAL_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "G_HYBRID_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_HYBRID_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "G_SATELLITE_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_SATELLITE_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + default: + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + } + break; + case "Static_Image": + baseLayer = null; + baseLayer = new OpenLayers.Layer.Image( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + new OpenLayers.Bounds( + objBaseLayers[baselayerIndex]["bb_left"], + objBaseLayers[baselayerIndex]["bb_bottom"], + objBaseLayers[baselayerIndex]["bb_right"], + objBaseLayers[baselayerIndex]["bb_top"] + ), + new OpenLayers.Size( + objBaseLayers[baselayerIndex]["image_width"], + objBaseLayers[baselayerIndex]["image_height"] + ), + { + projection: new OpenLayers.Projection("EPSG:4326"), + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"] + } + ); + map.addLayer(baseLayer); + break; + case "WMS": + // http:///geoserver/wms + // ?bbox=-130,24,-66,50 + // &styles=population + // &Format=application/openlayers + // &request=GetMap + // &layers=topp:states + // &width=550 + // &height=250 + // &srs=EPSG:4326 + var layer = new OpenLayers.Layer.WMS( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + { + layers: objBaseLayers[baselayerIndex]["layers"], + format: "image/png" + }, + { + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"] + } + ); + map.addLayer(layer); + break; + } + } + } + + var lonLat = new OpenLayers.LonLat( + center_longitude, + center_latitude + ).transform(map.displayProjection, map.getProjectionObject()); + + map.setCenter(lonLat, initial_zoom); } -function EventZoomEnd (evt,zoom = map.zoom) { - if(evt == null){ - var actual_zoom = (zoom < 6) ? 6 : zoom; - } - else{ - var actual_zoom = (evt.object.zoom < 6) ? 6 : evt.object.zoom; - } - - - var max_width_marker = 38; - var max_zoom_map = map.numZoomLevels; - var max_font_size = 15; - - var actual_font_size = (actual_zoom * max_font_size) / max_zoom_map; - - jQuery.each($("tspan"), function (i, tspan) { - if (actual_zoom <= 18 && actual_zoom > 13) - actual_font_size = (max_font_size - 3); - else if (actual_zoom <= 13 && actual_zoom >= 8) - actual_font_size = (max_font_size - 6); - else if (actual_zoom <= 8) - actual_font_size = (max_font_size - 6); - $(tspan).css('font-size', actual_font_size); - }); - - var layers = map.getLayersByClass("OpenLayers.Layer.Vector"); - - - jQuery.each(layers, function (i, layer) { - var features = layer.features; - - jQuery.each(features, function (j, feature) { - var graphicHeight = feature.style.graphicHeight || -1; - var graphicWidth = feature.style.graphicWidth || -1; - - if (graphicHeight > 0 && graphicWidth > 0) { - var new_width_marker = (actual_zoom * max_width_marker) / max_zoom_map; - var new_height_marker = (actual_zoom * max_width_marker) / max_zoom_map; - - feature.style.fontSize = '' + actual_font_size + ' !important'; - feature.style.graphicHeight = new_height_marker; - feature.style.graphicWidth = new_width_marker; - feature.style.labelYOffset = (new_width_marker * -1); - } - - }); - layer.redraw(); - }); +function EventZoomEnd(evt, zoom = map.zoom) { + if (evt == null) { + var actual_zoom = zoom < 6 ? 6 : zoom; + } else { + var actual_zoom = evt.object.zoom < 6 ? 6 : evt.object.zoom; + } + + var max_width_marker = 38; + var max_zoom_map = map.numZoomLevels; + var max_font_size = 15; + + var actual_font_size = (actual_zoom * max_font_size) / max_zoom_map; + + jQuery.each($("tspan"), function(i, tspan) { + if (actual_zoom <= 18 && actual_zoom > 13) + actual_font_size = max_font_size - 3; + else if (actual_zoom <= 13 && actual_zoom >= 8) + actual_font_size = max_font_size - 6; + else if (actual_zoom <= 8) actual_font_size = max_font_size - 6; + $(tspan).css("font-size", actual_font_size); + }); + + var layers = map.getLayersByClass("OpenLayers.Layer.Vector"); + + jQuery.each(layers, function(i, layer) { + var features = layer.features; + + jQuery.each(features, function(j, feature) { + var graphicHeight = feature.style.graphicHeight || -1; + var graphicWidth = feature.style.graphicWidth || -1; + + if (graphicHeight > 0 && graphicWidth > 0) { + var new_width_marker = (actual_zoom * max_width_marker) / max_zoom_map; + var new_height_marker = (actual_zoom * max_width_marker) / max_zoom_map; + + feature.style.fontSize = "" + actual_font_size + " !important"; + feature.style.graphicHeight = new_height_marker; + feature.style.graphicWidth = new_width_marker; + feature.style.labelYOffset = new_width_marker * -1; + } + }); + layer.redraw(); + }); } /** * Change the style of state button, and call the function "hideAgentsStatus" * whith new state for agents icons to show. - * + * * @param string newShowStatus State to show. * @return none */ function changeShowStatus(newShowStatus) { - statusShow = newShowStatus; - hideAgentsStatus(); - EventZoomEnd(null,map.zoom); - js_refreshParentLines(); + statusShow = newShowStatus; + hideAgentsStatus(); + EventZoomEnd(null, map.zoom); + js_refreshParentLines(); } /** * Function that change the visibility of feature by status and state var * statusShow - * + * * @param object feature The feature to change the visibility * @param int status The status code, it can be (1,4) for bad, (2) for warning, (0) for ok and the rest * @return */ function hideFeatureByStatus(feature, status) { - feature.style.display = 'none'; - - switch (statusShow) { - case 'bad': - if ((status == 1) || (status == 4) || (status == 100)) - feature.style.display = ''; - break; - case 'warning': - if ((status == 2) || (status == 200)) - feature.style.display = ''; - break; - case 'ok': - if ((status == 0) || (status == 300)) - feature.style.display = ''; - break; - case 'default': - if ((status != 1) && (status != 4) && (status != 2) && (status != 0) && (status != 100) && (status != 200) && (status != 300)) - feature.style.display = ''; - break; - case 'all': - feature.style.display = ''; - break; - } + feature.style.display = "none"; + + switch (statusShow) { + case "bad": + if (status == 1 || status == 4 || status == 100) + feature.style.display = ""; + break; + case "warning": + if (status == 2 || status == 200) feature.style.display = ""; + break; + case "ok": + if (status == 0 || status == 300) feature.style.display = ""; + break; + case "default": + if ( + status != 1 && + status != 4 && + status != 2 && + status != 0 && + status != 100 && + status != 200 && + status != 300 + ) + feature.style.display = ""; + break; + case "all": + feature.style.display = ""; + break; + } } /** * Test if the feature is hidden. - * - * @param integer status The integer status. + * + * @param integer status The integer status. * @return boolean The true or false. */ function isHideFeatureByStatus(status) { - returnVar = true; - - switch (statusShow) { - case 'bad': - if ((status == 1) || (status == 4) || (status == 100)) - returnVar = false; - break; - case 'warning': - if ((status == 2) || (status == 200)) - returnVar = false; - break; - case 'ok': - if ((status == 0) || (status == 300)) - returnVar = false; - break; - case 'default': - if ((status != 1) && (status != 4) && (status != 2) && (status != 0) && (status != 100) && (status != 200) && (status != 300)) - returnVar = false; - break; - case 'all': - returnVar = false; - break; - } - - return returnVar; + returnVar = true; + + switch (statusShow) { + case "bad": + if (status == 1 || status == 4 || status == 100) returnVar = false; + break; + case "warning": + if (status == 2 || status == 200) returnVar = false; + break; + case "ok": + if (status == 0 || status == 300) returnVar = false; + break; + case "default": + if ( + status != 1 && + status != 4 && + status != 2 && + status != 0 && + status != 100 && + status != 200 && + status != 300 + ) + returnVar = false; + break; + case "all": + returnVar = false; + break; + } + + return returnVar; } /** * Hide the agents icons that not is of current state var statusShow. - * + * * @return none */ function hideAgentsStatus() { - layers = map.getLayersByClass("OpenLayers.Layer.Vector"); - - jQuery.each(layers, function (i, layer) { - features = layer.features; - - jQuery.each(features, function (j, feature) { - status = feature.data.status; - - hideFeatureByStatus(feature, status); - }); - - layer.redraw(); - }); + layers = map.getLayersByClass("OpenLayers.Layer.Vector"); + + jQuery.each(layers, function(i, layer) { + features = layer.features; + + jQuery.each(features, function(j, feature) { + status = feature.data.status; + + hideFeatureByStatus(feature, status); + }); + + layer.redraw(); + }); } /** * Change the refresh time for the map. - * + * * @param int time seconds * @return none */ function changeRefreshTime(time) { - refreshAjaxIntervalSeconds = time * 1000; - - clearInterval(idIntervalAjax); - idIntervalAjax = setInterval("clock_ajax_refresh()", refreshAjaxIntervalSeconds); - oldRefreshAjaxIntervalSeconds = refreshAjaxIntervalSeconds; + refreshAjaxIntervalSeconds = time * 1000; + + clearInterval(idIntervalAjax); + idIntervalAjax = setInterval( + "clock_ajax_refresh()", + refreshAjaxIntervalSeconds + ); + oldRefreshAjaxIntervalSeconds = refreshAjaxIntervalSeconds; } /** * Make the layer in the map. - * + * * @param string name The name of layer, it's show in the toolbar of layer. * @param boolean visible Set visible the layer. - * @param array dot It's a asociative array that have 'url' of icon image, 'width' in pixeles and 'height' in pixeles. - * + * @param array dot It's a asociative array that have 'url' of icon image, 'width' in pixeles and 'height' in pixeles. + * * @return object The layer created. */ function js_makeLayer(name, visible, dot) { - if (dot == null) { - dot = Array(); - dot['url'] = 'images/dot_green.png'; - dot['width'] = 20; //11; - dot['height'] = 20; //11; - } - - //Set the style in layer - var style = new OpenLayers.StyleMap( - {fontColor: "#ff0000", - labelYOffset: - dot['height'], - graphicHeight: dot['height'], - graphicWidth: dot['width'], - externalGraphic: dot['url'], - label:"${nombre}" - } - ); - - //Make the layer as type vector - var layer = new OpenLayers.Layer.Vector(name, {styleMap: style}); - - layer.setVisibility(visible); - map.addLayer(layer); - - return layer; + if (dot == null) { + dot = Array(); + dot["url"] = "images/dot_green.png"; + dot["width"] = 20; //11; + dot["height"] = 20; //11; + } + + //Set the style in layer + var style = new OpenLayers.StyleMap({ + fontColor: "#ff0000", + labelYOffset: -dot["height"], + graphicHeight: dot["height"], + graphicWidth: dot["width"], + externalGraphic: dot["url"], + label: "${nombre}" + }); + + //Make the layer as type vector + var layer = new OpenLayers.Layer.Vector(name, { styleMap: style }); + + layer.setVisibility(visible); + map.addLayer(layer); + + return layer; } /** * Active and set callbacks of events. - * - * @param callbackFunClick Function to call when the user make single click in the map. - * + * + * @param callbackFunClick Function to call when the user make single click in the map. + * * @return None */ function js_activateEvents(callbackFunClick) { - /** - * Pandora click openlayers object. - */ - OpenLayers.Control.PandoraClick = OpenLayers.Class(OpenLayers.Control, { - defaultHandlerOptions: { - 'single': true, - 'double': false, - 'pixelTolerance': 0, - 'stopSingle': false, - 'stopDouble': false - }, - initialize: function(options) { - this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions); - OpenLayers.Control.prototype.initialize.apply(this, arguments); - this.handler = new OpenLayers.Handler.Click(this, {'click': options.callbackFunctionClick}, this.handlerOptions); - } - }); - - var click = new OpenLayers.Control.PandoraClick({callbackFunctionClick: callbackFunClick}); - - map.addControl(click); - click.activate(); + /** + * Pandora click openlayers object. + */ + OpenLayers.Control.PandoraClick = OpenLayers.Class(OpenLayers.Control, { + defaultHandlerOptions: { + single: true, + double: false, + pixelTolerance: 0, + stopSingle: false, + stopDouble: false + }, + initialize: function(options) { + this.handlerOptions = OpenLayers.Util.extend( + {}, + this.defaultHandlerOptions + ); + OpenLayers.Control.prototype.initialize.apply(this, arguments); + this.handler = new OpenLayers.Handler.Click( + this, + { click: options.callbackFunctionClick }, + this.handlerOptions + ); + } + }); + + var click = new OpenLayers.Control.PandoraClick({ + callbackFunctionClick: callbackFunClick + }); + + map.addControl(click); + click.activate(); } /** * Test the value is a int. - * + * * @param mixed X The val that test to if is int. - * + * * @return Boolean True if it's int. */ function isInt(x) { - var y=parseInt(x); - if (isNaN(y)) return false; - return x==y && x.toString()==y.toString(); + var y = parseInt(x); + if (isNaN(y)) return false; + return x == y && x.toString() == y.toString(); } /** * Set the visibility of a layer - * + * * @param string name The name of layer. * @param boolean action True or false */ function showHideLayer(name, action) { - var layer = map.getLayersByName(name); + var layer = map.getLayersByName(name); - layer[0].setVisibility(action); + layer[0].setVisibility(action); } /** * Add a point with the default icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. @@ -523,38 +585,51 @@ function showHideLayer(name, action) { * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. * @param integer idParent Id Parent of agent. - * + * * @return Object The point. */ -function js_addAgentPoint(layerName, pointName, lon, lat, id, type_string, statusAgent, idParent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - feature = new OpenLayers.Feature.Vector(point, - { - id_parent: idParent, - status: statusAgent, - nombre: pointName, - id: id, - type: type_string, - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) - }); +function js_addAgentPoint( + layerName, + pointName, + lon, + lat, + id, + type_string, + statusAgent, + idParent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + feature = new OpenLayers.Feature.Vector(point, { + id_parent: idParent, + status: statusAgent, + nombre: pointName, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a point with the default icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. @@ -562,207 +637,307 @@ function js_addAgentPoint(layerName, pointName, lon, lat, id, type_string, statu * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. - * + * * @return Object The point. */ -function js_addPoint(layerName, pointName, lon, lat, id, type_string, statusAgent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); +function js_addPoint( + layerName, + pointName, + lon, + lat, + id, + type_string, + statusAgent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var layer = map.getLayersByName(layerName); - layer = layer[0]; + var layer = map.getLayersByName(layerName); + layer = layer[0]; - feature = new OpenLayers.Feature.Vector(point,{status: statusAgent, nombre: pointName, id: id, type: type_string, long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) }); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + feature = new OpenLayers.Feature.Vector(point, { + status: statusAgent, + nombre: pointName, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a agent point and set the icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. * @param float lat The coord of longitude for point. - * @param string icon Url of icon image. + * @param string icon Url of icon image. * @param integer width The width of icon. * @param integer height The height of icon. * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. * @param integer idParent Id Parent of agent. - * + * * @return Object The point. */ -function js_addAgentPointExtent(layerName, pointName, lon, lat, icon, width, height, id, type_string, statusAgent, idParent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - if (typeof(statusAgent) == 'string') - statusA = parseInt(statusAgent); - else - statusA = statusAgent; - - feature = new OpenLayers.Feature.Vector(point, - { - id_parent: idParent.toString(), - status: statusA, - id: id.toString(), - type: type_string, - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) - }, - { - fontWeight: "bolder", - fontColor: "#00014F", - labelYOffset: -height, - graphicHeight: width, - graphicWidth: height, - externalGraphic: icon, - label: pointName - }); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; +function js_addAgentPointExtent( + layerName, + pointName, + lon, + lat, + icon, + width, + height, + id, + type_string, + statusAgent, + idParent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); + + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + if (typeof statusAgent == "string") statusA = parseInt(statusAgent); + else statusA = statusAgent; + + feature = new OpenLayers.Feature.Vector( + point, + { + id_parent: idParent.toString(), + status: statusA, + id: id.toString(), + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fontWeight: "bolder", + fontColor: "#00014F", + labelYOffset: -height, + graphicHeight: width, + graphicWidth: height, + externalGraphic: icon, + label: pointName + } + ); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a point and set the icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. * @param float lat The coord of longitude for point. - * @param string icon Url of icon image. + * @param string icon Url of icon image. * @param integer width The width of icon. * @param integer height The height of icon. * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. - * + * * @return Object The point. */ -function js_addPointExtent(layerName, pointName, lon, lat, icon, width, height, id, type_string, statusAgent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); +function js_addPointExtent( + layerName, + pointName, + lon, + lat, + icon, + width, + height, + id, + type_string, + statusAgent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - if (typeof(statusAgent) == 'string') - statusA = parseInt(statusAgent); - else - statusA = statusAgent; - - feature = new OpenLayers.Feature.Vector(point,{status: statusA, id: id, type: type_string, long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) }, {fontWeight: "bolder", fontColor: "#00014F", labelYOffset: -height, graphicHeight: width, graphicWidth: height, externalGraphic: icon, label: pointName}); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + if (typeof statusAgent == "string") statusA = parseInt(statusAgent); + else statusA = statusAgent; + + feature = new OpenLayers.Feature.Vector( + point, + { + status: statusA, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fontWeight: "bolder", + fontColor: "#00014F", + labelYOffset: -height, + graphicHeight: width, + graphicWidth: height, + externalGraphic: icon, + label: pointName + } + ); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** - * + * * @param string layerName The name of layer to put the point path. * @param float lon The coord of latitude for point path. * @param float lat The coord of longitude for point path. * @param string color The color of point path in rrggbb format. * @param boolean manual The type of point path, if it's manual, the point is same a donut. * @param string id The id of point path. - * + * * @return None */ function js_addPointPath(layerName, lon, lat, color, manual, id) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var pointRadiusNormal = 4; - var strokeWidth = 2; - var pointRadiusManual = pointRadiusNormal - (strokeWidth / 2); - - if (manual) { - point = new OpenLayers.Feature.Vector(point,{estado: "ok", id: id, type: "point_path_info", - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject())}, - {fillColor: "#ffffff", pointRadius: pointRadiusManual, stroke: 1, strokeColor: color, strokeWidth: strokeWidth, cursor: "pointer"} - ); - } - else { - point = new OpenLayers.Feature.Vector(point,{estado: "ok", id: id, type: "point_path_info", - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject())}, - {fillColor: color, pointRadius: pointRadiusNormal, cursor: "pointer"} - ); - } + var layer = map.getLayersByName(layerName); + layer = layer[0]; - layer.addFeatures(point); + var pointRadiusNormal = 4; + var strokeWidth = 2; + var pointRadiusManual = pointRadiusNormal - strokeWidth / 2; + + if (manual) { + point = new OpenLayers.Feature.Vector( + point, + { + estado: "ok", + id: id, + type: "point_path_info", + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fillColor: "#ffffff", + pointRadius: pointRadiusManual, + stroke: 1, + strokeColor: color, + strokeWidth: strokeWidth, + cursor: "pointer" + } + ); + } else { + point = new OpenLayers.Feature.Vector( + point, + { + estado: "ok", + id: id, + type: "point_path_info", + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { fillColor: color, pointRadius: pointRadiusNormal, cursor: "pointer" } + ); + } + + layer.addFeatures(point); } /** * Draw the lineString. - * + * * @param string layerName The name of layer to put the point path. * @param Array points The array have content the points, but the point as lonlat openlayers object without transformation. * @param string color The color of point path in rrggbb format. - * + * * @return None */ function js_addLineString(layerName, points, color) { - var mapPoints = new Array(points.length); - var layer = map.getLayersByName(layerName); + var mapPoints = new Array(points.length); + var layer = map.getLayersByName(layerName); - layer = layer[0]; - - for (var i = 0; i < points.length; i++) { - mapPoints[i] = points[i].transform(map.displayProjection, map.getProjectionObject()); - } - - var lineString = new OpenLayers.Feature.Vector( - new OpenLayers.Geometry.LineString(mapPoints), - null, - { strokeWidth: 2, fillOpacity: 0.2, fillColor: color, strokeColor: color} - ); + layer = layer[0]; - layer.addFeatures(lineString); + for (var i = 0; i < points.length; i++) { + mapPoints[i] = points[i].transform( + map.displayProjection, + map.getProjectionObject() + ); + } + + var lineString = new OpenLayers.Feature.Vector( + new OpenLayers.Geometry.LineString(mapPoints), + null, + { strokeWidth: 2, fillOpacity: 0.2, fillColor: color, strokeColor: color } + ); + + layer.addFeatures(lineString); } /** * Return feature object for a id agent passed. - * + * * @param interger id The agent id. * @return mixed Return the feature object, if it didn't found then return null. */ function searchPointAgentById(id) { - for (layerIndex = 0; layerIndex < map.getNumLayers(); layerIndex++) { - layer = map.layers[layerIndex]; + for (layerIndex = 0; layerIndex < map.getNumLayers(); layerIndex++) { + layer = map.layers[layerIndex]; - if (layer.features != undefined) { - for (featureIndex = 0; featureIndex < layer.features.length; featureIndex++) { - feature = layer.features[featureIndex]; - if (feature.data.id == id) { - return feature; - } - } - } - } + if (layer.features != undefined) { + for ( + featureIndex = 0; + featureIndex < layer.features.length; + featureIndex++ + ) { + feature = layer.features[featureIndex]; + if (feature.data.id == id) { + return feature; + } + } + } + } - return null; + return null; } diff --git a/pandora_console/include/javascript/pandora.base64.js b/pandora_console/include/javascript/pandora.base64.js index 174872b0e6..53c6e996ae 100644 --- a/pandora_console/include/javascript/pandora.base64.js +++ b/pandora_console/include/javascript/pandora.base64.js @@ -2,8 +2,7 @@ // Exports the strToBase64 and base64ToStr functions -(function () { - +(function() { "use strict"; /*\ @@ -16,38 +15,40 @@ /* Array of bytes to base64 string decoding */ - function b64ToUint6 (nChr) { - - return nChr > 64 && nChr < 91 ? - nChr - 65 - : nChr > 96 && nChr < 123 ? - nChr - 71 - : nChr > 47 && nChr < 58 ? - nChr + 4 - : nChr === 43 ? - 62 - : nChr === 47 ? - 63 - : - 0; - + function b64ToUint6(nChr) { + return nChr > 64 && nChr < 91 + ? nChr - 65 + : nChr > 96 && nChr < 123 + ? nChr - 71 + : nChr > 47 && nChr < 58 + ? nChr + 4 + : nChr === 43 + ? 62 + : nChr === 47 + ? 63 + : 0; } - function base64DecToArr (sBase64, nBlocksSize) { + function base64DecToArr(sBase64, nBlocksSize) { + var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), + nInLen = sB64Enc.length, + nOutLen = nBlocksSize + ? Math.ceil(((nInLen * 3 + 1) >> 2) / nBlocksSize) * nBlocksSize + : (nInLen * 3 + 1) >> 2, + taBytes = new Uint8Array(nOutLen); - var - sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, - nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); - - for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { + for ( + var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; + nInIdx < nInLen; + nInIdx++ + ) { nMod4 = nInIdx & 3; - nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; + nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << (18 - 6 * nMod4); if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { - taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; + taBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255; } nUint24 = 0; - } } @@ -56,79 +57,114 @@ /* Base64 string to array encoding */ - function uint6ToB64 (nUint6) { - - return nUint6 < 26 ? - nUint6 + 65 - : nUint6 < 52 ? - nUint6 + 71 - : nUint6 < 62 ? - nUint6 - 4 - : nUint6 === 62 ? - 43 - : nUint6 === 63 ? - 47 - : - 65; - + function uint6ToB64(nUint6) { + return nUint6 < 26 + ? nUint6 + 65 + : nUint6 < 52 + ? nUint6 + 71 + : nUint6 < 62 + ? nUint6 - 4 + : nUint6 === 62 + ? 43 + : nUint6 === 63 + ? 47 + : 65; } - function base64EncArr (aBytes) { - - var nMod3 = 2, sB64Enc = ""; + function base64EncArr(aBytes) { + var nMod3 = 2, + sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; - if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } - nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); + if (nIdx > 0 && ((nIdx * 4) / 3) % 76 === 0) { + sB64Enc += "\r\n"; + } + nUint24 |= aBytes[nIdx] << ((16 >>> nMod3) & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { - sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); + sB64Enc += String.fromCharCode( + uint6ToB64((nUint24 >>> 18) & 63), + uint6ToB64((nUint24 >>> 12) & 63), + uint6ToB64((nUint24 >>> 6) & 63), + uint6ToB64(nUint24 & 63) + ); nUint24 = 0; } } - return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); - + return ( + sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==") + ); } /* UTF-8 array to DOMString and vice versa */ - function UTF8ArrToStr (aBytes) { - + function UTF8ArrToStr(aBytes) { var sView = ""; for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { nPart = aBytes[nIdx]; sView += String.fromCharCode( - nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ - /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */ - (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ - (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ - (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ - (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ - (nPart - 192 << 6) + aBytes[++nIdx] - 128 - : /* nPart < 127 ? */ /* one byte */ - nPart + nPart > 251 && nPart < 254 && nIdx + 5 < nLen /* six bytes */ + ? /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */ + (nPart - 252) * 1073741824 + + ((aBytes[++nIdx] - 128) << 24) + + ((aBytes[++nIdx] - 128) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 247 && nPart < 252 && nIdx + 4 < nLen /* five bytes */ + ? ((nPart - 248) << 24) + + ((aBytes[++nIdx] - 128) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 239 && nPart < 248 && nIdx + 3 < nLen /* four bytes */ + ? ((nPart - 240) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 223 && nPart < 240 && nIdx + 2 < nLen /* three bytes */ + ? ((nPart - 224) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 191 && nPart < 224 && nIdx + 1 < nLen /* two bytes */ + ? ((nPart - 192) << 6) + aBytes[++nIdx] - 128 /* nPart < 127 ? */ + : /* one byte */ + nPart ); } return sView; - } - function strToUTF8Arr (sDOMStr) { - - var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; + function strToUTF8Arr(sDOMStr) { + var aBytes, + nChr, + nStrLen = sDOMStr.length, + nArrLen = 0; /* mapping... */ for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { nChr = sDOMStr.charCodeAt(nMapIdx); - nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; + nArrLen += + nChr < 0x80 + ? 1 + : nChr < 0x800 + ? 2 + : nChr < 0x10000 + ? 3 + : nChr < 0x200000 + ? 4 + : nChr < 0x4000000 + ? 5 + : 6; } aBytes = new Uint8Array(nArrLen); @@ -147,55 +183,52 @@ } else if (nChr < 0x10000) { /* three bytes */ aBytes[nIdx++] = 224 + (nChr >>> 12); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x200000) { /* four bytes */ aBytes[nIdx++] = 240 + (nChr >>> 18); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x4000000) { /* five bytes */ aBytes[nIdx++] = 248 + (nChr >>> 24); - aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 18) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); - } else /* if (nChr <= 0x7fffffff) */ { + } /* if (nChr <= 0x7fffffff) */ else { /* six bytes */ aBytes[nIdx++] = 252 + (nChr >>> 30); - aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 24) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 18) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } } return aBytes; - } - function strToBase64 (strInput) { - if (typeof strInput !== 'string') - throw new TypeError('The input should be a string') + function strToBase64(strInput) { + if (typeof strInput !== "string") + throw new TypeError("The input should be a string"); - return base64EncArr(strToUTF8Arr(strInput)) + return base64EncArr(strToUTF8Arr(strInput)); } - function base64ToStr (base64Input) { - if (typeof base64Input !== 'string') - throw new TypeError('The input should be a string') + function base64ToStr(base64Input) { + if (typeof base64Input !== "string") + throw new TypeError("The input should be a string"); - return UTF8ArrToStr(base64DecToArr(base64Input)) + return UTF8ArrToStr(base64DecToArr(base64Input)); } // Export the functions to the global scope if (window) { - if (!window.strToBase64) - window.strToBase64 = strToBase64 - if (!window.base64ToStr) - window.base64ToStr = base64ToStr + if (!window.strToBase64) window.strToBase64 = strToBase64; + if (!window.base64ToStr) window.base64ToStr = base64ToStr; } -}) () +})(); diff --git a/pandora_console/include/javascript/pandora.js b/pandora_console/include/javascript/pandora.js index 1ca0759801..37a9987812 100644 --- a/pandora_console/include/javascript/pandora.js +++ b/pandora_console/include/javascript/pandora.js @@ -1,29 +1,44 @@ -var ENTERPRISE_DIR = 'enterprise'; +var ENTERPRISE_DIR = "enterprise"; /* Function to hide/unhide a specific Div id */ -function toggleDiv (divid){ - if (document.getElementById(divid).style.display == 'none') { - document.getElementById(divid).style.display = 'block'; - } - else { - document.getElementById(divid).style.display = 'none'; - } +function toggleDiv(divid) { + if (document.getElementById(divid).style.display == "none") { + document.getElementById(divid).style.display = "block"; + } else { + document.getElementById(divid).style.display = "none"; + } } -function winopeng (url, wid) { - open (url, wid,"width=1000,height=550,status=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes"); - // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE - status = wid; +function winopeng(url, wid) { + open( + url, + wid, + "width=1000,height=550,status=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes" + ); + // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE + status = wid; } -function winopeng_var (url, wid, width, height) { - open (url, wid,"width="+width+",height="+height+",status=no,toolbar=no,menubar=no,scrollbar=yes"); - // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE - status = wid; +function winopeng_var(url, wid, width, height) { + open( + url, + wid, + "width=" + + width + + ",height=" + + height + + ",status=no,toolbar=no,menubar=no,scrollbar=yes" + ); + // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE + status = wid; } -function open_help (help_id, home_url, id_user) { - open (home_url+"general/pandora_help.php?id="+help_id+"&id_user="+id_user, "pandorahelp", "width=650,height=500,status=0,toolbar=0,menubar=0,scrollbars=1,location=0"); +function open_help(help_id, home_url, id_user) { + open( + home_url + "general/pandora_help.php?id=" + help_id + "&id_user=" + id_user, + "pandorahelp", + "width=650,height=500,status=0,toolbar=0,menubar=0,scrollbars=1,location=0" + ); } /** @@ -33,18 +48,23 @@ function open_help (help_id, home_url, id_user) { * * @retval str with entities decoded */ -function js_html_entity_decode (str) { - if (! str) - return ""; - - str2 = str.replace (//g,">").replace(/</g,'<') - .replace(/>/g,'>').replace(/\/g,'\\') - .replace(/"/g,'\"').replace(/'/g,'\'') - .replace(/&/g,'&').replace(/ /g,' ') - .replace(/ /g, '\r').replace(/ /g, '\n'); - - return str2; +function js_html_entity_decode(str) { + if (!str) return ""; + + str2 = str + .replace(//g, ">") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/\/g, "\\") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, "&") + .replace(/ /g, " ") + .replace(/ /g, "\r") + .replace(/ /g, "\n"); + + return str2; } /** @@ -56,30 +76,27 @@ function js_html_entity_decode (str) { alert (a.in_array (4)); // true alert (a.in_array (5)); // false */ -Array.prototype.in_array = function () { - for (var j in this) { - if (this[j] == arguments[0]) - return true; - } - - return false; +Array.prototype.in_array = function() { + for (var j in this) { + if (this[j] == arguments[0]) return true; + } + + return false; }; /** * Util for check is empty object - * + * * @param obj the object to check * @returns {Boolean} True it is empty */ function isEmptyObject(obj) { - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) - return false; - } - - return true; -} + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) return false; + } + return true; +} /** * Fill up select box with id "module" with modules after agent has been selected, but this not empty the select box.s @@ -88,177 +105,179 @@ function isEmptyObject(obj) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents (event, id_agent, selected) { - // Hack to avoid certain module types - var module_types_excluded = []; - if (typeof $("input.module_types_excluded") !== 'undefined') { - try { - $("input.module_types_excluded").each(function(index, el) { - var module_type = parseInt($(el).val()); - - if (module_type !== NaN) - module_types_excluded.push(module_type); - }); - } - catch (error) { - - } - } - - var module_status = -1; - if (typeof $("#status_module") !== 'undefined') { - try { - module_status = $("#status_module").val(); - } - catch (error) { - } - } - - // Module name - var module_name = $("#text-module_filter").val(); - - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); +function agent_changed_by_multiple_agents(event, id_agent, selected) { + // Hack to avoid certain module types + var module_types_excluded = []; + if (typeof $("input.module_types_excluded") !== "undefined") { + try { + $("input.module_types_excluded").each(function(index, el) { + var module_type = parseInt($(el).val()); - var tags_to_search = $('#tags1').val(); + if (module_type !== NaN) module_types_excluded.push(module_type); + }); + } catch (error) {} + } - //Hack to find only enabled modules - //Pass a flag as global var - find_modules = 'all'; - if (typeof show_only_enabled_modules !== 'undefined' - && show_only_enabled_modules) { - find_modules = 'enabled'; - } - - var selection_mode = $('#modules_selection_mode').val(); - if (typeof selection_mode === 'undefined') { - selection_mode = 'common'; - } - - var serialized = $('#hidden-serialized').val(); - if (typeof serialized === 'undefined') { - serialized = ''; - } - - $('#module') - .prop('disabled', true) - .empty() - .append($('') - .html("Loading...") - .attr("value", 0)); - - // Check if homedir was received like a JSON - var homedir = '.'; - var id_server = 0; - if (typeof event !== 'undefined' && typeof event.data !== 'undefined') { - - - if (event.data != null) { - if (typeof event.data !== 'undefined') { - if (typeof event.data.homedir !== 'undefined') { - homedir = event.data.homedir; - } - - if (typeof event.data.metaconsole !== 'undefined' - && event.data.metaconsole) { - id_server = $("#" + event.data.id_server).val(); - } - } - } - } - - jQuery.post (homedir + '/ajax.php', - { - "page": "operation/agentes/ver_agente", - "get_agent_modules_json_for_multiple_agents": 1, - "id_agent[]": idAgents, - "tags[]": tags_to_search, - "all": find_modules, - "module_types_excluded[]": module_types_excluded, - "name": module_name, - "selection_mode": selection_mode, - "serialized": serialized, - "id_server": id_server, - "status_module": module_status - }, - function (data) { - $('#module').empty (); - - if (isEmptyObject(data)) { - //Trick for catch the translate text. - var noneText = $("#id_agents").val() === null - ? $("#select_agent_first_text").html() - : $("#none_text").html(); - if (noneText == null) { - noneText = 'None'; - } - - $('#module') - .append ($('') - .html(noneText) - .attr ("None", "") - .prop('selected', true)); - - return; - } - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module') - .append ($('') - .html ($(document) - .data('text_for_module')) - .attr("value", 0) - .prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module') - .append ($('') - .html (data['any_text']) - .attr ("value", 0) - .prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module') - .append ($('') - .html (anyText) - .attr ("value", 0) - .prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - var s = js_html_entity_decode(val); - - $('#module') - .append ($('') - .html (s) - .attr ("value", i) - .attr("title", s)); - - $('#module').fadeIn ('normal'); - }); - if (typeof selected !== 'undefined') - $('#module').attr ('value', selected); - - $('#module') - .css ("max-width", "") - .prop('disabled', false); - - if (typeof(function_hook_loaded_module_list) == 'function') { - function_hook_loaded_module_list(); - } - }, - "json"); + var module_status = -1; + if (typeof $("#status_module") !== "undefined") { + try { + module_status = $("#status_module").val(); + } catch (error) {} + } + + // Module name + var module_name = $("#text-module_filter").val(); + + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var tags_to_search = $("#tags1").val(); + + //Hack to find only enabled modules + //Pass a flag as global var + find_modules = "all"; + if ( + typeof show_only_enabled_modules !== "undefined" && + show_only_enabled_modules + ) { + find_modules = "enabled"; + } + + var selection_mode = $("#modules_selection_mode").val(); + if (typeof selection_mode === "undefined") { + selection_mode = "common"; + } + + var serialized = $("#hidden-serialized").val(); + if (typeof serialized === "undefined") { + serialized = ""; + } + + $("#module") + .prop("disabled", true) + .empty() + .append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + // Check if homedir was received like a JSON + var homedir = "."; + var id_server = 0; + if (typeof event !== "undefined" && typeof event.data !== "undefined") { + if (event.data != null) { + if (typeof event.data !== "undefined") { + if (typeof event.data.homedir !== "undefined") { + homedir = event.data.homedir; + } + + if ( + typeof event.data.metaconsole !== "undefined" && + event.data.metaconsole + ) { + id_server = $("#" + event.data.id_server).val(); + } + } + } + } + + jQuery.post( + homedir + "/ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_json_for_multiple_agents: 1, + "id_agent[]": idAgents, + "tags[]": tags_to_search, + all: find_modules, + "module_types_excluded[]": module_types_excluded, + name: module_name, + selection_mode: selection_mode, + serialized: serialized, + id_server: id_server, + status_module: module_status + }, + function(data) { + $("#module").empty(); + + if (isEmptyObject(data)) { + //Trick for catch the translate text. + var noneText = + $("#id_agents").val() === null + ? $("#select_agent_first_text").html() + : $("#none_text").html(); + if (noneText == null) { + noneText = "None"; + } + + $("#module").append( + $("") + .html(noneText) + .attr("None", "") + .prop("selected", true) + ); + + return; + } + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + var s = js_html_entity_decode(val); + + $("#module").append( + $("") + .html(s) + .attr("value", i) + .attr("title", s) + ); + + $("#module").fadeIn("normal"); + }); + if (typeof selected !== "undefined") $("#module").attr("value", selected); + + $("#module") + .css("max-width", "") + .prop("disabled", false); + + if (typeof function_hook_loaded_module_list == "function") { + function_hook_loaded_module_list(); + } + }, + "json" + ); } /** @@ -269,62 +288,88 @@ function agent_changed_by_multiple_agents (event, id_agent, selected) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents_with_alerts (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - var selection_mode = $('#modules_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - template = $('#id_alert_template option:selected').val(); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_multiple_alerts_json_for_multiple_agents": 1, - "template": template, - "id_agent[]": idAgents, - "selection_mode": selection_mode - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#module').append ($('').html (s).attr ("value", val)); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); +function agent_changed_by_multiple_agents_with_alerts( + event, + id_agent, + selected +) { + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var selection_mode = $("#modules_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + template = $("#id_alert_template option:selected").val(); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_multiple_alerts_json_for_multiple_agents: 1, + template: template, + "id_agent[]": idAgents, + selection_mode: selection_mode + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#module").append( + $("") + .html(s) + .attr("value", val) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); } /** @@ -335,66 +380,92 @@ function agent_changed_by_multiple_agents_with_alerts (event, id_agent, selected * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function alert_templates_changed_by_multiple_agents_with_alerts (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - var selection_mode = $('#modules_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - templates = Array(); - jQuery.each ($("#id_alert_templates option:selected"), function (i, val) { - //val() because the var is same - templates.push($(val).val()); - }); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_alerts_json_for_multiple_agents": 1, - "templates[]": templates, - "id_agent[]": idAgents, - "selection_mode": selection_mode - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#module').append ($('').html (s).attr ("value", val)); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); +function alert_templates_changed_by_multiple_agents_with_alerts( + event, + id_agent, + selected +) { + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var selection_mode = $("#modules_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + templates = Array(); + jQuery.each($("#id_alert_templates option:selected"), function(i, val) { + //val() because the var is same + templates.push($(val).val()); + }); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_alerts_json_for_multiple_agents: 1, + "templates[]": templates, + "id_agent[]": idAgents, + selection_mode: selection_mode + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#module").append( + $("") + .html(s) + .attr("value", val) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); } /** @@ -404,91 +475,114 @@ function alert_templates_changed_by_multiple_agents_with_alerts (event, id_agent * @param id_module Module ID that has been selected * @param selected Which agent(s) have to be selected */ -function module_changed_by_multiple_modules (event, id_module, selected) { - var idModules = Array(); - - jQuery.each ($("#module_name option:selected"), function (i, val) { - //val() because the var is same - idModules.push($(val).val()); - }); - - $('#agents').attr ('disabled', 1); - $('#agents').empty (); - $('#agents').append ($('').html ("Loading...").attr ("value", 0)); - - var status_module = -1; - if (typeof $("#status_module") !== 'undefined') { - try { - status_module = $("#status_module").val(); - } - catch (error) { - } - } - - var selection_mode = $('#agents_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - jQuery.post('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agents_json_for_multiple_modules": 1, - "status_module": status_module, - "module_name[]": idModules, - "selection_mode": selection_mode - }, - function (data) { - $('#agents') - .append ($('').html ("Loading...").attr ("value", 0)); - - $('#agents').empty (); - - if (isEmptyObject(data)) { - var noneText = $("#none_text").html(); //Trick for catch the translate text. - - if (noneText == null) { - noneText = 'None'; - } - - $('#agents') - .append($('').html (noneText).attr ("None", "").prop('selected', true)); - - return; - } - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#agents') - .append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#agents') - .append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#agents') - .append($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#agents') - .append ($('').html (s).attr ("value", i)); - $('#agents').fadeIn ('normal'); - }); - - if (selected != undefined) - $('#agents').attr ('value', selected); - $('#agents').removeAttr('disabled'); - }, - "json" - ); +function module_changed_by_multiple_modules(event, id_module, selected) { + var idModules = Array(); + + jQuery.each($("#module_name option:selected"), function(i, val) { + //val() because the var is same + idModules.push($(val).val()); + }); + + $("#agents").attr("disabled", 1); + $("#agents").empty(); + $("#agents").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + var status_module = -1; + if (typeof $("#status_module") !== "undefined") { + try { + status_module = $("#status_module").val(); + } catch (error) {} + } + + var selection_mode = $("#agents_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agents_json_for_multiple_modules: 1, + status_module: status_module, + "module_name[]": idModules, + selection_mode: selection_mode + }, + function(data) { + $("#agents").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + $("#agents").empty(); + + if (isEmptyObject(data)) { + var noneText = $("#none_text").html(); //Trick for catch the translate text. + + if (noneText == null) { + noneText = "None"; + } + + $("#agents").append( + $("") + .html(noneText) + .attr("None", "") + .prop("selected", true) + ); + + return; + } + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#agents").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#agents").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#agents").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#agents").append( + $("") + .html(s) + .attr("value", i) + ); + $("#agents").fadeIn("normal"); + }); + + if (selected != undefined) $("#agents").attr("value", selected); + $("#agents").removeAttr("disabled"); + }, + "json" + ); } /** @@ -498,393 +592,403 @@ function module_changed_by_multiple_modules (event, id_module, selected) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents_id (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_json_for_multiple_agents_id": 1, - "id_agent[]": idAgents - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val['nombre']); - //$('#module').append ($('').html (s).attr ("value", val)); - $('#module').append ($('').html (s).attr ("value", val['id_agente_modulo'])); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); -} +function agent_changed_by_multiple_agents_id(event, id_agent, selected) { + var idAgents = Array(); + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_json_for_multiple_agents_id: 1, + "id_agent[]": idAgents + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val["nombre"]); + //$('#module').append ($('').html (s).attr ("value", val)); + $("#module").append( + $("") + .html(s) + .attr("value", val["id_agente_modulo"]) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); +} function post_process_select_init(name) { - // Manual mode is hidden by default - - $('#' + name + '_manual').hide(); - $('#' + name + '_default').show(); + // Manual mode is hidden by default + + $("#" + name + "_manual").hide(); + $("#" + name + "_default").show(); } -function post_process_select_init_unit(name,selected) { - // Manual mode is hidden by default - - $('#' + name + '_manual').hide(); - $('#' + name + '_default').show(); - - if(selected != "") { - var select_or_text = false; - $('#' + name + '_select option').each(function(i,item) { - if ($(item).val() == selected) { - select_or_text = true; - return false; - } - }); - - if(select_or_text) { - $('#' + name + '_select option[value='+ selected +']').attr("selected",true); - $('#text-' + name + '_text').val(""); - } else { - $('#' + name + '_select option[value=none]').attr("selected",true); - $('#' + name + '_default').hide(); - $('#' + name + '_manual').show(); - } - } else { - $('#' + name + '_select option[value=none]').attr("selected",true); - } - - $('#' + name + '_select').change(function() { - var value = $('#' + name + '_select').val(); - $('#' + name + '_select option[value='+ value +']').attr("selected",true); - }); - +function post_process_select_init_unit(name, selected) { + // Manual mode is hidden by default + + $("#" + name + "_manual").hide(); + $("#" + name + "_default").show(); + + if (selected != "") { + var select_or_text = false; + $("#" + name + "_select option").each(function(i, item) { + if ($(item).val() == selected) { + select_or_text = true; + return false; + } + }); + + if (select_or_text) { + $("#" + name + "_select option[value=" + selected + "]").attr( + "selected", + true + ); + $("#text-" + name + "_text").val(""); + } else { + $("#" + name + "_select option[value=none]").attr("selected", true); + $("#" + name + "_default").hide(); + $("#" + name + "_manual").show(); + } + } else { + $("#" + name + "_select option[value=none]").attr("selected", true); + } + + $("#" + name + "_select").change(function() { + var value = $("#" + name + "_select").val(); + $("#" + name + "_select option[value=" + value + "]").attr( + "selected", + true + ); + }); } -function post_process_select_events_unit(name,selected) { - - $('.' + name + '_toggler').click(function() { - var value = $('#text-' + name + '_text').val(); - - var count = $('#' + name + '_select option') - .filter(function(i, item) { - - if ($(item).val() == value) - return true; - else return false; - }) - .length; - - if (count != 1) { - $('#' + name + '_select') - .append($("