Вход Регистрация
Файл: wapxl.ru/top/amcharts/plugins/dataloader/dataloader.js
Строк: 717
<?php
/*
Plugin Name: amCharts Data Loader
Description: This plugin adds external data loading capabilities to all amCharts libraries.
Author: Martynas Majeris, amCharts
Version: 1.0.15
Author URI: http://www.amcharts.com/

Copyright 2015 amCharts

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Please note that the above license covers only this plugin. It by all means does
not apply to any other amCharts products that are covered by different licenses.
*/

/**
 * TODO:
 * incremental load
 * XML support (?)
 */

/* globals AmCharts, ActiveXObject */
/* jshint -W061 */

/**
 * Initialize language prompt container
 */
AmCharts.translations.dataLoader = {};

/**
 * Set init handler
 */
AmCharts.addInitHandler( function( chart ) {

  
/**
   * Check if dataLoader is set (initialize it)
   */
  
if ( undefined === chart.dataLoader || !isObjectchart.dataLoader ) )
    
chart.dataLoader = {};

  
/**
   * Check charts version for compatibility:
   * the first compatible version is 3.13
   */
  
var version chart.version.split'.' );
  if ( ( 
Numberversion] ) < ) || ( === Numberversion] ) && ( Numberversion] ) < 13 ) ) )
    return;

  
/**
   * Define object reference for easy access
   */
  
var chart.dataLoader;
  
l.remaining 0;
  
l.percentLoaded = {};

  
/**
   * Set defaults
   */
  
var defaults = {
    
'async'true,
    
'format''json',
    
'showErrors'true,
    
'showCurtain'true,
    
'noStyles'false,
    
'reload'0,
    
'timestamp'false,
    
'delimiter'',',
    
'skip'0,
    
'skipEmpty'true,
    
'emptyAs'undefined,
    
'useColumnNames'false,
    
'init'false,
    
'progress'false,
    
'reverse'false,
    
'reloading'false,
    
'complete'false,
    
'error'false,
    
'headers': [],
    
'chart'chart
  
};

  
/**
   * Create a function that can be used to load data (or reload via API)
   */
  
l.loadData = function() {

    
/**
     * Load all files in a row
     */
    
if ( 'stock' === chart.type ) {

      
// delay this a little bit so the chart has the chance to build itself
      
setTimeout( function() {

        
// preserve animation
        
if ( chart.panelsSettings.startDuration ) {
          
l.startDuration chart.panelsSettings.startDuration;
          
chart.panelsSettings.startDuration 0;
        }

        
// cycle through all of the data sets
        
for ( var 0chart.dataSets.lengthx++ ) {
          var 
ds chart.dataSets];

          
// load data
          
if ( undefined !== ds.dataLoader && undefined !== ds.dataLoader.url ) {

            
callFunctionds.dataLoader.initds.dataLoaderchart );
            
ds.dataProvider = [];
            
applyDefaultsds.dataLoader );
            
loadFileds.dataLoader.urldsds.dataLoader'dataProvider' );

          }

          
// load events data
          
if ( undefined !== ds.eventDataLoader && undefined !== ds.eventDataLoader.url ) {

            
callFunctionds.eventDataLoader.initds.eventDataLoaderchart );
            
ds.events = [];
            
applyDefaultsds.eventDataLoader );
            
loadFileds.eventDataLoader.urldsds.eventDataLoader'stockEvents' );

          }
        }

      }, 
100 );

    } else {

      
callFunctionl.initlchart );

      
applyDefaults);

      if ( 
undefined === l.url )
        return;

      
// preserve animation
      
if ( undefined !== chart.startDuration && ( chart.startDuration ) ) {
        
l.startDuration chart.startDuration;
        
chart.startDuration 0;
      }

      if ( 
'gauge' === chart.type ) {
        
// set empty data set
        
if ( undefined === chart.arrows )
          
chart.arrows = [];

        
loadFilel.urlchartl'arrows' );
      } else {
        
// set empty data set
        
if ( undefined === chart.dataProvider )
          
chart.dataProvider chart.type === 'map' ? {} : [];

        
loadFilel.urlchartl'dataProvider' );
      }

    }

  };

  
/**
   * Trigger load
   */
  
l.loadData();

  
/**
   * Loads a file and determines correct parsing mechanism for it
   */
  
function loadFileurlholderoptionsproviderKey ) {

    
// set default providerKey
    
if ( undefined === providerKey )
      
providerKey 'dataProvider';

    
// show curtain
    
if ( options.showCurtain )
      
showCurtainundefinedoptions.noStyles );

    
// increment loader count
    
l.remaining++;

    
// set percent loaded for this file
    
l.percentLoadedurl ] = 0;

    
// hijack user-defined "progress" handler with our own, so that we can
    // track progress
    
if ( options.progress !== undefined && typeofoptions.progress ) === 'function' && options._progress === undefined ) {
      
options._progress options.progress;
      
options.progress = function( percent ) {
        
// set progress
        
l.percentLoadedurl ] = percent;

        
// calculate global percent
        
var totalPercent 0;
        var 
fileCount 0;
        for ( var 
x in l.percentLoaded ) {
          if ( 
l.percentLoaded.hasOwnProperty) ) {
            
fileCount++;
            
totalPercent += l.percentLoaded];
          }
        }
        var 
globalPercent Math.round( ( totalPercent fileCount ) * 100 ) / 100;

        
// call user function
        
options._progress.callthisglobalPercentMath.roundpercent 100 ) / 100url );
      };
    }

    
// load the file
    
AmCharts.loadFileurloptions, function( response ) {

      
// error?
      
if ( false === response ) {
        
callFunctionoptions.erroroptionschart );
        
raiseErrorAmCharts.__'Error loading the file'chart.language ) + ': ' urlfalseoptions );
      } else {

        
// determine the format
        
if ( undefined === options.format ) {
          
// TODO
          
options.format 'json';
        }

        
// lowercase
        
options.format options.format.toLowerCase();

        
// invoke parsing function
        
switch ( options.format ) {

          case 
'json':

            
holderproviderKey ] = AmCharts.parseJSONresponse );

            if ( 
false === holderproviderKey ] ) {
              
callFunctionoptions.erroroptionschart );
              
raiseErrorAmCharts.__'Error parsing JSON file'chart.language ) + ': ' l.urlfalseoptions );
              
holderproviderKey ] = [];
              return;
            } else {
              
holderproviderKey ] = postprocessholderproviderKey ], options );
              
callFunctionoptions.loadoptionschart );
            }

            break;

          case 
'csv':

            
holderproviderKey ] = AmCharts.parseCSVresponseoptions );

            if ( 
false === holderproviderKey ] ) {
              
callFunctionoptions.erroroptionschart );
              
raiseErrorAmCharts.__'Error parsing CSV file'chart.language ) + ': ' l.urlfalseoptions );
              
holderproviderKey ] = [];
              return;
            } else {
              
holderproviderKey ] = postprocessholderproviderKey ], options );
              
callFunctionoptions.loadoptionschart );
            }

            break;

          default:
            
callFunctionoptions.erroroptionschart );
            
raiseErrorAmCharts.__'Unsupported data format'chart.language ) + ': ' options.formatfalseoptions.noStyles );
            return;
        }

        
// decrement remaining counter
        
l.remaining--;

        
// we done?
        
if ( === l.remaining ) {

          
// callback
          
callFunctionoptions.completechart );

          
// take in the new data
          
if ( options.async ) {

            if ( 
'map' === chart.type ) {

              
// take in new data
              
chart.validateNowtrue );

              
// remove curtain
              
removeCurtain();

            } else {

              
// add a dataUpdated event to handle post-load stuff
              
if ( 'gauge' !== chart.type ) {
                
chart.addListener'dataUpdated', function( event ) {

                  
// restore default period (stock chart)
                  
if ( 'stock' === chart.type && !options.reloading && undefined !== chart.periodSelector ) {
                    
chart.periodSelector.setDefaultPeriod();
                  }

                  
// remove curtain
                  
removeCurtain();

                  
// remove this listener
                  
chart.events.dataUpdated.pop();
                } );
              }


              
// take in new data
              
chart.validateData();

              
// invalidate size for the pie chart
              // disabled for now as it is not longer necessary
              /*if ( 'pie' === chart.type && chart.invalidateSize !== undefined )
                chart.invalidateSize();*/

              // gauge chart does not trigger dataUpdated event
              // let's explicitly remove the curtain for it
              
if ( 'gauge' === chart.type )
                
removeCurtain();

              
// make the chart animate again
              
if ( l.startDuration ) {
                if ( 
'stock' === chart.type ) {
                  
chart.panelsSettings.startDuration l.startDuration;
                  for ( var 
0chart.panels.lengthx++ ) {
                    
chart.panels].startDuration l.startDuration;
                    
chart.panels].animateAgain();
                  }
                } else {
                  
chart.startDuration l.startDuration;
                  if ( 
chart.animateAgain !== undefined )
                    
chart.animateAgain();
                }
              }
            }
          }

        }

        
// schedule another load if necessary
        
if ( options.reload ) {

          if ( 
options.timeout )
            
clearTimeoutoptions.timeout );

          
options.timeout setTimeoutloadFile1000 options.reloadurlholderoptions );
          
options.reloading true;

        }

      }

    } );

  }

  
/**
   * Checks if postProcess is set and invokes the handler
   */
  
function postprocessdataoptions ) {
    if ( 
undefined !== options.postProcess && isFunctionoptions.postProcess ) )
      try {
        return 
options.postProcess.callldataoptionschart );
      } catch ( 
) {
        
raiseErrorAmCharts.__'Error loading file'chart.language ) + ': ' options.urlfalseoptions );
        return 
data;
      } else
        return 
data;
  }

  
/**
   * Returns true if argument is array
   */
  
function isObjectobj ) {
    return 
'object' === typeofobj );
  }

  
/**
   * Returns true is argument is a function
   */
  
function isFunctionobj ) {
    return 
'function' === typeofobj );
  }

  
/**
   * Applies defaults to config object
   */
  
function applyDefaultsobj ) {
    for ( var 
x in defaults ) {
      if ( 
defaults.hasOwnProperty) )
        
setDefaultobjxdefaults] );
    }
  }

  
/**
   * Checks if object property is set, sets with a default if it isn't
   */
  
function setDefaultobjkeyvalue ) {
    if ( 
undefined === objkey ] )
      
objkey ] = value;
  }

  
/**
   * Raises an internal error (writes it out to console)
   */
  
function raiseErrormsgerroroptions ) {

    if ( 
options.showErrors )
      
showCurtainmsgoptions.noStyles );
    else {
      
removeCurtain();
      
console.logmsg );
    }

  }

  
/**
   * Shows curtain over chart area
   */
  
function showCurtainmsgnoStyles ) {

    
// remove previous curtain if there is one
    
removeCurtain();

    
// did we pass in the message?
    
if ( undefined === msg )
      
msg AmCharts.__'Loading data...'chart.language );

    
// create and populate curtain element
    
var curtain document.createElement'div' );
    
curtain.setAttribute'id'chart.div.id '-curtain' );
    
curtain.className 'amcharts-dataloader-curtain';

    if ( 
true !== noStyles ) {
      
curtain.style.position 'absolute';
      
curtain.style.top 0;
      
curtain.style.left 0;
      
curtain.style.width = ( undefined !== chart.realWidth chart.realWidth chart.divRealWidth ) + 'px';
      
curtain.style.height = ( undefined !== chart.realHeight chart.realHeight chart.divRealHeight ) + 'px';
      
curtain.style.textAlign 'center';
      
curtain.style.display 'table';
      
curtain.style.fontSize '20px';
      try {
        
curtain.style.background 'rgba(255, 255, 255, 0.3)';
      } catch ( 
) {
        
curtain.style.background 'rgb(255, 255, 255)';
      }
      
curtain.innerHTML '<div style="display: table-cell; vertical-align: middle;">' msg '</div>';
    } else {
      
curtain.innerHTML msg;
    }
    
chart.containerDiv.appendChildcurtain );

    
l.curtain curtain;
  }

  
/**
   * Removes the curtain
   */
  
function removeCurtain() {
    try {
      if ( 
undefined !== l.curtain )
        
chart.containerDiv.removeChildl.curtain );
    } catch ( 
) {
      
// do nothing
    
}

    
l.curtain undefined;

  }

  
/**
   * Execute callback function
   */
  
function callFunctionfuncparam1param2param3 ) {
    if ( 
'function' === typeof func )
      
func.calllparam1param2param3 );
  }

}, [ 
'pie''serial''xy''funnel''radar''gauge''gantt''stock''map' ] );


/**
 * Returns prompt in a chart language (set by chart.language) if it is
 * available
 */
if ( undefined === AmCharts.__ ) {
  
AmCharts.__ = function( msglanguage ) {
    if ( 
undefined !== language && undefined !== AmCharts.translations.dataLoaderlanguage ] && undefined !== AmCharts.translations.dataLoaderlanguage ][ msg ] )
      return 
AmCharts.translations.dataLoaderlanguage ][ msg ];
    else
      return 
msg;
  };
}

/**
 * Loads a file from url and calls function handler with the result
 */
AmCharts.loadFile = function( urloptionshandler ) {

  
// prepopulate options with minimal defaults if necessary
  
if ( typeofoptions ) !== 'object' )
    
options = {};
  if ( 
options.async === undefined )
    
options.async true;

  
// create the request
  
var request;
  if ( 
window.XMLHttpRequest ) {
    
// IE7+, Firefox, Chrome, Opera, Safari
    
request = new XMLHttpRequest();
  } else {
    
// code for IE6, IE5
    
request = new ActiveXObject'Microsoft.XMLHTTP' );
  }

  
// open the connection
  
try {
    
request.open'GET'options.timestamp AmCharts.timestampUrlurl ) : urloptions.async );
  } catch ( 
) {
    
handler.callthisfalse );
  }

  
// add headers?
  
if ( options.headers !== undefined && options.headers.length ) {
    for ( var 
0options.headers.lengthi++ ) {
      var 
header options.headers];
      
request.setRequestHeaderheader.keyheader.value );
    }
  }

  
// add onprogress handlers
  
if ( options.progress !== undefined && typeofoptions.progress ) === 'function' ) {
    
request.onprogress = function( ) {
      var 
complete = ( e.loaded e.total ) * 100;
      
options.progress.callthiscomplete );
    }
  }

  
// set handler for data if async loading
  
request.onreadystatechange = function() {

    if ( 
=== request.readyState && 404 === request.status )
      
handler.callthisfalse );

    else if ( 
=== request.readyState && 200 === request.status )
      
handler.callthisrequest.responseText );

  };

  
// load the file
  
try {
    
request.send();
  } catch ( 
) {
    
handler.callthisfalse );
  }

};

/**
 * Parses JSON string into an object
 */
AmCharts.parseJSON = function( response ) {
  try {
    if ( 
undefined !== JSON )
      return 
JSON.parseresponse );
    else
      return eval( 
response );
  } catch ( 
) {
    return 
false;
  }
};

/**
 * Prases CSV string into an object
 */
AmCharts.parseCSV = function( responseoptions ) {

  
// parse CSV into array
  
var data AmCharts.CSVToArrayresponseoptions.delimiter );

  
// init resuling array
  
var res = [];
  var 
cols = [];
  var 
coli;

  
// first row holds column names?
  
if ( options.useColumnNames ) {
    
cols data.shift();

    
// normalize column names
    
for ( var 0cols.lengthx++ ) {
      
// trim
      
col cols].replace( /^s+|s+$/gm'' );

      
// check for empty
      
if ( '' === col )
        
col 'col' x;

      
cols] = col;
    }

    if ( 
options.skip )
      
options.skip--;
  }

  
// skip rows
  
for ( 0options.skipi++ )
    
data.shift();

  
// iterate through the result set
  
var row;
  while ( ( 
row options.reverse data.pop() : data.shift() ) ) {
    if ( 
options.skipEmpty && row.length === && row] === '' )
      continue;
    var 
dataPoint = {};
    for ( 
0row.lengthi++ ) {
      
col undefined === cols] ? 'col' cols];
      
dataPointcol ] = row] === "" options.emptyAs row];
    }
    
res.pushdataPoint );
  }

  return 
res;
};

/**
 * Parses CSV data into array
 * Taken from here: (thanks!)
 * http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
 */
AmCharts.CSVToArray = function( strDatastrDelimiter ) {
  
// Check to see if the delimiter is defined. If not,
  // then default to comma.
  
strDelimiter = ( strDelimiter || ',' );

  
// Create a regular expression to parse the CSV values.
  
var objPattern = new RegExp(
    (
      
// Delimiters.
      
"(\" + strDelimiter + "|\r?\n|\r|^)" +

      // Quoted fields.
      "
(?:"([^"]*(?:""[^"]*)*)"|" +

      // Standard fields.
      "
([^"\" + strDelimiter + "\r\n]*))"
    ),
    "
gi"
  );


  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [
    []
  ];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;


  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while ( ( arrMatches = objPattern.exec( strData ) ) ) {

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      ( strMatchedDelimiter !== strDelimiter )
    ) {

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }


    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    var strMatchedValue;
    if ( arrMatches[ 2 ] ) {

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( """", "
g" ),
        """
      
);

    } else {

      
// We found a non-quoted value.
      
strMatchedValue arrMatches];

    }


    
// Now that we have our value string, let's add
    // it to the data array.
    
arrDataarrData.length ].pushstrMatchedValue );
  }

  
// Return the parsed data.
  
return ( arrData );
};

/**
 * Appends timestamp to the url
 */
AmCharts.timestampUrl = function( url ) {
  var 
url.split'?' );
  if ( 
=== p.length )
    
p] = new Date().getTime();
  else
    
p] += '&' + new Date().getTime();
  return 
p.join'?' );
};
?>
Онлайн: 0
Реклама